Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / dtensor / init_weights.py: 100%
30 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"""Empty / on-device weight initialization utilities."""
16# pylint: disable=C9006,C9007
18from collections.abc import Callable, Iterator
19from contextlib import contextmanager
20import sys
21from typing import Optional
23import torch
25from hyper_parallel.core.dtensor._utils import init_on_device as _init_on_device
28def _get_npu_fill_state() -> bool:
29 """Read NPU's independent uninitialized-memory fill flag when ``torch_npu`` is loaded."""
30 torch_npu_c = getattr(sys.modules.get("torch_npu"), "_C", None)
31 getter = getattr(torch_npu_c, "_npu_get_fill_uninitialized_memory", None)
32 return bool(getter()) if callable(getter) else False
35def _get_npu_fill_setter() -> Optional[Callable[[bool], None]]:
36 """Return ``torch_npu._C._npu_set_fill_uninitialized_memory`` when ``torch_npu`` is loaded."""
37 torch_npu_c = getattr(sys.modules.get("torch_npu"), "_C", None)
38 setter = getattr(torch_npu_c, "_npu_set_fill_uninitialized_memory", None)
39 return setter if callable(setter) else None
42@contextmanager
43def init_empty_weights(include_buffers: bool = False) -> Iterator[None]:
44 """Context manager that initializes model parameters (and optionally
45 buffers) on the meta device.
47 Models created under this context have no real data, which avoids allocating
48 any NPU/GPU/CPU memory. This is useful when the model is too large to fit in RAM
49 and the weights will be loaded from a checkpoint afterwards.
51 Args:
52 include_buffers (bool): If ``True``, buffers are also placed on the meta
53 device. Defaults to ``False``.
55 Example::
57 from hyper_parallel import init_empty_weights
59 with init_empty_weights():
60 model = MyLargeModel() # no memory allocated
62 Note:
63 A model initialised under this context has **no weights**. You cannot
64 call ``model.to(some_device)`` directly; load a checkpoint first.
66 Deterministic memory filling is suspended only inside this context:
67 factories may allocate CPU tensors before registration moves them to
68 meta. Filling that discarded storage defeats empty initialization.
69 The deterministic algorithm setting is unchanged.
70 """
71 fill_uninitialized_memory = torch.utils.deterministic.fill_uninitialized_memory
72 # torch_npu patches only the fill_uninitialized_memory setter while keeping its
73 # NPU-side fill flag False by default; preserve NPU's own flag across exit.
74 npu_fill_uninitialized_memory = _get_npu_fill_state()
75 try:
76 torch.utils.deterministic.fill_uninitialized_memory = False
77 with _init_on_device(torch.device("meta"), include_buffers=include_buffers):
78 yield
79 finally:
80 torch.utils.deterministic.fill_uninitialized_memory = fill_uninitialized_memory
81 npu_setter = _get_npu_fill_setter()
82 if npu_setter is not None:
83 npu_setter(npu_fill_uninitialized_memory)
86@contextmanager
87def init_on_device(device, include_buffers=False):
88 """Context manager that initializes model parameters (and optionally buffers) on *device*.
90 Args:
91 device: Target device for parameter (and buffer) allocation.
92 include_buffers (bool): If ``True``, buffers are also placed on *device*.
93 Defaults to ``False``.
95 Example::
97 from hyper_parallel import init_on_device
98 import torch
100 with init_on_device(torch.device("npu")):
101 model = MyModel() # parameters live on Ascend
102 """
103 with _init_on_device(device, include_buffers=include_buffers):
104 yield