File size: 3,105 Bytes
314ecfb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | import json
from pathlib import Path
from typing import Dict, TypeVar
import torch
from accelerate import init_empty_weights
from safetensors import safe_open
from torch import nn
ModuleT = TypeVar("ModuleT", bound=nn.Module)
def _shard_paths_for_prefix(model_dir: Path, prefix: str) -> list[Path]:
index_path = model_dir / "model.safetensors.index.json"
if index_path.exists():
with open(index_path, encoding="utf-8") as f:
weight_map = json.load(f)["weight_map"]
shard_names = sorted(
{shard_name for key, shard_name in weight_map.items() if key.startswith(prefix)}
)
if not shard_names:
raise RuntimeError(f"No weights found for prefix {prefix!r} in {index_path}")
return [model_dir / shard_name for shard_name in shard_names]
single_path = model_dir / "model.safetensors"
if single_path.exists():
with safe_open(single_path, framework="pt", device="cpu") as shard:
if any(key.startswith(prefix) for key in shard.keys()):
return [single_path]
raise RuntimeError(f"No weights found for prefix {prefix!r} in {single_path}")
raise FileNotFoundError(
f"Missing safetensors weights in {model_dir}: expected "
f"model.safetensors.index.json or model.safetensors"
)
def load_prefixed_state_dict(model_path: str, prefix: str) -> Dict[str, torch.Tensor]:
model_dir = Path(model_path)
state_dict: Dict[str, torch.Tensor] = {}
for shard_path in _shard_paths_for_prefix(model_dir, prefix):
with safe_open(shard_path, framework="pt", device="cpu") as shard:
for key in shard.keys():
if key.startswith(prefix):
state_dict[key[len(prefix) :]] = shard.get_tensor(key)
return state_dict
def build_empty_module(module_cls, config) -> ModuleT:
"""Build module on meta device without random weight initialization."""
with init_empty_weights():
return module_cls._from_config(config)
def load_prefixed_safetensors(
module: nn.Module,
model_path: str,
prefix: str,
torch_dtype: torch.dtype | None = None,
) -> None:
state_dict = load_prefixed_state_dict(model_path, prefix)
if torch_dtype is not None:
state_dict = {key: value.to(torch_dtype) for key, value in state_dict.items()}
missing, unexpected = module.load_state_dict(state_dict, strict=False, assign=True)
if missing or unexpected:
raise RuntimeError(
f"Failed loading Qwen weights for prefix {prefix!r}: "
f"missing={missing[:10]}, unexpected={unexpected[:10]}"
)
# Materialize any parameters that were not present in the checkpoint.
for name, param in module.named_parameters():
if param.device.type == "meta":
raise RuntimeError(f"Parameter {name!r} remained on meta device after loading {prefix!r}")
for name, buffer in module.named_buffers():
if buffer.device.type == "meta":
raise RuntimeError(f"Buffer {name!r} remained on meta device after loading {prefix!r}")
|