| 329 | |
| 330 | |
| 331 | def build_model(path, device): |
| 332 | config = Path(__file__).parent / "config.json" |
| 333 | assert config.exists(), f"Config path incorrect: config.json not found at {config}" |
| 334 | with open(config, "r") as r: |
| 335 | args = recursive_munch(json.load(r)) |
| 336 | assert args.decoder.type == "istftnet", f"Unknown decoder type: {args.decoder.type}" |
| 337 | decoder = Decoder( |
| 338 | dim_in=args.hidden_dim, |
| 339 | style_dim=args.style_dim, |
| 340 | dim_out=args.n_mels, |
| 341 | resblock_kernel_sizes=args.decoder.resblock_kernel_sizes, |
| 342 | upsample_rates=args.decoder.upsample_rates, |
| 343 | upsample_initial_channel=args.decoder.upsample_initial_channel, |
| 344 | resblock_dilation_sizes=args.decoder.resblock_dilation_sizes, |
| 345 | upsample_kernel_sizes=args.decoder.upsample_kernel_sizes, |
| 346 | gen_istft_n_fft=args.decoder.gen_istft_n_fft, |
| 347 | gen_istft_hop_size=args.decoder.gen_istft_hop_size, |
| 348 | ) |
| 349 | text_encoder = TextEncoder(channels=args.hidden_dim, kernel_size=5, depth=args.n_layer, n_symbols=args.n_token) |
| 350 | predictor = ProsodyPredictor( |
| 351 | style_dim=args.style_dim, |
| 352 | d_hid=args.hidden_dim, |
| 353 | nlayers=args.n_layer, |
| 354 | max_dur=args.max_dur, |
| 355 | dropout=args.dropout, |
| 356 | ) |
| 357 | bert = load_plbert() |
| 358 | bert_encoder = nn.Linear(bert.config.hidden_size, args.hidden_dim) |
| 359 | for parent in [bert, bert_encoder, predictor, decoder, text_encoder]: |
| 360 | for child in parent.children(): |
| 361 | if isinstance(child, nn.RNNBase): |
| 362 | child.flatten_parameters() |
| 363 | model = Munch( |
| 364 | bert=bert.to(device).eval(), |
| 365 | bert_encoder=bert_encoder.to(device).eval(), |
| 366 | predictor=predictor.to(device).eval(), |
| 367 | decoder=decoder.to(device).eval(), |
| 368 | text_encoder=text_encoder.to(device).eval(), |
| 369 | ) |
| 370 | for key, state_dict in torch.load(path, map_location="cpu", weights_only=True)["net"].items(): |
| 371 | assert key in model, key |
| 372 | try: |
| 373 | model[key].load_state_dict(state_dict) |
| 374 | except: |
| 375 | state_dict = {k[7:]: v for k, v in state_dict.items()} |
| 376 | model[key].load_state_dict(state_dict, strict=False) |
| 377 | return model |