flow-matching-1 / test /load_model.py
sabertoaster's picture
Add files using upload-large-folder tool
e8deda1 verified
Raw
History Blame Contribute Delete
3.6 kB
import sys
import argparse
from pathlib import Path
import torch
import torch.nn as nn
from omegaconf import OmegaConf
ROOT = Path(__file__).resolve().parent.parent.parent
sys.path.append(str(ROOT))
sys.path.append(str(ROOT / 'flow_matching'))
sys.path.append(str(ROOT / 'flow_matching/Matcha-TTS'))
from flow_matching.src.stage1.medarc_architecture import MultiSubjectConvLinearEncoder
from flow_matching.src.stage2.CFM import CFM
def _load_state_dict(path, map_location='cpu'):
try:
checkpoint = torch.load(path, map_location=map_location, weights_only=True)
except TypeError:
checkpoint = torch.load(path, map_location=map_location)
if isinstance(checkpoint, dict) and "state_dict" in checkpoint:
state_dict = checkpoint["state_dict"]
if isinstance(state_dict, dict):
return state_dict
return checkpoint
def export_stage1(cfg):
print('Exporting Stage 1...')
subjects_list = cfg.get('subjects', [1, 2, 3, 5])
feat_dims = (32,)
model = MultiSubjectConvLinearEncoder(
num_subjects=len(subjects_list),
feat_dims=feat_dims,
**cfg.stage1.model
)
weights_path = ROOT / 'output' / 'debug_run' / 'stage1_best.pt'
if weights_path.exists():
state_dict = _load_state_dict(weights_path, map_location='cpu')
model.load_state_dict(state_dict, strict=False)
print('Loaded Stage 1 weights.')
model.eval()
dummy_input = [torch.randn(2, 10, 32)]
save_path = 'stage1_model.onnx'
try:
torch.onnx.export(
model,
dummy_input,
save_path,
opset_version=14,
input_names=['features'],
output_names=['embeddings']
)
print(f'Saved {save_path}')
except Exception as e:
print(f'Failed exporting Stage 1: {e}')
def export_stage2(cfg, target_dim=1000):
print('\nExporting Stage 2...')
cfm_params = cfg.stage2.cfm
decoder_params = cfg.stage2.decoder
model = CFM(
feat_dim=target_dim,
cfm_params=cfm_params,
decoder_params=decoder_params,
)
weights_path = ROOT / 'output' / 'debug_run' / 'stage2_epoch_0.pt'
if weights_path.exists():
state_dict = _load_state_dict(weights_path, map_location='cpu')
model.load_state_dict(state_dict, strict=False)
print('Loaded Stage 2 weights.')
model.eval()
# Dummy input: (B, C, T)
B, C, T = 1, target_dim, 10
mu = torch.randn(B, C, T)
n_timesteps = torch.tensor(10)
save_path = 'stage2_model.onnx'
try:
torch.onnx.export(
model,
(mu, n_timesteps),
save_path,
opset_version=14,
input_names=['mu', 'n_timesteps'],
output_names=['output']
)
print(f'Saved {save_path}')
except Exception as e:
print(f'Failed exporting Stage 2: {e}')
if __name__ == '__main__':
config_path = ROOT / 'output' / 'debug_run' / 'config.yaml'
if config_path.exists():
cfg = OmegaConf.load(config_path)
else:
# Dummy config if config not found
cfg = OmegaConf.create({'stage1': {'model': {}}, 'stage2': {'cfm': {}, 'decoder': {'channels': [32, 32], 'dropout': 0.0, 'attention_head_dim': 16, 'n_blocks': 1, 'num_mid_blocks': 1, 'num_heads': 2, 'act_fn': 'snakebeta', 'down_block_type': 'transformer', 'mid_block_type': 'transformer', 'up_block_type': 'transformer'}}})
export_stage1(cfg)
export_stage2(cfg, target_dim=1000)