base
Base module for noise layers.
Classes:
| Name | Description |
|---|---|
BaseNoiseLayer |
Applies a stochastic transformation to a |
Attributes:
| Name | Type | Description |
|---|---|---|
POST_PROCESSOR_STATE_KEY |
Final[str]
|
The key under which a serialized noise layer records its attached post-processor's type and configuration. |
POST_PROCESSOR_STATE_KEY
module-attribute
¶
The key under which a serialized noise layer records its attached post-processor's type and configuration.
BaseNoiseLayer
¶
Bases: Module, ABC, Generic[EstimatorModuleT, ParameterizationT, OptionalMaskerT_contra]
Applies a stochastic transformation to a Tensor using the given Estimators.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int | None
|
Seed for the random number generator used to generate the stochastic transformation. If |
required |
|
Estimator[EstimatorModuleT, BoundedMeanParameterization | None, None]
|
The estimator to use to estimate the mean of the stochastic transformation. |
required |
|
Estimator[EstimatorModuleT, ParameterizationT, OptionalMaskerT_contra]
|
The estimator to use to estimate the standard deviation and optional input mask of the stochastic transformation. |
required |
|
dtype | None
|
The |
None
|
|
bool
|
Whether to remove the skip connection in the noise layer. This is highly experimental and should be used with caution. |
False
|
|
PostProcessor | None
|
An optional
|
None
|
Methods:
| Name | Description |
|---|---|
__call__ |
Transform the input data. |
__getstate__ |
Prepare a copy of the noise layer's state for serialization. |
__init__ |
|
__setstate__ |
Restore the state of the noise layer from a serialized copy. |
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 |
__getstate__
¶
Prepare a copy of the noise layer's state for serialization.
The returned dictionary can be JSON-serialized if the state_dict key is removed (it contains tensors). Generally you should
pop the state_dict, save it as a safetensors file, then JSON-serialize the rest of the dictionary.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary containing the configuration of the noise layer, including its type string, the state dict, the post-processor |
dict[str, Any]
|
configuration if one is attached, and the generator states if they exist. |
Changed in version v3.15.0: Added serialization support for all noise layers.
Changed in version v3.78.0: An attached `post_processor`'s type and configuration are now included, under the `post_processor` key. Its weights are already covered by the `state_dict` key.
__init__
¶
__init__(
seed: int | None,
mean_estimator: Estimator[
EstimatorModuleT,
BoundedMeanParameterization | None,
None,
],
std_estimator: Estimator[
EstimatorModuleT,
ParameterizationT,
OptionalMaskerT_contra,
],
noise_layer_dtype: dtype | None = None,
remove_skip_connection: bool = False,
*,
post_processor: PostProcessor | None = None
) -> None
Changed in version v3.32.0: Added `remove_skip_connection` argument to optionally remove the skip connection in the transformer cloak architecture. This is highly experimental and should be used with caution.
Changed in version v3.78.0: Added the optional `post_processor` argument, which applies a learned transformation to the composed output of the stochastic transformation.
__setstate__
¶
__setstate__(
state: dict[str, Any],
trust_remote_code: bool = False,
third_party_model_path: (
str | PathLike[str] | None
) = None,
) -> None
Restore the state of the noise layer from a serialized copy.
state_dict, post_processor, and _generators are all optional keys, and will be restored if they exist in the state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
dict[str, Any]
|
The state to set. |
required |
|
bool
|
Whether to trust remote code when loading from HuggingFace Hub. |
False
|
|
str | PathLike[str] | None
|
The path or huggingface reference to a third-party model to load. This is useful when loading SGTs whose internal structure depends on transformers which are not importable directly through transformers, but are present on the Hugging Face Hub. |
None
|
Changed in version v3.15.0: Added serialization support for all noise layers.
Changed in version v3.78.0: A post-processor recorded under the `post_processor` key is now reconstructed and passed to the constructor.
forward
¶
Transform the input data.
An attached post_processor is applied last, to the composed output. Subclasses that further transform the value returned by
this method (for example, by clamping it to a valid pixel range) therefore apply their own transform after the post-processor.
Note
Because the noise mask is applied to this method's return value by a forward hook (see __call__), a post-processor only
ever affects the positions the noise layer transformed; elsewhere the original input value is retained regardless of what
the post-processor computed.
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. |
Changed in version v3.64.0: The skip connection term is now taken from the overridable `_skip_connection_input` hook, which defaults to returning the input unchanged. Behavior is unchanged for every layer that does not override it.
Changed in version v3.78.0: An attached `post_processor` is now applied to the composed output. Behavior is unchanged for every noise layer without one, which is the default.
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
¶
manual_seed(
seed: int | None, rank_dependent: bool = True
) -> None
Seed each of the random number generators.
Setting seed to None will destroy any existing generators, disabling reproducible
behavior until the next call with an integer seed. Calling manual_seed again with
an integer after a None call fully recreates generators for every currently
available device type (CPU, CUDA, MPS) before applying the seed, making the
operation safely reversible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int | None
|
The seed to set. Pass |
required |
|
bool
|
Whether to add the distributed rank to the seed to ensure that each process samples different noise. |
True
|
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.