cloak_one_shot
CloakNoiseLayerOneShot
¶
Bases: CloakNoiseLayer
Stained Glass Transform inspired by the Cloak Algorithm (see paper), with a threshold that is recalculated every forward pass, to allow for one-step training.
The original Cloak Algorithm requires two steps to train. In the first step, the stochastic mapping is trained, and in the second step, masking is trained. This class allows for training in one step, by recalculating the threshold every forward pass.
For most use cases, this class is preferred over a multi-step Stained Glass Transform version, since it is simpler to use. For more advanced use cases, however, the multi-step version may be required, since it allows for more control over the masking process during training.
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
.
Examples:
>>> img_shape = (1, 3, 8, 8)
>>> noise_layer = CloakNoiseLayerOneShot(
... input_shape=img_shape, percent_to_mask=0.5, scale=(1e-4, 2.0)
... )
>>> img = torch.rand(img_shape)
>>> transformed_img = noise_layer(img)
>>> transformed_img.output.shape == img.shape
True
>>> torch.allclose(transformed_img.output, img)
False
See paper: Not All Features Are Equal: Discovering Essential Features for Preserving Prediction Privacy.
input_shape
property
¶
The shape of the expected input including its batch dimension.
mask
property
writable
¶
mask: Tensor | None
The mask to apply calculated from parameters of the stochastic transformation computed during the most recent call to forward.
mean
property
writable
¶
mean: Tensor
The means of the stochastic transformation computed during the most recent call to forward.
std
property
writable
¶
std: Tensor
The standard deviations of the stochastic transformation computed during the most recent call to forward.
__call__
¶
Stochastically transform the input.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input |
Tensor
|
The input to transform. |
required |
noise_mask |
Tensor | None
|
An optional mask that selects the elements of |
None
|
**kwargs |
Any
|
Additional keyword arguments to the estimator modules. |
required |
__init__
¶
__init__(input_shape: tuple[int, ...], percent_to_mask: float | Tensor, scale: tuple[float, float], shallow: float = 1.0, rhos_init: float = -4.0, seed: int | None = None) -> None
Construct a CloakNoiseLayerOneShot
with the given parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_shape |
tuple[int, ...]
|
The input shape of the layer. |
required |
scale |
tuple[float, float]
|
Used to set bound on the min and max standard deviation of the generated stochastic transformation. |
required |
percent_to_mask |
float | Tensor
|
The percentage of the outputs to mask. |
required |
shallow |
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
|
rhos_init |
float
|
The initial values for the rhos. |
-4.0
|
seed |
int | None
|
Seed for the random number generator used to generate the stochastic transformation. If |
None
|
Notes
Specifying percent_to_mask==0.0
is functionally equivalent to Cloak Step 1, as no masking occurs.
Raises:
Type | Description |
---|---|
ValueError
|
If |
ValueError
|
If |
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 |
---|---|---|---|
input |
Tensor
|
The input to transform. |
required |
noise_mask |
Tensor | None
|
An optional mask that selects the elements of |
None
|
**kwargs |
Any
|
Additional keyword arguments to the estimator modules. |
required |
Returns:
Type | Description |
---|---|
base.NoiseLayerOutput
|
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,
... input_shape=(-1, 20),
... )
>>> 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 = base_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(input_shape=(-1, 3, 32, 32))
>>> 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.output.equal(transformed_output)
initial_seed
¶
Return the initial seed of the CPU device's random number generator.
manual_seed
¶
manual_seed(seed: int) -> None
Seed each of the random number generators.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
seed |
int
|
The seed to set. |
required |
seed
¶
Seed each of the random number generators using a non-deterministic random number.