serialization.py 16.9 KB
Newer Older
liangjing's avatar
v1  
liangjing committed
1
2
# Copyright (c) 2022-2023, NVIDIA CORPORATION.  All rights reserved.

liangjing's avatar
liangjing committed
3
4
5
6
7
8
9
10
""" Entrypoints for saving and loading the distributed checkpoints.

Functions `load` and `save` are equivalents of `torch.load` and `torch.save`
but expect torch.Tensors to be wrapped with classes from the `mapping module`.
Additionally, `load` expects the sharded state dict argument as a guidance for
loading the sharded tensors.
"""

liangjing's avatar
v1  
liangjing committed
11
12
import logging
from pathlib import Path
liangjing's avatar
liangjing committed
13
from typing import Dict, Optional, Set, Tuple, Union
liangjing's avatar
v1  
liangjing committed
14
15
16

import torch

liangjing's avatar
liangjing committed
17
18
19
from . import ShardedTensor
from .core import CheckpointingConfig, save_config
from .dict_utils import extract_matching_values, merge
liangjing's avatar
v1  
liangjing committed
20
21
22
23
24
25
26
from .mapping import (
    CheckpointingException,
    ShardedObject,
    ShardedStateDict,
    StateDict,
    apply_factory_merges,
)
liangjing's avatar
liangjing committed
27
28
from .state_dict_transformation import load_preprocess, save_preprocess
from .strategies.async_utils import AsyncRequest
liangjing's avatar
v1  
liangjing committed
29
from .strategies.base import (
liangjing's avatar
liangjing committed
30
    AsyncSaveShardedStrategy,
liangjing's avatar
v1  
liangjing committed
31
32
33
34
35
36
37
    LoadCommonStrategy,
    LoadShardedStrategy,
    SaveCommonStrategy,
    SaveShardedStrategy,
    StrategyAction,
    get_default_strategy,
)
liangjing's avatar
liangjing committed
38
39
40
41
42
43
44
45
46
from .utils import extract_sharded_base
from .validation import (
    StrictHandling,
    determine_global_metadata,
    parse_strict_flag,
    validate_integrity_and_strict_load,
    validate_sharded_objects_handling,
    verify_checkpoint_and_load_strategy,
)
liangjing's avatar
v1  
liangjing committed
47
48
49
50

logger = logging.getLogger(__name__)


liangjing's avatar
liangjing committed
51
52
53
54
# flat state dict with sharded objects without any data
CkptShardedMetadata = Dict[str, Union[ShardedTensor, ShardedObject]]


liangjing's avatar
v1  
liangjing committed
55
56
57
def load(
    sharded_state_dict: ShardedStateDict,
    checkpoint_dir: str,
liangjing's avatar
liangjing committed
58
59
60
61
62
    sharded_strategy: Union[LoadShardedStrategy, Tuple[str, int], None] = None,
    common_strategy: Union[LoadCommonStrategy, Tuple[str, int], None] = None,
    validate_access_integrity: bool = True,
    strict: Union[str, StrictHandling] = StrictHandling.ASSUME_OK_UNEXPECTED,
) -> Union[StateDict, Tuple[StateDict, Set[str], Set[str]]]:
liangjing's avatar
v1  
liangjing committed
63
64
    """Loading entrypoint.

liangjing's avatar
liangjing committed
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
    In the steps below, the following verbs refer to corresponding objects:
    - load = load from checkpoint
    - extract = extract from sharded_state_dict
    - add = add to the final state dict
    Steps:
    1. Load common state dict and form the base of the result state dict
    2. Apply factories to sharded_state_dict
    3. Extract LocalNonPersistentObject and add
    4. (optional) Extract ShardedObjects, load and add
    5. Extract ShardedBase, load, apply factory merges and add

    Args:
        sharded_state_dict (ShardedStateDict): state dict of the existing model
            populated with ShardedTensors. Used as a mapping to determine which
            parts of global tensors stored in the checkpoint should be loaded.
        checkpoint_dir (str): directory with the checkpoint
        sharded_strategy (LoadShardedStrategy, Tuple[str, int], optional):
            configures loading behavior for sharded tensors
        common_strategy (LoadCommonStrategy, Tuple[str, int], optional):
            configures loading behavior for common data
        validate_access_integrity (bool default = True): checks if each tensor shard is accessed
            exactly once (as main replica) by some process
        strict (StrictHandling, str, optional): determines the behavior in case of a mismatch
            between the requested sharded state dict and the checkpoint. See `StrictHandling` docs
            for more details. Some values affect the return value of this function
            (missing and unexpected keys are returned).
            Defaults to `True` (StrictHandling.ASSUME_OK_UNEXPECTED) which doesn't
            incur any performance overhead. Other recommended values
            are: `False` (StrictHandling.LOG_UNEXPECTED) which logs only unexpected keys
            or `StrictHandling.RETURN_ALL` which returns all mismatch keys.

    Returns:
        StateDict or Tuple[StateDict, Set[str], Set[str]]: in most cases only
            the loaded state dict is returned. If `strict` flag was set to
liangjing's avatar
v1  
liangjing committed
99
    """
