| 1318 | logger.debug("DeepSpeedEngine.__del__ cleanup skipped: %s", exc, exc_info=True) |
| 1319 | |
| 1320 | def destroy(self): |
| 1321 | self._destroyed = True |
| 1322 | try: |
| 1323 | # DeepEP buffers ask the library not to reclaim them, so they outlive |
| 1324 | # the engine unless something releases them here. Only this engine's |
| 1325 | # own buffers: another engine in the same process still needs its own. |
| 1326 | module = getattr(self, "module", None) |
| 1327 | if module is not None: |
| 1328 | from deepspeed.module_inject.auto_ep_comm import destroy_exchanges |
| 1329 | destroy_exchanges(module) |
| 1330 | |
| 1331 | self._release_deepcompile_compiled_backward_state() |
| 1332 | self._release_deepcompile_dynamo_config() |
| 1333 | optimizer = getattr(self, "optimizer", None) |
| 1334 | if optimizer is not None and hasattr(optimizer, 'destroy'): |
| 1335 | optimizer.destroy() |
| 1336 | if self.is_deepcompile_active() or getattr(self, "_deepcompile_native_initialized", False): |
| 1337 | self._deactivate_deepcompile() |
| 1338 | # Callers often keep the model after destroy() (e.g. HF Trainer), and these hooks close |
| 1339 | # over the engine, so leaving them registered would keep the engine and optimizer alive. |
| 1340 | # This runs after _deactivate_deepcompile() because that re-registers the forward hooks. |
| 1341 | for hook_attr in ("module_forward_pre_hook", "module_forward_post_hook", "first_dataloader_check"): |
| 1342 | hook = getattr(self, hook_attr, None) |
| 1343 | if hook is not None: |
| 1344 | hook.remove() |
| 1345 | setattr(self, hook_attr, None) |
| 1346 | debug_clear_module_and_param_names() |
| 1347 | |
| 1348 | checkpoint_engine = getattr(self, "checkpoint_engine", None) |
| 1349 | if checkpoint_engine is not None and checkpoint_engine.is_decoupled(): |
| 1350 | checkpoint_engine.cleanup() |
| 1351 | finally: |
| 1352 | python_gc_generation = getattr(self, "_python_gc_generation", None) |
| 1353 | if python_gc_generation is not None: |
| 1354 | from deepspeed.runtime.python_gc import python_gc_manager |
| 1355 | python_gc_manager.release(python_gc_generation) |
| 1356 | self._python_gc_generation = None |
| 1357 | |
| 1358 | def collect_python_gc(self): |
| 1359 | """Run Python cyclic GC at an application-selected safe boundary.""" |