|
| 1 | +"""Deepspeed Zero One Adam Optimizer with a reset method. |
| 2 | +
|
| 3 | +This reset method is useful when resampling dead neurons during training. |
| 4 | +""" |
| 5 | +from collections.abc import Iterator |
| 6 | +from typing import final |
| 7 | + |
| 8 | +from deepspeed.runtime.fp16.onebit.zoadam import ZeroOneAdam |
| 9 | +from jaxtyping import Int |
| 10 | +from torch import Tensor |
| 11 | +from torch.nn.parameter import Parameter |
| 12 | +from torch.optim.optimizer import params_t |
| 13 | + |
| 14 | +from sparse_autoencoder.optimizer.abstract_optimizer import AbstractOptimizerWithReset |
| 15 | +from sparse_autoencoder.tensor_types import Axis |
| 16 | + |
| 17 | + |
| 18 | +@final |
| 19 | +class ZeroOneAdamWithReset(ZeroOneAdam, AbstractOptimizerWithReset): |
| 20 | + """Deepspeed Zero One Adam Optimizer with a reset method. |
| 21 | +
|
| 22 | + https://deepspeed.readthedocs.io/en/latest/optimizers.html#zerooneadam-gpu |
| 23 | +
|
| 24 | + The :meth:`reset_state_all_parameters` and :meth:`reset_neurons_state` methods are useful when |
| 25 | + manually editing the model parameters during training (e.g. when resampling dead neurons). This |
| 26 | + is because Adam maintains running averages of the gradients and the squares of gradients, which |
| 27 | + will be incorrect if the parameters are changed. |
| 28 | +
|
| 29 | + Otherwise this is the same as the standard ZeroOneAdam optimizer. |
| 30 | +
|
| 31 | + Warning: |
| 32 | + Requires a distributed torch backend. |
| 33 | + """ |
| 34 | + |
| 35 | + parameter_names: list[str] |
| 36 | + """Parameter Names. |
| 37 | +
|
| 38 | + The names of the parameters, so that we can find them later when resetting the state. |
| 39 | + """ |
| 40 | + |
| 41 | + _has_components_dim: bool |
| 42 | + """Whether the parameters have a components dimension.""" |
| 43 | + |
| 44 | + def __init__( |
| 45 | + self, |
| 46 | + params: params_t, |
| 47 | + lr: float = 1e-3, |
| 48 | + betas: tuple[float, float] = (0.9, 0.999), |
| 49 | + eps: float = 1e-8, |
| 50 | + weight_decay: float = 0.0, |
| 51 | + *, |
| 52 | + named_parameters: Iterator[tuple[str, Parameter]], |
| 53 | + has_components_dim: bool, |
| 54 | + ) -> None: |
| 55 | + """Initialize the optimizer. |
| 56 | +
|
| 57 | + Warning: |
| 58 | + Named parameters must be with default settings (remove duplicates and not recursive). |
| 59 | +
|
| 60 | + Args: |
| 61 | + params: Iterable of parameters to optimize or dicts defining parameter groups. |
| 62 | + lr: Learning rate. A Tensor LR is not yet fully supported for all implementations. Use a |
| 63 | + float LR unless specifying fused=True or capturable=True. |
| 64 | + betas: Coefficients used for computing running averages of gradient and its square. |
| 65 | + eps: Term added to the denominator to improve numerical stability. |
| 66 | + weight_decay: Weight decay (L2 penalty). |
| 67 | + named_parameters: An iterator over the named parameters of the model. This is used to |
| 68 | + find the parameters when resetting their state. You should set this as |
| 69 | + `model.named_parameters()`. |
| 70 | + has_components_dim: If the parameters have a components dimension (i.e. if you are |
| 71 | + training an SAE on more than one component). |
| 72 | +
|
| 73 | +
|
| 74 | + Raises: |
| 75 | + ValueError: If the number of parameter names does not match the number of parameters. |
| 76 | + """ |
| 77 | + # Initialise the parent class (note we repeat the parameter names so that type hints work). |
| 78 | + super().__init__( |
| 79 | + params=params, |
| 80 | + lr=lr, |
| 81 | + betas=betas, |
| 82 | + eps=eps, |
| 83 | + weight_decay=weight_decay, |
| 84 | + ) |
| 85 | + |
| 86 | + self._has_components_dim = has_components_dim |
| 87 | + |
| 88 | + # Store the names of the parameters, so that we can find them later when resetting the |
| 89 | + # state. |
| 90 | + self.parameter_names = [name for name, _value in named_parameters] |
| 91 | + |
| 92 | + if len(self.parameter_names) != len(self.param_groups[0]["params"]): |
| 93 | + error_message = ( |
| 94 | + "The number of parameter names does not match the number of parameters. " |
| 95 | + "If using model.named_parameters() make sure remove_duplicates is True " |
| 96 | + "and recursive is False (the default settings)." |
| 97 | + ) |
| 98 | + raise ValueError(error_message) |
| 99 | + |
| 100 | + def reset_state_all_parameters(self) -> None: |
| 101 | + """Reset the state for all parameters. |
| 102 | +
|
| 103 | + Iterates over all parameters and resets both the running averages of the gradients and the |
| 104 | + squares of gradients. |
| 105 | + """ |
| 106 | + # Iterate over every parameter |
| 107 | + for group in self.param_groups: |
| 108 | + for parameter in group["params"]: |
| 109 | + # Get the state |
| 110 | + state = self.state[parameter] |
| 111 | + |
| 112 | + # Check if state is initialized |
| 113 | + if len(state) == 0: |
| 114 | + continue |
| 115 | + |
| 116 | + # Reset running averages |
| 117 | + exp_avg: Tensor = state["exp_avg"] |
| 118 | + exp_avg.zero_() |
| 119 | + exp_avg_sq: Tensor = state["exp_avg_sq"] |
| 120 | + exp_avg_sq.zero_() |
| 121 | + |
| 122 | + # If AdamW is used (weight decay fix), also reset the max exp_avg_sq |
| 123 | + if "max_exp_avg_sq" in state: |
| 124 | + max_exp_avg_sq: Tensor = state["max_exp_avg_sq"] |
| 125 | + max_exp_avg_sq.zero_() |
| 126 | + |
| 127 | + def reset_neurons_state( |
| 128 | + self, |
| 129 | + parameter: Parameter, |
| 130 | + neuron_indices: Int[Tensor, Axis.names(Axis.LEARNT_FEATURE_IDX)], |
| 131 | + axis: int, |
| 132 | + component_idx: int = 0, |
| 133 | + ) -> None: |
| 134 | + """Reset the state for specific neurons, on a specific parameter. |
| 135 | +
|
| 136 | + Args: |
| 137 | + parameter: The parameter to be reset. Examples from the standard sparse autoencoder |
| 138 | + implementation include `tied_bias`, `_encoder._weight`, `_encoder._bias`, |
| 139 | + neuron_indices: The indices of the neurons to reset. |
| 140 | + axis: The axis of the state values to reset (i.e. the input/output features axis, as |
| 141 | + we're resetting all input/output features for a specific dead neuron). |
| 142 | + component_idx: The component index of the state values to reset. |
| 143 | +
|
| 144 | + Raises: |
| 145 | + ValueError: If the parameter has a components dimension, but has_components_dim is |
| 146 | + False. |
| 147 | + """ |
| 148 | + # Get the state of the parameter |
| 149 | + state = self.state[parameter] |
| 150 | + |
| 151 | + # If the number of dimensions is 3, we definitely have a components dimension. If 2, we may |
| 152 | + # do (as the bias has 2 dimensions with components, but the weight has 2 dimensions without |
| 153 | + # components). |
| 154 | + definitely_has_components_dimension = 3 |
| 155 | + if ( |
| 156 | + not self._has_components_dim |
| 157 | + and state["exp_avg"].ndim == definitely_has_components_dimension |
| 158 | + ): |
| 159 | + error_message = ( |
| 160 | + "The parameter has a components dimension, but has_components_dim is False. " |
| 161 | + "This should not happen." |
| 162 | + ) |
| 163 | + raise ValueError(error_message) |
| 164 | + |
| 165 | + # Check if state is initialized |
| 166 | + if len(state) == 0: |
| 167 | + return |
| 168 | + |
| 169 | + # Check there are any neurons to reset |
| 170 | + if neuron_indices.numel() == 0: |
| 171 | + return |
| 172 | + |
| 173 | + # Move the neuron indices to the correct device |
| 174 | + neuron_indices = neuron_indices.to(device=state["exp_avg"].device) |
| 175 | + |
| 176 | + # Reset running averages for the specified neurons |
| 177 | + if "exp_avg" in state: |
| 178 | + if self._has_components_dim: |
| 179 | + state["exp_avg"][component_idx].index_fill_(axis, neuron_indices, 0) |
| 180 | + else: |
| 181 | + state["exp_avg"].index_fill_(axis, neuron_indices, 0) |
| 182 | + |
| 183 | + if "exp_avg_sq" in state: |
| 184 | + if self._has_components_dim: |
| 185 | + state["exp_avg_sq"][component_idx].index_fill_(axis, neuron_indices, 0) |
| 186 | + else: |
| 187 | + state["exp_avg_sq"].index_fill_(axis, neuron_indices, 0) |
| 188 | + |
| 189 | + # If AdamW is used (weight decay fix), also reset the max exp_avg_sq |
| 190 | + if "max_exp_avg_sq" in state: |
| 191 | + if self._has_components_dim: |
| 192 | + state["max_exp_avg_sq"][component_idx].index_fill_(axis, neuron_indices, 0) |
| 193 | + else: |
| 194 | + state["max_exp_avg_sq"].index_fill_(axis, neuron_indices, 0) |
0 commit comments