liangjing's avatar
liangjing committed
100
101
102
    sharded_strategy, common_strategy = verify_checkpoint_and_load_strategy(
        checkpoint_dir, sharded_strategy, common_strategy
    )
liangjing's avatar
v1  
liangjing committed
103
104

    checkpoint_dir = Path(checkpoint_dir)
liangjing's avatar
liangjing committed
105
    common_state_dict = common_strategy.load_common(checkpoint_dir)
liangjing's avatar
v1  
liangjing committed
106
107
108
    if not sharded_state_dict:
        return common_state_dict

liangjing's avatar
liangjing committed
109
110
    sharded_state_dict, nonpersistent_state_dict, sh_ten_factories = load_preprocess(
        sharded_state_dict
liangjing's avatar
v1  
liangjing committed
111
112
113
    )
    merge(common_state_dict, nonpersistent_state_dict)

liangjing's avatar
liangjing committed
114
115
    # At this point we are only dealing with ShardedBase objects
    sharded_state_dict, _ = extract_sharded_base(sharded_state_dict)
liangjing's avatar
v1  
liangjing committed
116

liangjing's avatar
liangjing committed
117
118
119
120
121
122
123
    # Validation
    ckpt_sharded_metadata = None
    local_metadata, global_metadata = None, None
    strict = parse_strict_flag(strict)
    if StrictHandling.requires_explicit_ckpt_mismatch_check(strict):
        ckpt_sharded_metadata = load_sharded_metadata(
            str(checkpoint_dir), sharded_strategy, common_strategy
liangjing's avatar
v1  
liangjing committed
124
        )
liangjing's avatar
liangjing committed
125
126
127
128
129
130
131
132
133
134
135
    if validate_access_integrity or StrictHandling.requires_global_app_metadata(strict):
        local_metadata, global_metadata = determine_global_metadata(sharded_state_dict)

    sharded_state_dict, missing_keys, unexpected_keys = validate_integrity_and_strict_load(
        sharded_state_dict,
        strict,
        validate_access_integrity,
        local_metadata,
        global_metadata,
        ckpt_sharded_metadata,
    )
liangjing's avatar
v1  
liangjing committed
136

liangjing's avatar
liangjing committed
137
138
139
140
141
142
143
144
145
146
147
148
    # ShardedBase loading
    if not sharded_strategy.can_handle_sharded_objects:
        validate_sharded_objects_handling(sharded_strategy, common_strategy)
        sharded_objects_state_dict, sharded_state_dict = extract_matching_values(
            sharded_state_dict, lambda v: isinstance(v, ShardedObject)
        )
        sharded_objects = common_strategy.load_sharded_objects(
            sharded_objects_state_dict, checkpoint_dir
        )
        merge(common_state_dict, sharded_objects)

    loaded_state_dict = sharded_strategy.load(sharded_state_dict, checkpoint_dir)
liangjing's avatar
v1  
liangjing committed
149
150
151

    merge(common_state_dict, loaded_state_dict)

liangjing's avatar
liangjing committed
152
153
154
155
156
157
158
159
160
161
162
163
164
    loaded_state_dict = apply_factory_merges(common_state_dict, sh_ten_factories)

    if StrictHandling.requires_returning_mismatch_keys(strict):
        return common_state_dict, missing_keys, unexpected_keys
    else:
        return common_state_dict


