Source code for nemo_automodel.checkpoint._backports.hf_utils
# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import io
import json
import struct
from dataclasses import dataclass
from typing import Any, Optional
import torch
_metadata_fn: str = "model.safetensors.index.json"
FILE_NAME = "model-{cpt_idx}-of-{num_files}"
SHARDED_FILE_NAME = "shard-{shard_idx}-model-{cpt_idx}-of-{num_files}"
SUFFIX = ".safetensors"
# metadata keys
CUSTOM_METADATA_KEY = "DCP_SHARDING_INFO"
DEFAULT_EXTRA_METADATA_KEY = "__metadata__"
SAVED_OFFSETS_KEY = "saved_offsets"
SHAPE_KEY = "shape"
DATA_KEY = "data"
DTYPE_KEY = "dtype"
DATA_OFFSETS_KEY = "data_offsets"
DTYPE_MAP = {
"F16": torch.float16,
"F32": torch.float32,
"F64": torch.float64,
"I8": torch.int8,
"U8": torch.uint8,
"I16": torch.int16,
"I32": torch.int32,
"I64": torch.int64,
"BF16": torch.bfloat16,
}
HF_DCP_VERSION: float = 1.0
DCP_VERSION_KEY = "DCP_VERSION"
DCP_SHARDING_INFO_KEY = "DCP_SHARDING_INFO"
[docs]
@dataclass
class _HFStorageInfo:
"""This is the per entry storage info."""
relative_path: str
offset: int
length: int
shape: torch.Size
dtype: torch.dtype
[docs]
def __getstate__(self):
return {k: v for k, v in self.__dict__.items() if v is not None}
[docs]
def _gen_file_name(index: int, largest_index: int, shard_index: Optional[int] = None) -> str:
if shard_index is not None:
return (
SHARDED_FILE_NAME.format(
shard_idx=f"{shard_index}".zfill(5), cpt_idx=f"{index}".zfill(5), num_files=f"{largest_index}".zfill(5)
)
+ SUFFIX
)
else:
return FILE_NAME.format(cpt_idx=f"{index}".zfill(5), num_files=f"{largest_index}".zfill(5)) + SUFFIX
[docs]
def _get_dtype(dtype_str: str) -> torch.dtype:
try:
dtype = DTYPE_MAP[dtype_str]
except KeyError:
dtype = torch.get_default_dtype()
return dtype