| 1265 | logger.debug("DeepSpeedEngine.__del__ cleanup skipped: %s", exc, exc_info=True) |
| 1266 | |
| 1267 | def destroy(self): |
| 1268 | self._destroyed = True |
| 1269 | try: |
| 1270 | # DeepEP buffers ask the library not to reclaim them, so they outlive |
| 1271 | # the engine unless something releases them here. Only this engine's |
| 1272 | # own buffers: another engine in the same process still needs its own. |
| 1273 | module = getattr(self, "module", None) |
| 1274 | if module is not None: |
| 1275 | from deepspeed.module_inject.auto_ep_comm import destroy_exchanges |
| 1276 | destroy_exchanges(module) |
| 1277 | |
| 1278 | self._release_deepcompile_compiled_backward_state() |
| 1279 | self._release_deepcompile_dynamo_config() |
| 1280 | optimizer = getattr(self, "optimizer", None) |
| 1281 | if optimizer is not None and hasattr(optimizer, 'destroy'): |
| 1282 | optimizer.destroy() |
| 1283 | if self.is_deepcompile_active() or getattr(self, "_deepcompile_native_initialized", False): |
| 1284 | self._deactivate_deepcompile() |
| 1285 | # Callers often keep the model after destroy() (e.g. HF Trainer), and these hooks close |
| 1286 | # over the engine, so leaving them registered would keep the engine and optimizer alive. |
| 1287 | # This runs after _deactivate_deepcompile() because that re-registers the forward hooks. |
| 1288 | for hook_attr in ("module_forward_pre_hook", "module_forward_post_hook", "first_dataloader_check"): |
| 1289 | hook = getattr(self, hook_attr, None) |
| 1290 | if hook is not None: |
| 1291 | hook.remove() |
| 1292 | setattr(self, hook_attr, None) |
| 1293 | debug_clear_module_and_param_names() |
| 1294 | |
| 1295 | checkpoint_engine = getattr(self, "checkpoint_engine", None) |
| 1296 | if checkpoint_engine is not None and checkpoint_engine.is_decoupled(): |
| 1297 | checkpoint_engine.cleanup() |
| 1298 | finally: |
| 1299 | python_gc_generation = getattr(self, "_python_gc_generation", None) |
| 1300 | if python_gc_generation is not None: |
| 1301 | from deepspeed.runtime.python_gc import python_gc_manager |
| 1302 | python_gc_manager.release(python_gc_generation) |
| 1303 | self._python_gc_generation = None |
| 1304 | |
| 1305 | def collect_python_gc(self): |
| 1306 | """Run Python cyclic GC at an application-selected safe boundary.""" |