Patch all batchnorm instances (1d, 2d, 3d, sync_bn, etc.) of a module so that they don't track running stats when torch.no_grad() is enabled. This is important in activation checkpointing to ensure stats are tracked correctly as if there were no activation checkpointing. The rea
(module: nn.Module)
| 168 | # Manage the checkpoint context with thread-local data. |
| 169 | |
| 170 | def patch_batchnorm(module: nn.Module) -> List: |
| 171 | """Patch all batchnorm instances (1d, 2d, 3d, sync_bn, etc.) of a module |
| 172 | so that they don't track running stats when torch.no_grad() is enabled. |
| 173 | This is important in activation checkpointing to ensure stats are tracked |
| 174 | correctly as if there were no activation checkpointing. The reason is |
| 175 | that activation checkpointing runs the forward function twice, first |
| 176 | with torch.no_grad(), then with torch.grad(). |
| 177 | Args: |
| 178 | module (nn.Module): |
| 179 | The module to be patched in-place. |
| 180 | Returns: |
| 181 | (list): |
| 182 | A list of hook handles, late can be freed. |
| 183 | """ |
| 184 | |
| 185 | def pre_forward(module: _BatchNorm, input: Tensor) -> None: |
| 186 | if torch.is_grad_enabled(): |
| 187 | return |
| 188 | module._track_running_stats_backup = module.track_running_stats |
| 189 | module.track_running_stats = False |
| 190 | |
| 191 | def post_forward(module: _BatchNorm, input: Tensor, result: Tensor) -> None: |
| 192 | if torch.is_grad_enabled(): |
| 193 | return |
| 194 | module.track_running_stats = module._track_running_stats_backup |
| 195 | |
| 196 | hooks = [] |
| 197 | for name, child in module.named_modules(): |
| 198 | # _BatchNorm is base for bn1d, bn2d, bn3d and sync_bn, apex_sync_bn, etc. |
| 199 | if isinstance(child, _BatchNorm) and not hasattr(child, "disable_patch_batchnorm"): |
| 200 | # Register the pre/post hooks. |
| 201 | pre_handle = child.register_forward_pre_hook(pre_forward) |
| 202 | post_handle = child.register_forward_hook(post_forward) |
| 203 | hooks += [pre_handle, post_handle] |
| 204 | return hooks |
| 205 | |
| 206 | @dataclass |
| 207 | class ThreadLocalCheckpointingState(threading.local): |
no outgoing calls
no test coverage detected