VorA / tools /load_weights.py
DocD0c's picture
Keep four Human2Robot models and simplify the overview
9ed790d verified
Raw History Blame Contribute Delete
1.91 kB
"""Load safe tensor parameters and portable inference metadata."""
from pathlib import Path
import json
def load_weights(model_path, *, revision, repo_id='DocD0c/VorA', local_root=None):
from safetensors.torch import load_file
if local_root is None:
from huggingface_hub import hf_hub_download
def resolve(name):
return hf_hub_download(repo_id,model_path+name,repo_type='dataset',revision=revision)
else:
def resolve(name):return str(Path(local_root)/(model_path+name))
metadata=json.loads(Path(resolve('.json')).read_text())
state_dict=load_file(resolve('.safetensors'),device='cpu')
assert len(state_dict)==metadata['release']['tensor_count']
assert sum(x.numel() for x in state_dict.values())==metadata['release']['parameter_elements']
return state_dict,metadata
def model_module(model_path):
choices = {
'weights/recorded/full_seed0': 'main',
'weights/recorded/video_seed0': 'main',
'weights/recorded/action_seed0': 'carrier',
'weights/recorded/none_seed0': 'carrier',
}
if model_path not in choices:
raise ValueError('Choose one of the four models in weights/index.json')
prefix = __package__+'.model_code.' if __package__ else 'model_code.'
return prefix+'recorded.'+choices[model_path]+'.hr_mot'
def load_model(model_path, *, revision, repo_id='DocD0c/VorA', local_root=None):
import importlib
state,metadata=load_weights(model_path,revision=revision,repo_id=repo_id,local_root=local_root)
module=importlib.import_module(model_module(model_path))
if model_path.split('/')[1] in ('recorded','coupling','language'):
model=module.HRMoTFlowModel(module.HRMoTConfig(**metadata['config']))
else:
model=(module.Model if hasattr(module,'Model') else module.Policy)()
model.load_state_dict(state,strict=True)
return model.eval(),metadata