forked from mlc-ai/mlc-llm
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Slim-LM] Introduce HFLoad for loading Pytorch and SafeTensor weights (…
- Loading branch information
1 parent
e5927ce
commit 7ae8c6d
Showing
6 changed files
with
231 additions
and
166 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
"""Statistics of the loading process of parameter loaders""" | ||
import dataclasses | ||
import logging | ||
import time | ||
from contextlib import contextmanager | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
@dataclasses.dataclass | ||
class Stats: | ||
"""Statistics of the loading process of parameter loaders. | ||
Attributes | ||
---------- | ||
load_time_sec : float | ||
Time used in loading the parameters. | ||
map_time_sec : float | ||
Time used in applying the mapping function, i.e. `ExternMapping.map_func`. | ||
quant_time_sec : float | ||
Time used in quantizing the parameters, i.e. `QuantizeMapping.quant_func`. | ||
current_memory_gb : float | ||
The current RAM usage in GB. | ||
total_memory_gb : float | ||
The total size data loaded from disk in GB. | ||
max_memory_gb : float | ||
The maximum RAM usage in GB. | ||
""" | ||
|
||
load_time_sec: float = 0.0 | ||
map_time_sec: float = 0.0 | ||
quant_time_sec: float = 0.0 | ||
|
||
current_memory_gb: float = 0.0 | ||
total_memory_gb: float = 0.0 | ||
max_memory_gb: float = 0.0 | ||
|
||
def timer(self, attr): | ||
"""A context manager to time the scope and add the time to the attribute.""" | ||
|
||
@contextmanager | ||
def timed_scope(): | ||
start_time = time.time() | ||
yield | ||
elapsed_time = time.time() - start_time | ||
setattr(self, attr, getattr(self, attr) + elapsed_time) | ||
|
||
return timed_scope() | ||
|
||
def mem_add(self, nbytes: int): | ||
"""Add the memory usage by the given number of bytes.""" | ||
mem_gb = float(nbytes) / float(1024**3) | ||
self.current_memory_gb += mem_gb | ||
self.total_memory_gb += mem_gb | ||
self.max_memory_gb = max(self.max_memory_gb, self.current_memory_gb) | ||
|
||
def mem_rm(self, nbytes: int): | ||
"""Remove the memory usage by the given number of bytes.""" | ||
mem_gb = float(nbytes) / float(1024**3) | ||
self.current_memory_gb -= mem_gb | ||
|
||
def log_time_info(self, weight_format: str): | ||
"""Log the time used in loading, pre-quantization and quantization.""" | ||
logger.info( | ||
"Time used: " | ||
"%s loading: %.3f sec; " | ||
"Pre-quantization mapping: %.3f sec; " | ||
"Quantization: %.3f sec", | ||
weight_format, | ||
self.load_time_sec, | ||
self.map_time_sec, | ||
self.quant_time_sec, | ||
) | ||
|
||
def log_mem_usage(self): | ||
"""Log the Memory usage information.""" | ||
logger.info( | ||
"Memory usage: Total size loaded from disk: %.3f GB; Peak memory usage: %.3f GB", | ||
self.total_memory_gb, | ||
self.max_memory_gb, | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
"""Common utilities for loading parameters""" | ||
import logging | ||
from pathlib import Path | ||
from typing import Iterator, Set, Tuple | ||
|
||
import numpy as np | ||
|
||
from .mapping import ExternMapping | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
def check_parameter_usage(param_map: ExternMapping, extern_weights: Set[str]): | ||
"""Check that all external parameters have been used and are stored in the weights file.""" | ||
used_extern_names = set(sum(param_map.param_map.values(), [])) | ||
# Check 1. All extern parameters in the weight files are used unless explicitly specified | ||
unused_extern_names = extern_weights - used_extern_names - param_map.unused_params | ||
if unused_extern_names: | ||
logger.warning( | ||
"Unused extern parameters: %s", | ||
", ".join(sorted(unused_extern_names)), | ||
) | ||
# Check 2. All extern parameters required are stored in the weight files | ||
nonexistent_extern_names = used_extern_names - extern_weights | ||
if nonexistent_extern_names: | ||
raise ValueError( | ||
"The following extern parameters do not exist in the weight files:\n " | ||
+ "\n ".join(sorted(nonexistent_extern_names)), | ||
) | ||
|
||
|
||
def load_torch_shard(path: Path) -> Iterator[Tuple[str, np.ndarray]]: | ||
"""Load and yield PyTorch format parameters.""" | ||
import torch # pylint: disable=import-outside-toplevel | ||
|
||
for name, param in torch.load(path, map_location=torch.device("cpu")).items(): | ||
param = param.detach().cpu() | ||
dtype = str(param.dtype) | ||
if dtype == "torch.bfloat16": | ||
param = param.float() | ||
param = param.numpy() | ||
yield name, param | ||
|
||
|
||
def load_safetensor_shard(path: Path) -> Iterator[Tuple[str, np.ndarray]]: | ||
"""Load and yield SafeTensor format parameters.""" | ||
import safetensors # pylint: disable=import-outside-toplevel,import-error | ||
|
||
with safetensors.safe_open(path, framework="numpy", device="cpu") as in_file: | ||
for name in in_file.keys(): | ||
param = in_file.get_tensor(name) | ||
yield name, param |
Oops, something went wrong.