-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Introduce HFLoad for loading Pytorch and SafeTensor weights
- Loading branch information
1 parent
e5927ce
commit a8b0241
Showing
5 changed files
with
225 additions
and
165 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,129 @@ | ||
"""A weight loader for HuggingFace's PyTorch format""" | ||
import dataclasses | ||
import logging | ||
import time | ||
from contextlib import contextmanager | ||
from pathlib import Path | ||
from typing import Set | ||
|
||
from .mapping import ExternMapping | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
@dataclasses.dataclass | ||
class Stats: | ||
"""Statistics of the loading process of HuggingFace PyTorch loader. | ||
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, | ||
) | ||
|
||
|
||
def _check_parameter_usage(param_map: ExternMapping, torch_weights: Set[str]): | ||
used_torch_names = set(sum(param_map.param_map.values(), [])) | ||
# Check 1. All PyTorch parameters in the weight files are used unless explicitly specified | ||
unused_torch_names = torch_weights - used_torch_names - param_map.unused_params | ||
if unused_torch_names: | ||
logger.warning( | ||
"Unused torch parameters: %s", | ||
", ".join(sorted(unused_torch_names)), | ||
) | ||
# Check 2. All PyTorch parameters required are stored in the weight files | ||
nonexistent_torch_names = used_torch_names - torch_weights | ||
if nonexistent_torch_names: | ||
raise ValueError( | ||
"The following torch parameters do not exist in the weight files:\n " | ||
+ "\n ".join(sorted(nonexistent_torch_names)), | ||
) | ||
|
||
|
||
def _load_torch_shard(path: Path): | ||
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): | ||
import safetensors # pylint: disable=import-outside-toplevel | ||
|
||
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.