File size: 1,985 Bytes
e8deda1 | 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 | import torch
import torch.nn as nn
from pathlib import Path
from .stage1.medarc_architecture import MultiSubjectConvLinearEncoder
from .stage2.CFM import CFM
def build_models(cfg, ckpt_dir: Path, all_features, subjects, device, stage2_ckpt_name=None):
"""Build and load stage 1 and stage 2 models from checkpoints."""
sample_episode = next(iter(all_features[0]))
feat_dims = [feats[sample_episode].shape[-1] for feats in all_features]
print(f" Feature dims: {feat_dims}")
stage1_model = MultiSubjectConvLinearEncoder(
num_subjects=len(subjects),
feat_dims=feat_dims,
**cfg.stage1.model,
).to(device)
stage1_path = ckpt_dir / "stage1_best.pt"
print(f" Loading stage 1: {stage1_path}")
stage1_model.load_state_dict(torch.load(stage1_path, map_location=device, weights_only=True))
stage1_model.eval()
target_dim = 1000
cfm_params = cfg.stage2.cfm
decoder_params = cfg.stage2.decoder
latent_dim = cfg.stage2.get("latent_dim", 128)
stage2_models = nn.ModuleDict()
for sub in subjects:
sub_key = str(sub)
cfm_model = CFM(
in_channels=2 * target_dim,
out_channel=target_dim,
cfm_params=cfm_params,
decoder_params=decoder_params,
n_spks=1,
voxel_dim=target_dim,
latent_dim=latent_dim,
)
stage2_models[sub_key] = cfm_model
if stage2_ckpt_name:
stage2_path = ckpt_dir / stage2_ckpt_name
else:
stage2_paths = sorted(ckpt_dir.glob("stage2_epoch_*.pt"))
if not stage2_paths:
raise FileNotFoundError(f"No stage2 checkpoints found in {ckpt_dir}")
stage2_path = stage2_paths[-1]
print(f" Loading stage 2: {stage2_path}")
stage2_models.load_state_dict(torch.load(stage2_path, map_location=device, weights_only=True))
stage2_models = stage2_models.to(device)
stage2_models.eval()
return stage1_model, stage2_models
|