r""" A linear layer that is used with LoRA. Parameters: in_features (`int`): Number of input features. out_features (`int`): Number of output features. rank (`int`, `optional`, defaults to 4): The rank of the LoRA layer. ne
| 173 | |
| 174 | |
| 175 | class LoRALinearLayer(nn.Module): |
| 176 | r""" |
| 177 | A linear layer that is used with LoRA. |
| 178 | |
| 179 | Parameters: |
| 180 | in_features (`int`): |
| 181 | Number of input features. |
| 182 | out_features (`int`): |
| 183 | Number of output features. |
| 184 | rank (`int`, `optional`, defaults to 4): |
| 185 | The rank of the LoRA layer. |
| 186 | network_alpha (`float`, `optional`, defaults to `None`): |
| 187 | The value of the network alpha used for stable learning and preventing underflow. This value has the same |
| 188 | meaning as the `--network_alpha` option in the kohya-ss trainer script. See |
| 189 | https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning |
| 190 | device (`torch.device`, `optional`, defaults to `None`): |
| 191 | The device to use for the layer's weights. |
| 192 | dtype (`torch.dtype`, `optional`, defaults to `None`): |
| 193 | The dtype to use for the layer's weights. |
| 194 | """ |
| 195 | |
| 196 | def __init__( |
| 197 | self, |
| 198 | in_features: int, |
| 199 | out_features: int, |
| 200 | rank: int = 4, |
| 201 | network_alpha: Optional[float] = None, |
| 202 | device: Optional[Union[torch.device, str]] = None, |
| 203 | dtype: Optional[torch.dtype] = None, |
| 204 | ): |
| 205 | super().__init__() |
| 206 | |
| 207 | deprecation_message = "Use of `LoRALinearLayer` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`." |
| 208 | deprecate("LoRALinearLayer", "1.0.0", deprecation_message) |
| 209 | |
| 210 | self.down = nn.Linear(in_features, rank, bias=False, device=device, dtype=dtype) |
| 211 | self.up = nn.Linear(rank, out_features, bias=False, device=device, dtype=dtype) |
| 212 | # This value has the same meaning as the `--network_alpha` option in the kohya-ss trainer script. |
| 213 | # See https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning |
| 214 | self.network_alpha = network_alpha |
| 215 | self.rank = rank |
| 216 | self.out_features = out_features |
| 217 | self.in_features = in_features |
| 218 | |
| 219 | nn.init.normal_(self.down.weight, std=1 / rank) |
| 220 | nn.init.zeros_(self.up.weight) |
| 221 | |
| 222 | def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| 223 | orig_dtype = hidden_states.dtype |
| 224 | dtype = self.down.weight.dtype |
| 225 | |
| 226 | down_hidden_states = self.down(hidden_states.to(dtype)) |
| 227 | up_hidden_states = self.up(down_hidden_states) |
| 228 | |
| 229 | if self.network_alpha is not None: |
| 230 | up_hidden_states *= self.network_alpha / self.rank |
| 231 | |
| 232 | return up_hidden_states.to(orig_dtype) |