patches.py 1.62 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""Common patches shared across GMS integrations."""

from __future__ import annotations

import logging

import torch
11
from gpu_memory_service.client.torch.allocator import get_gms_client_memory_managers
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

logger = logging.getLogger(__name__)

_empty_cache_patched = False


def patch_empty_cache() -> None:
    """Patch torch.cuda.empty_cache to prevent segfaults with VMM allocations.

    When weights are allocated through our VMM-based pluggable allocator, calling
    torch.cuda.empty_cache() causes segfaults because the native caching allocator
    tries to release blocks that were allocated through VMM APIs.

    This patch is idempotent - calling it multiple times has no effect.
    """
    global _empty_cache_patched

    if _empty_cache_patched:
        return

    _original_empty_cache = torch.cuda.empty_cache

    def safe_empty_cache() -> None:
35
36
37
38
        # Allow empty_cache when all managers are unmapped (sleep/checkpoint)
        # or when there are no active VMM mappings with live handles.
        has_live_mappings = any(
            any(m.handle != 0 for m in manager.mappings.values())
39
            for manager in get_gms_client_memory_managers()
40
        )
41
42
43
        if has_live_mappings:
            logger.debug(
                "[GMS] Skipping torch.cuda.empty_cache() - live VMM mappings active",
44
45
46
47
48
49
50
            )
            return
        _original_empty_cache()

    torch.cuda.empty_cache = safe_empty_cache
    _empty_cache_patched = True
    logger.info("[GMS] Patched torch.cuda.empty_cache")