luxfer / runtime /weights /loading.py
mdxss's picture
Publish Luxfer early beta with runnable weights and language metadata
7b6f2cc verified
Raw History Blame Contribute Delete
2.04 kB
"""Strict mmap loading: no randomly initialized full-size model or checkpoint copy."""
import json
from pathlib import Path
import torch
from safetensors.torch import load_file
from architecture.config import LuxferConfig
from architecture.model import LuxferForCausalLM
def load_model(path, device='cpu'):
path = Path(path).resolve()
config = LuxferConfig(**json.loads((path/'config.json').read_text()))
if config.image_feature_size is not None:
raise ValueError('This translation implementation supports text checkpoints only')
with torch.device('meta'):
model = LuxferForCausalLM(config)
if hasattr(config, 'next_rank'):
rank = config.next_rank
if not 0 < rank < min(config.hidden_size, config.intermediate_size):
raise ValueError('Invalid factorization rank')
for layer in model.model.layers.layers:
layer.mlp.down_proj = torch.nn.Sequential(
torch.nn.Linear(config.intermediate_size, rank, bias=False),
torch.nn.Linear(rank, config.hidden_size, bias=False))
if (path/'model.safetensors').exists():state=load_file(str(path/'model.safetensors'),device=device)
else:
from weights.identity import shard_files
index,files=shard_files(path);state={}
for name in files:
shard=load_file(str(path/name),device=device)
if any(key in state or index['weight_map'].get(key)!=name for key in shard):raise ValueError('Shard/index tensor mismatch')
state.update(shard)
if set(state)!=set(index['weight_map']):raise ValueError('Missing indexed tensors')
model.load_state_dict(state, strict=True, assign=True)
for module in model.modules():
if hasattr(module, '_compute_buffers'):
module.device = torch.device(device)
module._compute_buffers()
for module in model.modules():
if hasattr(module,'refresh_expansion_state'):module.refresh_expansion_state()
return model.eval()