Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- checkpoints/step_0/config.jsonAdded+22
- checkpoints/step_0/fabric_state/checkpoint/bf16_zero_pp_rank_0_mp_rank_00_optim_states.ptAdded+3
- checkpoints/step_0/fabric_state/checkpoint/bf16_zero_pp_rank_1_mp_rank_00_optim_states.ptAdded+3
- checkpoints/step_0/fabric_state/checkpoint/bf16_zero_pp_rank_2_mp_rank_00_optim_states.ptAdded+3
- checkpoints/step_0/fabric_state/checkpoint/bf16_zero_pp_rank_3_mp_rank_00_optim_states.ptAdded+3
- checkpoints/step_0/fabric_state/checkpoint/mp_rank_00_model_states.ptAdded+3
- checkpoints/step_0/fabric_state/latestAdded+1
- checkpoints/step_0/fabric_state/zero_to_fp32.pyAdded+760
- checkpoints/step_0/model.safetensorsAdded+3
- checkpoints/step_0/pico_decoder.pyAdded+623
- checkpoints/step_0/special_tokens_map.jsonAdded+23
- checkpoints/step_0/tokenizer.jsonAdded
- checkpoints/step_0/tokenizer_config.jsonAdded+248
- checkpoints/step_100/config.jsonAdded+22
- checkpoints/step_100/fabric_state/checkpoint/bf16_zero_pp_rank_0_mp_rank_00_optim_states.ptAdded+3
- checkpoints/step_100/fabric_state/checkpoint/bf16_zero_pp_rank_1_mp_rank_00_optim_states.ptAdded+3
- checkpoints/step_100/fabric_state/checkpoint/bf16_zero_pp_rank_2_mp_rank_00_optim_states.ptAdded+3
- checkpoints/step_100/fabric_state/checkpoint/bf16_zero_pp_rank_3_mp_rank_00_optim_states.ptAdded+3
- checkpoints/step_100/fabric_state/checkpoint/mp_rank_00_model_states.ptAdded+3
- checkpoints/step_100/fabric_state/latestAdded+1
- checkpoints/step_100/fabric_state/zero_to_fp32.pyAdded+760
- checkpoints/step_100/model.safetensorsAdded+3
- checkpoints/step_100/pico_decoder.pyAdded+623
- checkpoints/step_100/special_tokens_map.jsonAdded+23
- checkpoints/step_100/tokenizer.jsonAdded
- checkpoints/step_100/tokenizer_config.jsonAdded+248
- checkpoints/step_1000/config.jsonAdded+22
- checkpoints/step_1000/fabric_state/checkpoint/bf16_zero_pp_rank_0_mp_rank_00_optim_states.ptAdded+3
- checkpoints/step_1000/fabric_state/checkpoint/bf16_zero_pp_rank_1_mp_rank_00_optim_states.ptAdded+3
- checkpoints/step_1000/fabric_state/checkpoint/bf16_zero_pp_rank_2_mp_rank_00_optim_states.ptAdded+3
- checkpoints/step_1000/fabric_state/checkpoint/bf16_zero_pp_rank_3_mp_rank_00_optim_states.ptAdded+3
- checkpoints/step_1000/fabric_state/checkpoint/mp_rank_00_model_states.ptAdded+3
- checkpoints/step_1000/fabric_state/latestAdded+1
- checkpoints/step_1000/fabric_state/zero_to_fp32.pyAdded+760
- checkpoints/step_1000/model.safetensorsAdded+3
- checkpoints/step_1000/pico_decoder.pyAdded+623
- checkpoints/step_1000/special_tokens_map.jsonAdded+23
- checkpoints/step_1000/tokenizer.jsonAdded
- checkpoints/step_1000/tokenizer_config.jsonAdded+248
- checkpoints/step_1100/config.jsonAdded+22
- checkpoints/step_1100/fabric_state/checkpoint/bf16_zero_pp_rank_0_mp_rank_00_optim_states.ptAdded+3
- checkpoints/step_1100/fabric_state/checkpoint/bf16_zero_pp_rank_1_mp_rank_00_optim_states.ptAdded+3
- checkpoints/step_1100/fabric_state/checkpoint/bf16_zero_pp_rank_2_mp_rank_00_optim_states.ptAdded+3
- checkpoints/step_1100/fabric_state/checkpoint/bf16_zero_pp_rank_3_mp_rank_00_optim_states.ptAdded+3
- checkpoints/step_1100/fabric_state/checkpoint/mp_rank_00_model_states.ptAdded+3
- checkpoints/step_1100/fabric_state/latestAdded+1
- checkpoints/step_1100/fabric_state/zero_to_fp32.pyAdded+760
- checkpoints/step_1100/model.safetensorsAdded+3
- checkpoints/step_1100/pico_decoder.pyAdded+623
- checkpoints/step_1100/special_tokens_map.jsonAdded+23
12345678910111213141516171819202122{ "activation_hidden_dim": 384, "architectures": [ "PicoDecoderHF" ], "attention_n_heads": 12, "attention_n_kv_heads": 4, "auto_map": { "AutoConfig": "pico_decoder.PicoDecoderHFConfig", "AutoModelForCausalLM": "pico_decoder.PicoDecoderHF" }, "batch_size": 1024, "d_model": 96, "max_seq_len": 512, "model_type": "pico_decoder", "n_layers": 12, "norm_eps": 1e-06, "position_emb_theta": 10000.0, "torch_dtype": "float32", "transformers_version": "4.48.3", "vocab_size": 50281}123version https://git-lfs.github.com/spec/v1oid sha256:a36c8cbc5473ee0e6581c5a4ef59c3d76c5a4ea96b143bc37d37bdf4f5d74fb3size 17813605123version https://git-lfs.github.com/spec/v1oid sha256:6dbe7b6c085002a5719e9a01d16105161fe1cda882661fcb45ba5f8c95987241size 17820709123version https://git-lfs.github.com/spec/v1oid sha256:086e73504b7e21f2b8d35c1538a6fb5ef96e402a3791be18fd450d8c69ab2b58size 17813989123version https://git-lfs.github.com/spec/v1oid sha256:e01b9cde440f6fc3c808213055a2207ca453df5377804c15c134132c1be946c0size 17813669123version https://git-lfs.github.com/spec/v1oid sha256:3afba4e494583b2af7c0c14f9122daf96f908e1afe6482b3f483f6b185343012size 356528251checkpoint123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760#!/usr/bin/env python
# Copyright (c) Microsoft Corporation.# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
# This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets# copied into the top level checkpoint dir, so the user can easily do the conversion at any point in# the future. Once extracted, the weights don't require DeepSpeed and can be used in any# application.## example:# python zero_to_fp32.py . output_dir/# or# python zero_to_fp32.py . output_dir/ --safe_serialization
import argparseimport torchimport globimport mathimport osimport reimport gcimport jsonimport numpy as npfrom tqdm import tqdmfrom collections import OrderedDictfrom dataclasses import dataclass
# while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with# DeepSpeed data structures it has to be available in the current python environment.from deepspeed.utils import loggerfrom deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS, FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES, FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
@dataclassclass zero_model_state: buffers: dict() param_shapes: dict() shared_params: list ds_version: int frozen_param_shapes: dict() frozen_param_fragments: dict()
debug = 0
# load to cpudevice = torch.device('cpu')
def atoi(text): return int(text) if text.isdigit() else text
def natural_keys(text): ''' alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments) ''' return [atoi(c) for c in re.split(r'(\d+)', text)]
def get_model_state_file(checkpoint_dir, zero_stage): if not os.path.isdir(checkpoint_dir): raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
# there should be only one file if zero_stage <= 2: file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt") elif zero_stage == 3: file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
if not os.path.exists(file): raise FileNotFoundError(f"can't find model states file at '{file}'")
return file
def get_checkpoint_files(checkpoint_dir, glob_pattern): # XXX: need to test that this simple glob rule works for multi-node setup too ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
if len(ckpt_files) == 0: raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
return ckpt_files
def get_optim_files(checkpoint_dir): return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
def get_model_state_files(checkpoint_dir): return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
def parse_model_states(files): zero_model_states = [] for file in files: state_dict = torch.load(file, map_location=device, weights_only=False)
if BUFFER_NAMES not in state_dict: raise ValueError(f"{file} is not a model state checkpoint") buffer_names = state_dict[BUFFER_NAMES] if debug: print("Found buffers:", buffer_names)
# recover just the buffers while restoring them to fp32 if they were saved in fp16 buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names} param_shapes = state_dict[PARAM_SHAPES]
# collect parameters that are included in param_shapes param_names = [] for s in param_shapes: for name in s.keys(): param_names.append(name)
# update with frozen parameters frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None) if frozen_param_shapes is not None: if debug: print(f"Found frozen_param_shapes: {frozen_param_shapes}") param_names += list(frozen_param_shapes.keys())
# handle shared params shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
ds_version = state_dict.get(DS_VERSION, None)
frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
z_model_state = zero_model_state(buffers=buffers, param_shapes=param_shapes, shared_params=shared_params, ds_version=ds_version, frozen_param_shapes=frozen_param_shapes, frozen_param_fragments=frozen_param_fragments) zero_model_states.append(z_model_state)
return zero_model_states
def parse_optim_states(files, ds_checkpoint_dir): total_files = len(files) state_dicts = [] for f in tqdm(files, desc='Loading checkpoint shards'): state_dict = torch.load(f, map_location=device, mmap=True, weights_only=False) # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights # and also handle the case where it was already removed by another helper script state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None) state_dicts.append(state_dict)
if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]: raise ValueError(f"{files[0]} is not a zero checkpoint") zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE] world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
# For ZeRO-2 each param group can have different partition_count as data parallelism for expert # parameters can be different from data parallelism for non-expert parameters. So we can just # use the max of the partition_count to get the dp world_size.
if type(world_size) is list: world_size = max(world_size)
if world_size != total_files: raise ValueError( f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. " "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes." )
# the groups are named differently in each stage if zero_stage <= 2: fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS elif zero_stage == 3: fp32_groups_key = FP32_FLAT_GROUPS else: raise ValueError(f"unknown zero stage {zero_stage}")
fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))] return zero_stage, world_size, fp32_flat_groups
def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters): """ Returns fp32 state_dict reconstructed from ds checkpoint
Args: - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
""" print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
optim_files = get_optim_files(ds_checkpoint_dir) zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir) print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
model_files = get_model_state_files(ds_checkpoint_dir)
zero_model_states = parse_model_states(model_files) print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
if zero_stage <= 2: return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters) elif zero_stage == 3: return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters)
def _zero2_merge_frozen_params(state_dict, zero_model_states): if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0: return
frozen_param_shapes = zero_model_states[0].frozen_param_shapes frozen_param_fragments = zero_model_states[0].frozen_param_fragments
if debug: num_elem = sum(s.numel() for s in frozen_param_shapes.values()) print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
wanted_params = len(frozen_param_shapes) wanted_numel = sum(s.numel() for s in frozen_param_shapes.values()) avail_numel = sum([p.numel() for p in frozen_param_fragments.values()]) print(f'Frozen params: Have {avail_numel} numels to process.') print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
total_params = 0 total_numel = 0 for name, shape in frozen_param_shapes.items(): total_params += 1 unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel
state_dict[name] = frozen_param_fragments[name]
if debug: print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
def _has_callable(obj, fn): attr = getattr(obj, fn, None) return callable(attr)
def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states): param_shapes = zero_model_states[0].param_shapes
# Reconstruction protocol: # # XXX: document this
if debug: for i in range(world_size): for j in range(len(fp32_flat_groups[0])): print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
# XXX: memory usage doubles here (zero2) num_param_groups = len(fp32_flat_groups[0]) merged_single_partition_of_fp32_groups = [] for i in range(num_param_groups): merged_partitions = [sd[i] for sd in fp32_flat_groups] full_single_fp32_vector = torch.cat(merged_partitions, 0) merged_single_partition_of_fp32_groups.append(full_single_fp32_vector) avail_numel = sum( [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
if debug: wanted_params = sum([len(shapes) for shapes in param_shapes]) wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes]) # not asserting if there is a mismatch due to possible padding print(f"Have {avail_numel} numels to process.") print(f"Need {wanted_numel} numels in {wanted_params} params.")
# params # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support # out-of-core computing solution total_numel = 0 total_params = 0 for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups): offset = 0 avail_numel = full_single_fp32_vector.numel() for name, shape in shapes.items():
unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape) total_numel += unpartitioned_numel total_params += 1
if debug: print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ") state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape) offset += unpartitioned_numel
# Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex # paddings performed in the code it's almost impossible to predict the exact numbers w/o the # live optimizer object, so we are checking that the numbers are within the right range align_to = 2 * world_size
def zero2_align(x): return align_to * math.ceil(x / align_to)
if debug: print(f"original offset={offset}, avail_numel={avail_numel}")
offset = zero2_align(offset) avail_numel = zero2_align(avail_numel)
if debug: print(f"aligned offset={offset}, avail_numel={avail_numel}")
# Sanity check if offset != avail_numel: raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters): state_dict = OrderedDict()
# buffers buffers = zero_model_states[0].buffers state_dict.update(buffers) if debug: print(f"added {len(buffers)} buffers")
if not exclude_frozen_parameters: _zero2_merge_frozen_params(state_dict, zero_model_states)
_zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
# recover shared parameters for pair in zero_model_states[0].shared_params: if pair[1] in state_dict: state_dict[pair[0]] = state_dict[pair[1]]
return state_dict
def zero3_partitioned_param_info(unpartitioned_numel, world_size): remainder = unpartitioned_numel % world_size padding_numel = (world_size - remainder) if remainder else 0 partitioned_numel = math.ceil(unpartitioned_numel / world_size) return partitioned_numel, padding_numel
def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states): if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0: return
if debug: for i in range(world_size): num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values()) print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
frozen_param_shapes = zero_model_states[0].frozen_param_shapes wanted_params = len(frozen_param_shapes) wanted_numel = sum(s.numel() for s in frozen_param_shapes.values()) avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size print(f'Frozen params: Have {avail_numel} numels to process.') print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
total_params = 0 total_numel = 0 for name, shape in zero_model_states[0].frozen_param_shapes.items(): total_params += 1 unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel
param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states) state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
if debug: print( f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}" )
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
class GatheredTensor: """ A pseudo tensor that collects partitioned weights. It is more memory efficient when there are multiple groups. """
def __init__(self, flat_groups, flat_groups_offset, offset, partitioned_numel, shape): self.flat_groups = flat_groups self.flat_groups_offset = flat_groups_offset self.offset = offset self.partitioned_numel = partitioned_numel self.shape = shape self.dtype = self.flat_groups[0][0].dtype
def contiguous(self): """ Merge partitioned weights from flat_groups into a single tensor. """ end_idx = self.offset + self.partitioned_numel world_size = len(self.flat_groups) pad_flat_param_chunks = []
for rank_i in range(world_size): # for each rank, we need to collect weights from related group/groups flat_groups_at_rank_i = self.flat_groups[rank_i] start_group_id = None end_group_id = None for group_id in range(len(self.flat_groups_offset)): if self.flat_groups_offset[group_id] <= self.offset < self.flat_groups_offset[group_id + 1]: start_group_id = group_id if self.flat_groups_offset[group_id] < end_idx <= self.flat_groups_offset[group_id + 1]: end_group_id = group_id break # collect weights from related group/groups for group_id in range(start_group_id, end_group_id + 1): flat_tensor = flat_groups_at_rank_i[group_id] start_offset = self.offset - self.flat_groups_offset[group_id] end_offset = min(end_idx, self.flat_groups_offset[group_id + 1]) - self.flat_groups_offset[group_id] pad_flat_param_chunks.append(flat_tensor[start_offset:end_offset])
# collect weights from all ranks pad_flat_param = torch.cat(pad_flat_param_chunks, dim=0) param = pad_flat_param[:self.shape.numel()].view(self.shape).contiguous() return param
def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states): param_shapes = zero_model_states[0].param_shapes avail_numel = sum([flat_group.numel() for flat_group in fp32_flat_groups[0]]) * world_size
# Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each # param, re-consolidating each param, while dealing with padding if any
# merge list of dicts, preserving order param_shapes = {k: v for d in param_shapes for k, v in d.items()}
if debug: for i in range(world_size): print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
wanted_params = len(param_shapes) wanted_numel = sum(shape.numel() for shape in param_shapes.values()) # not asserting if there is a mismatch due to possible padding avail_numel = fp32_flat_groups[0].numel() * world_size print(f"Trainable params: Have {avail_numel} numels to process.") print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
# params # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support # out-of-core computing solution offset = 0 total_numel = 0 total_params = 0 flat_groups_offset = [0] + list(np.cumsum([flat_tensor.numel() for flat_tensor in fp32_flat_groups[0]])) for name, shape in tqdm(param_shapes.items(), desc='Gathering sharded weights'): unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel total_params += 1 partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
if debug: print( f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}" )
# memory efficient tensor tensor = GatheredTensor(fp32_flat_groups, flat_groups_offset, offset, partitioned_numel, shape) state_dict[name] = tensor offset += partitioned_numel
offset *= world_size
# Sanity check if offset != avail_numel: raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters): state_dict = OrderedDict()
# buffers buffers = zero_model_states[0].buffers state_dict.update(buffers) if debug: print(f"added {len(buffers)} buffers")
if not exclude_frozen_parameters: _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
_zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
# recover shared parameters for pair in zero_model_states[0].shared_params: if pair[1] in state_dict: state_dict[pair[0]] = state_dict[pair[1]]
return state_dict
def to_torch_tensor(state_dict, return_empty_tensor=False): """ Convert state_dict of GatheredTensor to torch tensor """ torch_state_dict = {} converted_tensors = {} for name, tensor in state_dict.items(): tensor_id = id(tensor) if tensor_id in converted_tensors: # shared tensors shared_tensor = torch_state_dict[converted_tensors[tensor_id]] torch_state_dict[name] = shared_tensor else: converted_tensors[tensor_id] = name if return_empty_tensor: torch_state_dict[name] = torch.empty(tensor.shape, dtype=tensor.dtype) else: torch_state_dict[name] = tensor.contiguous() return torch_state_dict
def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None, exclude_frozen_parameters=False, lazy_mode=False): """ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example via a model hub.
Args: - ``checkpoint_dir``: path to the desired checkpoint folder - ``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`` - ``exclude_frozen_parameters``: exclude frozen parameters - ``lazy_mode``: get state_dict in lazy mode. It returns a dict of pesduo tensor instead of torch tensor, which is more memory efficient. Convert the pesduo tensor to torch tensor by ``.contiguous()``
Returns: - pytorch ``state_dict``
A typical usage might be ::
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint # do the training and checkpoint saving state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu model = model.cpu() # move to cpu model.load_state_dict(state_dict) # submit to model hub or save the model to share with others
In this example the ``model`` will no longer be usable in the deepspeed context of the same application. i.e. you will need to re-initialize the deepspeed engine, since ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
Note: the above usage may not work if your application doesn't have sufficient free CPU memory. You may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with the checkpoint. Or you can load state_dict in lazy mode ::
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, lazy_mode=True) # not on cpu for name, lazy_tensor in state_dict.item(): tensor = lazy_tensor.contiguous() # to cpu print(name, tensor) # del tensor to release memory if it no longer in use """ if tag is None: latest_path = os.path.join(checkpoint_dir, 'latest') if os.path.isfile(latest_path): with open(latest_path, 'r') as fd: tag = fd.read().strip() else: raise ValueError(f"Unable to find 'latest' file at {latest_path}")
ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
if not os.path.isdir(ds_checkpoint_dir): raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
state_dict = _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters) if lazy_mode: return state_dict else: return to_torch_tensor(state_dict)
def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_dir, max_shard_size="5GB", safe_serialization=False, tag=None, exclude_frozen_parameters=False): """ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
Args: - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) - ``output_dir``: directory to the pytorch fp32 state_dict output files - ``max_shard_size``: the maximum size for a checkpoint before being sharded, default value is 5GB - ``safe_serialization``: whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`). - ``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`` - ``exclude_frozen_parameters``: exclude frozen parameters """
# Dependency pre-check if safe_serialization: try: from safetensors.torch import save_file except ImportError: print('If you want to use `safe_serialization`, please `pip install safetensors`') raise if max_shard_size is not None: try: from huggingface_hub import split_torch_state_dict_into_shards except ImportError: print('If you want to use `max_shard_size`, please `pip install huggingface_hub`') raise
# Convert zero checkpoint to state_dict state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag, exclude_frozen_parameters, lazy_mode=True)
# Shard the model if it is too big. weights_name = "model.safetensors" if safe_serialization else "pytorch_model.bin" if max_shard_size is not None: filename_pattern = weights_name.replace(".bin", "{suffix}.bin").replace(".safetensors", "{suffix}.safetensors") # an memory-efficient approach for sharding empty_state_dict = to_torch_tensor(state_dict, return_empty_tensor=True) state_dict_split = split_torch_state_dict_into_shards(empty_state_dict, filename_pattern=filename_pattern, max_shard_size=max_shard_size) else: from collections import namedtuple StateDictSplit = namedtuple("StateDictSplit", ["is_sharded", "filename_to_tensors"]) state_dict_split = StateDictSplit(is_sharded=False, filename_to_tensors={weights_name: list(state_dict.keys())})
# Save the model by shard os.makedirs(output_dir, exist_ok=True) filename_to_tensors = state_dict_split.filename_to_tensors.items() for shard_file, tensors in tqdm(filename_to_tensors, desc="Saving checkpoint shards"): shard_state_dict = {tensor_name: state_dict[tensor_name] for tensor_name in tensors} shard_state_dict = to_torch_tensor(shard_state_dict) output_path = os.path.join(output_dir, shard_file) if safe_serialization: save_file(shard_state_dict, output_path, metadata={"format": "pt"}) else: torch.save(shard_state_dict, output_path) # release the memory of current shard for tensor_name in list(shard_state_dict.keys()): del state_dict[tensor_name] del shard_state_dict[tensor_name] del shard_state_dict gc.collect()
# Save index if sharded if state_dict_split.is_sharded: index = { "metadata": state_dict_split.metadata, "weight_map": state_dict_split.tensor_to_filename, } save_index_file = "model.safetensors.index.json" if safe_serialization else "pytorch_model.bin.index.json" save_index_file = os.path.join(output_dir, save_index_file) with open(save_index_file, "w", encoding="utf-8") as f: content = json.dumps(index, indent=2, sort_keys=True) + "\n" f.write(content)
def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None): """ 1. Put the provided model to cpu 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` 3. Load it into the provided model
Args: - ``model``: the model object to update - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) - ``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``
Returns: - ``model`: modified model
Make sure you have plenty of CPU memory available before you call this function. If you don't have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it conveniently placed for you in the checkpoint folder.
A typical usage might be ::
from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir) # submit to model hub or save the model to share with others
Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context of the same application. i.e. you will need to re-initialize the deepspeed engine, since ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
""" logger.info(f"Extracting fp32 weights") state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
logger.info(f"Overwriting model with fp32 weights") model = model.cpu() model.load_state_dict(state_dict, strict=False)
return model
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("checkpoint_dir", type=str, help="path to the desired checkpoint folder, e.g., path/checkpoint-12") parser.add_argument("output_dir", type=str, help="directory to the pytorch fp32 state_dict output files" "(e.g. path/checkpoint-12-output/)") parser.add_argument( "--max_shard_size", type=str, default="5GB", help="The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size" "lower than this size. If expressed as a string, needs to be digits followed by a unit (like `5MB`" "We default it to 5GB in order for models to be able to run easily on free-tier google colab instances" "without CPU OOM issues.") parser.add_argument( "--safe_serialization", default=False, action='store_true', help="Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).") parser.add_argument("-t", "--tag", type=str, default=None, help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1") parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters") parser.add_argument("-d", "--debug", action='store_true', help="enable debug") args = parser.parse_args()
debug = args.debug
convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir, args.output_dir, max_shard_size=args.max_shard_size, safe_serialization=args.safe_serialization, tag=args.tag, exclude_frozen_parameters=args.exclude_frozen_parameters)123version https://git-lfs.github.com/spec/v1oid sha256:6301e33cc7f38d246f9bc8ad8b5eb5481ffb34b3ff2404d26cadf6630fb567f2size 45125928123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623"""Pico Decoder: A Lightweight Causal Transformer Language Model
Pico Decoder uses a simple LLAMA-style transformer architecture, written for clarity and educational purposes.
Everything is written with a modular design for easy modification and experimentation.
Key features:- RMSNorm for layer normalization- Rotary Positional Embeddings (RoPE)- Multi-head attention with KV-cache support- SwiGLU activation function- Residual connections throughout
- KV-cache for faster autoregressive generation
References: - RoPE: https://arxiv.org/abs/2104.09864 - SwiGLU: https://arxiv.org/abs/2002.05202 - LLAMA: https://arxiv.org/abs/2302.13971
Adapted from: - OLMO: https://github.com/allenai/OLMo - LLAMA: https://github.com/meta/llama"""
from dataclasses import asdictfrom typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch.nn.attention import SDPBackend, sdpa_kernelfrom transformers import PretrainedConfig, PreTrainedModelfrom transformers.modeling_outputs import CausalLMOutput, CausalLMOutputWithPast
try: if TYPE_CHECKING: # We need to do this to avoid importing these when creating the HF-compatible models from src.config import ModelConfigexcept ImportError: pass
########################################################## Layer Normalization#########################################################
class RMSNorm(torch.nn.Module): """Root Mean Square Layer Normalization.
A variant of Layer Normalization that uses RMS statistics instead of mean/variance, resulting in improved stability and performance.
Args: config (Union[ModelConfig, PicoHFConfig]): Configuration object containing normalization parameters - config.norm_eps: Small constant for numerical stability - config.d_model: Model dimension for the weight parameter
References: https://arxiv.org/abs/1910.07467 """
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]): super().__init__() self.eps = config.norm_eps self.weight = nn.Parameter(torch.ones(config.d_model))
def _norm(self, x: torch.Tensor) -> torch.Tensor: """ Normalizes the input tensor by its RMS value. """ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x: torch.Tensor) -> torch.Tensor: """ Applies RMS normalization to the input tensor and scales it by the weight parameter. """ output = self._norm(x.float()).type_as(x) return output * self.weight
########################################################## Positional Embedding#########################################################
class RoPE(nn.Module): """Rotary Positional Embeddings (RoPE).
Implements position-dependent rotation of keys and queries in attention mechanism, allowing better modeling of relative positions in sequences. Uses complex number operations for efficient rotation.
Args: config (Union[ModelConfig, PicoHFConfig]): Model configuration containing: - config.position_emb_theta: Base for frequency computation - config.d_model: Model dimension - config.attention_n_heads: Number of attention heads - config.max_seq_len: Maximum sequence length
References: https://arxiv.org/abs/2104.09864 """
_freqs_cis_tensor: torch.Tensor | None = None
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]): super().__init__()
self.theta = config.position_emb_theta self.dim = config.d_model // config.attention_n_heads
max_seq_len = config.max_seq_len
# only gets set once, and then reused for all RoPE instances if RoPE._freqs_cis_tensor is None: RoPE._freqs_cis_tensor = self._setup_freqs_cis( max_seq_len, self.theta, self.dim )
# register _freqs_cis buffer # can be easily recomputed so persistent=False self.register_buffer("_freqs_cis", self._freqs_cis_tensor, persistent=False)
@classmethod def _setup_freqs_cis(cls, seq_len: int, theta: float, dim: int) -> torch.Tensor: """Setup Frequency Tensor for RoPE Embeddings
Initializes the complex frequency tensor that is used to compute the RoPE embeddings.
Note other implementations will use cos and sin directly, but using the complex number representation is (probably?) more efficient:
e^(theta * i * t) = cos(theta * t) + i * sin(theta * t) [Euler's formula] """ _freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)) positions = torch.arange(seq_len) freqs = torch.outer(positions, _freqs) return torch.polar(torch.ones_like(freqs), freqs) # complex64
def get_freqs_cis( self, input_shape: torch.Size, start_pos: int, end_pos: int ) -> torch.Tensor: """Reshape Frequency Tensor for RoPE Embeddings
Makes the frequency tensor broadcastable with the input tensor. """ _freqs_cis = self._freqs_cis[start_pos:end_pos] ndim = len(input_shape) assert 0 <= 1 < ndim assert _freqs_cis.shape == (input_shape[1], input_shape[-1])
# TODO: Check whether this is correct (might be able to remove this) shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(input_shape)] return _freqs_cis.view(*shape)
def forward( self, queries: torch.Tensor, keys: torch.Tensor, start_pos: int = 0, ) -> Tuple[torch.Tensor, torch.Tensor]: """Apply RoPE Embeddings to Queries and Keys
Applies the rotary positional embeddings to the input tensors via complex num multiplication
NOTE: The start_pos is used if we want to use the kv_cache in the attention mechanism. """ queries_ = torch.view_as_complex( queries.float().reshape(*queries.shape[:-1], -1, 2) ) keys_ = torch.view_as_complex(keys.float().reshape(*keys.shape[:-1], -1, 2))
input_shape = ( queries_.shape ) # same as keys: (batch_size, seq_len, n_heads, head_dim/2) freqs_start_pos = start_pos freqs_end_pos = freqs_start_pos + queries_.shape[1]
freqs_cis = self.get_freqs_cis(input_shape, freqs_start_pos, freqs_end_pos)
queries_rotated = torch.view_as_real(queries_ * freqs_cis).flatten(3) keys_rotated = torch.view_as_real(keys_ * freqs_cis).flatten(3) return queries_rotated.type_as(queries), keys_rotated.type_as(keys)
########################################################## Attention#########################################################
class Attention(nn.Module): """Multi-head Attention with Group Query Attention support.
Implements scaled dot-product attention and supports: - Grouped Query Attention (GQA) - Key-Value caching for efficient inference - RoPE integration
Args: config (Union[ModelConfig, PretrainedConfig]): Configuration containing: - config.attention_n_heads: Number of attention heads - config.attention_n_kv_heads: Number of key/value heads - config.d_model: Model dimension - config.batch_size: Maximum batch size - config.max_seq_len: Maximum sequence length
Shape: - Input: (batch_size, seq_len, d_model) - Output: (batch_size, seq_len, d_model) """
def __init__( self, config: Union["ModelConfig", "PicoDecoderHFConfig"], ): super().__init__()
self.n_heads = config.attention_n_heads self.n_kv_heads = config.attention_n_kv_heads
self.batch_size = config.batch_size self.max_seq_len = config.max_seq_len
d_model = config.d_model self.head_dim = d_model // self.n_heads
self.n_rep = self.n_heads // self.n_kv_heads
self.q_proj = nn.Linear(d_model, self.n_heads * self.head_dim, bias=False) self.k_proj = nn.Linear(d_model, self.n_kv_heads * self.head_dim, bias=False) self.v_proj = nn.Linear(d_model, self.n_kv_heads * self.head_dim, bias=False) self.o_proj = nn.Linear(self.n_heads * self.head_dim, d_model, bias=False)
self.rope = RoPE(config)
def forward( self, input: torch.Tensor, mask: Optional[torch.Tensor] = None, past_key_values: Optional[Tuple[torch.Tensor, ...]] = None, use_cache: bool = False, ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]: """Forward pass for the attention mechanism.
Computes queries, keys, and values for the attention mechanism. Applies rotary positional embeddings to the queries and keys, and then computes attention scores and outputs.
For an introduction to the attention mechanism, see: https://arxiv.org/abs/1706.03762
A few things to note: - The past_key_values is used to implement the KV cache, which is used to speed up generation by caching the KV pairs from previous forward passes. This is useful when doing tasks that require generating multiple tokens conditioned on previous tokens (e.g. language modeling, text generation, etc.). The way the KV cache is implemented is that each layer has its own KV cache - this KV cache is implemented as a tuple. """ bsz, seq_len, _ = input.shape _queries, _keys, _values = ( self.q_proj(input), self.k_proj(input), self.v_proj(input), )
# Reshaping for multi-head attention queries = _queries.view(bsz, seq_len, self.n_heads, self.head_dim) keys = _keys.view(bsz, seq_len, self.n_kv_heads, self.head_dim) values = _values.view(bsz, seq_len, self.n_kv_heads, self.head_dim)
# The start position is used to apply the RoPE embeddings to only the new tokens # when using the kv_cache in the attention mechanism. # We want to start from the last position in the cache. start_pos = past_key_values[0].shape[1] if past_key_values is not None else 0
# apply rotary positional embeddings queries, keys = self.rope(queries, keys, start_pos)
if past_key_values is not None: keys = torch.cat([past_key_values[0], keys], dim=1) values = torch.cat([past_key_values[1], values], dim=1)
if use_cache: cached_keys = keys cached_values = values else: cached_keys = None cached_values = None
queries = queries.transpose(1, 2) keys = keys.transpose(1, 2) values = values.transpose(1, 2)
apply_gqa = self.n_rep > 1 if apply_gqa and queries.device.type == "mps": # NOTE: MPS does not support GQA in the SDPA kernel, but we can repeat the keys and values # outside of the kernel to get the same effect. # See: https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html keys = keys.repeat_interleave(self.n_rep, dim=-3) values = values.repeat_interleave(self.n_rep, dim=-3) apply_gqa = False
backends = [SDPBackend.CUDNN_ATTENTION, SDPBackend.MATH]
with sdpa_kernel(backends=backends): attn_output = F.scaled_dot_product_attention( queries.contiguous(), keys.contiguous(), values.contiguous(), attn_mask=mask.to(queries.dtype), enable_gqa=apply_gqa, )
attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, seq_len, -1) output = self.o_proj(attn_output)
return output, (cached_keys, cached_values)
########################################################## SwiGLU (Combines MLP and Activation)#########################################################
class SwiGLU(nn.Module): """SwiGLU Activation Function with Linear Projections.
Implements the SwiGLU activation function combined with linear transformations, serving as the feed-forward network in transformer blocks.
Args: config (Union[ModelConfig, PicoDecoderHFConfig]): Configuration containing: - config.d_model: Model dimension - config.activation_hidden_dim: Hidden dimension (typically 4 * d_model)
References: https://arxiv.org/abs/2002.05202 """
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]): super().__init__()
model_dim = config.d_model act_hidden_dim = config.activation_hidden_dim # usually 4 * d_model
self.w_0 = nn.Linear(model_dim, act_hidden_dim, bias=False) self.w_1 = nn.Linear(model_dim, act_hidden_dim, bias=False) self.w_2 = nn.Linear(act_hidden_dim, model_dim, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.w_2(F.silu(self.w_0(x)) * self.w_1(x))
########################################################## PicoDecoderBlock#########################################################
class PicoDecoderBlock(nn.Module): """Single Transformer Block with Attention and Feed-forward layers.
Implements a standard transformer block with: - Multi-head attention with normalization and residual connection - SwiGLU feed-forward network with normalization and residual connection
Args: config (Union[ModelConfig, PicoDecoderHFConfig]): Model configuration; either a dataclass or a HuggingFace PicoDecoderHFConfig """
def __init__( self, config: Union["ModelConfig", "PicoDecoderHFConfig"], ): super().__init__()
self.attention = Attention(config) self.swiglu = SwiGLU(config) self.attention_norm = RMSNorm(config) self.swiglu_norm = RMSNorm(config)
def forward( self, input: torch.Tensor, mask: Optional[torch.Tensor] = None, past_key_values: Optional[Tuple[torch.Tensor]] = None, use_cache: bool = False, ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]: attention_output, cached_key_values = self.attention( self.attention_norm(input), mask=mask, past_key_values=past_key_values, use_cache=use_cache, ) # NOTE: cached_key_values is None if use_cache is False
h = input + attention_output out = h + self.swiglu(self.swiglu_norm(h)) return out, cached_key_values
########################################################## Pico Decoder (Causal Transformer Model)#########################################################
class PicoDecoder(nn.Module): """ Pico Decoder: combines the embedding, causal decoder blocks, and output projection into a single autoregressive model.
For more information on the model, see the classes for the modules that make up the model. """
def __init__( self, model_config: Union["ModelConfig", "PicoDecoderHFConfig"], ): super().__init__() self.config = model_config
self.embedding_proj = nn.Embedding(self.config.vocab_size, self.config.d_model) self.layers = nn.ModuleList( [PicoDecoderBlock(self.config) for _ in range(self.config.n_layers)] ) self.output_norm = RMSNorm(self.config) self.de_embedding_proj = nn.Linear( self.config.d_model, self.config.vocab_size, bias=False )
def convert_to_hf_model(self) -> "PicoDecoderHF": """Convert the Lightning model to a HuggingFace model.""" # Build HF config hf_config = PicoDecoderHFConfig.from_dataclass(self.config)
# Instantiate the HF-wrapped model hf_model = PicoDecoderHF(hf_config)
# Grab our full state dict, prefixing module names raw_state = self.state_dict(prefix="pico_decoder.")
# Only keep keys that exist in the HF model (drops classifier_head, etc.) hf_keys = set(hf_model.state_dict().keys()) filtered_state = {k: v for k, v in raw_state.items() if k in hf_keys}
# Load into HF model, ignore any missing keys hf_model.load_state_dict(filtered_state, strict=False)
return hf_model
def forward( self, input_ids: torch.Tensor, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, use_cache: bool = False, return_hidden: bool = False, ) -> Tuple[torch.Tensor, Optional[Tuple[Tuple[torch.Tensor, torch.Tensor]]]]: """ This is the forward pass for the entire Pico model. It boils down to: - Embedding the input ids - Creating a causal mask - Processing through the pico layers - Projecting the output to logits
NOTE: One feature that might be confusing is the KV cache. The KV cache is used to speed up generation by caching the KV pairs from previous forward passes. This is useful when doing tasks that require generating multiple tokens conditioned on previous tokens (e.g. language modeling, text generation, etc.). The way the KV cache is implemented is that each layer has its own KV cache which is stored as a tuple. The whole model then stores a tuple of these KV caches (so a tuple of tuples). """
seq_len = input_ids.shape[-1] h = self.embedding_proj(input_ids)
# Calculate start position from past cached KV pairs. Remember that each layer has its # own KV Cache. So when we index past_key_values, we need to index into the KV pairs for the # correct layer and then for either the keys or values. start_pos = 0 if past_key_values is None else past_key_values[0][0].shape[1]
# Create causal mask for current sequence mask = None if seq_len > 1: mask = torch.full((seq_len, seq_len), float("-inf")) mask = torch.triu(mask, diagonal=1)
# If using KV cache, extend mask to cover cached sequence length if past_key_values is not None: # Add zeros for cached tokens (we can attend to all of them) mask = torch.hstack([torch.zeros((seq_len, start_pos)), mask])
mask = mask.to(h.device)
# NOTE: If we are using the cache, we need to store the cached KV pairs for each layer # in a tuple. Each layer will have its own cached KV pair which we aggregate in a tuple. cached_key_values = () if use_cache else None
# Process through transformer blocks for idx, layer in enumerate(self.layers): layer_past_key_values = ( past_key_values[idx] if past_key_values is not None else None )
h, layer_cached_key_values = layer( h, mask=mask, past_key_values=layer_past_key_values, use_cache=use_cache )
if use_cache: cached_key_values += (layer_cached_key_values,)
# Final norm and projection h = self.output_norm(h)
if return_hidden: return h, cached_key_values
logits = self.de_embedding_proj(h).float()
return logits, cached_key_values
########################################################## HuggingFace Wrapper for the Pico Decoder model.#########################################################
class PicoDecoderHFConfig(PretrainedConfig): """Config class for the Pico Decoder HuggingFace wrapper."""
model_type = "pico_decoder"
@classmethod def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> "PicoDecoderHFConfig": # NOTE The typical from_dict method doesn't actually set the attributes unless they are # defined in the constructor.
pico_config = cls(**kwargs)
# Because this class is just a wrapper around the ModelConfig dataclass, we need to do # a little extra work to ensure that the attributes are actually set. for key, value in config_dict.items(): setattr(pico_config, key, value)
return_unused_kwargs = kwargs.pop("return_unused_kwargs", False) unused_kwargs = { key: value for key, value in kwargs.items() if not hasattr(pico_config, key) }
if return_unused_kwargs: return pico_config, unused_kwargs return pico_config
@classmethod def from_dataclass(cls, model_config: "ModelConfig"): """Initialise from our custom config dataclass.""" return cls.from_dict(asdict(model_config))
class PicoDecoderHF(PreTrainedModel): """ HuggingFace wrapper for the Pico model.
Many evaluation frameworks require a model be setup as a HuggingFace model, so we provide a simple wrapper that does just that. When we save checkpoints of the Pico model, we save both the normal Pico model as well as the model wrapped in this HuggingFace class.
This also lets you do cool things like:
`model = AutoModelForCausalLM.from_pretrained("path/to/checkpoint")` """
config_class = PicoDecoderHFConfig _no_split_modules = ["PicoBlock", "Attention", "SwiGLU", "RMSNorm"]
def __init__(self, config: PicoDecoderHFConfig): super().__init__(config) self.pico_decoder = PicoDecoder(config)
def forward( self, input_ids: torch.Tensor, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, use_cache: bool = False, **kwargs, ) -> Union[CausalLMOutput, CausalLMOutputWithPast]: """HuggingFace forward pass wrapper.
Forwards pass for the HuggingFace version of the Pico Model. Basic wrapper around the Pico model's forward pass, and returns the output as a HuggingFace CausalLMOutput. """ logits, past_key_values = self.pico_decoder( input_ids, past_key_values, use_cache ) if use_cache: return CausalLMOutputWithPast( logits=logits, past_key_values=past_key_values, ) else: return CausalLMOutput( logits=logits, )
# Register for auto classesPicoDecoderHFConfig.register_for_auto_class()PicoDecoderHF.register_for_auto_class("AutoModel")PicoDecoderHF.register_for_auto_class("AutoModelForCausalLM")1234567891011121314151617181920212223{ "eos_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "mask_token": { "content": "[MASK]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": { "content": "<|padding|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248{ "add_bos_token": false, "add_eos_token": false, "add_prefix_space": false, "added_tokens_decoder": { "0": { "content": "|||IP_ADDRESS|||", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "1": { "content": "<|padding|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "50254": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50255": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50256": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50257": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50258": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50259": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50260": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50261": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50262": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50263": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50264": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50265": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50266": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50267": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50268": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50269": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50270": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50271": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50272": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50273": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50274": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50275": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50276": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50277": { "content": "|||EMAIL_ADDRESS|||", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50278": { "content": "|||PHONE_NUMBER|||", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50279": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "50280": { "content": "[MASK]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true } }, "bos_token": null, "clean_up_tokenization_spaces": true, "eos_token": "<|endoftext|>", "extra_special_tokens": {}, "mask_token": "[MASK]", "model_max_length": 1000000000000000019884624838656, "pad_token": "<|padding|>", "tokenizer_class": "GPTNeoXTokenizer", "unk_token": null}12345678910111213141516171819202122{ "activation_hidden_dim": 384, "architectures": [ "PicoDecoderHF" ], "attention_n_heads": 12, "attention_n_kv_heads": 4, "auto_map": { "AutoConfig": "pico_decoder.PicoDecoderHFConfig", "AutoModelForCausalLM": "pico_decoder.PicoDecoderHF" }, "batch_size": 1024, "d_model": 96, "max_seq_len": 512, "model_type": "pico_decoder", "n_layers": 12, "norm_eps": 1e-06, "position_emb_theta": 10000.0, "torch_dtype": "float32", "transformers_version": "4.48.3", "vocab_size": 50281}123version https://git-lfs.github.com/spec/v1oid sha256:b8506c751b068cb04714edf2c57385a67f69ec53a0f3e3cba603b6c1343e5f18size 53434629123version https://git-lfs.github.com/spec/v1oid sha256:fbee43d3500a0da9b2dbe4459f9aa05eb0ffe86f7fe4a09244503406d6e46034size 53441797123version https://git-lfs.github.com/spec/v1oid sha256:49412e29f1e7bcf9359d8aa81dc478ee31f7a0723c5f3055344bfac547e06dfcsize 53434949123version https://git-lfs.github.com/spec/v1oid sha256:359b1dad8e4b95bb1e215be5679c94c3bd2a27da02e00be04af44dec41dc05besize 53434629123version https://git-lfs.github.com/spec/v1oid sha256:ab56386638a3956dd0c1d4ab8c2e5b723045936a35ade839c321eb01ec633a52size 356528251checkpoint123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760#!/usr/bin/env python
# Copyright (c) Microsoft Corporation.# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
# This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets# copied into the top level checkpoint dir, so the user can easily do the conversion at any point in# the future. Once extracted, the weights don't require DeepSpeed and can be used in any# application.## example:# python zero_to_fp32.py . output_dir/# or# python zero_to_fp32.py . output_dir/ --safe_serialization
import argparseimport torchimport globimport mathimport osimport reimport gcimport jsonimport numpy as npfrom tqdm import tqdmfrom collections import OrderedDictfrom dataclasses import dataclass
# while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with# DeepSpeed data structures it has to be available in the current python environment.from deepspeed.utils import loggerfrom deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS, FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES, FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
@dataclassclass zero_model_state: buffers: dict() param_shapes: dict() shared_params: list ds_version: int frozen_param_shapes: dict() frozen_param_fragments: dict()
debug = 0
# load to cpudevice = torch.device('cpu')
def atoi(text): return int(text) if text.isdigit() else text
def natural_keys(text): ''' alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments) ''' return [atoi(c) for c in re.split(r'(\d+)', text)]
def get_model_state_file(checkpoint_dir, zero_stage): if not os.path.isdir(checkpoint_dir): raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
# there should be only one file if zero_stage <= 2: file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt") elif zero_stage == 3: file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
if not os.path.exists(file): raise FileNotFoundError(f"can't find model states file at '{file}'")
return file
def get_checkpoint_files(checkpoint_dir, glob_pattern): # XXX: need to test that this simple glob rule works for multi-node setup too ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
if len(ckpt_files) == 0: raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
return ckpt_files
def get_optim_files(checkpoint_dir): return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
def get_model_state_files(checkpoint_dir): return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
def parse_model_states(files): zero_model_states = [] for file in files: state_dict = torch.load(file, map_location=device, weights_only=False)
if BUFFER_NAMES not in state_dict: raise ValueError(f"{file} is not a model state checkpoint") buffer_names = state_dict[BUFFER_NAMES] if debug: print("Found buffers:", buffer_names)
# recover just the buffers while restoring them to fp32 if they were saved in fp16 buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names} param_shapes = state_dict[PARAM_SHAPES]
# collect parameters that are included in param_shapes param_names = [] for s in param_shapes: for name in s.keys(): param_names.append(name)
# update with frozen parameters frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None) if frozen_param_shapes is not None: if debug: print(f"Found frozen_param_shapes: {frozen_param_shapes}") param_names += list(frozen_param_shapes.keys())
# handle shared params shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
ds_version = state_dict.get(DS_VERSION, None)
frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
z_model_state = zero_model_state(buffers=buffers, param_shapes=param_shapes, shared_params=shared_params, ds_version=ds_version, frozen_param_shapes=frozen_param_shapes, frozen_param_fragments=frozen_param_fragments) zero_model_states.append(z_model_state)
return zero_model_states
def parse_optim_states(files, ds_checkpoint_dir): total_files = len(files) state_dicts = [] for f in tqdm(files, desc='Loading checkpoint shards'): state_dict = torch.load(f, map_location=device, mmap=True, weights_only=False) # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights # and also handle the case where it was already removed by another helper script state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None) state_dicts.append(state_dict)
if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]: raise ValueError(f"{files[0]} is not a zero checkpoint") zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE] world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
# For ZeRO-2 each param group can have different partition_count as data parallelism for expert # parameters can be different from data parallelism for non-expert parameters. So we can just # use the max of the partition_count to get the dp world_size.
if type(world_size) is list: world_size = max(world_size)
if world_size != total_files: raise ValueError( f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. " "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes." )
# the groups are named differently in each stage if zero_stage <= 2: fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS elif zero_stage == 3: fp32_groups_key = FP32_FLAT_GROUPS else: raise ValueError(f"unknown zero stage {zero_stage}")
fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))] return zero_stage, world_size, fp32_flat_groups
def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters): """ Returns fp32 state_dict reconstructed from ds checkpoint
Args: - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
""" print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
optim_files = get_optim_files(ds_checkpoint_dir) zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir) print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
model_files = get_model_state_files(ds_checkpoint_dir)
zero_model_states = parse_model_states(model_files) print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
if zero_stage <= 2: return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters) elif zero_stage == 3: return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters)
def _zero2_merge_frozen_params(state_dict, zero_model_states): if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0: return
frozen_param_shapes = zero_model_states[0].frozen_param_shapes frozen_param_fragments = zero_model_states[0].frozen_param_fragments
if debug: num_elem = sum(s.numel() for s in frozen_param_shapes.values()) print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
wanted_params = len(frozen_param_shapes) wanted_numel = sum(s.numel() for s in frozen_param_shapes.values()) avail_numel = sum([p.numel() for p in frozen_param_fragments.values()]) print(f'Frozen params: Have {avail_numel} numels to process.') print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
total_params = 0 total_numel = 0 for name, shape in frozen_param_shapes.items(): total_params += 1 unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel
state_dict[name] = frozen_param_fragments[name]
if debug: print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
def _has_callable(obj, fn): attr = getattr(obj, fn, None) return callable(attr)
def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states): param_shapes = zero_model_states[0].param_shapes
# Reconstruction protocol: # # XXX: document this
if debug: for i in range(world_size): for j in range(len(fp32_flat_groups[0])): print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
# XXX: memory usage doubles here (zero2) num_param_groups = len(fp32_flat_groups[0]) merged_single_partition_of_fp32_groups = [] for i in range(num_param_groups): merged_partitions = [sd[i] for sd in fp32_flat_groups] full_single_fp32_vector = torch.cat(merged_partitions, 0) merged_single_partition_of_fp32_groups.append(full_single_fp32_vector) avail_numel = sum( [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
if debug: wanted_params = sum([len(shapes) for shapes in param_shapes]) wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes]) # not asserting if there is a mismatch due to possible padding print(f"Have {avail_numel} numels to process.") print(f"Need {wanted_numel} numels in {wanted_params} params.")
# params # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support # out-of-core computing solution total_numel = 0 total_params = 0 for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups): offset = 0 avail_numel = full_single_fp32_vector.numel() for name, shape in shapes.items():
unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape) total_numel += unpartitioned_numel total_params += 1
if debug: print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ") state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape) offset += unpartitioned_numel
# Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex # paddings performed in the code it's almost impossible to predict the exact numbers w/o the # live optimizer object, so we are checking that the numbers are within the right range align_to = 2 * world_size
def zero2_align(x): return align_to * math.ceil(x / align_to)
if debug: print(f"original offset={offset}, avail_numel={avail_numel}")
offset = zero2_align(offset) avail_numel = zero2_align(avail_numel)
if debug: print(f"aligned offset={offset}, avail_numel={avail_numel}")
# Sanity check if offset != avail_numel: raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters): state_dict = OrderedDict()
# buffers buffers = zero_model_states[0].buffers state_dict.update(buffers) if debug: print(f"added {len(buffers)} buffers")
if not exclude_frozen_parameters: _zero2_merge_frozen_params(state_dict, zero_model_states)
_zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
# recover shared parameters for pair in zero_model_states[0].shared_params: if pair[1] in state_dict: state_dict[pair[0]] = state_dict[pair[1]]
return state_dict
def zero3_partitioned_param_info(unpartitioned_numel, world_size): remainder = unpartitioned_numel % world_size padding_numel = (world_size - remainder) if remainder else 0 partitioned_numel = math.ceil(unpartitioned_numel / world_size) return partitioned_numel, padding_numel
def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states): if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0: return
if debug: for i in range(world_size): num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values()) print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
frozen_param_shapes = zero_model_states[0].frozen_param_shapes wanted_params = len(frozen_param_shapes) wanted_numel = sum(s.numel() for s in frozen_param_shapes.values()) avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size print(f'Frozen params: Have {avail_numel} numels to process.') print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
total_params = 0 total_numel = 0 for name, shape in zero_model_states[0].frozen_param_shapes.items(): total_params += 1 unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel
param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states) state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
if debug: print( f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}" )
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
class GatheredTensor: """ A pseudo tensor that collects partitioned weights. It is more memory efficient when there are multiple groups. """
def __init__(self, flat_groups, flat_groups_offset, offset, partitioned_numel, shape): self.flat_groups = flat_groups self.flat_groups_offset = flat_groups_offset self.offset = offset self.partitioned_numel = partitioned_numel self.shape = shape self.dtype = self.flat_groups[0][0].dtype
def contiguous(self): """ Merge partitioned weights from flat_groups into a single tensor. """ end_idx = self.offset + self.partitioned_numel world_size = len(self.flat_groups) pad_flat_param_chunks = []
for rank_i in range(world_size): # for each rank, we need to collect weights from related group/groups flat_groups_at_rank_i = self.flat_groups[rank_i] start_group_id = None end_group_id = None for group_id in range(len(self.flat_groups_offset)): if self.flat_groups_offset[group_id] <= self.offset < self.flat_groups_offset[group_id + 1]: start_group_id = group_id if self.flat_groups_offset[group_id] < end_idx <= self.flat_groups_offset[group_id + 1]: end_group_id = group_id break # collect weights from related group/groups for group_id in range(start_group_id, end_group_id + 1): flat_tensor = flat_groups_at_rank_i[group_id] start_offset = self.offset - self.flat_groups_offset[group_id] end_offset = min(end_idx, self.flat_groups_offset[group_id + 1]) - self.flat_groups_offset[group_id] pad_flat_param_chunks.append(flat_tensor[start_offset:end_offset])
# collect weights from all ranks pad_flat_param = torch.cat(pad_flat_param_chunks, dim=0) param = pad_flat_param[:self.shape.numel()].view(self.shape).contiguous() return param
def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states): param_shapes = zero_model_states[0].param_shapes avail_numel = sum([flat_group.numel() for flat_group in fp32_flat_groups[0]]) * world_size
# Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each # param, re-consolidating each param, while dealing with padding if any
# merge list of dicts, preserving order param_shapes = {k: v for d in param_shapes for k, v in d.items()}
if debug: for i in range(world_size): print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
wanted_params = len(param_shapes) wanted_numel = sum(shape.numel() for shape in param_shapes.values()) # not asserting if there is a mismatch due to possible padding avail_numel = fp32_flat_groups[0].numel() * world_size print(f"Trainable params: Have {avail_numel} numels to process.") print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
# params # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support # out-of-core computing solution offset = 0 total_numel = 0 total_params = 0 flat_groups_offset = [0] + list(np.cumsum([flat_tensor.numel() for flat_tensor in fp32_flat_groups[0]])) for name, shape in tqdm(param_shapes.items(), desc='Gathering sharded weights'): unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel total_params += 1 partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
if debug: print( f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}" )
# memory efficient tensor tensor = GatheredTensor(fp32_flat_groups, flat_groups_offset, offset, partitioned_numel, shape) state_dict[name] = tensor offset += partitioned_numel
offset *= world_size
# Sanity check if offset != avail_numel: raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters): state_dict = OrderedDict()
# buffers buffers = zero_model_states[0].buffers state_dict.update(buffers) if debug: print(f"added {len(buffers)} buffers")
if not exclude_frozen_parameters: _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
_zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
# recover shared parameters for pair in zero_model_states[0].shared_params: if pair[1] in state_dict: state_dict[pair[0]] = state_dict[pair[1]]
return state_dict
def to_torch_tensor(state_dict, return_empty_tensor=False): """ Convert state_dict of GatheredTensor to torch tensor """ torch_state_dict = {} converted_tensors = {} for name, tensor in state_dict.items(): tensor_id = id(tensor) if tensor_id in converted_tensors: # shared tensors shared_tensor = torch_state_dict[converted_tensors[tensor_id]] torch_state_dict[name] = shared_tensor else: converted_tensors[tensor_id] = name if return_empty_tensor: torch_state_dict[name] = torch.empty(tensor.shape, dtype=tensor.dtype) else: torch_state_dict[name] = tensor.contiguous() return torch_state_dict
def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None, exclude_frozen_parameters=False, lazy_mode=False): """ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example via a model hub.
Args: - ``checkpoint_dir``: path to the desired checkpoint folder - ``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`` - ``exclude_frozen_parameters``: exclude frozen parameters - ``lazy_mode``: get state_dict in lazy mode. It returns a dict of pesduo tensor instead of torch tensor, which is more memory efficient. Convert the pesduo tensor to torch tensor by ``.contiguous()``
Returns: - pytorch ``state_dict``
A typical usage might be ::
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint # do the training and checkpoint saving state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu model = model.cpu() # move to cpu model.load_state_dict(state_dict) # submit to model hub or save the model to share with others
In this example the ``model`` will no longer be usable in the deepspeed context of the same application. i.e. you will need to re-initialize the deepspeed engine, since ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
Note: the above usage may not work if your application doesn't have sufficient free CPU memory. You may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with the checkpoint. Or you can load state_dict in lazy mode ::
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, lazy_mode=True) # not on cpu for name, lazy_tensor in state_dict.item(): tensor = lazy_tensor.contiguous() # to cpu print(name, tensor) # del tensor to release memory if it no longer in use """ if tag is None: latest_path = os.path.join(checkpoint_dir, 'latest') if os.path.isfile(latest_path): with open(latest_path, 'r') as fd: tag = fd.read().strip() else: raise ValueError(f"Unable to find 'latest' file at {latest_path}")
ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
if not os.path.isdir(ds_checkpoint_dir): raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
state_dict = _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters) if lazy_mode: return state_dict else: return to_torch_tensor(state_dict)
def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_dir, max_shard_size="5GB", safe_serialization=False, tag=None, exclude_frozen_parameters=False): """ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
Args: - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) - ``output_dir``: directory to the pytorch fp32 state_dict output files - ``max_shard_size``: the maximum size for a checkpoint before being sharded, default value is 5GB - ``safe_serialization``: whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`). - ``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`` - ``exclude_frozen_parameters``: exclude frozen parameters """
# Dependency pre-check if safe_serialization: try: from safetensors.torch import save_file except ImportError: print('If you want to use `safe_serialization`, please `pip install safetensors`') raise if max_shard_size is not None: try: from huggingface_hub import split_torch_state_dict_into_shards except ImportError: print('If you want to use `max_shard_size`, please `pip install huggingface_hub`') raise
# Convert zero checkpoint to state_dict state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag, exclude_frozen_parameters, lazy_mode=True)
# Shard the model if it is too big. weights_name = "model.safetensors" if safe_serialization else "pytorch_model.bin" if max_shard_size is not None: filename_pattern = weights_name.replace(".bin", "{suffix}.bin").replace(".safetensors", "{suffix}.safetensors") # an memory-efficient approach for sharding empty_state_dict = to_torch_tensor(state_dict, return_empty_tensor=True) state_dict_split = split_torch_state_dict_into_shards(empty_state_dict, filename_pattern=filename_pattern, max_shard_size=max_shard_size) else: from collections import namedtuple StateDictSplit = namedtuple("StateDictSplit", ["is_sharded", "filename_to_tensors"]) state_dict_split = StateDictSplit(is_sharded=False, filename_to_tensors={weights_name: list(state_dict.keys())})
# Save the model by shard os.makedirs(output_dir, exist_ok=True) filename_to_tensors = state_dict_split.filename_to_tensors.items() for shard_file, tensors in tqdm(filename_to_tensors, desc="Saving checkpoint shards"): shard_state_dict = {tensor_name: state_dict[tensor_name] for tensor_name in tensors} shard_state_dict = to_torch_tensor(shard_state_dict) output_path = os.path.join(output_dir, shard_file) if safe_serialization: save_file(shard_state_dict, output_path, metadata={"format": "pt"}) else: torch.save(shard_state_dict, output_path) # release the memory of current shard for tensor_name in list(shard_state_dict.keys()): del state_dict[tensor_name] del shard_state_dict[tensor_name] del shard_state_dict gc.collect()
# Save index if sharded if state_dict_split.is_sharded: index = { "metadata": state_dict_split.metadata, "weight_map": state_dict_split.tensor_to_filename, } save_index_file = "model.safetensors.index.json" if safe_serialization else "pytorch_model.bin.index.json" save_index_file = os.path.join(output_dir, save_index_file) with open(save_index_file, "w", encoding="utf-8") as f: content = json.dumps(index, indent=2, sort_keys=True) + "\n" f.write(content)
def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None): """ 1. Put the provided model to cpu 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` 3. Load it into the provided model
Args: - ``model``: the model object to update - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) - ``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``
Returns: - ``model`: modified model
Make sure you have plenty of CPU memory available before you call this function. If you don't have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it conveniently placed for you in the checkpoint folder.
A typical usage might be ::
from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir) # submit to model hub or save the model to share with others
Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context of the same application. i.e. you will need to re-initialize the deepspeed engine, since ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
""" logger.info(f"Extracting fp32 weights") state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
logger.info(f"Overwriting model with fp32 weights") model = model.cpu() model.load_state_dict(state_dict, strict=False)
return model
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("checkpoint_dir", type=str, help="path to the desired checkpoint folder, e.g., path/checkpoint-12") parser.add_argument("output_dir", type=str, help="directory to the pytorch fp32 state_dict output files" "(e.g. path/checkpoint-12-output/)") parser.add_argument( "--max_shard_size", type=str, default="5GB", help="The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size" "lower than this size. If expressed as a string, needs to be digits followed by a unit (like `5MB`" "We default it to 5GB in order for models to be able to run easily on free-tier google colab instances" "without CPU OOM issues.") parser.add_argument( "--safe_serialization", default=False, action='store_true', help="Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).") parser.add_argument("-t", "--tag", type=str, default=None, help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1") parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters") parser.add_argument("-d", "--debug", action='store_true', help="enable debug") args = parser.parse_args()
debug = args.debug
convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir, args.output_dir, max_shard_size=args.max_shard_size, safe_serialization=args.safe_serialization, tag=args.tag, exclude_frozen_parameters=args.exclude_frozen_parameters)123version https://git-lfs.github.com/spec/v1oid sha256:ad209295ef61666d46989da56f8ad778f86b85da25c02cccb1f359a48c694fcesize 45125928123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623"""Pico Decoder: A Lightweight Causal Transformer Language Model
Pico Decoder uses a simple LLAMA-style transformer architecture, written for clarity and educational purposes.
Everything is written with a modular design for easy modification and experimentation.
Key features:- RMSNorm for layer normalization- Rotary Positional Embeddings (RoPE)- Multi-head attention with KV-cache support- SwiGLU activation function- Residual connections throughout
- KV-cache for faster autoregressive generation
References: - RoPE: https://arxiv.org/abs/2104.09864 - SwiGLU: https://arxiv.org/abs/2002.05202 - LLAMA: https://arxiv.org/abs/2302.13971
Adapted from: - OLMO: https://github.com/allenai/OLMo - LLAMA: https://github.com/meta/llama"""
from dataclasses import asdictfrom typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch.nn.attention import SDPBackend, sdpa_kernelfrom transformers import PretrainedConfig, PreTrainedModelfrom transformers.modeling_outputs import CausalLMOutput, CausalLMOutputWithPast
try: if TYPE_CHECKING: # We need to do this to avoid importing these when creating the HF-compatible models from src.config import ModelConfigexcept ImportError: pass
########################################################## Layer Normalization#########################################################
class RMSNorm(torch.nn.Module): """Root Mean Square Layer Normalization.
A variant of Layer Normalization that uses RMS statistics instead of mean/variance, resulting in improved stability and performance.
Args: config (Union[ModelConfig, PicoHFConfig]): Configuration object containing normalization parameters - config.norm_eps: Small constant for numerical stability - config.d_model: Model dimension for the weight parameter
References: https://arxiv.org/abs/1910.07467 """
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]): super().__init__() self.eps = config.norm_eps self.weight = nn.Parameter(torch.ones(config.d_model))
def _norm(self, x: torch.Tensor) -> torch.Tensor: """ Normalizes the input tensor by its RMS value. """ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x: torch.Tensor) -> torch.Tensor: """ Applies RMS normalization to the input tensor and scales it by the weight parameter. """ output = self._norm(x.float()).type_as(x) return output * self.weight
########################################################## Positional Embedding#########################################################
class RoPE(nn.Module): """Rotary Positional Embeddings (RoPE).
Implements position-dependent rotation of keys and queries in attention mechanism, allowing better modeling of relative positions in sequences. Uses complex number operations for efficient rotation.
Args: config (Union[ModelConfig, PicoHFConfig]): Model configuration containing: - config.position_emb_theta: Base for frequency computation - config.d_model: Model dimension - config.attention_n_heads: Number of attention heads - config.max_seq_len: Maximum sequence length
References: https://arxiv.org/abs/2104.09864 """
_freqs_cis_tensor: torch.Tensor | None = None
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]): super().__init__()
self.theta = config.position_emb_theta self.dim = config.d_model // config.attention_n_heads
max_seq_len = config.max_seq_len
# only gets set once, and then reused for all RoPE instances if RoPE._freqs_cis_tensor is None: RoPE._freqs_cis_tensor = self._setup_freqs_cis( max_seq_len, self.theta, self.dim )
# register _freqs_cis buffer # can be easily recomputed so persistent=False self.register_buffer("_freqs_cis", self._freqs_cis_tensor, persistent=False)
@classmethod def _setup_freqs_cis(cls, seq_len: int, theta: float, dim: int) -> torch.Tensor: """Setup Frequency Tensor for RoPE Embeddings
Initializes the complex frequency tensor that is used to compute the RoPE embeddings.
Note other implementations will use cos and sin directly, but using the complex number representation is (probably?) more efficient:
e^(theta * i * t) = cos(theta * t) + i * sin(theta * t) [Euler's formula] """ _freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)) positions = torch.arange(seq_len) freqs = torch.outer(positions, _freqs) return torch.polar(torch.ones_like(freqs), freqs) # complex64
def get_freqs_cis( self, input_shape: torch.Size, start_pos: int, end_pos: int ) -> torch.Tensor: """Reshape Frequency Tensor for RoPE Embeddings
Makes the frequency tensor broadcastable with the input tensor. """ _freqs_cis = self._freqs_cis[start_pos:end_pos] ndim = len(input_shape) assert 0 <= 1 < ndim assert _freqs_cis.shape == (input_shape[1], input_shape[-1])
# TODO: Check whether this is correct (might be able to remove this) shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(input_shape)] return _freqs_cis.view(*shape)
def forward( self, queries: torch.Tensor, keys: torch.Tensor, start_pos: int = 0, ) -> Tuple[torch.Tensor, torch.Tensor]: """Apply RoPE Embeddings to Queries and Keys
Applies the rotary positional embeddings to the input tensors via complex num multiplication
NOTE: The start_pos is used if we want to use the kv_cache in the attention mechanism. """ queries_ = torch.view_as_complex( queries.float().reshape(*queries.shape[:-1], -1, 2) ) keys_ = torch.view_as_complex(keys.float().reshape(*keys.shape[:-1], -1, 2))
input_shape = ( queries_.shape ) # same as keys: (batch_size, seq_len, n_heads, head_dim/2) freqs_start_pos = start_pos freqs_end_pos = freqs_start_pos + queries_.shape[1]
freqs_cis = self.get_freqs_cis(input_shape, freqs_start_pos, freqs_end_pos)
queries_rotated = torch.view_as_real(queries_ * freqs_cis).flatten(3) keys_rotated = torch.view_as_real(keys_ * freqs_cis).flatten(3) return queries_rotated.type_as(queries), keys_rotated.type_as(keys)
########################################################## Attention#########################################################
class Attention(nn.Module): """Multi-head Attention with Group Query Attention support.
Implements scaled dot-product attention and supports: - Grouped Query Attention (GQA) - Key-Value caching for efficient inference - RoPE integration
Args: config (Union[ModelConfig, PretrainedConfig]): Configuration containing: - config.attention_n_heads: Number of attention heads - config.attention_n_kv_heads: Number of key/value heads - config.d_model: Model dimension - config.batch_size: Maximum batch size - config.max_seq_len: Maximum sequence length
Shape: - Input: (batch_size, seq_len, d_model) - Output: (batch_size, seq_len, d_model) """
def __init__( self, config: Union["ModelConfig", "PicoDecoderHFConfig"], ): super().__init__()
self.n_heads = config.attention_n_heads self.n_kv_heads = config.attention_n_kv_heads
self.batch_size = config.batch_size self.max_seq_len = config.max_seq_len
d_model = config.d_model self.head_dim = d_model // self.n_heads
self.n_rep = self.n_heads // self.n_kv_heads
self.q_proj = nn.Linear(d_model, self.n_heads * self.head_dim, bias=False) self.k_proj = nn.Linear(d_model, self.n_kv_heads * self.head_dim, bias=False) self.v_proj = nn.Linear(d_model, self.n_kv_heads * self.head_dim, bias=False) self.o_proj = nn.Linear(self.n_heads * self.head_dim, d_model, bias=False)
self.rope = RoPE(config)
def forward( self, input: torch.Tensor, mask: Optional[torch.Tensor] = None, past_key_values: Optional[Tuple[torch.Tensor, ...]] = None, use_cache: bool = False, ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]: """Forward pass for the attention mechanism.
Computes queries, keys, and values for the attention mechanism. Applies rotary positional embeddings to the queries and keys, and then computes attention scores and outputs.
For an introduction to the attention mechanism, see: https://arxiv.org/abs/1706.03762
A few things to note: - The past_key_values is used to implement the KV cache, which is used to speed up generation by caching the KV pairs from previous forward passes. This is useful when doing tasks that require generating multiple tokens conditioned on previous tokens (e.g. language modeling, text generation, etc.). The way the KV cache is implemented is that each layer has its own KV cache - this KV cache is implemented as a tuple. """ bsz, seq_len, _ = input.shape _queries, _keys, _values = ( self.q_proj(input), self.k_proj(input), self.v_proj(input), )
# Reshaping for multi-head attention queries = _queries.view(bsz, seq_len, self.n_heads, self.head_dim) keys = _keys.view(bsz, seq_len, self.n_kv_heads, self.head_dim) values = _values.view(bsz, seq_len, self.n_kv_heads, self.head_dim)
# The start position is used to apply the RoPE embeddings to only the new tokens # when using the kv_cache in the attention mechanism. # We want to start from the last position in the cache. start_pos = past_key_values[0].shape[1] if past_key_values is not None else 0
# apply rotary positional embeddings queries, keys = self.rope(queries, keys, start_pos)
if past_key_values is not None: keys = torch.cat([past_key_values[0], keys], dim=1) values = torch.cat([past_key_values[1], values], dim=1)
if use_cache: cached_keys = keys cached_values = values else: cached_keys = None cached_values = None
queries = queries.transpose(1, 2) keys = keys.transpose(1, 2) values = values.transpose(1, 2)
apply_gqa = self.n_rep > 1 if apply_gqa and queries.device.type == "mps": # NOTE: MPS does not support GQA in the SDPA kernel, but we can repeat the keys and values # outside of the kernel to get the same effect. # See: https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html keys = keys.repeat_interleave(self.n_rep, dim=-3) values = values.repeat_interleave(self.n_rep, dim=-3) apply_gqa = False
backends = [SDPBackend.CUDNN_ATTENTION, SDPBackend.MATH]
with sdpa_kernel(backends=backends): attn_output = F.scaled_dot_product_attention( queries.contiguous(), keys.contiguous(), values.contiguous(), attn_mask=mask.to(queries.dtype), enable_gqa=apply_gqa, )
attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, seq_len, -1) output = self.o_proj(attn_output)
return output, (cached_keys, cached_values)
########################################################## SwiGLU (Combines MLP and Activation)#########################################################
class SwiGLU(nn.Module): """SwiGLU Activation Function with Linear Projections.
Implements the SwiGLU activation function combined with linear transformations, serving as the feed-forward network in transformer blocks.
Args: config (Union[ModelConfig, PicoDecoderHFConfig]): Configuration containing: - config.d_model: Model dimension - config.activation_hidden_dim: Hidden dimension (typically 4 * d_model)
References: https://arxiv.org/abs/2002.05202 """
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]): super().__init__()
model_dim = config.d_model act_hidden_dim = config.activation_hidden_dim # usually 4 * d_model
self.w_0 = nn.Linear(model_dim, act_hidden_dim, bias=False) self.w_1 = nn.Linear(model_dim, act_hidden_dim, bias=False) self.w_2 = nn.Linear(act_hidden_dim, model_dim, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.w_2(F.silu(self.w_0(x)) * self.w_1(x))
########################################################## PicoDecoderBlock#########################################################
class PicoDecoderBlock(nn.Module): """Single Transformer Block with Attention and Feed-forward layers.
Implements a standard transformer block with: - Multi-head attention with normalization and residual connection - SwiGLU feed-forward network with normalization and residual connection
Args: config (Union[ModelConfig, PicoDecoderHFConfig]): Model configuration; either a dataclass or a HuggingFace PicoDecoderHFConfig """
def __init__( self, config: Union["ModelConfig", "PicoDecoderHFConfig"], ): super().__init__()
self.attention = Attention(config) self.swiglu = SwiGLU(config) self.attention_norm = RMSNorm(config) self.swiglu_norm = RMSNorm(config)
def forward( self, input: torch.Tensor, mask: Optional[torch.Tensor] = None, past_key_values: Optional[Tuple[torch.Tensor]] = None, use_cache: bool = False, ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]: attention_output, cached_key_values = self.attention( self.attention_norm(input), mask=mask, past_key_values=past_key_values, use_cache=use_cache, ) # NOTE: cached_key_values is None if use_cache is False
h = input + attention_output out = h + self.swiglu(self.swiglu_norm(h)) return out, cached_key_values
########################################################## Pico Decoder (Causal Transformer Model)#########################################################
class PicoDecoder(nn.Module): """ Pico Decoder: combines the embedding, causal decoder blocks, and output projection into a single autoregressive model.
For more information on the model, see the classes for the modules that make up the model. """
def __init__( self, model_config: Union["ModelConfig", "PicoDecoderHFConfig"], ): super().__init__() self.config = model_config
self.embedding_proj = nn.Embedding(self.config.vocab_size, self.config.d_model) self.layers = nn.ModuleList( [PicoDecoderBlock(self.config) for _ in range(self.config.n_layers)] ) self.output_norm = RMSNorm(self.config) self.de_embedding_proj = nn.Linear( self.config.d_model, self.config.vocab_size, bias=False )
def convert_to_hf_model(self) -> "PicoDecoderHF": """Convert the Lightning model to a HuggingFace model.""" # Build HF config hf_config = PicoDecoderHFConfig.from_dataclass(self.config)
# Instantiate the HF-wrapped model hf_model = PicoDecoderHF(hf_config)
# Grab our full state dict, prefixing module names raw_state = self.state_dict(prefix="pico_decoder.")
# Only keep keys that exist in the HF model (drops classifier_head, etc.) hf_keys = set(hf_model.state_dict().keys()) filtered_state = {k: v for k, v in raw_state.items() if k in hf_keys}
# Load into HF model, ignore any missing keys hf_model.load_state_dict(filtered_state, strict=False)
return hf_model
def forward( self, input_ids: torch.Tensor, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, use_cache: bool = False, return_hidden: bool = False, ) -> Tuple[torch.Tensor, Optional[Tuple[Tuple[torch.Tensor, torch.Tensor]]]]: """ This is the forward pass for the entire Pico model. It boils down to: - Embedding the input ids - Creating a causal mask - Processing through the pico layers - Projecting the output to logits
NOTE: One feature that might be confusing is the KV cache. The KV cache is used to speed up generation by caching the KV pairs from previous forward passes. This is useful when doing tasks that require generating multiple tokens conditioned on previous tokens (e.g. language modeling, text generation, etc.). The way the KV cache is implemented is that each layer has its own KV cache which is stored as a tuple. The whole model then stores a tuple of these KV caches (so a tuple of tuples). """
seq_len = input_ids.shape[-1] h = self.embedding_proj(input_ids)
# Calculate start position from past cached KV pairs. Remember that each layer has its # own KV Cache. So when we index past_key_values, we need to index into the KV pairs for the # correct layer and then for either the keys or values. start_pos = 0 if past_key_values is None else past_key_values[0][0].shape[1]
# Create causal mask for current sequence mask = None if seq_len > 1: mask = torch.full((seq_len, seq_len), float("-inf")) mask = torch.triu(mask, diagonal=1)
# If using KV cache, extend mask to cover cached sequence length if past_key_values is not None: # Add zeros for cached tokens (we can attend to all of them) mask = torch.hstack([torch.zeros((seq_len, start_pos)), mask])
mask = mask.to(h.device)
# NOTE: If we are using the cache, we need to store the cached KV pairs for each layer # in a tuple. Each layer will have its own cached KV pair which we aggregate in a tuple. cached_key_values = () if use_cache else None
# Process through transformer blocks for idx, layer in enumerate(self.layers): layer_past_key_values = ( past_key_values[idx] if past_key_values is not None else None )
h, layer_cached_key_values = layer( h, mask=mask, past_key_values=layer_past_key_values, use_cache=use_cache )
if use_cache: cached_key_values += (layer_cached_key_values,)
# Final norm and projection h = self.output_norm(h)
if return_hidden: return h, cached_key_values
logits = self.de_embedding_proj(h).float()
return logits, cached_key_values
########################################################## HuggingFace Wrapper for the Pico Decoder model.#########################################################
class PicoDecoderHFConfig(PretrainedConfig): """Config class for the Pico Decoder HuggingFace wrapper."""
model_type = "pico_decoder"
@classmethod def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> "PicoDecoderHFConfig": # NOTE The typical from_dict method doesn't actually set the attributes unless they are # defined in the constructor.
pico_config = cls(**kwargs)
# Because this class is just a wrapper around the ModelConfig dataclass, we need to do # a little extra work to ensure that the attributes are actually set. for key, value in config_dict.items(): setattr(pico_config, key, value)
return_unused_kwargs = kwargs.pop("return_unused_kwargs", False) unused_kwargs = { key: value for key, value in kwargs.items() if not hasattr(pico_config, key) }
if return_unused_kwargs: return pico_config, unused_kwargs return pico_config
@classmethod def from_dataclass(cls, model_config: "ModelConfig"): """Initialise from our custom config dataclass.""" return cls.from_dict(asdict(model_config))
class PicoDecoderHF(PreTrainedModel): """ HuggingFace wrapper for the Pico model.
Many evaluation frameworks require a model be setup as a HuggingFace model, so we provide a simple wrapper that does just that. When we save checkpoints of the Pico model, we save both the normal Pico model as well as the model wrapped in this HuggingFace class.
This also lets you do cool things like:
`model = AutoModelForCausalLM.from_pretrained("path/to/checkpoint")` """
config_class = PicoDecoderHFConfig _no_split_modules = ["PicoBlock", "Attention", "SwiGLU", "RMSNorm"]
def __init__(self, config: PicoDecoderHFConfig): super().__init__(config) self.pico_decoder = PicoDecoder(config)
def forward( self, input_ids: torch.Tensor, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, use_cache: bool = False, **kwargs, ) -> Union[CausalLMOutput, CausalLMOutputWithPast]: """HuggingFace forward pass wrapper.
Forwards pass for the HuggingFace version of the Pico Model. Basic wrapper around the Pico model's forward pass, and returns the output as a HuggingFace CausalLMOutput. """ logits, past_key_values = self.pico_decoder( input_ids, past_key_values, use_cache ) if use_cache: return CausalLMOutputWithPast( logits=logits, past_key_values=past_key_values, ) else: return CausalLMOutput( logits=logits, )
# Register for auto classesPicoDecoderHFConfig.register_for_auto_class()PicoDecoderHF.register_for_auto_class("AutoModel")PicoDecoderHF.register_for_auto_class("AutoModelForCausalLM")1234567891011121314151617181920212223{ "eos_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "mask_token": { "content": "[MASK]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": { "content": "<|padding|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248{ "add_bos_token": false, "add_eos_token": false, "add_prefix_space": false, "added_tokens_decoder": { "0": { "content": "|||IP_ADDRESS|||", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "1": { "content": "<|padding|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "50254": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50255": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50256": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50257": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50258": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50259": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50260": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50261": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50262": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50263": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50264": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50265": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50266": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50267": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50268": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50269": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50270": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50271": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50272": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50273": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50274": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50275": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50276": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50277": { "content": "|||EMAIL_ADDRESS|||", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50278": { "content": "|||PHONE_NUMBER|||", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50279": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "50280": { "content": "[MASK]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true } }, "bos_token": null, "clean_up_tokenization_spaces": true, "eos_token": "<|endoftext|>", "extra_special_tokens": {}, "mask_token": "[MASK]", "model_max_length": 1000000000000000019884624838656, "pad_token": "<|padding|>", "tokenizer_class": "GPTNeoXTokenizer", "unk_token": null}12345678910111213141516171819202122{ "activation_hidden_dim": 384, "architectures": [ "PicoDecoderHF" ], "attention_n_heads": 12, "attention_n_kv_heads": 4, "auto_map": { "AutoConfig": "pico_decoder.PicoDecoderHFConfig", "AutoModelForCausalLM": "pico_decoder.PicoDecoderHF" }, "batch_size": 1024, "d_model": 96, "max_seq_len": 512, "model_type": "pico_decoder", "n_layers": 12, "norm_eps": 1e-06, "position_emb_theta": 10000.0, "torch_dtype": "float32", "transformers_version": "4.48.3", "vocab_size": 50281}123version https://git-lfs.github.com/spec/v1oid sha256:00fad282674a8bc3539a488cb4fe3c2a18a0326ab598ede00a0c27bdc4cf8346size 53434629123version https://git-lfs.github.com/spec/v1oid sha256:a5348ae6ca398236a9b34d86fab3136a6d15d7cd78245065e25bf29aff27cfc4size 53441797123version https://git-lfs.github.com/spec/v1oid sha256:aee9bb9aef714eaef1517cdec810f4e814b9fcaa20cabb2158fe063d65d1ed8fsize 53434949123version https://git-lfs.github.com/spec/v1oid sha256:38b421a4f953971d8c7e0c5ea618c621d15350dcf1872e4f1ff765350ed4e94bsize 53434629123version https://git-lfs.github.com/spec/v1oid sha256:918c142dd7a9a93581fc9207e02d8258df27d3f747b8e3fb77f9fd4b4a0a0d65size 356528251checkpoint123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760#!/usr/bin/env python
# Copyright (c) Microsoft Corporation.# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
# This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets# copied into the top level checkpoint dir, so the user can easily do the conversion at any point in# the future. Once extracted, the weights don't require DeepSpeed and can be used in any# application.## example:# python zero_to_fp32.py . output_dir/# or# python zero_to_fp32.py . output_dir/ --safe_serialization
import argparseimport torchimport globimport mathimport osimport reimport gcimport jsonimport numpy as npfrom tqdm import tqdmfrom collections import OrderedDictfrom dataclasses import dataclass
# while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with# DeepSpeed data structures it has to be available in the current python environment.from deepspeed.utils import loggerfrom deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS, FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES, FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
@dataclassclass zero_model_state: buffers: dict() param_shapes: dict() shared_params: list ds_version: int frozen_param_shapes: dict() frozen_param_fragments: dict()
debug = 0
# load to cpudevice = torch.device('cpu')
def atoi(text): return int(text) if text.isdigit() else text
def natural_keys(text): ''' alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments) ''' return [atoi(c) for c in re.split(r'(\d+)', text)]
def get_model_state_file(checkpoint_dir, zero_stage): if not os.path.isdir(checkpoint_dir): raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
# there should be only one file if zero_stage <= 2: file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt") elif zero_stage == 3: file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
if not os.path.exists(file): raise FileNotFoundError(f"can't find model states file at '{file}'")
return file
def get_checkpoint_files(checkpoint_dir, glob_pattern): # XXX: need to test that this simple glob rule works for multi-node setup too ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
if len(ckpt_files) == 0: raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
return ckpt_files
def get_optim_files(checkpoint_dir): return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
def get_model_state_files(checkpoint_dir): return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
def parse_model_states(files): zero_model_states = [] for file in files: state_dict = torch.load(file, map_location=device, weights_only=False)
if BUFFER_NAMES not in state_dict: raise ValueError(f"{file} is not a model state checkpoint") buffer_names = state_dict[BUFFER_NAMES] if debug: print("Found buffers:", buffer_names)
# recover just the buffers while restoring them to fp32 if they were saved in fp16 buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names} param_shapes = state_dict[PARAM_SHAPES]
# collect parameters that are included in param_shapes param_names = [] for s in param_shapes: for name in s.keys(): param_names.append(name)
# update with frozen parameters frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None) if frozen_param_shapes is not None: if debug: print(f"Found frozen_param_shapes: {frozen_param_shapes}") param_names += list(frozen_param_shapes.keys())
# handle shared params shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
ds_version = state_dict.get(DS_VERSION, None)
frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
z_model_state = zero_model_state(buffers=buffers, param_shapes=param_shapes, shared_params=shared_params, ds_version=ds_version, frozen_param_shapes=frozen_param_shapes, frozen_param_fragments=frozen_param_fragments) zero_model_states.append(z_model_state)
return zero_model_states
def parse_optim_states(files, ds_checkpoint_dir): total_files = len(files) state_dicts = [] for f in tqdm(files, desc='Loading checkpoint shards'): state_dict = torch.load(f, map_location=device, mmap=True, weights_only=False) # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights # and also handle the case where it was already removed by another helper script state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None) state_dicts.append(state_dict)
if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]: raise ValueError(f"{files[0]} is not a zero checkpoint") zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE] world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
# For ZeRO-2 each param group can have different partition_count as data parallelism for expert # parameters can be different from data parallelism for non-expert parameters. So we can just # use the max of the partition_count to get the dp world_size.
if type(world_size) is list: world_size = max(world_size)
if world_size != total_files: raise ValueError( f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. " "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes." )
# the groups are named differently in each stage if zero_stage <= 2: fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS elif zero_stage == 3: fp32_groups_key = FP32_FLAT_GROUPS else: raise ValueError(f"unknown zero stage {zero_stage}")
fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))] return zero_stage, world_size, fp32_flat_groups
def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters): """ Returns fp32 state_dict reconstructed from ds checkpoint
Args: - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
""" print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
optim_files = get_optim_files(ds_checkpoint_dir) zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir) print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
model_files = get_model_state_files(ds_checkpoint_dir)
zero_model_states = parse_model_states(model_files) print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
if zero_stage <= 2: return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters) elif zero_stage == 3: return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters)
def _zero2_merge_frozen_params(state_dict, zero_model_states): if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0: return
frozen_param_shapes = zero_model_states[0].frozen_param_shapes frozen_param_fragments = zero_model_states[0].frozen_param_fragments
if debug: num_elem = sum(s.numel() for s in frozen_param_shapes.values()) print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
wanted_params = len(frozen_param_shapes) wanted_numel = sum(s.numel() for s in frozen_param_shapes.values()) avail_numel = sum([p.numel() for p in frozen_param_fragments.values()]) print(f'Frozen params: Have {avail_numel} numels to process.') print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
total_params = 0 total_numel = 0 for name, shape in frozen_param_shapes.items(): total_params += 1 unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel
state_dict[name] = frozen_param_fragments[name]
if debug: print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
def _has_callable(obj, fn): attr = getattr(obj, fn, None) return callable(attr)
def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states): param_shapes = zero_model_states[0].param_shapes
# Reconstruction protocol: # # XXX: document this
if debug: for i in range(world_size): for j in range(len(fp32_flat_groups[0])): print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
# XXX: memory usage doubles here (zero2) num_param_groups = len(fp32_flat_groups[0]) merged_single_partition_of_fp32_groups = [] for i in range(num_param_groups): merged_partitions = [sd[i] for sd in fp32_flat_groups] full_single_fp32_vector = torch.cat(merged_partitions, 0) merged_single_partition_of_fp32_groups.append(full_single_fp32_vector) avail_numel = sum( [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
if debug: wanted_params = sum([len(shapes) for shapes in param_shapes]) wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes]) # not asserting if there is a mismatch due to possible padding print(f"Have {avail_numel} numels to process.") print(f"Need {wanted_numel} numels in {wanted_params} params.")
# params # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support # out-of-core computing solution total_numel = 0 total_params = 0 for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups): offset = 0 avail_numel = full_single_fp32_vector.numel() for name, shape in shapes.items():
unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape) total_numel += unpartitioned_numel total_params += 1
if debug: print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ") state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape) offset += unpartitioned_numel
# Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex # paddings performed in the code it's almost impossible to predict the exact numbers w/o the # live optimizer object, so we are checking that the numbers are within the right range align_to = 2 * world_size
def zero2_align(x): return align_to * math.ceil(x / align_to)
if debug: print(f"original offset={offset}, avail_numel={avail_numel}")
offset = zero2_align(offset) avail_numel = zero2_align(avail_numel)
if debug: print(f"aligned offset={offset}, avail_numel={avail_numel}")
# Sanity check if offset != avail_numel: raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters): state_dict = OrderedDict()
# buffers buffers = zero_model_states[0].buffers state_dict.update(buffers) if debug: print(f"added {len(buffers)} buffers")
if not exclude_frozen_parameters: _zero2_merge_frozen_params(state_dict, zero_model_states)
_zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
# recover shared parameters for pair in zero_model_states[0].shared_params: if pair[1] in state_dict: state_dict[pair[0]] = state_dict[pair[1]]
return state_dict
def zero3_partitioned_param_info(unpartitioned_numel, world_size): remainder = unpartitioned_numel % world_size padding_numel = (world_size - remainder) if remainder else 0 partitioned_numel = math.ceil(unpartitioned_numel / world_size) return partitioned_numel, padding_numel
def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states): if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0: return
if debug: for i in range(world_size): num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values()) print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
frozen_param_shapes = zero_model_states[0].frozen_param_shapes wanted_params = len(frozen_param_shapes) wanted_numel = sum(s.numel() for s in frozen_param_shapes.values()) avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size print(f'Frozen params: Have {avail_numel} numels to process.') print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
total_params = 0 total_numel = 0 for name, shape in zero_model_states[0].frozen_param_shapes.items(): total_params += 1 unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel
param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states) state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
if debug: print( f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}" )
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
class GatheredTensor: """ A pseudo tensor that collects partitioned weights. It is more memory efficient when there are multiple groups. """
def __init__(self, flat_groups, flat_groups_offset, offset, partitioned_numel, shape): self.flat_groups = flat_groups self.flat_groups_offset = flat_groups_offset self.offset = offset self.partitioned_numel = partitioned_numel self.shape = shape self.dtype = self.flat_groups[0][0].dtype
def contiguous(self): """ Merge partitioned weights from flat_groups into a single tensor. """ end_idx = self.offset + self.partitioned_numel world_size = len(self.flat_groups) pad_flat_param_chunks = []
for rank_i in range(world_size): # for each rank, we need to collect weights from related group/groups flat_groups_at_rank_i = self.flat_groups[rank_i] start_group_id = None end_group_id = None for group_id in range(len(self.flat_groups_offset)): if self.flat_groups_offset[group_id] <= self.offset < self.flat_groups_offset[group_id + 1]: start_group_id = group_id if self.flat_groups_offset[group_id] < end_idx <= self.flat_groups_offset[group_id + 1]: end_group_id = group_id break # collect weights from related group/groups for group_id in range(start_group_id, end_group_id + 1): flat_tensor = flat_groups_at_rank_i[group_id] start_offset = self.offset - self.flat_groups_offset[group_id] end_offset = min(end_idx, self.flat_groups_offset[group_id + 1]) - self.flat_groups_offset[group_id] pad_flat_param_chunks.append(flat_tensor[start_offset:end_offset])
# collect weights from all ranks pad_flat_param = torch.cat(pad_flat_param_chunks, dim=0) param = pad_flat_param[:self.shape.numel()].view(self.shape).contiguous() return param
def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states): param_shapes = zero_model_states[0].param_shapes avail_numel = sum([flat_group.numel() for flat_group in fp32_flat_groups[0]]) * world_size
# Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each # param, re-consolidating each param, while dealing with padding if any
# merge list of dicts, preserving order param_shapes = {k: v for d in param_shapes for k, v in d.items()}
if debug: for i in range(world_size): print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
wanted_params = len(param_shapes) wanted_numel = sum(shape.numel() for shape in param_shapes.values()) # not asserting if there is a mismatch due to possible padding avail_numel = fp32_flat_groups[0].numel() * world_size print(f"Trainable params: Have {avail_numel} numels to process.") print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
# params # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support # out-of-core computing solution offset = 0 total_numel = 0 total_params = 0 flat_groups_offset = [0] + list(np.cumsum([flat_tensor.numel() for flat_tensor in fp32_flat_groups[0]])) for name, shape in tqdm(param_shapes.items(), desc='Gathering sharded weights'): unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel total_params += 1 partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
if debug: print( f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}" )
# memory efficient tensor tensor = GatheredTensor(fp32_flat_groups, flat_groups_offset, offset, partitioned_numel, shape) state_dict[name] = tensor offset += partitioned_numel
offset *= world_size
# Sanity check if offset != avail_numel: raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters): state_dict = OrderedDict()
# buffers buffers = zero_model_states[0].buffers state_dict.update(buffers) if debug: print(f"added {len(buffers)} buffers")
if not exclude_frozen_parameters: _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
_zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
# recover shared parameters for pair in zero_model_states[0].shared_params: if pair[1] in state_dict: state_dict[pair[0]] = state_dict[pair[1]]
return state_dict
def to_torch_tensor(state_dict, return_empty_tensor=False): """ Convert state_dict of GatheredTensor to torch tensor """ torch_state_dict = {} converted_tensors = {} for name, tensor in state_dict.items(): tensor_id = id(tensor) if tensor_id in converted_tensors: # shared tensors shared_tensor = torch_state_dict[converted_tensors[tensor_id]] torch_state_dict[name] = shared_tensor else: converted_tensors[tensor_id] = name if return_empty_tensor: torch_state_dict[name] = torch.empty(tensor.shape, dtype=tensor.dtype) else: torch_state_dict[name] = tensor.contiguous() return torch_state_dict
def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None, exclude_frozen_parameters=False, lazy_mode=False): """ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example via a model hub.
Args: - ``checkpoint_dir``: path to the desired checkpoint folder - ``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`` - ``exclude_frozen_parameters``: exclude frozen parameters - ``lazy_mode``: get state_dict in lazy mode. It returns a dict of pesduo tensor instead of torch tensor, which is more memory efficient. Convert the pesduo tensor to torch tensor by ``.contiguous()``
Returns: - pytorch ``state_dict``
A typical usage might be ::
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint # do the training and checkpoint saving state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu model = model.cpu() # move to cpu model.load_state_dict(state_dict) # submit to model hub or save the model to share with others
In this example the ``model`` will no longer be usable in the deepspeed context of the same application. i.e. you will need to re-initialize the deepspeed engine, since ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
Note: the above usage may not work if your application doesn't have sufficient free CPU memory. You may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with the checkpoint. Or you can load state_dict in lazy mode ::
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, lazy_mode=True) # not on cpu for name, lazy_tensor in state_dict.item(): tensor = lazy_tensor.contiguous() # to cpu print(name, tensor) # del tensor to release memory if it no longer in use """ if tag is None: latest_path = os.path.join(checkpoint_dir, 'latest') if os.path.isfile(latest_path): with open(latest_path, 'r') as fd: tag = fd.read().strip() else: raise ValueError(f"Unable to find 'latest' file at {latest_path}")
ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
if not os.path.isdir(ds_checkpoint_dir): raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
state_dict = _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters) if lazy_mode: return state_dict else: return to_torch_tensor(state_dict)
def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_dir, max_shard_size="5GB", safe_serialization=False, tag=None, exclude_frozen_parameters=False): """ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
Args: - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) - ``output_dir``: directory to the pytorch fp32 state_dict output files - ``max_shard_size``: the maximum size for a checkpoint before being sharded, default value is 5GB - ``safe_serialization``: whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`). - ``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`` - ``exclude_frozen_parameters``: exclude frozen parameters """
# Dependency pre-check if safe_serialization: try: from safetensors.torch import save_file except ImportError: print('If you want to use `safe_serialization`, please `pip install safetensors`') raise if max_shard_size is not None: try: from huggingface_hub import split_torch_state_dict_into_shards except ImportError: print('If you want to use `max_shard_size`, please `pip install huggingface_hub`') raise
# Convert zero checkpoint to state_dict state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag, exclude_frozen_parameters, lazy_mode=True)
# Shard the model if it is too big. weights_name = "model.safetensors" if safe_serialization else "pytorch_model.bin" if max_shard_size is not None: filename_pattern = weights_name.replace(".bin", "{suffix}.bin").replace(".safetensors", "{suffix}.safetensors") # an memory-efficient approach for sharding empty_state_dict = to_torch_tensor(state_dict, return_empty_tensor=True) state_dict_split = split_torch_state_dict_into_shards(empty_state_dict, filename_pattern=filename_pattern, max_shard_size=max_shard_size) else: from collections import namedtuple StateDictSplit = namedtuple("StateDictSplit", ["is_sharded", "filename_to_tensors"]) state_dict_split = StateDictSplit(is_sharded=False, filename_to_tensors={weights_name: list(state_dict.keys())})
# Save the model by shard os.makedirs(output_dir, exist_ok=True) filename_to_tensors = state_dict_split.filename_to_tensors.items() for shard_file, tensors in tqdm(filename_to_tensors, desc="Saving checkpoint shards"): shard_state_dict = {tensor_name: state_dict[tensor_name] for tensor_name in tensors} shard_state_dict = to_torch_tensor(shard_state_dict) output_path = os.path.join(output_dir, shard_file) if safe_serialization: save_file(shard_state_dict, output_path, metadata={"format": "pt"}) else: torch.save(shard_state_dict, output_path) # release the memory of current shard for tensor_name in list(shard_state_dict.keys()): del state_dict[tensor_name] del shard_state_dict[tensor_name] del shard_state_dict gc.collect()
# Save index if sharded if state_dict_split.is_sharded: index = { "metadata": state_dict_split.metadata, "weight_map": state_dict_split.tensor_to_filename, } save_index_file = "model.safetensors.index.json" if safe_serialization else "pytorch_model.bin.index.json" save_index_file = os.path.join(output_dir, save_index_file) with open(save_index_file, "w", encoding="utf-8") as f: content = json.dumps(index, indent=2, sort_keys=True) + "\n" f.write(content)
def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None): """ 1. Put the provided model to cpu 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` 3. Load it into the provided model
Args: - ``model``: the model object to update - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) - ``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``
Returns: - ``model`: modified model
Make sure you have plenty of CPU memory available before you call this function. If you don't have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it conveniently placed for you in the checkpoint folder.
A typical usage might be ::
from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir) # submit to model hub or save the model to share with others
Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context of the same application. i.e. you will need to re-initialize the deepspeed engine, since ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
""" logger.info(f"Extracting fp32 weights") state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
logger.info(f"Overwriting model with fp32 weights") model = model.cpu() model.load_state_dict(state_dict, strict=False)
return model
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("checkpoint_dir", type=str, help="path to the desired checkpoint folder, e.g., path/checkpoint-12") parser.add_argument("output_dir", type=str, help="directory to the pytorch fp32 state_dict output files" "(e.g. path/checkpoint-12-output/)") parser.add_argument( "--max_shard_size", type=str, default="5GB", help="The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size" "lower than this size. If expressed as a string, needs to be digits followed by a unit (like `5MB`" "We default it to 5GB in order for models to be able to run easily on free-tier google colab instances" "without CPU OOM issues.") parser.add_argument( "--safe_serialization", default=False, action='store_true', help="Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).") parser.add_argument("-t", "--tag", type=str, default=None, help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1") parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters") parser.add_argument("-d", "--debug", action='store_true', help="enable debug") args = parser.parse_args()
debug = args.debug
convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir, args.output_dir, max_shard_size=args.max_shard_size, safe_serialization=args.safe_serialization, tag=args.tag, exclude_frozen_parameters=args.exclude_frozen_parameters)123version https://git-lfs.github.com/spec/v1oid sha256:547bf0551e8207391f805b173739169e787505fda7972573178a891d2546eb9csize 45125928123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623"""Pico Decoder: A Lightweight Causal Transformer Language Model
Pico Decoder uses a simple LLAMA-style transformer architecture, written for clarity and educational purposes.
Everything is written with a modular design for easy modification and experimentation.
Key features:- RMSNorm for layer normalization- Rotary Positional Embeddings (RoPE)- Multi-head attention with KV-cache support- SwiGLU activation function- Residual connections throughout
- KV-cache for faster autoregressive generation
References: - RoPE: https://arxiv.org/abs/2104.09864 - SwiGLU: https://arxiv.org/abs/2002.05202 - LLAMA: https://arxiv.org/abs/2302.13971
Adapted from: - OLMO: https://github.com/allenai/OLMo - LLAMA: https://github.com/meta/llama"""
from dataclasses import asdictfrom typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch.nn.attention import SDPBackend, sdpa_kernelfrom transformers import PretrainedConfig, PreTrainedModelfrom transformers.modeling_outputs import CausalLMOutput, CausalLMOutputWithPast
try: if TYPE_CHECKING: # We need to do this to avoid importing these when creating the HF-compatible models from src.config import ModelConfigexcept ImportError: pass
########################################################## Layer Normalization#########################################################
class RMSNorm(torch.nn.Module): """Root Mean Square Layer Normalization.
A variant of Layer Normalization that uses RMS statistics instead of mean/variance, resulting in improved stability and performance.
Args: config (Union[ModelConfig, PicoHFConfig]): Configuration object containing normalization parameters - config.norm_eps: Small constant for numerical stability - config.d_model: Model dimension for the weight parameter
References: https://arxiv.org/abs/1910.07467 """
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]): super().__init__() self.eps = config.norm_eps self.weight = nn.Parameter(torch.ones(config.d_model))
def _norm(self, x: torch.Tensor) -> torch.Tensor: """ Normalizes the input tensor by its RMS value. """ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x: torch.Tensor) -> torch.Tensor: """ Applies RMS normalization to the input tensor and scales it by the weight parameter. """ output = self._norm(x.float()).type_as(x) return output * self.weight
########################################################## Positional Embedding#########################################################
class RoPE(nn.Module): """Rotary Positional Embeddings (RoPE).
Implements position-dependent rotation of keys and queries in attention mechanism, allowing better modeling of relative positions in sequences. Uses complex number operations for efficient rotation.
Args: config (Union[ModelConfig, PicoHFConfig]): Model configuration containing: - config.position_emb_theta: Base for frequency computation - config.d_model: Model dimension - config.attention_n_heads: Number of attention heads - config.max_seq_len: Maximum sequence length
References: https://arxiv.org/abs/2104.09864 """
_freqs_cis_tensor: torch.Tensor | None = None
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]): super().__init__()
self.theta = config.position_emb_theta self.dim = config.d_model // config.attention_n_heads
max_seq_len = config.max_seq_len
# only gets set once, and then reused for all RoPE instances if RoPE._freqs_cis_tensor is None: RoPE._freqs_cis_tensor = self._setup_freqs_cis( max_seq_len, self.theta, self.dim )
# register _freqs_cis buffer # can be easily recomputed so persistent=False self.register_buffer("_freqs_cis", self._freqs_cis_tensor, persistent=False)
@classmethod def _setup_freqs_cis(cls, seq_len: int, theta: float, dim: int) -> torch.Tensor: """Setup Frequency Tensor for RoPE Embeddings
Initializes the complex frequency tensor that is used to compute the RoPE embeddings.
Note other implementations will use cos and sin directly, but using the complex number representation is (probably?) more efficient:
e^(theta * i * t) = cos(theta * t) + i * sin(theta * t) [Euler's formula] """ _freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)) positions = torch.arange(seq_len) freqs = torch.outer(positions, _freqs) return torch.polar(torch.ones_like(freqs), freqs) # complex64
def get_freqs_cis( self, input_shape: torch.Size, start_pos: int, end_pos: int ) -> torch.Tensor: """Reshape Frequency Tensor for RoPE Embeddings
Makes the frequency tensor broadcastable with the input tensor. """ _freqs_cis = self._freqs_cis[start_pos:end_pos] ndim = len(input_shape) assert 0 <= 1 < ndim assert _freqs_cis.shape == (input_shape[1], input_shape[-1])
# TODO: Check whether this is correct (might be able to remove this) shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(input_shape)] return _freqs_cis.view(*shape)
def forward( self, queries: torch.Tensor, keys: torch.Tensor, start_pos: int = 0, ) -> Tuple[torch.Tensor, torch.Tensor]: """Apply RoPE Embeddings to Queries and Keys
Applies the rotary positional embeddings to the input tensors via complex num multiplication
NOTE: The start_pos is used if we want to use the kv_cache in the attention mechanism. """ queries_ = torch.view_as_complex( queries.float().reshape(*queries.shape[:-1], -1, 2) ) keys_ = torch.view_as_complex(keys.float().reshape(*keys.shape[:-1], -1, 2))
input_shape = ( queries_.shape ) # same as keys: (batch_size, seq_len, n_heads, head_dim/2) freqs_start_pos = start_pos freqs_end_pos = freqs_start_pos + queries_.shape[1]
freqs_cis = self.get_freqs_cis(input_shape, freqs_start_pos, freqs_end_pos)
queries_rotated = torch.view_as_real(queries_ * freqs_cis).flatten(3) keys_rotated = torch.view_as_real(keys_ * freqs_cis).flatten(3) return queries_rotated.type_as(queries), keys_rotated.type_as(keys)
########################################################## Attention#########################################################
class Attention(nn.Module): """Multi-head Attention with Group Query Attention support.
Implements scaled dot-product attention and supports: - Grouped Query Attention (GQA) - Key-Value caching for efficient inference - RoPE integration
Args: config (Union[ModelConfig, PretrainedConfig]): Configuration containing: - config.attention_n_heads: Number of attention heads - config.attention_n_kv_heads: Number of key/value heads - config.d_model: Model dimension - config.batch_size: Maximum batch size - config.max_seq_len: Maximum sequence length
Shape: - Input: (batch_size, seq_len, d_model) - Output: (batch_size, seq_len, d_model) """
def __init__( self, config: Union["ModelConfig", "PicoDecoderHFConfig"], ): super().__init__()
self.n_heads = config.attention_n_heads self.n_kv_heads = config.attention_n_kv_heads
self.batch_size = config.batch_size self.max_seq_len = config.max_seq_len
d_model = config.d_model self.head_dim = d_model // self.n_heads
self.n_rep = self.n_heads // self.n_kv_heads
self.q_proj = nn.Linear(d_model, self.n_heads * self.head_dim, bias=False) self.k_proj = nn.Linear(d_model, self.n_kv_heads * self.head_dim, bias=False) self.v_proj = nn.Linear(d_model, self.n_kv_heads * self.head_dim, bias=False) self.o_proj = nn.Linear(self.n_heads * self.head_dim, d_model, bias=False)
self.rope = RoPE(config)
def forward( self, input: torch.Tensor, mask: Optional[torch.Tensor] = None, past_key_values: Optional[Tuple[torch.Tensor, ...]] = None, use_cache: bool = False, ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]: """Forward pass for the attention mechanism.
Computes queries, keys, and values for the attention mechanism. Applies rotary positional embeddings to the queries and keys, and then computes attention scores and outputs.
For an introduction to the attention mechanism, see: https://arxiv.org/abs/1706.03762
A few things to note: - The past_key_values is used to implement the KV cache, which is used to speed up generation by caching the KV pairs from previous forward passes. This is useful when doing tasks that require generating multiple tokens conditioned on previous tokens (e.g. language modeling, text generation, etc.). The way the KV cache is implemented is that each layer has its own KV cache - this KV cache is implemented as a tuple. """ bsz, seq_len, _ = input.shape _queries, _keys, _values = ( self.q_proj(input), self.k_proj(input), self.v_proj(input), )
# Reshaping for multi-head attention queries = _queries.view(bsz, seq_len, self.n_heads, self.head_dim) keys = _keys.view(bsz, seq_len, self.n_kv_heads, self.head_dim) values = _values.view(bsz, seq_len, self.n_kv_heads, self.head_dim)
# The start position is used to apply the RoPE embeddings to only the new tokens # when using the kv_cache in the attention mechanism. # We want to start from the last position in the cache. start_pos = past_key_values[0].shape[1] if past_key_values is not None else 0
# apply rotary positional embeddings queries, keys = self.rope(queries, keys, start_pos)
if past_key_values is not None: keys = torch.cat([past_key_values[0], keys], dim=1) values = torch.cat([past_key_values[1], values], dim=1)
if use_cache: cached_keys = keys cached_values = values else: cached_keys = None cached_values = None
queries = queries.transpose(1, 2) keys = keys.transpose(1, 2) values = values.transpose(1, 2)
apply_gqa = self.n_rep > 1 if apply_gqa and queries.device.type == "mps": # NOTE: MPS does not support GQA in the SDPA kernel, but we can repeat the keys and values # outside of the kernel to get the same effect. # See: https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html keys = keys.repeat_interleave(self.n_rep, dim=-3) values = values.repeat_interleave(self.n_rep, dim=-3) apply_gqa = False
backends = [SDPBackend.CUDNN_ATTENTION, SDPBackend.MATH]
with sdpa_kernel(backends=backends): attn_output = F.scaled_dot_product_attention( queries.contiguous(), keys.contiguous(), values.contiguous(), attn_mask=mask.to(queries.dtype), enable_gqa=apply_gqa, )
attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, seq_len, -1) output = self.o_proj(attn_output)
return output, (cached_keys, cached_values)
########################################################## SwiGLU (Combines MLP and Activation)#########################################################
class SwiGLU(nn.Module): """SwiGLU Activation Function with Linear Projections.
Implements the SwiGLU activation function combined with linear transformations, serving as the feed-forward network in transformer blocks.
Args: config (Union[ModelConfig, PicoDecoderHFConfig]): Configuration containing: - config.d_model: Model dimension - config.activation_hidden_dim: Hidden dimension (typically 4 * d_model)
References: https://arxiv.org/abs/2002.05202 """
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]): super().__init__()
model_dim = config.d_model act_hidden_dim = config.activation_hidden_dim # usually 4 * d_model
self.w_0 = nn.Linear(model_dim, act_hidden_dim, bias=False) self.w_1 = nn.Linear(model_dim, act_hidden_dim, bias=False) self.w_2 = nn.Linear(act_hidden_dim, model_dim, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.w_2(F.silu(self.w_0(x)) * self.w_1(x))
########################################################## PicoDecoderBlock#########################################################
class PicoDecoderBlock(nn.Module): """Single Transformer Block with Attention and Feed-forward layers.
Implements a standard transformer block with: - Multi-head attention with normalization and residual connection - SwiGLU feed-forward network with normalization and residual connection
Args: config (Union[ModelConfig, PicoDecoderHFConfig]): Model configuration; either a dataclass or a HuggingFace PicoDecoderHFConfig """
def __init__( self, config: Union["ModelConfig", "PicoDecoderHFConfig"], ): super().__init__()
self.attention = Attention(config) self.swiglu = SwiGLU(config) self.attention_norm = RMSNorm(config) self.swiglu_norm = RMSNorm(config)
def forward( self, input: torch.Tensor, mask: Optional[torch.Tensor] = None, past_key_values: Optional[Tuple[torch.Tensor]] = None, use_cache: bool = False, ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]: attention_output, cached_key_values = self.attention( self.attention_norm(input), mask=mask, past_key_values=past_key_values, use_cache=use_cache, ) # NOTE: cached_key_values is None if use_cache is False
h = input + attention_output out = h + self.swiglu(self.swiglu_norm(h)) return out, cached_key_values
########################################################## Pico Decoder (Causal Transformer Model)#########################################################
class PicoDecoder(nn.Module): """ Pico Decoder: combines the embedding, causal decoder blocks, and output projection into a single autoregressive model.
For more information on the model, see the classes for the modules that make up the model. """
def __init__( self, model_config: Union["ModelConfig", "PicoDecoderHFConfig"], ): super().__init__() self.config = model_config
self.embedding_proj = nn.Embedding(self.config.vocab_size, self.config.d_model) self.layers = nn.ModuleList( [PicoDecoderBlock(self.config) for _ in range(self.config.n_layers)] ) self.output_norm = RMSNorm(self.config) self.de_embedding_proj = nn.Linear( self.config.d_model, self.config.vocab_size, bias=False )
def convert_to_hf_model(self) -> "PicoDecoderHF": """Convert the Lightning model to a HuggingFace model.""" # Build HF config hf_config = PicoDecoderHFConfig.from_dataclass(self.config)
# Instantiate the HF-wrapped model hf_model = PicoDecoderHF(hf_config)
# Grab our full state dict, prefixing module names raw_state = self.state_dict(prefix="pico_decoder.")
# Only keep keys that exist in the HF model (drops classifier_head, etc.) hf_keys = set(hf_model.state_dict().keys()) filtered_state = {k: v for k, v in raw_state.items() if k in hf_keys}
# Load into HF model, ignore any missing keys hf_model.load_state_dict(filtered_state, strict=False)
return hf_model
def forward( self, input_ids: torch.Tensor, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, use_cache: bool = False, return_hidden: bool = False, ) -> Tuple[torch.Tensor, Optional[Tuple[Tuple[torch.Tensor, torch.Tensor]]]]: """ This is the forward pass for the entire Pico model. It boils down to: - Embedding the input ids - Creating a causal mask - Processing through the pico layers - Projecting the output to logits
NOTE: One feature that might be confusing is the KV cache. The KV cache is used to speed up generation by caching the KV pairs from previous forward passes. This is useful when doing tasks that require generating multiple tokens conditioned on previous tokens (e.g. language modeling, text generation, etc.). The way the KV cache is implemented is that each layer has its own KV cache which is stored as a tuple. The whole model then stores a tuple of these KV caches (so a tuple of tuples). """
seq_len = input_ids.shape[-1] h = self.embedding_proj(input_ids)
# Calculate start position from past cached KV pairs. Remember that each layer has its # own KV Cache. So when we index past_key_values, we need to index into the KV pairs for the # correct layer and then for either the keys or values. start_pos = 0 if past_key_values is None else past_key_values[0][0].shape[1]
# Create causal mask for current sequence mask = None if seq_len > 1: mask = torch.full((seq_len, seq_len), float("-inf")) mask = torch.triu(mask, diagonal=1)
# If using KV cache, extend mask to cover cached sequence length if past_key_values is not None: # Add zeros for cached tokens (we can attend to all of them) mask = torch.hstack([torch.zeros((seq_len, start_pos)), mask])
mask = mask.to(h.device)
# NOTE: If we are using the cache, we need to store the cached KV pairs for each layer # in a tuple. Each layer will have its own cached KV pair which we aggregate in a tuple. cached_key_values = () if use_cache else None
# Process through transformer blocks for idx, layer in enumerate(self.layers): layer_past_key_values = ( past_key_values[idx] if past_key_values is not None else None )
h, layer_cached_key_values = layer( h, mask=mask, past_key_values=layer_past_key_values, use_cache=use_cache )
if use_cache: cached_key_values += (layer_cached_key_values,)
# Final norm and projection h = self.output_norm(h)
if return_hidden: return h, cached_key_values
logits = self.de_embedding_proj(h).float()
return logits, cached_key_values
########################################################## HuggingFace Wrapper for the Pico Decoder model.#########################################################
class PicoDecoderHFConfig(PretrainedConfig): """Config class for the Pico Decoder HuggingFace wrapper."""
model_type = "pico_decoder"
@classmethod def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> "PicoDecoderHFConfig": # NOTE The typical from_dict method doesn't actually set the attributes unless they are # defined in the constructor.
pico_config = cls(**kwargs)
# Because this class is just a wrapper around the ModelConfig dataclass, we need to do # a little extra work to ensure that the attributes are actually set. for key, value in config_dict.items(): setattr(pico_config, key, value)
return_unused_kwargs = kwargs.pop("return_unused_kwargs", False) unused_kwargs = { key: value for key, value in kwargs.items() if not hasattr(pico_config, key) }
if return_unused_kwargs: return pico_config, unused_kwargs return pico_config
@classmethod def from_dataclass(cls, model_config: "ModelConfig"): """Initialise from our custom config dataclass.""" return cls.from_dict(asdict(model_config))
class PicoDecoderHF(PreTrainedModel): """ HuggingFace wrapper for the Pico model.
Many evaluation frameworks require a model be setup as a HuggingFace model, so we provide a simple wrapper that does just that. When we save checkpoints of the Pico model, we save both the normal Pico model as well as the model wrapped in this HuggingFace class.
This also lets you do cool things like:
`model = AutoModelForCausalLM.from_pretrained("path/to/checkpoint")` """
config_class = PicoDecoderHFConfig _no_split_modules = ["PicoBlock", "Attention", "SwiGLU", "RMSNorm"]
def __init__(self, config: PicoDecoderHFConfig): super().__init__(config) self.pico_decoder = PicoDecoder(config)
def forward( self, input_ids: torch.Tensor, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, use_cache: bool = False, **kwargs, ) -> Union[CausalLMOutput, CausalLMOutputWithPast]: """HuggingFace forward pass wrapper.
Forwards pass for the HuggingFace version of the Pico Model. Basic wrapper around the Pico model's forward pass, and returns the output as a HuggingFace CausalLMOutput. """ logits, past_key_values = self.pico_decoder( input_ids, past_key_values, use_cache ) if use_cache: return CausalLMOutputWithPast( logits=logits, past_key_values=past_key_values, ) else: return CausalLMOutput( logits=logits, )
# Register for auto classesPicoDecoderHFConfig.register_for_auto_class()PicoDecoderHF.register_for_auto_class("AutoModel")PicoDecoderHF.register_for_auto_class("AutoModelForCausalLM")1234567891011121314151617181920212223{ "eos_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "mask_token": { "content": "[MASK]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": { "content": "<|padding|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248{ "add_bos_token": false, "add_eos_token": false, "add_prefix_space": false, "added_tokens_decoder": { "0": { "content": "|||IP_ADDRESS|||", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "1": { "content": "<|padding|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "50254": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50255": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50256": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50257": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50258": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50259": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50260": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50261": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50262": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50263": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50264": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50265": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50266": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50267": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50268": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50269": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50270": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50271": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50272": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50273": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50274": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50275": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50276": { "content": " ", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50277": { "content": "|||EMAIL_ADDRESS|||", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50278": { "content": "|||PHONE_NUMBER|||", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": false }, "50279": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "50280": { "content": "[MASK]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true } }, "bos_token": null, "clean_up_tokenization_spaces": true, "eos_token": "<|endoftext|>", "extra_special_tokens": {}, "mask_token": "[MASK]", "model_max_length": 1000000000000000019884624838656, "pad_token": "<|padding|>", "tokenizer_class": "GPTNeoXTokenizer", "unk_token": null}12345678910111213141516171819202122{ "activation_hidden_dim": 384, "architectures": [ "PicoDecoderHF" ], "attention_n_heads": 12, "attention_n_kv_heads": 4, "auto_map": { "AutoConfig": "pico_decoder.PicoDecoderHFConfig", "AutoModelForCausalLM": "pico_decoder.PicoDecoderHF" }, "batch_size": 1024, "d_model": 96, "max_seq_len": 512, "model_type": "pico_decoder", "n_layers": 12, "norm_eps": 1e-06, "position_emb_theta": 10000.0, "torch_dtype": "float32", "transformers_version": "4.48.3", "vocab_size": 50281}123version https://git-lfs.github.com/spec/v1oid sha256:e72519e390b89c62c5856dd0f543a21487cf70eed9a0495b18cbf1dbee041019size 53434629123version https://git-lfs.github.com/spec/v1oid sha256:106517764a8b0ae2abe99e745c8415e761b4d082dc8ad97c43dab7488d1b7b40size 53441797123version https://git-lfs.github.com/spec/v1oid sha256:aa5a9118f0ef42b2d6a701926414dc9c4a4b10bf43d7aa506fab376785c9b70bsize 53434949123version https://git-lfs.github.com/spec/v1oid sha256:2589c34a6e95ab3d00da1ec221e714dd9a173d0db08a113f618f23de14e5369fsize 53434629123version https://git-lfs.github.com/spec/v1oid sha256:017f849d772984c909e1f9271fd89e064a7cc6aaf47f49d74603cdd106901d87size 356528251checkpoint123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760#!/usr/bin/env python
# Copyright (c) Microsoft Corporation.# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
# This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets# copied into the top level checkpoint dir, so the user can easily do the conversion at any point in# the future. Once extracted, the weights don't require DeepSpeed and can be used in any# application.## example:# python zero_to_fp32.py . output_dir/# or# python zero_to_fp32.py . output_dir/ --safe_serialization
import argparseimport torchimport globimport mathimport osimport reimport gcimport jsonimport numpy as npfrom tqdm import tqdmfrom collections import OrderedDictfrom dataclasses import dataclass
# while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with# DeepSpeed data structures it has to be available in the current python environment.from deepspeed.utils import loggerfrom deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS, FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES, FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
@dataclassclass zero_model_state: buffers: dict() param_shapes: dict() shared_params: list ds_version: int frozen_param_shapes: dict() frozen_param_fragments: dict()
debug = 0
# load to cpudevice = torch.device('cpu')
def atoi(text): return int(text) if text.isdigit() else text
def natural_keys(text): ''' alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments) ''' return [atoi(c) for c in re.split(r'(\d+)', text)]
def get_model_state_file(checkpoint_dir, zero_stage): if not os.path.isdir(checkpoint_dir): raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
# there should be only one file if zero_stage <= 2: file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt") elif zero_stage == 3: file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
if not os.path.exists(file): raise FileNotFoundError(f"can't find model states file at '{file}'")
return file
def get_checkpoint_files(checkpoint_dir, glob_pattern): # XXX: need to test that this simple glob rule works for multi-node setup too ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
if len(ckpt_files) == 0: raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
return ckpt_files
def get_optim_files(checkpoint_dir): return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
def get_model_state_files(checkpoint_dir): return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
def parse_model_states(files): zero_model_states = [] for file in files: state_dict = torch.load(file, map_location=device, weights_only=False)
if BUFFER_NAMES not in state_dict: raise ValueError(f"{file} is not a model state checkpoint") buffer_names = state_dict[BUFFER_NAMES] if debug: print("Found buffers:", buffer_names)
# recover just the buffers while restoring them to fp32 if they were saved in fp16 buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names} param_shapes = state_dict[PARAM_SHAPES]
# collect parameters that are included in param_shapes param_names = [] for s in param_shapes: for name in s.keys(): param_names.append(name)
# update with frozen parameters frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None) if frozen_param_shapes is not None: if debug: print(f"Found frozen_param_shapes: {frozen_param_shapes}") param_names += list(frozen_param_shapes.keys())
# handle shared params shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
ds_version = state_dict.get(DS_VERSION, None)
frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
z_model_state = zero_model_state(buffers=buffers, param_shapes=param_shapes, shared_params=shared_params, ds_version=ds_version, frozen_param_shapes=frozen_param_shapes, frozen_param_fragments=frozen_param_fragments) zero_model_states.append(z_model_state)
return zero_model_states
def parse_optim_states(files, ds_checkpoint_dir): total_files = len(files) state_dicts = [] for f in tqdm(files, desc='Loading checkpoint shards'): state_dict = torch.load(f, map_location=device, mmap=True, weights_only=False) # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights # and also handle the case where it was already removed by another helper script state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None) state_dicts.append(state_dict)
if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]: raise ValueError(f"{files[0]} is not a zero checkpoint") zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE] world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
# For ZeRO-2 each param group can have different partition_count as data parallelism for expert # parameters can be different from data parallelism for non-expert parameters. So we can just # use the max of the partition_count to get the dp world_size.
if type(world_size) is list: world_size = max(world_size)
if world_size != total_files: raise ValueError( f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. " "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes." )
# the groups are named differently in each stage if zero_stage <= 2: fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS elif zero_stage == 3: fp32_groups_key = FP32_FLAT_GROUPS else: raise ValueError(f"unknown zero stage {zero_stage}")
fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))] return zero_stage, world_size, fp32_flat_groups
def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters): """ Returns fp32 state_dict reconstructed from ds checkpoint
Args: - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
""" print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
optim_files = get_optim_files(ds_checkpoint_dir) zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir) print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
model_files = get_model_state_files(ds_checkpoint_dir)
zero_model_states = parse_model_states(model_files) print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
if zero_stage <= 2: return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters) elif zero_stage == 3: return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters)
def _zero2_merge_frozen_params(state_dict, zero_model_states): if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0: return
frozen_param_shapes = zero_model_states[0].frozen_param_shapes frozen_param_fragments = zero_model_states[0].frozen_param_fragments
if debug: num_elem = sum(s.numel() for s in frozen_param_shapes.values()) print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
wanted_params = len(frozen_param_shapes) wanted_numel = sum(s.numel() for s in frozen_param_shapes.values()) avail_numel = sum([p.numel() for p in frozen_param_fragments.values()]) print(f'Frozen params: Have {avail_numel} numels to process.') print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
total_params = 0 total_numel = 0 for name, shape in frozen_param_shapes.items(): total_params += 1 unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel
state_dict[name] = frozen_param_fragments[name]
if debug: print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
def _has_callable(obj, fn): attr = getattr(obj, fn, None) return callable(attr)
def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states): param_shapes = zero_model_states[0].param_shapes
# Reconstruction protocol: # # XXX: document this
if debug: for i in range(world_size): for j in range(len(fp32_flat_groups[0])): print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
# XXX: memory usage doubles here (zero2) num_param_groups = len(fp32_flat_groups[0]) merged_single_partition_of_fp32_groups = [] for i in range(num_param_groups): merged_partitions = [sd[i] for sd in fp32_flat_groups] full_single_fp32_vector = torch.cat(merged_partitions, 0) merged_single_partition_of_fp32_groups.append(full_single_fp32_vector) avail_numel = sum( [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
if debug: wanted_params = sum([len(shapes) for shapes in param_shapes]) wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes]) # not asserting if there is a mismatch due to possible padding print(f"Have {avail_numel} numels to process.") print(f"Need {wanted_numel} numels in {wanted_params} params.")
# params # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support # out-of-core computing solution total_numel = 0 total_params = 0 for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups): offset = 0 avail_numel = full_single_fp32_vector.numel() for name, shape in shapes.items():
unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape) total_numel += unpartitioned_numel total_params += 1
if debug: print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ") state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape) offset += unpartitioned_numel
# Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex # paddings performed in the code it's almost impossible to predict the exact numbers w/o the # live optimizer object, so we are checking that the numbers are within the right range align_to = 2 * world_size
def zero2_align(x): return align_to * math.ceil(x / align_to)
if debug: print(f"original offset={offset}, avail_numel={avail_numel}")
offset = zero2_align(offset) avail_numel = zero2_align(avail_numel)
if debug: print(f"aligned offset={offset}, avail_numel={avail_numel}")
# Sanity check if offset != avail_numel: raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters): state_dict = OrderedDict()
# buffers buffers = zero_model_states[0].buffers state_dict.update(buffers) if debug: print(f"added {len(buffers)} buffers")
if not exclude_frozen_parameters: _zero2_merge_frozen_params(state_dict, zero_model_states)
_zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
# recover shared parameters for pair in zero_model_states[0].shared_params: if pair[1] in state_dict: state_dict[pair[0]] = state_dict[pair[1]]
return state_dict
def zero3_partitioned_param_info(unpartitioned_numel, world_size): remainder = unpartitioned_numel % world_size padding_numel = (world_size - remainder) if remainder else 0 partitioned_numel = math.ceil(unpartitioned_numel / world_size) return partitioned_numel, padding_numel
def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states): if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0: return
if debug: for i in range(world_size): num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values()) print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
frozen_param_shapes = zero_model_states[0].frozen_param_shapes wanted_params = len(frozen_param_shapes) wanted_numel = sum(s.numel() for s in frozen_param_shapes.values()) avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size print(f'Frozen params: Have {avail_numel} numels to process.') print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
total_params = 0 total_numel = 0 for name, shape in zero_model_states[0].frozen_param_shapes.items(): total_params += 1 unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel
param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states) state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
if debug: print( f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}" )
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
class GatheredTensor: """ A pseudo tensor that collects partitioned weights. It is more memory efficient when there are multiple groups. """
def __init__(self, flat_groups, flat_groups_offset, offset, partitioned_numel, shape): self.flat_groups = flat_groups self.flat_groups_offset = flat_groups_offset self.offset = offset self.partitioned_numel = partitioned_numel self.shape = shape self.dtype = self.flat_groups[0][0].dtype
def contiguous(self): """ Merge partitioned weights from flat_groups into a single tensor. """ end_idx = self.offset + self.partitioned_numel world_size = len(self.flat_groups) pad_flat_param_chunks = []
for rank_i in range(world_size): # for each rank, we need to collect weights from related group/groups flat_groups_at_rank_i = self.flat_groups[rank_i] start_group_id = None end_group_id = None for group_id in range(len(self.flat_groups_offset)): if self.flat_groups_offset[group_id] <= self.offset < self.flat_groups_offset[group_id + 1]: start_group_id = group_id if self.flat_groups_offset[group_id] < end_idx <= self.flat_groups_offset[group_id + 1]: end_group_id = group_id break # collect weights from related group/groups for group_id in range(start_group_id, end_group_id + 1): flat_tensor = flat_groups_at_rank_i[group_id] start_offset = self.offset - self.flat_groups_offset[group_id] end_offset = min(end_idx, self.flat_groups_offset[group_id + 1]) - self.flat_groups_offset[group_id] pad_flat_param_chunks.append(flat_tensor[start_offset:end_offset])
# collect weights from all ranks pad_flat_param = torch.cat(pad_flat_param_chunks, dim=0) param = pad_flat_param[:self.shape.numel()].view(self.shape).contiguous() return param
def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states): param_shapes = zero_model_states[0].param_shapes avail_numel = sum([flat_group.numel() for flat_group in fp32_flat_groups[0]]) * world_size
# Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each # param, re-consolidating each param, while dealing with padding if any
# merge list of dicts, preserving order param_shapes = {k: v for d in param_shapes for k, v in d.items()}
if debug: for i in range(world_size): print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
wanted_params = len(param_shapes) wanted_numel = sum(shape.numel() for shape in param_shapes.values()) # not asserting if there is a mismatch due to possible padding avail_numel = fp32_flat_groups[0].numel() * world_size print(f"Trainable params: Have {avail_numel} numels to process.") print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
# params # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support # out-of-core computing solution offset = 0 total_numel = 0 total_params = 0 flat_groups_offset = [0] + list(np.cumsum([flat_tensor.numel() for flat_tensor in fp32_flat_groups[0]])) for name, shape in tqdm(param_shapes.items(), desc='Gathering sharded weights'): unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel total_params += 1 partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
if debug: print( f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}" )
# memory efficient tensor tensor = GatheredTensor(fp32_flat_groups, flat_groups_offset, offset, partitioned_numel, shape) state_dict[name] = tensor offset += partitioned_numel
offset *= world_size
# Sanity check if offset != avail_numel: raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters): state_dict = OrderedDict()
# buffers buffers = zero_model_states[0].buffers state_dict.update(buffers) if debug: print(f"added {len(buffers)} buffers")
if not exclude_frozen_parameters: _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
_zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
# recover shared parameters for pair in zero_model_states[0].shared_params: if pair[1] in state_dict: state_dict[pair[0]] = state_dict[pair[1]]
return state_dict
def to_torch_tensor(state_dict, return_empty_tensor=False): """ Convert state_dict of GatheredTensor to torch tensor """ torch_state_dict = {} converted_tensors = {} for name, tensor in state_dict.items(): tensor_id = id(tensor) if tensor_id in converted_tensors: # shared tensors shared_tensor = torch_state_dict[converted_tensors[tensor_id]] torch_state_dict[name] = shared_tensor else: converted_tensors[tensor_id] = name if return_empty_tensor: torch_state_dict[name] = torch.empty(tensor.shape, dtype=tensor.dtype) else: torch_state_dict[name] = tensor.contiguous() return torch_state_dict
def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None, exclude_frozen_parameters=False, lazy_mode=False): """ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example via a model hub.
Args: - ``checkpoint_dir``: path to the desired checkpoint folder - ``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`` - ``exclude_frozen_parameters``: exclude frozen parameters - ``lazy_mode``: get state_dict in lazy mode. It returns a dict of pesduo tensor instead of torch tensor, which is more memory efficient. Convert the pesduo tensor to torch tensor by ``.contiguous()``
Returns: - pytorch ``state_dict``
A typical usage might be ::
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint # do the training and checkpoint saving state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu model = model.cpu() # move to cpu model.load_state_dict(state_dict) # submit to model hub or save the model to share with others
In this example the ``model`` will no longer be usable in the deepspeed context of the same application. i.e. you will need to re-initialize the deepspeed engine, since ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
Note: the above usage may not work if your application doesn't have sufficient free CPU memory. You may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with the checkpoint. Or you can load state_dict in lazy mode ::
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, lazy_mode=True) # not on cpu for name, lazy_tensor in state_dict.item(): tensor = lazy_tensor.contiguous() # to cpu print(name, tensor) # del tensor to release memory if it no longer in use """ if tag is None: latest_path = os.path.join(checkpoint_dir, 'latest') if os.path.isfile(latest_path): with open(latest_path, 'r') as fd: tag = fd.read().strip() else: raise ValueError(f"Unable to find 'latest' file at {latest_path}")
ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
if not os.path.isdir(ds_checkpoint_dir): raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
state_dict = _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters) if lazy_mode: return state_dict else: return to_torch_tensor(state_dict)
def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_dir, max_shard_size="5GB", safe_serialization=False, tag=None, exclude_frozen_parameters=False): """ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
Args: - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) - ``output_dir``: directory to the pytorch fp32 state_dict output files - ``max_shard_size``: the maximum size for a checkpoint before being sharded, default value is 5GB - ``safe_serialization``: whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`). - ``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`` - ``exclude_frozen_parameters``: exclude frozen parameters """
# Dependency pre-check if safe_serialization: try: from safetensors.torch import save_file except ImportError: print('If you want to use `safe_serialization`, please `pip install safetensors`') raise if max_shard_size is not None: try: from huggingface_hub import split_torch_state_dict_into_shards except ImportError: print('If you want to use `max_shard_size`, please `pip install huggingface_hub`') raise
# Convert zero checkpoint to state_dict state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag, exclude_frozen_parameters, lazy_mode=True)
# Shard the model if it is too big. weights_name = "model.safetensors" if safe_serialization else "pytorch_model.bin" if max_shard_size is not None: filename_pattern = weights_name.replace(".bin", "{suffix}.bin").replace(".safetensors", "{suffix}.safetensors") # an memory-efficient approach for sharding empty_state_dict = to_torch_tensor(state_dict, return_empty_tensor=True) state_dict_split = split_torch_state_dict_into_shards(empty_state_dict, filename_pattern=filename_pattern, max_shard_size=max_shard_size) else: from collections import namedtuple StateDictSplit = namedtuple("StateDictSplit", ["is_sharded", "filename_to_tensors"]) state_dict_split = StateDictSplit(is_sharded=False, filename_to_tensors={weights_name: list(state_dict.keys())})
# Save the model by shard os.makedirs(output_dir, exist_ok=True) filename_to_tensors = state_dict_split.filename_to_tensors.items() for shard_file, tensors in tqdm(filename_to_tensors, desc="Saving checkpoint shards"): shard_state_dict = {tensor_name: state_dict[tensor_name] for tensor_name in tensors} shard_state_dict = to_torch_tensor(shard_state_dict) output_path = os.path.join(output_dir, shard_file) if safe_serialization: save_file(shard_state_dict, output_path, metadata={"format": "pt"}) else: torch.save(shard_state_dict, output_path) # release the memory of current shard for tensor_name in list(shard_state_dict.keys()): del state_dict[tensor_name] del shard_state_dict[tensor_name] del shard_state_dict gc.collect()
# Save index if sharded if state_dict_split.is_sharded: index = { "metadata": state_dict_split.metadata, "weight_map": state_dict_split.tensor_to_filename, } save_index_file = "model.safetensors.index.json" if safe_serialization else "pytorch_model.bin.index.json" save_index_file = os.path.join(output_dir, save_index_file) with open(save_index_file, "w", encoding="utf-8") as f: content = json.dumps(index, indent=2, sort_keys=True) + "\n" f.write(content)
def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None): """ 1. Put the provided model to cpu 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` 3. Load it into the provided model
Args: - ``model``: the model object to update - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) - ``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``
Returns: - ``model`: modified model
Make sure you have plenty of CPU memory available before you call this function. If you don't have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it conveniently placed for you in the checkpoint folder.
A typical usage might be ::
from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir) # submit to model hub or save the model to share with others
Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context of the same application. i.e. you will need to re-initialize the deepspeed engine, since ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
""" logger.info(f"Extracting fp32 weights") state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
logger.info(f"Overwriting model with fp32 weights") model = model.cpu() model.load_state_dict(state_dict, strict=False)
return model
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("checkpoint_dir", type=str, help="path to the desired checkpoint folder, e.g., path/checkpoint-12") parser.add_argument("output_dir", type=str, help="directory to the pytorch fp32 state_dict output files" "(e.g. path/checkpoint-12-output/)") parser.add_argument( "--max_shard_size", type=str, default="5GB", help="The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size" "lower than this size. If expressed as a string, needs to be digits followed by a unit (like `5MB`" "We default it to 5GB in order for models to be able to run easily on free-tier google colab instances" "without CPU OOM issues.") parser.add_argument( "--safe_serialization", default=False, action='store_true', help="Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).") parser.add_argument("-t", "--tag", type=str, default=None, help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1") parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters") parser.add_argument("-d", "--debug", action='store_true', help="enable debug") args = parser.parse_args()
debug = args.debug
convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir, args.output_dir, max_shard_size=args.max_shard_size, safe_serialization=args.safe_serialization, tag=args.tag, exclude_frozen_parameters=args.exclude_frozen_parameters)123version https://git-lfs.github.com/spec/v1oid sha256:178a98a77974faf1e1742166ac5cb1668b7e35d282a57bfb60e876d76c14fe79size 45125928123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623"""Pico Decoder: A Lightweight Causal Transformer Language Model
Pico Decoder uses a simple LLAMA-style transformer architecture, written for clarity and educational purposes.
Everything is written with a modular design for easy modification and experimentation.
Key features:- RMSNorm for layer normalization- Rotary Positional Embeddings (RoPE)- Multi-head attention with KV-cache support- SwiGLU activation function- Residual connections throughout
- KV-cache for faster autoregressive generation
References: - RoPE: https://arxiv.org/abs/2104.09864 - SwiGLU: https://arxiv.org/abs/2002.05202 - LLAMA: https://arxiv.org/abs/2302.13971
Adapted from: - OLMO: https://github.com/allenai/OLMo - LLAMA: https://github.com/meta/llama"""
from dataclasses import asdictfrom typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch.nn.attention import SDPBackend, sdpa_kernelfrom transformers import PretrainedConfig, PreTrainedModelfrom transformers.modeling_outputs import CausalLMOutput, CausalLMOutputWithPast
try: if TYPE_CHECKING: # We need to do this to avoid importing these when creating the HF-compatible models from src.config import ModelConfigexcept ImportError: pass
########################################################## Layer Normalization#########################################################
class RMSNorm(torch.nn.Module): """Root Mean Square Layer Normalization.
A variant of Layer Normalization that uses RMS statistics instead of mean/variance, resulting in improved stability and performance.
Args: config (Union[ModelConfig, PicoHFConfig]): Configuration object containing normalization parameters - config.norm_eps: Small constant for numerical stability - config.d_model: Model dimension for the weight parameter
References: https://arxiv.org/abs/1910.07467 """
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]): super().__init__() self.eps = config.norm_eps self.weight = nn.Parameter(torch.ones(config.d_model))
def _norm(self, x: torch.Tensor) -> torch.Tensor: """ Normalizes the input tensor by its RMS value. """ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x: torch.Tensor) -> torch.Tensor: """ Applies RMS normalization to the input tensor and scales it by the weight parameter. """ output = self._norm(x.float()).type_as(x) return output * self.weight
########################################################## Positional Embedding#########################################################
class RoPE(nn.Module): """Rotary Positional Embeddings (RoPE).
Implements position-dependent rotation of keys and queries in attention mechanism, allowing better modeling of relative positions in sequences. Uses complex number operations for efficient rotation.
Args: config (Union[ModelConfig, PicoHFConfig]): Model configuration containing: - config.position_emb_theta: Base for frequency computation - config.d_model: Model dimension - config.attention_n_heads: Number of attention heads - config.max_seq_len: Maximum sequence length
References: https://arxiv.org/abs/2104.09864 """
_freqs_cis_tensor: torch.Tensor | None = None
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]): super().__init__()
self.theta = config.position_emb_theta self.dim = config.d_model // config.attention_n_heads
max_seq_len = config.max_seq_len
# only gets set once, and then reused for all RoPE instances if RoPE._freqs_cis_tensor is None: RoPE._freqs_cis_tensor = self._setup_freqs_cis( max_seq_len, self.theta, self.dim )
# register _freqs_cis buffer # can be easily recomputed so persistent=False self.register_buffer("_freqs_cis", self._freqs_cis_tensor, persistent=False)
@classmethod def _setup_freqs_cis(cls, seq_len: int, theta: float, dim: int) -> torch.Tensor: """Setup Frequency Tensor for RoPE Embeddings
Initializes the complex frequency tensor that is used to compute the RoPE embeddings.
Note other implementations will use cos and sin directly, but using the complex number representation is (probably?) more efficient:
e^(theta * i * t) = cos(theta * t) + i * sin(theta * t) [Euler's formula] """ _freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)) positions = torch.arange(seq_len) freqs = torch.outer(positions, _freqs) return torch.polar(torch.ones_like(freqs), freqs) # complex64
def get_freqs_cis( self, input_shape: torch.Size, start_pos: int, end_pos: int ) -> torch.Tensor: """Reshape Frequency Tensor for RoPE Embeddings
Makes the frequency tensor broadcastable with the input tensor. """ _freqs_cis = self._freqs_cis[start_pos:end_pos] ndim = len(input_shape) assert 0 <= 1 < ndim assert _freqs_cis.shape == (input_shape[1], input_shape[-1])
# TODO: Check whether this is correct (might be able to remove this) shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(input_shape)] return _freqs_cis.view(*shape)
def forward( self, queries: torch.Tensor, keys: torch.Tensor, start_pos: int = 0, ) -> Tuple[torch.Tensor, torch.Tensor]: """Apply RoPE Embeddings to Queries and Keys
Applies the rotary positional embeddings to the input tensors via complex num multiplication
NOTE: The start_pos is used if we want to use the kv_cache in the attention mechanism. """ queries_ = torch.view_as_complex( queries.float().reshape(*queries.shape[:-1], -1, 2) ) keys_ = torch.view_as_complex(keys.float().reshape(*keys.shape[:-1], -1, 2))
input_shape = ( queries_.shape ) # same as keys: (batch_size, seq_len, n_heads, head_dim/2) freqs_start_pos = start_pos freqs_end_pos = freqs_start_pos + queries_.shape[1]
freqs_cis = self.get_freqs_cis(input_shape, freqs_start_pos, freqs_end_pos)
queries_rotated = torch.view_as_real(queries_ * freqs_cis).flatten(3) keys_rotated = torch.view_as_real(keys_ * freqs_cis).flatten(3) return queries_rotated.type_as(queries), keys_rotated.type_as(keys)
########################################################## Attention#########################################################
class Attention(nn.Module): """Multi-head Attention with Group Query Attention support.
Implements scaled dot-product attention and supports: - Grouped Query Attention (GQA) - Key-Value caching for efficient inference - RoPE integration
Args: config (Union[ModelConfig, PretrainedConfig]): Configuration containing: - config.attention_n_heads: Number of attention heads - config.attention_n_kv_heads: Number of key/value heads - config.d_model: Model dimension - config.batch_size: Maximum batch size - config.max_seq_len: Maximum sequence length
Shape: - Input: (batch_size, seq_len, d_model) - Output: (batch_size, seq_len, d_model) """
def __init__( self, config: Union["ModelConfig", "PicoDecoderHFConfig"], ): super().__init__()
self.n_heads = config.attention_n_heads self.n_kv_heads = config.attention_n_kv_heads
self.batch_size = config.batch_size self.max_seq_len = config.max_seq_len
d_model = config.d_model self.head_dim = d_model // self.n_heads
self.n_rep = self.n_heads // self.n_kv_heads
self.q_proj = nn.Linear(d_model, self.n_heads * self.head_dim, bias=False) self.k_proj = nn.Linear(d_model, self.n_kv_heads * self.head_dim, bias=False) self.v_proj = nn.Linear(d_model, self.n_kv_heads * self.head_dim, bias=False) self.o_proj = nn.Linear(self.n_heads * self.head_dim, d_model, bias=False)
self.rope = RoPE(config)
def forward( self, input: torch.Tensor, mask: Optional[torch.Tensor] = None, past_key_values: Optional[Tuple[torch.Tensor, ...]] = None, use_cache: bool = False, ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]: """Forward pass for the attention mechanism.
Computes queries, keys, and values for the attention mechanism. Applies rotary positional embeddings to the queries and keys, and then computes attention scores and outputs.
For an introduction to the attention mechanism, see: https://arxiv.org/abs/1706.03762
A few things to note: - The past_key_values is used to implement the KV cache, which is used to speed up generation by caching the KV pairs from previous forward passes. This is useful when doing tasks that require generating multiple tokens conditioned on previous tokens (e.g. language modeling, text generation, etc.). The way the KV cache is implemented is that each layer has its own KV cache - this KV cache is implemented as a tuple. """ bsz, seq_len, _ = input.shape _queries, _keys, _values = ( self.q_proj(input), self.k_proj(input), self.v_proj(input), )
# Reshaping for multi-head attention queries = _queries.view(bsz, seq_len, self.n_heads, self.head_dim) keys = _keys.view(bsz, seq_len, self.n_kv_heads, self.head_dim) values = _values.view(bsz, seq_len, self.n_kv_heads, self.head_dim)
# The start position is used to apply the RoPE embeddings to only the new tokens # when using the kv_cache in the attention mechanism. # We want to start from the last position in the cache. start_pos = past_key_values[0].shape[1] if past_key_values is not None else 0
# apply rotary positional embeddings queries, keys = self.rope(queries, keys, start_pos)
if past_key_values is not None: keys = torch.cat([past_key_values[0], keys], dim=1) values = torch.cat([past_key_values[1], values], dim=1)
if use_cache: cached_keys = keys cached_values = values else: cached_keys = None cached_values = None
queries = queries.transpose(1, 2) keys = keys.transpose(1, 2) values = values.transpose(1, 2)
apply_gqa = self.n_rep > 1 if apply_gqa and queries.device.type == "mps": # NOTE: MPS does not support GQA in the SDPA kernel, but we can repeat the keys and values # outside of the kernel to get the same effect. # See: https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html keys = keys.repeat_interleave(self.n_rep, dim=-3) values = values.repeat_interleave(self.n_rep, dim=-3) apply_gqa = False
backends = [SDPBackend.CUDNN_ATTENTION, SDPBackend.MATH]
with sdpa_kernel(backends=backends): attn_output = F.scaled_dot_product_attention( queries.contiguous(), keys.contiguous(), values.contiguous(), attn_mask=mask.to(queries.dtype), enable_gqa=apply_gqa, )
attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, seq_len, -1) output = self.o_proj(attn_output)
return output, (cached_keys, cached_values)
########################################################## SwiGLU (Combines MLP and Activation)#########################################################
class SwiGLU(nn.Module): """SwiGLU Activation Function with Linear Projections.
Implements the SwiGLU activation function combined with linear transformations, serving as the feed-forward network in transformer blocks.
Args: config (Union[ModelConfig, PicoDecoderHFConfig]): Configuration containing: - config.d_model: Model dimension - config.activation_hidden_dim: Hidden dimension (typically 4 * d_model)
References: https://arxiv.org/abs/2002.05202 """
def __init__(self, config: Union["ModelConfig", "PicoDecoderHFConfig"]): super().__init__()
model_dim = config.d_model act_hidden_dim = config.activation_hidden_dim # usually 4 * d_model
self.w_0 = nn.Linear(model_dim, act_hidden_dim, bias=False) self.w_1 = nn.Linear(model_dim, act_hidden_dim, bias=False) self.w_2 = nn.Linear(act_hidden_dim, model_dim, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.w_2(F.silu(self.w_0(x)) * self.w_1(x))
########################################################## PicoDecoderBlock#########################################################
class PicoDecoderBlock(nn.Module): """Single Transformer Block with Attention and Feed-forward layers.
Implements a standard transformer block with: - Multi-head attention with normalization and residual connection - SwiGLU feed-forward network with normalization and residual connection
Args: config (Union[ModelConfig, PicoDecoderHFConfig]): Model configuration; either a dataclass or a HuggingFace PicoDecoderHFConfig """
def __init__( self, config: Union["ModelConfig", "PicoDecoderHFConfig"], ): super().__init__()
self.attention = Attention(config) self.swiglu = SwiGLU(config) self.attention_norm = RMSNorm(config) self.swiglu_norm = RMSNorm(config)
def forward( self, input: torch.Tensor, mask: Optional[torch.Tensor] = None, past_key_values: Optional[Tuple[torch.Tensor]] = None, use_cache: bool = False, ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]: attention_output, cached_key_values = self.attention( self.attention_norm(input), mask=mask, past_key_values=past_key_values, use_cache=use_cache, ) # NOTE: cached_key_values is None if use_cache is False
h = input + attention_output out = h + self.swiglu(self.swiglu_norm(h)) return out, cached_key_values
########################################################## Pico Decoder (Causal Transformer Model)#########################################################
class PicoDecoder(nn.Module): """ Pico Decoder: combines the embedding, causal decoder blocks, and output projection into a single autoregressive model.
For more information on the model, see the classes for the modules that make up the model. """
def __init__( self, model_config: Union["ModelConfig", "PicoDecoderHFConfig"], ): super().__init__() self.config = model_config
self.embedding_proj = nn.Embedding(self.config.vocab_size, self.config.d_model) self.layers = nn.ModuleList( [PicoDecoderBlock(self.config) for _ in range(self.config.n_layers)] ) self.output_norm = RMSNorm(self.config) self.de_embedding_proj = nn.Linear( self.config.d_model, self.config.vocab_size, bias=False )
def convert_to_hf_model(self) -> "PicoDecoderHF": """Convert the Lightning model to a HuggingFace model.""" # Build HF config hf_config = PicoDecoderHFConfig.from_dataclass(self.config)
# Instantiate the HF-wrapped model hf_model = PicoDecoderHF(hf_config)
# Grab our full state dict, prefixing module names raw_state = self.state_dict(prefix="pico_decoder.")
# Only keep keys that exist in the HF model (drops classifier_head, etc.) hf_keys = set(hf_model.state_dict().keys()) filtered_state = {k: v for k, v in raw_state.items() if k in hf_keys}
# Load into HF model, ignore any missing keys hf_model.load_state_dict(filtered_state, strict=False)
return hf_model
def forward( self, input_ids: torch.Tensor, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, use_cache: bool = False, return_hidden: bool = False, ) -> Tuple[torch.Tensor, Optional[Tuple[Tuple[torch.Tensor, torch.Tensor]]]]: """ This is the forward pass for the entire Pico model. It boils down to: - Embedding the input ids - Creating a causal mask - Processing through the pico layers - Projecting the output to logits
NOTE: One feature that might be confusing is the KV cache. The KV cache is used to speed up generation by caching the KV pairs from previous forward passes. This is useful when doing tasks that require generating multiple tokens conditioned on previous tokens (e.g. language modeling, text generation, etc.). The way the KV cache is implemented is that each layer has its own KV cache which is stored as a tuple. The whole model then stores a tuple of these KV caches (so a tuple of tuples). """
seq_len = input_ids.shape[-1] h = self.embedding_proj(input_ids)
# Calculate start position from past cached KV pairs. Remember that each layer has its # own KV Cache. So when we index past_key_values, we need to index into the KV pairs for the # correct layer and then for either the keys or values. start_pos = 0 if past_key_values is None else past_key_values[0][0].shape[1]
# Create causal mask for current sequence mask = None if seq_len > 1: mask = torch.full((seq_len, seq_len), float("-inf")) mask = torch.triu(mask, diagonal=1)
# If using KV cache, extend mask to cover cached sequence length if past_key_values is not None: # Add zeros for cached tokens (we can attend to all of them) mask = torch.hstack([torch.zeros((seq_len, start_pos)), mask])
mask = mask.to(h.device)
# NOTE: If we are using the cache, we need to store the cached KV pairs for each layer # in a tuple. Each layer will have its own cached KV pair which we aggregate in a tuple. cached_key_values = () if use_cache else None
# Process through transformer blocks for idx, layer in enumerate(self.layers): layer_past_key_values = ( past_key_values[idx] if past_key_values is not None else None )
h, layer_cached_key_values = layer( h, mask=mask, past_key_values=layer_past_key_values, use_cache=use_cache )
if use_cache: cached_key_values += (layer_cached_key_values,)
# Final norm and projection h = self.output_norm(h)
if return_hidden: return h, cached_key_values
logits = self.de_embedding_proj(h).float()
return logits, cached_key_values
########################################################## HuggingFace Wrapper for the Pico Decoder model.#########################################################
class PicoDecoderHFConfig(PretrainedConfig): """Config class for the Pico Decoder HuggingFace wrapper."""
model_type = "pico_decoder"
@classmethod def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> "PicoDecoderHFConfig": # NOTE The typical from_dict method doesn't actually set the attributes unless they are # defined in the constructor.
pico_config = cls(**kwargs)
# Because this class is just a wrapper around the ModelConfig dataclass, we need to do # a little extra work to ensure that the attributes are actually set. for key, value in config_dict.items(): setattr(pico_config, key, value)
return_unused_kwargs = kwargs.pop("return_unused_kwargs", False) unused_kwargs = { key: value for key, value in kwargs.items() if not hasattr(pico_config, key) }
if return_unused_kwargs: return pico_config, unused_kwargs return pico_config
@classmethod def from_dataclass(cls, model_config: "ModelConfig"): """Initialise from our custom config dataclass.""" return cls.from_dict(asdict(model_config))
class PicoDecoderHF(PreTrainedModel): """ HuggingFace wrapper for the Pico model.
Many evaluation frameworks require a model be setup as a HuggingFace model, so we provide a simple wrapper that does just that. When we save checkpoints of the Pico model, we save both the normal Pico model as well as the model wrapped in this HuggingFace class.
This also lets you do cool things like:
`model = AutoModelForCausalLM.from_pretrained("path/to/checkpoint")` """
config_class = PicoDecoderHFConfig _no_split_modules = ["PicoBlock", "Attention", "SwiGLU", "RMSNorm"]
def __init__(self, config: PicoDecoderHFConfig): super().__init__(config) self.pico_decoder = PicoDecoder(config)
def forward( self, input_ids: torch.Tensor, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, use_cache: bool = False, **kwargs, ) -> Union[CausalLMOutput, CausalLMOutputWithPast]: """HuggingFace forward pass wrapper.
Forwards pass for the HuggingFace version of the Pico Model. Basic wrapper around the Pico model's forward pass, and returns the output as a HuggingFace CausalLMOutput. """ logits, past_key_values = self.pico_decoder( input_ids, past_key_values, use_cache ) if use_cache: return CausalLMOutputWithPast( logits=logits, past_key_values=past_key_values, ) else: return CausalLMOutput( logits=logits, )
# Register for auto classesPicoDecoderHFConfig.register_for_auto_class()PicoDecoderHF.register_for_auto_class("AutoModel")PicoDecoderHF.register_for_auto_class("AutoModelForCausalLM")1234567891011121314151617181920212223{ "eos_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "mask_token": { "content": "[MASK]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": { "content": "<|padding|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }}checkpoints/step_0/config.jsonAdded+22
checkpoints/step_0/fabric_state/checkpoint/bf16_zero_pp_rank_0_mp_rank_00_optim_states.ptAdded+3
checkpoints/step_0/fabric_state/checkpoint/bf16_zero_pp_rank_1_mp_rank_00_optim_states.ptAdded+3
checkpoints/step_0/fabric_state/checkpoint/bf16_zero_pp_rank_2_mp_rank_00_optim_states.ptAdded+3
checkpoints/step_0/fabric_state/checkpoint/bf16_zero_pp_rank_3_mp_rank_00_optim_states.ptAdded+3
checkpoints/step_0/fabric_state/checkpoint/mp_rank_00_model_states.ptAdded+3
checkpoints/step_0/fabric_state/latestAdded+1
checkpoints/step_0/fabric_state/zero_to_fp32.pyAdded+760
checkpoints/step_0/model.safetensorsAdded+3
checkpoints/step_0/pico_decoder.pyAdded+623
checkpoints/step_0/special_tokens_map.jsonAdded+23
checkpoints/step_0/tokenizer.jsonAdded
checkpoints/step_0/tokenizer_config.jsonAdded+248
checkpoints/step_100/config.jsonAdded+22
checkpoints/step_100/fabric_state/checkpoint/bf16_zero_pp_rank_0_mp_rank_00_optim_states.ptAdded+3
checkpoints/step_100/fabric_state/checkpoint/bf16_zero_pp_rank_1_mp_rank_00_optim_states.ptAdded+3
checkpoints/step_100/fabric_state/checkpoint/bf16_zero_pp_rank_2_mp_rank_00_optim_states.ptAdded+3
checkpoints/step_100/fabric_state/checkpoint/bf16_zero_pp_rank_3_mp_rank_00_optim_states.ptAdded+3
checkpoints/step_100/fabric_state/checkpoint/mp_rank_00_model_states.ptAdded+3
checkpoints/step_100/fabric_state/latestAdded+1
checkpoints/step_100/fabric_state/zero_to_fp32.pyAdded+760
checkpoints/step_100/model.safetensorsAdded+3
checkpoints/step_100/pico_decoder.pyAdded+623
checkpoints/step_100/special_tokens_map.jsonAdded+23
checkpoints/step_100/tokenizer.jsonAdded
checkpoints/step_100/tokenizer_config.jsonAdded+248
checkpoints/step_1000/config.jsonAdded+22
checkpoints/step_1000/fabric_state/checkpoint/bf16_zero_pp_rank_0_mp_rank_00_optim_states.ptAdded+3
checkpoints/step_1000/fabric_state/checkpoint/bf16_zero_pp_rank_1_mp_rank_00_optim_states.ptAdded+3
checkpoints/step_1000/fabric_state/checkpoint/bf16_zero_pp_rank_2_mp_rank_00_optim_states.ptAdded+3
checkpoints/step_1000/fabric_state/checkpoint/bf16_zero_pp_rank_3_mp_rank_00_optim_states.ptAdded+3
checkpoints/step_1000/fabric_state/checkpoint/mp_rank_00_model_states.ptAdded+3
checkpoints/step_1000/fabric_state/latestAdded+1
checkpoints/step_1000/fabric_state/zero_to_fp32.pyAdded+760
checkpoints/step_1000/model.safetensorsAdded+3
checkpoints/step_1000/pico_decoder.pyAdded+623
checkpoints/step_1000/special_tokens_map.jsonAdded+23
checkpoints/step_1000/tokenizer.jsonAdded
checkpoints/step_1000/tokenizer_config.jsonAdded+248
checkpoints/step_1100/config.jsonAdded+22
checkpoints/step_1100/fabric_state/checkpoint/bf16_zero_pp_rank_0_mp_rank_00_optim_states.ptAdded+3
checkpoints/step_1100/fabric_state/checkpoint/bf16_zero_pp_rank_1_mp_rank_00_optim_states.ptAdded+3
checkpoints/step_1100/fabric_state/checkpoint/bf16_zero_pp_rank_2_mp_rank_00_optim_states.ptAdded+3
checkpoints/step_1100/fabric_state/checkpoint/bf16_zero_pp_rank_3_mp_rank_00_optim_states.ptAdded+3
checkpoints/step_1100/fabric_state/checkpoint/mp_rank_00_model_states.ptAdded+3
checkpoints/step_1100/fabric_state/latestAdded+1
checkpoints/step_1100/fabric_state/zero_to_fp32.pyAdded+760
checkpoints/step_1100/model.safetensorsAdded+3
checkpoints/step_1100/pico_decoder.pyAdded+623
checkpoints/step_1100/special_tokens_map.jsonAdded+23