aetherflow-ai 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- aetherflow/__init__.py +322 -0
- aetherflow/agent_api.py +234 -0
- aetherflow/backends/__init__.py +69 -0
- aetherflow/backends/base.py +74 -0
- aetherflow/backends/capabilities.py +286 -0
- aetherflow/backends/contracts.py +278 -0
- aetherflow/backends/cuda/__init__.py +16 -0
- aetherflow/backends/cuda/backend.py +1023 -0
- aetherflow/backends/cuda/codegen.py +2874 -0
- aetherflow/backends/cuda/cublas.py +428 -0
- aetherflow/backends/cuda/cudnn.py +305 -0
- aetherflow/backends/cuda/cufft.py +384 -0
- aetherflow/backends/cuda/cusparse.py +381 -0
- aetherflow/backends/cuda/dialect.py +80 -0
- aetherflow/backends/cuda/memory.py +243 -0
- aetherflow/backends/device_attention.py +257 -0
- aetherflow/backends/device_backend.py +1569 -0
- aetherflow/backends/device_conv.py +970 -0
- aetherflow/backends/device_elementwise.py +629 -0
- aetherflow/backends/device_index.py +230 -0
- aetherflow/backends/device_linear.py +1301 -0
- aetherflow/backends/device_loss.py +109 -0
- aetherflow/backends/device_misc.py +249 -0
- aetherflow/backends/device_norm.py +197 -0
- aetherflow/backends/device_plan.py +1062 -0
- aetherflow/backends/device_pool.py +592 -0
- aetherflow/backends/device_reduce.py +512 -0
- aetherflow/backends/device_scan.py +457 -0
- aetherflow/backends/device_shape.py +108 -0
- aetherflow/backends/device_shared.py +1107 -0
- aetherflow/backends/device_sparse.py +373 -0
- aetherflow/backends/discovery.py +286 -0
- aetherflow/backends/hardware.py +784 -0
- aetherflow/backends/hip/__init__.py +15 -0
- aetherflow/backends/hip/backend.py +567 -0
- aetherflow/backends/hip/blas.py +227 -0
- aetherflow/backends/hip/codegen.py +109 -0
- aetherflow/backends/hip/dialect.py +62 -0
- aetherflow/backends/hip/memory.py +418 -0
- aetherflow/backends/hip/rtc.py +126 -0
- aetherflow/backends/hip/runtime.py +2018 -0
- aetherflow/backends/kernel_cache.py +240 -0
- aetherflow/backends/reference_backend.py +76 -0
- aetherflow/backends/registry.py +224 -0
- aetherflow/conformance.py +2791 -0
- aetherflow/deploy.py +259 -0
- aetherflow/dynamic.py +252 -0
- aetherflow/frontend/__init__.py +39 -0
- aetherflow/frontend/compat.py +118 -0
- aetherflow/frontend/eager.py +345 -0
- aetherflow/frontend/module.py +320 -0
- aetherflow/frontend/torch_export.py +2047 -0
- aetherflow/fuzz.py +1093 -0
- aetherflow/gguf.py +693 -0
- aetherflow/ir/__init__.py +144 -0
- aetherflow/ir/control.py +444 -0
- aetherflow/ir/grad.py +240 -0
- aetherflow/ir/grad_rules.py +1814 -0
- aetherflow/ir/graph.py +370 -0
- aetherflow/ir/liveness.py +227 -0
- aetherflow/ir/loop.py +437 -0
- aetherflow/ir/ops.py +6333 -0
- aetherflow/ir/second_order.py +111 -0
- aetherflow/ir/serialize.py +180 -0
- aetherflow/ir/shape_contract.py +146 -0
- aetherflow/ir/types.py +363 -0
- aetherflow/ir/verifier.py +130 -0
- aetherflow/ir/version.py +196 -0
- aetherflow/lower/__init__.py +202 -0
- aetherflow/lower/cstyle.py +354 -0
- aetherflow/lower/elementwise.py +346 -0
- aetherflow/lower/indexing.py +170 -0
- aetherflow/lower/kernel.py +448 -0
- aetherflow/lower/kernels/__init__.py +262 -0
- aetherflow/lower/kernels/attention.py +390 -0
- aetherflow/lower/kernels/common.py +95 -0
- aetherflow/lower/kernels/conv.py +2927 -0
- aetherflow/lower/kernels/elementwise.py +676 -0
- aetherflow/lower/kernels/image.py +97 -0
- aetherflow/lower/kernels/interpolate.py +381 -0
- aetherflow/lower/kernels/misc.py +154 -0
- aetherflow/lower/kernels/norm.py +675 -0
- aetherflow/lower/kernels/pool.py +650 -0
- aetherflow/lower/kernels/reduce.py +891 -0
- aetherflow/lower/kernels/scan.py +939 -0
- aetherflow/lower/kernels/sparse.py +680 -0
- aetherflow/lower/plan.py +884 -0
- aetherflow/lower/translate.py +382 -0
- aetherflow/models/__init__.py +227 -0
- aetherflow/models/cached_attention.py +1133 -0
- aetherflow/models/cnn.py +208 -0
- aetherflow/models/hf_export.py +363 -0
- aetherflow/models/llama.py +875 -0
- aetherflow/models/lm.py +2888 -0
- aetherflow/models/lm_bpe.py +812 -0
- aetherflow/models/lm_text.py +159 -0
- aetherflow/models/lm_tools.py +1048 -0
- aetherflow/models/lm_unigram.py +794 -0
- aetherflow/models/lm_wordpiece.py +429 -0
- aetherflow/models/mamba.py +917 -0
- aetherflow/models/mamba_reference.py +183 -0
- aetherflow/models/mlp.py +84 -0
- aetherflow/models/moe.py +158 -0
- aetherflow/models/quantize.py +775 -0
- aetherflow/models/rnn.py +157 -0
- aetherflow/models/snn.py +362 -0
- aetherflow/models/speculative.py +426 -0
- aetherflow/models/ssm.py +179 -0
- aetherflow/models/transformer.py +382 -0
- aetherflow/passes/__init__.py +73 -0
- aetherflow/passes/autocast.py +180 -0
- aetherflow/passes/base.py +92 -0
- aetherflow/passes/cse.py +85 -0
- aetherflow/passes/dce.py +57 -0
- aetherflow/passes/fold.py +158 -0
- aetherflow/passes/fusion.py +268 -0
- aetherflow/passes/layout.py +261 -0
- aetherflow/passes/registry.py +213 -0
- aetherflow/passes/simplify.py +42 -0
- aetherflow/plugin.py +75 -0
- aetherflow/runtime/__init__.py +48 -0
- aetherflow/runtime/bf16.py +83 -0
- aetherflow/runtime/device_control.py +472 -0
- aetherflow/runtime/events.py +251 -0
- aetherflow/runtime/executor.py +617 -0
- aetherflow/runtime/fp8.py +275 -0
- aetherflow/runtime/paged_cache.py +897 -0
- aetherflow/runtime/prefix_store.py +508 -0
- aetherflow/runtime/reference.py +27 -0
- aetherflow/runtime/telemetry.py +596 -0
- aetherflow/runtime/trace.py +256 -0
- aetherflow/serve/__init__.py +20 -0
- aetherflow/serve/openai.py +767 -0
- aetherflow/train/__init__.py +154 -0
- aetherflow/train/_arrays.py +150 -0
- aetherflow/train/amp.py +219 -0
- aetherflow/train/bn.py +224 -0
- aetherflow/train/checkpoint.py +480 -0
- aetherflow/train/data.py +219 -0
- aetherflow/train/dataset.py +544 -0
- aetherflow/train/distributed.py +394 -0
- aetherflow/train/ema.py +143 -0
- aetherflow/train/grads.py +293 -0
- aetherflow/train/host_collective.py +497 -0
- aetherflow/train/lm.py +117 -0
- aetherflow/train/loop.py +1860 -0
- aetherflow/train/loss.py +105 -0
- aetherflow/train/monitor.py +208 -0
- aetherflow/train/nccl.py +831 -0
- aetherflow/train/optim.py +456 -0
- aetherflow/train/parallel.py +1296 -0
- aetherflow/train/params.py +220 -0
- aetherflow/train/pipeline.py +532 -0
- aetherflow/train/recompute.py +344 -0
- aetherflow/train/schedule.py +212 -0
- aetherflow/train/shard_io.py +685 -0
- aetherflow/train/sharded.py +490 -0
- aetherflow/train/tensor_parallel.py +527 -0
- aetherflow/train/zero.py +847 -0
- aetherflow/train/zero2.py +410 -0
- aetherflow/train/zero3.py +529 -0
- aetherflow/tuning/__init__.py +95 -0
- aetherflow/tuning/cost.py +535 -0
- aetherflow/tuning/paired.py +991 -0
- aetherflow/tuning/policy.py +195 -0
- aetherflow/tuning/search.py +290 -0
- aetherflow/tuning/signature.py +90 -0
- aetherflow/tuning/space.py +124 -0
- aetherflow/tuning/store.py +280 -0
- aetherflow/weights.py +1271 -0
- aetherflow_ai-0.2.0.dist-info/METADATA +578 -0
- aetherflow_ai-0.2.0.dist-info/RECORD +175 -0
- aetherflow_ai-0.2.0.dist-info/WHEEL +5 -0
- aetherflow_ai-0.2.0.dist-info/licenses/LICENSE +201 -0
- aetherflow_ai-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,685 @@
|
|
|
1
|
+
"""分布式存档的合并与重分片:N 个分片 ↔ 一份完整状态。
|
|
2
|
+
|
|
3
|
+
ZeRO-1/2/3 的 ``save_shard`` 都只写"本 rank 那一份":单卡数续训够用,但两件
|
|
4
|
+
事做不了——
|
|
5
|
+
|
|
6
|
+
1. **合并**:把 N 个分片合成一份完整权重 / 优化器状态(推理、发布、单卡续训);
|
|
7
|
+
2. **换 world_size**:8 卡训到一半换成 4 卡(或反过来),分片数与归属全变了,
|
|
8
|
+
直接 ``load_shard`` 会被"分片数不一致"拦下。
|
|
9
|
+
|
|
10
|
+
本模块补这两件。它**不碰通信**:全是文件读写的纯函数,任何进程都能调,也不
|
|
11
|
+
需要六个 rank 同时在线。换 world_size 靠的是"先拼回完整状态、再按新布局重新
|
|
12
|
+
切"——而不是让两个不同规模的 world 直接对话。想不落盘直接把旧分片交给新
|
|
13
|
+
world 的某个 rank 时用 :func:`resume_shard`:它等价于 merge + split 后取那
|
|
14
|
+
一片,结果可直接喂给 ``ZeroRank.load_state()`` / ``Zero3Rank.load_state()``。
|
|
15
|
+
|
|
16
|
+
**两种布局。**
|
|
17
|
+
|
|
18
|
+
- ``names``(ZeRO-1 / ZeRO-2):按参数名分片,存档里**只有槽位**,参数在模型
|
|
19
|
+
里。合并掉的只是各片槽位的并集;要写出完整 checkpoint,必须把模型权重作为
|
|
20
|
+
``params=`` 一起给进来。
|
|
21
|
+
- ``elements``(ZeRO-3):按元素切块,存档里**有参数分片**,合并后能原样拼回
|
|
22
|
+
完整参数,不需要额外权重。
|
|
23
|
+
|
|
24
|
+
合并产物的判据只有一条:**能被既有读取路径读回**。``save()`` 写的是
|
|
25
|
+
``checkpoint.py`` 的同构格式,``load_checkpoint`` 直接可读、参数与槽位逐位
|
|
26
|
+
相等,才算真的合并对了。
|
|
27
|
+
|
|
28
|
+
**为什么元素布局要 reshape 回完整形状而不是留一维。** 合并后的槽位是给"整份
|
|
29
|
+
参数"的优化器用的,``Optimizer.load_state_dict`` 校验槽位形状等于参数形状;
|
|
30
|
+
留在 flatten 后的样子会被当成"形状不符"拒绝。切分时再 ravel,等价往返。
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import json
|
|
36
|
+
import os
|
|
37
|
+
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
|
|
38
|
+
|
|
39
|
+
import numpy as np
|
|
40
|
+
|
|
41
|
+
from .checkpoint import _HYPER, _PARAM, _SLOT, _STEP, _atomic_savez, _payload_from
|
|
42
|
+
from .sharded import shard_params
|
|
43
|
+
from .zero3 import plan_chunks
|
|
44
|
+
|
|
45
|
+
__all__ = ["ShardedCheckpoint", "merge_shards", "split_checkpoint", "resume_shard"]
|
|
46
|
+
|
|
47
|
+
_META_KEY = "__meta__"
|
|
48
|
+
|
|
49
|
+
#: 按参数名分片(ZeRO-1 / ZeRO-2)。
|
|
50
|
+
_NAMES = "names"
|
|
51
|
+
#: 按元素切块(ZeRO-3)。
|
|
52
|
+
_ELEMENTS = "elements"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _with_suffix(path: Any) -> str:
|
|
56
|
+
target = str(path)
|
|
57
|
+
return target if target.endswith(".npz") else target + ".npz"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _read_shard_file(path: Any) -> Tuple[Dict[str, Any], Dict[str, np.ndarray]]:
|
|
61
|
+
"""读一份分片:meta 解析成字典,数组按 ``kind::name`` 原样取出。"""
|
|
62
|
+
target = _with_suffix(path)
|
|
63
|
+
arrays: Dict[str, np.ndarray] = {}
|
|
64
|
+
with np.load(target, allow_pickle=False) as data:
|
|
65
|
+
if _META_KEY not in data.files:
|
|
66
|
+
raise ValueError(f"{target} 不是分片存档:缺少 {_META_KEY}")
|
|
67
|
+
meta = json.loads(str(data[_META_KEY]))
|
|
68
|
+
for key in data.files:
|
|
69
|
+
if key == _META_KEY:
|
|
70
|
+
continue
|
|
71
|
+
_, sep, name = key.partition("::")
|
|
72
|
+
if not sep or not name:
|
|
73
|
+
raise ValueError(f"{target} 里的键 {key!r} 不是 kind::name 形式")
|
|
74
|
+
arrays[key] = np.array(data[key], copy=True)
|
|
75
|
+
if "plan" in meta:
|
|
76
|
+
meta["layout"] = _ELEMENTS
|
|
77
|
+
elif "assignments" in meta:
|
|
78
|
+
meta["layout"] = _NAMES
|
|
79
|
+
else:
|
|
80
|
+
raise ValueError(
|
|
81
|
+
f"{target} 既没有 plan 也没有 assignments,无法判断分片布局;"
|
|
82
|
+
"这个文件不是 ZeRO 的分片存档"
|
|
83
|
+
)
|
|
84
|
+
return meta, arrays
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _check_common(metas: Sequence[Mapping[str, Any]]) -> int:
|
|
88
|
+
"""跨分片的一致性:片数、片号、步数、超参、布局。返回 world_size。"""
|
|
89
|
+
worlds = {int(meta.get("world_size", 0)) for meta in metas}
|
|
90
|
+
if len(worlds) != 1:
|
|
91
|
+
raise ValueError(f"这些分片的 world_size 不一致: {sorted(worlds)}")
|
|
92
|
+
world_size = worlds.pop()
|
|
93
|
+
ranks = sorted(int(meta.get("rank", -1)) for meta in metas)
|
|
94
|
+
if len(set(ranks)) != len(ranks):
|
|
95
|
+
raise ValueError(f"分片里的 rank 有重复: {ranks}")
|
|
96
|
+
if ranks != list(range(world_size)):
|
|
97
|
+
missing = sorted(set(range(world_size)) - set(ranks))
|
|
98
|
+
extra = sorted(set(ranks) - set(range(world_size)))
|
|
99
|
+
raise ValueError(
|
|
100
|
+
f"分片不齐:world_size={world_size} 需要 rank 0..{world_size - 1},"
|
|
101
|
+
f"缺少 {missing},越界 {extra}"
|
|
102
|
+
)
|
|
103
|
+
steps = {int(meta.get("step", 0)) for meta in metas}
|
|
104
|
+
if len(steps) != 1:
|
|
105
|
+
raise ValueError(f"这些分片的步数不一致: {sorted(steps)}")
|
|
106
|
+
hypers = {json.dumps(meta.get("hyper") or {}, sort_keys=True) for meta in metas}
|
|
107
|
+
if len(hypers) != 1:
|
|
108
|
+
raise ValueError("这些分片的优化器超参不一致;它们不属于同一条训练轨迹")
|
|
109
|
+
layouts = {str(meta["layout"]) for meta in metas}
|
|
110
|
+
if len(layouts) != 1:
|
|
111
|
+
raise ValueError(f"这些分片的布局不一致: {sorted(layouts)};不能混合布局合并")
|
|
112
|
+
return world_size
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _slice_elements(
|
|
116
|
+
name: str,
|
|
117
|
+
array: np.ndarray,
|
|
118
|
+
*,
|
|
119
|
+
shape: Tuple[int, ...],
|
|
120
|
+
size: int,
|
|
121
|
+
chunk: int,
|
|
122
|
+
rank: int,
|
|
123
|
+
what: str,
|
|
124
|
+
) -> np.ndarray:
|
|
125
|
+
"""把一个参数的完整数组按 ``rank`` 切出第 ``rank`` 块(尾部补零)。"""
|
|
126
|
+
flat = np.ascontiguousarray(np.asarray(array)).ravel()
|
|
127
|
+
if flat.size != size:
|
|
128
|
+
raise ValueError(
|
|
129
|
+
f"{what} {name!r} 有 {flat.size} 个元素,与形状 {shape} 的 {size} 个不符"
|
|
130
|
+
)
|
|
131
|
+
piece = np.zeros(chunk, dtype=flat.dtype)
|
|
132
|
+
start = rank * chunk
|
|
133
|
+
stop = min(start + chunk, size)
|
|
134
|
+
if start < stop:
|
|
135
|
+
piece[: stop - start] = flat[start:stop]
|
|
136
|
+
return piece
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _join_elements(
|
|
140
|
+
pieces: Sequence[np.ndarray],
|
|
141
|
+
*,
|
|
142
|
+
shape: Tuple[int, ...],
|
|
143
|
+
size: int,
|
|
144
|
+
chunk: int,
|
|
145
|
+
name: str,
|
|
146
|
+
what: str,
|
|
147
|
+
) -> np.ndarray:
|
|
148
|
+
"""把 ``world_size`` 块按 rank 顺序拼回完整数组(丢掉尾部补零)。"""
|
|
149
|
+
flat = np.concatenate([np.asarray(piece).ravel() for piece in pieces])
|
|
150
|
+
if flat.size < size:
|
|
151
|
+
raise ValueError(
|
|
152
|
+
f"{what} {name!r} 的分片总长 {flat.size} 小于参数元素数 {size}"
|
|
153
|
+
)
|
|
154
|
+
return flat[:size].reshape(shape)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class ShardedCheckpoint:
|
|
158
|
+
"""合并后的完整状态:参数 + 槽位 + 步数 + 超参,以及它是从哪种布局来的。
|
|
159
|
+
|
|
160
|
+
``params`` 在 ``elements`` 布局下必然存在(分片里就带参数);``names`` 布局
|
|
161
|
+
下只有当调用方把模型权重传给 ``merge_shards(params=...)`` 时才有。
|
|
162
|
+
"""
|
|
163
|
+
|
|
164
|
+
def __init__(
|
|
165
|
+
self,
|
|
166
|
+
*,
|
|
167
|
+
layout: str,
|
|
168
|
+
world_size: int,
|
|
169
|
+
step: int,
|
|
170
|
+
hyper: Mapping[str, Any],
|
|
171
|
+
params: Optional[Mapping[str, np.ndarray]] = None,
|
|
172
|
+
slots: Optional[Mapping[str, Mapping[str, np.ndarray]]] = None,
|
|
173
|
+
assignments: Optional[Mapping[str, int]] = None,
|
|
174
|
+
plan: Optional[Mapping[str, Tuple[Tuple[int, ...], int]]] = None,
|
|
175
|
+
) -> None:
|
|
176
|
+
if layout not in (_NAMES, _ELEMENTS):
|
|
177
|
+
raise ValueError(f"不认识的布局 {layout!r},只支持 {_NAMES!r} / {_ELEMENTS!r}")
|
|
178
|
+
self.layout = layout
|
|
179
|
+
self.world_size = int(world_size)
|
|
180
|
+
self.step = int(step)
|
|
181
|
+
self.hyper: Dict[str, Any] = dict(hyper)
|
|
182
|
+
self.params: Dict[str, np.ndarray] = {
|
|
183
|
+
name: np.array(array, copy=True) for name, array in (params or {}).items()
|
|
184
|
+
}
|
|
185
|
+
self.slots: Dict[str, Dict[str, np.ndarray]] = {
|
|
186
|
+
slot: {name: np.array(array, copy=True) for name, array in by_name.items()}
|
|
187
|
+
for slot, by_name in (slots or {}).items()
|
|
188
|
+
}
|
|
189
|
+
self.assignments: Dict[str, int] = {
|
|
190
|
+
name: int(owner) for name, owner in (assignments or {}).items()
|
|
191
|
+
}
|
|
192
|
+
self.plan: Dict[str, Tuple[Tuple[int, ...], int]] = {
|
|
193
|
+
name: (tuple(int(dim) for dim in shape), int(chunk))
|
|
194
|
+
for name, (shape, chunk) in (plan or {}).items()
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
# -- 输出 ---------------------------------------------------------
|
|
198
|
+
|
|
199
|
+
def save(self, path: Any, *, meta: Optional[Mapping[str, object]] = None) -> str:
|
|
200
|
+
"""写成一份完整 checkpoint(与 ``save_checkpoint`` 同构)。
|
|
201
|
+
|
|
202
|
+
没有参数时报错:``names`` 布局的存档本来只存槽位,"合并出权重"这件事
|
|
203
|
+
必须由调用方把模型权重一起交进来——这里不做"用零填上"的猜测。
|
|
204
|
+
"""
|
|
205
|
+
if not self.params:
|
|
206
|
+
raise ValueError(
|
|
207
|
+
"这份合并结果里没有参数:按名分片的存档(ZeRO-1/2)只存槽位,"
|
|
208
|
+
"请把模型权重作为 params= 传给 merge_shards();"
|
|
209
|
+
"只有槽位的话别用 save(),用 write_shards() 重新分片"
|
|
210
|
+
)
|
|
211
|
+
target = str(path)
|
|
212
|
+
if not target.endswith(".npz"):
|
|
213
|
+
raise ValueError(f"存档后缀必须是 .npz,得到 {target!r}")
|
|
214
|
+
optimizer_state = {
|
|
215
|
+
"step": self.step,
|
|
216
|
+
"hyper": dict(self.hyper),
|
|
217
|
+
"slots": self.slots,
|
|
218
|
+
}
|
|
219
|
+
payload = _payload_from(self.params, optimizer_state, None, meta)
|
|
220
|
+
_atomic_savez(target, payload)
|
|
221
|
+
return target
|
|
222
|
+
|
|
223
|
+
def split(
|
|
224
|
+
self, world_size: Optional[int] = None, *, layout: Optional[str] = None
|
|
225
|
+
) -> List[Dict[str, Any]]:
|
|
226
|
+
"""按目标 ``world_size`` / ``layout`` 切成每 rank 一份的存档内容。
|
|
227
|
+
|
|
228
|
+
返回的每个字典与 ``save_shard`` 写入的内容同构,既能直接交给
|
|
229
|
+
``_write_state`` 落盘,也能被调用方读走做别的事。
|
|
230
|
+
"""
|
|
231
|
+
target_world = self.world_size if world_size is None else world_size
|
|
232
|
+
if isinstance(target_world, bool) or not isinstance(target_world, int):
|
|
233
|
+
raise TypeError(f"world_size 必须是 int,收到 {target_world!r}")
|
|
234
|
+
if target_world < 1:
|
|
235
|
+
raise ValueError(f"world_size 必须 >= 1,收到 {target_world}")
|
|
236
|
+
target_layout = self.layout if layout is None else layout
|
|
237
|
+
if target_layout not in (_NAMES, _ELEMENTS):
|
|
238
|
+
raise ValueError(f"不认识的布局 {target_layout!r}")
|
|
239
|
+
if target_layout == _ELEMENTS:
|
|
240
|
+
return self._split_elements(target_world)
|
|
241
|
+
return self._split_names(target_world)
|
|
242
|
+
|
|
243
|
+
def write_shards(
|
|
244
|
+
self,
|
|
245
|
+
pattern: str,
|
|
246
|
+
world_size: Optional[int] = None,
|
|
247
|
+
*,
|
|
248
|
+
layout: Optional[str] = None,
|
|
249
|
+
) -> List[str]:
|
|
250
|
+
"""把每个 rank 的分片写到 ``pattern``(必须含 ``{rank}``),返回路径。"""
|
|
251
|
+
if "{rank}" not in str(pattern):
|
|
252
|
+
raise ValueError(
|
|
253
|
+
f"命名模板 {pattern!r} 里没有 {{rank}}:每个 rank 会覆盖同一个文件"
|
|
254
|
+
)
|
|
255
|
+
states = self.split(world_size, layout=layout)
|
|
256
|
+
return [_write_state(state, str(pattern).format(rank=state["rank"])) for state in states]
|
|
257
|
+
|
|
258
|
+
# -- 内部 ---------------------------------------------------------
|
|
259
|
+
|
|
260
|
+
def _split_names(self, world_size: int) -> List[Dict[str, Any]]:
|
|
261
|
+
"""按参数名重新分片(ZeRO-1 / ZeRO-2 的布局)。"""
|
|
262
|
+
if self.params:
|
|
263
|
+
buckets = shard_params(self.params, world_size)
|
|
264
|
+
owners = {name: index for index, bucket in enumerate(buckets) for name in bucket}
|
|
265
|
+
elif world_size == self.world_size and self.assignments:
|
|
266
|
+
owners = dict(self.assignments)
|
|
267
|
+
else:
|
|
268
|
+
raise ValueError(
|
|
269
|
+
"换 world_size 重新按名分片需要完整参数表(按字节均衡的归属由形状"
|
|
270
|
+
"决定),请把模型权重作为 params= 传给 merge_shards()"
|
|
271
|
+
)
|
|
272
|
+
states: List[Dict[str, Any]] = []
|
|
273
|
+
for rank in range(world_size):
|
|
274
|
+
owned = [name for name, owner in owners.items() if owner == rank]
|
|
275
|
+
slots: Dict[str, Dict[str, np.ndarray]] = {}
|
|
276
|
+
for slot, by_name in self.slots.items():
|
|
277
|
+
missing = [name for name in owned if name not in by_name]
|
|
278
|
+
if missing:
|
|
279
|
+
raise KeyError(
|
|
280
|
+
f"槽位 {slot!r} 缺少这些参数的数组: {missing};"
|
|
281
|
+
"分片存档不完整,不能重新分片"
|
|
282
|
+
)
|
|
283
|
+
slots[slot] = {name: np.array(by_name[name], copy=True) for name in owned}
|
|
284
|
+
states.append(
|
|
285
|
+
{
|
|
286
|
+
"layout": _NAMES,
|
|
287
|
+
"rank": rank,
|
|
288
|
+
"world_size": world_size,
|
|
289
|
+
"step": self.step,
|
|
290
|
+
"hyper": dict(self.hyper),
|
|
291
|
+
"slots": slots,
|
|
292
|
+
"assignments": {name: rank for name in owned},
|
|
293
|
+
}
|
|
294
|
+
)
|
|
295
|
+
return states
|
|
296
|
+
|
|
297
|
+
def _split_elements(self, world_size: int) -> List[Dict[str, Any]]:
|
|
298
|
+
"""按元素重新切块(ZeRO-3 的布局)。"""
|
|
299
|
+
if not self.params:
|
|
300
|
+
raise ValueError(
|
|
301
|
+
"元素级分片必须有完整参数表:分片合并出的参数缺失,"
|
|
302
|
+
"请把模型权重作为 params= 传给 merge_shards()"
|
|
303
|
+
)
|
|
304
|
+
plan = plan_chunks(self.params, world_size)
|
|
305
|
+
states: List[Dict[str, Any]] = []
|
|
306
|
+
for rank in range(world_size):
|
|
307
|
+
params: Dict[str, np.ndarray] = {}
|
|
308
|
+
slots: Dict[str, Dict[str, np.ndarray]] = {}
|
|
309
|
+
for name, (shape, size, chunk) in plan.items():
|
|
310
|
+
params[name] = _slice_elements(
|
|
311
|
+
name,
|
|
312
|
+
self.params[name],
|
|
313
|
+
shape=shape,
|
|
314
|
+
size=size,
|
|
315
|
+
chunk=chunk,
|
|
316
|
+
rank=rank,
|
|
317
|
+
what="参数",
|
|
318
|
+
)
|
|
319
|
+
for slot, by_name in self.slots.items():
|
|
320
|
+
if name not in by_name:
|
|
321
|
+
raise KeyError(
|
|
322
|
+
f"槽位 {slot!r} 缺少参数 {name!r} 的数组;分片存档不完整"
|
|
323
|
+
)
|
|
324
|
+
slots.setdefault(slot, {})[name] = _slice_elements(
|
|
325
|
+
name,
|
|
326
|
+
by_name[name],
|
|
327
|
+
shape=shape,
|
|
328
|
+
size=size,
|
|
329
|
+
chunk=chunk,
|
|
330
|
+
rank=rank,
|
|
331
|
+
what=f"槽位 {slot!r}",
|
|
332
|
+
)
|
|
333
|
+
states.append(
|
|
334
|
+
{
|
|
335
|
+
"layout": _ELEMENTS,
|
|
336
|
+
"rank": rank,
|
|
337
|
+
"world_size": world_size,
|
|
338
|
+
"step": self.step,
|
|
339
|
+
"hyper": dict(self.hyper),
|
|
340
|
+
"params": params,
|
|
341
|
+
"slots": slots,
|
|
342
|
+
"plan": {
|
|
343
|
+
name: [list(plan[name][0]), plan[name][2]] for name in plan
|
|
344
|
+
},
|
|
345
|
+
}
|
|
346
|
+
)
|
|
347
|
+
return states
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _write_state(state: Mapping[str, Any], path: Any) -> str:
|
|
351
|
+
"""把一份"每 rank 的存档内容"写成 npz(格式与 ``save_shard`` 完全一致)。"""
|
|
352
|
+
target = _with_suffix(path)
|
|
353
|
+
arrays: Dict[str, np.ndarray] = {}
|
|
354
|
+
if state["layout"] == _ELEMENTS:
|
|
355
|
+
for name, array in state["params"].items():
|
|
356
|
+
arrays[f"param::{name}"] = np.asarray(array)
|
|
357
|
+
meta = {
|
|
358
|
+
"rank": state["rank"],
|
|
359
|
+
"world_size": state["world_size"],
|
|
360
|
+
"step": state["step"],
|
|
361
|
+
"hyper": state["hyper"],
|
|
362
|
+
"plan": state["plan"],
|
|
363
|
+
}
|
|
364
|
+
else:
|
|
365
|
+
meta = {
|
|
366
|
+
"rank": state["rank"],
|
|
367
|
+
"world_size": state["world_size"],
|
|
368
|
+
"step": state["step"],
|
|
369
|
+
"hyper": state["hyper"],
|
|
370
|
+
"assignments": state["assignments"],
|
|
371
|
+
}
|
|
372
|
+
for slot, by_name in state["slots"].items():
|
|
373
|
+
for name, array in by_name.items():
|
|
374
|
+
arrays[f"{slot}::{name}"] = np.asarray(array)
|
|
375
|
+
arrays[_META_KEY] = np.array(json.dumps(meta, ensure_ascii=False))
|
|
376
|
+
_atomic_savez(target, arrays)
|
|
377
|
+
return target
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def merge_shards(
|
|
381
|
+
paths: Sequence[Any],
|
|
382
|
+
*,
|
|
383
|
+
params: Optional[Mapping[str, np.ndarray]] = None,
|
|
384
|
+
) -> ShardedCheckpoint:
|
|
385
|
+
"""把 N 个分片合成一份完整状态。
|
|
386
|
+
|
|
387
|
+
``params`` 是可选的模型权重:``elements`` 布局会拿它当"分片拼出来的参数
|
|
388
|
+
是否对得上"的 oracle(不一致说明分片来自另一份权重);``names`` 布局则必
|
|
389
|
+
须靠它才能写出完整 checkpoint(按名分片的存档不含参数)。
|
|
390
|
+
"""
|
|
391
|
+
targets = [_with_suffix(path) for path in paths]
|
|
392
|
+
if not targets:
|
|
393
|
+
raise ValueError("没有给任何分片文件")
|
|
394
|
+
loaded = [_read_shard_file(target) for target in targets]
|
|
395
|
+
metas = [meta for meta, _ in loaded]
|
|
396
|
+
world_size = _check_common(metas)
|
|
397
|
+
layout = str(metas[0]["layout"])
|
|
398
|
+
step = int(metas[0]["step"])
|
|
399
|
+
hyper = dict(metas[0].get("hyper") or {})
|
|
400
|
+
if layout == _ELEMENTS:
|
|
401
|
+
return _merge_elements(metas, [arrays for _, arrays in loaded], world_size, step, hyper, params)
|
|
402
|
+
return _merge_names(metas, [arrays for _, arrays in loaded], world_size, step, hyper, params)
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _merge_names(
|
|
406
|
+
metas: Sequence[Mapping[str, Any]],
|
|
407
|
+
arrays: Sequence[Mapping[str, np.ndarray]],
|
|
408
|
+
world_size: int,
|
|
409
|
+
step: int,
|
|
410
|
+
hyper: Mapping[str, Any],
|
|
411
|
+
params: Optional[Mapping[str, np.ndarray]],
|
|
412
|
+
) -> ShardedCheckpoint:
|
|
413
|
+
assignments: Dict[str, int] = {}
|
|
414
|
+
for meta in metas:
|
|
415
|
+
rank = int(meta["rank"])
|
|
416
|
+
for name, owner in dict(meta["assignments"]).items():
|
|
417
|
+
if int(owner) != rank:
|
|
418
|
+
raise ValueError(
|
|
419
|
+
f"rank {rank} 的存档里把 {name!r} 记在了 rank {owner} 名下;"
|
|
420
|
+
"分片自相矛盾,不能合并"
|
|
421
|
+
)
|
|
422
|
+
if name in assignments:
|
|
423
|
+
raise ValueError(
|
|
424
|
+
f"参数 {name!r} 同时出现在多个分片的归属表里"
|
|
425
|
+
f"(rank {assignments[name]} 与 rank {rank})"
|
|
426
|
+
)
|
|
427
|
+
assignments[name] = rank
|
|
428
|
+
|
|
429
|
+
slots: Dict[str, Dict[str, np.ndarray]] = {}
|
|
430
|
+
for rank, by_key in enumerate(arrays):
|
|
431
|
+
for key, array in by_key.items():
|
|
432
|
+
slot, sep, name = key.partition("::")
|
|
433
|
+
if not sep:
|
|
434
|
+
raise ValueError(f"分片 {rank} 里的键 {key!r} 不完整")
|
|
435
|
+
if slot == "param":
|
|
436
|
+
raise ValueError(
|
|
437
|
+
f"分片 {rank} 里有参数数组 {name!r}:按名分片的存档不该带参数;"
|
|
438
|
+
"它可能是元素布局(ZeRO-3)的存档,请勿混用"
|
|
439
|
+
)
|
|
440
|
+
if name not in assignments:
|
|
441
|
+
raise KeyError(
|
|
442
|
+
f"分片 {rank} 的槽位 {slot!r} 里有 {name!r},但它不在归属表里"
|
|
443
|
+
)
|
|
444
|
+
if name in slots.get(slot, {}):
|
|
445
|
+
raise ValueError(f"槽位 {slot!r} 的 {name!r} 在两个分片里都有")
|
|
446
|
+
slots.setdefault(slot, {})[name] = array
|
|
447
|
+
|
|
448
|
+
for slot, by_name in slots.items():
|
|
449
|
+
missing = sorted(set(assignments) - set(by_name))
|
|
450
|
+
if missing:
|
|
451
|
+
raise KeyError(f"槽位 {slot!r} 缺少这些参数的数组: {missing};分片不完整")
|
|
452
|
+
|
|
453
|
+
full_params: Dict[str, np.ndarray] = {}
|
|
454
|
+
if params is not None:
|
|
455
|
+
given = {name: np.asarray(array) for name, array in params.items()}
|
|
456
|
+
if set(given) != set(assignments):
|
|
457
|
+
raise KeyError(
|
|
458
|
+
f"传入的参数表与分片不一致:多 {sorted(set(given) - set(assignments))},"
|
|
459
|
+
f"少 {sorted(set(assignments) - set(given))}"
|
|
460
|
+
)
|
|
461
|
+
for slot, by_name in slots.items():
|
|
462
|
+
for name, array in by_name.items():
|
|
463
|
+
if tuple(np.shape(array)) != tuple(given[name].shape):
|
|
464
|
+
raise ValueError(
|
|
465
|
+
f"槽位 {slot!r} 的 {name!r} 形状 {np.shape(array)} 与参数 "
|
|
466
|
+
f"{given[name].shape} 不一致"
|
|
467
|
+
)
|
|
468
|
+
full_params = given
|
|
469
|
+
|
|
470
|
+
return ShardedCheckpoint(
|
|
471
|
+
layout=_NAMES,
|
|
472
|
+
world_size=world_size,
|
|
473
|
+
step=step,
|
|
474
|
+
hyper=hyper,
|
|
475
|
+
params=full_params,
|
|
476
|
+
slots=slots,
|
|
477
|
+
assignments=assignments,
|
|
478
|
+
)
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def _merge_elements(
|
|
482
|
+
metas: Sequence[Mapping[str, Any]],
|
|
483
|
+
arrays: Sequence[Mapping[str, np.ndarray]],
|
|
484
|
+
world_size: int,
|
|
485
|
+
step: int,
|
|
486
|
+
hyper: Mapping[str, Any],
|
|
487
|
+
params: Optional[Mapping[str, np.ndarray]],
|
|
488
|
+
) -> ShardedCheckpoint:
|
|
489
|
+
plan: Dict[str, Tuple[Tuple[int, ...], int]] = {}
|
|
490
|
+
for meta in metas:
|
|
491
|
+
current = {
|
|
492
|
+
name: (tuple(int(dim) for dim in shape), int(chunk))
|
|
493
|
+
for name, (shape, chunk) in dict(meta["plan"]).items()
|
|
494
|
+
}
|
|
495
|
+
if not plan:
|
|
496
|
+
plan = current
|
|
497
|
+
elif current != plan:
|
|
498
|
+
diff = sorted(
|
|
499
|
+
name
|
|
500
|
+
for name in set(plan) | set(current)
|
|
501
|
+
if plan.get(name) != current.get(name)
|
|
502
|
+
)
|
|
503
|
+
raise ValueError(
|
|
504
|
+
f"这些分片的块布局不一致({diff});它们不是同一次训练写下的"
|
|
505
|
+
)
|
|
506
|
+
|
|
507
|
+
merged_params: Dict[str, np.ndarray] = {}
|
|
508
|
+
for name, (shape, chunk) in plan.items():
|
|
509
|
+
size = int(np.prod(shape, dtype=np.int64)) if shape else 1
|
|
510
|
+
pieces = []
|
|
511
|
+
dtype = None
|
|
512
|
+
for rank, by_key in enumerate(arrays):
|
|
513
|
+
key = f"param::{name}"
|
|
514
|
+
if key not in by_key:
|
|
515
|
+
raise KeyError(f"rank {rank} 的分片里没有参数 {name!r}")
|
|
516
|
+
piece = by_key[key]
|
|
517
|
+
if piece.shape != (chunk,):
|
|
518
|
+
raise ValueError(
|
|
519
|
+
f"rank {rank} 的 {name!r} 分片形状 {piece.shape} 与块长 ({chunk},) 不一致"
|
|
520
|
+
)
|
|
521
|
+
if dtype is None:
|
|
522
|
+
dtype = piece.dtype
|
|
523
|
+
elif piece.dtype != dtype:
|
|
524
|
+
raise TypeError(
|
|
525
|
+
f"{name!r} 的分片 dtype 不一致:{dtype} 与 {piece.dtype}"
|
|
526
|
+
)
|
|
527
|
+
pieces.append(piece)
|
|
528
|
+
merged_params[name] = _join_elements(
|
|
529
|
+
pieces, shape=shape, size=size, chunk=chunk, name=name, what="参数"
|
|
530
|
+
)
|
|
531
|
+
|
|
532
|
+
slots: Dict[str, Dict[str, np.ndarray]] = {}
|
|
533
|
+
slot_names = {
|
|
534
|
+
key.partition("::")[0]
|
|
535
|
+
for by_key in arrays
|
|
536
|
+
for key in by_key
|
|
537
|
+
if key.partition("::")[0] != "param"
|
|
538
|
+
}
|
|
539
|
+
for rank, by_key in enumerate(arrays):
|
|
540
|
+
present = {key.partition("::")[0] for key in by_key if key.partition("::")[0] != "param"}
|
|
541
|
+
if present != slot_names:
|
|
542
|
+
raise ValueError(
|
|
543
|
+
f"rank {rank} 的槽位集合 {sorted(present)} 与其它分片 "
|
|
544
|
+
f"{sorted(slot_names)} 不一致"
|
|
545
|
+
)
|
|
546
|
+
for slot in sorted(slot_names):
|
|
547
|
+
merged: Dict[str, np.ndarray] = {}
|
|
548
|
+
for name, (shape, chunk) in plan.items():
|
|
549
|
+
size = int(np.prod(shape, dtype=np.int64)) if shape else 1
|
|
550
|
+
pieces = []
|
|
551
|
+
for rank, by_key in enumerate(arrays):
|
|
552
|
+
key = f"{slot}::{name}"
|
|
553
|
+
if key not in by_key:
|
|
554
|
+
raise KeyError(f"rank {rank} 的槽位 {slot!r} 里没有参数 {name!r}")
|
|
555
|
+
piece = by_key[key]
|
|
556
|
+
if piece.shape != (chunk,):
|
|
557
|
+
raise ValueError(
|
|
558
|
+
f"rank {rank} 的槽位 {slot!r} / {name!r} 形状 {piece.shape} "
|
|
559
|
+
f"与块长 ({chunk},) 不一致"
|
|
560
|
+
)
|
|
561
|
+
pieces.append(piece)
|
|
562
|
+
merged[name] = _join_elements(
|
|
563
|
+
pieces, shape=shape, size=size, chunk=chunk, name=name, what=f"槽位 {slot!r}"
|
|
564
|
+
)
|
|
565
|
+
slots[slot] = merged
|
|
566
|
+
|
|
567
|
+
if params is not None:
|
|
568
|
+
given = {name: np.asarray(array) for name, array in params.items()}
|
|
569
|
+
if set(given) != set(merged_params):
|
|
570
|
+
raise KeyError(
|
|
571
|
+
f"传入的参数表与分片不一致:多 {sorted(set(given) - set(merged_params))},"
|
|
572
|
+
f"少 {sorted(set(merged_params) - set(given))}"
|
|
573
|
+
)
|
|
574
|
+
for name, array in merged_params.items():
|
|
575
|
+
if tuple(given[name].shape) != tuple(array.shape):
|
|
576
|
+
raise ValueError(
|
|
577
|
+
f"传入的 {name!r} 形状 {given[name].shape} 与分片拼出的 "
|
|
578
|
+
f"{array.shape} 不一致"
|
|
579
|
+
)
|
|
580
|
+
if not np.array_equal(given[name], array):
|
|
581
|
+
raise ValueError(
|
|
582
|
+
f"传入的 {name!r} 与分片拼出的数值不同:分片来自另一份权重,"
|
|
583
|
+
"别把它们合并到一起"
|
|
584
|
+
)
|
|
585
|
+
|
|
586
|
+
return ShardedCheckpoint(
|
|
587
|
+
layout=_ELEMENTS,
|
|
588
|
+
world_size=world_size,
|
|
589
|
+
step=step,
|
|
590
|
+
hyper=hyper,
|
|
591
|
+
params=merged_params,
|
|
592
|
+
slots=slots,
|
|
593
|
+
plan=plan,
|
|
594
|
+
)
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def _read_full_checkpoint(path: Any) -> Tuple[Dict[str, np.ndarray], Dict[str, Dict[str, np.ndarray]], int, Dict[str, Any]]:
|
|
598
|
+
"""读一份普通 checkpoint 的参数 / 槽位 / 步数 / 超参(忽略流式状态与 meta)。"""
|
|
599
|
+
source = str(path)
|
|
600
|
+
params: Dict[str, np.ndarray] = {}
|
|
601
|
+
slots: Dict[str, Dict[str, np.ndarray]] = {}
|
|
602
|
+
hyper: Dict[str, Any] = {}
|
|
603
|
+
step = 0
|
|
604
|
+
with np.load(source) as data:
|
|
605
|
+
for key in data.files:
|
|
606
|
+
if key.startswith(_PARAM):
|
|
607
|
+
params[key[len(_PARAM):]] = np.array(data[key], copy=True)
|
|
608
|
+
elif key.startswith(_SLOT):
|
|
609
|
+
rest = key[len(_SLOT):]
|
|
610
|
+
slot, sep, name = rest.partition("/")
|
|
611
|
+
if not sep or not name:
|
|
612
|
+
raise KeyError(f"存档里的槽位条目 {key!r} 不完整")
|
|
613
|
+
slots.setdefault(slot, {})[name] = np.array(data[key], copy=True)
|
|
614
|
+
elif key == _STEP:
|
|
615
|
+
step = int(data[key])
|
|
616
|
+
elif key.startswith(_HYPER):
|
|
617
|
+
hyper[key[len(_HYPER):]] = data[key].item()
|
|
618
|
+
if not params:
|
|
619
|
+
raise ValueError(f"{source} 里没有参数条目({_PARAM}*),不是一份完整 checkpoint")
|
|
620
|
+
return params, slots, step, hyper
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def split_checkpoint(
|
|
624
|
+
path: Any,
|
|
625
|
+
world_size: int,
|
|
626
|
+
pattern: str,
|
|
627
|
+
*,
|
|
628
|
+
layout: str = _ELEMENTS,
|
|
629
|
+
) -> List[str]:
|
|
630
|
+
"""把一份完整 checkpoint 按 ``world_size`` 切成每 rank 一个分片文件。
|
|
631
|
+
|
|
632
|
+
``layout="elements"`` 对应 ZeRO-3(写出的文件带参数分片),
|
|
633
|
+
``layout="names"`` 对应 ZeRO-1/2(只切槽位,参数仍由各 rank 自己的模型提供)。
|
|
634
|
+
两种写出的文件都能被对应类的 ``load_shard`` 直接读回。
|
|
635
|
+
"""
|
|
636
|
+
if os.path.isdir(str(path)):
|
|
637
|
+
raise ValueError(f"{path} 是目录,不是 checkpoint 文件")
|
|
638
|
+
params, slots, step, hyper = _read_full_checkpoint(path)
|
|
639
|
+
checkpoint = ShardedCheckpoint(
|
|
640
|
+
layout=layout,
|
|
641
|
+
world_size=int(world_size),
|
|
642
|
+
step=step,
|
|
643
|
+
hyper=hyper,
|
|
644
|
+
params=params,
|
|
645
|
+
slots=slots,
|
|
646
|
+
# 归属/块布局都由目标 world_size 现算,于是"换了卡数也能接上"。
|
|
647
|
+
assignments=None,
|
|
648
|
+
plan=None,
|
|
649
|
+
)
|
|
650
|
+
return checkpoint.write_shards(pattern, world_size, layout=layout)
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def resume_shard(
|
|
654
|
+
paths: Sequence[Any],
|
|
655
|
+
*,
|
|
656
|
+
rank: int,
|
|
657
|
+
world_size: int,
|
|
658
|
+
params: Optional[Mapping[str, np.ndarray]] = None,
|
|
659
|
+
) -> Dict[str, Any]:
|
|
660
|
+
"""把旧 world 的一组分片重组到新 world,返回 ``rank`` 那一片的状态。
|
|
661
|
+
|
|
662
|
+
与 :func:`split_checkpoint` 的分工:那个从"一份完整 checkpoint"出发,这个
|
|
663
|
+
从"N 个分片文件"出发,且**不落盘**——结果直接交给 ``ZeroRank`` /
|
|
664
|
+
``Zero2Rank`` / ``Zero3Rank`` 的 ``load_state()``。于是"8 卡训到一半换
|
|
665
|
+
4 卡"不必先写出一份 8 卡的完整 checkpoint:少一次全量读写,也省一半磁盘
|
|
666
|
+
峰值。
|
|
667
|
+
|
|
668
|
+
``paths`` 必须是**旧** world 的全部分片(顺序随意,按存档里的 rank 认)。
|
|
669
|
+
ZeRO-1/2 的分片只存槽位,换 world_size 重新按名分片需要完整参数表,此时
|
|
670
|
+
必须给 ``params=``;ZeRO-3 的分片自带参数,不需要。
|
|
671
|
+
|
|
672
|
+
**代价。** 每个 rank 各自把所有分片读进内存再切,峰值是"整份优化器状态
|
|
673
|
+
+ 自己那片"。适合数百 MB 到数 GB 的模型;整份状态放不下时,应当先用
|
|
674
|
+
``ShardedCheckpoint.write_shards()`` 落盘一次,之后各 rank 只读自己那份。
|
|
675
|
+
"""
|
|
676
|
+
if isinstance(world_size, bool) or not isinstance(world_size, int):
|
|
677
|
+
raise TypeError(f"world_size 必须是 int,收到 {world_size!r}")
|
|
678
|
+
if world_size < 1:
|
|
679
|
+
raise ValueError(f"world_size 必须 >= 1,收到 {world_size}")
|
|
680
|
+
if isinstance(rank, bool) or not isinstance(rank, int):
|
|
681
|
+
raise TypeError(f"rank 必须是 int,收到 {rank!r}")
|
|
682
|
+
if not 0 <= rank < world_size:
|
|
683
|
+
raise ValueError(f"rank {rank} 越界:world_size={world_size}")
|
|
684
|
+
merged = merge_shards(paths, params=params)
|
|
685
|
+
return dict(merged.split(world_size)[rank])
|