def load_common_state_dict(checkpoint_dir: Path) -> StateDict:
    """Load common (non-sharded) objects state dict from the checkpoint.

    Args:
        checkpoint_dir (Path): checkpoint directory
liangjing's avatar
v1  
liangjing committed
165

liangjing's avatar
liangjing committed
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
    Returns:
        StateDict: state dict with non-sharded objects from the checkpoint
    """
    sharded_strategy, common_strategy = verify_checkpoint_and_load_strategy(str(checkpoint_dir))
    return common_strategy.load_common(checkpoint_dir)


def load_tensors_metadata(
    checkpoint_dir: str, sharded_strategy: Union[LoadShardedStrategy, None] = None
) -> CkptShardedMetadata:
    """Load tensors metadata from the checkpoint.

    Returns a dictionary similar to a sharded state dict, but note that
    the dictionary keys are simply ShardedTensor keys (contrary to the
    actual sharded state dicts where keys correspond to state dict keys).

    Dict values are ShardedTensors without any sharding (so, the only useful
    information is tensors global shape and dtype).
liangjing's avatar
v1  
liangjing committed
184

liangjing's avatar
liangjing committed
185
186
    Concrete implementation depends on the loading strategy. If no strategy is
    given, a default for a given backend is used.
liangjing's avatar
v1  
liangjing committed
187

liangjing's avatar
liangjing committed
188
189
190
191
192
193
194
195
196
197
198
199
    Args:
        checkpoint_dir (str): checkpoint directory to load from
        sharded_strategy (LoadShardedStrategy, optional): sharded strategy to load metadata.
            Defaults to None - in this case a default load strategy for a given checkpoint type
            is used.

    Returns:
        CkptShardedMetadata: flat state dict without data describing ShardedTensors
            in the checkpoint
    """
    sharded_strategy, common_strategy = verify_checkpoint_and_load_strategy(
        checkpoint_dir, sharded_strategy
liangjing's avatar
v1  
liangjing committed
200
    )
liangjing's avatar
liangjing committed
201
    return sharded_strategy.load_tensors_metadata(Path(checkpoint_dir))
liangjing's avatar
v1  
liangjing committed
202
203


liangjing's avatar
liangjing committed
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
def load_sharded_metadata(
    checkpoint_dir: str,
    sharded_strategy: Union[LoadShardedStrategy, None] = None,
    common_strategy: Union[LoadCommonStrategy, None] = None,
) -> CkptShardedMetadata:
    """Load sharded metadata from the checkpoint.

    Similar to `load_tensors_metadata`, but includes also ShardedObjects.

    Returns a dictionary similar to a sharded state dict, but note that
    the dictionary keys are simply ShardedTensor keys (contrary to the
    actual sharded state dicts where keys correspond to state dict keys).

    Dict values are ShardedTensors without any sharding (so, the only useful
    information is tensors global shape and dtype).

    Concrete implementation depends on the loading strategy. If no strategy is
    given, a default for a given backend is used.

    Args:
        checkpoint_dir (str): checkpoint directory to load from
        sharded_strategy (LoadShardedStrategy, optional): sharded strategy to load metadata.
            Defaults to None - in this case a default load strategy for a given checkpoint type
            is used.
        common_strategy (LoadCommonStrategy, optional): common strategy to load metadata.
            Defaults to None - in this case a default load strategy for a given checkpoint type is
            used. This strategy won't be used unless `sharded_strategy` can't handle ShardedObjects

    Returns:
        CkptShardedMetadata: flat state dict without data describing ShardedTensors
            and ShardedObjects in the checkpoint
    """
    sharded_strategy, common_strategy = verify_checkpoint_and_load_strategy(
        checkpoint_dir, sharded_strategy, common_strategy
    )
    sharded_metadata = sharded_strategy.load_sharded_metadata(Path(checkpoint_dir))
    if not sharded_strategy.can_handle_sharded_objects:
        validate_sharded_objects_handling(sharded_strategy, common_strategy)
        common_metadata = common_strategy.load_sharded_metadata(Path(checkpoint_dir))
        sharded_metadata = merge(sharded_metadata, common_metadata)
    return sharded_metadata


