ConsDrive / models /qwen_utils.py
ZenoNing's picture
Upload ConsDrive v2 source (part 2)
314ecfb verified
Raw History Blame Contribute Delete
3.11 kB
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}")