Files
Kakaru 2a8a013162 Unify training and ONNX-export environment, lift PyTorch 1.13 pin (#305)
* Unify training and ONNX-export environment, lift PyTorch 1.13 pin

The historical PyTorch 1.13 pin existed because two bugs surfaced in newer
torch when exporting to ONNX. Both are now fixed; training and export can
share a single environment (PyTorch >= 2.0).

Bug 1 - WaveNet diffusion ONNX export crashes on PyTorch >= 2.0
  modules/backbones/wavenet.py:83 used spec.squeeze(1), which the ONNX
  tracer lowers to an onnx::If whose two branches have different ranks
  (block0 Squeeze -> rank-3, block1 Identity -> rank-4). Shape inference
  for the downstream Conv then fails with SymbolicValueError. Replaced
  with spec[:, 0] - an unconditional rank-reducing gather, semantically
  identical (eager max-diff = 0) and producing a clean ONNX graph.

Bug 2 - non-RoPE encoder ONNX inference fails at dynamic lengths
  torch.nn.MultiheadAttention's multi_head_attention_forward gained an
  SDPA-branched implementation in torch 2.0. The branching caused the
  tracer to specialize tgt_len as a Python int constant and bake it into
  the output Reshape, so a model traced at T=40 errored with
  'requested shape:{40,2,32}' at any other length. The historical
  comment blaming espnet_positional_embedding.py was incorrect: the
  failure reproduces with a bare nn.MultiheadAttention and zero PE code,
  and survives even with the sinusoidal PE path which never touches
  the espnet module.

  Routed both non-RoPE paths through the in-house manual attention
  (MultiheadSelfAttentionWithRoPE with rotary_embed=None) that was
  already used on the RoPE path. It is fully dynamic-safe and produces
  identical eager output (max-diff 7e-7) at T=40/80/160.

Checkpoint compatibility
  Manual attention uses state_dict key 'in_proj.weight' whereas
  nn.MultiheadAttention used 'in_proj_weight'. Same shape and same
  Q/K/V-stacked-along-dim-0 semantics; utils.load_ckpt now renames the
  old key on load, so legacy ckpts continue to work with strict=True.

Diffusion graph simplification
  Each diffusion sub-graph was simplified twice: once before
  graph_extract_conditioner_projections and once after. The pre-surgery
  pass is removed. The conditioner-projection extraction rewrites the
  graph in a way that can collide with the first simplifier's node
  ordering and make the merged model fail onnx topological-sort
  validation downstream (a latent merge bug). The post-surgery
  simplifier subsumes the dropped pass, so the final graph is unchanged
  on the models that already worked, and the merge bug is avoided.
  Applies to acoustic (main diffusion), variance (pitch and multi-
  variance diffusions).

Dependency cleanup
  - Removed requirements-onnx.txt entirely (training and export share
    requirements.txt with PyTorch >= 2.0).
  - Replaced onnxsim with onnxslim (>=0.1.93) via a thin
    utils.onnx_helper.simplify_onnx wrapper. onnxslim is easier to
    install across environments and has no native build chain.
  - All torch.onnx.export calls stay on the TorchScript exporter that
    utils.onnx_helper's graph surgery was written against. The dynamo
    backend's availability differs across PyTorch versions: it first
    shipped as a separate torch.onnx.dynamo_export API in 2.1, and
    torch.onnx.export gained a 'dynamo' kwarg in 2.4 (default False,
    flipped to True in 2.9). Versions 2.0-2.3 have no such kwarg. To
    stay correct on all of them we probe
    inspect.signature(torch.onnx.export) once at import time and only
    pass dynamo=False when the kwarg exists - exposed as
    utils.onnx_helper.TORCHSCRIPT_EXPORT_KWARGS, splatted into every
    export call. Verified across torch 2.1 (no kwarg -> empty dict) and
    2.8 (kwarg present -> dynamo=False forwarded).
  - opset 15 -> 17. Verified with onnx.checker on all three model
    families.

* Unify ONNX env and bump PyTorch to >=2.4

Remove instructions to use a separate environment and requirements-onnx.txt for ONNX export; docs now recommend using the same environment for training and ONNX export and installing dependencies via the Installation section. Update requirements.txt comment to require PyTorch >= 2.4.

* Clarify PyTorch and environment recommendations

Update documentation and requirements comments to clarify environment setup: add 'uv' to the recommended virtual environment options, explicitly recommend using the latest stable PyTorch release (>= 2.4.0) in GettingStarted.md, and remove a redundant paragraph about a unified training/ONNX environment. Also adjust the top comment in requirements.txt to state that PyTorch >= 2.4 is recommended rather than required.

* Bump ONNX requirement to >=1.21.0

Update requirements.txt to change the onnx constraint from ~=1.16.0 to >=1.21.0, allowing newer ONNX releases for compatibility with updated dependencies/features.

* Unpin MonkeyType in requirements

Remove the exact version constraint for MonkeyType in requirements.txt (changed from MonkeyType==23.3.0 to MonkeyType) to allow installation of newer/compatible releases and relax strict dependency pinning.

Update requirements.txt
2026-06-21 00:18:58 +08:00

295 lines
8.8 KiB
Python

import os
import pathlib
import re
import sys
from typing import List
import click
import torch
root_dir = pathlib.Path(__file__).resolve().parent.parent
os.environ['PYTHONPATH'] = str(root_dir)
sys.path.insert(0, str(root_dir))
from utils.hparams import set_hparams, hparams
def find_exp(exp):
if not (root_dir / 'checkpoints' / exp).exists():
for subdir in (root_dir / 'checkpoints').iterdir():
if not subdir.is_dir():
continue
if subdir.name.startswith(exp):
print(f'| match ckpt by prefix: {subdir.name}')
exp = subdir.name
break
else:
raise click.BadParameter(
f'There are no matching exp starting with \'{exp}\' in \'checkpoints\' folder. '
'Please specify \'--exp\' as the folder name or prefix.'
)
else:
print(f'| found ckpt by name: {exp}')
return exp
def parse_spk_settings(export_spk, freeze_spk):
if export_spk is None:
export_spk = []
else:
export_spk = list(export_spk)
from utils.infer_utils import parse_commandline_spk_mix
spk_name_pattern = r'[0-9A-Za-z_-]+'
export_spk_mix = []
for spk in export_spk:
assert '=' in spk or '|' not in spk, \
'You must specify an alias with \'NAME=\' for each speaker mix.'
if '=' in spk:
alias, mix = spk.split('=', maxsplit=1)
assert re.fullmatch(spk_name_pattern, alias) is not None, f'Invalid alias \'{alias}\' for speaker mix.'
export_spk_mix.append((alias, parse_commandline_spk_mix(mix)))
else:
export_spk_mix.append((spk, {spk: 1.0}))
freeze_spk_mix = None
if freeze_spk is not None:
assert '=' in freeze_spk or '|' not in freeze_spk, \
'You must specify an alias with \'NAME=\' for each speaker mix.'
if '=' in freeze_spk:
alias, mix = freeze_spk.split('=', maxsplit=1)
assert re.fullmatch(spk_name_pattern, alias) is not None, f'Invalid alias \'{alias}\' for speaker mix.'
freeze_spk_mix = (alias, parse_commandline_spk_mix(mix))
else:
freeze_spk_mix = (freeze_spk, {freeze_spk: 1.0})
return export_spk_mix, freeze_spk_mix
@click.group()
def main():
pass
@main.command(help='Export DiffSinger acoustic model to ONNX format.')
@click.option(
'--exp', type=click.STRING,
required=True, metavar='EXP', callback=lambda ctx, param, value: find_exp(value),
help='Choose an experiment to export.'
)
@click.option(
'--ckpt', type=click.IntRange(min=0),
required=False, metavar='STEPS',
help='Checkpoint training steps.'
)
@click.option(
'--out', type=click.Path(
dir_okay=True, file_okay=False,
path_type=pathlib.Path, resolve_path=True
),
required=False,
help='Output directory for the artifacts.'
)
@click.option(
'--freeze_gender', type=click.FloatRange(min=-1, max=1),
help='(for random pitch shifting) Freeze gender value into the model.'
)
@click.option(
'--freeze_velocity', is_flag=True,
help='(for random time stretching) Freeze default velocity value into the model.'
)
@click.option(
'--export_spk', type=click.STRING,
required=False, multiple=True,
help='(for multi-speaker models) Export one or more speaker or speaker mixture keys.'
)
@click.option(
'--freeze_spk', type=click.STRING,
required=False,
help='(for multi-speaker models) Freeze one speaker or speaker mixture into the model.'
)
def acoustic(
exp: str,
ckpt: int = None,
out: pathlib.Path = None,
freeze_gender: float = 0.,
freeze_velocity: bool = False,
export_spk: List[str] = None,
freeze_spk: str = None
):
# Validate arguments
if export_spk and freeze_spk:
print('--export_spk is exclusive to --freeze_spk.')
exit(-1)
if out is None:
out = root_dir / 'artifacts' / exp
export_spk_mix, freeze_spk_mix = parse_spk_settings(export_spk, freeze_spk)
# Load configurations
sys.argv = [
sys.argv[0],
'--exp_name',
exp,
'--infer'
]
set_hparams()
# Export artifacts
from deployment.exporters import DiffSingerAcousticExporter
print(f'| Exporter: {DiffSingerAcousticExporter}')
exporter = DiffSingerAcousticExporter(
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu'),
cache_dir=root_dir / 'deployment' / 'cache',
ckpt_steps=ckpt,
freeze_gender=freeze_gender,
freeze_velocity=freeze_velocity,
export_spk=export_spk_mix,
freeze_spk=freeze_spk_mix
)
try:
exporter.export(out)
except KeyboardInterrupt:
exit(-1)
@main.command(help='Export DiffSinger variance model to ONNX format.')
@click.option(
'--exp', type=click.STRING,
required=True, metavar='EXP', callback=lambda ctx, param, value: find_exp(value),
help='Choose an experiment to export.'
)
@click.option(
'--ckpt', type=click.IntRange(min=0),
required=False, metavar='STEPS',
help='Checkpoint training steps.'
)
@click.option(
'--out', type=click.Path(
dir_okay=True, file_okay=False,
path_type=pathlib.Path, resolve_path=True
),
required=False,
help='Output directory for the artifacts.'
)
@click.option(
'--freeze_glide', is_flag=True,
help='Freeze default glide embedding into the model.'
)
@click.option(
'--freeze_expr', is_flag=True,
help='Freeze default pitch expressiveness factor into the model.'
)
@click.option(
'--export_spk', type=click.STRING,
required=False, multiple=True,
help='(for multi-speaker models) Export one or more speaker or speaker mixture keys.'
)
@click.option(
'--freeze_spk', type=click.STRING,
required=False,
help='(for multi-speaker models) Freeze one speaker or speaker mixture into the model.'
)
def variance(
exp: str,
ckpt: int = None,
out: str = None,
freeze_glide: bool = False,
freeze_expr: bool = False,
export_spk: List[str] = None,
freeze_spk: str = None
):
# Validate arguments
if export_spk and freeze_spk:
print('--export_spk is exclusive to --freeze_spk.')
exit(-1)
if out is None:
out = root_dir / 'artifacts' / exp
export_spk_mix, freeze_spk_mix = parse_spk_settings(export_spk, freeze_spk)
# Load configurations
sys.argv = [
sys.argv[0],
'--exp_name',
exp,
'--infer'
]
set_hparams()
from deployment.exporters import DiffSingerVarianceExporter
print(f'| Exporter: {DiffSingerVarianceExporter}')
exporter = DiffSingerVarianceExporter(
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu'),
cache_dir=root_dir / 'deployment' / 'cache',
ckpt_steps=ckpt,
freeze_glide=freeze_glide,
freeze_expr=freeze_expr,
export_spk=export_spk_mix,
freeze_spk=freeze_spk_mix
)
try:
exporter.export(out)
except KeyboardInterrupt:
exit(-1)
@main.command(help='Export NSF-HiFiGAN vocoder model to ONNX format.')
@click.option(
'--config', type=click.Path(
exists=True, file_okay=True, dir_okay=False, readable=True,
path_type=pathlib.Path, resolve_path=True
),
required=True,
help='Specify a configuration file for the vocoder.'
)
@click.option(
'--ckpt', type=click.Path(
exists=True, file_okay=True, dir_okay=False, readable=True,
path_type=pathlib.Path, resolve_path=True
),
required=False,
help='Specify a model path of the vocoder checkpoint.'
)
@click.option(
'--out', type=click.Path(
dir_okay=True, file_okay=False,
path_type=pathlib.Path, resolve_path=True
),
required=False,
help='Output directory for the artifacts.'
)
@click.option(
'--name', type=click.STRING,
required=False, default='nsf_hifigan', show_default=False,
help='Specify filename (without suffix) of the target model file.'
)
def nsf_hifigan(
config: pathlib.Path,
ckpt: pathlib.Path = None,
out: pathlib.Path = None,
name: str = None
):
# Check arguments
if out is None:
out = root_dir / 'artifacts' / 'nsf_hifigan'
# Load configurations
set_hparams(config.as_posix())
if ckpt is None:
model_path = pathlib.Path(hparams['vocoder_ckpt']).resolve()
else:
model_path = ckpt
# Export artifacts
from deployment.exporters import NSFHiFiGANExporter
print(f'| Exporter: {NSFHiFiGANExporter}')
exporter = NSFHiFiGANExporter(
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu'),
cache_dir=root_dir / 'deployment' / 'cache',
model_path=model_path,
model_name=name
)
try:
exporter.export(out)
except KeyboardInterrupt:
exit(-1)
if __name__ == '__main__':
main()