cloak_noise
Classes:
Name | Description |
---|---|
CloakNoiseLayer |
Applies an input independent stochastic transformation to a |
CloakNoiseLayer1 |
Applies an input independent stochastic transformation to a |
CloakNoiseLayer2 |
Applies an input independent stochastic transformation to a |
CloakNoiseLayer2_NoClip |
Applies an input independent stochastic transformation to a |
ParameterWrapper |
Returns its |
CloakNoiseLayer
¶
Bases: BaseNoiseLayer[ParameterWrapper, CloakStandardDeviationParameterization, Optional[PercentMasker]]
Applies an input independent stochastic transformation to a Tensor
using ParameterWrapper
,
with standard deviations parameterized by CloakStandardDeviationParameterization
,
optional standard deviation-based input masking using PercentMasker
, and
optional output clamping.
Inspired by the Cloak algorithm defined in the paper: Not All Features Are Equal: Discovering Essential Features for Preserving Prediction Privacy.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
tuple[float, float]
|
Used to set bound on the min and max standard deviation of the stochastic transformation. |
(0.0001, 2.0)
|
|
float
|
A temperature-like parameter which controls the spread of the parameterization function. Controls both the magnitude of parameterized standard deviations and their rate of change with respect to rhos. |
1.0
|
|
float | None
|
The percentage of the input to mask. |
None
|
|
tuple[float | None, float | None] | None
|
Minimum and maximum values of the range to clamp the output into. |
None
|
|
bool
|
Whether the locs parameters (related to the means of the transform) have their gradients tracked. |
True
|
|
bool
|
Whether the rhos parameters (related to the standard deviations of the transform) have their gradients tracked. |
True
|
|
float
|
The initial values for the rhos. |
-4.0
|
|
int | None
|
Seed for the random number generator used to generate the stochastic transformation. If |
None
|
Warning
The directly learned locs
and rhos
used by this class are prone to vanishing when trained with weight decay regularization.
To avoid this, ensure that optimizer parameter group(s) containing locs
or rhos
are configured with weight_decay=0.0
.
Methods:
Name | Description |
---|---|
__call__ |
Transform the input data. |
__getstate__ |
Prepare a serializable copy of |
__init_subclass__ |
Set the default dtype to |
__setstate__ |
Restore from a serialized copy of |
forward |
Transform the input data. |
get_applied_transform_components_factory |
Create a function that returns the elements of the transform components ( |
get_transformed_output_factory |
Create a function that returns the transformed output from the most recent forward pass. |
initial_seed |
Return the initial seed of the CPU device's random number generator. |
manual_seed |
Seed each of the random number generators. |
reset_parameters |
Reinitialize parameters and buffers. |
seed |
Seed each of the random number generators using a non-deterministic random number. |
__call__
¶
Transform the input data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Tensor
|
The input to transform. |
required |
|
Tensor | None
|
An optional mask that selects the elements of |
None
|
|
Any
|
Additional keyword arguments to the estimator modules. |
required |
__init_subclass__
¶
Set the default dtype to torch.float32
inside all subclass __init__
methods.
__setstate__
¶
Restore from a serialized copy of self.__dict__
.
forward
¶
Transform the input data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Tensor
|
The input to transform. |
required |
|
Tensor | None
|
An optional mask that selects the elements of |
None
|
|
Any
|
Additional keyword arguments to the estimator modules. |
required |
Returns:
Type | Description |
---|---|
torch.Tensor
|
The transformed input data. |
get_applied_transform_components_factory
¶
Create a function that returns the elements of the transform components ('mean'
and 'std'
) applied during the most recent
forward pass.
Specifically, the applied elements are those selected by the noise mask (if supplied) and standard deviation mask (if
std_estimator.masker is not None
). If no masks are used, all elements are returned.
The applied transform components are returned flattened.
This function is intended to be used to log histograms of the transform components.
Returns:
Type | Description |
---|---|
Callable[[], dict[str, torch.Tensor]]
|
A function that returns the the elements of the transform components applied during the most recent forward pass. |
Examples:
>>> from torch import nn
>>> from stainedglass_core import model as sg_model, noise_layer as sg_noise_layer
>>> base_model = nn.Linear(20, 2)
>>> noisy_model = sg_model.NoisyModel(
... sg_noise_layer.CloakNoiseLayer1,
... base_model,
... target_parameter="input",
... )
>>> get_applied_transform_components = (
... noisy_model.noise_layer.get_applied_transform_components_factory()
... )
>>> input = torch.ones(1, 20)
>>> noise_mask = torch.tensor(5 * [False] + 15 * [True])
>>> output = noisy_model(input, noise_mask=noise_mask)
>>> applied_transform_components = get_applied_transform_components()
>>> applied_transform_components
{'mean': tensor(...), 'std': tensor(...)}
>>> {
... component_name: component.shape
... for component_name, component in applied_transform_components.items()
... }
{'mean': torch.Size([15]), 'std': torch.Size([15])}
get_transformed_output_factory
¶
Create a function that returns the transformed output from the most recent forward pass.
If super batching is active, only the transformed half of the super batch output is returned.
Returns:
Type | Description |
---|---|
Callable[[], torch.Tensor]
|
A function that returns the transformed output from the most recent forward pass. |
Examples:
>>> from stainedglass_core import noise_layer as sg_noise_layer
>>> noise_layer = sg_noise_layer.CloakNoiseLayer1()
>>> get_transformed_output = noise_layer.get_transformed_output_factory()
>>> input = torch.ones(2, 3, 32, 32)
>>> output = noise_layer(input)
>>> transformed_output = get_transformed_output()
>>> assert output.equal(transformed_output)
initial_seed
¶
Return the initial seed of the CPU device's random number generator.
manual_seed
¶
reset_parameters
¶
Reinitialize parameters and buffers.
This method is useful for initializing tensors created on the meta device.
seed
¶
Seed each of the random number generators using a non-deterministic random number.
CloakNoiseLayer1
¶
Bases: CloakNoiseLayer
Applies an input independent stochastic transformation to a Tensor
using ParameterWrapper
and with standard deviations parameterized by CloakStandardDeviationParameterization
.
Inspired by the Cloak Step 1 algorithm defined in the paper: Not All Features Are Equal: Discovering Essential Features for Preserving Prediction Privacy
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
tuple[float, float]
|
Used to set bound on the min and max standard deviation of the stochastic transformation. |
(0.0001, 2.0)
|
|
float
|
A temperature-like parameter which controls the spread of the parameterization function. Controls both the magnitude of parameterized standard deviations and their rate of change with respect to rhos. |
1.0
|
|
bool
|
Whether the locs parameters (related to the means of the transform) have their gradients tracked. |
True
|
|
bool
|
Whether the rhos parameters (related to the standard deviations of the transform) have their gradients tracked. Usually True. |
True
|
|
float
|
The initial values for the rhos. |
-4.0
|
|
int | None
|
Seed for the random number generator used to generate the stochastic transformation. If |
None
|
Warning
The directly learned locs
and rhos
used by this class are prone to vanishing when trained with weight decay regularization.
To avoid this, ensure that optimizer parameter group(s) containing locs
or rhos
are configured with weight_decay=0.0
.
Note
For maximum privacy preservation, Stained Glass Transform Step 1 should only be used to pre-train a Stained Glass Transform Step 2
(see CloakNoiseLayer2
or CloakNoiseLayer2_NoClip
). First training a Step 1, then fine-tuning that transform with step 2 is
a common recipe.
For a more convenient type Stained Glass Transform that requires only one step of training, see CloakNoiseLayerOneShot
.
Note
In almost all cases, rhos_requires_grad
should be True
while training CloakNoiseLayer1
.
Methods:
Name | Description |
---|---|
__call__ |
Transform the input data. |
__getstate__ |
Prepare a serializable copy of |
__init_subclass__ |
Set the default dtype to |
__setstate__ |
Restore from a serialized copy of |
forward |
Transform the input data. |
get_applied_transform_components_factory |
Create a function that returns the elements of the transform components ( |
get_transformed_output_factory |
Create a function that returns the transformed output from the most recent forward pass. |
initial_seed |
Return the initial seed of the CPU device's random number generator. |
manual_seed |
Seed each of the random number generators. |
reset_parameters |
Reinitialize parameters and buffers. |
seed |
Seed each of the random number generators using a non-deterministic random number. |
__call__
¶
Transform the input data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Tensor
|
The input to transform. |
required |
|
Tensor | None
|
An optional mask that selects the elements of |
None
|
|
Any
|
Additional keyword arguments to the estimator modules. |
required |
__init_subclass__
¶
Set the default dtype to torch.float32
inside all subclass __init__
methods.
__setstate__
¶
Restore from a serialized copy of self.__dict__
.
forward
¶
Transform the input data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Tensor
|
The input to transform. |
required |
|
Tensor | None
|
An optional mask that selects the elements of |
None
|
|
Any
|
Additional keyword arguments to the estimator modules. |
required |
Returns:
Type | Description |
---|---|
torch.Tensor
|
The transformed input data. |
get_applied_transform_components_factory
¶
Create a function that returns the elements of the transform components ('mean'
and 'std'
) applied during the most recent
forward pass.
Specifically, the applied elements are those selected by the noise mask (if supplied) and standard deviation mask (if
std_estimator.masker is not None
). If no masks are used, all elements are returned.
The applied transform components are returned flattened.
This function is intended to be used to log histograms of the transform components.
Returns:
Type | Description |
---|---|
Callable[[], dict[str, torch.Tensor]]
|
A function that returns the the elements of the transform components applied during the most recent forward pass. |
Examples:
>>> from torch import nn
>>> from stainedglass_core import model as sg_model, noise_layer as sg_noise_layer
>>> base_model = nn.Linear(20, 2)
>>> noisy_model = sg_model.NoisyModel(
... sg_noise_layer.CloakNoiseLayer1,
... base_model,
... target_parameter="input",
... )
>>> get_applied_transform_components = (
... noisy_model.noise_layer.get_applied_transform_components_factory()
... )
>>> input = torch.ones(1, 20)
>>> noise_mask = torch.tensor(5 * [False] + 15 * [True])
>>> output = noisy_model(input, noise_mask=noise_mask)
>>> applied_transform_components = get_applied_transform_components()
>>> applied_transform_components
{'mean': tensor(...), 'std': tensor(...)}
>>> {
... component_name: component.shape
... for component_name, component in applied_transform_components.items()
... }
{'mean': torch.Size([15]), 'std': torch.Size([15])}
get_transformed_output_factory
¶
Create a function that returns the transformed output from the most recent forward pass.
If super batching is active, only the transformed half of the super batch output is returned.
Returns:
Type | Description |
---|---|
Callable[[], torch.Tensor]
|
A function that returns the transformed output from the most recent forward pass. |
Examples:
>>> from stainedglass_core import noise_layer as sg_noise_layer
>>> noise_layer = sg_noise_layer.CloakNoiseLayer1()
>>> get_transformed_output = noise_layer.get_transformed_output_factory()
>>> input = torch.ones(2, 3, 32, 32)
>>> output = noise_layer(input)
>>> transformed_output = get_transformed_output()
>>> assert output.equal(transformed_output)
initial_seed
¶
Return the initial seed of the CPU device's random number generator.
manual_seed
¶
reset_parameters
¶
Reinitialize parameters and buffers.
This method is useful for initializing tensors created on the meta device.
seed
¶
Seed each of the random number generators using a non-deterministic random number.
CloakNoiseLayer2
¶
Bases: CloakNoiseLayer
Applies an input independent stochastic transformation to a Tensor
using ParameterWrapper
,
with standard deviations parameterized by CloakStandardDeviationParameterization
,
standard deviation-based input masking using PercentMasker
, and output clamping.
Inspired by the Cloak Step 2 algorithm defined in the paper: Not All Features Are Equal: Discovering Essential Features for Preserving Prediction Privacy
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
tuple[float, float]
|
Used to set bound on the min and max standard deviation of the stochastic transformation. |
(0.0001, 2.0)
|
|
float
|
The percentage of the outputs to mask. |
required |
|
float
|
A temperature-like parameter which controls the spread of the parameterization function. Controls both the magnitude of parameterized standard deviations and their rate of change with respect to rhos. |
1.0
|
|
tuple[float | None, float | None]
|
Minimum and maximum values of the range to clamp the output into. |
(-1.0, 1.0)
|
|
int | None
|
Seed for the random number generator used to generate the stochastic transformation. If |
None
|
Note
Specifying percent_to_mask==0.0
with a NoClip
variant of Cloak Step 2 is functionally equivalent to Cloak Step 1, as no
masking occurs.
Note
In training mode, the threshold
buffer is recalculated over the learned standard deviations of the stochastic transformation,
and a new input mask is generated with each forward call. In eval mode, threshold
is static, and the cached mask from the most
recent mask calculation is used.
Raises:
Type | Description |
---|---|
ValueError
|
If |
Warning
The directly learned locs
and rhos
used by this class are prone to vanishing when trained with weight decay regularization.
To avoid this, ensure that optimizer parameter group(s) containing locs
or rhos
are configured with weight_decay=0.0
.
Note
For maximum privacy preservation, Stained Glass Transform Step 2 should be pre-trained from a Stained Glass Transform Step 1. For a
more convenient type of Stained Glass Transform that requires only one step of training, see CloakNoiseLayerOneShot
.
Note
Masking is done using a static threshold on the learned standard deviation of the stochastic transformation. This threshold is
calculated from percent_to_mask
when loading a pre-trained transform layer. Consequently, continuing to train the stochastic
transformation will not affect masking. For a variant of Cloak Step 2 that recalculates its masking using percent_to_mask
on each
call (i.e. the masking can change during training), see CloakNoiseLayerOneShot
.
Methods:
Name | Description |
---|---|
__call__ |
Transform the input data. |
__getstate__ |
Prepare a serializable copy of |
__init__ |
|
__init_subclass__ |
Set the default dtype to |
__setstate__ |
Restore from a serialized copy of |
forward |
Transform the input data. |
get_applied_transform_components_factory |
Create a function that returns the elements of the transform components ( |
get_transformed_output_factory |
Create a function that returns the transformed output from the most recent forward pass. |
initial_seed |
Return the initial seed of the CPU device's random number generator. |
manual_seed |
Seed each of the random number generators. |
reset_parameters |
Reinitialize parameters and buffers. |
seed |
Seed each of the random number generators using a non-deterministic random number. |
__call__
¶
Transform the input data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Tensor
|
The input to transform. |
required |
|
Tensor | None
|
An optional mask that selects the elements of |
None
|
|
Any
|
Additional keyword arguments to the estimator modules. |
required |
__init__
¶
__init__(
percent_to_mask: float,
scale: tuple[float, float] = (0.0001, 2.0),
shallow: float = 1.0,
value_range: tuple[float | None, float | None] = (
-1.0,
1.0,
),
seed: int | None = None,
) -> None
Changed in version 0.10.0: `threshold` and `percent_threshold` parameters were removed in favor of `percent_to_mask`
__init_subclass__
¶
Set the default dtype to torch.float32
inside all subclass __init__
methods.
__setstate__
¶
Restore from a serialized copy of self.__dict__
.
forward
¶
Transform the input data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Tensor
|
The input to transform. |
required |
|
Tensor | None
|
An optional mask that selects the elements of |
None
|
|
Any
|
Additional keyword arguments to the estimator modules. |
required |
Returns:
Type | Description |
---|---|
torch.Tensor
|
The transformed input data. |
get_applied_transform_components_factory
¶
Create a function that returns the elements of the transform components ('mean'
and 'std'
) applied during the most recent
forward pass.
Specifically, the applied elements are those selected by the noise mask (if supplied) and standard deviation mask (if
std_estimator.masker is not None
). If no masks are used, all elements are returned.
The applied transform components are returned flattened.
This function is intended to be used to log histograms of the transform components.
Returns:
Type | Description |
---|---|
Callable[[], dict[str, torch.Tensor]]
|
A function that returns the the elements of the transform components applied during the most recent forward pass. |
Examples:
>>> from torch import nn
>>> from stainedglass_core import model as sg_model, noise_layer as sg_noise_layer
>>> base_model = nn.Linear(20, 2)
>>> noisy_model = sg_model.NoisyModel(
... sg_noise_layer.CloakNoiseLayer1,
... base_model,
... target_parameter="input",
... )
>>> get_applied_transform_components = (
... noisy_model.noise_layer.get_applied_transform_components_factory()
... )
>>> input = torch.ones(1, 20)
>>> noise_mask = torch.tensor(5 * [False] + 15 * [True])
>>> output = noisy_model(input, noise_mask=noise_mask)
>>> applied_transform_components = get_applied_transform_components()
>>> applied_transform_components
{'mean': tensor(...), 'std': tensor(...)}
>>> {
... component_name: component.shape
... for component_name, component in applied_transform_components.items()
... }
{'mean': torch.Size([15]), 'std': torch.Size([15])}
get_transformed_output_factory
¶
Create a function that returns the transformed output from the most recent forward pass.
If super batching is active, only the transformed half of the super batch output is returned.
Returns:
Type | Description |
---|---|
Callable[[], torch.Tensor]
|
A function that returns the transformed output from the most recent forward pass. |
Examples:
>>> from stainedglass_core import noise_layer as sg_noise_layer
>>> noise_layer = sg_noise_layer.CloakNoiseLayer1()
>>> get_transformed_output = noise_layer.get_transformed_output_factory()
>>> input = torch.ones(2, 3, 32, 32)
>>> output = noise_layer(input)
>>> transformed_output = get_transformed_output()
>>> assert output.equal(transformed_output)
initial_seed
¶
Return the initial seed of the CPU device's random number generator.
manual_seed
¶
reset_parameters
¶
Reinitialize parameters and buffers.
This method is useful for initializing tensors created on the meta device.
seed
¶
Seed each of the random number generators using a non-deterministic random number.
CloakNoiseLayer2_NoClip
¶
Bases: CloakNoiseLayer
Applies an input independent stochastic transformation to a Tensor
using ParameterWrapper
,
with standard deviations parameterized by CloakStandardDeviationParameterization
,
and standard deviation-based input masking using PercentMasker
.
Inspired by the Cloak Step 2 algorithm defined in the paper: Not All Features Are Equal: Discovering Essential Features for Preserving Prediction Privacy
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
tuple[float, float]
|
Used to set bound on the min and max standard deviation of the stochastic transformation. |
(0.0001, 2.0)
|
|
float
|
The percentage of the outputs to mask. |
required |
|
float
|
A temperature-like parameter which controls the spread of the parameterization function. Controls both the magnitude of parameterized standard deviations and their rate of change with respect to rhos. |
1.0
|
|
int | None
|
Seed for the random number generator used to generate the stochastic transformation. If |
None
|
Note
Specifying percent_to_mask==0.0
with a NoClip
variant of Cloak Step 2 is functionally equivalent to Cloak Step 1, as no
masking occurs.
Note
In training mode, the threshold
buffer is recalculated over the learned standard deviations of the stochastic transformation,
and a new input mask is generated with each forward call. In eval mode, threshold
is static, and the cached mask from the most
recent mask calculation is used.
Raises:
Type | Description |
---|---|
ValueError
|
If |
Warning
The directly learned locs
and rhos
used by this class are prone to vanishing when trained with weight decay regularization.
To avoid this, ensure that optimizer parameter group(s) containing locs
or rhos
are configured with weight_decay=0.0
.
Note
For maximum privacy preservation, Stained Glass Transform Step 2 should be pre-trained from a Stained Glass Transform Step 1.
For a more convenient type Stained Glass Transform that requires only one step of training, see CloakNoiseLayerOneShot
.
Methods:
Name | Description |
---|---|
__call__ |
Transform the input data. |
__getstate__ |
Prepare a serializable copy of |
__init_subclass__ |
Set the default dtype to |
__setstate__ |
Restore from a serialized copy of |
forward |
Transform the input data. |
get_applied_transform_components_factory |
Create a function that returns the elements of the transform components ( |
get_transformed_output_factory |
Create a function that returns the transformed output from the most recent forward pass. |
initial_seed |
Return the initial seed of the CPU device's random number generator. |
manual_seed |
Seed each of the random number generators. |
reset_parameters |
Reinitialize parameters and buffers. |
seed |
Seed each of the random number generators using a non-deterministic random number. |
__call__
¶
Transform the input data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Tensor
|
The input to transform. |
required |
|
Tensor | None
|
An optional mask that selects the elements of |
None
|
|
Any
|
Additional keyword arguments to the estimator modules. |
required |
__init_subclass__
¶
Set the default dtype to torch.float32
inside all subclass __init__
methods.
__setstate__
¶
Restore from a serialized copy of self.__dict__
.
forward
¶
Transform the input data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Tensor
|
The input to transform. |
required |
|
Tensor | None
|
An optional mask that selects the elements of |
None
|
|
Any
|
Additional keyword arguments to the estimator modules. |
required |
Returns:
Type | Description |
---|---|
torch.Tensor
|
The transformed input data. |
get_applied_transform_components_factory
¶
Create a function that returns the elements of the transform components ('mean'
and 'std'
) applied during the most recent
forward pass.
Specifically, the applied elements are those selected by the noise mask (if supplied) and standard deviation mask (if
std_estimator.masker is not None
). If no masks are used, all elements are returned.
The applied transform components are returned flattened.
This function is intended to be used to log histograms of the transform components.
Returns:
Type | Description |
---|---|
Callable[[], dict[str, torch.Tensor]]
|
A function that returns the the elements of the transform components applied during the most recent forward pass. |
Examples:
>>> from torch import nn
>>> from stainedglass_core import model as sg_model, noise_layer as sg_noise_layer
>>> base_model = nn.Linear(20, 2)
>>> noisy_model = sg_model.NoisyModel(
... sg_noise_layer.CloakNoiseLayer1,
... base_model,
... target_parameter="input",
... )
>>> get_applied_transform_components = (
... noisy_model.noise_layer.get_applied_transform_components_factory()
... )
>>> input = torch.ones(1, 20)
>>> noise_mask = torch.tensor(5 * [False] + 15 * [True])
>>> output = noisy_model(input, noise_mask=noise_mask)
>>> applied_transform_components = get_applied_transform_components()
>>> applied_transform_components
{'mean': tensor(...), 'std': tensor(...)}
>>> {
... component_name: component.shape
... for component_name, component in applied_transform_components.items()
... }
{'mean': torch.Size([15]), 'std': torch.Size([15])}
get_transformed_output_factory
¶
Create a function that returns the transformed output from the most recent forward pass.
If super batching is active, only the transformed half of the super batch output is returned.
Returns:
Type | Description |
---|---|
Callable[[], torch.Tensor]
|
A function that returns the transformed output from the most recent forward pass. |
Examples:
>>> from stainedglass_core import noise_layer as sg_noise_layer
>>> noise_layer = sg_noise_layer.CloakNoiseLayer1()
>>> get_transformed_output = noise_layer.get_transformed_output_factory()
>>> input = torch.ones(2, 3, 32, 32)
>>> output = noise_layer(input)
>>> transformed_output = get_transformed_output()
>>> assert output.equal(transformed_output)
initial_seed
¶
Return the initial seed of the CPU device's random number generator.
manual_seed
¶
reset_parameters
¶
Reinitialize parameters and buffers.
This method is useful for initializing tensors created on the meta device.
seed
¶
Seed each of the random number generators using a non-deterministic random number.
ParameterWrapper
¶
Bases: Module
Returns its torch.nn.parameter.Parameter
weight irrespective of input.
The shape of the weight is automatically determined on the first forward pass as the shape of the input, excluding the first dimension. The shape of the weight is also automatically assumed when loading from a state_dict.
The original Cloak implementation used nn.Parameter
directly, but this class allows for modular swapping with more complex Module
s.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Callable[[Tensor], Tensor]
|
The function to use to initialize the weight. Must operate in-place. |
required |
|
bool
|
Whether to require gradient calculations for the underlying |
True
|
Methods:
Name | Description |
---|---|
__init__ |
|
forward |
Return the weight irrespective of input. |
reset_parameters |
Reinitialize parameters and buffers. |