Coverage for src / cufile_patcher / torch_patcher.py: 77%
121 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 ctypes
4import os
5from abc import ABC, abstractmethod
6from pathlib import Path
7from tempfile import SpooledTemporaryFile
8from types import ModuleType
9from typing import Any
11from .cufile import CuFile
14class TorchStreamReader(ABC):
15 """Plugin contract for reading model files in chunks."""
17 @abstractmethod
18 def iter_chunks(self, file_path: str, chunk_size: int):
19 """Yield file bytes in chunk-sized pieces."""
22class PythonStreamReader(TorchStreamReader):
23 """Portable chunk reader that works everywhere."""
25 def iter_chunks(self, file_path: str, chunk_size: int):
26 with open(file_path, "rb") as fp:
27 while True:
28 chunk = fp.read(chunk_size)
29 if not chunk:
30 break
31 yield chunk
34class CuFileStreamReader(TorchStreamReader):
35 """Chunk reader that pulls data through the CuFile wrapper."""
37 def iter_chunks(self, file_path: str, chunk_size: int):
38 file_size = os.path.getsize(file_path)
39 offset = 0
41 with CuFile(file_path, "r") as cu_file:
42 while offset < file_size:
43 to_read = min(chunk_size, file_size - offset)
44 staging = ctypes.create_string_buffer(to_read)
45 read_n = cu_file.read(
46 ctypes.cast(staging, ctypes.c_void_p),
47 to_read,
48 file_offset=offset,
49 )
50 if read_n <= 0:
51 break
52 offset += read_n
53 yield staging.raw[:read_n]
56class TorchCuFilePatcher:
57 """
58 Monkey-patch torch.load to stream large files through a chunked spool path.
60 This avoids loading large model files in one giant read call. The patch preserves
61 the original torch.load behavior for small files and non-path inputs.
62 """
64 def __init__(
65 self,
66 torch_module: ModuleType,
67 *,
68 min_file_size_mb: int = 64,
69 chunk_size_mb: int = 16,
70 stream_reader: TorchStreamReader | None = None,
71 use_cufile: bool = False,
72 fallback_to_original: bool = True,
73 patch_ops_on_oom: bool = False,
74 ) -> None:
75 self._torch = torch_module
76 self._min_file_size = max(1, min_file_size_mb) * 1024 * 1024
77 self._chunk_size = max(1, chunk_size_mb) * 1024 * 1024
78 self._reader = stream_reader or (
79 CuFileStreamReader() if use_cufile else PythonStreamReader()
80 )
81 self._fallback_to_original = fallback_to_original
82 self._patch_ops_on_oom = patch_ops_on_oom
83 self._original_load = None
84 self._original_ops: dict[str, Any] = {}
86 @property
87 def installed(self) -> bool:
88 return self._original_load is not None
90 def install(self) -> None:
91 if self.installed:
92 return
93 self._original_load = self._torch.load
94 self._torch.load = self._patched_load
95 self._install_operation_wrappers()
97 def uninstall(self) -> None:
98 if not self.installed:
99 return
100 self._uninstall_operation_wrappers()
101 self._torch.load = self._original_load
102 self._original_load = None
104 def _install_operation_wrappers(self) -> None:
105 if not self._patch_ops_on_oom:
106 return
107 for name in ("add", "sub", "mul", "matmul"):
108 if not hasattr(self._torch, name):
109 continue
110 original = getattr(self._torch, name)
111 self._original_ops[name] = original
113 def _wrapped(*args: Any, _name: str = name, **kwargs: Any):
114 return self._patched_operation(_name, *args, **kwargs)
116 setattr(self._torch, name, _wrapped)
118 def _uninstall_operation_wrappers(self) -> None:
119 for name, original in self._original_ops.items():
120 setattr(self._torch, name, original)
121 self._original_ops.clear()
123 def _patched_operation(self, op_name: str, *args: Any, **kwargs: Any):
124 original = self._original_ops[op_name]
125 try:
126 return original(*args, **kwargs)
127 except RuntimeError as exc:
128 if "out of memory" not in str(exc).lower():
129 raise
130 cpu_args = tuple(self._to_cpu(v) for v in args)
131 cpu_kwargs = {k: self._to_cpu(v) for k, v in kwargs.items()}
132 return original(*cpu_args, **cpu_kwargs)
134 def _to_cpu(self, value: Any) -> Any:
135 tensor_cls = getattr(self._torch, "Tensor", None)
136 if tensor_cls is not None and isinstance(value, tensor_cls):
137 return value.to("cpu")
138 if isinstance(value, dict):
139 return {k: self._to_cpu(v) for k, v in value.items()}
140 if isinstance(value, list):
141 return [self._to_cpu(v) for v in value]
142 if isinstance(value, tuple):
143 return tuple(self._to_cpu(v) for v in value)
144 return value
146 def _should_stream(self, source: Any) -> bool:
147 if not isinstance(source, (str, os.PathLike, Path)):
148 return False
149 source_path = os.fspath(source)
150 if not os.path.isfile(source_path):
151 return False
152 return os.path.getsize(source_path) >= self._min_file_size
154 def _patched_load(self, source: Any, *args: Any, **kwargs: Any):
155 if not self._should_stream(source):
156 return self._original_load(source, *args, **kwargs)
158 source_path = os.fspath(source)
159 try:
160 return self._streaming_load(source_path, *args, **kwargs)
161 except Exception:
162 if not self._fallback_to_original:
163 raise
164 return self._original_load(source, *args, **kwargs)
166 def _streaming_load(self, file_path: str, *args: Any, **kwargs: Any):
167 with SpooledTemporaryFile(max_size=self._chunk_size * 2) as spooled:
168 for chunk in self._reader.iter_chunks(file_path, self._chunk_size):
169 spooled.write(chunk)
170 spooled.seek(0)
171 return self._original_load(spooled, *args, **kwargs)
174def patch_torch_load(
175 torch_module: ModuleType,
176 *,
177 min_file_size_mb: int = 64,
178 chunk_size_mb: int = 16,
179 stream_reader: TorchStreamReader | None = None,
180 use_cufile: bool = False,
181 fallback_to_original: bool = True,
182 patch_ops_on_oom: bool = False,
183) -> TorchCuFilePatcher:
184 patcher = TorchCuFilePatcher(
185 torch_module,
186 min_file_size_mb=min_file_size_mb,
187 chunk_size_mb=chunk_size_mb,
188 stream_reader=stream_reader,
189 use_cufile=use_cufile,
190 fallback_to_original=fallback_to_original,
191 patch_ops_on_oom=patch_ops_on_oom,
192 )
193 patcher.install()
194 return patcher