Dropout Operator¤
Randomly drop pixels or regions for regularization.
See Also¤
- Operators Overview - All operator types
- Patch Dropout - Drop image patches
- Noise Operator - Add noise augmentation
- Probabilistic Operator - Random augmentation
datarax.operators.modality.image.dropout_operator ¤
DropoutOperator - Operator for image dropout augmentation.
This operator extends ModalityOperator to provide pixel-wise and channel-wise dropout.
Key Features:
- Two dropout modes: 'pixel' (element-wise) and 'channel' (entire channels)
- Stochastic mode with per-sample dropout masks
- Deterministic mode for fixed dropout pattern
- Full JAX compatibility with JIT compilation
Examples:
Basic usage:
config = DropoutOperatorConfig(
field_key="image",
dropout_rate=0.2,
mode="pixel"
)
op = DropoutOperator(config, rngs=rngs)
DropoutOperatorConfig
dataclass
¤
DropoutOperatorConfig(cacheable: bool = False, batch_stats_fn: Callable | Module | None = None, precomputed_stats: dict[str, Any] | None = None, stochastic: bool = False, stream_name: str | None = None, batch_strategy: str = 'vmap', *, field_key: str, target_key: str | None = None, auxiliary_fields: list[str] | None = None, clip_range: tuple[float, float] | None = None, preserve_auxiliary: bool = True, validate_domain_constraints: bool = True, dropout_rate: float = 0.1, mode: Literal['pixel', 'channel'] = 'pixel')
Bases: ModalityOperatorConfig
Configuration for DropoutOperator.
Extends ModalityOperatorConfig with dropout-specific parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
dropout_rate |
float
|
Probability of dropping pixels/channels (0.0 to 1.0). Used in deterministic mode or as default. Default: 0.1 |
mode |
Literal['pixel', 'channel']
|
Dropout mode. Either "pixel" for pixel-wise dropout or "channel" for channel-wise dropout. Default: "pixel" |
clip_range |
tuple[float, float] | None
|
Range for clipping output values. None means no clipping. Default: None (dropout naturally produces values in valid range) |
Note
Use dropout_rate and mode parameters to configure the dropout behavior.
dropout_rate
class-attribute
instance-attribute
¤
mode
class-attribute
instance-attribute
¤
precomputed_stats
class-attribute
instance-attribute
¤
target_key
class-attribute
instance-attribute
¤
auxiliary_fields
class-attribute
instance-attribute
¤
clip_range
class-attribute
instance-attribute
¤
preserve_auxiliary
class-attribute
instance-attribute
¤
DropoutOperator ¤
DropoutOperator(config: DropoutOperatorConfig, *, rngs: Rngs)
Bases: ModalityOperator
Image dropout transformation operator.
Applies dropout to images by randomly setting pixels or channels to zero:
- Pixel mode: Each pixel independently dropped with probability dropout_rate
- Channel mode: Entire channels dropped with probability dropout_rate
Supports three modes: 1. Deterministic: Fixed dropout pattern using fixed seed 2. Stochastic: Per-sample random dropout masks from generate_random_params() 3. External params: Accept pre-generated random parameters
The operator works on single elements (H, W, C images) and is composed into batch processing via apply_batch() from the base class.
Examples:
Deterministic dropout:
config = DropoutOperatorConfig(
field_key="image",
dropout_rate=0.2,
mode="pixel",
stochastic=False
)
operator = DropoutOperator(config, rngs=nnx.Rngs(0))
result, state, metadata = operator.apply(data, state, metadata)
Stochastic dropout with random masks:
config = DropoutOperatorConfig(
field_key="image",
dropout_rate=0.2,
mode="channel",
stochastic=True
)
operator = DropoutOperator(config, rngs=nnx.Rngs(0))
# Use apply_batch() for automatic random param generation
result, state, metadata = operator.apply_batch(batch_data, state, metadata)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
DropoutOperatorConfig
|
Configuration for dropout operation |
required |
rngs
|
Rngs
|
RNG streams for stochastic operations |
required |
generate_random_params ¤
Generate random dropout masks for stochastic mode.
In stochastic mode, this pre-generates the dropout masks for the entire batch. This approach avoids RNG state mutations inside vmapped apply().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rng
|
Array
|
JAX random key |
required |
data_shapes
|
dict[str, tuple[int, ...]]
|
Dictionary mapping field keys to their shapes. Used to determine batch size and element shapes. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Array]
|
Dictionary with:
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If field_key not in data_shapes |
apply ¤
apply(data: dict[str, Array], state: dict[str, Any], metadata: dict[str, Any], random_params: dict[str, Array] | None = None, stats: dict[str, Any] | None = None) -> tuple[dict[str, Array], dict[str, Any], dict[str, Any]]
Apply dropout transformation to a single element.
This operates on single elements (e.g., one image of shape [H, W, C]). For batch processing, use apply_batch() which handles random param generation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Array]
|
Input data dictionary. Must contain field specified by config.field_key |
required |
state
|
dict[str, Any]
|
Operator state (unused for dropout, passed through) |
required |
metadata
|
dict[str, Any]
|
Metadata dictionary (passed through unchanged) |
required |
random_params
|
dict[str, Array] | None
|
Optional random parameters from generate_random_params(). If config.stochastic=True and this is provided, uses random_params["keep_mask"] for the dropout mask. |
None
|
stats
|
dict[str, Any] | None
|
Optional statistics dictionary (unused) |
None
|
Returns:
| Type | Description |
|---|---|
tuple[dict[str, Array], dict[str, Any], dict[str, Any]]
|
Tuple of (transformed_data, state, metadata) - transformed_data: Data dict with dropout applied to target field - state: Unchanged state dict - metadata: Unchanged metadata dict |
Note
CRITICAL: Always check config.stochastic flag, not whether random_params is None. apply_batch() always passes random_params even in deterministic mode.
get_operation_stats ¤
reset_operation_stats ¤
Reset operation statistics to zero.
Note: Creates new JAX arrays to reset the counters.
compute_statistics ¤
Compute statistics from data using batch_stats_fn.
If batch_stats_fn is not configured, returns None. Computed statistics are cached in _computed_stats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
Input data to compute statistics from |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
Dictionary of statistics, or None if no batch_stats_fn configured |
get_statistics ¤
set_statistics ¤
reset_statistics ¤
Reset all statistics to None.
This clears both computed statistics and marks that precomputed_stats should be ignored (via internal flag). After reset, get_statistics() will return None until new statistics are set or computed.
copy ¤
copy(*, config: DataraxModuleConfig | None = None, rngs: Rngs | None = None, name: str | None = None) -> DataraxModule
Create a copy of this module with optional config/parameter changes.
This allows creating a new module instance with modified configuration while preserving other attributes. Useful for hyperparameter tuning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
DataraxModuleConfig | None
|
New config (if None, uses current config) |
None
|
rngs
|
Rngs | None
|
New RNG state (if None, uses current rngs) |
None
|
name
|
str | None
|
New name (if None, uses current name) |
None
|
Returns:
| Type | Description |
|---|---|
DataraxModule
|
New module instance with updated parameters |
Examples:
Change configuration¤
new_config = DataraxModuleConfig(cacheable=True) new_module = module.copy(config=new_config)
Change name only¤
renamed = module.copy(name="new_name")
Note
Subclasses can override this method to provide more fine-grained control over copying, such as allowing individual config field updates without requiring dataclass replace().
get_state ¤
Get module state for checkpointing.
This method implements the Checkpointable protocol using NNX state management. It extracts all state variables from the module and converts them to a serializable format.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary containing the internal state of the component. |
set_state ¤
Restore module state from a checkpoint.
This method implements the Checkpointable protocol using NNX state management. It restores the module state from a serialized format. Restoration is strict: checkpoint structure must match module state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
dict[str, Any]
|
A dictionary containing the internal state to restore. |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If state is not a dictionary. |
ValueError
|
If checkpoint structure does not match module state. |
clone ¤
clone() -> DataraxModule
Create a new instance with the same state as this module.
Uses NNX's clone function for proper deep cloning of all state.
Returns:
| Type | Description |
|---|---|
DataraxModule
|
A new module instance with the same state. |
requires_rng_streams ¤
ensure_rng_streams ¤
Ensure that the required RNG streams are available.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stream_names
|
list[str]
|
A list of available RNG stream names. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a required RNG stream is not available. |
get_output_structure ¤
get_output_structure(sample_data: PyTree, sample_state: PyTree) -> tuple[PyTree, PyTree]
Declare output PyTree structure for vmap axis specification.
Default uses jax.eval_shape to discover structure automatically. Override for efficiency or when eval_shape doesn't work (e.g., data-dependent shapes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample_data
|
PyTree
|
Single element data (not batched) |
required |
sample_state
|
PyTree
|
Single element state (not batched) |
required |
Returns:
| Type | Description |
|---|---|
PyTree
|
Tuple of (output_data_structure, output_state_structure) with None leaves. |
PyTree
|
The structure (keys/nesting) matters, leaf values are ignored. |
Example override for operator that adds keys
def get_output_structure(self, sample_data, sample_state): out_data = { **jax.tree.map(lambda _: None, sample_data), "score": None, "alignment": None, } return out_data, sample_state
apply_batch ¤
Process entire batch with vmap and optional RNG generation.
This method implements the batch processing logic for both stochastic and deterministic modes. It uses static branching on self.stochastic for JIT compilation efficiency.
The implementation delegates to _vmap_apply() for the shared computational core, then wraps the result in a Batch object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
Batch
|
Input batch (Batch[Element] structure) |
required |
stats
|
dict[str, Any] | None
|
Optional statistics (if None, uses get_statistics()) |
None
|
Returns:
| Type | Description |
|---|---|
Batch
|
Transformed batch with same structure |
Note
This method is concrete (not abstract). Subclasses typically don't override it, but can if they need custom batch processing logic.
output_spec ¤
Return the operator's output spec given an input spec.
Most operators (normalization, additive noise, simple element-wise
transforms) do not change shape; the default returns input_spec
unchanged. Shape-changing operators (Resize, Crop, Reshape) MUST
override this method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_spec
|
PyTree
|
PyTree of |
required |
Returns:
| Type | Description |
|---|---|
PyTree
|
PyTree of |
PyTree
|
By default, equal to |