Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- checkpoints/step_5200/config.json +22 -0
- checkpoints/step_5200/fabric_state/checkpoint/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt +3 -0
- checkpoints/step_5200/fabric_state/checkpoint/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt +3 -0
- checkpoints/step_5200/fabric_state/checkpoint/bf16_zero_pp_rank_2_mp_rank_00_optim_states.pt +3 -0
- checkpoints/step_5200/fabric_state/checkpoint/bf16_zero_pp_rank_3_mp_rank_00_optim_states.pt +3 -0
- checkpoints/step_5200/fabric_state/checkpoint/mp_rank_00_model_states.pt +3 -0
- checkpoints/step_5200/fabric_state/latest +1 -0
- checkpoints/step_5200/fabric_state/zero_to_fp32.py +760 -0
- checkpoints/step_5200/model.safetensors +3 -0
- checkpoints/step_5200/pico_decoder.py +623 -0
- checkpoints/step_5200/special_tokens_map.json +23 -0
- checkpoints/step_5200/tokenizer.json +0 -0
- checkpoints/step_5200/tokenizer_config.json +248 -0
- checkpoints/step_5300/config.json +22 -0
- checkpoints/step_5300/fabric_state/checkpoint/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt +3 -0
- checkpoints/step_5300/fabric_state/checkpoint/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt +3 -0
- checkpoints/step_5300/fabric_state/checkpoint/bf16_zero_pp_rank_2_mp_rank_00_optim_states.pt +3 -0
- checkpoints/step_5300/fabric_state/checkpoint/bf16_zero_pp_rank_3_mp_rank_00_optim_states.pt +3 -0
- checkpoints/step_5300/fabric_state/checkpoint/mp_rank_00_model_states.pt +3 -0
- checkpoints/step_5300/fabric_state/latest +1 -0
- checkpoints/step_5300/fabric_state/zero_to_fp32.py +760 -0
- checkpoints/step_5300/model.safetensors +3 -0
- checkpoints/step_5300/pico_decoder.py +623 -0
- checkpoints/step_5300/special_tokens_map.json +23 -0
- checkpoints/step_5300/tokenizer.json +0 -0
- checkpoints/step_5300/tokenizer_config.json +248 -0
- checkpoints/step_5400/config.json +22 -0
- checkpoints/step_5400/fabric_state/checkpoint/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt +3 -0
- checkpoints/step_5400/fabric_state/checkpoint/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt +3 -0
- checkpoints/step_5400/fabric_state/checkpoint/bf16_zero_pp_rank_2_mp_rank_00_optim_states.pt +3 -0
- checkpoints/step_5400/fabric_state/checkpoint/bf16_zero_pp_rank_3_mp_rank_00_optim_states.pt +3 -0
- checkpoints/step_5400/fabric_state/checkpoint/mp_rank_00_model_states.pt +3 -0
- checkpoints/step_5400/fabric_state/latest +1 -0
- checkpoints/step_5400/fabric_state/zero_to_fp32.py +760 -0
- checkpoints/step_5400/model.safetensors +3 -0
- checkpoints/step_5400/pico_decoder.py +623 -0
- checkpoints/step_5400/special_tokens_map.json +23 -0
- checkpoints/step_5400/tokenizer.json +0 -0
- checkpoints/step_5400/tokenizer_config.json +248 -0
- checkpoints/step_5500/config.json +22 -0
- checkpoints/step_5500/fabric_state/checkpoint/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt +3 -0
- checkpoints/step_5500/fabric_state/checkpoint/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt +3 -0
- checkpoints/step_5500/fabric_state/checkpoint/bf16_zero_pp_rank_2_mp_rank_00_optim_states.pt +3 -0
- checkpoints/step_5500/fabric_state/checkpoint/bf16_zero_pp_rank_3_mp_rank_00_optim_states.pt +3 -0
- checkpoints/step_5500/fabric_state/checkpoint/mp_rank_00_model_states.pt +3 -0
- checkpoints/step_5500/fabric_state/latest +1 -0
- checkpoints/step_5500/fabric_state/zero_to_fp32.py +760 -0
- checkpoints/step_5500/model.safetensors +3 -0
- checkpoints/step_5500/pico_decoder.py +623 -0
- checkpoints/step_5500/special_tokens_map.json +23 -0
checkpoints/step_5200/config.json
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"activation_hidden_dim": 1536,
|
3 |
+
"architectures": [
|
4 |
+
"PicoDecoderHF"
|
5 |
+
],
|
6 |
+
"attention_n_heads": 12,
|
7 |
+
"attention_n_kv_heads": 4,
|
8 |
+
"auto_map": {
|
9 |
+
"AutoConfig": "pico_decoder.PicoDecoderHFConfig",
|
10 |
+
"AutoModelForCausalLM": "pico_decoder.PicoDecoderHF"
|
11 |
+
},
|
12 |
+
"batch_size": 1024,
|
13 |
+
"d_model": 384,
|
14 |
+
"max_seq_len": 512,
|
15 |
+
"model_type": "pico_decoder",
|
16 |
+
"n_layers": 12,
|
17 |
+
"norm_eps": 1e-06,
|
18 |
+
"position_emb_theta": 10000.0,
|
19 |
+
"torch_dtype": "float32",
|
20 |
+
"transformers_version": "4.48.3",
|
21 |
+
"vocab_size": 50281
|
22 |
+
}
|
checkpoints/step_5200/fabric_state/checkpoint/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3d7360a5e3f18a0e7c383cf716e33d8f55212c8113c5f35de8a925a86a89a35a
|
3 |
+
size 213443205
|
checkpoints/step_5200/fabric_state/checkpoint/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:61356e5e3d0471fe4c0a7c3d1360fb3ae934b1f145f2ebdaed0992088cf4e654
|
3 |
+
size 213447621
|
checkpoints/step_5200/fabric_state/checkpoint/bf16_zero_pp_rank_2_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5f24bf89675997f72b6a0694ffb3142698c52c08a1463e63fe7811891f67e094
|
3 |
+
size 213445701
|
checkpoints/step_5200/fabric_state/checkpoint/bf16_zero_pp_rank_3_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1ccfd0f779945f7d0fe8f1912d22f3bda6189fa07637022440fab07bc768ac7f
|
3 |
+
size 213443589
|
checkpoints/step_5200/fabric_state/checkpoint/mp_rank_00_model_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a6ea5f4570d262ffd9ad1eb5bdd4466e854e90fe62ab152d7f03433d1f26c04f
|
3 |
+
size 142325529
|
checkpoints/step_5200/fabric_state/latest
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
checkpoint
|
checkpoints/step_5200/fabric_state/zero_to_fp32.py
ADDED
@@ -0,0 +1,760 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
|
3 |
+
# Copyright (c) Microsoft Corporation.
|
4 |
+
# SPDX-License-Identifier: Apache-2.0
|
5 |
+
|
6 |
+
# DeepSpeed Team
|
7 |
+
|
8 |
+
# This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets
|
9 |
+
# copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
|
10 |
+
# the future. Once extracted, the weights don't require DeepSpeed and can be used in any
|
11 |
+
# application.
|
12 |
+
#
|
13 |
+
# example:
|
14 |
+
# python zero_to_fp32.py . output_dir/
|
15 |
+
# or
|
16 |
+
# python zero_to_fp32.py . output_dir/ --safe_serialization
|
17 |
+
|
18 |
+
import argparse
|
19 |
+
import torch
|
20 |
+
import glob
|
21 |
+
import math
|
22 |
+
import os
|
23 |
+
import re
|
24 |
+
import gc
|
25 |
+
import json
|
26 |
+
import numpy as np
|
27 |
+
from tqdm import tqdm
|
28 |
+
from collections import OrderedDict
|
29 |
+
from dataclasses import dataclass
|
30 |
+
|
31 |
+
# while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
|
32 |
+
# DeepSpeed data structures it has to be available in the current python environment.
|
33 |
+
from deepspeed.utils import logger
|
34 |
+
from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
|
35 |
+
FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
|
36 |
+
FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
|
37 |
+
|
38 |
+
|
39 |
+
@dataclass
|
40 |
+
class zero_model_state:
|
41 |
+
buffers: dict()
|
42 |
+
param_shapes: dict()
|
43 |
+
shared_params: list
|
44 |
+
ds_version: int
|
45 |
+
frozen_param_shapes: dict()
|
46 |
+
frozen_param_fragments: dict()
|
47 |
+
|
48 |
+
|
49 |
+
debug = 0
|
50 |
+
|
51 |
+
# load to cpu
|
52 |
+
device = torch.device('cpu')
|
53 |
+
|
54 |
+
|
55 |
+
def atoi(text):
|
56 |
+
return int(text) if text.isdigit() else text
|
57 |
+
|
58 |
+
|
59 |
+
def natural_keys(text):
|
60 |
+
'''
|
61 |
+
alist.sort(key=natural_keys) sorts in human order
|
62 |
+
http://nedbatchelder.com/blog/200712/human_sorting.html
|
63 |
+
(See Toothy's implementation in the comments)
|
64 |
+
'''
|
65 |
+
return [atoi(c) for c in re.split(r'(\d+)', text)]
|
66 |
+
|
67 |
+
|
68 |
+
def get_model_state_file(checkpoint_dir, zero_stage):
|
69 |
+
if not os.path.isdir(checkpoint_dir):
|
70 |
+
raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
|
71 |
+
|
72 |
+
# there should be only one file
|
73 |
+
if zero_stage <= 2:
|
74 |
+
file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
|
75 |
+
elif zero_stage == 3:
|
76 |
+
file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
|
77 |
+
|
78 |
+
if not os.path.exists(file):
|
79 |
+
raise FileNotFoundError(f"can't find model states file at '{file}'")
|
80 |
+
|
81 |
+
return file
|
82 |
+
|
83 |
+
|
84 |
+
def get_checkpoint_files(checkpoint_dir, glob_pattern):
|
85 |
+
# XXX: need to test that this simple glob rule works for multi-node setup too
|
86 |
+
ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
|
87 |
+
|
88 |
+
if len(ckpt_files) == 0:
|
89 |
+
raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
|
90 |
+
|
91 |
+
return ckpt_files
|
92 |
+
|
93 |
+
|
94 |
+
def get_optim_files(checkpoint_dir):
|
95 |
+
return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
|
96 |
+
|
97 |
+
|
98 |
+
def get_model_state_files(checkpoint_dir):
|
99 |
+
return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
|
100 |
+
|
101 |
+
|
102 |
+
def parse_model_states(files):
|
103 |
+
zero_model_states = []
|
104 |
+
for file in files:
|
105 |
+
state_dict = torch.load(file, map_location=device, weights_only=False)
|
106 |
+
|
107 |
+
if BUFFER_NAMES not in state_dict:
|
108 |
+
raise ValueError(f"{file} is not a model state checkpoint")
|
109 |
+
buffer_names = state_dict[BUFFER_NAMES]
|
110 |
+
if debug:
|
111 |
+
print("Found buffers:", buffer_names)
|
112 |
+
|
113 |
+
# recover just the buffers while restoring them to fp32 if they were saved in fp16
|
114 |
+
buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
|
115 |
+
param_shapes = state_dict[PARAM_SHAPES]
|
116 |
+
|
117 |
+
# collect parameters that are included in param_shapes
|
118 |
+
param_names = []
|
119 |
+
for s in param_shapes:
|
120 |
+
for name in s.keys():
|
121 |
+
param_names.append(name)
|
122 |
+
|
123 |
+
# update with frozen parameters
|
124 |
+
frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
|
125 |
+
if frozen_param_shapes is not None:
|
126 |
+
if debug:
|
127 |
+
print(f"Found frozen_param_shapes: {frozen_param_shapes}")
|
128 |
+
param_names += list(frozen_param_shapes.keys())
|
129 |
+
|
130 |
+
# handle shared params
|
131 |
+
shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
|
132 |
+
|
133 |
+
ds_version = state_dict.get(DS_VERSION, None)
|
134 |
+
|
135 |
+
frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
|
136 |
+
|
137 |
+
z_model_state = zero_model_state(buffers=buffers,
|
138 |
+
param_shapes=param_shapes,
|
139 |
+
shared_params=shared_params,
|
140 |
+
ds_version=ds_version,
|
141 |
+
frozen_param_shapes=frozen_param_shapes,
|
142 |
+
frozen_param_fragments=frozen_param_fragments)
|
143 |
+
zero_model_states.append(z_model_state)
|
144 |
+
|
145 |
+
return zero_model_states
|
146 |
+
|
147 |
+
|
148 |
+
def parse_optim_states(files, ds_checkpoint_dir):
|
149 |
+
total_files = len(files)
|
150 |
+
state_dicts = []
|
151 |
+
for f in tqdm(files, desc='Loading checkpoint shards'):
|
152 |
+
state_dict = torch.load(f, map_location=device, mmap=True, weights_only=False)
|
153 |
+
# immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights
|
154 |
+
# and also handle the case where it was already removed by another helper script
|
155 |
+
state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
|
156 |
+
state_dicts.append(state_dict)
|
157 |
+
|
158 |
+
if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
|
159 |
+
raise ValueError(f"{files[0]} is not a zero checkpoint")
|
160 |
+
zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
|
161 |
+
world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
|
162 |
+
|
163 |
+
# For ZeRO-2 each param group can have different partition_count as data parallelism for expert
|
164 |
+
# parameters can be different from data parallelism for non-expert parameters. So we can just
|
165 |
+
# use the max of the partition_count to get the dp world_size.
|
166 |
+
|
167 |
+
if type(world_size) is list:
|
168 |
+
world_size = max(world_size)
|
169 |
+
|
170 |
+
if world_size != total_files:
|
171 |
+
raise ValueError(
|
172 |
+
f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
|
173 |
+
"Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
|
174 |
+
)
|
175 |
+
|
176 |
+
# the groups are named differently in each stage
|
177 |
+
if zero_stage <= 2:
|
178 |
+
fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
|
179 |
+
elif zero_stage == 3:
|
180 |
+
fp32_groups_key = FP32_FLAT_GROUPS
|
181 |
+
else:
|
182 |
+
raise ValueError(f"unknown zero stage {zero_stage}")
|
183 |
+
|
184 |
+
fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
|
185 |
+
return zero_stage, world_size, fp32_flat_groups
|
186 |
+
|
187 |
+
|
188 |
+
def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters):
|
189 |
+
"""
|
190 |
+
Returns fp32 state_dict reconstructed from ds checkpoint
|
191 |
+
|
192 |
+
Args:
|
193 |
+
- ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
|
194 |
+
|
195 |
+
"""
|
196 |
+
print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
|
197 |
+
|
198 |
+
optim_files = get_optim_files(ds_checkpoint_dir)
|
199 |
+
zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
|
200 |
+
print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
|
201 |
+
|
202 |
+
model_files = get_model_state_files(ds_checkpoint_dir)
|
203 |
+
|
204 |
+
zero_model_states = parse_model_states(model_files)
|
205 |
+
print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
|
206 |
+
|
207 |
+
if zero_stage <= 2:
|
208 |
+
return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
209 |
+
exclude_frozen_parameters)
|
210 |
+
elif zero_stage == 3:
|
211 |
+
return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
212 |
+
exclude_frozen_parameters)
|
213 |
+
|
214 |
+
|
215 |
+
def _zero2_merge_frozen_params(state_dict, zero_model_states):
|
216 |
+
if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
|
217 |
+
return
|
218 |
+
|
219 |
+
frozen_param_shapes = zero_model_states[0].frozen_param_shapes
|
220 |
+
frozen_param_fragments = zero_model_states[0].frozen_param_fragments
|
221 |
+
|
222 |
+
if debug:
|
223 |
+
num_elem = sum(s.numel() for s in frozen_param_shapes.values())
|
224 |
+
print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
|
225 |
+
|
226 |
+
wanted_params = len(frozen_param_shapes)
|
227 |
+
wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
|
228 |
+
avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
|
229 |
+
print(f'Frozen params: Have {avail_numel} numels to process.')
|
230 |
+
print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
|
231 |
+
|
232 |
+
total_params = 0
|
233 |
+
total_numel = 0
|
234 |
+
for name, shape in frozen_param_shapes.items():
|
235 |
+
total_params += 1
|
236 |
+
unpartitioned_numel = shape.numel()
|
237 |
+
total_numel += unpartitioned_numel
|
238 |
+
|
239 |
+
state_dict[name] = frozen_param_fragments[name]
|
240 |
+
|
241 |
+
if debug:
|
242 |
+
print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
|
243 |
+
|
244 |
+
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
|
245 |
+
|
246 |
+
|
247 |
+
def _has_callable(obj, fn):
|
248 |
+
attr = getattr(obj, fn, None)
|
249 |
+
return callable(attr)
|
250 |
+
|
251 |
+
|
252 |
+
def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
|
253 |
+
param_shapes = zero_model_states[0].param_shapes
|
254 |
+
|
255 |
+
# Reconstruction protocol:
|
256 |
+
#
|
257 |
+
# XXX: document this
|
258 |
+
|
259 |
+
if debug:
|
260 |
+
for i in range(world_size):
|
261 |
+
for j in range(len(fp32_flat_groups[0])):
|
262 |
+
print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
|
263 |
+
|
264 |
+
# XXX: memory usage doubles here (zero2)
|
265 |
+
num_param_groups = len(fp32_flat_groups[0])
|
266 |
+
merged_single_partition_of_fp32_groups = []
|
267 |
+
for i in range(num_param_groups):
|
268 |
+
merged_partitions = [sd[i] for sd in fp32_flat_groups]
|
269 |
+
full_single_fp32_vector = torch.cat(merged_partitions, 0)
|
270 |
+
merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
|
271 |
+
avail_numel = sum(
|
272 |
+
[full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
|
273 |
+
|
274 |
+
if debug:
|
275 |
+
wanted_params = sum([len(shapes) for shapes in param_shapes])
|
276 |
+
wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
|
277 |
+
# not asserting if there is a mismatch due to possible padding
|
278 |
+
print(f"Have {avail_numel} numels to process.")
|
279 |
+
print(f"Need {wanted_numel} numels in {wanted_params} params.")
|
280 |
+
|
281 |
+
# params
|
282 |
+
# XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
|
283 |
+
# out-of-core computing solution
|
284 |
+
total_numel = 0
|
285 |
+
total_params = 0
|
286 |
+
for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
|
287 |
+
offset = 0
|
288 |
+
avail_numel = full_single_fp32_vector.numel()
|
289 |
+
for name, shape in shapes.items():
|
290 |
+
|
291 |
+
unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape)
|
292 |
+
total_numel += unpartitioned_numel
|
293 |
+
total_params += 1
|
294 |
+
|
295 |
+
if debug:
|
296 |
+
print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
|
297 |
+
state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
|
298 |
+
offset += unpartitioned_numel
|
299 |
+
|
300 |
+
# Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
|
301 |
+
# avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
|
302 |
+
# paddings performed in the code it's almost impossible to predict the exact numbers w/o the
|
303 |
+
# live optimizer object, so we are checking that the numbers are within the right range
|
304 |
+
align_to = 2 * world_size
|
305 |
+
|
306 |
+
def zero2_align(x):
|
307 |
+
return align_to * math.ceil(x / align_to)
|
308 |
+
|
309 |
+
if debug:
|
310 |
+
print(f"original offset={offset}, avail_numel={avail_numel}")
|
311 |
+
|
312 |
+
offset = zero2_align(offset)
|
313 |
+
avail_numel = zero2_align(avail_numel)
|
314 |
+
|
315 |
+
if debug:
|
316 |
+
print(f"aligned offset={offset}, avail_numel={avail_numel}")
|
317 |
+
|
318 |
+
# Sanity check
|
319 |
+
if offset != avail_numel:
|
320 |
+
raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
|
321 |
+
|
322 |
+
print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
|
323 |
+
|
324 |
+
|
325 |
+
def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
326 |
+
exclude_frozen_parameters):
|
327 |
+
state_dict = OrderedDict()
|
328 |
+
|
329 |
+
# buffers
|
330 |
+
buffers = zero_model_states[0].buffers
|
331 |
+
state_dict.update(buffers)
|
332 |
+
if debug:
|
333 |
+
print(f"added {len(buffers)} buffers")
|
334 |
+
|
335 |
+
if not exclude_frozen_parameters:
|
336 |
+
_zero2_merge_frozen_params(state_dict, zero_model_states)
|
337 |
+
|
338 |
+
_zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
|
339 |
+
|
340 |
+
# recover shared parameters
|
341 |
+
for pair in zero_model_states[0].shared_params:
|
342 |
+
if pair[1] in state_dict:
|
343 |
+
state_dict[pair[0]] = state_dict[pair[1]]
|
344 |
+
|
345 |
+
return state_dict
|
346 |
+
|
347 |
+
|
348 |
+
def zero3_partitioned_param_info(unpartitioned_numel, world_size):
|
349 |
+
remainder = unpartitioned_numel % world_size
|
350 |
+
padding_numel = (world_size - remainder) if remainder else 0
|
351 |
+
partitioned_numel = math.ceil(unpartitioned_numel / world_size)
|
352 |
+
return partitioned_numel, padding_numel
|
353 |
+
|
354 |
+
|
355 |
+
def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
|
356 |
+
if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
|
357 |
+
return
|
358 |
+
|
359 |
+
if debug:
|
360 |
+
for i in range(world_size):
|
361 |
+
num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
|
362 |
+
print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
|
363 |
+
|
364 |
+
frozen_param_shapes = zero_model_states[0].frozen_param_shapes
|
365 |
+
wanted_params = len(frozen_param_shapes)
|
366 |
+
wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
|
367 |
+
avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
|
368 |
+
print(f'Frozen params: Have {avail_numel} numels to process.')
|
369 |
+
print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
|
370 |
+
|
371 |
+
total_params = 0
|
372 |
+
total_numel = 0
|
373 |
+
for name, shape in zero_model_states[0].frozen_param_shapes.items():
|
374 |
+
total_params += 1
|
375 |
+
unpartitioned_numel = shape.numel()
|
376 |
+
total_numel += unpartitioned_numel
|
377 |
+
|
378 |
+
param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
|
379 |
+
state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
|
380 |
+
|
381 |
+
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
|
382 |
+
|
383 |
+
if debug:
|
384 |
+
print(
|
385 |
+
f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
|
386 |
+
)
|
387 |
+
|
388 |
+
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
|
389 |
+
|
390 |
+
|
391 |
+
class GatheredTensor:
|
392 |
+
"""
|
393 |
+
A pseudo tensor that collects partitioned weights.
|
394 |
+
It is more memory efficient when there are multiple groups.
|
395 |
+
"""
|
396 |
+
|
397 |
+
def __init__(self, flat_groups, flat_groups_offset, offset, partitioned_numel, shape):
|
398 |
+
self.flat_groups = flat_groups
|
399 |
+
self.flat_groups_offset = flat_groups_offset
|
400 |
+
self.offset = offset
|
401 |
+
self.partitioned_numel = partitioned_numel
|
402 |
+
self.shape = shape
|
403 |
+
self.dtype = self.flat_groups[0][0].dtype
|
404 |
+
|
405 |
+
def contiguous(self):
|
406 |
+
"""
|
407 |
+
Merge partitioned weights from flat_groups into a single tensor.
|
408 |
+
"""
|
409 |
+
end_idx = self.offset + self.partitioned_numel
|
410 |
+
world_size = len(self.flat_groups)
|
411 |
+
pad_flat_param_chunks = []
|
412 |
+
|
413 |
+
for rank_i in range(world_size):
|
414 |
+
# for each rank, we need to collect weights from related group/groups
|
415 |
+
flat_groups_at_rank_i = self.flat_groups[rank_i]
|
416 |
+
start_group_id = None
|
417 |
+
end_group_id = None
|
418 |
+
for group_id in range(len(self.flat_groups_offset)):
|
419 |
+
if self.flat_groups_offset[group_id] <= self.offset < self.flat_groups_offset[group_id + 1]:
|
420 |
+
start_group_id = group_id
|
421 |
+
if self.flat_groups_offset[group_id] < end_idx <= self.flat_groups_offset[group_id + 1]:
|
422 |
+
end_group_id = group_id
|
423 |
+
break
|
424 |
+
# collect weights from related group/groups
|
425 |
+
for group_id in range(start_group_id, end_group_id + 1):
|
426 |
+
flat_tensor = flat_groups_at_rank_i[group_id]
|
427 |
+
start_offset = self.offset - self.flat_groups_offset[group_id]
|
428 |
+
end_offset = min(end_idx, self.flat_groups_offset[group_id + 1]) - self.flat_groups_offset[group_id]
|
429 |
+
pad_flat_param_chunks.append(flat_tensor[start_offset:end_offset])
|
430 |
+
|
431 |
+
# collect weights from all ranks
|
432 |
+
pad_flat_param = torch.cat(pad_flat_param_chunks, dim=0)
|
433 |
+
param = pad_flat_param[:self.shape.numel()].view(self.shape).contiguous()
|
434 |
+
return param
|
435 |
+
|
436 |
+
|
437 |
+
def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
|
438 |
+
param_shapes = zero_model_states[0].param_shapes
|
439 |
+
avail_numel = sum([flat_group.numel() for flat_group in fp32_flat_groups[0]]) * world_size
|
440 |
+
|
441 |
+
# Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
|
442 |
+
# param, re-consolidating each param, while dealing with padding if any
|
443 |
+
|
444 |
+
# merge list of dicts, preserving order
|
445 |
+
param_shapes = {k: v for d in param_shapes for k, v in d.items()}
|
446 |
+
|
447 |
+
if debug:
|
448 |
+
for i in range(world_size):
|
449 |
+
print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
|
450 |
+
|
451 |
+
wanted_params = len(param_shapes)
|
452 |
+
wanted_numel = sum(shape.numel() for shape in param_shapes.values())
|
453 |
+
# not asserting if there is a mismatch due to possible padding
|
454 |
+
avail_numel = fp32_flat_groups[0].numel() * world_size
|
455 |
+
print(f"Trainable params: Have {avail_numel} numels to process.")
|
456 |
+
print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
|
457 |
+
|
458 |
+
# params
|
459 |
+
# XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
|
460 |
+
# out-of-core computing solution
|
461 |
+
offset = 0
|
462 |
+
total_numel = 0
|
463 |
+
total_params = 0
|
464 |
+
flat_groups_offset = [0] + list(np.cumsum([flat_tensor.numel() for flat_tensor in fp32_flat_groups[0]]))
|
465 |
+
for name, shape in tqdm(param_shapes.items(), desc='Gathering sharded weights'):
|
466 |
+
unpartitioned_numel = shape.numel()
|
467 |
+
total_numel += unpartitioned_numel
|
468 |
+
total_params += 1
|
469 |
+
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
|
470 |
+
|
471 |
+
if debug:
|
472 |
+
print(
|
473 |
+
f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
|
474 |
+
)
|
475 |
+
|
476 |
+
# memory efficient tensor
|
477 |
+
tensor = GatheredTensor(fp32_flat_groups, flat_groups_offset, offset, partitioned_numel, shape)
|
478 |
+
state_dict[name] = tensor
|
479 |
+
offset += partitioned_numel
|
480 |
+
|
481 |
+
offset *= world_size
|
482 |
+
|
483 |
+
# Sanity check
|
484 |
+
if offset != avail_numel:
|
485 |
+
raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
|
486 |
+
|
487 |
+
print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
|
488 |
+
|
489 |
+
|
490 |
+
def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
491 |
+
exclude_frozen_parameters):
|
492 |
+
state_dict = OrderedDict()
|
493 |
+
|
494 |
+
# buffers
|
495 |
+
buffers = zero_model_states[0].buffers
|
496 |
+
state_dict.update(buffers)
|
497 |
+
if debug:
|
498 |
+
print(f"added {len(buffers)} buffers")
|
499 |
+
|
500 |
+
if not exclude_frozen_parameters:
|
501 |
+
_zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
|
502 |
+
|
503 |
+
_zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
|
504 |
+
|
505 |
+
# recover shared parameters
|
506 |
+
for pair in zero_model_states[0].shared_params:
|
507 |
+
if pair[1] in state_dict:
|
508 |
+
state_dict[pair[0]] = state_dict[pair[1]]
|
509 |
+
|
510 |
+
return state_dict
|
511 |
+
|
512 |
+
|
513 |
+
def to_torch_tensor(state_dict, return_empty_tensor=False):
|
514 |
+
"""
|
515 |
+
Convert state_dict of GatheredTensor to torch tensor
|
516 |
+
"""
|
517 |
+
torch_state_dict = {}
|
518 |
+
converted_tensors = {}
|
519 |
+
for name, tensor in state_dict.items():
|
520 |
+
tensor_id = id(tensor)
|
521 |
+
if tensor_id in converted_tensors: # shared tensors
|
522 |
+
shared_tensor = torch_state_dict[converted_tensors[tensor_id]]
|
523 |
+
torch_state_dict[name] = shared_tensor
|
524 |
+
else:
|
525 |
+
converted_tensors[tensor_id] = name
|
526 |
+
if return_empty_tensor:
|
527 |
+
torch_state_dict[name] = torch.empty(tensor.shape, dtype=tensor.dtype)
|
528 |
+
else:
|
529 |
+
torch_state_dict[name] = tensor.contiguous()
|
530 |
+
return torch_state_dict
|
531 |
+
|
532 |
+
|
533 |
+
def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir,
|
534 |
+
tag=None,
|
535 |
+
exclude_frozen_parameters=False,
|
536 |
+
lazy_mode=False):
|
537 |
+
"""
|
538 |
+
Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
|
539 |
+
``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
|
540 |
+
via a model hub.
|
541 |
+
|
542 |
+
Args:
|
543 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder
|
544 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in 'latest' file. e.g., ``global_step14``
|
545 |
+
- ``exclude_frozen_parameters``: exclude frozen parameters
|
546 |
+
- ``lazy_mode``: get state_dict in lazy mode. It returns a dict of pesduo tensor instead of torch tensor, which is more memory efficient.
|
547 |
+
Convert the pesduo tensor to torch tensor by ``.contiguous()``
|
548 |
+
|
549 |
+
Returns:
|
550 |
+
- pytorch ``state_dict``
|
551 |
+
|
552 |
+
A typical usage might be ::
|
553 |
+
|
554 |
+
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
|
555 |
+
# do the training and checkpoint saving
|
556 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
|
557 |
+
model = model.cpu() # move to cpu
|
558 |
+
model.load_state_dict(state_dict)
|
559 |
+
# submit to model hub or save the model to share with others
|
560 |
+
|
561 |
+
In this example the ``model`` will no longer be usable in the deepspeed context of the same
|
562 |
+
application. i.e. you will need to re-initialize the deepspeed engine, since
|
563 |
+
``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
|
564 |
+
|
565 |
+
If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
|
566 |
+
|
567 |
+
Note: the above usage may not work if your application doesn't have sufficient free CPU memory.
|
568 |
+
You may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
|
569 |
+
the checkpoint. Or you can load state_dict in lazy mode ::
|
570 |
+
|
571 |
+
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
|
572 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, lazy_mode=True) # not on cpu
|
573 |
+
for name, lazy_tensor in state_dict.item():
|
574 |
+
tensor = lazy_tensor.contiguous() # to cpu
|
575 |
+
print(name, tensor)
|
576 |
+
# del tensor to release memory if it no longer in use
|
577 |
+
"""
|
578 |
+
if tag is None:
|
579 |
+
latest_path = os.path.join(checkpoint_dir, 'latest')
|
580 |
+
if os.path.isfile(latest_path):
|
581 |
+
with open(latest_path, 'r') as fd:
|
582 |
+
tag = fd.read().strip()
|
583 |
+
else:
|
584 |
+
raise ValueError(f"Unable to find 'latest' file at {latest_path}")
|
585 |
+
|
586 |
+
ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
|
587 |
+
|
588 |
+
if not os.path.isdir(ds_checkpoint_dir):
|
589 |
+
raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
|
590 |
+
|
591 |
+
state_dict = _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
|
592 |
+
if lazy_mode:
|
593 |
+
return state_dict
|
594 |
+
else:
|
595 |
+
return to_torch_tensor(state_dict)
|
596 |
+
|
597 |
+
|
598 |
+
def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir,
|
599 |
+
output_dir,
|
600 |
+
max_shard_size="5GB",
|
601 |
+
safe_serialization=False,
|
602 |
+
tag=None,
|
603 |
+
exclude_frozen_parameters=False):
|
604 |
+
"""
|
605 |
+
Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
|
606 |
+
loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
|
607 |
+
|
608 |
+
Args:
|
609 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
|
610 |
+
- ``output_dir``: directory to the pytorch fp32 state_dict output files
|
611 |
+
- ``max_shard_size``: the maximum size for a checkpoint before being sharded, default value is 5GB
|
612 |
+
- ``safe_serialization``: whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
|
613 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
|
614 |
+
- ``exclude_frozen_parameters``: exclude frozen parameters
|
615 |
+
"""
|
616 |
+
|
617 |
+
# Dependency pre-check
|
618 |
+
if safe_serialization:
|
619 |
+
try:
|
620 |
+
from safetensors.torch import save_file
|
621 |
+
except ImportError:
|
622 |
+
print('If you want to use `safe_serialization`, please `pip install safetensors`')
|
623 |
+
raise
|
624 |
+
if max_shard_size is not None:
|
625 |
+
try:
|
626 |
+
from huggingface_hub import split_torch_state_dict_into_shards
|
627 |
+
except ImportError:
|
628 |
+
print('If you want to use `max_shard_size`, please `pip install huggingface_hub`')
|
629 |
+
raise
|
630 |
+
|
631 |
+
# Convert zero checkpoint to state_dict
|
632 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir,
|
633 |
+
tag,
|
634 |
+
exclude_frozen_parameters,
|
635 |
+
lazy_mode=True)
|
636 |
+
|
637 |
+
# Shard the model if it is too big.
|
638 |
+
weights_name = "model.safetensors" if safe_serialization else "pytorch_model.bin"
|
639 |
+
if max_shard_size is not None:
|
640 |
+
filename_pattern = weights_name.replace(".bin", "{suffix}.bin").replace(".safetensors", "{suffix}.safetensors")
|
641 |
+
# an memory-efficient approach for sharding
|
642 |
+
empty_state_dict = to_torch_tensor(state_dict, return_empty_tensor=True)
|
643 |
+
state_dict_split = split_torch_state_dict_into_shards(empty_state_dict,
|
644 |
+
filename_pattern=filename_pattern,
|
645 |
+
max_shard_size=max_shard_size)
|
646 |
+
else:
|
647 |
+
from collections import namedtuple
|
648 |
+
StateDictSplit = namedtuple("StateDictSplit", ["is_sharded", "filename_to_tensors"])
|
649 |
+
state_dict_split = StateDictSplit(is_sharded=False,
|
650 |
+
filename_to_tensors={weights_name: list(state_dict.keys())})
|
651 |
+
|
652 |
+
# Save the model by shard
|
653 |
+
os.makedirs(output_dir, exist_ok=True)
|
654 |
+
filename_to_tensors = state_dict_split.filename_to_tensors.items()
|
655 |
+
for shard_file, tensors in tqdm(filename_to_tensors, desc="Saving checkpoint shards"):
|
656 |
+
shard_state_dict = {tensor_name: state_dict[tensor_name] for tensor_name in tensors}
|
657 |
+
shard_state_dict = to_torch_tensor(shard_state_dict)
|
658 |
+
output_path = os.path.join(output_dir, shard_file)
|
659 |
+
if safe_serialization:
|
660 |
+
save_file(shard_state_dict, output_path, metadata={"format": "pt"})
|
661 |
+
else:
|
662 |
+
torch.save(shard_state_dict, output_path)
|
663 |
+
# release the memory of current shard
|
664 |
+
for tensor_name in list(shard_state_dict.keys()):
|
665 |
+
del state_dict[tensor_name]
|
666 |
+
del shard_state_dict[tensor_name]
|
667 |
+
del shard_state_dict
|
668 |
+
gc.collect()
|
669 |
+
|
670 |
+
# Save index if sharded
|
671 |
+
if state_dict_split.is_sharded:
|
672 |
+
index = {
|
673 |
+
"metadata": state_dict_split.metadata,
|
674 |
+
"weight_map": state_dict_split.tensor_to_filename,
|
675 |
+
}
|
676 |
+
save_index_file = "model.safetensors.index.json" if safe_serialization else "pytorch_model.bin.index.json"
|
677 |
+
save_index_file = os.path.join(output_dir, save_index_file)
|
678 |
+
with open(save_index_file, "w", encoding="utf-8") as f:
|
679 |
+
content = json.dumps(index, indent=2, sort_keys=True) + "\n"
|
680 |
+
f.write(content)
|
681 |
+
|
682 |
+
|
683 |
+
def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
|
684 |
+
"""
|
685 |
+
1. Put the provided model to cpu
|
686 |
+
2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
|
687 |
+
3. Load it into the provided model
|
688 |
+
|
689 |
+
Args:
|
690 |
+
- ``model``: the model object to update
|
691 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
|
692 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
|
693 |
+
|
694 |
+
Returns:
|
695 |
+
- ``model`: modified model
|
696 |
+
|
697 |
+
Make sure you have plenty of CPU memory available before you call this function. If you don't
|
698 |
+
have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
|
699 |
+
conveniently placed for you in the checkpoint folder.
|
700 |
+
|
701 |
+
A typical usage might be ::
|
702 |
+
|
703 |
+
from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
|
704 |
+
model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
|
705 |
+
# submit to model hub or save the model to share with others
|
706 |
+
|
707 |
+
Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
|
708 |
+
of the same application. i.e. you will need to re-initialize the deepspeed engine, since
|
709 |
+
``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
|
710 |
+
|
711 |
+
"""
|
712 |
+
logger.info(f"Extracting fp32 weights")
|
713 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
|
714 |
+
|
715 |
+
logger.info(f"Overwriting model with fp32 weights")
|
716 |
+
model = model.cpu()
|
717 |
+
model.load_state_dict(state_dict, strict=False)
|
718 |
+
|
719 |
+
return model
|
720 |
+
|
721 |
+
|
722 |
+
if __name__ == "__main__":
|
723 |
+
parser = argparse.ArgumentParser()
|
724 |
+
parser.add_argument("checkpoint_dir",
|
725 |
+
type=str,
|
726 |
+
help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
|
727 |
+
parser.add_argument("output_dir",
|
728 |
+
type=str,
|
729 |
+
help="directory to the pytorch fp32 state_dict output files"
|
730 |
+
"(e.g. path/checkpoint-12-output/)")
|
731 |
+
parser.add_argument(
|
732 |
+
"--max_shard_size",
|
733 |
+
type=str,
|
734 |
+
default="5GB",
|
735 |
+
help="The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size"
|
736 |
+
"lower than this size. If expressed as a string, needs to be digits followed by a unit (like `5MB`"
|
737 |
+
"We default it to 5GB in order for models to be able to run easily on free-tier google colab instances"
|
738 |
+
"without CPU OOM issues.")
|
739 |
+
parser.add_argument(
|
740 |
+
"--safe_serialization",
|
741 |
+
default=False,
|
742 |
+
action='store_true',
|
743 |
+
help="Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).")
|
744 |
+
parser.add_argument("-t",
|
745 |
+
"--tag",
|
746 |
+
type=str,
|
747 |
+
default=None,
|
748 |
+
help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
|
749 |
+
parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters")
|
750 |
+
parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
|
751 |
+
args = parser.parse_args()
|
752 |
+
|
753 |
+
debug = args.debug
|
754 |
+
|
755 |
+
convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir,
|
756 |
+
args.output_dir,
|
757 |
+
max_shard_size=args.max_shard_size,
|
758 |
+
safe_serialization=args.safe_serialization,
|
759 |
+
tag=args.tag,
|
760 |
+
exclude_frozen_parameters=args.exclude_frozen_parameters)
|
checkpoints/step_5200/model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:bf333c8a1518ae90ee1b99f66d7d2f77597186661b7796b82552c5c3fed0efea
|
3 |
+
size 258323520
|
checkpoints/step_5200/pico_decoder.py
ADDED
@@ -0,0 +1,623 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Pico Decoder: A Lightweight Causal Transformer Language Model
|
3 |
+
|
4 |
+
Pico Decoder uses a simple LLAMA-style transformer architecture, written for clarity and educational purposes.
|
5 |
+
|
6 |
+
Everything is written with a modular design for easy modification and experimentation.
|
7 |
+
|
8 |
+
Key features:
|
9 |
+
- RMSNorm for layer normalization
|
10 |
+
- Rotary Positional Embeddings (RoPE)
|
11 |
+
- Multi-head attention with KV-cache support
|
12 |
+
- SwiGLU activation function
|
13 |
+
- Residual connections throughout
|
14 |
+
|
15 |
+
- KV-cache for faster autoregressive generation
|
16 |
+
|
17 |
+
References:
|
18 |
+
- RoPE: https://arxiv.org/abs/2104.09864
|
19 |
+
- SwiGLU: https://arxiv.org/abs/2002.05202
|
20 |
+
- LLAMA: https://arxiv.org/abs/2302.13971
|
21 |
+
|
22 |
+
Adapted from:
|
23 |
+
- OLMO: https://github.com/allenai/OLMo
|
24 |
+
- LLAMA: https://github.com/meta/llama
|
25 |
+
"""
|
26 |
+
|
27 |
+
from dataclasses import asdict
|
28 |
+
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union
|
29 |
+
|
30 |
+
import torch
|
31 |
+
import torch.nn as nn
|
32 |
+
import torch.nn.functional as F
|
33 |
+
from torch.nn.attention import SDPBackend, sdpa_kernel
|
34 |
+
from transformers import PretrainedConfig, PreTrainedModel
|
35 |
+
from transformers.modeling_outputs import CausalLMOutput, CausalLMOutputWithPast
|
36 |
+
|
37 |
+
try:
|
38 |
+
if TYPE_CHECKING:
|
39 |
+
# We need to do this to avoid importing these when creating the HF-compatible models
|
40 |
+
from src.config import ModelConfig
|
41 |
+
except ImportError:
|
42 |
+
pass
|
43 |
+
|
44 |
+
########################################################
|
45 |
+
#
|
46 |
+
# Layer Normalization
|
47 |
+
#
|
48 |
+
########################################################
|
49 |
+
|
50 |
+
|
51 |
+
class RMSNorm(torch.nn.Module):
|
52 |
+
"""Root Mean Square Layer Normalization.
|
53 |
+
|
54 |
+
A variant of Layer Normalization that uses RMS statistics instead of mean/variance,
|
55 |
+
resulting in improved stability and performance.
|
56 |
+
|
57 |
+
Args:
|
58 |
+
config (Union[ModelConfig, PicoHFConfig]): Configuration object containing normalization parameters
|
59 |
+
- config.norm_eps: Small constant for numerical stability
|
60 |
+
- config.d_model: Model dimension for the weight parameter
|
61 |
+
|
62 |
+
References:
|
63 |
+
https://arxiv.org/abs/1910.07467
|
64 |
+
"""
|
65 |
+
|
66 |
+
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]):
|
67 |
+
super().__init__()
|
68 |
+
self.eps = config.norm_eps
|
69 |
+
self.weight = nn.Parameter(torch.ones(config.d_model))
|
70 |
+
|
71 |
+
def _norm(self, x: torch.Tensor) -> torch.Tensor:
|
72 |
+
"""
|
73 |
+
Normalizes the input tensor by its RMS value.
|
74 |
+
"""
|
75 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
76 |
+
|
77 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
78 |
+
"""
|
79 |
+
Applies RMS normalization to the input tensor and scales it by the weight parameter.
|
80 |
+
"""
|
81 |
+
output = self._norm(x.float()).type_as(x)
|
82 |
+
return output * self.weight
|
83 |
+
|
84 |
+
|
85 |
+
########################################################
|
86 |
+
#
|
87 |
+
# Positional Embedding
|
88 |
+
#
|
89 |
+
########################################################
|
90 |
+
|
91 |
+
|
92 |
+
class RoPE(nn.Module):
|
93 |
+
"""Rotary Positional Embeddings (RoPE).
|
94 |
+
|
95 |
+
Implements position-dependent rotation of keys and queries in attention mechanism,
|
96 |
+
allowing better modeling of relative positions in sequences. Uses complex number
|
97 |
+
operations for efficient rotation.
|
98 |
+
|
99 |
+
Args:
|
100 |
+
config (Union[ModelConfig, PicoHFConfig]): Model configuration containing:
|
101 |
+
- config.position_emb_theta: Base for frequency computation
|
102 |
+
- config.d_model: Model dimension
|
103 |
+
- config.attention_n_heads: Number of attention heads
|
104 |
+
- config.max_seq_len: Maximum sequence length
|
105 |
+
|
106 |
+
References:
|
107 |
+
https://arxiv.org/abs/2104.09864
|
108 |
+
"""
|
109 |
+
|
110 |
+
_freqs_cis_tensor: torch.Tensor | None = None
|
111 |
+
|
112 |
+
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]):
|
113 |
+
super().__init__()
|
114 |
+
|
115 |
+
self.theta = config.position_emb_theta
|
116 |
+
self.dim = config.d_model // config.attention_n_heads
|
117 |
+
|
118 |
+
max_seq_len = config.max_seq_len
|
119 |
+
|
120 |
+
# only gets set once, and then reused for all RoPE instances
|
121 |
+
if RoPE._freqs_cis_tensor is None:
|
122 |
+
RoPE._freqs_cis_tensor = self._setup_freqs_cis(
|
123 |
+
max_seq_len, self.theta, self.dim
|
124 |
+
)
|
125 |
+
|
126 |
+
# register _freqs_cis buffer
|
127 |
+
# can be easily recomputed so persistent=False
|
128 |
+
self.register_buffer("_freqs_cis", self._freqs_cis_tensor, persistent=False)
|
129 |
+
|
130 |
+
@classmethod
|
131 |
+
def _setup_freqs_cis(cls, seq_len: int, theta: float, dim: int) -> torch.Tensor:
|
132 |
+
"""Setup Frequency Tensor for RoPE Embeddings
|
133 |
+
|
134 |
+
Initializes the complex frequency tensor that is used to compute the RoPE embeddings.
|
135 |
+
|
136 |
+
Note other implementations will use cos and sin directly, but using the complex
|
137 |
+
number representation is (probably?) more efficient:
|
138 |
+
|
139 |
+
e^(theta * i * t) = cos(theta * t) + i * sin(theta * t) [Euler's formula]
|
140 |
+
"""
|
141 |
+
_freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
|
142 |
+
positions = torch.arange(seq_len)
|
143 |
+
freqs = torch.outer(positions, _freqs)
|
144 |
+
return torch.polar(torch.ones_like(freqs), freqs) # complex64
|
145 |
+
|
146 |
+
def get_freqs_cis(
|
147 |
+
self, input_shape: torch.Size, start_pos: int, end_pos: int
|
148 |
+
) -> torch.Tensor:
|
149 |
+
"""Reshape Frequency Tensor for RoPE Embeddings
|
150 |
+
|
151 |
+
Makes the frequency tensor broadcastable with the input tensor.
|
152 |
+
"""
|
153 |
+
_freqs_cis = self._freqs_cis[start_pos:end_pos]
|
154 |
+
ndim = len(input_shape)
|
155 |
+
assert 0 <= 1 < ndim
|
156 |
+
assert _freqs_cis.shape == (input_shape[1], input_shape[-1])
|
157 |
+
|
158 |
+
# TODO: Check whether this is correct (might be able to remove this)
|
159 |
+
shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(input_shape)]
|
160 |
+
return _freqs_cis.view(*shape)
|
161 |
+
|
162 |
+
def forward(
|
163 |
+
self,
|
164 |
+
queries: torch.Tensor,
|
165 |
+
keys: torch.Tensor,
|
166 |
+
start_pos: int = 0,
|
167 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
168 |
+
"""Apply RoPE Embeddings to Queries and Keys
|
169 |
+
|
170 |
+
Applies the rotary positional embeddings to the input tensors via complex num multiplication
|
171 |
+
|
172 |
+
NOTE: The start_pos is used if we want to use the kv_cache in the attention mechanism.
|
173 |
+
"""
|
174 |
+
queries_ = torch.view_as_complex(
|
175 |
+
queries.float().reshape(*queries.shape[:-1], -1, 2)
|
176 |
+
)
|
177 |
+
keys_ = torch.view_as_complex(keys.float().reshape(*keys.shape[:-1], -1, 2))
|
178 |
+
|
179 |
+
input_shape = (
|
180 |
+
queries_.shape
|
181 |
+
) # same as keys: (batch_size, seq_len, n_heads, head_dim/2)
|
182 |
+
freqs_start_pos = start_pos
|
183 |
+
freqs_end_pos = freqs_start_pos + queries_.shape[1]
|
184 |
+
|
185 |
+
freqs_cis = self.get_freqs_cis(input_shape, freqs_start_pos, freqs_end_pos)
|
186 |
+
|
187 |
+
queries_rotated = torch.view_as_real(queries_ * freqs_cis).flatten(3)
|
188 |
+
keys_rotated = torch.view_as_real(keys_ * freqs_cis).flatten(3)
|
189 |
+
return queries_rotated.type_as(queries), keys_rotated.type_as(keys)
|
190 |
+
|
191 |
+
|
192 |
+
########################################################
|
193 |
+
#
|
194 |
+
# Attention
|
195 |
+
#
|
196 |
+
########################################################
|
197 |
+
|
198 |
+
|
199 |
+
class Attention(nn.Module):
|
200 |
+
"""Multi-head Attention with Group Query Attention support.
|
201 |
+
|
202 |
+
Implements scaled dot-product attention and supports:
|
203 |
+
- Grouped Query Attention (GQA)
|
204 |
+
- Key-Value caching for efficient inference
|
205 |
+
- RoPE integration
|
206 |
+
|
207 |
+
Args:
|
208 |
+
config (Union[ModelConfig, PretrainedConfig]): Configuration containing:
|
209 |
+
- config.attention_n_heads: Number of attention heads
|
210 |
+
- config.attention_n_kv_heads: Number of key/value heads
|
211 |
+
- config.d_model: Model dimension
|
212 |
+
- config.batch_size: Maximum batch size
|
213 |
+
- config.max_seq_len: Maximum sequence length
|
214 |
+
|
215 |
+
Shape:
|
216 |
+
- Input: (batch_size, seq_len, d_model)
|
217 |
+
- Output: (batch_size, seq_len, d_model)
|
218 |
+
"""
|
219 |
+
|
220 |
+
def __init__(
|
221 |
+
self,
|
222 |
+
config: Union["ModelConfig", "PicoDecoderHFConfig"],
|
223 |
+
):
|
224 |
+
super().__init__()
|
225 |
+
|
226 |
+
self.n_heads = config.attention_n_heads
|
227 |
+
self.n_kv_heads = config.attention_n_kv_heads
|
228 |
+
|
229 |
+
self.batch_size = config.batch_size
|
230 |
+
self.max_seq_len = config.max_seq_len
|
231 |
+
|
232 |
+
d_model = config.d_model
|
233 |
+
self.head_dim = d_model // self.n_heads
|
234 |
+
|
235 |
+
self.n_rep = self.n_heads // self.n_kv_heads
|
236 |
+
|
237 |
+
self.q_proj = nn.Linear(d_model, self.n_heads * self.head_dim, bias=False)
|
238 |
+
self.k_proj = nn.Linear(d_model, self.n_kv_heads * self.head_dim, bias=False)
|
239 |
+
self.v_proj = nn.Linear(d_model, self.n_kv_heads * self.head_dim, bias=False)
|
240 |
+
self.o_proj = nn.Linear(self.n_heads * self.head_dim, d_model, bias=False)
|
241 |
+
|
242 |
+
self.rope = RoPE(config)
|
243 |
+
|
244 |
+
def forward(
|
245 |
+
self,
|
246 |
+
input: torch.Tensor,
|
247 |
+
mask: Optional[torch.Tensor] = None,
|
248 |
+
past_key_values: Optional[Tuple[torch.Tensor, ...]] = None,
|
249 |
+
use_cache: bool = False,
|
250 |
+
) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
|
251 |
+
"""Forward pass for the attention mechanism.
|
252 |
+
|
253 |
+
Computes queries, keys, and values for the attention mechanism. Applies rotary positional
|
254 |
+
embeddings to the queries and keys, and then computes attention scores and outputs.
|
255 |
+
|
256 |
+
For an introduction to the attention mechanism, see:
|
257 |
+
https://arxiv.org/abs/1706.03762
|
258 |
+
|
259 |
+
A few things to note:
|
260 |
+
- The past_key_values is used to implement the KV cache, which is used to speed up
|
261 |
+
generation by caching the KV pairs from previous forward passes. This is useful when doing
|
262 |
+
tasks that require generating multiple tokens conditioned on previous tokens (e.g. language
|
263 |
+
modeling, text generation, etc.). The way the KV cache is implemented is that each layer has
|
264 |
+
its own KV cache - this KV cache is implemented as a tuple.
|
265 |
+
"""
|
266 |
+
bsz, seq_len, _ = input.shape
|
267 |
+
_queries, _keys, _values = (
|
268 |
+
self.q_proj(input),
|
269 |
+
self.k_proj(input),
|
270 |
+
self.v_proj(input),
|
271 |
+
)
|
272 |
+
|
273 |
+
# Reshaping for multi-head attention
|
274 |
+
queries = _queries.view(bsz, seq_len, self.n_heads, self.head_dim)
|
275 |
+
keys = _keys.view(bsz, seq_len, self.n_kv_heads, self.head_dim)
|
276 |
+
values = _values.view(bsz, seq_len, self.n_kv_heads, self.head_dim)
|
277 |
+
|
278 |
+
# The start position is used to apply the RoPE embeddings to only the new tokens
|
279 |
+
# when using the kv_cache in the attention mechanism.
|
280 |
+
# We want to start from the last position in the cache.
|
281 |
+
start_pos = past_key_values[0].shape[1] if past_key_values is not None else 0
|
282 |
+
|
283 |
+
# apply rotary positional embeddings
|
284 |
+
queries, keys = self.rope(queries, keys, start_pos)
|
285 |
+
|
286 |
+
if past_key_values is not None:
|
287 |
+
keys = torch.cat([past_key_values[0], keys], dim=1)
|
288 |
+
values = torch.cat([past_key_values[1], values], dim=1)
|
289 |
+
|
290 |
+
if use_cache:
|
291 |
+
cached_keys = keys
|
292 |
+
cached_values = values
|
293 |
+
else:
|
294 |
+
cached_keys = None
|
295 |
+
cached_values = None
|
296 |
+
|
297 |
+
queries = queries.transpose(1, 2)
|
298 |
+
keys = keys.transpose(1, 2)
|
299 |
+
values = values.transpose(1, 2)
|
300 |
+
|
301 |
+
apply_gqa = self.n_rep > 1
|
302 |
+
if apply_gqa and queries.device.type == "mps":
|
303 |
+
# NOTE: MPS does not support GQA in the SDPA kernel, but we can repeat the keys and values
|
304 |
+
# outside of the kernel to get the same effect.
|
305 |
+
# See: https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html
|
306 |
+
keys = keys.repeat_interleave(self.n_rep, dim=-3)
|
307 |
+
values = values.repeat_interleave(self.n_rep, dim=-3)
|
308 |
+
apply_gqa = False
|
309 |
+
|
310 |
+
backends = [SDPBackend.CUDNN_ATTENTION, SDPBackend.MATH]
|
311 |
+
|
312 |
+
with sdpa_kernel(backends=backends):
|
313 |
+
attn_output = F.scaled_dot_product_attention(
|
314 |
+
queries.contiguous(),
|
315 |
+
keys.contiguous(),
|
316 |
+
values.contiguous(),
|
317 |
+
attn_mask=mask.to(queries.dtype),
|
318 |
+
enable_gqa=apply_gqa,
|
319 |
+
)
|
320 |
+
|
321 |
+
attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, seq_len, -1)
|
322 |
+
output = self.o_proj(attn_output)
|
323 |
+
|
324 |
+
return output, (cached_keys, cached_values)
|
325 |
+
|
326 |
+
|
327 |
+
########################################################
|
328 |
+
#
|
329 |
+
# SwiGLU (Combines MLP and Activation)
|
330 |
+
#
|
331 |
+
########################################################
|
332 |
+
|
333 |
+
|
334 |
+
class SwiGLU(nn.Module):
|
335 |
+
"""SwiGLU Activation Function with Linear Projections.
|
336 |
+
|
337 |
+
Implements the SwiGLU activation function combined with linear transformations,
|
338 |
+
serving as the feed-forward network in transformer blocks.
|
339 |
+
|
340 |
+
Args:
|
341 |
+
config (Union[ModelConfig, PicoDecoderHFConfig]): Configuration containing:
|
342 |
+
- config.d_model: Model dimension
|
343 |
+
- config.activation_hidden_dim: Hidden dimension (typically 4 * d_model)
|
344 |
+
|
345 |
+
References:
|
346 |
+
https://arxiv.org/abs/2002.05202
|
347 |
+
"""
|
348 |
+
|
349 |
+
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]):
|
350 |
+
super().__init__()
|
351 |
+
|
352 |
+
model_dim = config.d_model
|
353 |
+
act_hidden_dim = config.activation_hidden_dim # usually 4 * d_model
|
354 |
+
|
355 |
+
self.w_0 = nn.Linear(model_dim, act_hidden_dim, bias=False)
|
356 |
+
self.w_1 = nn.Linear(model_dim, act_hidden_dim, bias=False)
|
357 |
+
self.w_2 = nn.Linear(act_hidden_dim, model_dim, bias=False)
|
358 |
+
|
359 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
360 |
+
return self.w_2(F.silu(self.w_0(x)) * self.w_1(x))
|
361 |
+
|
362 |
+
|
363 |
+
########################################################
|
364 |
+
#
|
365 |
+
# PicoDecoderBlock
|
366 |
+
#
|
367 |
+
########################################################
|
368 |
+
|
369 |
+
|
370 |
+
class PicoDecoderBlock(nn.Module):
|
371 |
+
"""Single Transformer Block with Attention and Feed-forward layers.
|
372 |
+
|
373 |
+
Implements a standard transformer block with:
|
374 |
+
- Multi-head attention with normalization and residual connection
|
375 |
+
- SwiGLU feed-forward network with normalization and residual connection
|
376 |
+
|
377 |
+
Args:
|
378 |
+
config (Union[ModelConfig, PicoDecoderHFConfig]): Model configuration; either a dataclass or
|
379 |
+
a HuggingFace PicoDecoderHFConfig
|
380 |
+
"""
|
381 |
+
|
382 |
+
def __init__(
|
383 |
+
self,
|
384 |
+
config: Union["ModelConfig", "PicoDecoderHFConfig"],
|
385 |
+
):
|
386 |
+
super().__init__()
|
387 |
+
|
388 |
+
self.attention = Attention(config)
|
389 |
+
self.swiglu = SwiGLU(config)
|
390 |
+
self.attention_norm = RMSNorm(config)
|
391 |
+
self.swiglu_norm = RMSNorm(config)
|
392 |
+
|
393 |
+
def forward(
|
394 |
+
self,
|
395 |
+
input: torch.Tensor,
|
396 |
+
mask: Optional[torch.Tensor] = None,
|
397 |
+
past_key_values: Optional[Tuple[torch.Tensor]] = None,
|
398 |
+
use_cache: bool = False,
|
399 |
+
) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
|
400 |
+
attention_output, cached_key_values = self.attention(
|
401 |
+
self.attention_norm(input),
|
402 |
+
mask=mask,
|
403 |
+
past_key_values=past_key_values,
|
404 |
+
use_cache=use_cache,
|
405 |
+
)
|
406 |
+
# NOTE: cached_key_values is None if use_cache is False
|
407 |
+
|
408 |
+
h = input + attention_output
|
409 |
+
out = h + self.swiglu(self.swiglu_norm(h))
|
410 |
+
return out, cached_key_values
|
411 |
+
|
412 |
+
|
413 |
+
########################################################
|
414 |
+
#
|
415 |
+
# Pico Decoder (Causal Transformer Model)
|
416 |
+
#
|
417 |
+
########################################################
|
418 |
+
|
419 |
+
|
420 |
+
class PicoDecoder(nn.Module):
|
421 |
+
"""
|
422 |
+
Pico Decoder: combines the embedding, causal decoder blocks, and output projection into a
|
423 |
+
single autoregressive model.
|
424 |
+
|
425 |
+
For more information on the model, see the classes for the modules that make up the model.
|
426 |
+
"""
|
427 |
+
|
428 |
+
def __init__(
|
429 |
+
self,
|
430 |
+
model_config: Union["ModelConfig", "PicoDecoderHFConfig"],
|
431 |
+
):
|
432 |
+
super().__init__()
|
433 |
+
self.config = model_config
|
434 |
+
|
435 |
+
self.embedding_proj = nn.Embedding(self.config.vocab_size, self.config.d_model)
|
436 |
+
self.layers = nn.ModuleList(
|
437 |
+
[PicoDecoderBlock(self.config) for _ in range(self.config.n_layers)]
|
438 |
+
)
|
439 |
+
self.output_norm = RMSNorm(self.config)
|
440 |
+
self.de_embedding_proj = nn.Linear(
|
441 |
+
self.config.d_model, self.config.vocab_size, bias=False
|
442 |
+
)
|
443 |
+
|
444 |
+
def convert_to_hf_model(self) -> "PicoDecoderHF":
|
445 |
+
"""Convert the Lightning model to a HuggingFace model."""
|
446 |
+
# Build HF config
|
447 |
+
hf_config = PicoDecoderHFConfig.from_dataclass(self.config)
|
448 |
+
|
449 |
+
# Instantiate the HF-wrapped model
|
450 |
+
hf_model = PicoDecoderHF(hf_config)
|
451 |
+
|
452 |
+
# Grab our full state dict, prefixing module names
|
453 |
+
raw_state = self.state_dict(prefix="pico_decoder.")
|
454 |
+
|
455 |
+
# Only keep keys that exist in the HF model (drops classifier_head, etc.)
|
456 |
+
hf_keys = set(hf_model.state_dict().keys())
|
457 |
+
filtered_state = {k: v for k, v in raw_state.items() if k in hf_keys}
|
458 |
+
|
459 |
+
# Load into HF model, ignore any missing keys
|
460 |
+
hf_model.load_state_dict(filtered_state, strict=False)
|
461 |
+
|
462 |
+
return hf_model
|
463 |
+
|
464 |
+
def forward(
|
465 |
+
self,
|
466 |
+
input_ids: torch.Tensor,
|
467 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
468 |
+
use_cache: bool = False,
|
469 |
+
return_hidden: bool = False,
|
470 |
+
) -> Tuple[torch.Tensor, Optional[Tuple[Tuple[torch.Tensor, torch.Tensor]]]]:
|
471 |
+
"""
|
472 |
+
This is the forward pass for the entire Pico model. It boils down to:
|
473 |
+
- Embedding the input ids
|
474 |
+
- Creating a causal mask
|
475 |
+
- Processing through the pico layers
|
476 |
+
- Projecting the output to logits
|
477 |
+
|
478 |
+
NOTE: One feature that might be confusing is the KV cache. The KV cache is used to speed up
|
479 |
+
generation by caching the KV pairs from previous forward passes. This is useful when doing
|
480 |
+
tasks that require generating multiple tokens conditioned on previous tokens (e.g. language
|
481 |
+
modeling, text generation, etc.). The way the KV cache is implemented is that each layer has
|
482 |
+
its own KV cache which is stored as a tuple. The whole model then stores a tuple of these
|
483 |
+
KV caches (so a tuple of tuples).
|
484 |
+
"""
|
485 |
+
|
486 |
+
seq_len = input_ids.shape[-1]
|
487 |
+
h = self.embedding_proj(input_ids)
|
488 |
+
|
489 |
+
# Calculate start position from past cached KV pairs. Remember that each layer has its
|
490 |
+
# own KV Cache. So when we index past_key_values, we need to index into the KV pairs for the
|
491 |
+
# correct layer and then for either the keys or values.
|
492 |
+
start_pos = 0 if past_key_values is None else past_key_values[0][0].shape[1]
|
493 |
+
|
494 |
+
# Create causal mask for current sequence
|
495 |
+
mask = None
|
496 |
+
if seq_len > 1:
|
497 |
+
mask = torch.full((seq_len, seq_len), float("-inf"))
|
498 |
+
mask = torch.triu(mask, diagonal=1)
|
499 |
+
|
500 |
+
# If using KV cache, extend mask to cover cached sequence length
|
501 |
+
if past_key_values is not None:
|
502 |
+
# Add zeros for cached tokens (we can attend to all of them)
|
503 |
+
mask = torch.hstack([torch.zeros((seq_len, start_pos)), mask])
|
504 |
+
|
505 |
+
mask = mask.to(h.device)
|
506 |
+
|
507 |
+
# NOTE: If we are using the cache, we need to store the cached KV pairs for each layer
|
508 |
+
# in a tuple. Each layer will have its own cached KV pair which we aggregate in a tuple.
|
509 |
+
cached_key_values = () if use_cache else None
|
510 |
+
|
511 |
+
# Process through transformer blocks
|
512 |
+
for idx, layer in enumerate(self.layers):
|
513 |
+
layer_past_key_values = (
|
514 |
+
past_key_values[idx] if past_key_values is not None else None
|
515 |
+
)
|
516 |
+
|
517 |
+
h, layer_cached_key_values = layer(
|
518 |
+
h, mask=mask, past_key_values=layer_past_key_values, use_cache=use_cache
|
519 |
+
)
|
520 |
+
|
521 |
+
if use_cache:
|
522 |
+
cached_key_values += (layer_cached_key_values,)
|
523 |
+
|
524 |
+
# Final norm and projection
|
525 |
+
h = self.output_norm(h)
|
526 |
+
|
527 |
+
if return_hidden:
|
528 |
+
return h, cached_key_values
|
529 |
+
|
530 |
+
logits = self.de_embedding_proj(h).float()
|
531 |
+
|
532 |
+
return logits, cached_key_values
|
533 |
+
|
534 |
+
|
535 |
+
########################################################
|
536 |
+
#
|
537 |
+
# HuggingFace Wrapper for the Pico Decoder model.
|
538 |
+
#
|
539 |
+
########################################################
|
540 |
+
|
541 |
+
|
542 |
+
class PicoDecoderHFConfig(PretrainedConfig):
|
543 |
+
"""Config class for the Pico Decoder HuggingFace wrapper."""
|
544 |
+
|
545 |
+
model_type = "pico_decoder"
|
546 |
+
|
547 |
+
@classmethod
|
548 |
+
def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> "PicoDecoderHFConfig":
|
549 |
+
# NOTE The typical from_dict method doesn't actually set the attributes unless they are
|
550 |
+
# defined in the constructor.
|
551 |
+
|
552 |
+
pico_config = cls(**kwargs)
|
553 |
+
|
554 |
+
# Because this class is just a wrapper around the ModelConfig dataclass, we need to do
|
555 |
+
# a little extra work to ensure that the attributes are actually set.
|
556 |
+
for key, value in config_dict.items():
|
557 |
+
setattr(pico_config, key, value)
|
558 |
+
|
559 |
+
return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
|
560 |
+
unused_kwargs = {
|
561 |
+
key: value for key, value in kwargs.items() if not hasattr(pico_config, key)
|
562 |
+
}
|
563 |
+
|
564 |
+
if return_unused_kwargs:
|
565 |
+
return pico_config, unused_kwargs
|
566 |
+
return pico_config
|
567 |
+
|
568 |
+
@classmethod
|
569 |
+
def from_dataclass(cls, model_config: "ModelConfig"):
|
570 |
+
"""Initialise from our custom config dataclass."""
|
571 |
+
return cls.from_dict(asdict(model_config))
|
572 |
+
|
573 |
+
|
574 |
+
class PicoDecoderHF(PreTrainedModel):
|
575 |
+
"""
|
576 |
+
HuggingFace wrapper for the Pico model.
|
577 |
+
|
578 |
+
Many evaluation frameworks require a model be setup as a HuggingFace model, so we provide a simple
|
579 |
+
wrapper that does just that. When we save checkpoints of the Pico model, we save both the normal
|
580 |
+
Pico model as well as the model wrapped in this HuggingFace class.
|
581 |
+
|
582 |
+
This also lets you do cool things like:
|
583 |
+
|
584 |
+
`model = AutoModelForCausalLM.from_pretrained("path/to/checkpoint")`
|
585 |
+
"""
|
586 |
+
|
587 |
+
config_class = PicoDecoderHFConfig
|
588 |
+
_no_split_modules = ["PicoBlock", "Attention", "SwiGLU", "RMSNorm"]
|
589 |
+
|
590 |
+
def __init__(self, config: PicoDecoderHFConfig):
|
591 |
+
super().__init__(config)
|
592 |
+
self.pico_decoder = PicoDecoder(config)
|
593 |
+
|
594 |
+
def forward(
|
595 |
+
self,
|
596 |
+
input_ids: torch.Tensor,
|
597 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
598 |
+
use_cache: bool = False,
|
599 |
+
**kwargs,
|
600 |
+
) -> Union[CausalLMOutput, CausalLMOutputWithPast]:
|
601 |
+
"""HuggingFace forward pass wrapper.
|
602 |
+
|
603 |
+
Forwards pass for the HuggingFace version of the Pico Model. Basic wrapper around the
|
604 |
+
Pico model's forward pass, and returns the output as a HuggingFace CausalLMOutput.
|
605 |
+
"""
|
606 |
+
logits, past_key_values = self.pico_decoder(
|
607 |
+
input_ids, past_key_values, use_cache
|
608 |
+
)
|
609 |
+
if use_cache:
|
610 |
+
return CausalLMOutputWithPast(
|
611 |
+
logits=logits,
|
612 |
+
past_key_values=past_key_values,
|
613 |
+
)
|
614 |
+
else:
|
615 |
+
return CausalLMOutput(
|
616 |
+
logits=logits,
|
617 |
+
)
|
618 |
+
|
619 |
+
|
620 |
+
# Register for auto classes
|
621 |
+
PicoDecoderHFConfig.register_for_auto_class()
|
622 |
+
PicoDecoderHF.register_for_auto_class("AutoModel")
|
623 |
+
PicoDecoderHF.register_for_auto_class("AutoModelForCausalLM")
|
checkpoints/step_5200/special_tokens_map.json
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"eos_token": {
|
3 |
+
"content": "<|endoftext|>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": false,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"mask_token": {
|
10 |
+
"content": "[MASK]",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": false,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"pad_token": {
|
17 |
+
"content": "<|padding|>",
|
18 |
+
"lstrip": false,
|
19 |
+
"normalized": false,
|
20 |
+
"rstrip": false,
|
21 |
+
"single_word": false
|
22 |
+
}
|
23 |
+
}
|
checkpoints/step_5200/tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
checkpoints/step_5200/tokenizer_config.json
ADDED
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": false,
|
3 |
+
"add_eos_token": false,
|
4 |
+
"add_prefix_space": false,
|
5 |
+
"added_tokens_decoder": {
|
6 |
+
"0": {
|
7 |
+
"content": "|||IP_ADDRESS|||",
|
8 |
+
"lstrip": false,
|
9 |
+
"normalized": true,
|
10 |
+
"rstrip": false,
|
11 |
+
"single_word": false,
|
12 |
+
"special": false
|
13 |
+
},
|
14 |
+
"1": {
|
15 |
+
"content": "<|padding|>",
|
16 |
+
"lstrip": false,
|
17 |
+
"normalized": false,
|
18 |
+
"rstrip": false,
|
19 |
+
"single_word": false,
|
20 |
+
"special": true
|
21 |
+
},
|
22 |
+
"50254": {
|
23 |
+
"content": " ",
|
24 |
+
"lstrip": false,
|
25 |
+
"normalized": true,
|
26 |
+
"rstrip": false,
|
27 |
+
"single_word": false,
|
28 |
+
"special": false
|
29 |
+
},
|
30 |
+
"50255": {
|
31 |
+
"content": " ",
|
32 |
+
"lstrip": false,
|
33 |
+
"normalized": true,
|
34 |
+
"rstrip": false,
|
35 |
+
"single_word": false,
|
36 |
+
"special": false
|
37 |
+
},
|
38 |
+
"50256": {
|
39 |
+
"content": " ",
|
40 |
+
"lstrip": false,
|
41 |
+
"normalized": true,
|
42 |
+
"rstrip": false,
|
43 |
+
"single_word": false,
|
44 |
+
"special": false
|
45 |
+
},
|
46 |
+
"50257": {
|
47 |
+
"content": " ",
|
48 |
+
"lstrip": false,
|
49 |
+
"normalized": true,
|
50 |
+
"rstrip": false,
|
51 |
+
"single_word": false,
|
52 |
+
"special": false
|
53 |
+
},
|
54 |
+
"50258": {
|
55 |
+
"content": " ",
|
56 |
+
"lstrip": false,
|
57 |
+
"normalized": true,
|
58 |
+
"rstrip": false,
|
59 |
+
"single_word": false,
|
60 |
+
"special": false
|
61 |
+
},
|
62 |
+
"50259": {
|
63 |
+
"content": " ",
|
64 |
+
"lstrip": false,
|
65 |
+
"normalized": true,
|
66 |
+
"rstrip": false,
|
67 |
+
"single_word": false,
|
68 |
+
"special": false
|
69 |
+
},
|
70 |
+
"50260": {
|
71 |
+
"content": " ",
|
72 |
+
"lstrip": false,
|
73 |
+
"normalized": true,
|
74 |
+
"rstrip": false,
|
75 |
+
"single_word": false,
|
76 |
+
"special": false
|
77 |
+
},
|
78 |
+
"50261": {
|
79 |
+
"content": " ",
|
80 |
+
"lstrip": false,
|
81 |
+
"normalized": true,
|
82 |
+
"rstrip": false,
|
83 |
+
"single_word": false,
|
84 |
+
"special": false
|
85 |
+
},
|
86 |
+
"50262": {
|
87 |
+
"content": " ",
|
88 |
+
"lstrip": false,
|
89 |
+
"normalized": true,
|
90 |
+
"rstrip": false,
|
91 |
+
"single_word": false,
|
92 |
+
"special": false
|
93 |
+
},
|
94 |
+
"50263": {
|
95 |
+
"content": " ",
|
96 |
+
"lstrip": false,
|
97 |
+
"normalized": true,
|
98 |
+
"rstrip": false,
|
99 |
+
"single_word": false,
|
100 |
+
"special": false
|
101 |
+
},
|
102 |
+
"50264": {
|
103 |
+
"content": " ",
|
104 |
+
"lstrip": false,
|
105 |
+
"normalized": true,
|
106 |
+
"rstrip": false,
|
107 |
+
"single_word": false,
|
108 |
+
"special": false
|
109 |
+
},
|
110 |
+
"50265": {
|
111 |
+
"content": " ",
|
112 |
+
"lstrip": false,
|
113 |
+
"normalized": true,
|
114 |
+
"rstrip": false,
|
115 |
+
"single_word": false,
|
116 |
+
"special": false
|
117 |
+
},
|
118 |
+
"50266": {
|
119 |
+
"content": " ",
|
120 |
+
"lstrip": false,
|
121 |
+
"normalized": true,
|
122 |
+
"rstrip": false,
|
123 |
+
"single_word": false,
|
124 |
+
"special": false
|
125 |
+
},
|
126 |
+
"50267": {
|
127 |
+
"content": " ",
|
128 |
+
"lstrip": false,
|
129 |
+
"normalized": true,
|
130 |
+
"rstrip": false,
|
131 |
+
"single_word": false,
|
132 |
+
"special": false
|
133 |
+
},
|
134 |
+
"50268": {
|
135 |
+
"content": " ",
|
136 |
+
"lstrip": false,
|
137 |
+
"normalized": true,
|
138 |
+
"rstrip": false,
|
139 |
+
"single_word": false,
|
140 |
+
"special": false
|
141 |
+
},
|
142 |
+
"50269": {
|
143 |
+
"content": " ",
|
144 |
+
"lstrip": false,
|
145 |
+
"normalized": true,
|
146 |
+
"rstrip": false,
|
147 |
+
"single_word": false,
|
148 |
+
"special": false
|
149 |
+
},
|
150 |
+
"50270": {
|
151 |
+
"content": " ",
|
152 |
+
"lstrip": false,
|
153 |
+
"normalized": true,
|
154 |
+
"rstrip": false,
|
155 |
+
"single_word": false,
|
156 |
+
"special": false
|
157 |
+
},
|
158 |
+
"50271": {
|
159 |
+
"content": " ",
|
160 |
+
"lstrip": false,
|
161 |
+
"normalized": true,
|
162 |
+
"rstrip": false,
|
163 |
+
"single_word": false,
|
164 |
+
"special": false
|
165 |
+
},
|
166 |
+
"50272": {
|
167 |
+
"content": " ",
|
168 |
+
"lstrip": false,
|
169 |
+
"normalized": true,
|
170 |
+
"rstrip": false,
|
171 |
+
"single_word": false,
|
172 |
+
"special": false
|
173 |
+
},
|
174 |
+
"50273": {
|
175 |
+
"content": " ",
|
176 |
+
"lstrip": false,
|
177 |
+
"normalized": true,
|
178 |
+
"rstrip": false,
|
179 |
+
"single_word": false,
|
180 |
+
"special": false
|
181 |
+
},
|
182 |
+
"50274": {
|
183 |
+
"content": " ",
|
184 |
+
"lstrip": false,
|
185 |
+
"normalized": true,
|
186 |
+
"rstrip": false,
|
187 |
+
"single_word": false,
|
188 |
+
"special": false
|
189 |
+
},
|
190 |
+
"50275": {
|
191 |
+
"content": " ",
|
192 |
+
"lstrip": false,
|
193 |
+
"normalized": true,
|
194 |
+
"rstrip": false,
|
195 |
+
"single_word": false,
|
196 |
+
"special": false
|
197 |
+
},
|
198 |
+
"50276": {
|
199 |
+
"content": " ",
|
200 |
+
"lstrip": false,
|
201 |
+
"normalized": true,
|
202 |
+
"rstrip": false,
|
203 |
+
"single_word": false,
|
204 |
+
"special": false
|
205 |
+
},
|
206 |
+
"50277": {
|
207 |
+
"content": "|||EMAIL_ADDRESS|||",
|
208 |
+
"lstrip": false,
|
209 |
+
"normalized": true,
|
210 |
+
"rstrip": false,
|
211 |
+
"single_word": false,
|
212 |
+
"special": false
|
213 |
+
},
|
214 |
+
"50278": {
|
215 |
+
"content": "|||PHONE_NUMBER|||",
|
216 |
+
"lstrip": false,
|
217 |
+
"normalized": true,
|
218 |
+
"rstrip": false,
|
219 |
+
"single_word": false,
|
220 |
+
"special": false
|
221 |
+
},
|
222 |
+
"50279": {
|
223 |
+
"content": "<|endoftext|>",
|
224 |
+
"lstrip": false,
|
225 |
+
"normalized": false,
|
226 |
+
"rstrip": false,
|
227 |
+
"single_word": false,
|
228 |
+
"special": true
|
229 |
+
},
|
230 |
+
"50280": {
|
231 |
+
"content": "[MASK]",
|
232 |
+
"lstrip": false,
|
233 |
+
"normalized": false,
|
234 |
+
"rstrip": false,
|
235 |
+
"single_word": false,
|
236 |
+
"special": true
|
237 |
+
}
|
238 |
+
},
|
239 |
+
"bos_token": null,
|
240 |
+
"clean_up_tokenization_spaces": true,
|
241 |
+
"eos_token": "<|endoftext|>",
|
242 |
+
"extra_special_tokens": {},
|
243 |
+
"mask_token": "[MASK]",
|
244 |
+
"model_max_length": 1000000000000000019884624838656,
|
245 |
+
"pad_token": "<|padding|>",
|
246 |
+
"tokenizer_class": "GPTNeoXTokenizer",
|
247 |
+
"unk_token": null
|
248 |
+
}
|
checkpoints/step_5300/config.json
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"activation_hidden_dim": 1536,
|
3 |
+
"architectures": [
|
4 |
+
"PicoDecoderHF"
|
5 |
+
],
|
6 |
+
"attention_n_heads": 12,
|
7 |
+
"attention_n_kv_heads": 4,
|
8 |
+
"auto_map": {
|
9 |
+
"AutoConfig": "pico_decoder.PicoDecoderHFConfig",
|
10 |
+
"AutoModelForCausalLM": "pico_decoder.PicoDecoderHF"
|
11 |
+
},
|
12 |
+
"batch_size": 1024,
|
13 |
+
"d_model": 384,
|
14 |
+
"max_seq_len": 512,
|
15 |
+
"model_type": "pico_decoder",
|
16 |
+
"n_layers": 12,
|
17 |
+
"norm_eps": 1e-06,
|
18 |
+
"position_emb_theta": 10000.0,
|
19 |
+
"torch_dtype": "float32",
|
20 |
+
"transformers_version": "4.48.3",
|
21 |
+
"vocab_size": 50281
|
22 |
+
}
|
checkpoints/step_5300/fabric_state/checkpoint/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b4f186a3d24e46bc7eb2320e1abc93fe4c2c61ae04225fe7e7a232fccbe4b90a
|
3 |
+
size 213443205
|
checkpoints/step_5300/fabric_state/checkpoint/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:519ed47009fa2de676b8c554fba58d109c801e21bc741272d3b7adba0784a5c8
|
3 |
+
size 213447621
|
checkpoints/step_5300/fabric_state/checkpoint/bf16_zero_pp_rank_2_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1d45e4d5a6a067656dcea1048de78666348140c64a519b4b54226c06703700bf
|
3 |
+
size 213445701
|
checkpoints/step_5300/fabric_state/checkpoint/bf16_zero_pp_rank_3_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d5ca182c75d3603ccc982676373a8594197d90c5eb271f727d124b1878904f9f
|
3 |
+
size 213443589
|
checkpoints/step_5300/fabric_state/checkpoint/mp_rank_00_model_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4d598c440f11a42ce85595a6c1fd78d3496041202bdbc30339389da15f5bc6f3
|
3 |
+
size 142325529
|
checkpoints/step_5300/fabric_state/latest
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
checkpoint
|
checkpoints/step_5300/fabric_state/zero_to_fp32.py
ADDED
@@ -0,0 +1,760 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
|
3 |
+
# Copyright (c) Microsoft Corporation.
|
4 |
+
# SPDX-License-Identifier: Apache-2.0
|
5 |
+
|
6 |
+
# DeepSpeed Team
|
7 |
+
|
8 |
+
# This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets
|
9 |
+
# copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
|
10 |
+
# the future. Once extracted, the weights don't require DeepSpeed and can be used in any
|
11 |
+
# application.
|
12 |
+
#
|
13 |
+
# example:
|
14 |
+
# python zero_to_fp32.py . output_dir/
|
15 |
+
# or
|
16 |
+
# python zero_to_fp32.py . output_dir/ --safe_serialization
|
17 |
+
|
18 |
+
import argparse
|
19 |
+
import torch
|
20 |
+
import glob
|
21 |
+
import math
|
22 |
+
import os
|
23 |
+
import re
|
24 |
+
import gc
|
25 |
+
import json
|
26 |
+
import numpy as np
|
27 |
+
from tqdm import tqdm
|
28 |
+
from collections import OrderedDict
|
29 |
+
from dataclasses import dataclass
|
30 |
+
|
31 |
+
# while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
|
32 |
+
# DeepSpeed data structures it has to be available in the current python environment.
|
33 |
+
from deepspeed.utils import logger
|
34 |
+
from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
|
35 |
+
FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
|
36 |
+
FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
|
37 |
+
|
38 |
+
|
39 |
+
@dataclass
|
40 |
+
class zero_model_state:
|
41 |
+
buffers: dict()
|
42 |
+
param_shapes: dict()
|
43 |
+
shared_params: list
|
44 |
+
ds_version: int
|
45 |
+
frozen_param_shapes: dict()
|
46 |
+
frozen_param_fragments: dict()
|
47 |
+
|
48 |
+
|
49 |
+
debug = 0
|
50 |
+
|
51 |
+
# load to cpu
|
52 |
+
device = torch.device('cpu')
|
53 |
+
|
54 |
+
|
55 |
+
def atoi(text):
|
56 |
+
return int(text) if text.isdigit() else text
|
57 |
+
|
58 |
+
|
59 |
+
def natural_keys(text):
|
60 |
+
'''
|
61 |
+
alist.sort(key=natural_keys) sorts in human order
|
62 |
+
http://nedbatchelder.com/blog/200712/human_sorting.html
|
63 |
+
(See Toothy's implementation in the comments)
|
64 |
+
'''
|
65 |
+
return [atoi(c) for c in re.split(r'(\d+)', text)]
|
66 |
+
|
67 |
+
|
68 |
+
def get_model_state_file(checkpoint_dir, zero_stage):
|
69 |
+
if not os.path.isdir(checkpoint_dir):
|
70 |
+
raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
|
71 |
+
|
72 |
+
# there should be only one file
|
73 |
+
if zero_stage <= 2:
|
74 |
+
file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
|
75 |
+
elif zero_stage == 3:
|
76 |
+
file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
|
77 |
+
|
78 |
+
if not os.path.exists(file):
|
79 |
+
raise FileNotFoundError(f"can't find model states file at '{file}'")
|
80 |
+
|
81 |
+
return file
|
82 |
+
|
83 |
+
|
84 |
+
def get_checkpoint_files(checkpoint_dir, glob_pattern):
|
85 |
+
# XXX: need to test that this simple glob rule works for multi-node setup too
|
86 |
+
ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
|
87 |
+
|
88 |
+
if len(ckpt_files) == 0:
|
89 |
+
raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
|
90 |
+
|
91 |
+
return ckpt_files
|
92 |
+
|
93 |
+
|
94 |
+
def get_optim_files(checkpoint_dir):
|
95 |
+
return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
|
96 |
+
|
97 |
+
|
98 |
+
def get_model_state_files(checkpoint_dir):
|
99 |
+
return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
|
100 |
+
|
101 |
+
|
102 |
+
def parse_model_states(files):
|
103 |
+
zero_model_states = []
|
104 |
+
for file in files:
|
105 |
+
state_dict = torch.load(file, map_location=device, weights_only=False)
|
106 |
+
|
107 |
+
if BUFFER_NAMES not in state_dict:
|
108 |
+
raise ValueError(f"{file} is not a model state checkpoint")
|
109 |
+
buffer_names = state_dict[BUFFER_NAMES]
|
110 |
+
if debug:
|
111 |
+
print("Found buffers:", buffer_names)
|
112 |
+
|
113 |
+
# recover just the buffers while restoring them to fp32 if they were saved in fp16
|
114 |
+
buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
|
115 |
+
param_shapes = state_dict[PARAM_SHAPES]
|
116 |
+
|
117 |
+
# collect parameters that are included in param_shapes
|
118 |
+
param_names = []
|
119 |
+
for s in param_shapes:
|
120 |
+
for name in s.keys():
|
121 |
+
param_names.append(name)
|
122 |
+
|
123 |
+
# update with frozen parameters
|
124 |
+
frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
|
125 |
+
if frozen_param_shapes is not None:
|
126 |
+
if debug:
|
127 |
+
print(f"Found frozen_param_shapes: {frozen_param_shapes}")
|
128 |
+
param_names += list(frozen_param_shapes.keys())
|
129 |
+
|
130 |
+
# handle shared params
|
131 |
+
shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
|
132 |
+
|
133 |
+
ds_version = state_dict.get(DS_VERSION, None)
|
134 |
+
|
135 |
+
frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
|
136 |
+
|
137 |
+
z_model_state = zero_model_state(buffers=buffers,
|
138 |
+
param_shapes=param_shapes,
|
139 |
+
shared_params=shared_params,
|
140 |
+
ds_version=ds_version,
|
141 |
+
frozen_param_shapes=frozen_param_shapes,
|
142 |
+
frozen_param_fragments=frozen_param_fragments)
|
143 |
+
zero_model_states.append(z_model_state)
|
144 |
+
|
145 |
+
return zero_model_states
|
146 |
+
|
147 |
+
|
148 |
+
def parse_optim_states(files, ds_checkpoint_dir):
|
149 |
+
total_files = len(files)
|
150 |
+
state_dicts = []
|
151 |
+
for f in tqdm(files, desc='Loading checkpoint shards'):
|
152 |
+
state_dict = torch.load(f, map_location=device, mmap=True, weights_only=False)
|
153 |
+
# immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights
|
154 |
+
# and also handle the case where it was already removed by another helper script
|
155 |
+
state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
|
156 |
+
state_dicts.append(state_dict)
|
157 |
+
|
158 |
+
if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
|
159 |
+
raise ValueError(f"{files[0]} is not a zero checkpoint")
|
160 |
+
zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
|
161 |
+
world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
|
162 |
+
|
163 |
+
# For ZeRO-2 each param group can have different partition_count as data parallelism for expert
|
164 |
+
# parameters can be different from data parallelism for non-expert parameters. So we can just
|
165 |
+
# use the max of the partition_count to get the dp world_size.
|
166 |
+
|
167 |
+
if type(world_size) is list:
|
168 |
+
world_size = max(world_size)
|
169 |
+
|
170 |
+
if world_size != total_files:
|
171 |
+
raise ValueError(
|
172 |
+
f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
|
173 |
+
"Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
|
174 |
+
)
|
175 |
+
|
176 |
+
# the groups are named differently in each stage
|
177 |
+
if zero_stage <= 2:
|
178 |
+
fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
|
179 |
+
elif zero_stage == 3:
|
180 |
+
fp32_groups_key = FP32_FLAT_GROUPS
|
181 |
+
else:
|
182 |
+
raise ValueError(f"unknown zero stage {zero_stage}")
|
183 |
+
|
184 |
+
fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
|
185 |
+
return zero_stage, world_size, fp32_flat_groups
|
186 |
+
|
187 |
+
|
188 |
+
def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters):
|
189 |
+
"""
|
190 |
+
Returns fp32 state_dict reconstructed from ds checkpoint
|
191 |
+
|
192 |
+
Args:
|
193 |
+
- ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
|
194 |
+
|
195 |
+
"""
|
196 |
+
print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
|
197 |
+
|
198 |
+
optim_files = get_optim_files(ds_checkpoint_dir)
|
199 |
+
zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
|
200 |
+
print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
|
201 |
+
|
202 |
+
model_files = get_model_state_files(ds_checkpoint_dir)
|
203 |
+
|
204 |
+
zero_model_states = parse_model_states(model_files)
|
205 |
+
print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
|
206 |
+
|
207 |
+
if zero_stage <= 2:
|
208 |
+
return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
209 |
+
exclude_frozen_parameters)
|
210 |
+
elif zero_stage == 3:
|
211 |
+
return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
212 |
+
exclude_frozen_parameters)
|
213 |
+
|
214 |
+
|
215 |
+
def _zero2_merge_frozen_params(state_dict, zero_model_states):
|
216 |
+
if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
|
217 |
+
return
|
218 |
+
|
219 |
+
frozen_param_shapes = zero_model_states[0].frozen_param_shapes
|
220 |
+
frozen_param_fragments = zero_model_states[0].frozen_param_fragments
|
221 |
+
|
222 |
+
if debug:
|
223 |
+
num_elem = sum(s.numel() for s in frozen_param_shapes.values())
|
224 |
+
print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
|
225 |
+
|
226 |
+
wanted_params = len(frozen_param_shapes)
|
227 |
+
wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
|
228 |
+
avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
|
229 |
+
print(f'Frozen params: Have {avail_numel} numels to process.')
|
230 |
+
print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
|
231 |
+
|
232 |
+
total_params = 0
|
233 |
+
total_numel = 0
|
234 |
+
for name, shape in frozen_param_shapes.items():
|
235 |
+
total_params += 1
|
236 |
+
unpartitioned_numel = shape.numel()
|
237 |
+
total_numel += unpartitioned_numel
|
238 |
+
|
239 |
+
state_dict[name] = frozen_param_fragments[name]
|
240 |
+
|
241 |
+
if debug:
|
242 |
+
print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
|
243 |
+
|
244 |
+
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
|
245 |
+
|
246 |
+
|
247 |
+
def _has_callable(obj, fn):
|
248 |
+
attr = getattr(obj, fn, None)
|
249 |
+
return callable(attr)
|
250 |
+
|
251 |
+
|
252 |
+
def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
|
253 |
+
param_shapes = zero_model_states[0].param_shapes
|
254 |
+
|
255 |
+
# Reconstruction protocol:
|
256 |
+
#
|
257 |
+
# XXX: document this
|
258 |
+
|
259 |
+
if debug:
|
260 |
+
for i in range(world_size):
|
261 |
+
for j in range(len(fp32_flat_groups[0])):
|
262 |
+
print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
|
263 |
+
|
264 |
+
# XXX: memory usage doubles here (zero2)
|
265 |
+
num_param_groups = len(fp32_flat_groups[0])
|
266 |
+
merged_single_partition_of_fp32_groups = []
|
267 |
+
for i in range(num_param_groups):
|
268 |
+
merged_partitions = [sd[i] for sd in fp32_flat_groups]
|
269 |
+
full_single_fp32_vector = torch.cat(merged_partitions, 0)
|
270 |
+
merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
|
271 |
+
avail_numel = sum(
|
272 |
+
[full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
|
273 |
+
|
274 |
+
if debug:
|
275 |
+
wanted_params = sum([len(shapes) for shapes in param_shapes])
|
276 |
+
wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
|
277 |
+
# not asserting if there is a mismatch due to possible padding
|
278 |
+
print(f"Have {avail_numel} numels to process.")
|
279 |
+
print(f"Need {wanted_numel} numels in {wanted_params} params.")
|
280 |
+
|
281 |
+
# params
|
282 |
+
# XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
|
283 |
+
# out-of-core computing solution
|
284 |
+
total_numel = 0
|
285 |
+
total_params = 0
|
286 |
+
for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
|
287 |
+
offset = 0
|
288 |
+
avail_numel = full_single_fp32_vector.numel()
|
289 |
+
for name, shape in shapes.items():
|
290 |
+
|
291 |
+
unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape)
|
292 |
+
total_numel += unpartitioned_numel
|
293 |
+
total_params += 1
|
294 |
+
|
295 |
+
if debug:
|
296 |
+
print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
|
297 |
+
state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
|
298 |
+
offset += unpartitioned_numel
|
299 |
+
|
300 |
+
# Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
|
301 |
+
# avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
|
302 |
+
# paddings performed in the code it's almost impossible to predict the exact numbers w/o the
|
303 |
+
# live optimizer object, so we are checking that the numbers are within the right range
|
304 |
+
align_to = 2 * world_size
|
305 |
+
|
306 |
+
def zero2_align(x):
|
307 |
+
return align_to * math.ceil(x / align_to)
|
308 |
+
|
309 |
+
if debug:
|
310 |
+
print(f"original offset={offset}, avail_numel={avail_numel}")
|
311 |
+
|
312 |
+
offset = zero2_align(offset)
|
313 |
+
avail_numel = zero2_align(avail_numel)
|
314 |
+
|
315 |
+
if debug:
|
316 |
+
print(f"aligned offset={offset}, avail_numel={avail_numel}")
|
317 |
+
|
318 |
+
# Sanity check
|
319 |
+
if offset != avail_numel:
|
320 |
+
raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
|
321 |
+
|
322 |
+
print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
|
323 |
+
|
324 |
+
|
325 |
+
def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
326 |
+
exclude_frozen_parameters):
|
327 |
+
state_dict = OrderedDict()
|
328 |
+
|
329 |
+
# buffers
|
330 |
+
buffers = zero_model_states[0].buffers
|
331 |
+
state_dict.update(buffers)
|
332 |
+
if debug:
|
333 |
+
print(f"added {len(buffers)} buffers")
|
334 |
+
|
335 |
+
if not exclude_frozen_parameters:
|
336 |
+
_zero2_merge_frozen_params(state_dict, zero_model_states)
|
337 |
+
|
338 |
+
_zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
|
339 |
+
|
340 |
+
# recover shared parameters
|
341 |
+
for pair in zero_model_states[0].shared_params:
|
342 |
+
if pair[1] in state_dict:
|
343 |
+
state_dict[pair[0]] = state_dict[pair[1]]
|
344 |
+
|
345 |
+
return state_dict
|
346 |
+
|
347 |
+
|
348 |
+
def zero3_partitioned_param_info(unpartitioned_numel, world_size):
|
349 |
+
remainder = unpartitioned_numel % world_size
|
350 |
+
padding_numel = (world_size - remainder) if remainder else 0
|
351 |
+
partitioned_numel = math.ceil(unpartitioned_numel / world_size)
|
352 |
+
return partitioned_numel, padding_numel
|
353 |
+
|
354 |
+
|
355 |
+
def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
|
356 |
+
if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
|
357 |
+
return
|
358 |
+
|
359 |
+
if debug:
|
360 |
+
for i in range(world_size):
|
361 |
+
num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
|
362 |
+
print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
|
363 |
+
|
364 |
+
frozen_param_shapes = zero_model_states[0].frozen_param_shapes
|
365 |
+
wanted_params = len(frozen_param_shapes)
|
366 |
+
wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
|
367 |
+
avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
|
368 |
+
print(f'Frozen params: Have {avail_numel} numels to process.')
|
369 |
+
print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
|
370 |
+
|
371 |
+
total_params = 0
|
372 |
+
total_numel = 0
|
373 |
+
for name, shape in zero_model_states[0].frozen_param_shapes.items():
|
374 |
+
total_params += 1
|
375 |
+
unpartitioned_numel = shape.numel()
|
376 |
+
total_numel += unpartitioned_numel
|
377 |
+
|
378 |
+
param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
|
379 |
+
state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
|
380 |
+
|
381 |
+
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
|
382 |
+
|
383 |
+
if debug:
|
384 |
+
print(
|
385 |
+
f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
|
386 |
+
)
|
387 |
+
|
388 |
+
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
|
389 |
+
|
390 |
+
|
391 |
+
class GatheredTensor:
|
392 |
+
"""
|
393 |
+
A pseudo tensor that collects partitioned weights.
|
394 |
+
It is more memory efficient when there are multiple groups.
|
395 |
+
"""
|
396 |
+
|
397 |
+
def __init__(self, flat_groups, flat_groups_offset, offset, partitioned_numel, shape):
|
398 |
+
self.flat_groups = flat_groups
|
399 |
+
self.flat_groups_offset = flat_groups_offset
|
400 |
+
self.offset = offset
|
401 |
+
self.partitioned_numel = partitioned_numel
|
402 |
+
self.shape = shape
|
403 |
+
self.dtype = self.flat_groups[0][0].dtype
|
404 |
+
|
405 |
+
def contiguous(self):
|
406 |
+
"""
|
407 |
+
Merge partitioned weights from flat_groups into a single tensor.
|
408 |
+
"""
|
409 |
+
end_idx = self.offset + self.partitioned_numel
|
410 |
+
world_size = len(self.flat_groups)
|
411 |
+
pad_flat_param_chunks = []
|
412 |
+
|
413 |
+
for rank_i in range(world_size):
|
414 |
+
# for each rank, we need to collect weights from related group/groups
|
415 |
+
flat_groups_at_rank_i = self.flat_groups[rank_i]
|
416 |
+
start_group_id = None
|
417 |
+
end_group_id = None
|
418 |
+
for group_id in range(len(self.flat_groups_offset)):
|
419 |
+
if self.flat_groups_offset[group_id] <= self.offset < self.flat_groups_offset[group_id + 1]:
|
420 |
+
start_group_id = group_id
|
421 |
+
if self.flat_groups_offset[group_id] < end_idx <= self.flat_groups_offset[group_id + 1]:
|
422 |
+
end_group_id = group_id
|
423 |
+
break
|
424 |
+
# collect weights from related group/groups
|
425 |
+
for group_id in range(start_group_id, end_group_id + 1):
|
426 |
+
flat_tensor = flat_groups_at_rank_i[group_id]
|
427 |
+
start_offset = self.offset - self.flat_groups_offset[group_id]
|
428 |
+
end_offset = min(end_idx, self.flat_groups_offset[group_id + 1]) - self.flat_groups_offset[group_id]
|
429 |
+
pad_flat_param_chunks.append(flat_tensor[start_offset:end_offset])
|
430 |
+
|
431 |
+
# collect weights from all ranks
|
432 |
+
pad_flat_param = torch.cat(pad_flat_param_chunks, dim=0)
|
433 |
+
param = pad_flat_param[:self.shape.numel()].view(self.shape).contiguous()
|
434 |
+
return param
|
435 |
+
|
436 |
+
|
437 |
+
def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
|
438 |
+
param_shapes = zero_model_states[0].param_shapes
|
439 |
+
avail_numel = sum([flat_group.numel() for flat_group in fp32_flat_groups[0]]) * world_size
|
440 |
+
|
441 |
+
# Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
|
442 |
+
# param, re-consolidating each param, while dealing with padding if any
|
443 |
+
|
444 |
+
# merge list of dicts, preserving order
|
445 |
+
param_shapes = {k: v for d in param_shapes for k, v in d.items()}
|
446 |
+
|
447 |
+
if debug:
|
448 |
+
for i in range(world_size):
|
449 |
+
print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
|
450 |
+
|
451 |
+
wanted_params = len(param_shapes)
|
452 |
+
wanted_numel = sum(shape.numel() for shape in param_shapes.values())
|
453 |
+
# not asserting if there is a mismatch due to possible padding
|
454 |
+
avail_numel = fp32_flat_groups[0].numel() * world_size
|
455 |
+
print(f"Trainable params: Have {avail_numel} numels to process.")
|
456 |
+
print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
|
457 |
+
|
458 |
+
# params
|
459 |
+
# XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
|
460 |
+
# out-of-core computing solution
|
461 |
+
offset = 0
|
462 |
+
total_numel = 0
|
463 |
+
total_params = 0
|
464 |
+
flat_groups_offset = [0] + list(np.cumsum([flat_tensor.numel() for flat_tensor in fp32_flat_groups[0]]))
|
465 |
+
for name, shape in tqdm(param_shapes.items(), desc='Gathering sharded weights'):
|
466 |
+
unpartitioned_numel = shape.numel()
|
467 |
+
total_numel += unpartitioned_numel
|
468 |
+
total_params += 1
|
469 |
+
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
|
470 |
+
|
471 |
+
if debug:
|
472 |
+
print(
|
473 |
+
f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
|
474 |
+
)
|
475 |
+
|
476 |
+
# memory efficient tensor
|
477 |
+
tensor = GatheredTensor(fp32_flat_groups, flat_groups_offset, offset, partitioned_numel, shape)
|
478 |
+
state_dict[name] = tensor
|
479 |
+
offset += partitioned_numel
|
480 |
+
|
481 |
+
offset *= world_size
|
482 |
+
|
483 |
+
# Sanity check
|
484 |
+
if offset != avail_numel:
|
485 |
+
raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
|
486 |
+
|
487 |
+
print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
|
488 |
+
|
489 |
+
|
490 |
+
def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
491 |
+
exclude_frozen_parameters):
|
492 |
+
state_dict = OrderedDict()
|
493 |
+
|
494 |
+
# buffers
|
495 |
+
buffers = zero_model_states[0].buffers
|
496 |
+
state_dict.update(buffers)
|
497 |
+
if debug:
|
498 |
+
print(f"added {len(buffers)} buffers")
|
499 |
+
|
500 |
+
if not exclude_frozen_parameters:
|
501 |
+
_zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
|
502 |
+
|
503 |
+
_zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
|
504 |
+
|
505 |
+
# recover shared parameters
|
506 |
+
for pair in zero_model_states[0].shared_params:
|
507 |
+
if pair[1] in state_dict:
|
508 |
+
state_dict[pair[0]] = state_dict[pair[1]]
|
509 |
+
|
510 |
+
return state_dict
|
511 |
+
|
512 |
+
|
513 |
+
def to_torch_tensor(state_dict, return_empty_tensor=False):
|
514 |
+
"""
|
515 |
+
Convert state_dict of GatheredTensor to torch tensor
|
516 |
+
"""
|
517 |
+
torch_state_dict = {}
|
518 |
+
converted_tensors = {}
|
519 |
+
for name, tensor in state_dict.items():
|
520 |
+
tensor_id = id(tensor)
|
521 |
+
if tensor_id in converted_tensors: # shared tensors
|
522 |
+
shared_tensor = torch_state_dict[converted_tensors[tensor_id]]
|
523 |
+
torch_state_dict[name] = shared_tensor
|
524 |
+
else:
|
525 |
+
converted_tensors[tensor_id] = name
|
526 |
+
if return_empty_tensor:
|
527 |
+
torch_state_dict[name] = torch.empty(tensor.shape, dtype=tensor.dtype)
|
528 |
+
else:
|
529 |
+
torch_state_dict[name] = tensor.contiguous()
|
530 |
+
return torch_state_dict
|
531 |
+
|
532 |
+
|
533 |
+
def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir,
|
534 |
+
tag=None,
|
535 |
+
exclude_frozen_parameters=False,
|
536 |
+
lazy_mode=False):
|
537 |
+
"""
|
538 |
+
Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
|
539 |
+
``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
|
540 |
+
via a model hub.
|
541 |
+
|
542 |
+
Args:
|
543 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder
|
544 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in 'latest' file. e.g., ``global_step14``
|
545 |
+
- ``exclude_frozen_parameters``: exclude frozen parameters
|
546 |
+
- ``lazy_mode``: get state_dict in lazy mode. It returns a dict of pesduo tensor instead of torch tensor, which is more memory efficient.
|
547 |
+
Convert the pesduo tensor to torch tensor by ``.contiguous()``
|
548 |
+
|
549 |
+
Returns:
|
550 |
+
- pytorch ``state_dict``
|
551 |
+
|
552 |
+
A typical usage might be ::
|
553 |
+
|
554 |
+
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
|
555 |
+
# do the training and checkpoint saving
|
556 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
|
557 |
+
model = model.cpu() # move to cpu
|
558 |
+
model.load_state_dict(state_dict)
|
559 |
+
# submit to model hub or save the model to share with others
|
560 |
+
|
561 |
+
In this example the ``model`` will no longer be usable in the deepspeed context of the same
|
562 |
+
application. i.e. you will need to re-initialize the deepspeed engine, since
|
563 |
+
``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
|
564 |
+
|
565 |
+
If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
|
566 |
+
|
567 |
+
Note: the above usage may not work if your application doesn't have sufficient free CPU memory.
|
568 |
+
You may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
|
569 |
+
the checkpoint. Or you can load state_dict in lazy mode ::
|
570 |
+
|
571 |
+
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
|
572 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, lazy_mode=True) # not on cpu
|
573 |
+
for name, lazy_tensor in state_dict.item():
|
574 |
+
tensor = lazy_tensor.contiguous() # to cpu
|
575 |
+
print(name, tensor)
|
576 |
+
# del tensor to release memory if it no longer in use
|
577 |
+
"""
|
578 |
+
if tag is None:
|
579 |
+
latest_path = os.path.join(checkpoint_dir, 'latest')
|
580 |
+
if os.path.isfile(latest_path):
|
581 |
+
with open(latest_path, 'r') as fd:
|
582 |
+
tag = fd.read().strip()
|
583 |
+
else:
|
584 |
+
raise ValueError(f"Unable to find 'latest' file at {latest_path}")
|
585 |
+
|
586 |
+
ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
|
587 |
+
|
588 |
+
if not os.path.isdir(ds_checkpoint_dir):
|
589 |
+
raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
|
590 |
+
|
591 |
+
state_dict = _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
|
592 |
+
if lazy_mode:
|
593 |
+
return state_dict
|
594 |
+
else:
|
595 |
+
return to_torch_tensor(state_dict)
|
596 |
+
|
597 |
+
|
598 |
+
def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir,
|
599 |
+
output_dir,
|
600 |
+
max_shard_size="5GB",
|
601 |
+
safe_serialization=False,
|
602 |
+
tag=None,
|
603 |
+
exclude_frozen_parameters=False):
|
604 |
+
"""
|
605 |
+
Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
|
606 |
+
loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
|
607 |
+
|
608 |
+
Args:
|
609 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
|
610 |
+
- ``output_dir``: directory to the pytorch fp32 state_dict output files
|
611 |
+
- ``max_shard_size``: the maximum size for a checkpoint before being sharded, default value is 5GB
|
612 |
+
- ``safe_serialization``: whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
|
613 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
|
614 |
+
- ``exclude_frozen_parameters``: exclude frozen parameters
|
615 |
+
"""
|
616 |
+
|
617 |
+
# Dependency pre-check
|
618 |
+
if safe_serialization:
|
619 |
+
try:
|
620 |
+
from safetensors.torch import save_file
|
621 |
+
except ImportError:
|
622 |
+
print('If you want to use `safe_serialization`, please `pip install safetensors`')
|
623 |
+
raise
|
624 |
+
if max_shard_size is not None:
|
625 |
+
try:
|
626 |
+
from huggingface_hub import split_torch_state_dict_into_shards
|
627 |
+
except ImportError:
|
628 |
+
print('If you want to use `max_shard_size`, please `pip install huggingface_hub`')
|
629 |
+
raise
|
630 |
+
|
631 |
+
# Convert zero checkpoint to state_dict
|
632 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir,
|
633 |
+
tag,
|
634 |
+
exclude_frozen_parameters,
|
635 |
+
lazy_mode=True)
|
636 |
+
|
637 |
+
# Shard the model if it is too big.
|
638 |
+
weights_name = "model.safetensors" if safe_serialization else "pytorch_model.bin"
|
639 |
+
if max_shard_size is not None:
|
640 |
+
filename_pattern = weights_name.replace(".bin", "{suffix}.bin").replace(".safetensors", "{suffix}.safetensors")
|
641 |
+
# an memory-efficient approach for sharding
|
642 |
+
empty_state_dict = to_torch_tensor(state_dict, return_empty_tensor=True)
|
643 |
+
state_dict_split = split_torch_state_dict_into_shards(empty_state_dict,
|
644 |
+
filename_pattern=filename_pattern,
|
645 |
+
max_shard_size=max_shard_size)
|
646 |
+
else:
|
647 |
+
from collections import namedtuple
|
648 |
+
StateDictSplit = namedtuple("StateDictSplit", ["is_sharded", "filename_to_tensors"])
|
649 |
+
state_dict_split = StateDictSplit(is_sharded=False,
|
650 |
+
filename_to_tensors={weights_name: list(state_dict.keys())})
|
651 |
+
|
652 |
+
# Save the model by shard
|
653 |
+
os.makedirs(output_dir, exist_ok=True)
|
654 |
+
filename_to_tensors = state_dict_split.filename_to_tensors.items()
|
655 |
+
for shard_file, tensors in tqdm(filename_to_tensors, desc="Saving checkpoint shards"):
|
656 |
+
shard_state_dict = {tensor_name: state_dict[tensor_name] for tensor_name in tensors}
|
657 |
+
shard_state_dict = to_torch_tensor(shard_state_dict)
|
658 |
+
output_path = os.path.join(output_dir, shard_file)
|
659 |
+
if safe_serialization:
|
660 |
+
save_file(shard_state_dict, output_path, metadata={"format": "pt"})
|
661 |
+
else:
|
662 |
+
torch.save(shard_state_dict, output_path)
|
663 |
+
# release the memory of current shard
|
664 |
+
for tensor_name in list(shard_state_dict.keys()):
|
665 |
+
del state_dict[tensor_name]
|
666 |
+
del shard_state_dict[tensor_name]
|
667 |
+
del shard_state_dict
|
668 |
+
gc.collect()
|
669 |
+
|
670 |
+
# Save index if sharded
|
671 |
+
if state_dict_split.is_sharded:
|
672 |
+
index = {
|
673 |
+
"metadata": state_dict_split.metadata,
|
674 |
+
"weight_map": state_dict_split.tensor_to_filename,
|
675 |
+
}
|
676 |
+
save_index_file = "model.safetensors.index.json" if safe_serialization else "pytorch_model.bin.index.json"
|
677 |
+
save_index_file = os.path.join(output_dir, save_index_file)
|
678 |
+
with open(save_index_file, "w", encoding="utf-8") as f:
|
679 |
+
content = json.dumps(index, indent=2, sort_keys=True) + "\n"
|
680 |
+
f.write(content)
|
681 |
+
|
682 |
+
|
683 |
+
def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
|
684 |
+
"""
|
685 |
+
1. Put the provided model to cpu
|
686 |
+
2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
|
687 |
+
3. Load it into the provided model
|
688 |
+
|
689 |
+
Args:
|
690 |
+
- ``model``: the model object to update
|
691 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
|
692 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
|
693 |
+
|
694 |
+
Returns:
|
695 |
+
- ``model`: modified model
|
696 |
+
|
697 |
+
Make sure you have plenty of CPU memory available before you call this function. If you don't
|
698 |
+
have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
|
699 |
+
conveniently placed for you in the checkpoint folder.
|
700 |
+
|
701 |
+
A typical usage might be ::
|
702 |
+
|
703 |
+
from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
|
704 |
+
model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
|
705 |
+
# submit to model hub or save the model to share with others
|
706 |
+
|
707 |
+
Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
|
708 |
+
of the same application. i.e. you will need to re-initialize the deepspeed engine, since
|
709 |
+
``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
|
710 |
+
|
711 |
+
"""
|
712 |
+
logger.info(f"Extracting fp32 weights")
|
713 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
|
714 |
+
|
715 |
+
logger.info(f"Overwriting model with fp32 weights")
|
716 |
+
model = model.cpu()
|
717 |
+
model.load_state_dict(state_dict, strict=False)
|
718 |
+
|
719 |
+
return model
|
720 |
+
|
721 |
+
|
722 |
+
if __name__ == "__main__":
|
723 |
+
parser = argparse.ArgumentParser()
|
724 |
+
parser.add_argument("checkpoint_dir",
|
725 |
+
type=str,
|
726 |
+
help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
|
727 |
+
parser.add_argument("output_dir",
|
728 |
+
type=str,
|
729 |
+
help="directory to the pytorch fp32 state_dict output files"
|
730 |
+
"(e.g. path/checkpoint-12-output/)")
|
731 |
+
parser.add_argument(
|
732 |
+
"--max_shard_size",
|
733 |
+
type=str,
|
734 |
+
default="5GB",
|
735 |
+
help="The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size"
|
736 |
+
"lower than this size. If expressed as a string, needs to be digits followed by a unit (like `5MB`"
|
737 |
+
"We default it to 5GB in order for models to be able to run easily on free-tier google colab instances"
|
738 |
+
"without CPU OOM issues.")
|
739 |
+
parser.add_argument(
|
740 |
+
"--safe_serialization",
|
741 |
+
default=False,
|
742 |
+
action='store_true',
|
743 |
+
help="Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).")
|
744 |
+
parser.add_argument("-t",
|
745 |
+
"--tag",
|
746 |
+
type=str,
|
747 |
+
default=None,
|
748 |
+
help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
|
749 |
+
parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters")
|
750 |
+
parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
|
751 |
+
args = parser.parse_args()
|
752 |
+
|
753 |
+
debug = args.debug
|
754 |
+
|
755 |
+
convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir,
|
756 |
+
args.output_dir,
|
757 |
+
max_shard_size=args.max_shard_size,
|
758 |
+
safe_serialization=args.safe_serialization,
|
759 |
+
tag=args.tag,
|
760 |
+
exclude_frozen_parameters=args.exclude_frozen_parameters)
|
checkpoints/step_5300/model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6af91360b36720cb427673d3d611531378c8698713d6565b8bde714726b5e08f
|
3 |
+
size 258323520
|
checkpoints/step_5300/pico_decoder.py
ADDED
@@ -0,0 +1,623 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Pico Decoder: A Lightweight Causal Transformer Language Model
|
3 |
+
|
4 |
+
Pico Decoder uses a simple LLAMA-style transformer architecture, written for clarity and educational purposes.
|
5 |
+
|
6 |
+
Everything is written with a modular design for easy modification and experimentation.
|
7 |
+
|
8 |
+
Key features:
|
9 |
+
- RMSNorm for layer normalization
|
10 |
+
- Rotary Positional Embeddings (RoPE)
|
11 |
+
- Multi-head attention with KV-cache support
|
12 |
+
- SwiGLU activation function
|
13 |
+
- Residual connections throughout
|
14 |
+
|
15 |
+
- KV-cache for faster autoregressive generation
|
16 |
+
|
17 |
+
References:
|
18 |
+
- RoPE: https://arxiv.org/abs/2104.09864
|
19 |
+
- SwiGLU: https://arxiv.org/abs/2002.05202
|
20 |
+
- LLAMA: https://arxiv.org/abs/2302.13971
|
21 |
+
|
22 |
+
Adapted from:
|
23 |
+
- OLMO: https://github.com/allenai/OLMo
|
24 |
+
- LLAMA: https://github.com/meta/llama
|
25 |
+
"""
|
26 |
+
|
27 |
+
from dataclasses import asdict
|
28 |
+
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union
|
29 |
+
|
30 |
+
import torch
|
31 |
+
import torch.nn as nn
|
32 |
+
import torch.nn.functional as F
|
33 |
+
from torch.nn.attention import SDPBackend, sdpa_kernel
|
34 |
+
from transformers import PretrainedConfig, PreTrainedModel
|
35 |
+
from transformers.modeling_outputs import CausalLMOutput, CausalLMOutputWithPast
|
36 |
+
|
37 |
+
try:
|
38 |
+
if TYPE_CHECKING:
|
39 |
+
# We need to do this to avoid importing these when creating the HF-compatible models
|
40 |
+
from src.config import ModelConfig
|
41 |
+
except ImportError:
|
42 |
+
pass
|
43 |
+
|
44 |
+
########################################################
|
45 |
+
#
|
46 |
+
# Layer Normalization
|
47 |
+
#
|
48 |
+
########################################################
|
49 |
+
|
50 |
+
|
51 |
+
class RMSNorm(torch.nn.Module):
|
52 |
+
"""Root Mean Square Layer Normalization.
|
53 |
+
|
54 |
+
A variant of Layer Normalization that uses RMS statistics instead of mean/variance,
|
55 |
+
resulting in improved stability and performance.
|
56 |
+
|
57 |
+
Args:
|
58 |
+
config (Union[ModelConfig, PicoHFConfig]): Configuration object containing normalization parameters
|
59 |
+
- config.norm_eps: Small constant for numerical stability
|
60 |
+
- config.d_model: Model dimension for the weight parameter
|
61 |
+
|
62 |
+
References:
|
63 |
+
https://arxiv.org/abs/1910.07467
|
64 |
+
"""
|
65 |
+
|
66 |
+
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]):
|
67 |
+
super().__init__()
|
68 |
+
self.eps = config.norm_eps
|
69 |
+
self.weight = nn.Parameter(torch.ones(config.d_model))
|
70 |
+
|
71 |
+
def _norm(self, x: torch.Tensor) -> torch.Tensor:
|
72 |
+
"""
|
73 |
+
Normalizes the input tensor by its RMS value.
|
74 |
+
"""
|
75 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
76 |
+
|
77 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
78 |
+
"""
|
79 |
+
Applies RMS normalization to the input tensor and scales it by the weight parameter.
|
80 |
+
"""
|
81 |
+
output = self._norm(x.float()).type_as(x)
|
82 |
+
return output * self.weight
|
83 |
+
|
84 |
+
|
85 |
+
########################################################
|
86 |
+
#
|
87 |
+
# Positional Embedding
|
88 |
+
#
|
89 |
+
########################################################
|
90 |
+
|
91 |
+
|
92 |
+
class RoPE(nn.Module):
|
93 |
+
"""Rotary Positional Embeddings (RoPE).
|
94 |
+
|
95 |
+
Implements position-dependent rotation of keys and queries in attention mechanism,
|
96 |
+
allowing better modeling of relative positions in sequences. Uses complex number
|
97 |
+
operations for efficient rotation.
|
98 |
+
|
99 |
+
Args:
|
100 |
+
config (Union[ModelConfig, PicoHFConfig]): Model configuration containing:
|
101 |
+
- config.position_emb_theta: Base for frequency computation
|
102 |
+
- config.d_model: Model dimension
|
103 |
+
- config.attention_n_heads: Number of attention heads
|
104 |
+
- config.max_seq_len: Maximum sequence length
|
105 |
+
|
106 |
+
References:
|
107 |
+
https://arxiv.org/abs/2104.09864
|
108 |
+
"""
|
109 |
+
|
110 |
+
_freqs_cis_tensor: torch.Tensor | None = None
|
111 |
+
|
112 |
+
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]):
|
113 |
+
super().__init__()
|
114 |
+
|
115 |
+
self.theta = config.position_emb_theta
|
116 |
+
self.dim = config.d_model // config.attention_n_heads
|
117 |
+
|
118 |
+
max_seq_len = config.max_seq_len
|
119 |
+
|
120 |
+
# only gets set once, and then reused for all RoPE instances
|
121 |
+
if RoPE._freqs_cis_tensor is None:
|
122 |
+
RoPE._freqs_cis_tensor = self._setup_freqs_cis(
|
123 |
+
max_seq_len, self.theta, self.dim
|
124 |
+
)
|
125 |
+
|
126 |
+
# register _freqs_cis buffer
|
127 |
+
# can be easily recomputed so persistent=False
|
128 |
+
self.register_buffer("_freqs_cis", self._freqs_cis_tensor, persistent=False)
|
129 |
+
|
130 |
+
@classmethod
|
131 |
+
def _setup_freqs_cis(cls, seq_len: int, theta: float, dim: int) -> torch.Tensor:
|
132 |
+
"""Setup Frequency Tensor for RoPE Embeddings
|
133 |
+
|
134 |
+
Initializes the complex frequency tensor that is used to compute the RoPE embeddings.
|
135 |
+
|
136 |
+
Note other implementations will use cos and sin directly, but using the complex
|
137 |
+
number representation is (probably?) more efficient:
|
138 |
+
|
139 |
+
e^(theta * i * t) = cos(theta * t) + i * sin(theta * t) [Euler's formula]
|
140 |
+
"""
|
141 |
+
_freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
|
142 |
+
positions = torch.arange(seq_len)
|
143 |
+
freqs = torch.outer(positions, _freqs)
|
144 |
+
return torch.polar(torch.ones_like(freqs), freqs) # complex64
|
145 |
+
|
146 |
+
def get_freqs_cis(
|
147 |
+
self, input_shape: torch.Size, start_pos: int, end_pos: int
|
148 |
+
) -> torch.Tensor:
|
149 |
+
"""Reshape Frequency Tensor for RoPE Embeddings
|
150 |
+
|
151 |
+
Makes the frequency tensor broadcastable with the input tensor.
|
152 |
+
"""
|
153 |
+
_freqs_cis = self._freqs_cis[start_pos:end_pos]
|
154 |
+
ndim = len(input_shape)
|
155 |
+
assert 0 <= 1 < ndim
|
156 |
+
assert _freqs_cis.shape == (input_shape[1], input_shape[-1])
|
157 |
+
|
158 |
+
# TODO: Check whether this is correct (might be able to remove this)
|
159 |
+
shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(input_shape)]
|
160 |
+
return _freqs_cis.view(*shape)
|
161 |
+
|
162 |
+
def forward(
|
163 |
+
self,
|
164 |
+
queries: torch.Tensor,
|
165 |
+
keys: torch.Tensor,
|
166 |
+
start_pos: int = 0,
|
167 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
168 |
+
"""Apply RoPE Embeddings to Queries and Keys
|
169 |
+
|
170 |
+
Applies the rotary positional embeddings to the input tensors via complex num multiplication
|
171 |
+
|
172 |
+
NOTE: The start_pos is used if we want to use the kv_cache in the attention mechanism.
|
173 |
+
"""
|
174 |
+
queries_ = torch.view_as_complex(
|
175 |
+
queries.float().reshape(*queries.shape[:-1], -1, 2)
|
176 |
+
)
|
177 |
+
keys_ = torch.view_as_complex(keys.float().reshape(*keys.shape[:-1], -1, 2))
|
178 |
+
|
179 |
+
input_shape = (
|
180 |
+
queries_.shape
|
181 |
+
) # same as keys: (batch_size, seq_len, n_heads, head_dim/2)
|
182 |
+
freqs_start_pos = start_pos
|
183 |
+
freqs_end_pos = freqs_start_pos + queries_.shape[1]
|
184 |
+
|
185 |
+
freqs_cis = self.get_freqs_cis(input_shape, freqs_start_pos, freqs_end_pos)
|
186 |
+
|
187 |
+
queries_rotated = torch.view_as_real(queries_ * freqs_cis).flatten(3)
|
188 |
+
keys_rotated = torch.view_as_real(keys_ * freqs_cis).flatten(3)
|
189 |
+
return queries_rotated.type_as(queries), keys_rotated.type_as(keys)
|
190 |
+
|
191 |
+
|
192 |
+
########################################################
|
193 |
+
#
|
194 |
+
# Attention
|
195 |
+
#
|
196 |
+
########################################################
|
197 |
+
|
198 |
+
|
199 |
+
class Attention(nn.Module):
|
200 |
+
"""Multi-head Attention with Group Query Attention support.
|
201 |
+
|
202 |
+
Implements scaled dot-product attention and supports:
|
203 |
+
- Grouped Query Attention (GQA)
|
204 |
+
- Key-Value caching for efficient inference
|
205 |
+
- RoPE integration
|
206 |
+
|
207 |
+
Args:
|
208 |
+
config (Union[ModelConfig, PretrainedConfig]): Configuration containing:
|
209 |
+
- config.attention_n_heads: Number of attention heads
|
210 |
+
- config.attention_n_kv_heads: Number of key/value heads
|
211 |
+
- config.d_model: Model dimension
|
212 |
+
- config.batch_size: Maximum batch size
|
213 |
+
- config.max_seq_len: Maximum sequence length
|
214 |
+
|
215 |
+
Shape:
|
216 |
+
- Input: (batch_size, seq_len, d_model)
|
217 |
+
- Output: (batch_size, seq_len, d_model)
|
218 |
+
"""
|
219 |
+
|
220 |
+
def __init__(
|
221 |
+
self,
|
222 |
+
config: Union["ModelConfig", "PicoDecoderHFConfig"],
|
223 |
+
):
|
224 |
+
super().__init__()
|
225 |
+
|
226 |
+
self.n_heads = config.attention_n_heads
|
227 |
+
self.n_kv_heads = config.attention_n_kv_heads
|
228 |
+
|
229 |
+
self.batch_size = config.batch_size
|
230 |
+
self.max_seq_len = config.max_seq_len
|
231 |
+
|
232 |
+
d_model = config.d_model
|
233 |
+
self.head_dim = d_model // self.n_heads
|
234 |
+
|
235 |
+
self.n_rep = self.n_heads // self.n_kv_heads
|
236 |
+
|
237 |
+
self.q_proj = nn.Linear(d_model, self.n_heads * self.head_dim, bias=False)
|
238 |
+
self.k_proj = nn.Linear(d_model, self.n_kv_heads * self.head_dim, bias=False)
|
239 |
+
self.v_proj = nn.Linear(d_model, self.n_kv_heads * self.head_dim, bias=False)
|
240 |
+
self.o_proj = nn.Linear(self.n_heads * self.head_dim, d_model, bias=False)
|
241 |
+
|
242 |
+
self.rope = RoPE(config)
|
243 |
+
|
244 |
+
def forward(
|
245 |
+
self,
|
246 |
+
input: torch.Tensor,
|
247 |
+
mask: Optional[torch.Tensor] = None,
|
248 |
+
past_key_values: Optional[Tuple[torch.Tensor, ...]] = None,
|
249 |
+
use_cache: bool = False,
|
250 |
+
) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
|
251 |
+
"""Forward pass for the attention mechanism.
|
252 |
+
|
253 |
+
Computes queries, keys, and values for the attention mechanism. Applies rotary positional
|
254 |
+
embeddings to the queries and keys, and then computes attention scores and outputs.
|
255 |
+
|
256 |
+
For an introduction to the attention mechanism, see:
|
257 |
+
https://arxiv.org/abs/1706.03762
|
258 |
+
|
259 |
+
A few things to note:
|
260 |
+
- The past_key_values is used to implement the KV cache, which is used to speed up
|
261 |
+
generation by caching the KV pairs from previous forward passes. This is useful when doing
|
262 |
+
tasks that require generating multiple tokens conditioned on previous tokens (e.g. language
|
263 |
+
modeling, text generation, etc.). The way the KV cache is implemented is that each layer has
|
264 |
+
its own KV cache - this KV cache is implemented as a tuple.
|
265 |
+
"""
|
266 |
+
bsz, seq_len, _ = input.shape
|
267 |
+
_queries, _keys, _values = (
|
268 |
+
self.q_proj(input),
|
269 |
+
self.k_proj(input),
|
270 |
+
self.v_proj(input),
|
271 |
+
)
|
272 |
+
|
273 |
+
# Reshaping for multi-head attention
|
274 |
+
queries = _queries.view(bsz, seq_len, self.n_heads, self.head_dim)
|
275 |
+
keys = _keys.view(bsz, seq_len, self.n_kv_heads, self.head_dim)
|
276 |
+
values = _values.view(bsz, seq_len, self.n_kv_heads, self.head_dim)
|
277 |
+
|
278 |
+
# The start position is used to apply the RoPE embeddings to only the new tokens
|
279 |
+
# when using the kv_cache in the attention mechanism.
|
280 |
+
# We want to start from the last position in the cache.
|
281 |
+
start_pos = past_key_values[0].shape[1] if past_key_values is not None else 0
|
282 |
+
|
283 |
+
# apply rotary positional embeddings
|
284 |
+
queries, keys = self.rope(queries, keys, start_pos)
|
285 |
+
|
286 |
+
if past_key_values is not None:
|
287 |
+
keys = torch.cat([past_key_values[0], keys], dim=1)
|
288 |
+
values = torch.cat([past_key_values[1], values], dim=1)
|
289 |
+
|
290 |
+
if use_cache:
|
291 |
+
cached_keys = keys
|
292 |
+
cached_values = values
|
293 |
+
else:
|
294 |
+
cached_keys = None
|
295 |
+
cached_values = None
|
296 |
+
|
297 |
+
queries = queries.transpose(1, 2)
|
298 |
+
keys = keys.transpose(1, 2)
|
299 |
+
values = values.transpose(1, 2)
|
300 |
+
|
301 |
+
apply_gqa = self.n_rep > 1
|
302 |
+
if apply_gqa and queries.device.type == "mps":
|
303 |
+
# NOTE: MPS does not support GQA in the SDPA kernel, but we can repeat the keys and values
|
304 |
+
# outside of the kernel to get the same effect.
|
305 |
+
# See: https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html
|
306 |
+
keys = keys.repeat_interleave(self.n_rep, dim=-3)
|
307 |
+
values = values.repeat_interleave(self.n_rep, dim=-3)
|
308 |
+
apply_gqa = False
|
309 |
+
|
310 |
+
backends = [SDPBackend.CUDNN_ATTENTION, SDPBackend.MATH]
|
311 |
+
|
312 |
+
with sdpa_kernel(backends=backends):
|
313 |
+
attn_output = F.scaled_dot_product_attention(
|
314 |
+
queries.contiguous(),
|
315 |
+
keys.contiguous(),
|
316 |
+
values.contiguous(),
|
317 |
+
attn_mask=mask.to(queries.dtype),
|
318 |
+
enable_gqa=apply_gqa,
|
319 |
+
)
|
320 |
+
|
321 |
+
attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, seq_len, -1)
|
322 |
+
output = self.o_proj(attn_output)
|
323 |
+
|
324 |
+
return output, (cached_keys, cached_values)
|
325 |
+
|
326 |
+
|
327 |
+
########################################################
|
328 |
+
#
|
329 |
+
# SwiGLU (Combines MLP and Activation)
|
330 |
+
#
|
331 |
+
########################################################
|
332 |
+
|
333 |
+
|
334 |
+
class SwiGLU(nn.Module):
|
335 |
+
"""SwiGLU Activation Function with Linear Projections.
|
336 |
+
|
337 |
+
Implements the SwiGLU activation function combined with linear transformations,
|
338 |
+
serving as the feed-forward network in transformer blocks.
|
339 |
+
|
340 |
+
Args:
|
341 |
+
config (Union[ModelConfig, PicoDecoderHFConfig]): Configuration containing:
|
342 |
+
- config.d_model: Model dimension
|
343 |
+
- config.activation_hidden_dim: Hidden dimension (typically 4 * d_model)
|
344 |
+
|
345 |
+
References:
|
346 |
+
https://arxiv.org/abs/2002.05202
|
347 |
+
"""
|
348 |
+
|
349 |
+
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]):
|
350 |
+
super().__init__()
|
351 |
+
|
352 |
+
model_dim = config.d_model
|
353 |
+
act_hidden_dim = config.activation_hidden_dim # usually 4 * d_model
|
354 |
+
|
355 |
+
self.w_0 = nn.Linear(model_dim, act_hidden_dim, bias=False)
|
356 |
+
self.w_1 = nn.Linear(model_dim, act_hidden_dim, bias=False)
|
357 |
+
self.w_2 = nn.Linear(act_hidden_dim, model_dim, bias=False)
|
358 |
+
|
359 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
360 |
+
return self.w_2(F.silu(self.w_0(x)) * self.w_1(x))
|
361 |
+
|
362 |
+
|
363 |
+
########################################################
|
364 |
+
#
|
365 |
+
# PicoDecoderBlock
|
366 |
+
#
|
367 |
+
########################################################
|
368 |
+
|
369 |
+
|
370 |
+
class PicoDecoderBlock(nn.Module):
|
371 |
+
"""Single Transformer Block with Attention and Feed-forward layers.
|
372 |
+
|
373 |
+
Implements a standard transformer block with:
|
374 |
+
- Multi-head attention with normalization and residual connection
|
375 |
+
- SwiGLU feed-forward network with normalization and residual connection
|
376 |
+
|
377 |
+
Args:
|
378 |
+
config (Union[ModelConfig, PicoDecoderHFConfig]): Model configuration; either a dataclass or
|
379 |
+
a HuggingFace PicoDecoderHFConfig
|
380 |
+
"""
|
381 |
+
|
382 |
+
def __init__(
|
383 |
+
self,
|
384 |
+
config: Union["ModelConfig", "PicoDecoderHFConfig"],
|
385 |
+
):
|
386 |
+
super().__init__()
|
387 |
+
|
388 |
+
self.attention = Attention(config)
|
389 |
+
self.swiglu = SwiGLU(config)
|
390 |
+
self.attention_norm = RMSNorm(config)
|
391 |
+
self.swiglu_norm = RMSNorm(config)
|
392 |
+
|
393 |
+
def forward(
|
394 |
+
self,
|
395 |
+
input: torch.Tensor,
|
396 |
+
mask: Optional[torch.Tensor] = None,
|
397 |
+
past_key_values: Optional[Tuple[torch.Tensor]] = None,
|
398 |
+
use_cache: bool = False,
|
399 |
+
) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
|
400 |
+
attention_output, cached_key_values = self.attention(
|
401 |
+
self.attention_norm(input),
|
402 |
+
mask=mask,
|
403 |
+
past_key_values=past_key_values,
|
404 |
+
use_cache=use_cache,
|
405 |
+
)
|
406 |
+
# NOTE: cached_key_values is None if use_cache is False
|
407 |
+
|
408 |
+
h = input + attention_output
|
409 |
+
out = h + self.swiglu(self.swiglu_norm(h))
|
410 |
+
return out, cached_key_values
|
411 |
+
|
412 |
+
|
413 |
+
########################################################
|
414 |
+
#
|
415 |
+
# Pico Decoder (Causal Transformer Model)
|
416 |
+
#
|
417 |
+
########################################################
|
418 |
+
|
419 |
+
|
420 |
+
class PicoDecoder(nn.Module):
|
421 |
+
"""
|
422 |
+
Pico Decoder: combines the embedding, causal decoder blocks, and output projection into a
|
423 |
+
single autoregressive model.
|
424 |
+
|
425 |
+
For more information on the model, see the classes for the modules that make up the model.
|
426 |
+
"""
|
427 |
+
|
428 |
+
def __init__(
|
429 |
+
self,
|
430 |
+
model_config: Union["ModelConfig", "PicoDecoderHFConfig"],
|
431 |
+
):
|
432 |
+
super().__init__()
|
433 |
+
self.config = model_config
|
434 |
+
|
435 |
+
self.embedding_proj = nn.Embedding(self.config.vocab_size, self.config.d_model)
|
436 |
+
self.layers = nn.ModuleList(
|
437 |
+
[PicoDecoderBlock(self.config) for _ in range(self.config.n_layers)]
|
438 |
+
)
|
439 |
+
self.output_norm = RMSNorm(self.config)
|
440 |
+
self.de_embedding_proj = nn.Linear(
|
441 |
+
self.config.d_model, self.config.vocab_size, bias=False
|
442 |
+
)
|
443 |
+
|
444 |
+
def convert_to_hf_model(self) -> "PicoDecoderHF":
|
445 |
+
"""Convert the Lightning model to a HuggingFace model."""
|
446 |
+
# Build HF config
|
447 |
+
hf_config = PicoDecoderHFConfig.from_dataclass(self.config)
|
448 |
+
|
449 |
+
# Instantiate the HF-wrapped model
|
450 |
+
hf_model = PicoDecoderHF(hf_config)
|
451 |
+
|
452 |
+
# Grab our full state dict, prefixing module names
|
453 |
+
raw_state = self.state_dict(prefix="pico_decoder.")
|
454 |
+
|
455 |
+
# Only keep keys that exist in the HF model (drops classifier_head, etc.)
|
456 |
+
hf_keys = set(hf_model.state_dict().keys())
|
457 |
+
filtered_state = {k: v for k, v in raw_state.items() if k in hf_keys}
|
458 |
+
|
459 |
+
# Load into HF model, ignore any missing keys
|
460 |
+
hf_model.load_state_dict(filtered_state, strict=False)
|
461 |
+
|
462 |
+
return hf_model
|
463 |
+
|
464 |
+
def forward(
|
465 |
+
self,
|
466 |
+
input_ids: torch.Tensor,
|
467 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
468 |
+
use_cache: bool = False,
|
469 |
+
return_hidden: bool = False,
|
470 |
+
) -> Tuple[torch.Tensor, Optional[Tuple[Tuple[torch.Tensor, torch.Tensor]]]]:
|
471 |
+
"""
|
472 |
+
This is the forward pass for the entire Pico model. It boils down to:
|
473 |
+
- Embedding the input ids
|
474 |
+
- Creating a causal mask
|
475 |
+
- Processing through the pico layers
|
476 |
+
- Projecting the output to logits
|
477 |
+
|
478 |
+
NOTE: One feature that might be confusing is the KV cache. The KV cache is used to speed up
|
479 |
+
generation by caching the KV pairs from previous forward passes. This is useful when doing
|
480 |
+
tasks that require generating multiple tokens conditioned on previous tokens (e.g. language
|
481 |
+
modeling, text generation, etc.). The way the KV cache is implemented is that each layer has
|
482 |
+
its own KV cache which is stored as a tuple. The whole model then stores a tuple of these
|
483 |
+
KV caches (so a tuple of tuples).
|
484 |
+
"""
|
485 |
+
|
486 |
+
seq_len = input_ids.shape[-1]
|
487 |
+
h = self.embedding_proj(input_ids)
|
488 |
+
|
489 |
+
# Calculate start position from past cached KV pairs. Remember that each layer has its
|
490 |
+
# own KV Cache. So when we index past_key_values, we need to index into the KV pairs for the
|
491 |
+
# correct layer and then for either the keys or values.
|
492 |
+
start_pos = 0 if past_key_values is None else past_key_values[0][0].shape[1]
|
493 |
+
|
494 |
+
# Create causal mask for current sequence
|
495 |
+
mask = None
|
496 |
+
if seq_len > 1:
|
497 |
+
mask = torch.full((seq_len, seq_len), float("-inf"))
|
498 |
+
mask = torch.triu(mask, diagonal=1)
|
499 |
+
|
500 |
+
# If using KV cache, extend mask to cover cached sequence length
|
501 |
+
if past_key_values is not None:
|
502 |
+
# Add zeros for cached tokens (we can attend to all of them)
|
503 |
+
mask = torch.hstack([torch.zeros((seq_len, start_pos)), mask])
|
504 |
+
|
505 |
+
mask = mask.to(h.device)
|
506 |
+
|
507 |
+
# NOTE: If we are using the cache, we need to store the cached KV pairs for each layer
|
508 |
+
# in a tuple. Each layer will have its own cached KV pair which we aggregate in a tuple.
|
509 |
+
cached_key_values = () if use_cache else None
|
510 |
+
|
511 |
+
# Process through transformer blocks
|
512 |
+
for idx, layer in enumerate(self.layers):
|
513 |
+
layer_past_key_values = (
|
514 |
+
past_key_values[idx] if past_key_values is not None else None
|
515 |
+
)
|
516 |
+
|
517 |
+
h, layer_cached_key_values = layer(
|
518 |
+
h, mask=mask, past_key_values=layer_past_key_values, use_cache=use_cache
|
519 |
+
)
|
520 |
+
|
521 |
+
if use_cache:
|
522 |
+
cached_key_values += (layer_cached_key_values,)
|
523 |
+
|
524 |
+
# Final norm and projection
|
525 |
+
h = self.output_norm(h)
|
526 |
+
|
527 |
+
if return_hidden:
|
528 |
+
return h, cached_key_values
|
529 |
+
|
530 |
+
logits = self.de_embedding_proj(h).float()
|
531 |
+
|
532 |
+
return logits, cached_key_values
|
533 |
+
|
534 |
+
|
535 |
+
########################################################
|
536 |
+
#
|
537 |
+
# HuggingFace Wrapper for the Pico Decoder model.
|
538 |
+
#
|
539 |
+
########################################################
|
540 |
+
|
541 |
+
|
542 |
+
class PicoDecoderHFConfig(PretrainedConfig):
|
543 |
+
"""Config class for the Pico Decoder HuggingFace wrapper."""
|
544 |
+
|
545 |
+
model_type = "pico_decoder"
|
546 |
+
|
547 |
+
@classmethod
|
548 |
+
def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> "PicoDecoderHFConfig":
|
549 |
+
# NOTE The typical from_dict method doesn't actually set the attributes unless they are
|
550 |
+
# defined in the constructor.
|
551 |
+
|
552 |
+
pico_config = cls(**kwargs)
|
553 |
+
|
554 |
+
# Because this class is just a wrapper around the ModelConfig dataclass, we need to do
|
555 |
+
# a little extra work to ensure that the attributes are actually set.
|
556 |
+
for key, value in config_dict.items():
|
557 |
+
setattr(pico_config, key, value)
|
558 |
+
|
559 |
+
return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
|
560 |
+
unused_kwargs = {
|
561 |
+
key: value for key, value in kwargs.items() if not hasattr(pico_config, key)
|
562 |
+
}
|
563 |
+
|
564 |
+
if return_unused_kwargs:
|
565 |
+
return pico_config, unused_kwargs
|
566 |
+
return pico_config
|
567 |
+
|
568 |
+
@classmethod
|
569 |
+
def from_dataclass(cls, model_config: "ModelConfig"):
|
570 |
+
"""Initialise from our custom config dataclass."""
|
571 |
+
return cls.from_dict(asdict(model_config))
|
572 |
+
|
573 |
+
|
574 |
+
class PicoDecoderHF(PreTrainedModel):
|
575 |
+
"""
|
576 |
+
HuggingFace wrapper for the Pico model.
|
577 |
+
|
578 |
+
Many evaluation frameworks require a model be setup as a HuggingFace model, so we provide a simple
|
579 |
+
wrapper that does just that. When we save checkpoints of the Pico model, we save both the normal
|
580 |
+
Pico model as well as the model wrapped in this HuggingFace class.
|
581 |
+
|
582 |
+
This also lets you do cool things like:
|
583 |
+
|
584 |
+
`model = AutoModelForCausalLM.from_pretrained("path/to/checkpoint")`
|
585 |
+
"""
|
586 |
+
|
587 |
+
config_class = PicoDecoderHFConfig
|
588 |
+
_no_split_modules = ["PicoBlock", "Attention", "SwiGLU", "RMSNorm"]
|
589 |
+
|
590 |
+
def __init__(self, config: PicoDecoderHFConfig):
|
591 |
+
super().__init__(config)
|
592 |
+
self.pico_decoder = PicoDecoder(config)
|
593 |
+
|
594 |
+
def forward(
|
595 |
+
self,
|
596 |
+
input_ids: torch.Tensor,
|
597 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
598 |
+
use_cache: bool = False,
|
599 |
+
**kwargs,
|
600 |
+
) -> Union[CausalLMOutput, CausalLMOutputWithPast]:
|
601 |
+
"""HuggingFace forward pass wrapper.
|
602 |
+
|
603 |
+
Forwards pass for the HuggingFace version of the Pico Model. Basic wrapper around the
|
604 |
+
Pico model's forward pass, and returns the output as a HuggingFace CausalLMOutput.
|
605 |
+
"""
|
606 |
+
logits, past_key_values = self.pico_decoder(
|
607 |
+
input_ids, past_key_values, use_cache
|
608 |
+
)
|
609 |
+
if use_cache:
|
610 |
+
return CausalLMOutputWithPast(
|
611 |
+
logits=logits,
|
612 |
+
past_key_values=past_key_values,
|
613 |
+
)
|
614 |
+
else:
|
615 |
+
return CausalLMOutput(
|
616 |
+
logits=logits,
|
617 |
+
)
|
618 |
+
|
619 |
+
|
620 |
+
# Register for auto classes
|
621 |
+
PicoDecoderHFConfig.register_for_auto_class()
|
622 |
+
PicoDecoderHF.register_for_auto_class("AutoModel")
|
623 |
+
PicoDecoderHF.register_for_auto_class("AutoModelForCausalLM")
|
checkpoints/step_5300/special_tokens_map.json
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"eos_token": {
|
3 |
+
"content": "<|endoftext|>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": false,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"mask_token": {
|
10 |
+
"content": "[MASK]",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": false,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"pad_token": {
|
17 |
+
"content": "<|padding|>",
|
18 |
+
"lstrip": false,
|
19 |
+
"normalized": false,
|
20 |
+
"rstrip": false,
|
21 |
+
"single_word": false
|
22 |
+
}
|
23 |
+
}
|
checkpoints/step_5300/tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
checkpoints/step_5300/tokenizer_config.json
ADDED
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": false,
|
3 |
+
"add_eos_token": false,
|
4 |
+
"add_prefix_space": false,
|
5 |
+
"added_tokens_decoder": {
|
6 |
+
"0": {
|
7 |
+
"content": "|||IP_ADDRESS|||",
|
8 |
+
"lstrip": false,
|
9 |
+
"normalized": true,
|
10 |
+
"rstrip": false,
|
11 |
+
"single_word": false,
|
12 |
+
"special": false
|
13 |
+
},
|
14 |
+
"1": {
|
15 |
+
"content": "<|padding|>",
|
16 |
+
"lstrip": false,
|
17 |
+
"normalized": false,
|
18 |
+
"rstrip": false,
|
19 |
+
"single_word": false,
|
20 |
+
"special": true
|
21 |
+
},
|
22 |
+
"50254": {
|
23 |
+
"content": " ",
|
24 |
+
"lstrip": false,
|
25 |
+
"normalized": true,
|
26 |
+
"rstrip": false,
|
27 |
+
"single_word": false,
|
28 |
+
"special": false
|
29 |
+
},
|
30 |
+
"50255": {
|
31 |
+
"content": " ",
|
32 |
+
"lstrip": false,
|
33 |
+
"normalized": true,
|
34 |
+
"rstrip": false,
|
35 |
+
"single_word": false,
|
36 |
+
"special": false
|
37 |
+
},
|
38 |
+
"50256": {
|
39 |
+
"content": " ",
|
40 |
+
"lstrip": false,
|
41 |
+
"normalized": true,
|
42 |
+
"rstrip": false,
|
43 |
+
"single_word": false,
|
44 |
+
"special": false
|
45 |
+
},
|
46 |
+
"50257": {
|
47 |
+
"content": " ",
|
48 |
+
"lstrip": false,
|
49 |
+
"normalized": true,
|
50 |
+
"rstrip": false,
|
51 |
+
"single_word": false,
|
52 |
+
"special": false
|
53 |
+
},
|
54 |
+
"50258": {
|
55 |
+
"content": " ",
|
56 |
+
"lstrip": false,
|
57 |
+
"normalized": true,
|
58 |
+
"rstrip": false,
|
59 |
+
"single_word": false,
|
60 |
+
"special": false
|
61 |
+
},
|
62 |
+
"50259": {
|
63 |
+
"content": " ",
|
64 |
+
"lstrip": false,
|
65 |
+
"normalized": true,
|
66 |
+
"rstrip": false,
|
67 |
+
"single_word": false,
|
68 |
+
"special": false
|
69 |
+
},
|
70 |
+
"50260": {
|
71 |
+
"content": " ",
|
72 |
+
"lstrip": false,
|
73 |
+
"normalized": true,
|
74 |
+
"rstrip": false,
|
75 |
+
"single_word": false,
|
76 |
+
"special": false
|
77 |
+
},
|
78 |
+
"50261": {
|
79 |
+
"content": " ",
|
80 |
+
"lstrip": false,
|
81 |
+
"normalized": true,
|
82 |
+
"rstrip": false,
|
83 |
+
"single_word": false,
|
84 |
+
"special": false
|
85 |
+
},
|
86 |
+
"50262": {
|
87 |
+
"content": " ",
|
88 |
+
"lstrip": false,
|
89 |
+
"normalized": true,
|
90 |
+
"rstrip": false,
|
91 |
+
"single_word": false,
|
92 |
+
"special": false
|
93 |
+
},
|
94 |
+
"50263": {
|
95 |
+
"content": " ",
|
96 |
+
"lstrip": false,
|
97 |
+
"normalized": true,
|
98 |
+
"rstrip": false,
|
99 |
+
"single_word": false,
|
100 |
+
"special": false
|
101 |
+
},
|
102 |
+
"50264": {
|
103 |
+
"content": " ",
|
104 |
+
"lstrip": false,
|
105 |
+
"normalized": true,
|
106 |
+
"rstrip": false,
|
107 |
+
"single_word": false,
|
108 |
+
"special": false
|
109 |
+
},
|
110 |
+
"50265": {
|
111 |
+
"content": " ",
|
112 |
+
"lstrip": false,
|
113 |
+
"normalized": true,
|
114 |
+
"rstrip": false,
|
115 |
+
"single_word": false,
|
116 |
+
"special": false
|
117 |
+
},
|
118 |
+
"50266": {
|
119 |
+
"content": " ",
|
120 |
+
"lstrip": false,
|
121 |
+
"normalized": true,
|
122 |
+
"rstrip": false,
|
123 |
+
"single_word": false,
|
124 |
+
"special": false
|
125 |
+
},
|
126 |
+
"50267": {
|
127 |
+
"content": " ",
|
128 |
+
"lstrip": false,
|
129 |
+
"normalized": true,
|
130 |
+
"rstrip": false,
|
131 |
+
"single_word": false,
|
132 |
+
"special": false
|
133 |
+
},
|
134 |
+
"50268": {
|
135 |
+
"content": " ",
|
136 |
+
"lstrip": false,
|
137 |
+
"normalized": true,
|
138 |
+
"rstrip": false,
|
139 |
+
"single_word": false,
|
140 |
+
"special": false
|
141 |
+
},
|
142 |
+
"50269": {
|
143 |
+
"content": " ",
|
144 |
+
"lstrip": false,
|
145 |
+
"normalized": true,
|
146 |
+
"rstrip": false,
|
147 |
+
"single_word": false,
|
148 |
+
"special": false
|
149 |
+
},
|
150 |
+
"50270": {
|
151 |
+
"content": " ",
|
152 |
+
"lstrip": false,
|
153 |
+
"normalized": true,
|
154 |
+
"rstrip": false,
|
155 |
+
"single_word": false,
|
156 |
+
"special": false
|
157 |
+
},
|
158 |
+
"50271": {
|
159 |
+
"content": " ",
|
160 |
+
"lstrip": false,
|
161 |
+
"normalized": true,
|
162 |
+
"rstrip": false,
|
163 |
+
"single_word": false,
|
164 |
+
"special": false
|
165 |
+
},
|
166 |
+
"50272": {
|
167 |
+
"content": " ",
|
168 |
+
"lstrip": false,
|
169 |
+
"normalized": true,
|
170 |
+
"rstrip": false,
|
171 |
+
"single_word": false,
|
172 |
+
"special": false
|
173 |
+
},
|
174 |
+
"50273": {
|
175 |
+
"content": " ",
|
176 |
+
"lstrip": false,
|
177 |
+
"normalized": true,
|
178 |
+
"rstrip": false,
|
179 |
+
"single_word": false,
|
180 |
+
"special": false
|
181 |
+
},
|
182 |
+
"50274": {
|
183 |
+
"content": " ",
|
184 |
+
"lstrip": false,
|
185 |
+
"normalized": true,
|
186 |
+
"rstrip": false,
|
187 |
+
"single_word": false,
|
188 |
+
"special": false
|
189 |
+
},
|
190 |
+
"50275": {
|
191 |
+
"content": " ",
|
192 |
+
"lstrip": false,
|
193 |
+
"normalized": true,
|
194 |
+
"rstrip": false,
|
195 |
+
"single_word": false,
|
196 |
+
"special": false
|
197 |
+
},
|
198 |
+
"50276": {
|
199 |
+
"content": " ",
|
200 |
+
"lstrip": false,
|
201 |
+
"normalized": true,
|
202 |
+
"rstrip": false,
|
203 |
+
"single_word": false,
|
204 |
+
"special": false
|
205 |
+
},
|
206 |
+
"50277": {
|
207 |
+
"content": "|||EMAIL_ADDRESS|||",
|
208 |
+
"lstrip": false,
|
209 |
+
"normalized": true,
|
210 |
+
"rstrip": false,
|
211 |
+
"single_word": false,
|
212 |
+
"special": false
|
213 |
+
},
|
214 |
+
"50278": {
|
215 |
+
"content": "|||PHONE_NUMBER|||",
|
216 |
+
"lstrip": false,
|
217 |
+
"normalized": true,
|
218 |
+
"rstrip": false,
|
219 |
+
"single_word": false,
|
220 |
+
"special": false
|
221 |
+
},
|
222 |
+
"50279": {
|
223 |
+
"content": "<|endoftext|>",
|
224 |
+
"lstrip": false,
|
225 |
+
"normalized": false,
|
226 |
+
"rstrip": false,
|
227 |
+
"single_word": false,
|
228 |
+
"special": true
|
229 |
+
},
|
230 |
+
"50280": {
|
231 |
+
"content": "[MASK]",
|
232 |
+
"lstrip": false,
|
233 |
+
"normalized": false,
|
234 |
+
"rstrip": false,
|
235 |
+
"single_word": false,
|
236 |
+
"special": true
|
237 |
+
}
|
238 |
+
},
|
239 |
+
"bos_token": null,
|
240 |
+
"clean_up_tokenization_spaces": true,
|
241 |
+
"eos_token": "<|endoftext|>",
|
242 |
+
"extra_special_tokens": {},
|
243 |
+
"mask_token": "[MASK]",
|
244 |
+
"model_max_length": 1000000000000000019884624838656,
|
245 |
+
"pad_token": "<|padding|>",
|
246 |
+
"tokenizer_class": "GPTNeoXTokenizer",
|
247 |
+
"unk_token": null
|
248 |
+
}
|
checkpoints/step_5400/config.json
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"activation_hidden_dim": 1536,
|
3 |
+
"architectures": [
|
4 |
+
"PicoDecoderHF"
|
5 |
+
],
|
6 |
+
"attention_n_heads": 12,
|
7 |
+
"attention_n_kv_heads": 4,
|
8 |
+
"auto_map": {
|
9 |
+
"AutoConfig": "pico_decoder.PicoDecoderHFConfig",
|
10 |
+
"AutoModelForCausalLM": "pico_decoder.PicoDecoderHF"
|
11 |
+
},
|
12 |
+
"batch_size": 1024,
|
13 |
+
"d_model": 384,
|
14 |
+
"max_seq_len": 512,
|
15 |
+
"model_type": "pico_decoder",
|
16 |
+
"n_layers": 12,
|
17 |
+
"norm_eps": 1e-06,
|
18 |
+
"position_emb_theta": 10000.0,
|
19 |
+
"torch_dtype": "float32",
|
20 |
+
"transformers_version": "4.48.3",
|
21 |
+
"vocab_size": 50281
|
22 |
+
}
|
checkpoints/step_5400/fabric_state/checkpoint/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3bb2974d5d7a309dfb70d05621411367069d349ecfa2b54da2a361d6c51c5e4c
|
3 |
+
size 213443205
|
checkpoints/step_5400/fabric_state/checkpoint/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1c24fcb923e02569ec6d17cc371b12a18c79e63d4b64e37d9abb70c543de1bb6
|
3 |
+
size 213447621
|
checkpoints/step_5400/fabric_state/checkpoint/bf16_zero_pp_rank_2_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1164e4daa4174c3a50e41da74a9e8ee6ff1d861c29946a5fd28fa9880cee66e0
|
3 |
+
size 213445701
|
checkpoints/step_5400/fabric_state/checkpoint/bf16_zero_pp_rank_3_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:799887faf69fa4db010a991ec75fbe3b0eded5dea3d7f7b910173c9f612fffed
|
3 |
+
size 213443589
|
checkpoints/step_5400/fabric_state/checkpoint/mp_rank_00_model_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8f643728d9146644cb97689aff1a6cd27be9b20f64fbf4a437ebd49148fed335
|
3 |
+
size 142325529
|
checkpoints/step_5400/fabric_state/latest
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
checkpoint
|
checkpoints/step_5400/fabric_state/zero_to_fp32.py
ADDED
@@ -0,0 +1,760 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
|
3 |
+
# Copyright (c) Microsoft Corporation.
|
4 |
+
# SPDX-License-Identifier: Apache-2.0
|
5 |
+
|
6 |
+
# DeepSpeed Team
|
7 |
+
|
8 |
+
# This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets
|
9 |
+
# copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
|
10 |
+
# the future. Once extracted, the weights don't require DeepSpeed and can be used in any
|
11 |
+
# application.
|
12 |
+
#
|
13 |
+
# example:
|
14 |
+
# python zero_to_fp32.py . output_dir/
|
15 |
+
# or
|
16 |
+
# python zero_to_fp32.py . output_dir/ --safe_serialization
|
17 |
+
|
18 |
+
import argparse
|
19 |
+
import torch
|
20 |
+
import glob
|
21 |
+
import math
|
22 |
+
import os
|
23 |
+
import re
|
24 |
+
import gc
|
25 |
+
import json
|
26 |
+
import numpy as np
|
27 |
+
from tqdm import tqdm
|
28 |
+
from collections import OrderedDict
|
29 |
+
from dataclasses import dataclass
|
30 |
+
|
31 |
+
# while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
|
32 |
+
# DeepSpeed data structures it has to be available in the current python environment.
|
33 |
+
from deepspeed.utils import logger
|
34 |
+
from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
|
35 |
+
FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
|
36 |
+
FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
|
37 |
+
|
38 |
+
|
39 |
+
@dataclass
|
40 |
+
class zero_model_state:
|
41 |
+
buffers: dict()
|
42 |
+
param_shapes: dict()
|
43 |
+
shared_params: list
|
44 |
+
ds_version: int
|
45 |
+
frozen_param_shapes: dict()
|
46 |
+
frozen_param_fragments: dict()
|
47 |
+
|
48 |
+
|
49 |
+
debug = 0
|
50 |
+
|
51 |
+
# load to cpu
|
52 |
+
device = torch.device('cpu')
|
53 |
+
|
54 |
+
|
55 |
+
def atoi(text):
|
56 |
+
return int(text) if text.isdigit() else text
|
57 |
+
|
58 |
+
|
59 |
+
def natural_keys(text):
|
60 |
+
'''
|
61 |
+
alist.sort(key=natural_keys) sorts in human order
|
62 |
+
http://nedbatchelder.com/blog/200712/human_sorting.html
|
63 |
+
(See Toothy's implementation in the comments)
|
64 |
+
'''
|
65 |
+
return [atoi(c) for c in re.split(r'(\d+)', text)]
|
66 |
+
|
67 |
+
|
68 |
+
def get_model_state_file(checkpoint_dir, zero_stage):
|
69 |
+
if not os.path.isdir(checkpoint_dir):
|
70 |
+
raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
|
71 |
+
|
72 |
+
# there should be only one file
|
73 |
+
if zero_stage <= 2:
|
74 |
+
file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
|
75 |
+
elif zero_stage == 3:
|
76 |
+
file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
|
77 |
+
|
78 |
+
if not os.path.exists(file):
|
79 |
+
raise FileNotFoundError(f"can't find model states file at '{file}'")
|
80 |
+
|
81 |
+
return file
|
82 |
+
|
83 |
+
|
84 |
+
def get_checkpoint_files(checkpoint_dir, glob_pattern):
|
85 |
+
# XXX: need to test that this simple glob rule works for multi-node setup too
|
86 |
+
ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
|
87 |
+
|
88 |
+
if len(ckpt_files) == 0:
|
89 |
+
raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
|
90 |
+
|
91 |
+
return ckpt_files
|
92 |
+
|
93 |
+
|
94 |
+
def get_optim_files(checkpoint_dir):
|
95 |
+
return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
|
96 |
+
|
97 |
+
|
98 |
+
def get_model_state_files(checkpoint_dir):
|
99 |
+
return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
|
100 |
+
|
101 |
+
|
102 |
+
def parse_model_states(files):
|
103 |
+
zero_model_states = []
|
104 |
+
for file in files:
|
105 |
+
state_dict = torch.load(file, map_location=device, weights_only=False)
|
106 |
+
|
107 |
+
if BUFFER_NAMES not in state_dict:
|
108 |
+
raise ValueError(f"{file} is not a model state checkpoint")
|
109 |
+
buffer_names = state_dict[BUFFER_NAMES]
|
110 |
+
if debug:
|
111 |
+
print("Found buffers:", buffer_names)
|
112 |
+
|
113 |
+
# recover just the buffers while restoring them to fp32 if they were saved in fp16
|
114 |
+
buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
|
115 |
+
param_shapes = state_dict[PARAM_SHAPES]
|
116 |
+
|
117 |
+
# collect parameters that are included in param_shapes
|
118 |
+
param_names = []
|
119 |
+
for s in param_shapes:
|
120 |
+
for name in s.keys():
|
121 |
+
param_names.append(name)
|
122 |
+
|
123 |
+
# update with frozen parameters
|
124 |
+
frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
|
125 |
+
if frozen_param_shapes is not None:
|
126 |
+
if debug:
|
127 |
+
print(f"Found frozen_param_shapes: {frozen_param_shapes}")
|
128 |
+
param_names += list(frozen_param_shapes.keys())
|
129 |
+
|
130 |
+
# handle shared params
|
131 |
+
shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
|
132 |
+
|
133 |
+
ds_version = state_dict.get(DS_VERSION, None)
|
134 |
+
|
135 |
+
frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
|
136 |
+
|
137 |
+
z_model_state = zero_model_state(buffers=buffers,
|
138 |
+
param_shapes=param_shapes,
|
139 |
+
shared_params=shared_params,
|
140 |
+
ds_version=ds_version,
|
141 |
+
frozen_param_shapes=frozen_param_shapes,
|
142 |
+
frozen_param_fragments=frozen_param_fragments)
|
143 |
+
zero_model_states.append(z_model_state)
|
144 |
+
|
145 |
+
return zero_model_states
|
146 |
+
|
147 |
+
|
148 |
+
def parse_optim_states(files, ds_checkpoint_dir):
|
149 |
+
total_files = len(files)
|
150 |
+
state_dicts = []
|
151 |
+
for f in tqdm(files, desc='Loading checkpoint shards'):
|
152 |
+
state_dict = torch.load(f, map_location=device, mmap=True, weights_only=False)
|
153 |
+
# immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights
|
154 |
+
# and also handle the case where it was already removed by another helper script
|
155 |
+
state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
|
156 |
+
state_dicts.append(state_dict)
|
157 |
+
|
158 |
+
if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
|
159 |
+
raise ValueError(f"{files[0]} is not a zero checkpoint")
|
160 |
+
zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
|
161 |
+
world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
|
162 |
+
|
163 |
+
# For ZeRO-2 each param group can have different partition_count as data parallelism for expert
|
164 |
+
# parameters can be different from data parallelism for non-expert parameters. So we can just
|
165 |
+
# use the max of the partition_count to get the dp world_size.
|
166 |
+
|
167 |
+
if type(world_size) is list:
|
168 |
+
world_size = max(world_size)
|
169 |
+
|
170 |
+
if world_size != total_files:
|
171 |
+
raise ValueError(
|
172 |
+
f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
|
173 |
+
"Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
|
174 |
+
)
|
175 |
+
|
176 |
+
# the groups are named differently in each stage
|
177 |
+
if zero_stage <= 2:
|
178 |
+
fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
|
179 |
+
elif zero_stage == 3:
|
180 |
+
fp32_groups_key = FP32_FLAT_GROUPS
|
181 |
+
else:
|
182 |
+
raise ValueError(f"unknown zero stage {zero_stage}")
|
183 |
+
|
184 |
+
fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
|
185 |
+
return zero_stage, world_size, fp32_flat_groups
|
186 |
+
|
187 |
+
|
188 |
+
def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters):
|
189 |
+
"""
|
190 |
+
Returns fp32 state_dict reconstructed from ds checkpoint
|
191 |
+
|
192 |
+
Args:
|
193 |
+
- ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
|
194 |
+
|
195 |
+
"""
|
196 |
+
print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
|
197 |
+
|
198 |
+
optim_files = get_optim_files(ds_checkpoint_dir)
|
199 |
+
zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
|
200 |
+
print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
|
201 |
+
|
202 |
+
model_files = get_model_state_files(ds_checkpoint_dir)
|
203 |
+
|
204 |
+
zero_model_states = parse_model_states(model_files)
|
205 |
+
print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
|
206 |
+
|
207 |
+
if zero_stage <= 2:
|
208 |
+
return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
209 |
+
exclude_frozen_parameters)
|
210 |
+
elif zero_stage == 3:
|
211 |
+
return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
212 |
+
exclude_frozen_parameters)
|
213 |
+
|
214 |
+
|
215 |
+
def _zero2_merge_frozen_params(state_dict, zero_model_states):
|
216 |
+
if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
|
217 |
+
return
|
218 |
+
|
219 |
+
frozen_param_shapes = zero_model_states[0].frozen_param_shapes
|
220 |
+
frozen_param_fragments = zero_model_states[0].frozen_param_fragments
|
221 |
+
|
222 |
+
if debug:
|
223 |
+
num_elem = sum(s.numel() for s in frozen_param_shapes.values())
|
224 |
+
print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
|
225 |
+
|
226 |
+
wanted_params = len(frozen_param_shapes)
|
227 |
+
wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
|
228 |
+
avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
|
229 |
+
print(f'Frozen params: Have {avail_numel} numels to process.')
|
230 |
+
print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
|
231 |
+
|
232 |
+
total_params = 0
|
233 |
+
total_numel = 0
|
234 |
+
for name, shape in frozen_param_shapes.items():
|
235 |
+
total_params += 1
|
236 |
+
unpartitioned_numel = shape.numel()
|
237 |
+
total_numel += unpartitioned_numel
|
238 |
+
|
239 |
+
state_dict[name] = frozen_param_fragments[name]
|
240 |
+
|
241 |
+
if debug:
|
242 |
+
print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
|
243 |
+
|
244 |
+
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
|
245 |
+
|
246 |
+
|
247 |
+
def _has_callable(obj, fn):
|
248 |
+
attr = getattr(obj, fn, None)
|
249 |
+
return callable(attr)
|
250 |
+
|
251 |
+
|
252 |
+
def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
|
253 |
+
param_shapes = zero_model_states[0].param_shapes
|
254 |
+
|
255 |
+
# Reconstruction protocol:
|
256 |
+
#
|
257 |
+
# XXX: document this
|
258 |
+
|
259 |
+
if debug:
|
260 |
+
for i in range(world_size):
|
261 |
+
for j in range(len(fp32_flat_groups[0])):
|
262 |
+
print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
|
263 |
+
|
264 |
+
# XXX: memory usage doubles here (zero2)
|
265 |
+
num_param_groups = len(fp32_flat_groups[0])
|
266 |
+
merged_single_partition_of_fp32_groups = []
|
267 |
+
for i in range(num_param_groups):
|
268 |
+
merged_partitions = [sd[i] for sd in fp32_flat_groups]
|
269 |
+
full_single_fp32_vector = torch.cat(merged_partitions, 0)
|
270 |
+
merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
|
271 |
+
avail_numel = sum(
|
272 |
+
[full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
|
273 |
+
|
274 |
+
if debug:
|
275 |
+
wanted_params = sum([len(shapes) for shapes in param_shapes])
|
276 |
+
wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
|
277 |
+
# not asserting if there is a mismatch due to possible padding
|
278 |
+
print(f"Have {avail_numel} numels to process.")
|
279 |
+
print(f"Need {wanted_numel} numels in {wanted_params} params.")
|
280 |
+
|
281 |
+
# params
|
282 |
+
# XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
|
283 |
+
# out-of-core computing solution
|
284 |
+
total_numel = 0
|
285 |
+
total_params = 0
|
286 |
+
for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
|
287 |
+
offset = 0
|
288 |
+
avail_numel = full_single_fp32_vector.numel()
|
289 |
+
for name, shape in shapes.items():
|
290 |
+
|
291 |
+
unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape)
|
292 |
+
total_numel += unpartitioned_numel
|
293 |
+
total_params += 1
|
294 |
+
|
295 |
+
if debug:
|
296 |
+
print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
|
297 |
+
state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
|
298 |
+
offset += unpartitioned_numel
|
299 |
+
|
300 |
+
# Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
|
301 |
+
# avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
|
302 |
+
# paddings performed in the code it's almost impossible to predict the exact numbers w/o the
|
303 |
+
# live optimizer object, so we are checking that the numbers are within the right range
|
304 |
+
align_to = 2 * world_size
|
305 |
+
|
306 |
+
def zero2_align(x):
|
307 |
+
return align_to * math.ceil(x / align_to)
|
308 |
+
|
309 |
+
if debug:
|
310 |
+
print(f"original offset={offset}, avail_numel={avail_numel}")
|
311 |
+
|
312 |
+
offset = zero2_align(offset)
|
313 |
+
avail_numel = zero2_align(avail_numel)
|
314 |
+
|
315 |
+
if debug:
|
316 |
+
print(f"aligned offset={offset}, avail_numel={avail_numel}")
|
317 |
+
|
318 |
+
# Sanity check
|
319 |
+
if offset != avail_numel:
|
320 |
+
raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
|
321 |
+
|
322 |
+
print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
|
323 |
+
|
324 |
+
|
325 |
+
def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
326 |
+
exclude_frozen_parameters):
|
327 |
+
state_dict = OrderedDict()
|
328 |
+
|
329 |
+
# buffers
|
330 |
+
buffers = zero_model_states[0].buffers
|
331 |
+
state_dict.update(buffers)
|
332 |
+
if debug:
|
333 |
+
print(f"added {len(buffers)} buffers")
|
334 |
+
|
335 |
+
if not exclude_frozen_parameters:
|
336 |
+
_zero2_merge_frozen_params(state_dict, zero_model_states)
|
337 |
+
|
338 |
+
_zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
|
339 |
+
|
340 |
+
# recover shared parameters
|
341 |
+
for pair in zero_model_states[0].shared_params:
|
342 |
+
if pair[1] in state_dict:
|
343 |
+
state_dict[pair[0]] = state_dict[pair[1]]
|
344 |
+
|
345 |
+
return state_dict
|
346 |
+
|
347 |
+
|
348 |
+
def zero3_partitioned_param_info(unpartitioned_numel, world_size):
|
349 |
+
remainder = unpartitioned_numel % world_size
|
350 |
+
padding_numel = (world_size - remainder) if remainder else 0
|
351 |
+
partitioned_numel = math.ceil(unpartitioned_numel / world_size)
|
352 |
+
return partitioned_numel, padding_numel
|
353 |
+
|
354 |
+
|
355 |
+
def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
|
356 |
+
if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
|
357 |
+
return
|
358 |
+
|
359 |
+
if debug:
|
360 |
+
for i in range(world_size):
|
361 |
+
num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
|
362 |
+
print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
|
363 |
+
|
364 |
+
frozen_param_shapes = zero_model_states[0].frozen_param_shapes
|
365 |
+
wanted_params = len(frozen_param_shapes)
|
366 |
+
wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
|
367 |
+
avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
|
368 |
+
print(f'Frozen params: Have {avail_numel} numels to process.')
|
369 |
+
print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
|
370 |
+
|
371 |
+
total_params = 0
|
372 |
+
total_numel = 0
|
373 |
+
for name, shape in zero_model_states[0].frozen_param_shapes.items():
|
374 |
+
total_params += 1
|
375 |
+
unpartitioned_numel = shape.numel()
|
376 |
+
total_numel += unpartitioned_numel
|
377 |
+
|
378 |
+
param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
|
379 |
+
state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
|
380 |
+
|
381 |
+
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
|
382 |
+
|
383 |
+
if debug:
|
384 |
+
print(
|
385 |
+
f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
|
386 |
+
)
|
387 |
+
|
388 |
+
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
|
389 |
+
|
390 |
+
|
391 |
+
class GatheredTensor:
|
392 |
+
"""
|
393 |
+
A pseudo tensor that collects partitioned weights.
|
394 |
+
It is more memory efficient when there are multiple groups.
|
395 |
+
"""
|
396 |
+
|
397 |
+
def __init__(self, flat_groups, flat_groups_offset, offset, partitioned_numel, shape):
|
398 |
+
self.flat_groups = flat_groups
|
399 |
+
self.flat_groups_offset = flat_groups_offset
|
400 |
+
self.offset = offset
|
401 |
+
self.partitioned_numel = partitioned_numel
|
402 |
+
self.shape = shape
|
403 |
+
self.dtype = self.flat_groups[0][0].dtype
|
404 |
+
|
405 |
+
def contiguous(self):
|
406 |
+
"""
|
407 |
+
Merge partitioned weights from flat_groups into a single tensor.
|
408 |
+
"""
|
409 |
+
end_idx = self.offset + self.partitioned_numel
|
410 |
+
world_size = len(self.flat_groups)
|
411 |
+
pad_flat_param_chunks = []
|
412 |
+
|
413 |
+
for rank_i in range(world_size):
|
414 |
+
# for each rank, we need to collect weights from related group/groups
|
415 |
+
flat_groups_at_rank_i = self.flat_groups[rank_i]
|
416 |
+
start_group_id = None
|
417 |
+
end_group_id = None
|
418 |
+
for group_id in range(len(self.flat_groups_offset)):
|
419 |
+
if self.flat_groups_offset[group_id] <= self.offset < self.flat_groups_offset[group_id + 1]:
|
420 |
+
start_group_id = group_id
|
421 |
+
if self.flat_groups_offset[group_id] < end_idx <= self.flat_groups_offset[group_id + 1]:
|
422 |
+
end_group_id = group_id
|
423 |
+
break
|
424 |
+
# collect weights from related group/groups
|
425 |
+
for group_id in range(start_group_id, end_group_id + 1):
|
426 |
+
flat_tensor = flat_groups_at_rank_i[group_id]
|
427 |
+
start_offset = self.offset - self.flat_groups_offset[group_id]
|
428 |
+
end_offset = min(end_idx, self.flat_groups_offset[group_id + 1]) - self.flat_groups_offset[group_id]
|
429 |
+
pad_flat_param_chunks.append(flat_tensor[start_offset:end_offset])
|
430 |
+
|
431 |
+
# collect weights from all ranks
|
432 |
+
pad_flat_param = torch.cat(pad_flat_param_chunks, dim=0)
|
433 |
+
param = pad_flat_param[:self.shape.numel()].view(self.shape).contiguous()
|
434 |
+
return param
|
435 |
+
|
436 |
+
|
437 |
+
def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
|
438 |
+
param_shapes = zero_model_states[0].param_shapes
|
439 |
+
avail_numel = sum([flat_group.numel() for flat_group in fp32_flat_groups[0]]) * world_size
|
440 |
+
|
441 |
+
# Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
|
442 |
+
# param, re-consolidating each param, while dealing with padding if any
|
443 |
+
|
444 |
+
# merge list of dicts, preserving order
|
445 |
+
param_shapes = {k: v for d in param_shapes for k, v in d.items()}
|
446 |
+
|
447 |
+
if debug:
|
448 |
+
for i in range(world_size):
|
449 |
+
print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
|
450 |
+
|
451 |
+
wanted_params = len(param_shapes)
|
452 |
+
wanted_numel = sum(shape.numel() for shape in param_shapes.values())
|
453 |
+
# not asserting if there is a mismatch due to possible padding
|
454 |
+
avail_numel = fp32_flat_groups[0].numel() * world_size
|
455 |
+
print(f"Trainable params: Have {avail_numel} numels to process.")
|
456 |
+
print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
|
457 |
+
|
458 |
+
# params
|
459 |
+
# XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
|
460 |
+
# out-of-core computing solution
|
461 |
+
offset = 0
|
462 |
+
total_numel = 0
|
463 |
+
total_params = 0
|
464 |
+
flat_groups_offset = [0] + list(np.cumsum([flat_tensor.numel() for flat_tensor in fp32_flat_groups[0]]))
|
465 |
+
for name, shape in tqdm(param_shapes.items(), desc='Gathering sharded weights'):
|
466 |
+
unpartitioned_numel = shape.numel()
|
467 |
+
total_numel += unpartitioned_numel
|
468 |
+
total_params += 1
|
469 |
+
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
|
470 |
+
|
471 |
+
if debug:
|
472 |
+
print(
|
473 |
+
f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
|
474 |
+
)
|
475 |
+
|
476 |
+
# memory efficient tensor
|
477 |
+
tensor = GatheredTensor(fp32_flat_groups, flat_groups_offset, offset, partitioned_numel, shape)
|
478 |
+
state_dict[name] = tensor
|
479 |
+
offset += partitioned_numel
|
480 |
+
|
481 |
+
offset *= world_size
|
482 |
+
|
483 |
+
# Sanity check
|
484 |
+
if offset != avail_numel:
|
485 |
+
raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
|
486 |
+
|
487 |
+
print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
|
488 |
+
|
489 |
+
|
490 |
+
def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
491 |
+
exclude_frozen_parameters):
|
492 |
+
state_dict = OrderedDict()
|
493 |
+
|
494 |
+
# buffers
|
495 |
+
buffers = zero_model_states[0].buffers
|
496 |
+
state_dict.update(buffers)
|
497 |
+
if debug:
|
498 |
+
print(f"added {len(buffers)} buffers")
|
499 |
+
|
500 |
+
if not exclude_frozen_parameters:
|
501 |
+
_zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
|
502 |
+
|
503 |
+
_zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
|
504 |
+
|
505 |
+
# recover shared parameters
|
506 |
+
for pair in zero_model_states[0].shared_params:
|
507 |
+
if pair[1] in state_dict:
|
508 |
+
state_dict[pair[0]] = state_dict[pair[1]]
|
509 |
+
|
510 |
+
return state_dict
|
511 |
+
|
512 |
+
|
513 |
+
def to_torch_tensor(state_dict, return_empty_tensor=False):
|
514 |
+
"""
|
515 |
+
Convert state_dict of GatheredTensor to torch tensor
|
516 |
+
"""
|
517 |
+
torch_state_dict = {}
|
518 |
+
converted_tensors = {}
|
519 |
+
for name, tensor in state_dict.items():
|
520 |
+
tensor_id = id(tensor)
|
521 |
+
if tensor_id in converted_tensors: # shared tensors
|
522 |
+
shared_tensor = torch_state_dict[converted_tensors[tensor_id]]
|
523 |
+
torch_state_dict[name] = shared_tensor
|
524 |
+
else:
|
525 |
+
converted_tensors[tensor_id] = name
|
526 |
+
if return_empty_tensor:
|
527 |
+
torch_state_dict[name] = torch.empty(tensor.shape, dtype=tensor.dtype)
|
528 |
+
else:
|
529 |
+
torch_state_dict[name] = tensor.contiguous()
|
530 |
+
return torch_state_dict
|
531 |
+
|
532 |
+
|
533 |
+
def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir,
|
534 |
+
tag=None,
|
535 |
+
exclude_frozen_parameters=False,
|
536 |
+
lazy_mode=False):
|
537 |
+
"""
|
538 |
+
Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
|
539 |
+
``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
|
540 |
+
via a model hub.
|
541 |
+
|
542 |
+
Args:
|
543 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder
|
544 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in 'latest' file. e.g., ``global_step14``
|
545 |
+
- ``exclude_frozen_parameters``: exclude frozen parameters
|
546 |
+
- ``lazy_mode``: get state_dict in lazy mode. It returns a dict of pesduo tensor instead of torch tensor, which is more memory efficient.
|
547 |
+
Convert the pesduo tensor to torch tensor by ``.contiguous()``
|
548 |
+
|
549 |
+
Returns:
|
550 |
+
- pytorch ``state_dict``
|
551 |
+
|
552 |
+
A typical usage might be ::
|
553 |
+
|
554 |
+
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
|
555 |
+
# do the training and checkpoint saving
|
556 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
|
557 |
+
model = model.cpu() # move to cpu
|
558 |
+
model.load_state_dict(state_dict)
|
559 |
+
# submit to model hub or save the model to share with others
|
560 |
+
|
561 |
+
In this example the ``model`` will no longer be usable in the deepspeed context of the same
|
562 |
+
application. i.e. you will need to re-initialize the deepspeed engine, since
|
563 |
+
``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
|
564 |
+
|
565 |
+
If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
|
566 |
+
|
567 |
+
Note: the above usage may not work if your application doesn't have sufficient free CPU memory.
|
568 |
+
You may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
|
569 |
+
the checkpoint. Or you can load state_dict in lazy mode ::
|
570 |
+
|
571 |
+
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
|
572 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, lazy_mode=True) # not on cpu
|
573 |
+
for name, lazy_tensor in state_dict.item():
|
574 |
+
tensor = lazy_tensor.contiguous() # to cpu
|
575 |
+
print(name, tensor)
|
576 |
+
# del tensor to release memory if it no longer in use
|
577 |
+
"""
|
578 |
+
if tag is None:
|
579 |
+
latest_path = os.path.join(checkpoint_dir, 'latest')
|
580 |
+
if os.path.isfile(latest_path):
|
581 |
+
with open(latest_path, 'r') as fd:
|
582 |
+
tag = fd.read().strip()
|
583 |
+
else:
|
584 |
+
raise ValueError(f"Unable to find 'latest' file at {latest_path}")
|
585 |
+
|
586 |
+
ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
|
587 |
+
|
588 |
+
if not os.path.isdir(ds_checkpoint_dir):
|
589 |
+
raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
|
590 |
+
|
591 |
+
state_dict = _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
|
592 |
+
if lazy_mode:
|
593 |
+
return state_dict
|
594 |
+
else:
|
595 |
+
return to_torch_tensor(state_dict)
|
596 |
+
|
597 |
+
|
598 |
+
def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir,
|
599 |
+
output_dir,
|
600 |
+
max_shard_size="5GB",
|
601 |
+
safe_serialization=False,
|
602 |
+
tag=None,
|
603 |
+
exclude_frozen_parameters=False):
|
604 |
+
"""
|
605 |
+
Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
|
606 |
+
loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
|
607 |
+
|
608 |
+
Args:
|
609 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
|
610 |
+
- ``output_dir``: directory to the pytorch fp32 state_dict output files
|
611 |
+
- ``max_shard_size``: the maximum size for a checkpoint before being sharded, default value is 5GB
|
612 |
+
- ``safe_serialization``: whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
|
613 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
|
614 |
+
- ``exclude_frozen_parameters``: exclude frozen parameters
|
615 |
+
"""
|
616 |
+
|
617 |
+
# Dependency pre-check
|
618 |
+
if safe_serialization:
|
619 |
+
try:
|
620 |
+
from safetensors.torch import save_file
|
621 |
+
except ImportError:
|
622 |
+
print('If you want to use `safe_serialization`, please `pip install safetensors`')
|
623 |
+
raise
|
624 |
+
if max_shard_size is not None:
|
625 |
+
try:
|
626 |
+
from huggingface_hub import split_torch_state_dict_into_shards
|
627 |
+
except ImportError:
|
628 |
+
print('If you want to use `max_shard_size`, please `pip install huggingface_hub`')
|
629 |
+
raise
|
630 |
+
|
631 |
+
# Convert zero checkpoint to state_dict
|
632 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir,
|
633 |
+
tag,
|
634 |
+
exclude_frozen_parameters,
|
635 |
+
lazy_mode=True)
|
636 |
+
|
637 |
+
# Shard the model if it is too big.
|
638 |
+
weights_name = "model.safetensors" if safe_serialization else "pytorch_model.bin"
|
639 |
+
if max_shard_size is not None:
|
640 |
+
filename_pattern = weights_name.replace(".bin", "{suffix}.bin").replace(".safetensors", "{suffix}.safetensors")
|
641 |
+
# an memory-efficient approach for sharding
|
642 |
+
empty_state_dict = to_torch_tensor(state_dict, return_empty_tensor=True)
|
643 |
+
state_dict_split = split_torch_state_dict_into_shards(empty_state_dict,
|
644 |
+
filename_pattern=filename_pattern,
|
645 |
+
max_shard_size=max_shard_size)
|
646 |
+
else:
|
647 |
+
from collections import namedtuple
|
648 |
+
StateDictSplit = namedtuple("StateDictSplit", ["is_sharded", "filename_to_tensors"])
|
649 |
+
state_dict_split = StateDictSplit(is_sharded=False,
|
650 |
+
filename_to_tensors={weights_name: list(state_dict.keys())})
|
651 |
+
|
652 |
+
# Save the model by shard
|
653 |
+
os.makedirs(output_dir, exist_ok=True)
|
654 |
+
filename_to_tensors = state_dict_split.filename_to_tensors.items()
|
655 |
+
for shard_file, tensors in tqdm(filename_to_tensors, desc="Saving checkpoint shards"):
|
656 |
+
shard_state_dict = {tensor_name: state_dict[tensor_name] for tensor_name in tensors}
|
657 |
+
shard_state_dict = to_torch_tensor(shard_state_dict)
|
658 |
+
output_path = os.path.join(output_dir, shard_file)
|
659 |
+
if safe_serialization:
|
660 |
+
save_file(shard_state_dict, output_path, metadata={"format": "pt"})
|
661 |
+
else:
|
662 |
+
torch.save(shard_state_dict, output_path)
|
663 |
+
# release the memory of current shard
|
664 |
+
for tensor_name in list(shard_state_dict.keys()):
|
665 |
+
del state_dict[tensor_name]
|
666 |
+
del shard_state_dict[tensor_name]
|
667 |
+
del shard_state_dict
|
668 |
+
gc.collect()
|
669 |
+
|
670 |
+
# Save index if sharded
|
671 |
+
if state_dict_split.is_sharded:
|
672 |
+
index = {
|
673 |
+
"metadata": state_dict_split.metadata,
|
674 |
+
"weight_map": state_dict_split.tensor_to_filename,
|
675 |
+
}
|
676 |
+
save_index_file = "model.safetensors.index.json" if safe_serialization else "pytorch_model.bin.index.json"
|
677 |
+
save_index_file = os.path.join(output_dir, save_index_file)
|
678 |
+
with open(save_index_file, "w", encoding="utf-8") as f:
|
679 |
+
content = json.dumps(index, indent=2, sort_keys=True) + "\n"
|
680 |
+
f.write(content)
|
681 |
+
|
682 |
+
|
683 |
+
def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
|
684 |
+
"""
|
685 |
+
1. Put the provided model to cpu
|
686 |
+
2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
|
687 |
+
3. Load it into the provided model
|
688 |
+
|
689 |
+
Args:
|
690 |
+
- ``model``: the model object to update
|
691 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
|
692 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
|
693 |
+
|
694 |
+
Returns:
|
695 |
+
- ``model`: modified model
|
696 |
+
|
697 |
+
Make sure you have plenty of CPU memory available before you call this function. If you don't
|
698 |
+
have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
|
699 |
+
conveniently placed for you in the checkpoint folder.
|
700 |
+
|
701 |
+
A typical usage might be ::
|
702 |
+
|
703 |
+
from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
|
704 |
+
model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
|
705 |
+
# submit to model hub or save the model to share with others
|
706 |
+
|
707 |
+
Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
|
708 |
+
of the same application. i.e. you will need to re-initialize the deepspeed engine, since
|
709 |
+
``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
|
710 |
+
|
711 |
+
"""
|
712 |
+
logger.info(f"Extracting fp32 weights")
|
713 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
|
714 |
+
|
715 |
+
logger.info(f"Overwriting model with fp32 weights")
|
716 |
+
model = model.cpu()
|
717 |
+
model.load_state_dict(state_dict, strict=False)
|
718 |
+
|
719 |
+
return model
|
720 |
+
|
721 |
+
|
722 |
+
if __name__ == "__main__":
|
723 |
+
parser = argparse.ArgumentParser()
|
724 |
+
parser.add_argument("checkpoint_dir",
|
725 |
+
type=str,
|
726 |
+
help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
|
727 |
+
parser.add_argument("output_dir",
|
728 |
+
type=str,
|
729 |
+
help="directory to the pytorch fp32 state_dict output files"
|
730 |
+
"(e.g. path/checkpoint-12-output/)")
|
731 |
+
parser.add_argument(
|
732 |
+
"--max_shard_size",
|
733 |
+
type=str,
|
734 |
+
default="5GB",
|
735 |
+
help="The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size"
|
736 |
+
"lower than this size. If expressed as a string, needs to be digits followed by a unit (like `5MB`"
|
737 |
+
"We default it to 5GB in order for models to be able to run easily on free-tier google colab instances"
|
738 |
+
"without CPU OOM issues.")
|
739 |
+
parser.add_argument(
|
740 |
+
"--safe_serialization",
|
741 |
+
default=False,
|
742 |
+
action='store_true',
|
743 |
+
help="Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).")
|
744 |
+
parser.add_argument("-t",
|
745 |
+
"--tag",
|
746 |
+
type=str,
|
747 |
+
default=None,
|
748 |
+
help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
|
749 |
+
parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters")
|
750 |
+
parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
|
751 |
+
args = parser.parse_args()
|
752 |
+
|
753 |
+
debug = args.debug
|
754 |
+
|
755 |
+
convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir,
|
756 |
+
args.output_dir,
|
757 |
+
max_shard_size=args.max_shard_size,
|
758 |
+
safe_serialization=args.safe_serialization,
|
759 |
+
tag=args.tag,
|
760 |
+
exclude_frozen_parameters=args.exclude_frozen_parameters)
|
checkpoints/step_5400/model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1d3d8534f6b4788c4ce6ca6ccc61354a31368ce12866d7ef6ca23b3591e1acee
|
3 |
+
size 258323520
|
checkpoints/step_5400/pico_decoder.py
ADDED
@@ -0,0 +1,623 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Pico Decoder: A Lightweight Causal Transformer Language Model
|
3 |
+
|
4 |
+
Pico Decoder uses a simple LLAMA-style transformer architecture, written for clarity and educational purposes.
|
5 |
+
|
6 |
+
Everything is written with a modular design for easy modification and experimentation.
|
7 |
+
|
8 |
+
Key features:
|
9 |
+
- RMSNorm for layer normalization
|
10 |
+
- Rotary Positional Embeddings (RoPE)
|
11 |
+
- Multi-head attention with KV-cache support
|
12 |
+
- SwiGLU activation function
|
13 |
+
- Residual connections throughout
|
14 |
+
|
15 |
+
- KV-cache for faster autoregressive generation
|
16 |
+
|
17 |
+
References:
|
18 |
+
- RoPE: https://arxiv.org/abs/2104.09864
|
19 |
+
- SwiGLU: https://arxiv.org/abs/2002.05202
|
20 |
+
- LLAMA: https://arxiv.org/abs/2302.13971
|
21 |
+
|
22 |
+
Adapted from:
|
23 |
+
- OLMO: https://github.com/allenai/OLMo
|
24 |
+
- LLAMA: https://github.com/meta/llama
|
25 |
+
"""
|
26 |
+
|
27 |
+
from dataclasses import asdict
|
28 |
+
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union
|
29 |
+
|
30 |
+
import torch
|
31 |
+
import torch.nn as nn
|
32 |
+
import torch.nn.functional as F
|
33 |
+
from torch.nn.attention import SDPBackend, sdpa_kernel
|
34 |
+
from transformers import PretrainedConfig, PreTrainedModel
|
35 |
+
from transformers.modeling_outputs import CausalLMOutput, CausalLMOutputWithPast
|
36 |
+
|
37 |
+
try:
|
38 |
+
if TYPE_CHECKING:
|
39 |
+
# We need to do this to avoid importing these when creating the HF-compatible models
|
40 |
+
from src.config import ModelConfig
|
41 |
+
except ImportError:
|
42 |
+
pass
|
43 |
+
|
44 |
+
########################################################
|
45 |
+
#
|
46 |
+
# Layer Normalization
|
47 |
+
#
|
48 |
+
########################################################
|
49 |
+
|
50 |
+
|
51 |
+
class RMSNorm(torch.nn.Module):
|
52 |
+
"""Root Mean Square Layer Normalization.
|
53 |
+
|
54 |
+
A variant of Layer Normalization that uses RMS statistics instead of mean/variance,
|
55 |
+
resulting in improved stability and performance.
|
56 |
+
|
57 |
+
Args:
|
58 |
+
config (Union[ModelConfig, PicoHFConfig]): Configuration object containing normalization parameters
|
59 |
+
- config.norm_eps: Small constant for numerical stability
|
60 |
+
- config.d_model: Model dimension for the weight parameter
|
61 |
+
|
62 |
+
References:
|
63 |
+
https://arxiv.org/abs/1910.07467
|
64 |
+
"""
|
65 |
+
|
66 |
+
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]):
|
67 |
+
super().__init__()
|
68 |
+
self.eps = config.norm_eps
|
69 |
+
self.weight = nn.Parameter(torch.ones(config.d_model))
|
70 |
+
|
71 |
+
def _norm(self, x: torch.Tensor) -> torch.Tensor:
|
72 |
+
"""
|
73 |
+
Normalizes the input tensor by its RMS value.
|
74 |
+
"""
|
75 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
76 |
+
|
77 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
78 |
+
"""
|
79 |
+
Applies RMS normalization to the input tensor and scales it by the weight parameter.
|
80 |
+
"""
|
81 |
+
output = self._norm(x.float()).type_as(x)
|
82 |
+
return output * self.weight
|
83 |
+
|
84 |
+
|
85 |
+
########################################################
|
86 |
+
#
|
87 |
+
# Positional Embedding
|
88 |
+
#
|
89 |
+
########################################################
|
90 |
+
|
91 |
+
|
92 |
+
class RoPE(nn.Module):
|
93 |
+
"""Rotary Positional Embeddings (RoPE).
|
94 |
+
|
95 |
+
Implements position-dependent rotation of keys and queries in attention mechanism,
|
96 |
+
allowing better modeling of relative positions in sequences. Uses complex number
|
97 |
+
operations for efficient rotation.
|
98 |
+
|
99 |
+
Args:
|
100 |
+
config (Union[ModelConfig, PicoHFConfig]): Model configuration containing:
|
101 |
+
- config.position_emb_theta: Base for frequency computation
|
102 |
+
- config.d_model: Model dimension
|
103 |
+
- config.attention_n_heads: Number of attention heads
|
104 |
+
- config.max_seq_len: Maximum sequence length
|
105 |
+
|
106 |
+
References:
|
107 |
+
https://arxiv.org/abs/2104.09864
|
108 |
+
"""
|
109 |
+
|
110 |
+
_freqs_cis_tensor: torch.Tensor | None = None
|
111 |
+
|
112 |
+
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]):
|
113 |
+
super().__init__()
|
114 |
+
|
115 |
+
self.theta = config.position_emb_theta
|
116 |
+
self.dim = config.d_model // config.attention_n_heads
|
117 |
+
|
118 |
+
max_seq_len = config.max_seq_len
|
119 |
+
|
120 |
+
# only gets set once, and then reused for all RoPE instances
|
121 |
+
if RoPE._freqs_cis_tensor is None:
|
122 |
+
RoPE._freqs_cis_tensor = self._setup_freqs_cis(
|
123 |
+
max_seq_len, self.theta, self.dim
|
124 |
+
)
|
125 |
+
|
126 |
+
# register _freqs_cis buffer
|
127 |
+
# can be easily recomputed so persistent=False
|
128 |
+
self.register_buffer("_freqs_cis", self._freqs_cis_tensor, persistent=False)
|
129 |
+
|
130 |
+
@classmethod
|
131 |
+
def _setup_freqs_cis(cls, seq_len: int, theta: float, dim: int) -> torch.Tensor:
|
132 |
+
"""Setup Frequency Tensor for RoPE Embeddings
|
133 |
+
|
134 |
+
Initializes the complex frequency tensor that is used to compute the RoPE embeddings.
|
135 |
+
|
136 |
+
Note other implementations will use cos and sin directly, but using the complex
|
137 |
+
number representation is (probably?) more efficient:
|
138 |
+
|
139 |
+
e^(theta * i * t) = cos(theta * t) + i * sin(theta * t) [Euler's formula]
|
140 |
+
"""
|
141 |
+
_freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
|
142 |
+
positions = torch.arange(seq_len)
|
143 |
+
freqs = torch.outer(positions, _freqs)
|
144 |
+
return torch.polar(torch.ones_like(freqs), freqs) # complex64
|
145 |
+
|
146 |
+
def get_freqs_cis(
|
147 |
+
self, input_shape: torch.Size, start_pos: int, end_pos: int
|
148 |
+
) -> torch.Tensor:
|
149 |
+
"""Reshape Frequency Tensor for RoPE Embeddings
|
150 |
+
|
151 |
+
Makes the frequency tensor broadcastable with the input tensor.
|
152 |
+
"""
|
153 |
+
_freqs_cis = self._freqs_cis[start_pos:end_pos]
|
154 |
+
ndim = len(input_shape)
|
155 |
+
assert 0 <= 1 < ndim
|
156 |
+
assert _freqs_cis.shape == (input_shape[1], input_shape[-1])
|
157 |
+
|
158 |
+
# TODO: Check whether this is correct (might be able to remove this)
|
159 |
+
shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(input_shape)]
|
160 |
+
return _freqs_cis.view(*shape)
|
161 |
+
|
162 |
+
def forward(
|
163 |
+
self,
|
164 |
+
queries: torch.Tensor,
|
165 |
+
keys: torch.Tensor,
|
166 |
+
start_pos: int = 0,
|
167 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
168 |
+
"""Apply RoPE Embeddings to Queries and Keys
|
169 |
+
|
170 |
+
Applies the rotary positional embeddings to the input tensors via complex num multiplication
|
171 |
+
|
172 |
+
NOTE: The start_pos is used if we want to use the kv_cache in the attention mechanism.
|
173 |
+
"""
|
174 |
+
queries_ = torch.view_as_complex(
|
175 |
+
queries.float().reshape(*queries.shape[:-1], -1, 2)
|
176 |
+
)
|
177 |
+
keys_ = torch.view_as_complex(keys.float().reshape(*keys.shape[:-1], -1, 2))
|
178 |
+
|
179 |
+
input_shape = (
|
180 |
+
queries_.shape
|
181 |
+
) # same as keys: (batch_size, seq_len, n_heads, head_dim/2)
|
182 |
+
freqs_start_pos = start_pos
|
183 |
+
freqs_end_pos = freqs_start_pos + queries_.shape[1]
|
184 |
+
|
185 |
+
freqs_cis = self.get_freqs_cis(input_shape, freqs_start_pos, freqs_end_pos)
|
186 |
+
|
187 |
+
queries_rotated = torch.view_as_real(queries_ * freqs_cis).flatten(3)
|
188 |
+
keys_rotated = torch.view_as_real(keys_ * freqs_cis).flatten(3)
|
189 |
+
return queries_rotated.type_as(queries), keys_rotated.type_as(keys)
|
190 |
+
|
191 |
+
|
192 |
+
########################################################
|
193 |
+
#
|
194 |
+
# Attention
|
195 |
+
#
|
196 |
+
########################################################
|
197 |
+
|
198 |
+
|
199 |
+
class Attention(nn.Module):
|
200 |
+
"""Multi-head Attention with Group Query Attention support.
|
201 |
+
|
202 |
+
Implements scaled dot-product attention and supports:
|
203 |
+
- Grouped Query Attention (GQA)
|
204 |
+
- Key-Value caching for efficient inference
|
205 |
+
- RoPE integration
|
206 |
+
|
207 |
+
Args:
|
208 |
+
config (Union[ModelConfig, PretrainedConfig]): Configuration containing:
|
209 |
+
- config.attention_n_heads: Number of attention heads
|
210 |
+
- config.attention_n_kv_heads: Number of key/value heads
|
211 |
+
- config.d_model: Model dimension
|
212 |
+
- config.batch_size: Maximum batch size
|
213 |
+
- config.max_seq_len: Maximum sequence length
|
214 |
+
|
215 |
+
Shape:
|
216 |
+
- Input: (batch_size, seq_len, d_model)
|
217 |
+
- Output: (batch_size, seq_len, d_model)
|
218 |
+
"""
|
219 |
+
|
220 |
+
def __init__(
|
221 |
+
self,
|
222 |
+
config: Union["ModelConfig", "PicoDecoderHFConfig"],
|
223 |
+
):
|
224 |
+
super().__init__()
|
225 |
+
|
226 |
+
self.n_heads = config.attention_n_heads
|
227 |
+
self.n_kv_heads = config.attention_n_kv_heads
|
228 |
+
|
229 |
+
self.batch_size = config.batch_size
|
230 |
+
self.max_seq_len = config.max_seq_len
|
231 |
+
|
232 |
+
d_model = config.d_model
|
233 |
+
self.head_dim = d_model // self.n_heads
|
234 |
+
|
235 |
+
self.n_rep = self.n_heads // self.n_kv_heads
|
236 |
+
|
237 |
+
self.q_proj = nn.Linear(d_model, self.n_heads * self.head_dim, bias=False)
|
238 |
+
self.k_proj = nn.Linear(d_model, self.n_kv_heads * self.head_dim, bias=False)
|
239 |
+
self.v_proj = nn.Linear(d_model, self.n_kv_heads * self.head_dim, bias=False)
|
240 |
+
self.o_proj = nn.Linear(self.n_heads * self.head_dim, d_model, bias=False)
|
241 |
+
|
242 |
+
self.rope = RoPE(config)
|
243 |
+
|
244 |
+
def forward(
|
245 |
+
self,
|
246 |
+
input: torch.Tensor,
|
247 |
+
mask: Optional[torch.Tensor] = None,
|
248 |
+
past_key_values: Optional[Tuple[torch.Tensor, ...]] = None,
|
249 |
+
use_cache: bool = False,
|
250 |
+
) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
|
251 |
+
"""Forward pass for the attention mechanism.
|
252 |
+
|
253 |
+
Computes queries, keys, and values for the attention mechanism. Applies rotary positional
|
254 |
+
embeddings to the queries and keys, and then computes attention scores and outputs.
|
255 |
+
|
256 |
+
For an introduction to the attention mechanism, see:
|
257 |
+
https://arxiv.org/abs/1706.03762
|
258 |
+
|
259 |
+
A few things to note:
|
260 |
+
- The past_key_values is used to implement the KV cache, which is used to speed up
|
261 |
+
generation by caching the KV pairs from previous forward passes. This is useful when doing
|
262 |
+
tasks that require generating multiple tokens conditioned on previous tokens (e.g. language
|
263 |
+
modeling, text generation, etc.). The way the KV cache is implemented is that each layer has
|
264 |
+
its own KV cache - this KV cache is implemented as a tuple.
|
265 |
+
"""
|
266 |
+
bsz, seq_len, _ = input.shape
|
267 |
+
_queries, _keys, _values = (
|
268 |
+
self.q_proj(input),
|
269 |
+
self.k_proj(input),
|
270 |
+
self.v_proj(input),
|
271 |
+
)
|
272 |
+
|
273 |
+
# Reshaping for multi-head attention
|
274 |
+
queries = _queries.view(bsz, seq_len, self.n_heads, self.head_dim)
|
275 |
+
keys = _keys.view(bsz, seq_len, self.n_kv_heads, self.head_dim)
|
276 |
+
values = _values.view(bsz, seq_len, self.n_kv_heads, self.head_dim)
|
277 |
+
|
278 |
+
# The start position is used to apply the RoPE embeddings to only the new tokens
|
279 |
+
# when using the kv_cache in the attention mechanism.
|
280 |
+
# We want to start from the last position in the cache.
|
281 |
+
start_pos = past_key_values[0].shape[1] if past_key_values is not None else 0
|
282 |
+
|
283 |
+
# apply rotary positional embeddings
|
284 |
+
queries, keys = self.rope(queries, keys, start_pos)
|
285 |
+
|
286 |
+
if past_key_values is not None:
|
287 |
+
keys = torch.cat([past_key_values[0], keys], dim=1)
|
288 |
+
values = torch.cat([past_key_values[1], values], dim=1)
|
289 |
+
|
290 |
+
if use_cache:
|
291 |
+
cached_keys = keys
|
292 |
+
cached_values = values
|
293 |
+
else:
|
294 |
+
cached_keys = None
|
295 |
+
cached_values = None
|
296 |
+
|
297 |
+
queries = queries.transpose(1, 2)
|
298 |
+
keys = keys.transpose(1, 2)
|
299 |
+
values = values.transpose(1, 2)
|
300 |
+
|
301 |
+
apply_gqa = self.n_rep > 1
|
302 |
+
if apply_gqa and queries.device.type == "mps":
|
303 |
+
# NOTE: MPS does not support GQA in the SDPA kernel, but we can repeat the keys and values
|
304 |
+
# outside of the kernel to get the same effect.
|
305 |
+
# See: https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html
|
306 |
+
keys = keys.repeat_interleave(self.n_rep, dim=-3)
|
307 |
+
values = values.repeat_interleave(self.n_rep, dim=-3)
|
308 |
+
apply_gqa = False
|
309 |
+
|
310 |
+
backends = [SDPBackend.CUDNN_ATTENTION, SDPBackend.MATH]
|
311 |
+
|
312 |
+
with sdpa_kernel(backends=backends):
|
313 |
+
attn_output = F.scaled_dot_product_attention(
|
314 |
+
queries.contiguous(),
|
315 |
+
keys.contiguous(),
|
316 |
+
values.contiguous(),
|
317 |
+
attn_mask=mask.to(queries.dtype),
|
318 |
+
enable_gqa=apply_gqa,
|
319 |
+
)
|
320 |
+
|
321 |
+
attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, seq_len, -1)
|
322 |
+
output = self.o_proj(attn_output)
|
323 |
+
|
324 |
+
return output, (cached_keys, cached_values)
|
325 |
+
|
326 |
+
|
327 |
+
########################################################
|
328 |
+
#
|
329 |
+
# SwiGLU (Combines MLP and Activation)
|
330 |
+
#
|
331 |
+
########################################################
|
332 |
+
|
333 |
+
|
334 |
+
class SwiGLU(nn.Module):
|
335 |
+
"""SwiGLU Activation Function with Linear Projections.
|
336 |
+
|
337 |
+
Implements the SwiGLU activation function combined with linear transformations,
|
338 |
+
serving as the feed-forward network in transformer blocks.
|
339 |
+
|
340 |
+
Args:
|
341 |
+
config (Union[ModelConfig, PicoDecoderHFConfig]): Configuration containing:
|
342 |
+
- config.d_model: Model dimension
|
343 |
+
- config.activation_hidden_dim: Hidden dimension (typically 4 * d_model)
|
344 |
+
|
345 |
+
References:
|
346 |
+
https://arxiv.org/abs/2002.05202
|
347 |
+
"""
|
348 |
+
|
349 |
+
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]):
|
350 |
+
super().__init__()
|
351 |
+
|
352 |
+
model_dim = config.d_model
|
353 |
+
act_hidden_dim = config.activation_hidden_dim # usually 4 * d_model
|
354 |
+
|
355 |
+
self.w_0 = nn.Linear(model_dim, act_hidden_dim, bias=False)
|
356 |
+
self.w_1 = nn.Linear(model_dim, act_hidden_dim, bias=False)
|
357 |
+
self.w_2 = nn.Linear(act_hidden_dim, model_dim, bias=False)
|
358 |
+
|
359 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
360 |
+
return self.w_2(F.silu(self.w_0(x)) * self.w_1(x))
|
361 |
+
|
362 |
+
|
363 |
+
########################################################
|
364 |
+
#
|
365 |
+
# PicoDecoderBlock
|
366 |
+
#
|
367 |
+
########################################################
|
368 |
+
|
369 |
+
|
370 |
+
class PicoDecoderBlock(nn.Module):
|
371 |
+
"""Single Transformer Block with Attention and Feed-forward layers.
|
372 |
+
|
373 |
+
Implements a standard transformer block with:
|
374 |
+
- Multi-head attention with normalization and residual connection
|
375 |
+
- SwiGLU feed-forward network with normalization and residual connection
|
376 |
+
|
377 |
+
Args:
|
378 |
+
config (Union[ModelConfig, PicoDecoderHFConfig]): Model configuration; either a dataclass or
|
379 |
+
a HuggingFace PicoDecoderHFConfig
|
380 |
+
"""
|
381 |
+
|
382 |
+
def __init__(
|
383 |
+
self,
|
384 |
+
config: Union["ModelConfig", "PicoDecoderHFConfig"],
|
385 |
+
):
|
386 |
+
super().__init__()
|
387 |
+
|
388 |
+
self.attention = Attention(config)
|
389 |
+
self.swiglu = SwiGLU(config)
|
390 |
+
self.attention_norm = RMSNorm(config)
|
391 |
+
self.swiglu_norm = RMSNorm(config)
|
392 |
+
|
393 |
+
def forward(
|
394 |
+
self,
|
395 |
+
input: torch.Tensor,
|
396 |
+
mask: Optional[torch.Tensor] = None,
|
397 |
+
past_key_values: Optional[Tuple[torch.Tensor]] = None,
|
398 |
+
use_cache: bool = False,
|
399 |
+
) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
|
400 |
+
attention_output, cached_key_values = self.attention(
|
401 |
+
self.attention_norm(input),
|
402 |
+
mask=mask,
|
403 |
+
past_key_values=past_key_values,
|
404 |
+
use_cache=use_cache,
|
405 |
+
)
|
406 |
+
# NOTE: cached_key_values is None if use_cache is False
|
407 |
+
|
408 |
+
h = input + attention_output
|
409 |
+
out = h + self.swiglu(self.swiglu_norm(h))
|
410 |
+
return out, cached_key_values
|
411 |
+
|
412 |
+
|
413 |
+
########################################################
|
414 |
+
#
|
415 |
+
# Pico Decoder (Causal Transformer Model)
|
416 |
+
#
|
417 |
+
########################################################
|
418 |
+
|
419 |
+
|
420 |
+
class PicoDecoder(nn.Module):
|
421 |
+
"""
|
422 |
+
Pico Decoder: combines the embedding, causal decoder blocks, and output projection into a
|
423 |
+
single autoregressive model.
|
424 |
+
|
425 |
+
For more information on the model, see the classes for the modules that make up the model.
|
426 |
+
"""
|
427 |
+
|
428 |
+
def __init__(
|
429 |
+
self,
|
430 |
+
model_config: Union["ModelConfig", "PicoDecoderHFConfig"],
|
431 |
+
):
|
432 |
+
super().__init__()
|
433 |
+
self.config = model_config
|
434 |
+
|
435 |
+
self.embedding_proj = nn.Embedding(self.config.vocab_size, self.config.d_model)
|
436 |
+
self.layers = nn.ModuleList(
|
437 |
+
[PicoDecoderBlock(self.config) for _ in range(self.config.n_layers)]
|
438 |
+
)
|
439 |
+
self.output_norm = RMSNorm(self.config)
|
440 |
+
self.de_embedding_proj = nn.Linear(
|
441 |
+
self.config.d_model, self.config.vocab_size, bias=False
|
442 |
+
)
|
443 |
+
|
444 |
+
def convert_to_hf_model(self) -> "PicoDecoderHF":
|
445 |
+
"""Convert the Lightning model to a HuggingFace model."""
|
446 |
+
# Build HF config
|
447 |
+
hf_config = PicoDecoderHFConfig.from_dataclass(self.config)
|
448 |
+
|
449 |
+
# Instantiate the HF-wrapped model
|
450 |
+
hf_model = PicoDecoderHF(hf_config)
|
451 |
+
|
452 |
+
# Grab our full state dict, prefixing module names
|
453 |
+
raw_state = self.state_dict(prefix="pico_decoder.")
|
454 |
+
|
455 |
+
# Only keep keys that exist in the HF model (drops classifier_head, etc.)
|
456 |
+
hf_keys = set(hf_model.state_dict().keys())
|
457 |
+
filtered_state = {k: v for k, v in raw_state.items() if k in hf_keys}
|
458 |
+
|
459 |
+
# Load into HF model, ignore any missing keys
|
460 |
+
hf_model.load_state_dict(filtered_state, strict=False)
|
461 |
+
|
462 |
+
return hf_model
|
463 |
+
|
464 |
+
def forward(
|
465 |
+
self,
|
466 |
+
input_ids: torch.Tensor,
|
467 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
468 |
+
use_cache: bool = False,
|
469 |
+
return_hidden: bool = False,
|
470 |
+
) -> Tuple[torch.Tensor, Optional[Tuple[Tuple[torch.Tensor, torch.Tensor]]]]:
|
471 |
+
"""
|
472 |
+
This is the forward pass for the entire Pico model. It boils down to:
|
473 |
+
- Embedding the input ids
|
474 |
+
- Creating a causal mask
|
475 |
+
- Processing through the pico layers
|
476 |
+
- Projecting the output to logits
|
477 |
+
|
478 |
+
NOTE: One feature that might be confusing is the KV cache. The KV cache is used to speed up
|
479 |
+
generation by caching the KV pairs from previous forward passes. This is useful when doing
|
480 |
+
tasks that require generating multiple tokens conditioned on previous tokens (e.g. language
|
481 |
+
modeling, text generation, etc.). The way the KV cache is implemented is that each layer has
|
482 |
+
its own KV cache which is stored as a tuple. The whole model then stores a tuple of these
|
483 |
+
KV caches (so a tuple of tuples).
|
484 |
+
"""
|
485 |
+
|
486 |
+
seq_len = input_ids.shape[-1]
|
487 |
+
h = self.embedding_proj(input_ids)
|
488 |
+
|
489 |
+
# Calculate start position from past cached KV pairs. Remember that each layer has its
|
490 |
+
# own KV Cache. So when we index past_key_values, we need to index into the KV pairs for the
|
491 |
+
# correct layer and then for either the keys or values.
|
492 |
+
start_pos = 0 if past_key_values is None else past_key_values[0][0].shape[1]
|
493 |
+
|
494 |
+
# Create causal mask for current sequence
|
495 |
+
mask = None
|
496 |
+
if seq_len > 1:
|
497 |
+
mask = torch.full((seq_len, seq_len), float("-inf"))
|
498 |
+
mask = torch.triu(mask, diagonal=1)
|
499 |
+
|
500 |
+
# If using KV cache, extend mask to cover cached sequence length
|
501 |
+
if past_key_values is not None:
|
502 |
+
# Add zeros for cached tokens (we can attend to all of them)
|
503 |
+
mask = torch.hstack([torch.zeros((seq_len, start_pos)), mask])
|
504 |
+
|
505 |
+
mask = mask.to(h.device)
|
506 |
+
|
507 |
+
# NOTE: If we are using the cache, we need to store the cached KV pairs for each layer
|
508 |
+
# in a tuple. Each layer will have its own cached KV pair which we aggregate in a tuple.
|
509 |
+
cached_key_values = () if use_cache else None
|
510 |
+
|
511 |
+
# Process through transformer blocks
|
512 |
+
for idx, layer in enumerate(self.layers):
|
513 |
+
layer_past_key_values = (
|
514 |
+
past_key_values[idx] if past_key_values is not None else None
|
515 |
+
)
|
516 |
+
|
517 |
+
h, layer_cached_key_values = layer(
|
518 |
+
h, mask=mask, past_key_values=layer_past_key_values, use_cache=use_cache
|
519 |
+
)
|
520 |
+
|
521 |
+
if use_cache:
|
522 |
+
cached_key_values += (layer_cached_key_values,)
|
523 |
+
|
524 |
+
# Final norm and projection
|
525 |
+
h = self.output_norm(h)
|
526 |
+
|
527 |
+
if return_hidden:
|
528 |
+
return h, cached_key_values
|
529 |
+
|
530 |
+
logits = self.de_embedding_proj(h).float()
|
531 |
+
|
532 |
+
return logits, cached_key_values
|
533 |
+
|
534 |
+
|
535 |
+
########################################################
|
536 |
+
#
|
537 |
+
# HuggingFace Wrapper for the Pico Decoder model.
|
538 |
+
#
|
539 |
+
########################################################
|
540 |
+
|
541 |
+
|
542 |
+
class PicoDecoderHFConfig(PretrainedConfig):
|
543 |
+
"""Config class for the Pico Decoder HuggingFace wrapper."""
|
544 |
+
|
545 |
+
model_type = "pico_decoder"
|
546 |
+
|
547 |
+
@classmethod
|
548 |
+
def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> "PicoDecoderHFConfig":
|
549 |
+
# NOTE The typical from_dict method doesn't actually set the attributes unless they are
|
550 |
+
# defined in the constructor.
|
551 |
+
|
552 |
+
pico_config = cls(**kwargs)
|
553 |
+
|
554 |
+
# Because this class is just a wrapper around the ModelConfig dataclass, we need to do
|
555 |
+
# a little extra work to ensure that the attributes are actually set.
|
556 |
+
for key, value in config_dict.items():
|
557 |
+
setattr(pico_config, key, value)
|
558 |
+
|
559 |
+
return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
|
560 |
+
unused_kwargs = {
|
561 |
+
key: value for key, value in kwargs.items() if not hasattr(pico_config, key)
|
562 |
+
}
|
563 |
+
|
564 |
+
if return_unused_kwargs:
|
565 |
+
return pico_config, unused_kwargs
|
566 |
+
return pico_config
|
567 |
+
|
568 |
+
@classmethod
|
569 |
+
def from_dataclass(cls, model_config: "ModelConfig"):
|
570 |
+
"""Initialise from our custom config dataclass."""
|
571 |
+
return cls.from_dict(asdict(model_config))
|
572 |
+
|
573 |
+
|
574 |
+
class PicoDecoderHF(PreTrainedModel):
|
575 |
+
"""
|
576 |
+
HuggingFace wrapper for the Pico model.
|
577 |
+
|
578 |
+
Many evaluation frameworks require a model be setup as a HuggingFace model, so we provide a simple
|
579 |
+
wrapper that does just that. When we save checkpoints of the Pico model, we save both the normal
|
580 |
+
Pico model as well as the model wrapped in this HuggingFace class.
|
581 |
+
|
582 |
+
This also lets you do cool things like:
|
583 |
+
|
584 |
+
`model = AutoModelForCausalLM.from_pretrained("path/to/checkpoint")`
|
585 |
+
"""
|
586 |
+
|
587 |
+
config_class = PicoDecoderHFConfig
|
588 |
+
_no_split_modules = ["PicoBlock", "Attention", "SwiGLU", "RMSNorm"]
|
589 |
+
|
590 |
+
def __init__(self, config: PicoDecoderHFConfig):
|
591 |
+
super().__init__(config)
|
592 |
+
self.pico_decoder = PicoDecoder(config)
|
593 |
+
|
594 |
+
def forward(
|
595 |
+
self,
|
596 |
+
input_ids: torch.Tensor,
|
597 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
598 |
+
use_cache: bool = False,
|
599 |
+
**kwargs,
|
600 |
+
) -> Union[CausalLMOutput, CausalLMOutputWithPast]:
|
601 |
+
"""HuggingFace forward pass wrapper.
|
602 |
+
|
603 |
+
Forwards pass for the HuggingFace version of the Pico Model. Basic wrapper around the
|
604 |
+
Pico model's forward pass, and returns the output as a HuggingFace CausalLMOutput.
|
605 |
+
"""
|
606 |
+
logits, past_key_values = self.pico_decoder(
|
607 |
+
input_ids, past_key_values, use_cache
|
608 |
+
)
|
609 |
+
if use_cache:
|
610 |
+
return CausalLMOutputWithPast(
|
611 |
+
logits=logits,
|
612 |
+
past_key_values=past_key_values,
|
613 |
+
)
|
614 |
+
else:
|
615 |
+
return CausalLMOutput(
|
616 |
+
logits=logits,
|
617 |
+
)
|
618 |
+
|
619 |
+
|
620 |
+
# Register for auto classes
|
621 |
+
PicoDecoderHFConfig.register_for_auto_class()
|
622 |
+
PicoDecoderHF.register_for_auto_class("AutoModel")
|
623 |
+
PicoDecoderHF.register_for_auto_class("AutoModelForCausalLM")
|
checkpoints/step_5400/special_tokens_map.json
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"eos_token": {
|
3 |
+
"content": "<|endoftext|>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": false,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"mask_token": {
|
10 |
+
"content": "[MASK]",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": false,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"pad_token": {
|
17 |
+
"content": "<|padding|>",
|
18 |
+
"lstrip": false,
|
19 |
+
"normalized": false,
|
20 |
+
"rstrip": false,
|
21 |
+
"single_word": false
|
22 |
+
}
|
23 |
+
}
|
checkpoints/step_5400/tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
checkpoints/step_5400/tokenizer_config.json
ADDED
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": false,
|
3 |
+
"add_eos_token": false,
|
4 |
+
"add_prefix_space": false,
|
5 |
+
"added_tokens_decoder": {
|
6 |
+
"0": {
|
7 |
+
"content": "|||IP_ADDRESS|||",
|
8 |
+
"lstrip": false,
|
9 |
+
"normalized": true,
|
10 |
+
"rstrip": false,
|
11 |
+
"single_word": false,
|
12 |
+
"special": false
|
13 |
+
},
|
14 |
+
"1": {
|
15 |
+
"content": "<|padding|>",
|
16 |
+
"lstrip": false,
|
17 |
+
"normalized": false,
|
18 |
+
"rstrip": false,
|
19 |
+
"single_word": false,
|
20 |
+
"special": true
|
21 |
+
},
|
22 |
+
"50254": {
|
23 |
+
"content": " ",
|
24 |
+
"lstrip": false,
|
25 |
+
"normalized": true,
|
26 |
+
"rstrip": false,
|
27 |
+
"single_word": false,
|
28 |
+
"special": false
|
29 |
+
},
|
30 |
+
"50255": {
|
31 |
+
"content": " ",
|
32 |
+
"lstrip": false,
|
33 |
+
"normalized": true,
|
34 |
+
"rstrip": false,
|
35 |
+
"single_word": false,
|
36 |
+
"special": false
|
37 |
+
},
|
38 |
+
"50256": {
|
39 |
+
"content": " ",
|
40 |
+
"lstrip": false,
|
41 |
+
"normalized": true,
|
42 |
+
"rstrip": false,
|
43 |
+
"single_word": false,
|
44 |
+
"special": false
|
45 |
+
},
|
46 |
+
"50257": {
|
47 |
+
"content": " ",
|
48 |
+
"lstrip": false,
|
49 |
+
"normalized": true,
|
50 |
+
"rstrip": false,
|
51 |
+
"single_word": false,
|
52 |
+
"special": false
|
53 |
+
},
|
54 |
+
"50258": {
|
55 |
+
"content": " ",
|
56 |
+
"lstrip": false,
|
57 |
+
"normalized": true,
|
58 |
+
"rstrip": false,
|
59 |
+
"single_word": false,
|
60 |
+
"special": false
|
61 |
+
},
|
62 |
+
"50259": {
|
63 |
+
"content": " ",
|
64 |
+
"lstrip": false,
|
65 |
+
"normalized": true,
|
66 |
+
"rstrip": false,
|
67 |
+
"single_word": false,
|
68 |
+
"special": false
|
69 |
+
},
|
70 |
+
"50260": {
|
71 |
+
"content": " ",
|
72 |
+
"lstrip": false,
|
73 |
+
"normalized": true,
|
74 |
+
"rstrip": false,
|
75 |
+
"single_word": false,
|
76 |
+
"special": false
|
77 |
+
},
|
78 |
+
"50261": {
|
79 |
+
"content": " ",
|
80 |
+
"lstrip": false,
|
81 |
+
"normalized": true,
|
82 |
+
"rstrip": false,
|
83 |
+
"single_word": false,
|
84 |
+
"special": false
|
85 |
+
},
|
86 |
+
"50262": {
|
87 |
+
"content": " ",
|
88 |
+
"lstrip": false,
|
89 |
+
"normalized": true,
|
90 |
+
"rstrip": false,
|
91 |
+
"single_word": false,
|
92 |
+
"special": false
|
93 |
+
},
|
94 |
+
"50263": {
|
95 |
+
"content": " ",
|
96 |
+
"lstrip": false,
|
97 |
+
"normalized": true,
|
98 |
+
"rstrip": false,
|
99 |
+
"single_word": false,
|
100 |
+
"special": false
|
101 |
+
},
|
102 |
+
"50264": {
|
103 |
+
"content": " ",
|
104 |
+
"lstrip": false,
|
105 |
+
"normalized": true,
|
106 |
+
"rstrip": false,
|
107 |
+
"single_word": false,
|
108 |
+
"special": false
|
109 |
+
},
|
110 |
+
"50265": {
|
111 |
+
"content": " ",
|
112 |
+
"lstrip": false,
|
113 |
+
"normalized": true,
|
114 |
+
"rstrip": false,
|
115 |
+
"single_word": false,
|
116 |
+
"special": false
|
117 |
+
},
|
118 |
+
"50266": {
|
119 |
+
"content": " ",
|
120 |
+
"lstrip": false,
|
121 |
+
"normalized": true,
|
122 |
+
"rstrip": false,
|
123 |
+
"single_word": false,
|
124 |
+
"special": false
|
125 |
+
},
|
126 |
+
"50267": {
|
127 |
+
"content": " ",
|
128 |
+
"lstrip": false,
|
129 |
+
"normalized": true,
|
130 |
+
"rstrip": false,
|
131 |
+
"single_word": false,
|
132 |
+
"special": false
|
133 |
+
},
|
134 |
+
"50268": {
|
135 |
+
"content": " ",
|
136 |
+
"lstrip": false,
|
137 |
+
"normalized": true,
|
138 |
+
"rstrip": false,
|
139 |
+
"single_word": false,
|
140 |
+
"special": false
|
141 |
+
},
|
142 |
+
"50269": {
|
143 |
+
"content": " ",
|
144 |
+
"lstrip": false,
|
145 |
+
"normalized": true,
|
146 |
+
"rstrip": false,
|
147 |
+
"single_word": false,
|
148 |
+
"special": false
|
149 |
+
},
|
150 |
+
"50270": {
|
151 |
+
"content": " ",
|
152 |
+
"lstrip": false,
|
153 |
+
"normalized": true,
|
154 |
+
"rstrip": false,
|
155 |
+
"single_word": false,
|
156 |
+
"special": false
|
157 |
+
},
|
158 |
+
"50271": {
|
159 |
+
"content": " ",
|
160 |
+
"lstrip": false,
|
161 |
+
"normalized": true,
|
162 |
+
"rstrip": false,
|
163 |
+
"single_word": false,
|
164 |
+
"special": false
|
165 |
+
},
|
166 |
+
"50272": {
|
167 |
+
"content": " ",
|
168 |
+
"lstrip": false,
|
169 |
+
"normalized": true,
|
170 |
+
"rstrip": false,
|
171 |
+
"single_word": false,
|
172 |
+
"special": false
|
173 |
+
},
|
174 |
+
"50273": {
|
175 |
+
"content": " ",
|
176 |
+
"lstrip": false,
|
177 |
+
"normalized": true,
|
178 |
+
"rstrip": false,
|
179 |
+
"single_word": false,
|
180 |
+
"special": false
|
181 |
+
},
|
182 |
+
"50274": {
|
183 |
+
"content": " ",
|
184 |
+
"lstrip": false,
|
185 |
+
"normalized": true,
|
186 |
+
"rstrip": false,
|
187 |
+
"single_word": false,
|
188 |
+
"special": false
|
189 |
+
},
|
190 |
+
"50275": {
|
191 |
+
"content": " ",
|
192 |
+
"lstrip": false,
|
193 |
+
"normalized": true,
|
194 |
+
"rstrip": false,
|
195 |
+
"single_word": false,
|
196 |
+
"special": false
|
197 |
+
},
|
198 |
+
"50276": {
|
199 |
+
"content": " ",
|
200 |
+
"lstrip": false,
|
201 |
+
"normalized": true,
|
202 |
+
"rstrip": false,
|
203 |
+
"single_word": false,
|
204 |
+
"special": false
|
205 |
+
},
|
206 |
+
"50277": {
|
207 |
+
"content": "|||EMAIL_ADDRESS|||",
|
208 |
+
"lstrip": false,
|
209 |
+
"normalized": true,
|
210 |
+
"rstrip": false,
|
211 |
+
"single_word": false,
|
212 |
+
"special": false
|
213 |
+
},
|
214 |
+
"50278": {
|
215 |
+
"content": "|||PHONE_NUMBER|||",
|
216 |
+
"lstrip": false,
|
217 |
+
"normalized": true,
|
218 |
+
"rstrip": false,
|
219 |
+
"single_word": false,
|
220 |
+
"special": false
|
221 |
+
},
|
222 |
+
"50279": {
|
223 |
+
"content": "<|endoftext|>",
|
224 |
+
"lstrip": false,
|
225 |
+
"normalized": false,
|
226 |
+
"rstrip": false,
|
227 |
+
"single_word": false,
|
228 |
+
"special": true
|
229 |
+
},
|
230 |
+
"50280": {
|
231 |
+
"content": "[MASK]",
|
232 |
+
"lstrip": false,
|
233 |
+
"normalized": false,
|
234 |
+
"rstrip": false,
|
235 |
+
"single_word": false,
|
236 |
+
"special": true
|
237 |
+
}
|
238 |
+
},
|
239 |
+
"bos_token": null,
|
240 |
+
"clean_up_tokenization_spaces": true,
|
241 |
+
"eos_token": "<|endoftext|>",
|
242 |
+
"extra_special_tokens": {},
|
243 |
+
"mask_token": "[MASK]",
|
244 |
+
"model_max_length": 1000000000000000019884624838656,
|
245 |
+
"pad_token": "<|padding|>",
|
246 |
+
"tokenizer_class": "GPTNeoXTokenizer",
|
247 |
+
"unk_token": null
|
248 |
+
}
|
checkpoints/step_5500/config.json
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"activation_hidden_dim": 1536,
|
3 |
+
"architectures": [
|
4 |
+
"PicoDecoderHF"
|
5 |
+
],
|
6 |
+
"attention_n_heads": 12,
|
7 |
+
"attention_n_kv_heads": 4,
|
8 |
+
"auto_map": {
|
9 |
+
"AutoConfig": "pico_decoder.PicoDecoderHFConfig",
|
10 |
+
"AutoModelForCausalLM": "pico_decoder.PicoDecoderHF"
|
11 |
+
},
|
12 |
+
"batch_size": 1024,
|
13 |
+
"d_model": 384,
|
14 |
+
"max_seq_len": 512,
|
15 |
+
"model_type": "pico_decoder",
|
16 |
+
"n_layers": 12,
|
17 |
+
"norm_eps": 1e-06,
|
18 |
+
"position_emb_theta": 10000.0,
|
19 |
+
"torch_dtype": "float32",
|
20 |
+
"transformers_version": "4.48.3",
|
21 |
+
"vocab_size": 50281
|
22 |
+
}
|
checkpoints/step_5500/fabric_state/checkpoint/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:42cfb84cd4b9670005de66448b51f322fe2ee3383f4e2af0f577b203cb3be1ad
|
3 |
+
size 213443205
|
checkpoints/step_5500/fabric_state/checkpoint/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:302a06c18d5912123fd9c802a060dfdeb46390adb8900be59c8279203167b24b
|
3 |
+
size 213447621
|
checkpoints/step_5500/fabric_state/checkpoint/bf16_zero_pp_rank_2_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6aa53d8c64a21998f9c22a5173ef2bd2aa51b47ca9c768f6c6e9f4dc3f9a62db
|
3 |
+
size 213445701
|
checkpoints/step_5500/fabric_state/checkpoint/bf16_zero_pp_rank_3_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6c573374b708dccaf59983870aa51ddcea316cc4bf0b3f1a6497698dcae10613
|
3 |
+
size 213443589
|
checkpoints/step_5500/fabric_state/checkpoint/mp_rank_00_model_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:bb1aed7f056a9d362c605072a22a32c1995fead54473ef4553ae1c2697fa3b2b
|
3 |
+
size 142325529
|
checkpoints/step_5500/fabric_state/latest
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
checkpoint
|
checkpoints/step_5500/fabric_state/zero_to_fp32.py
ADDED
@@ -0,0 +1,760 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
|
3 |
+
# Copyright (c) Microsoft Corporation.
|
4 |
+
# SPDX-License-Identifier: Apache-2.0
|
5 |
+
|
6 |
+
# DeepSpeed Team
|
7 |
+
|
8 |
+
# This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets
|
9 |
+
# copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
|
10 |
+
# the future. Once extracted, the weights don't require DeepSpeed and can be used in any
|
11 |
+
# application.
|
12 |
+
#
|
13 |
+
# example:
|
14 |
+
# python zero_to_fp32.py . output_dir/
|
15 |
+
# or
|
16 |
+
# python zero_to_fp32.py . output_dir/ --safe_serialization
|
17 |
+
|
18 |
+
import argparse
|
19 |
+
import torch
|
20 |
+
import glob
|
21 |
+
import math
|
22 |
+
import os
|
23 |
+
import re
|
24 |
+
import gc
|
25 |
+
import json
|
26 |
+
import numpy as np
|
27 |
+
from tqdm import tqdm
|
28 |
+
from collections import OrderedDict
|
29 |
+
from dataclasses import dataclass
|
30 |
+
|
31 |
+
# while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
|
32 |
+
# DeepSpeed data structures it has to be available in the current python environment.
|
33 |
+
from deepspeed.utils import logger
|
34 |
+
from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
|
35 |
+
FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
|
36 |
+
FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
|
37 |
+
|
38 |
+
|
39 |
+
@dataclass
|
40 |
+
class zero_model_state:
|
41 |
+
buffers: dict()
|
42 |
+
param_shapes: dict()
|
43 |
+
shared_params: list
|
44 |
+
ds_version: int
|
45 |
+
frozen_param_shapes: dict()
|
46 |
+
frozen_param_fragments: dict()
|
47 |
+
|
48 |
+
|
49 |
+
debug = 0
|
50 |
+
|
51 |
+
# load to cpu
|
52 |
+
device = torch.device('cpu')
|
53 |
+
|
54 |
+
|
55 |
+
def atoi(text):
|
56 |
+
return int(text) if text.isdigit() else text
|
57 |
+
|
58 |
+
|
59 |
+
def natural_keys(text):
|
60 |
+
'''
|
61 |
+
alist.sort(key=natural_keys) sorts in human order
|
62 |
+
http://nedbatchelder.com/blog/200712/human_sorting.html
|
63 |
+
(See Toothy's implementation in the comments)
|
64 |
+
'''
|
65 |
+
return [atoi(c) for c in re.split(r'(\d+)', text)]
|
66 |
+
|
67 |
+
|
68 |
+
def get_model_state_file(checkpoint_dir, zero_stage):
|
69 |
+
if not os.path.isdir(checkpoint_dir):
|
70 |
+
raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
|
71 |
+
|
72 |
+
# there should be only one file
|
73 |
+
if zero_stage <= 2:
|
74 |
+
file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
|
75 |
+
elif zero_stage == 3:
|
76 |
+
file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
|
77 |
+
|
78 |
+
if not os.path.exists(file):
|
79 |
+
raise FileNotFoundError(f"can't find model states file at '{file}'")
|
80 |
+
|
81 |
+
return file
|
82 |
+
|
83 |
+
|
84 |
+
def get_checkpoint_files(checkpoint_dir, glob_pattern):
|
85 |
+
# XXX: need to test that this simple glob rule works for multi-node setup too
|
86 |
+
ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
|
87 |
+
|
88 |
+
if len(ckpt_files) == 0:
|
89 |
+
raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
|
90 |
+
|
91 |
+
return ckpt_files
|
92 |
+
|
93 |
+
|
94 |
+
def get_optim_files(checkpoint_dir):
|
95 |
+
return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
|
96 |
+
|
97 |
+
|
98 |
+
def get_model_state_files(checkpoint_dir):
|
99 |
+
return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
|
100 |
+
|
101 |
+
|
102 |
+
def parse_model_states(files):
|
103 |
+
zero_model_states = []
|
104 |
+
for file in files:
|
105 |
+
state_dict = torch.load(file, map_location=device, weights_only=False)
|
106 |
+
|
107 |
+
if BUFFER_NAMES not in state_dict:
|
108 |
+
raise ValueError(f"{file} is not a model state checkpoint")
|
109 |
+
buffer_names = state_dict[BUFFER_NAMES]
|
110 |
+
if debug:
|
111 |
+
print("Found buffers:", buffer_names)
|
112 |
+
|
113 |
+
# recover just the buffers while restoring them to fp32 if they were saved in fp16
|
114 |
+
buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
|
115 |
+
param_shapes = state_dict[PARAM_SHAPES]
|
116 |
+
|
117 |
+
# collect parameters that are included in param_shapes
|
118 |
+
param_names = []
|
119 |
+
for s in param_shapes:
|
120 |
+
for name in s.keys():
|
121 |
+
param_names.append(name)
|
122 |
+
|
123 |
+
# update with frozen parameters
|
124 |
+
frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
|
125 |
+
if frozen_param_shapes is not None:
|
126 |
+
if debug:
|
127 |
+
print(f"Found frozen_param_shapes: {frozen_param_shapes}")
|
128 |
+
param_names += list(frozen_param_shapes.keys())
|
129 |
+
|
130 |
+
# handle shared params
|
131 |
+
shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
|
132 |
+
|
133 |
+
ds_version = state_dict.get(DS_VERSION, None)
|
134 |
+
|
135 |
+
frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
|
136 |
+
|
137 |
+
z_model_state = zero_model_state(buffers=buffers,
|
138 |
+
param_shapes=param_shapes,
|
139 |
+
shared_params=shared_params,
|
140 |
+
ds_version=ds_version,
|
141 |
+
frozen_param_shapes=frozen_param_shapes,
|
142 |
+
frozen_param_fragments=frozen_param_fragments)
|
143 |
+
zero_model_states.append(z_model_state)
|
144 |
+
|
145 |
+
return zero_model_states
|
146 |
+
|
147 |
+
|
148 |
+
def parse_optim_states(files, ds_checkpoint_dir):
|
149 |
+
total_files = len(files)
|
150 |
+
state_dicts = []
|
151 |
+
for f in tqdm(files, desc='Loading checkpoint shards'):
|
152 |
+
state_dict = torch.load(f, map_location=device, mmap=True, weights_only=False)
|
153 |
+
# immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights
|
154 |
+
# and also handle the case where it was already removed by another helper script
|
155 |
+
state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
|
156 |
+
state_dicts.append(state_dict)
|
157 |
+
|
158 |
+
if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
|
159 |
+
raise ValueError(f"{files[0]} is not a zero checkpoint")
|
160 |
+
zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
|
161 |
+
world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
|
162 |
+
|
163 |
+
# For ZeRO-2 each param group can have different partition_count as data parallelism for expert
|
164 |
+
# parameters can be different from data parallelism for non-expert parameters. So we can just
|
165 |
+
# use the max of the partition_count to get the dp world_size.
|
166 |
+
|
167 |
+
if type(world_size) is list:
|
168 |
+
world_size = max(world_size)
|
169 |
+
|
170 |
+
if world_size != total_files:
|
171 |
+
raise ValueError(
|
172 |
+
f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
|
173 |
+
"Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
|
174 |
+
)
|
175 |
+
|
176 |
+
# the groups are named differently in each stage
|
177 |
+
if zero_stage <= 2:
|
178 |
+
fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
|
179 |
+
elif zero_stage == 3:
|
180 |
+
fp32_groups_key = FP32_FLAT_GROUPS
|
181 |
+
else:
|
182 |
+
raise ValueError(f"unknown zero stage {zero_stage}")
|
183 |
+
|
184 |
+
fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
|
185 |
+
return zero_stage, world_size, fp32_flat_groups
|
186 |
+
|
187 |
+
|
188 |
+
def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters):
|
189 |
+
"""
|
190 |
+
Returns fp32 state_dict reconstructed from ds checkpoint
|
191 |
+
|
192 |
+
Args:
|
193 |
+
- ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
|
194 |
+
|
195 |
+
"""
|
196 |
+
print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
|
197 |
+
|
198 |
+
optim_files = get_optim_files(ds_checkpoint_dir)
|
199 |
+
zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
|
200 |
+
print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
|
201 |
+
|
202 |
+
model_files = get_model_state_files(ds_checkpoint_dir)
|
203 |
+
|
204 |
+
zero_model_states = parse_model_states(model_files)
|
205 |
+
print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
|
206 |
+
|
207 |
+
if zero_stage <= 2:
|
208 |
+
return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
209 |
+
exclude_frozen_parameters)
|
210 |
+
elif zero_stage == 3:
|
211 |
+
return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
212 |
+
exclude_frozen_parameters)
|
213 |
+
|
214 |
+
|
215 |
+
def _zero2_merge_frozen_params(state_dict, zero_model_states):
|
216 |
+
if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
|
217 |
+
return
|
218 |
+
|
219 |
+
frozen_param_shapes = zero_model_states[0].frozen_param_shapes
|
220 |
+
frozen_param_fragments = zero_model_states[0].frozen_param_fragments
|
221 |
+
|
222 |
+
if debug:
|
223 |
+
num_elem = sum(s.numel() for s in frozen_param_shapes.values())
|
224 |
+
print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
|
225 |
+
|
226 |
+
wanted_params = len(frozen_param_shapes)
|
227 |
+
wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
|
228 |
+
avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
|
229 |
+
print(f'Frozen params: Have {avail_numel} numels to process.')
|
230 |
+
print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
|
231 |
+
|
232 |
+
total_params = 0
|
233 |
+
total_numel = 0
|
234 |
+
for name, shape in frozen_param_shapes.items():
|
235 |
+
total_params += 1
|
236 |
+
unpartitioned_numel = shape.numel()
|
237 |
+
total_numel += unpartitioned_numel
|
238 |
+
|
239 |
+
state_dict[name] = frozen_param_fragments[name]
|
240 |
+
|
241 |
+
if debug:
|
242 |
+
print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
|
243 |
+
|
244 |
+
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
|
245 |
+
|
246 |
+
|
247 |
+
def _has_callable(obj, fn):
|
248 |
+
attr = getattr(obj, fn, None)
|
249 |
+
return callable(attr)
|
250 |
+
|
251 |
+
|
252 |
+
def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
|
253 |
+
param_shapes = zero_model_states[0].param_shapes
|
254 |
+
|
255 |
+
# Reconstruction protocol:
|
256 |
+
#
|
257 |
+
# XXX: document this
|
258 |
+
|
259 |
+
if debug:
|
260 |
+
for i in range(world_size):
|
261 |
+
for j in range(len(fp32_flat_groups[0])):
|
262 |
+
print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
|
263 |
+
|
264 |
+
# XXX: memory usage doubles here (zero2)
|
265 |
+
num_param_groups = len(fp32_flat_groups[0])
|
266 |
+
merged_single_partition_of_fp32_groups = []
|
267 |
+
for i in range(num_param_groups):
|
268 |
+
merged_partitions = [sd[i] for sd in fp32_flat_groups]
|
269 |
+
full_single_fp32_vector = torch.cat(merged_partitions, 0)
|
270 |
+
merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
|
271 |
+
avail_numel = sum(
|
272 |
+
[full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
|
273 |
+
|
274 |
+
if debug:
|
275 |
+
wanted_params = sum([len(shapes) for shapes in param_shapes])
|
276 |
+
wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
|
277 |
+
# not asserting if there is a mismatch due to possible padding
|
278 |
+
print(f"Have {avail_numel} numels to process.")
|
279 |
+
print(f"Need {wanted_numel} numels in {wanted_params} params.")
|
280 |
+
|
281 |
+
# params
|
282 |
+
# XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
|
283 |
+
# out-of-core computing solution
|
284 |
+
total_numel = 0
|
285 |
+
total_params = 0
|
286 |
+
for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
|
287 |
+
offset = 0
|
288 |
+
avail_numel = full_single_fp32_vector.numel()
|
289 |
+
for name, shape in shapes.items():
|
290 |
+
|
291 |
+
unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape)
|
292 |
+
total_numel += unpartitioned_numel
|
293 |
+
total_params += 1
|
294 |
+
|
295 |
+
if debug:
|
296 |
+
print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
|
297 |
+
state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
|
298 |
+
offset += unpartitioned_numel
|
299 |
+
|
300 |
+
# Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
|
301 |
+
# avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
|
302 |
+
# paddings performed in the code it's almost impossible to predict the exact numbers w/o the
|
303 |
+
# live optimizer object, so we are checking that the numbers are within the right range
|
304 |
+
align_to = 2 * world_size
|
305 |
+
|
306 |
+
def zero2_align(x):
|
307 |
+
return align_to * math.ceil(x / align_to)
|
308 |
+
|
309 |
+
if debug:
|
310 |
+
print(f"original offset={offset}, avail_numel={avail_numel}")
|
311 |
+
|
312 |
+
offset = zero2_align(offset)
|
313 |
+
avail_numel = zero2_align(avail_numel)
|
314 |
+
|
315 |
+
if debug:
|
316 |
+
print(f"aligned offset={offset}, avail_numel={avail_numel}")
|
317 |
+
|
318 |
+
# Sanity check
|
319 |
+
if offset != avail_numel:
|
320 |
+
raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
|
321 |
+
|
322 |
+
print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
|
323 |
+
|
324 |
+
|
325 |
+
def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
326 |
+
exclude_frozen_parameters):
|
327 |
+
state_dict = OrderedDict()
|
328 |
+
|
329 |
+
# buffers
|
330 |
+
buffers = zero_model_states[0].buffers
|
331 |
+
state_dict.update(buffers)
|
332 |
+
if debug:
|
333 |
+
print(f"added {len(buffers)} buffers")
|
334 |
+
|
335 |
+
if not exclude_frozen_parameters:
|
336 |
+
_zero2_merge_frozen_params(state_dict, zero_model_states)
|
337 |
+
|
338 |
+
_zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
|
339 |
+
|
340 |
+
# recover shared parameters
|
341 |
+
for pair in zero_model_states[0].shared_params:
|
342 |
+
if pair[1] in state_dict:
|
343 |
+
state_dict[pair[0]] = state_dict[pair[1]]
|
344 |
+
|
345 |
+
return state_dict
|
346 |
+
|
347 |
+
|
348 |
+
def zero3_partitioned_param_info(unpartitioned_numel, world_size):
|
349 |
+
remainder = unpartitioned_numel % world_size
|
350 |
+
padding_numel = (world_size - remainder) if remainder else 0
|
351 |
+
partitioned_numel = math.ceil(unpartitioned_numel / world_size)
|
352 |
+
return partitioned_numel, padding_numel
|
353 |
+
|
354 |
+
|
355 |
+
def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
|
356 |
+
if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
|
357 |
+
return
|
358 |
+
|
359 |
+
if debug:
|
360 |
+
for i in range(world_size):
|
361 |
+
num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
|
362 |
+
print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
|
363 |
+
|
364 |
+
frozen_param_shapes = zero_model_states[0].frozen_param_shapes
|
365 |
+
wanted_params = len(frozen_param_shapes)
|
366 |
+
wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
|
367 |
+
avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
|
368 |
+
print(f'Frozen params: Have {avail_numel} numels to process.')
|
369 |
+
print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
|
370 |
+
|
371 |
+
total_params = 0
|
372 |
+
total_numel = 0
|
373 |
+
for name, shape in zero_model_states[0].frozen_param_shapes.items():
|
374 |
+
total_params += 1
|
375 |
+
unpartitioned_numel = shape.numel()
|
376 |
+
total_numel += unpartitioned_numel
|
377 |
+
|
378 |
+
param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
|
379 |
+
state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
|
380 |
+
|
381 |
+
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
|
382 |
+
|
383 |
+
if debug:
|
384 |
+
print(
|
385 |
+
f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
|
386 |
+
)
|
387 |
+
|
388 |
+
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
|
389 |
+
|
390 |
+
|
391 |
+
class GatheredTensor:
|
392 |
+
"""
|
393 |
+
A pseudo tensor that collects partitioned weights.
|
394 |
+
It is more memory efficient when there are multiple groups.
|
395 |
+
"""
|
396 |
+
|
397 |
+
def __init__(self, flat_groups, flat_groups_offset, offset, partitioned_numel, shape):
|
398 |
+
self.flat_groups = flat_groups
|
399 |
+
self.flat_groups_offset = flat_groups_offset
|
400 |
+
self.offset = offset
|
401 |
+
self.partitioned_numel = partitioned_numel
|
402 |
+
self.shape = shape
|
403 |
+
self.dtype = self.flat_groups[0][0].dtype
|
404 |
+
|
405 |
+
def contiguous(self):
|
406 |
+
"""
|
407 |
+
Merge partitioned weights from flat_groups into a single tensor.
|
408 |
+
"""
|
409 |
+
end_idx = self.offset + self.partitioned_numel
|
410 |
+
world_size = len(self.flat_groups)
|
411 |
+
pad_flat_param_chunks = []
|
412 |
+
|
413 |
+
for rank_i in range(world_size):
|
414 |
+
# for each rank, we need to collect weights from related group/groups
|
415 |
+
flat_groups_at_rank_i = self.flat_groups[rank_i]
|
416 |
+
start_group_id = None
|
417 |
+
end_group_id = None
|
418 |
+
for group_id in range(len(self.flat_groups_offset)):
|
419 |
+
if self.flat_groups_offset[group_id] <= self.offset < self.flat_groups_offset[group_id + 1]:
|
420 |
+
start_group_id = group_id
|
421 |
+
if self.flat_groups_offset[group_id] < end_idx <= self.flat_groups_offset[group_id + 1]:
|
422 |
+
end_group_id = group_id
|
423 |
+
break
|
424 |
+
# collect weights from related group/groups
|
425 |
+
for group_id in range(start_group_id, end_group_id + 1):
|
426 |
+
flat_tensor = flat_groups_at_rank_i[group_id]
|
427 |
+
start_offset = self.offset - self.flat_groups_offset[group_id]
|
428 |
+
end_offset = min(end_idx, self.flat_groups_offset[group_id + 1]) - self.flat_groups_offset[group_id]
|
429 |
+
pad_flat_param_chunks.append(flat_tensor[start_offset:end_offset])
|
430 |
+
|
431 |
+
# collect weights from all ranks
|
432 |
+
pad_flat_param = torch.cat(pad_flat_param_chunks, dim=0)
|
433 |
+
param = pad_flat_param[:self.shape.numel()].view(self.shape).contiguous()
|
434 |
+
return param
|
435 |
+
|
436 |
+
|
437 |
+
def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
|
438 |
+
param_shapes = zero_model_states[0].param_shapes
|
439 |
+
avail_numel = sum([flat_group.numel() for flat_group in fp32_flat_groups[0]]) * world_size
|
440 |
+
|
441 |
+
# Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
|
442 |
+
# param, re-consolidating each param, while dealing with padding if any
|
443 |
+
|
444 |
+
# merge list of dicts, preserving order
|
445 |
+
param_shapes = {k: v for d in param_shapes for k, v in d.items()}
|
446 |
+
|
447 |
+
if debug:
|
448 |
+
for i in range(world_size):
|
449 |
+
print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
|
450 |
+
|
451 |
+
wanted_params = len(param_shapes)
|
452 |
+
wanted_numel = sum(shape.numel() for shape in param_shapes.values())
|
453 |
+
# not asserting if there is a mismatch due to possible padding
|
454 |
+
avail_numel = fp32_flat_groups[0].numel() * world_size
|
455 |
+
print(f"Trainable params: Have {avail_numel} numels to process.")
|
456 |
+
print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
|
457 |
+
|
458 |
+
# params
|
459 |
+
# XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
|
460 |
+
# out-of-core computing solution
|
461 |
+
offset = 0
|
462 |
+
total_numel = 0
|
463 |
+
total_params = 0
|
464 |
+
flat_groups_offset = [0] + list(np.cumsum([flat_tensor.numel() for flat_tensor in fp32_flat_groups[0]]))
|
465 |
+
for name, shape in tqdm(param_shapes.items(), desc='Gathering sharded weights'):
|
466 |
+
unpartitioned_numel = shape.numel()
|
467 |
+
total_numel += unpartitioned_numel
|
468 |
+
total_params += 1
|
469 |
+
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
|
470 |
+
|
471 |
+
if debug:
|
472 |
+
print(
|
473 |
+
f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
|
474 |
+
)
|
475 |
+
|
476 |
+
# memory efficient tensor
|
477 |
+
tensor = GatheredTensor(fp32_flat_groups, flat_groups_offset, offset, partitioned_numel, shape)
|
478 |
+
state_dict[name] = tensor
|
479 |
+
offset += partitioned_numel
|
480 |
+
|
481 |
+
offset *= world_size
|
482 |
+
|
483 |
+
# Sanity check
|
484 |
+
if offset != avail_numel:
|
485 |
+
raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
|
486 |
+
|
487 |
+
print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
|
488 |
+
|
489 |
+
|
490 |
+
def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
491 |
+
exclude_frozen_parameters):
|
492 |
+
state_dict = OrderedDict()
|
493 |
+
|
494 |
+
# buffers
|
495 |
+
buffers = zero_model_states[0].buffers
|
496 |
+
state_dict.update(buffers)
|
497 |
+
if debug:
|
498 |
+
print(f"added {len(buffers)} buffers")
|
499 |
+
|
500 |
+
if not exclude_frozen_parameters:
|
501 |
+
_zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
|
502 |
+
|
503 |
+
_zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
|
504 |
+
|
505 |
+
# recover shared parameters
|
506 |
+
for pair in zero_model_states[0].shared_params:
|
507 |
+
if pair[1] in state_dict:
|
508 |
+
state_dict[pair[0]] = state_dict[pair[1]]
|
509 |
+
|
510 |
+
return state_dict
|
511 |
+
|
512 |
+
|
513 |
+
def to_torch_tensor(state_dict, return_empty_tensor=False):
|
514 |
+
"""
|
515 |
+
Convert state_dict of GatheredTensor to torch tensor
|
516 |
+
"""
|
517 |
+
torch_state_dict = {}
|
518 |
+
converted_tensors = {}
|
519 |
+
for name, tensor in state_dict.items():
|
520 |
+
tensor_id = id(tensor)
|
521 |
+
if tensor_id in converted_tensors: # shared tensors
|
522 |
+
shared_tensor = torch_state_dict[converted_tensors[tensor_id]]
|
523 |
+
torch_state_dict[name] = shared_tensor
|
524 |
+
else:
|
525 |
+
converted_tensors[tensor_id] = name
|
526 |
+
if return_empty_tensor:
|
527 |
+
torch_state_dict[name] = torch.empty(tensor.shape, dtype=tensor.dtype)
|
528 |
+
else:
|
529 |
+
torch_state_dict[name] = tensor.contiguous()
|
530 |
+
return torch_state_dict
|
531 |
+
|
532 |
+
|
533 |
+
def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir,
|
534 |
+
tag=None,
|
535 |
+
exclude_frozen_parameters=False,
|
536 |
+
lazy_mode=False):
|
537 |
+
"""
|
538 |
+
Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
|
539 |
+
``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
|
540 |
+
via a model hub.
|
541 |
+
|
542 |
+
Args:
|
543 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder
|
544 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in 'latest' file. e.g., ``global_step14``
|
545 |
+
- ``exclude_frozen_parameters``: exclude frozen parameters
|
546 |
+
- ``lazy_mode``: get state_dict in lazy mode. It returns a dict of pesduo tensor instead of torch tensor, which is more memory efficient.
|
547 |
+
Convert the pesduo tensor to torch tensor by ``.contiguous()``
|
548 |
+
|
549 |
+
Returns:
|
550 |
+
- pytorch ``state_dict``
|
551 |
+
|
552 |
+
A typical usage might be ::
|
553 |
+
|
554 |
+
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
|
555 |
+
# do the training and checkpoint saving
|
556 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
|
557 |
+
model = model.cpu() # move to cpu
|
558 |
+
model.load_state_dict(state_dict)
|
559 |
+
# submit to model hub or save the model to share with others
|
560 |
+
|
561 |
+
In this example the ``model`` will no longer be usable in the deepspeed context of the same
|
562 |
+
application. i.e. you will need to re-initialize the deepspeed engine, since
|
563 |
+
``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
|
564 |
+
|
565 |
+
If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
|
566 |
+
|
567 |
+
Note: the above usage may not work if your application doesn't have sufficient free CPU memory.
|
568 |
+
You may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
|
569 |
+
the checkpoint. Or you can load state_dict in lazy mode ::
|
570 |
+
|
571 |
+
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
|
572 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, lazy_mode=True) # not on cpu
|
573 |
+
for name, lazy_tensor in state_dict.item():
|
574 |
+
tensor = lazy_tensor.contiguous() # to cpu
|
575 |
+
print(name, tensor)
|
576 |
+
# del tensor to release memory if it no longer in use
|
577 |
+
"""
|
578 |
+
if tag is None:
|
579 |
+
latest_path = os.path.join(checkpoint_dir, 'latest')
|
580 |
+
if os.path.isfile(latest_path):
|
581 |
+
with open(latest_path, 'r') as fd:
|
582 |
+
tag = fd.read().strip()
|
583 |
+
else:
|
584 |
+
raise ValueError(f"Unable to find 'latest' file at {latest_path}")
|
585 |
+
|
586 |
+
ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
|
587 |
+
|
588 |
+
if not os.path.isdir(ds_checkpoint_dir):
|
589 |
+
raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
|
590 |
+
|
591 |
+
state_dict = _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
|
592 |
+
if lazy_mode:
|
593 |
+
return state_dict
|
594 |
+
else:
|
595 |
+
return to_torch_tensor(state_dict)
|
596 |
+
|
597 |
+
|
598 |
+
def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir,
|
599 |
+
output_dir,
|
600 |
+
max_shard_size="5GB",
|
601 |
+
safe_serialization=False,
|
602 |
+
tag=None,
|
603 |
+
exclude_frozen_parameters=False):
|
604 |
+
"""
|
605 |
+
Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
|
606 |
+
loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
|
607 |
+
|
608 |
+
Args:
|
609 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
|
610 |
+
- ``output_dir``: directory to the pytorch fp32 state_dict output files
|
611 |
+
- ``max_shard_size``: the maximum size for a checkpoint before being sharded, default value is 5GB
|
612 |
+
- ``safe_serialization``: whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
|
613 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
|
614 |
+
- ``exclude_frozen_parameters``: exclude frozen parameters
|
615 |
+
"""
|
616 |
+
|
617 |
+
# Dependency pre-check
|
618 |
+
if safe_serialization:
|
619 |
+
try:
|
620 |
+
from safetensors.torch import save_file
|
621 |
+
except ImportError:
|
622 |
+
print('If you want to use `safe_serialization`, please `pip install safetensors`')
|
623 |
+
raise
|
624 |
+
if max_shard_size is not None:
|
625 |
+
try:
|
626 |
+
from huggingface_hub import split_torch_state_dict_into_shards
|
627 |
+
except ImportError:
|
628 |
+
print('If you want to use `max_shard_size`, please `pip install huggingface_hub`')
|
629 |
+
raise
|
630 |
+
|
631 |
+
# Convert zero checkpoint to state_dict
|
632 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir,
|
633 |
+
tag,
|
634 |
+
exclude_frozen_parameters,
|
635 |
+
lazy_mode=True)
|
636 |
+
|
637 |
+
# Shard the model if it is too big.
|
638 |
+
weights_name = "model.safetensors" if safe_serialization else "pytorch_model.bin"
|
639 |
+
if max_shard_size is not None:
|
640 |
+
filename_pattern = weights_name.replace(".bin", "{suffix}.bin").replace(".safetensors", "{suffix}.safetensors")
|
641 |
+
# an memory-efficient approach for sharding
|
642 |
+
empty_state_dict = to_torch_tensor(state_dict, return_empty_tensor=True)
|
643 |
+
state_dict_split = split_torch_state_dict_into_shards(empty_state_dict,
|
644 |
+
filename_pattern=filename_pattern,
|
645 |
+
max_shard_size=max_shard_size)
|
646 |
+
else:
|
647 |
+
from collections import namedtuple
|
648 |
+
StateDictSplit = namedtuple("StateDictSplit", ["is_sharded", "filename_to_tensors"])
|
649 |
+
state_dict_split = StateDictSplit(is_sharded=False,
|
650 |
+
filename_to_tensors={weights_name: list(state_dict.keys())})
|
651 |
+
|
652 |
+
# Save the model by shard
|
653 |
+
os.makedirs(output_dir, exist_ok=True)
|
654 |
+
filename_to_tensors = state_dict_split.filename_to_tensors.items()
|
655 |
+
for shard_file, tensors in tqdm(filename_to_tensors, desc="Saving checkpoint shards"):
|
656 |
+
shard_state_dict = {tensor_name: state_dict[tensor_name] for tensor_name in tensors}
|
657 |
+
shard_state_dict = to_torch_tensor(shard_state_dict)
|
658 |
+
output_path = os.path.join(output_dir, shard_file)
|
659 |
+
if safe_serialization:
|
660 |
+
save_file(shard_state_dict, output_path, metadata={"format": "pt"})
|
661 |
+
else:
|
662 |
+
torch.save(shard_state_dict, output_path)
|
663 |
+
# release the memory of current shard
|
664 |
+
for tensor_name in list(shard_state_dict.keys()):
|
665 |
+
del state_dict[tensor_name]
|
666 |
+
del shard_state_dict[tensor_name]
|
667 |
+
del shard_state_dict
|
668 |
+
gc.collect()
|
669 |
+
|
670 |
+
# Save index if sharded
|
671 |
+
if state_dict_split.is_sharded:
|
672 |
+
index = {
|
673 |
+
"metadata": state_dict_split.metadata,
|
674 |
+
"weight_map": state_dict_split.tensor_to_filename,
|
675 |
+
}
|
676 |
+
save_index_file = "model.safetensors.index.json" if safe_serialization else "pytorch_model.bin.index.json"
|
677 |
+
save_index_file = os.path.join(output_dir, save_index_file)
|
678 |
+
with open(save_index_file, "w", encoding="utf-8") as f:
|
679 |
+
content = json.dumps(index, indent=2, sort_keys=True) + "\n"
|
680 |
+
f.write(content)
|
681 |
+
|
682 |
+
|
683 |
+
def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
|
684 |
+
"""
|
685 |
+
1. Put the provided model to cpu
|
686 |
+
2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
|
687 |
+
3. Load it into the provided model
|
688 |
+
|
689 |
+
Args:
|
690 |
+
- ``model``: the model object to update
|
691 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
|
692 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
|
693 |
+
|
694 |
+
Returns:
|
695 |
+
- ``model`: modified model
|
696 |
+
|
697 |
+
Make sure you have plenty of CPU memory available before you call this function. If you don't
|
698 |
+
have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
|
699 |
+
conveniently placed for you in the checkpoint folder.
|
700 |
+
|
701 |
+
A typical usage might be ::
|
702 |
+
|
703 |
+
from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
|
704 |
+
model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
|
705 |
+
# submit to model hub or save the model to share with others
|
706 |
+
|
707 |
+
Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
|
708 |
+
of the same application. i.e. you will need to re-initialize the deepspeed engine, since
|
709 |
+
``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
|
710 |
+
|
711 |
+
"""
|
712 |
+
logger.info(f"Extracting fp32 weights")
|
713 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
|
714 |
+
|
715 |
+
logger.info(f"Overwriting model with fp32 weights")
|
716 |
+
model = model.cpu()
|
717 |
+
model.load_state_dict(state_dict, strict=False)
|
718 |
+
|
719 |
+
return model
|
720 |
+
|
721 |
+
|
722 |
+
if __name__ == "__main__":
|
723 |
+
parser = argparse.ArgumentParser()
|
724 |
+
parser.add_argument("checkpoint_dir",
|
725 |
+
type=str,
|
726 |
+
help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
|
727 |
+
parser.add_argument("output_dir",
|
728 |
+
type=str,
|
729 |
+
help="directory to the pytorch fp32 state_dict output files"
|
730 |
+
"(e.g. path/checkpoint-12-output/)")
|
731 |
+
parser.add_argument(
|
732 |
+
"--max_shard_size",
|
733 |
+
type=str,
|
734 |
+
default="5GB",
|
735 |
+
help="The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size"
|
736 |
+
"lower than this size. If expressed as a string, needs to be digits followed by a unit (like `5MB`"
|
737 |
+
"We default it to 5GB in order for models to be able to run easily on free-tier google colab instances"
|
738 |
+
"without CPU OOM issues.")
|
739 |
+
parser.add_argument(
|
740 |
+
"--safe_serialization",
|
741 |
+
default=False,
|
742 |
+
action='store_true',
|
743 |
+
help="Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).")
|
744 |
+
parser.add_argument("-t",
|
745 |
+
"--tag",
|
746 |
+
type=str,
|
747 |
+
default=None,
|
748 |
+
help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
|
749 |
+
parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters")
|
750 |
+
parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
|
751 |
+
args = parser.parse_args()
|
752 |
+
|
753 |
+
debug = args.debug
|
754 |
+
|
755 |
+
convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir,
|
756 |
+
args.output_dir,
|
757 |
+
max_shard_size=args.max_shard_size,
|
758 |
+
safe_serialization=args.safe_serialization,
|
759 |
+
tag=args.tag,
|
760 |
+
exclude_frozen_parameters=args.exclude_frozen_parameters)
|
checkpoints/step_5500/model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9244cd4b73321a3763989ecad43fc2222f503768f9eb53a7091d1967d4ea9310
|
3 |
+
size 258323520
|
checkpoints/step_5500/pico_decoder.py
ADDED
@@ -0,0 +1,623 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Pico Decoder: A Lightweight Causal Transformer Language Model
|
3 |
+
|
4 |
+
Pico Decoder uses a simple LLAMA-style transformer architecture, written for clarity and educational purposes.
|
5 |
+
|
6 |
+
Everything is written with a modular design for easy modification and experimentation.
|
7 |
+
|
8 |
+
Key features:
|
9 |
+
- RMSNorm for layer normalization
|
10 |
+
- Rotary Positional Embeddings (RoPE)
|
11 |
+
- Multi-head attention with KV-cache support
|
12 |
+
- SwiGLU activation function
|
13 |
+
- Residual connections throughout
|
14 |
+
|
15 |
+
- KV-cache for faster autoregressive generation
|
16 |
+
|
17 |
+
References:
|
18 |
+
- RoPE: https://arxiv.org/abs/2104.09864
|
19 |
+
- SwiGLU: https://arxiv.org/abs/2002.05202
|
20 |
+
- LLAMA: https://arxiv.org/abs/2302.13971
|
21 |
+
|
22 |
+
Adapted from:
|
23 |
+
- OLMO: https://github.com/allenai/OLMo
|
24 |
+
- LLAMA: https://github.com/meta/llama
|
25 |
+
"""
|
26 |
+
|
27 |
+
from dataclasses import asdict
|
28 |
+
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union
|
29 |
+
|
30 |
+
import torch
|
31 |
+
import torch.nn as nn
|
32 |
+
import torch.nn.functional as F
|
33 |
+
from torch.nn.attention import SDPBackend, sdpa_kernel
|
34 |
+
from transformers import PretrainedConfig, PreTrainedModel
|
35 |
+
from transformers.modeling_outputs import CausalLMOutput, CausalLMOutputWithPast
|
36 |
+
|
37 |
+
try:
|
38 |
+
if TYPE_CHECKING:
|
39 |
+
# We need to do this to avoid importing these when creating the HF-compatible models
|
40 |
+
from src.config import ModelConfig
|
41 |
+
except ImportError:
|
42 |
+
pass
|
43 |
+
|
44 |
+
########################################################
|
45 |
+
#
|
46 |
+
# Layer Normalization
|
47 |
+
#
|
48 |
+
########################################################
|
49 |
+
|
50 |
+
|
51 |
+
class RMSNorm(torch.nn.Module):
|
52 |
+
"""Root Mean Square Layer Normalization.
|
53 |
+
|
54 |
+
A variant of Layer Normalization that uses RMS statistics instead of mean/variance,
|
55 |
+
resulting in improved stability and performance.
|
56 |
+
|
57 |
+
Args:
|
58 |
+
config (Union[ModelConfig, PicoHFConfig]): Configuration object containing normalization parameters
|
59 |
+
- config.norm_eps: Small constant for numerical stability
|
60 |
+
- config.d_model: Model dimension for the weight parameter
|
61 |
+
|
62 |
+
References:
|
63 |
+
https://arxiv.org/abs/1910.07467
|
64 |
+
"""
|
65 |
+
|
66 |
+
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]):
|
67 |
+
super().__init__()
|
68 |
+
self.eps = config.norm_eps
|
69 |
+
self.weight = nn.Parameter(torch.ones(config.d_model))
|
70 |
+
|
71 |
+
def _norm(self, x: torch.Tensor) -> torch.Tensor:
|
72 |
+
"""
|
73 |
+
Normalizes the input tensor by its RMS value.
|
74 |
+
"""
|
75 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
76 |
+
|
77 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
78 |
+
"""
|
79 |
+
Applies RMS normalization to the input tensor and scales it by the weight parameter.
|
80 |
+
"""
|
81 |
+
output = self._norm(x.float()).type_as(x)
|
82 |
+
return output * self.weight
|
83 |
+
|
84 |
+
|
85 |
+
########################################################
|
86 |
+
#
|
87 |
+
# Positional Embedding
|
88 |
+
#
|
89 |
+
########################################################
|
90 |
+
|
91 |
+
|
92 |
+
class RoPE(nn.Module):
|
93 |
+
"""Rotary Positional Embeddings (RoPE).
|
94 |
+
|
95 |
+
Implements position-dependent rotation of keys and queries in attention mechanism,
|
96 |
+
allowing better modeling of relative positions in sequences. Uses complex number
|
97 |
+
operations for efficient rotation.
|
98 |
+
|
99 |
+
Args:
|
100 |
+
config (Union[ModelConfig, PicoHFConfig]): Model configuration containing:
|
101 |
+
- config.position_emb_theta: Base for frequency computation
|
102 |
+
- config.d_model: Model dimension
|
103 |
+
- config.attention_n_heads: Number of attention heads
|
104 |
+
- config.max_seq_len: Maximum sequence length
|
105 |
+
|
106 |
+
References:
|
107 |
+
https://arxiv.org/abs/2104.09864
|
108 |
+
"""
|
109 |
+
|
110 |
+
_freqs_cis_tensor: torch.Tensor | None = None
|
111 |
+
|
112 |
+
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]):
|
113 |
+
super().__init__()
|
114 |
+
|
115 |
+
self.theta = config.position_emb_theta
|
116 |
+
self.dim = config.d_model // config.attention_n_heads
|
117 |
+
|
118 |
+
max_seq_len = config.max_seq_len
|
119 |
+
|
120 |
+
# only gets set once, and then reused for all RoPE instances
|
121 |
+
if RoPE._freqs_cis_tensor is None:
|
122 |
+
RoPE._freqs_cis_tensor = self._setup_freqs_cis(
|
123 |
+
max_seq_len, self.theta, self.dim
|
124 |
+
)
|
125 |
+
|
126 |
+
# register _freqs_cis buffer
|
127 |
+
# can be easily recomputed so persistent=False
|
128 |
+
self.register_buffer("_freqs_cis", self._freqs_cis_tensor, persistent=False)
|
129 |
+
|
130 |
+
@classmethod
|
131 |
+
def _setup_freqs_cis(cls, seq_len: int, theta: float, dim: int) -> torch.Tensor:
|
132 |
+
"""Setup Frequency Tensor for RoPE Embeddings
|
133 |
+
|
134 |
+
Initializes the complex frequency tensor that is used to compute the RoPE embeddings.
|
135 |
+
|
136 |
+
Note other implementations will use cos and sin directly, but using the complex
|
137 |
+
number representation is (probably?) more efficient:
|
138 |
+
|
139 |
+
e^(theta * i * t) = cos(theta * t) + i * sin(theta * t) [Euler's formula]
|
140 |
+
"""
|
141 |
+
_freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
|
142 |
+
positions = torch.arange(seq_len)
|
143 |
+
freqs = torch.outer(positions, _freqs)
|
144 |
+
return torch.polar(torch.ones_like(freqs), freqs) # complex64
|
145 |
+
|
146 |
+
def get_freqs_cis(
|
147 |
+
self, input_shape: torch.Size, start_pos: int, end_pos: int
|
148 |
+
) -> torch.Tensor:
|
149 |
+
"""Reshape Frequency Tensor for RoPE Embeddings
|
150 |
+
|
151 |
+
Makes the frequency tensor broadcastable with the input tensor.
|
152 |
+
"""
|
153 |
+
_freqs_cis = self._freqs_cis[start_pos:end_pos]
|
154 |
+
ndim = len(input_shape)
|
155 |
+
assert 0 <= 1 < ndim
|
156 |
+
assert _freqs_cis.shape == (input_shape[1], input_shape[-1])
|
157 |
+
|
158 |
+
# TODO: Check whether this is correct (might be able to remove this)
|
159 |
+
shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(input_shape)]
|
160 |
+
return _freqs_cis.view(*shape)
|
161 |
+
|
162 |
+
def forward(
|
163 |
+
self,
|
164 |
+
queries: torch.Tensor,
|
165 |
+
keys: torch.Tensor,
|
166 |
+
start_pos: int = 0,
|
167 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
168 |
+
"""Apply RoPE Embeddings to Queries and Keys
|
169 |
+
|
170 |
+
Applies the rotary positional embeddings to the input tensors via complex num multiplication
|
171 |
+
|
172 |
+
NOTE: The start_pos is used if we want to use the kv_cache in the attention mechanism.
|
173 |
+
"""
|
174 |
+
queries_ = torch.view_as_complex(
|
175 |
+
queries.float().reshape(*queries.shape[:-1], -1, 2)
|
176 |
+
)
|
177 |
+
keys_ = torch.view_as_complex(keys.float().reshape(*keys.shape[:-1], -1, 2))
|
178 |
+
|
179 |
+
input_shape = (
|
180 |
+
queries_.shape
|
181 |
+
) # same as keys: (batch_size, seq_len, n_heads, head_dim/2)
|
182 |
+
freqs_start_pos = start_pos
|
183 |
+
freqs_end_pos = freqs_start_pos + queries_.shape[1]
|
184 |
+
|
185 |
+
freqs_cis = self.get_freqs_cis(input_shape, freqs_start_pos, freqs_end_pos)
|
186 |
+
|
187 |
+
queries_rotated = torch.view_as_real(queries_ * freqs_cis).flatten(3)
|
188 |
+
keys_rotated = torch.view_as_real(keys_ * freqs_cis).flatten(3)
|
189 |
+
return queries_rotated.type_as(queries), keys_rotated.type_as(keys)
|
190 |
+
|
191 |
+
|
192 |
+
########################################################
|
193 |
+
#
|
194 |
+
# Attention
|
195 |
+
#
|
196 |
+
########################################################
|
197 |
+
|
198 |
+
|
199 |
+
class Attention(nn.Module):
|
200 |
+
"""Multi-head Attention with Group Query Attention support.
|
201 |
+
|
202 |
+
Implements scaled dot-product attention and supports:
|
203 |
+
- Grouped Query Attention (GQA)
|
204 |
+
- Key-Value caching for efficient inference
|
205 |
+
- RoPE integration
|
206 |
+
|
207 |
+
Args:
|
208 |
+
config (Union[ModelConfig, PretrainedConfig]): Configuration containing:
|
209 |
+
- config.attention_n_heads: Number of attention heads
|
210 |
+
- config.attention_n_kv_heads: Number of key/value heads
|
211 |
+
- config.d_model: Model dimension
|
212 |
+
- config.batch_size: Maximum batch size
|
213 |
+
- config.max_seq_len: Maximum sequence length
|
214 |
+
|
215 |
+
Shape:
|
216 |
+
- Input: (batch_size, seq_len, d_model)
|
217 |
+
- Output: (batch_size, seq_len, d_model)
|
218 |
+
"""
|
219 |
+
|
220 |
+
def __init__(
|
221 |
+
self,
|
222 |
+
config: Union["ModelConfig", "PicoDecoderHFConfig"],
|
223 |
+
):
|
224 |
+
super().__init__()
|
225 |
+
|
226 |
+
self.n_heads = config.attention_n_heads
|
227 |
+
self.n_kv_heads = config.attention_n_kv_heads
|
228 |
+
|
229 |
+
self.batch_size = config.batch_size
|
230 |
+
self.max_seq_len = config.max_seq_len
|
231 |
+
|
232 |
+
d_model = config.d_model
|
233 |
+
self.head_dim = d_model // self.n_heads
|
234 |
+
|
235 |
+
self.n_rep = self.n_heads // self.n_kv_heads
|
236 |
+
|
237 |
+
self.q_proj = nn.Linear(d_model, self.n_heads * self.head_dim, bias=False)
|
238 |
+
self.k_proj = nn.Linear(d_model, self.n_kv_heads * self.head_dim, bias=False)
|
239 |
+
self.v_proj = nn.Linear(d_model, self.n_kv_heads * self.head_dim, bias=False)
|
240 |
+
self.o_proj = nn.Linear(self.n_heads * self.head_dim, d_model, bias=False)
|
241 |
+
|
242 |
+
self.rope = RoPE(config)
|
243 |
+
|
244 |
+
def forward(
|
245 |
+
self,
|
246 |
+
input: torch.Tensor,
|
247 |
+
mask: Optional[torch.Tensor] = None,
|
248 |
+
past_key_values: Optional[Tuple[torch.Tensor, ...]] = None,
|
249 |
+
use_cache: bool = False,
|
250 |
+
) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
|
251 |
+
"""Forward pass for the attention mechanism.
|
252 |
+
|
253 |
+
Computes queries, keys, and values for the attention mechanism. Applies rotary positional
|
254 |
+
embeddings to the queries and keys, and then computes attention scores and outputs.
|
255 |
+
|
256 |
+
For an introduction to the attention mechanism, see:
|
257 |
+
https://arxiv.org/abs/1706.03762
|
258 |
+
|
259 |
+
A few things to note:
|
260 |
+
- The past_key_values is used to implement the KV cache, which is used to speed up
|
261 |
+
generation by caching the KV pairs from previous forward passes. This is useful when doing
|
262 |
+
tasks that require generating multiple tokens conditioned on previous tokens (e.g. language
|
263 |
+
modeling, text generation, etc.). The way the KV cache is implemented is that each layer has
|
264 |
+
its own KV cache - this KV cache is implemented as a tuple.
|
265 |
+
"""
|
266 |
+
bsz, seq_len, _ = input.shape
|
267 |
+
_queries, _keys, _values = (
|
268 |
+
self.q_proj(input),
|
269 |
+
self.k_proj(input),
|
270 |
+
self.v_proj(input),
|
271 |
+
)
|
272 |
+
|
273 |
+
# Reshaping for multi-head attention
|
274 |
+
queries = _queries.view(bsz, seq_len, self.n_heads, self.head_dim)
|
275 |
+
keys = _keys.view(bsz, seq_len, self.n_kv_heads, self.head_dim)
|
276 |
+
values = _values.view(bsz, seq_len, self.n_kv_heads, self.head_dim)
|
277 |
+
|
278 |
+
# The start position is used to apply the RoPE embeddings to only the new tokens
|
279 |
+
# when using the kv_cache in the attention mechanism.
|
280 |
+
# We want to start from the last position in the cache.
|
281 |
+
start_pos = past_key_values[0].shape[1] if past_key_values is not None else 0
|
282 |
+
|
283 |
+
# apply rotary positional embeddings
|
284 |
+
queries, keys = self.rope(queries, keys, start_pos)
|
285 |
+
|
286 |
+
if past_key_values is not None:
|
287 |
+
keys = torch.cat([past_key_values[0], keys], dim=1)
|
288 |
+
values = torch.cat([past_key_values[1], values], dim=1)
|
289 |
+
|
290 |
+
if use_cache:
|
291 |
+
cached_keys = keys
|
292 |
+
cached_values = values
|
293 |
+
else:
|
294 |
+
cached_keys = None
|
295 |
+
cached_values = None
|
296 |
+
|
297 |
+
queries = queries.transpose(1, 2)
|
298 |
+
keys = keys.transpose(1, 2)
|
299 |
+
values = values.transpose(1, 2)
|
300 |
+
|
301 |
+
apply_gqa = self.n_rep > 1
|
302 |
+
if apply_gqa and queries.device.type == "mps":
|
303 |
+
# NOTE: MPS does not support GQA in the SDPA kernel, but we can repeat the keys and values
|
304 |
+
# outside of the kernel to get the same effect.
|
305 |
+
# See: https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html
|
306 |
+
keys = keys.repeat_interleave(self.n_rep, dim=-3)
|
307 |
+
values = values.repeat_interleave(self.n_rep, dim=-3)
|
308 |
+
apply_gqa = False
|
309 |
+
|
310 |
+
backends = [SDPBackend.CUDNN_ATTENTION, SDPBackend.MATH]
|
311 |
+
|
312 |
+
with sdpa_kernel(backends=backends):
|
313 |
+
attn_output = F.scaled_dot_product_attention(
|
314 |
+
queries.contiguous(),
|
315 |
+
keys.contiguous(),
|
316 |
+
values.contiguous(),
|
317 |
+
attn_mask=mask.to(queries.dtype),
|
318 |
+
enable_gqa=apply_gqa,
|
319 |
+
)
|
320 |
+
|
321 |
+
attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, seq_len, -1)
|
322 |
+
output = self.o_proj(attn_output)
|
323 |
+
|
324 |
+
return output, (cached_keys, cached_values)
|
325 |
+
|
326 |
+
|
327 |
+
########################################################
|
328 |
+
#
|
329 |
+
# SwiGLU (Combines MLP and Activation)
|
330 |
+
#
|
331 |
+
########################################################
|
332 |
+
|
333 |
+
|
334 |
+
class SwiGLU(nn.Module):
|
335 |
+
"""SwiGLU Activation Function with Linear Projections.
|
336 |
+
|
337 |
+
Implements the SwiGLU activation function combined with linear transformations,
|
338 |
+
serving as the feed-forward network in transformer blocks.
|
339 |
+
|
340 |
+
Args:
|
341 |
+
config (Union[ModelConfig, PicoDecoderHFConfig]): Configuration containing:
|
342 |
+
- config.d_model: Model dimension
|
343 |
+
- config.activation_hidden_dim: Hidden dimension (typically 4 * d_model)
|
344 |
+
|
345 |
+
References:
|
346 |
+
https://arxiv.org/abs/2002.05202
|
347 |
+
"""
|
348 |
+
|
349 |
+
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]):
|
350 |
+
super().__init__()
|
351 |
+
|
352 |
+
model_dim = config.d_model
|
353 |
+
act_hidden_dim = config.activation_hidden_dim # usually 4 * d_model
|
354 |
+
|
355 |
+
self.w_0 = nn.Linear(model_dim, act_hidden_dim, bias=False)
|
356 |
+
self.w_1 = nn.Linear(model_dim, act_hidden_dim, bias=False)
|
357 |
+
self.w_2 = nn.Linear(act_hidden_dim, model_dim, bias=False)
|
358 |
+
|
359 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
360 |
+
return self.w_2(F.silu(self.w_0(x)) * self.w_1(x))
|
361 |
+
|
362 |
+
|
363 |
+
########################################################
|
364 |
+
#
|
365 |
+
# PicoDecoderBlock
|
366 |
+
#
|
367 |
+
########################################################
|
368 |
+
|
369 |
+
|
370 |
+
class PicoDecoderBlock(nn.Module):
|
371 |
+
"""Single Transformer Block with Attention and Feed-forward layers.
|
372 |
+
|
373 |
+
Implements a standard transformer block with:
|
374 |
+
- Multi-head attention with normalization and residual connection
|
375 |
+
- SwiGLU feed-forward network with normalization and residual connection
|
376 |
+
|
377 |
+
Args:
|
378 |
+
config (Union[ModelConfig, PicoDecoderHFConfig]): Model configuration; either a dataclass or
|
379 |
+
a HuggingFace PicoDecoderHFConfig
|
380 |
+
"""
|
381 |
+
|
382 |
+
def __init__(
|
383 |
+
self,
|
384 |
+
config: Union["ModelConfig", "PicoDecoderHFConfig"],
|
385 |
+
):
|
386 |
+
super().__init__()
|
387 |
+
|
388 |
+
self.attention = Attention(config)
|
389 |
+
self.swiglu = SwiGLU(config)
|
390 |
+
self.attention_norm = RMSNorm(config)
|
391 |
+
self.swiglu_norm = RMSNorm(config)
|
392 |
+
|
393 |
+
def forward(
|
394 |
+
self,
|
395 |
+
input: torch.Tensor,
|
396 |
+
mask: Optional[torch.Tensor] = None,
|
397 |
+
past_key_values: Optional[Tuple[torch.Tensor]] = None,
|
398 |
+
use_cache: bool = False,
|
399 |
+
) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
|
400 |
+
attention_output, cached_key_values = self.attention(
|
401 |
+
self.attention_norm(input),
|
402 |
+
mask=mask,
|
403 |
+
past_key_values=past_key_values,
|
404 |
+
use_cache=use_cache,
|
405 |
+
)
|
406 |
+
# NOTE: cached_key_values is None if use_cache is False
|
407 |
+
|
408 |
+
h = input + attention_output
|
409 |
+
out = h + self.swiglu(self.swiglu_norm(h))
|
410 |
+
return out, cached_key_values
|
411 |
+
|
412 |
+
|
413 |
+
########################################################
|
414 |
+
#
|
415 |
+
# Pico Decoder (Causal Transformer Model)
|
416 |
+
#
|
417 |
+
########################################################
|
418 |
+
|
419 |
+
|
420 |
+
class PicoDecoder(nn.Module):
|
421 |
+
"""
|
422 |
+
Pico Decoder: combines the embedding, causal decoder blocks, and output projection into a
|
423 |
+
single autoregressive model.
|
424 |
+
|
425 |
+
For more information on the model, see the classes for the modules that make up the model.
|
426 |
+
"""
|
427 |
+
|
428 |
+
def __init__(
|
429 |
+
self,
|
430 |
+
model_config: Union["ModelConfig", "PicoDecoderHFConfig"],
|
431 |
+
):
|
432 |
+
super().__init__()
|
433 |
+
self.config = model_config
|
434 |
+
|
435 |
+
self.embedding_proj = nn.Embedding(self.config.vocab_size, self.config.d_model)
|
436 |
+
self.layers = nn.ModuleList(
|
437 |
+
[PicoDecoderBlock(self.config) for _ in range(self.config.n_layers)]
|
438 |
+
)
|
439 |
+
self.output_norm = RMSNorm(self.config)
|
440 |
+
self.de_embedding_proj = nn.Linear(
|
441 |
+
self.config.d_model, self.config.vocab_size, bias=False
|
442 |
+
)
|
443 |
+
|
444 |
+
def convert_to_hf_model(self) -> "PicoDecoderHF":
|
445 |
+
"""Convert the Lightning model to a HuggingFace model."""
|
446 |
+
# Build HF config
|
447 |
+
hf_config = PicoDecoderHFConfig.from_dataclass(self.config)
|
448 |
+
|
449 |
+
# Instantiate the HF-wrapped model
|
450 |
+
hf_model = PicoDecoderHF(hf_config)
|
451 |
+
|
452 |
+
# Grab our full state dict, prefixing module names
|
453 |
+
raw_state = self.state_dict(prefix="pico_decoder.")
|
454 |
+
|
455 |
+
# Only keep keys that exist in the HF model (drops classifier_head, etc.)
|
456 |
+
hf_keys = set(hf_model.state_dict().keys())
|
457 |
+
filtered_state = {k: v for k, v in raw_state.items() if k in hf_keys}
|
458 |
+
|
459 |
+
# Load into HF model, ignore any missing keys
|
460 |
+
hf_model.load_state_dict(filtered_state, strict=False)
|
461 |
+
|
462 |
+
return hf_model
|
463 |
+
|
464 |
+
def forward(
|
465 |
+
self,
|
466 |
+
input_ids: torch.Tensor,
|
467 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
468 |
+
use_cache: bool = False,
|
469 |
+
return_hidden: bool = False,
|
470 |
+
) -> Tuple[torch.Tensor, Optional[Tuple[Tuple[torch.Tensor, torch.Tensor]]]]:
|
471 |
+
"""
|
472 |
+
This is the forward pass for the entire Pico model. It boils down to:
|
473 |
+
- Embedding the input ids
|
474 |
+
- Creating a causal mask
|
475 |
+
- Processing through the pico layers
|
476 |
+
- Projecting the output to logits
|
477 |
+
|
478 |
+
NOTE: One feature that might be confusing is the KV cache. The KV cache is used to speed up
|
479 |
+
generation by caching the KV pairs from previous forward passes. This is useful when doing
|
480 |
+
tasks that require generating multiple tokens conditioned on previous tokens (e.g. language
|
481 |
+
modeling, text generation, etc.). The way the KV cache is implemented is that each layer has
|
482 |
+
its own KV cache which is stored as a tuple. The whole model then stores a tuple of these
|
483 |
+
KV caches (so a tuple of tuples).
|
484 |
+
"""
|
485 |
+
|
486 |
+
seq_len = input_ids.shape[-1]
|
487 |
+
h = self.embedding_proj(input_ids)
|
488 |
+
|
489 |
+
# Calculate start position from past cached KV pairs. Remember that each layer has its
|
490 |
+
# own KV Cache. So when we index past_key_values, we need to index into the KV pairs for the
|
491 |
+
# correct layer and then for either the keys or values.
|
492 |
+
start_pos = 0 if past_key_values is None else past_key_values[0][0].shape[1]
|
493 |
+
|
494 |
+
# Create causal mask for current sequence
|
495 |
+
mask = None
|
496 |
+
if seq_len > 1:
|
497 |
+
mask = torch.full((seq_len, seq_len), float("-inf"))
|
498 |
+
mask = torch.triu(mask, diagonal=1)
|
499 |
+
|
500 |
+
# If using KV cache, extend mask to cover cached sequence length
|
501 |
+
if past_key_values is not None:
|
502 |
+
# Add zeros for cached tokens (we can attend to all of them)
|
503 |
+
mask = torch.hstack([torch.zeros((seq_len, start_pos)), mask])
|
504 |
+
|
505 |
+
mask = mask.to(h.device)
|
506 |
+
|
507 |
+
# NOTE: If we are using the cache, we need to store the cached KV pairs for each layer
|
508 |
+
# in a tuple. Each layer will have its own cached KV pair which we aggregate in a tuple.
|
509 |
+
cached_key_values = () if use_cache else None
|
510 |
+
|
511 |
+
# Process through transformer blocks
|
512 |
+
for idx, layer in enumerate(self.layers):
|
513 |
+
layer_past_key_values = (
|
514 |
+
past_key_values[idx] if past_key_values is not None else None
|
515 |
+
)
|
516 |
+
|
517 |
+
h, layer_cached_key_values = layer(
|
518 |
+
h, mask=mask, past_key_values=layer_past_key_values, use_cache=use_cache
|
519 |
+
)
|
520 |
+
|
521 |
+
if use_cache:
|
522 |
+
cached_key_values += (layer_cached_key_values,)
|
523 |
+
|
524 |
+
# Final norm and projection
|
525 |
+
h = self.output_norm(h)
|
526 |
+
|
527 |
+
if return_hidden:
|
528 |
+
return h, cached_key_values
|
529 |
+
|
530 |
+
logits = self.de_embedding_proj(h).float()
|
531 |
+
|
532 |
+
return logits, cached_key_values
|
533 |
+
|
534 |
+
|
535 |
+
########################################################
|
536 |
+
#
|
537 |
+
# HuggingFace Wrapper for the Pico Decoder model.
|
538 |
+
#
|
539 |
+
########################################################
|
540 |
+
|
541 |
+
|
542 |
+
class PicoDecoderHFConfig(PretrainedConfig):
|
543 |
+
"""Config class for the Pico Decoder HuggingFace wrapper."""
|
544 |
+
|
545 |
+
model_type = "pico_decoder"
|
546 |
+
|
547 |
+
@classmethod
|
548 |
+
def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> "PicoDecoderHFConfig":
|
549 |
+
# NOTE The typical from_dict method doesn't actually set the attributes unless they are
|
550 |
+
# defined in the constructor.
|
551 |
+
|
552 |
+
pico_config = cls(**kwargs)
|
553 |
+
|
554 |
+
# Because this class is just a wrapper around the ModelConfig dataclass, we need to do
|
555 |
+
# a little extra work to ensure that the attributes are actually set.
|
556 |
+
for key, value in config_dict.items():
|
557 |
+
setattr(pico_config, key, value)
|
558 |
+
|
559 |
+
return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
|
560 |
+
unused_kwargs = {
|
561 |
+
key: value for key, value in kwargs.items() if not hasattr(pico_config, key)
|
562 |
+
}
|
563 |
+
|
564 |
+
if return_unused_kwargs:
|
565 |
+
return pico_config, unused_kwargs
|
566 |
+
return pico_config
|
567 |
+
|
568 |
+
@classmethod
|
569 |
+
def from_dataclass(cls, model_config: "ModelConfig"):
|
570 |
+
"""Initialise from our custom config dataclass."""
|
571 |
+
return cls.from_dict(asdict(model_config))
|
572 |
+
|
573 |
+
|
574 |
+
class PicoDecoderHF(PreTrainedModel):
|
575 |
+
"""
|
576 |
+
HuggingFace wrapper for the Pico model.
|
577 |
+
|
578 |
+
Many evaluation frameworks require a model be setup as a HuggingFace model, so we provide a simple
|
579 |
+
wrapper that does just that. When we save checkpoints of the Pico model, we save both the normal
|
580 |
+
Pico model as well as the model wrapped in this HuggingFace class.
|
581 |
+
|
582 |
+
This also lets you do cool things like:
|
583 |
+
|
584 |
+
`model = AutoModelForCausalLM.from_pretrained("path/to/checkpoint")`
|
585 |
+
"""
|
586 |
+
|
587 |
+
config_class = PicoDecoderHFConfig
|
588 |
+
_no_split_modules = ["PicoBlock", "Attention", "SwiGLU", "RMSNorm"]
|
589 |
+
|
590 |
+
def __init__(self, config: PicoDecoderHFConfig):
|
591 |
+
super().__init__(config)
|
592 |
+
self.pico_decoder = PicoDecoder(config)
|
593 |
+
|
594 |
+
def forward(
|
595 |
+
self,
|
596 |
+
input_ids: torch.Tensor,
|
597 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
598 |
+
use_cache: bool = False,
|
599 |
+
**kwargs,
|
600 |
+
) -> Union[CausalLMOutput, CausalLMOutputWithPast]:
|
601 |
+
"""HuggingFace forward pass wrapper.
|
602 |
+
|
603 |
+
Forwards pass for the HuggingFace version of the Pico Model. Basic wrapper around the
|
604 |
+
Pico model's forward pass, and returns the output as a HuggingFace CausalLMOutput.
|
605 |
+
"""
|
606 |
+
logits, past_key_values = self.pico_decoder(
|
607 |
+
input_ids, past_key_values, use_cache
|
608 |
+
)
|
609 |
+
if use_cache:
|
610 |
+
return CausalLMOutputWithPast(
|
611 |
+
logits=logits,
|
612 |
+
past_key_values=past_key_values,
|
613 |
+
)
|
614 |
+
else:
|
615 |
+
return CausalLMOutput(
|
616 |
+
logits=logits,
|
617 |
+
)
|
618 |
+
|
619 |
+
|
620 |
+
# Register for auto classes
|
621 |
+
PicoDecoderHFConfig.register_for_auto_class()
|
622 |
+
PicoDecoderHF.register_for_auto_class("AutoModel")
|
623 |
+
PicoDecoderHF.register_for_auto_class("AutoModelForCausalLM")
|
checkpoints/step_5500/special_tokens_map.json
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"eos_token": {
|
3 |
+
"content": "<|endoftext|>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": false,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"mask_token": {
|
10 |
+
"content": "[MASK]",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": false,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"pad_token": {
|
17 |
+
"content": "<|padding|>",
|
18 |
+
"lstrip": false,
|
19 |
+
"normalized": false,
|
20 |
+
"rstrip": false,
|
21 |
+
"single_word": false
|
22 |
+
}
|
23 |
+
}
|