| 240 | |
| 241 | |
| 242 | class NestedTensorBlock(Block): |
| 243 | |
| 244 | # ********** Modified by Zexin He in 2023-2024 ********** |
| 245 | warnings.warn("NestedTensorBlock is deprecated for now!", DeprecationWarning) |
| 246 | # ******************************************************** |
| 247 | |
| 248 | def forward_nested(self, x_list: List[Tensor]) -> List[Tensor]: |
| 249 | """ |
| 250 | x_list contains a list of tensors to nest together and run |
| 251 | """ |
| 252 | assert isinstance(self.attn, MemEffAttention) |
| 253 | |
| 254 | if self.training and self.sample_drop_ratio > 0.0: |
| 255 | |
| 256 | def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor: |
| 257 | return self.attn(self.norm1(x), attn_bias=attn_bias) |
| 258 | |
| 259 | def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor: |
| 260 | return self.mlp(self.norm2(x)) |
| 261 | |
| 262 | x_list = drop_add_residual_stochastic_depth_list( |
| 263 | x_list, |
| 264 | residual_func=attn_residual_func, |
| 265 | sample_drop_ratio=self.sample_drop_ratio, |
| 266 | scaling_vector=self.ls1.gamma if isinstance(self.ls1, LayerScale) else None, |
| 267 | ) |
| 268 | x_list = drop_add_residual_stochastic_depth_list( |
| 269 | x_list, |
| 270 | residual_func=ffn_residual_func, |
| 271 | sample_drop_ratio=self.sample_drop_ratio, |
| 272 | scaling_vector=self.ls2.gamma if isinstance(self.ls1, LayerScale) else None, |
| 273 | ) |
| 274 | return x_list |
| 275 | else: |
| 276 | |
| 277 | def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor: |
| 278 | return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias)) |
| 279 | |
| 280 | def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor: |
| 281 | return self.ls2(self.mlp(self.norm2(x))) |
| 282 | |
| 283 | attn_bias, x = get_attn_bias_and_cat(x_list) |
| 284 | x = x + attn_residual_func(x, attn_bias=attn_bias) |
| 285 | x = x + ffn_residual_func(x) |
| 286 | return attn_bias.split(x) |
| 287 | |
| 288 | def forward(self, x_or_x_list): |
| 289 | if isinstance(x_or_x_list, Tensor): |
| 290 | return super().forward(x_or_x_list) |
| 291 | elif isinstance(x_or_x_list, list): |
| 292 | if not XFORMERS_AVAILABLE: |
| 293 | raise AssertionError("xFormers is required for using nested tensors") |
| 294 | return self.forward_nested(x_or_x_list) |
| 295 | else: |
| 296 | raise AssertionError |
nothing calls this directly
no outgoing calls
no test coverage detected