Coverage for src / cufile_patcher / auto_patch.py: 100%
64 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-24 05:27 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-24 05:27 +0000
1from __future__ import annotations
3import importlib
4from contextlib import AbstractContextManager
5from dataclasses import dataclass
6from types import ModuleType
7from typing import Any
9from .safetensor_patcher import patch_safetensor_load_file
10from .tensorflow_patcher import patch_tensorflow_load_model
11from .torch_patcher import patch_torch_load
14@dataclass(frozen=True)
15class _FrameworkSpec:
16 name: str
17 import_name: str
18 enabled: bool | None
21def _normalize_flag(flag: bool | None) -> bool | None:
22 if flag in (True, False, None):
23 return flag
24 raise TypeError("framework flags must be True, False, or None")
27class AutoPatchContext(AbstractContextManager["AutoPatchContext"]):
28 """Context manager that installs and removes framework patchers automatically."""
30 def __init__(
31 self,
32 *,
33 torch: bool | None = None,
34 tensorflow: bool | None = None,
35 safetensors: bool | None = None,
36 strict: bool = False,
37 min_file_size_mb: int = 64,
38 chunk_size_mb: int = 16,
39 use_cufile: bool = False,
40 fallback_to_original: bool = True,
41 torch_patch_ops_on_oom: bool = False,
42 ) -> None:
43 self._strict = strict
44 self._min_file_size_mb = min_file_size_mb
45 self._chunk_size_mb = chunk_size_mb
46 self._use_cufile = use_cufile
47 self._fallback_to_original = fallback_to_original
48 self._torch_patch_ops_on_oom = torch_patch_ops_on_oom
49 self._specs = [
50 _FrameworkSpec("torch", "torch", _normalize_flag(torch)),
51 _FrameworkSpec("tensorflow", "tensorflow", _normalize_flag(tensorflow)),
52 _FrameworkSpec("safetensors", "safetensors.torch", _normalize_flag(safetensors)),
53 ]
54 self._patchers: list[Any] = []
56 def __enter__(self) -> AutoPatchContext:
57 self._patchers = []
58 for spec in self._specs:
59 module = self._resolve_module(spec)
60 if module is None:
61 continue
62 patcher = self._build_patcher(spec.name, module)
63 patcher.install()
64 self._patchers.append(patcher)
65 return self
67 def __exit__(self, exc_type, exc, tb) -> None:
68 while self._patchers:
69 patcher = self._patchers.pop()
70 patcher.uninstall()
71 return None
73 def _resolve_module(self, spec: _FrameworkSpec) -> ModuleType | None:
74 if spec.enabled is False:
75 return None
76 try:
77 return importlib.import_module(spec.import_name)
78 except ModuleNotFoundError:
79 if self._strict or spec.enabled is True:
80 raise RuntimeError(f"requested framework is not available: {spec.name}") from None
81 return None
83 def _build_patcher(self, framework: str, module: ModuleType):
84 kwargs = {
85 "min_file_size_mb": self._min_file_size_mb,
86 "chunk_size_mb": self._chunk_size_mb,
87 "use_cufile": self._use_cufile,
88 "fallback_to_original": self._fallback_to_original,
89 }
90 if framework == "torch":
91 kwargs["patch_ops_on_oom"] = self._torch_patch_ops_on_oom
92 return patch_torch_load(module, **kwargs)
93 if framework == "tensorflow":
94 return patch_tensorflow_load_model(module, **kwargs)
95 if framework == "safetensors":
96 return patch_safetensor_load_file(module, **kwargs)
97 raise ValueError(f"unsupported framework: {framework}")
100def auto_patch(
101 *,
102 torch: bool | None = None,
103 tensorflow: bool | None = None,
104 safetensors: bool | None = None,
105 strict: bool = False,
106 min_file_size_mb: int = 64,
107 chunk_size_mb: int = 16,
108 use_cufile: bool = False,
109 fallback_to_original: bool = True,
110 torch_patch_ops_on_oom: bool = False,
111) -> AutoPatchContext:
112 """
113 Return a context manager that installs available framework patchers.
115 By default, framework flags are auto-detected (`None`): if import succeeds,
116 the corresponding patcher is installed.
117 """
118 return AutoPatchContext(
119 torch=torch,
120 tensorflow=tensorflow,
121 safetensors=safetensors,
122 strict=strict,
123 min_file_size_mb=min_file_size_mb,
124 chunk_size_mb=chunk_size_mb,
125 use_cufile=use_cufile,
126 fallback_to_original=fallback_to_original,
127 torch_patch_ops_on_oom=torch_patch_ops_on_oom,
128 )