def load_plain_tensors(checkpoint_dir: str) -> StateDict:
    """Load checkpoint tensors without any sharding and plain structure.

    NOTE: common state dict is NOT included.

    Args:
        checkpoint_dir (str): checkpoint directory to load the tensors from.

    Returns:
        StateDict: checkpoint state dict containing only torch.Tensors.
    """
    sharded_state_dict = load_tensors_metadata(checkpoint_dir)
    # Don't validate integrity because shards will be overlapped
    # if world_size > 1 (all processes load whole tensors)
    return load(sharded_state_dict, checkpoint_dir, validate_access_integrity=False)


#
# def load_plain_tensors_and_objects(checkpoint_dir: str) -> StateDict:
#     """Load checkpoint tensors and objects without any sharding and plain structure.
#
#     NOTE: state dict structure might be different than the one used for checkpoint saving.
#     NOTE: common state dict is NOT included.
#
#     Args:
#         checkpoint_dir (str): checkpoint directory to load the state dict from.
#
#     Returns:
#         StateDict: complete checkpoint state dict without any sharding.
#     """
#     sharded_state_dict = load_tensors_metadata(checkpoint_dir)
#     # Don't validate integrity because shards will be overlapped
#     # if world_size > 1 (all processes load whole tensors)
#     return load(sharded_state_dict, checkpoint_dir, validate_access_integrity=False)
liangjing's avatar
v1  
liangjing committed
281
282
283
284
285


def save(
    sharded_state_dict: ShardedStateDict,
    checkpoint_dir: str,
liangjing's avatar
liangjing committed
286
287
288
289
290
    sharded_strategy: Union[SaveShardedStrategy, Tuple[str, int], None] = None,
    common_strategy: Union[SaveCommonStrategy, Tuple[str, int], None] = None,
    validate_access_integrity: bool = True,
    async_sharded_save: bool = False,
) -> Optional[AsyncRequest]:
liangjing's avatar
v1  
liangjing committed
291
292
293
294
295
296
297
    """Saving entrypoint.

    Extracts ShardedTensors from the given state dict. Rank 0 saves the
    "regular" part of the checkpoint to common torch file.
    The ShardedTensors are saved according to a strategy specified by the
    config.

liangjing's avatar
liangjing committed
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
    Steps:
    1. Apply factories
    2. Extract and discard LocalNonPersistentObject
    3. Extract all ShardedBase object
    4. Save all other objects to common.pt
    5. (optional) Extract and save ShardedObjects
    6. Save all ShardedBase objects
    7. Write metadata.json file with backend and version metadata.

    Step (6) can be performed asynchronously (see `async_sharded_save`), in this
    case the actual save is embodied in the returned async request and can be
    scheduled by the external caller. For async request, step (7) is added as
    one of the finalization functions, so that metadata.json is written only
    if the checkpoint is complete.

    Args:
        sharded_state_dict (ShardedStateDict): state dict of the populated with
liangjing's avatar
v1  
liangjing committed
315
316
            ShardedTensors. Used as a mapping to determine how local tensors
            should be saved as global tensors in the checkpoint.
liangjing's avatar
liangjing committed
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
        checkpoint_dir (str): directory to save the checkpoint to
        sharded_strategy (SaveShardedStrategy, Tuple[str, int], optional):
            configures sharded tensors saving behavior and backend
        common_strategy (SaveCommonStrategy, Tuple[str, int], optional):
            configures common data saving behavior and backend
        validate_access_integrity (bool default = True): checks if each tensor shard is accessed
            exactly once (as main replica) by some process
        async_sharded_save (bool, optional): if True, for the sharded state dict part
            an async save implementation will be called, with the AsyncRequest
            being returned to the caller. Note that it is the caller responsibility to
            actually schedule the async save. Defaults to False.

    Returns:
        AsyncRequest (optional): if `async_sharded_save` is True, returns
            async request that should be scheduled by the caller of this function.
            None otherwise.
liangjing's avatar
v1  
liangjing committed
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
    """
    checkpoint_dir = Path(checkpoint_dir)

    if torch.distributed.get_rank() == 0:
        if not checkpoint_dir.exists():
            raise CheckpointingException(
                f'Checkpoint destination directory does not exist: {checkpoint_dir}'
            )

        if next(checkpoint_dir.iterdir(), None) is not None:
            raise CheckpointingException(
                f'Checkpoint destination directory ({checkpoint_dir}) is not empty'
            )

    if common_strategy is not None:
        raise NotImplementedError('The only supported common strategy is torch')

    if sharded_strategy is None:
