Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / activation_memory / checkpoint.py: 85%
402 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Eager non-reentrant activation checkpointing for the Torch backend.
17The saved-tensor hook algorithm is adapted from ``torch.utils.checkpoint`` in
18PyTorch release/2.9. Hyper owns the scheduling and session extensions here so
19the implementation can run consistently on PyTorch 2.6, 2.7, and 2.9 without
20patching the installed framework.
21"""
22import contextlib
23import contextvars
24import threading
25import uuid
26import warnings
27import weakref
28from collections import defaultdict
29from dataclasses import dataclass, field
30from functools import partial
31from typing import Any, Callable, DefaultDict, Dict, Generator, Iterator, List, Optional, Tuple
33import torch
34from torch.utils._pytree import tree_map
35from torch.utils.checkpoint import DefaultDeviceType
36from torch.utils.checkpoint import checkpoint as torch_checkpoint
37from torch.utils.checkpoint import set_checkpoint_early_stop
40_DEFAULT_DETERMINISM_MODE = "default"
41_RECOMPUTE_COLLECTOR = contextvars.ContextVar("hyper_recompute_collector", default=None)
42_RECOMPUTE_SESSION = contextvars.ContextVar("hyper_recompute_session", default=None)
43_SESSION_FRAMES: DefaultDict[Any, weakref.WeakSet] = defaultdict(weakref.WeakSet)
44_SESSION_FRAMES_LOCK = threading.RLock()
47class CheckpointError(RuntimeError):
48 """Raised when checkpoint forward and recomputation are inconsistent."""
51class _Handle:
52 """Identity key for one recomputed saved tensor."""
55class _Holder:
56 """Saved-tensor placeholder containing handles keyed by recompute session."""
58 def __init__(self) -> None:
59 """Initialize an empty per-session handle mapping."""
60 self.handles: Dict[Any, Optional[_Handle]] = {}
63class _StopRecomputationError(Exception):
64 """Internal control-flow exception used by early-stop recomputation."""
67class _SessionActivation:
68 """Control-plane state shared by checkpoint frames in one session scope."""
70 def __init__(self, session_id: Any, retain_on_unpack: bool) -> None:
71 """Initialize one scoped session activation."""
72 self.session_id = session_id
73 self.retain_on_unpack = retain_on_unpack
74 self.frames: weakref.WeakSet = weakref.WeakSet()
77class _NoopSaveInputs(torch.autograd.Function):
78 """Save checkpoint inputs without adding a meaningful forward operation."""
80 @staticmethod
81 def forward(*args: Any) -> Any:
82 """Return a dummy output whose grad function retains checkpoint inputs."""
83 del args
84 return torch.empty((0,))
86 @staticmethod
87 def setup_context(ctx: Any, inputs: Tuple[Any, ...], output: Any) -> None:
88 """Save tensor inputs while retaining non-tensor input structure."""
89 del output
90 tensor_pairs = [(index, value) for index, value in enumerate(inputs) if isinstance(value, torch.Tensor)]
91 tensor_indices, tensors = zip(*tensor_pairs)
92 index_to_saved_index = {input_index: saved_index for saved_index, input_index in enumerate(tensor_indices)}
93 stored_args = [None if isinstance(value, torch.Tensor) else value for value in inputs]
95 def get_args(saved_tensors: Tuple[Any, ...]) -> List[Any]:
96 """Reconstruct the original checkpoint arguments."""
97 restored_args = [
98 saved_tensors[index_to_saved_index[index]] if index in tensor_indices else value
99 for index, value in enumerate(stored_args)
100 ]
101 return restored_args[1:]
103 ctx.get_args = get_args
104 ctx.save_for_backward(*tensors)
106 @staticmethod
107 def backward(ctx: Any, *grad_outputs: Any) -> None:
108 """Reject direct backward through the internal input saver."""
109 del ctx, grad_outputs
110 raise CheckpointError("The internal checkpoint input saver must not be backwarded directly.")
113class _CheckpointFrame:
114 """State shared by one checkpoint forward and its recomputations."""
116 def __init__(self, recompute_fn: Callable, early_stop: bool, metadata_fn: Optional[Callable]) -> None:
117 """Initialize frame state captured by the saved-tensor hooks."""
118 self.recompute_fn = recompute_fn
119 self.input_saver = None
120 self.weak_holders: List[weakref.ReferenceType] = []
121 self.recomputed: DefaultDict[Any, weakref.WeakKeyDictionary] = defaultdict(weakref.WeakKeyDictionary)
122 self.recomp_counter: DefaultDict[Any, int] = defaultdict(int)
123 self.is_recomputed: DefaultDict[Any, bool] = defaultdict(bool)
124 self.early_stop = early_stop
125 self.metadata_fn = metadata_fn
126 self.x_metadatas: List[Any] = []
127 self.forward_completed = False
128 self.ignore_saved_mismatch = False
129 self.active_session: Optional[_SessionActivation] = None
131 def check_recomputed_tensors_match(self, session_id: Any) -> None:
132 """Validate saved-tensor count and metadata after recomputation."""
133 if self.ignore_saved_mismatch:
134 return
135 if len(self.weak_holders) != self.recomp_counter[session_id]:
136 raise CheckpointError(
137 "Hyper checkpoint saved a different number of tensors during forward and recomputation. "
138 f"Forward saved {len(self.weak_holders)} tensors, but recomputation saved "
139 f"{self.recomp_counter[session_id]} tensors."
140 )
142 mismatches = []
143 for index, weak_holder in enumerate(self.weak_holders):
144 holder = weak_holder()
145 if holder is None:
146 continue
147 handle = holder.handles.get(session_id)
148 _internal_assert(handle is not None, "Missing recomputed tensor handle during metadata validation.")
149 _internal_assert(
150 handle in self.recomputed[session_id],
151 "Missing recomputed tensor during metadata validation.",
152 )
153 recomputed_tensor = self.recomputed[session_id][handle]
154 recomputed_metadata = self.metadata_fn(recomputed_tensor)
155 if self.x_metadatas[index] != recomputed_metadata:
156 mismatches.append((index, self.x_metadatas[index], recomputed_metadata))
158 if mismatches:
159 details = "\n".join(
160 f"tensor {index}: forward={forward_metadata}, recompute={recomputed_metadata}"
161 for index, forward_metadata, recomputed_metadata in mismatches
162 )
163 raise CheckpointError(
164 "Hyper checkpoint detected different tensor metadata during recomputation:\n" + details
165 )
167 def clear_session(self, session_id: Any) -> None:
168 """Release all tensors and handles associated with one session."""
169 for weak_holder in self.weak_holders:
170 holder = weak_holder()
171 if holder is not None:
172 holder.handles.pop(session_id, None)
173 self.recomputed.pop(session_id, None)
174 self.recomp_counter.pop(session_id, None)
175 self.is_recomputed.pop(session_id, None)
178def _bind_session_activation(frame: _CheckpointFrame, activation: _SessionActivation) -> None:
179 """Bind one activation to a frame outside the unpack hot path."""
180 if frame.active_session is activation:
181 return
182 if frame.active_session is not None:
183 raise CheckpointError("Concurrent recompute sessions on the same checkpoint frame are not supported.")
184 frame.active_session = activation
185 activation.frames.add(frame)
188def _register_session_frame(
189 frame: _CheckpointFrame,
190 session_id: Any,
191 activation: Optional[_SessionActivation] = None,
192) -> None:
193 """Register a frame for cleanup and bind its current activation when present."""
194 with _SESSION_FRAMES_LOCK:
195 _SESSION_FRAMES[session_id].add(frame)
196 if activation is not None:
197 _internal_assert(activation.session_id == session_id, "Session activation key does not match its frame.")
198 _bind_session_activation(frame, activation)
201def _activate_registered_frames(activation: _SessionActivation) -> None:
202 """Install an activation on every frame already registered for its session."""
203 with _SESSION_FRAMES_LOCK:
204 for frame in list(_SESSION_FRAMES.get(activation.session_id, ())):
205 _bind_session_activation(frame, activation)
208def _deactivate_session(activation: _SessionActivation) -> None:
209 """Remove one activation from every frame bound at context entry."""
210 with _SESSION_FRAMES_LOCK:
211 for frame in list(activation.frames):
212 if frame.active_session is activation:
213 frame.active_session = None
214 activation.frames.clear()
217def _internal_assert(condition: bool, message: str) -> None:
218 if not condition:
219 raise CheckpointError(message)
222def _noop_context_fn() -> Tuple[contextlib.AbstractContextManager, contextlib.AbstractContextManager]:
223 return contextlib.nullcontext(), contextlib.nullcontext()
226def _default_metadata_fn(tensor: Any) -> Dict[str, Any]:
227 return {"shape": tensor.shape, "dtype": tensor.dtype, "device": tensor.device}
230def _infer_device_type(*args: Any) -> str:
231 """Return the preferred non-CPU device type found in checkpoint inputs."""
232 device_types = []
234 def add_device_type(value: Any) -> None:
235 """Record one non-CPU tensor device type."""
236 if isinstance(value, torch.Tensor) and value.device.type != "cpu":
237 device_types.append(value.device.type)
239 tree_map(add_device_type, args)
240 device_types_set = set(device_types)
241 if len(device_types_set) > 1:
242 warnings.warn(
243 "Hyper checkpoint received tensors on multiple non-CPU device types. RNG state is preserved only for "
244 "one device type; CUDA is preferred when present.",
245 stacklevel=3,
246 )
247 if not device_types:
248 return DefaultDeviceType.get_device_type()
249 if "cuda" in device_types_set:
250 return "cuda"
251 return device_types[0]
254def _get_device_module(device_type: str) -> Any:
255 if device_type == "meta":
256 return torch.device("meta")
257 return getattr(torch, device_type)
260def _get_device_states(device_type: str, *args: Any) -> Tuple[List[int], List[Any]]:
261 """Capture RNG states for non-CPU input devices of the requested type."""
262 device_ids = []
264 def add_device_id(value: Any) -> None:
265 """Record one non-CPU tensor device index."""
266 if isinstance(value, torch.Tensor) and value.device.type not in {"cpu", "meta"}:
267 device_ids.append(value.get_device())
269 tree_map(add_device_id, args)
270 device_module = _get_device_module(device_type)
271 states = []
272 for device_id in device_ids:
273 with device_module.device(device_id):
274 states.append(device_module.get_rng_state())
275 return device_ids, states
278def _set_device_states(device_type: str, devices: List[int], states: List[Any]) -> None:
279 if device_type == "meta":
280 return
281 device_module = _get_device_module(device_type)
282 for device, state in zip(devices, states):
283 with device_module.device(device):
284 device_module.set_rng_state(state)
287def _get_autocast_kwargs(device_type: str) -> Tuple[Optional[Dict[str, Any]], Dict[str, Any]]:
288 """Return active autocast settings for the selected device and CPU."""
289 device_kwargs = None
290 if torch.amp.is_autocast_available(device_type):
291 device_kwargs = {
292 "enabled": torch.is_autocast_enabled(device_type),
293 "dtype": torch.get_autocast_dtype(device_type),
294 "cache_enabled": torch.is_autocast_cache_enabled(),
295 }
296 cpu_kwargs = {
297 "enabled": torch.is_autocast_enabled("cpu"),
298 "dtype": torch.get_autocast_dtype("cpu"),
299 "cache_enabled": torch.is_autocast_cache_enabled(),
300 }
301 return device_kwargs, cpu_kwargs
304def _autocast_context(device_type: str, kwargs: Optional[Dict[str, Any]]) -> Any:
305 """Recreate the autocast state recorded before the checkpointed forward.
307 A recorded ``enabled=False`` must be restored explicitly: recomputation may
308 run inside the backward pass's own autocast region (e.g. forward outside
309 AMP, backward under ``autocast(bf16)``), and a null context would let that
310 ambient state leak into the replay, changing recomputed tensor dtypes.
311 """
312 if kwargs is None:
313 return contextlib.nullcontext()
314 if not kwargs.get("enabled", False) and not torch.is_autocast_enabled(device_type):
315 # Saved and ambient state are both "disabled": entering autocast here
316 # would only trigger needless device backend setup.
317 return contextlib.nullcontext()
318 return torch.amp.autocast(device_type=device_type, **kwargs)
321def _create_recomputation_hooks(frame: _CheckpointFrame, session_id: Any) -> Any:
322 """Create saved-tensor hooks that retain tensors from one recomputation."""
323 frame_ref = weakref.ref(frame)
325 def pack_hook(tensor: Any) -> Any:
326 """Store recomputed tensors in their forward holders."""
327 tensor = tensor.detach() if tensor.requires_grad else tensor
328 target_frame = frame_ref()
329 _internal_assert(target_frame is not None, "Checkpoint frame was released during recomputation.")
330 recompute_index = target_frame.recomp_counter[session_id]
331 target_frame.recomp_counter[session_id] += 1
333 if recompute_index >= len(target_frame.weak_holders):
334 if not target_frame.early_stop and not target_frame.forward_completed:
335 target_frame.ignore_saved_mismatch = True
336 return tensor
337 raise CheckpointError(
338 "Hyper checkpoint tried to save more tensors during recomputation than during forward."
339 )
341 holder = target_frame.weak_holders[recompute_index]()
342 if holder is not None:
343 _internal_assert(
344 holder.handles.get(session_id) is None,
345 "A recomputed tensor handle already exists for this session.",
346 )
347 handle = _Handle()
348 holder.handles[session_id] = handle
349 target_frame.recomputed[session_id][handle] = tensor
351 if target_frame.early_stop and target_frame.recomp_counter[session_id] == len(target_frame.weak_holders):
352 raise _StopRecomputationError
353 return tensor
355 def unpack_hook(tensor: Any) -> Any:
356 """Return tensors saved by operations inside the recomputation."""
357 return tensor
359 return torch.autograd.graph.saved_tensors_hooks(pack_hook, unpack_hook)
362# PyTorch exposes this tracing guard only as a private decorator.
363@torch._disable_dynamo # pylint: disable=protected-access
364def _run_fn_with_dynamo_disabled(function: Callable, *args: Any, **kwargs: Any) -> Any:
365 """Run recomputation without tracing the saved-tensor unpack hook with Dynamo."""
366 return function(*args, **kwargs)
369def _run_recomputation(frame: _CheckpointFrame, session_id: Any) -> None:
370 """Run and validate a frame recomputation for the given session."""
371 if frame.is_recomputed[session_id]:
372 return
374 activation = frame.active_session
375 if activation is not None:
376 _internal_assert(activation.session_id == session_id, "Active session key does not match recomputation key.")
377 previous_activation = _RECOMPUTE_SESSION.get()
378 token = None
379 if activation is not None and previous_activation is not activation:
380 token = _RECOMPUTE_SESSION.set(activation)
381 try:
382 input_context = frame.input_saver.grad_fn
383 args = input_context.get_args(input_context.saved_tensors)
384 try:
385 with _create_recomputation_hooks(frame, session_id), torch.autograd.enable_grad():
386 _run_fn_with_dynamo_disabled(frame.recompute_fn, *args)
387 except _StopRecomputationError:
388 pass
389 finally:
390 if token is not None:
391 _RECOMPUTE_SESSION.reset(token)
392 frame.is_recomputed[session_id] = True
393 frame.check_recomputed_tensors_match(session_id)
396def _create_checkpoint_hooks(frame: _CheckpointFrame) -> Any:
397 """Create hooks that lazily recompute tensors saved during forward."""
398 def pack_hook(tensor: Any) -> _Holder:
399 """Replace a forward saved tensor with an opaque holder."""
400 holder = _Holder()
401 frame.weak_holders.append(weakref.ref(holder))
402 if frame.metadata_fn is not None:
403 with torch.no_grad():
404 frame.x_metadatas.append(frame.metadata_fn(tensor))
405 return holder
407 def unpack_hook(holder: _Holder) -> Any:
408 """Return the corresponding tensor from lazy or prefired recomputation."""
409 activation = frame.active_session
410 if activation is not None:
411 session_id = activation.session_id
412 retain_on_unpack = activation.retain_on_unpack
413 else:
414 session_id = torch._C._current_graph_task_id() # pylint: disable=W0212
415 if session_id == -1:
416 session_id = int(uuid.uuid4())
417 retain_on_unpack = False
419 _run_recomputation(frame, session_id)
420 _internal_assert(session_id in holder.handles, "No recomputed tensor was saved for this checkpoint value.")
421 handle = holder.handles[session_id]
422 if handle is None:
423 raise CheckpointError("A checkpoint tensor was unpacked more than once in the same recompute session.")
424 _internal_assert(handle in frame.recomputed[session_id], "The recomputed tensor has already been released.")
425 tensor = frame.recomputed[session_id][handle]
426 if not retain_on_unpack:
427 holder.handles[session_id] = None
428 return tensor
430 return torch.autograd.graph.saved_tensors_hooks(pack_hook, unpack_hook)
433def _is_compiling() -> bool:
434 compiler = getattr(torch, "compiler", None)
435 return bool(compiler is not None and compiler.is_compiling())
438def _native_checkpoint(
439 function: Callable,
440 *args: Any,
441 context_fn: Callable,
442 preserve_rng_state: bool,
443 determinism_check: str,
444 debug: bool,
445 early_stop: bool,
446 **kwargs: Any,
447) -> Any:
448 """Use the public native API for compile, adapting 2.6/2.7 early-stop."""
449 with set_checkpoint_early_stop(early_stop):
450 return torch_checkpoint(
451 function,
452 *args,
453 use_reentrant=False,
454 context_fn=context_fn,
455 preserve_rng_state=preserve_rng_state,
456 determinism_check=determinism_check,
457 debug=debug,
458 **kwargs,
459 )
462@dataclass
463class _ExecutionState:
464 """Device, RNG, and autocast state captured before a checkpointed forward.
466 Bundles the values that both the forward pass and every later recomputation
467 must agree on, so the generator that owns the checkpoint lifetime can hand
468 them around as one object instead of a dozen loose locals.
469 """
471 device_type: str
472 device_module: Any
473 forward_context: Any
474 recompute_context: Any
475 device_autocast_kwargs: Optional[Dict[str, Any]]
476 cpu_autocast_kwargs: Dict[str, Any]
477 device_was_initialized: bool = False
478 device_ids: List[int] = field(default_factory=list)
479 device_states: List[Any] = field(default_factory=list)
480 cpu_state: Any = None
482 @classmethod
483 def capture(cls, context_fn: Callable, preserve_rng_state: bool, args: Tuple[Any, ...]) -> "_ExecutionState":
484 """Resolve contexts and capture RNG state before the forward pass runs."""
485 device_type = _infer_device_type(*args)
486 device_module = _get_device_module(device_type)
487 forward_context, recompute_context = _resolve_contexts(context_fn)
488 device_autocast_kwargs, cpu_autocast_kwargs = _get_autocast_kwargs(device_type)
490 # Device RNG is captured only when the device is already initialized;
491 # otherwise the device indexes its state lazily at first use.
492 device_initialized = preserve_rng_state and getattr(device_module, "_initialized", False)
493 device_ids, device_states = _get_device_states(device_type, *args) if device_initialized else ([], [])
495 return cls(
496 device_type=device_type,
497 device_module=device_module,
498 forward_context=forward_context,
499 recompute_context=recompute_context,
500 device_autocast_kwargs=device_autocast_kwargs,
501 cpu_autocast_kwargs=cpu_autocast_kwargs,
502 device_was_initialized=device_initialized,
503 device_ids=device_ids,
504 device_states=device_states,
505 cpu_state=torch.get_rng_state() if preserve_rng_state else None,
506 )
508 def check_device_state_preserved(self, preserve_rng_state: bool) -> None:
509 """Fail when the device was first initialized inside the checkpointed forward."""
510 device_initialized = getattr(self.device_module, "_initialized", False)
511 if preserve_rng_state and not self.device_was_initialized and device_initialized:
512 raise RuntimeError(
513 "The device state was initialized inside a Hyper checkpoint forward, so its initial RNG state "
514 "could not be preserved. Initialize the device before entering checkpoint."
515 )
517 def recompute_fn(self, function: Callable, *inputs: Any) -> None:
518 """Restore execution state and rerun the checkpointed ``function``."""
519 function_kwargs, *function_args = inputs
520 with torch.random.fork_rng(
521 devices=self.device_ids,
522 enabled=self.cpu_state is not None,
523 device_type=self.device_type,
524 ):
525 if self.cpu_state is not None:
526 torch.set_rng_state(self.cpu_state)
527 if self.device_was_initialized:
528 _set_device_states(self.device_type, self.device_ids, self.device_states)
530 device_autocast_context = _autocast_context(self.device_type, self.device_autocast_kwargs)
531 cpu_autocast_context = _autocast_context("cpu", self.cpu_autocast_kwargs)
532 with device_autocast_context, cpu_autocast_context, self.recompute_context:
533 function(*function_args, **function_kwargs)
536def _resolve_contexts(context_fn: Callable) -> Tuple[Any, Any]:
537 """Validate and unpack the (forward, recompute) context tuple from ``context_fn``."""
538 contexts = context_fn()
539 if not isinstance(contexts, tuple) or len(contexts) != 2:
540 raise ValueError("context_fn must return a (forward_context, recompute_context) tuple.")
541 return contexts[0], contexts[1]
544def _checkpoint_without_reentrant_generator(
545 function: Callable,
546 preserve_rng_state: bool,
547 context_fn: Callable,
548 determinism_check: str,
549 early_stop: bool,
550 *args: Any,
551 **kwargs: Any,
552) -> Generator[None, None, None]:
553 """Set up eager checkpoint state around the caller's forward execution."""
554 metadata_fn = _resolve_metadata_fn(determinism_check)
555 state = _ExecutionState.capture(context_fn, preserve_rng_state, args)
557 frame = _CheckpointFrame(partial(state.recompute_fn, function), early_stop, metadata_fn)
558 dummy = torch.empty((0,), requires_grad=True)
559 frame.input_saver = _NoopSaveInputs.apply(dummy, kwargs, *args)
561 if frame.input_saver.grad_fn is None:
562 yield
563 return
565 if _RECOMPUTE_SESSION.get() is not None:
566 raise CheckpointError("Nested checkpoint is not supported during scheduled recomputation.")
568 collector = _RECOMPUTE_COLLECTOR.get()
569 if collector is not None:
570 collector.append(frame)
571 try:
572 with _create_checkpoint_hooks(frame), state.forward_context:
573 yield
574 frame.forward_completed = True
575 state.check_device_state_preserved(preserve_rng_state)
576 except BaseException:
577 if collector is not None and frame in collector:
578 collector.remove(frame)
579 raise
582def _resolve_metadata_fn(determinism_check: str) -> Callable:
583 """Return the metadata extractor implementing ``determinism_check``."""
584 metadata_functions = {_DEFAULT_DETERMINISM_MODE: _default_metadata_fn, "none": lambda tensor: None}
585 if determinism_check not in metadata_functions:
586 raise ValueError(
587 f"determinism_check must be one of {list(metadata_functions)}, but got {determinism_check!r}."
588 )
589 return metadata_functions[determinism_check]
592def checkpoint(
593 function: Callable,
594 *args: Any,
595 use_reentrant: bool = False,
596 context_fn: Callable = _noop_context_fn,
597 preserve_rng_state: bool = True,
598 determinism_check: str = _DEFAULT_DETERMINISM_MODE,
599 debug: bool = False,
600 early_stop: bool = True,
601 **kwargs: Any,
602) -> Any:
603 """Run Hyper's non-reentrant checkpoint implementation.
605 Eager execution always uses this implementation. Compile execution falls
606 back to PyTorch's public non-reentrant checkpoint API.
607 """
608 if use_reentrant is not False:
609 raise ValueError("Hyper checkpoint only supports use_reentrant=False.")
610 if not isinstance(early_stop, bool):
611 raise ValueError(f"early_stop must be bool, but got {type(early_stop).__name__}.")
612 if not isinstance(preserve_rng_state, bool):
613 raise ValueError(
614 f"preserve_rng_state must be bool, but got {type(preserve_rng_state).__name__}."
615 )
616 if not callable(context_fn):
617 raise ValueError("context_fn must be callable.")
618 if _is_compiling():
619 return _native_checkpoint(
620 function,
621 *args,
622 context_fn=context_fn,
623 preserve_rng_state=preserve_rng_state,
624 determinism_check=determinism_check,
625 debug=debug,
626 early_stop=early_stop,
627 **kwargs,
628 )
629 if debug:
630 raise ValueError("debug=True is not supported by Hyper eager checkpoint yet.")
632 generator = _checkpoint_without_reentrant_generator(
633 function,
634 preserve_rng_state,
635 context_fn,
636 determinism_check,
637 early_stop,
638 *args,
639 **kwargs,
640 )
641 next(generator)
642 try:
643 result = function(*args, **kwargs)
644 except BaseException:
645 generator.close()
646 raise
647 try:
648 next(generator)
649 except StopIteration:
650 return result
651 generator.close()
652 raise CheckpointError("The internal checkpoint generator yielded more than once.")
655@contextlib.contextmanager
656def recompute_handle_collector_ctx() -> Iterator[List[Any]]:
657 """Collect opaque checkpoint handles created in this context."""
658 handles = []
659 token = _RECOMPUTE_COLLECTOR.set(handles)
660 try:
661 yield handles
662 finally:
663 _RECOMPUTE_COLLECTOR.reset(token)
666def recompute_handle(handle: Any, session_id: Any) -> None:
667 """Run one collected checkpoint recomputation ahead of backward."""
668 if not isinstance(handle, _CheckpointFrame):
669 raise ValueError("handle must be produced by recompute_handle_collector_ctx().")
670 _validate_session_id(session_id)
671 activation = _RECOMPUTE_SESSION.get()
672 if (
673 activation is not None
674 and activation.session_id == session_id
675 and activation.retain_on_unpack
676 ):
677 _register_session_frame(handle, session_id, activation)
678 _run_recomputation(handle, session_id)
679 return
680 if activation is not None:
681 raise CheckpointError("recompute_handle cannot enter another active recompute session.")
683 _register_session_frame(handle, session_id)
684 with recompute_session_ctx(session_id=session_id, retain_on_unpack=True):
685 _run_recomputation(handle, session_id)
688def _validate_session_id(session_id: Any) -> None:
689 if session_id is None:
690 raise ValueError("session_id must not be None.")
691 try:
692 hash(session_id)
693 except TypeError as error:
694 raise ValueError("session_id must be hashable.") from error
697@contextlib.contextmanager
698def recompute_session_ctx(session_id: Any, retain_on_unpack: bool = False) -> Iterator[Any]:
699 """Select the key and retention policy used by checkpoint unpack hooks."""
700 _validate_session_id(session_id)
701 if not isinstance(retain_on_unpack, bool):
702 raise ValueError(f"retain_on_unpack must be bool, but got {type(retain_on_unpack).__name__}.")
703 if _RECOMPUTE_SESSION.get() is not None:
704 raise CheckpointError("Nested recompute session contexts are not supported.")
705 activation = _SessionActivation(session_id, retain_on_unpack)
706 token = _RECOMPUTE_SESSION.set(activation)
707 try:
708 _activate_registered_frames(activation)
709 yield session_id
710 finally:
711 try:
712 _deactivate_session(activation)
713 finally:
714 _RECOMPUTE_SESSION.reset(token)
717def clear_recompute_session(session_id: Any) -> None:
718 """Release retained recomputation data for a session; repeated calls are safe."""
719 _validate_session_id(session_id)
720 with _SESSION_FRAMES_LOCK:
721 registered_frames = _SESSION_FRAMES.pop(session_id, None)
722 frames = list(registered_frames) if registered_frames is not None else []
723 for frame in frames:
724 frame.clear_session(session_id)