liangjing's avatar
liangjing committed
351
352
353
354
        sharded_strategy = get_default_save_sharded_strategy()
    if not isinstance(sharded_strategy, SaveShardedStrategy):
        assert isinstance(sharded_strategy, tuple), type(sharded_strategy)
        sharded_strategy = get_default_strategy(StrategyAction.SAVE_SHARDED, *sharded_strategy)
liangjing's avatar
v1  
liangjing committed
355

liangjing's avatar
liangjing committed
356
357
358
359
360
    if common_strategy is None:
        common_strategy = get_default_save_common_strategy()
    if not isinstance(common_strategy, SaveCommonStrategy):
        assert isinstance(common_strategy, tuple), type(common_strategy)
        common_strategy = get_default_strategy(StrategyAction.SAVE_COMMON, *common_strategy)
liangjing's avatar
v1  
liangjing committed
361

liangjing's avatar
liangjing committed
362
    sharded_state_dict, state_dict = save_preprocess(sharded_state_dict, validate_access_integrity)
liangjing's avatar
v1  
liangjing committed
363

liangjing's avatar
liangjing committed
364
    common_strategy.save_common(state_dict, checkpoint_dir)
liangjing's avatar
v1  
liangjing committed
365

liangjing's avatar
liangjing committed
366
367
368
369
    if not sharded_strategy.can_handle_sharded_objects:
        validate_sharded_objects_handling(sharded_strategy, common_strategy)
        sharded_objects_state_dict, sharded_state_dict = extract_matching_values(
            sharded_state_dict, lambda v: isinstance(v, ShardedObject)
liangjing's avatar
v1  
liangjing committed
370
        )
liangjing's avatar
liangjing committed
371
        common_strategy.save_sharded_objects(sharded_objects_state_dict, checkpoint_dir)
liangjing's avatar
v1  
liangjing committed
372

liangjing's avatar
liangjing committed
373
374
375
376
377
    def metadata_finalize_fn():
        if torch.distributed.get_rank() == 0:
            save_config(
                CheckpointingConfig(sharded_strategy.backend, sharded_strategy.version),
                checkpoint_dir,
liangjing's avatar
v1  
liangjing committed
378
            )
liangjing's avatar
liangjing committed
379
        torch.distributed.barrier()
liangjing's avatar
v1  
liangjing committed
380

liangjing's avatar
liangjing committed
381
382
383
384
385
386
    if not async_sharded_save:
        sharded_strategy.save(sharded_state_dict, checkpoint_dir)
        metadata_finalize_fn()
        return

    if not isinstance(sharded_strategy, AsyncSaveShardedStrategy):
liangjing's avatar
v1  
liangjing committed
387
        raise CheckpointingException(
liangjing's avatar
liangjing committed
388
            f'Cannot apply async_save to non-async strategy {sharded_strategy}'
liangjing's avatar
v1  
liangjing committed
389
        )
liangjing's avatar
liangjing committed
390
391
392
    async_request = sharded_strategy.async_save(sharded_state_dict, checkpoint_dir)
    async_request.finalize_fns.append(metadata_finalize_fn)
    return async_request
liangjing's avatar
v1  
liangjing committed
393
394


liangjing's avatar
liangjing committed
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
def get_default_save_sharded_strategy(
    backend: str = 'torch_dist', version: int = 1
) -> SaveShardedStrategy:
    """Get default save sharded strategy."""
    return get_default_strategy(StrategyAction.SAVE_SHARDED, backend, version)


def get_default_save_common_strategy(
    backend: str = 'torch', version: int = 1
) -> SaveCommonStrategy:
    """Get default save common strategy."""
    return get_default_strategy(StrategyAction.SAVE_COMMON, backend, version)


def get_default_load_sharded_strategy(checkpoint_dir: str) -> LoadShardedStrategy:
    """Get default load sharded strategy."""
    return verify_checkpoint_and_load_strategy(checkpoint_dir)[0]