diff --git a/packages/sie_server/src/sie_server/adapters/kokoro/model.py b/packages/sie_server/src/sie_server/adapters/kokoro/model.py index 002024381..3739ea6bd 100644 --- a/packages/sie_server/src/sie_server/adapters/kokoro/model.py +++ b/packages/sie_server/src/sie_server/adapters/kokoro/model.py @@ -2,17 +2,19 @@ Adapted from ``kokoro/model.py`` of kokoro 0.9.4 (https://github.com/hexgrad/kokoro, Apache-2.0). See ``NOTICE`` in this directory. Changes: config and weights are read -from local paths only (no Hub download), inference only, type annotations, and the -ONNX wrapper removed. +from local paths only (no Hub download), inference only, type annotations, the +ONNX wrapper removed, and convolutions that skip cuDNN autotuning. """ from __future__ import annotations import json +import logging from pathlib import Path from typing import Any import torch +import torch.nn.functional as F from torch import nn from transformers import AlbertConfig @@ -25,6 +27,143 @@ #: The released checkpoint does not store the affine parameters of the instance #: norms inside its adaptive normalization layers; they keep their constructor values. _UNSAVED_SUFFIXES = (".norm.weight", ".norm.bias") +#: Values ``torch._C._get_fp32_precision_getter`` returns. +_FP32_PRECISIONS = frozenset({"none", "ieee", "tf32"}) + +logger = logging.getLogger(__name__) + + +def _convolution( + module: nn.Conv1d | nn.ConvTranspose1d, + input_: torch.Tensor, + weight: torch.Tensor, + bias: torch.Tensor | None, + padding: tuple[int, ...], + *, + transposed: bool, + output_padding: list[int], +) -> torch.Tensor: + """The convolution ``torch.nn.functional`` would run, with cuDNN's autotuner off for this call only. + + ``F.conv1d`` reads ``torch.backends.cudnn.benchmark`` from process-global + state. The server turns it on for every model, so cuDNN times its candidate + algorithms for each new input shape. A Kokoro sequence's length follows its + text, so nearly every new text is a new shape and pays that search. Here the + flag is passed per call instead, which leaves the process setting, and every + other model sharing the process, untouched. The other cuDNN settings are + read the way ``torch.nn.functional`` reads them. + """ + return torch._convolution( + input_, + weight, + bias, + list(module.stride), + list(padding), + list(module.dilation), + transposed, + output_padding, + module.groups, + False, # benchmark + torch.backends.cudnn.deterministic or torch.are_deterministic_algorithms_enabled(), + torch.backends.cudnn.enabled, + cudnn_conv_allows_tf32(), + ) + + +def cudnn_conv_allows_tf32() -> bool: + """Whether cuDNN convolutions may use TF32, as ``torch.nn.functional`` decides it. + + A precision of ``"none"`` inherits from the level above it: the convolution + setting, then cuDNN's, then the generic one. The legacy + ``torch.backends.cudnn.allow_tf32`` writes the convolution setting, and its + getter refuses to answer when convolution and RNN settings differ, so it is + not read here. + """ + for backend, op in (("cuda", "conv"), ("cuda", "all"), ("generic", "all")): + precision = torch._C._get_fp32_precision_getter(backend, op) + if precision != "none": + return precision == "tf32" + return False + + +def per_call_benchmark_supported() -> bool: + """Whether this torch build has the private functions the per-call path calls. + + ``torch._convolution`` and ``torch._C._get_fp32_precision_getter`` are not + public API and can change or disappear in a torch release. One tiny CPU + convolution through the same call checks that both still exist and take the + arguments used here; if not, Kokoro keeps torch's own convolutions. + """ + try: + for backend, op in (("cuda", "conv"), ("cuda", "all"), ("generic", "all")): + if torch._C._get_fp32_precision_getter(backend, op) not in _FP32_PRECISIONS: + return False + x = torch.arange(6.0).reshape(1, 1, 6) + weight = torch.tensor([[[1.0, -2.0, 3.0]]]) + bias = torch.tensor([0.5]) + with torch.no_grad(): + got = torch._convolution( + x, weight, bias, [1], [1], [1], False, [0], 1, False, False, True, cudnn_conv_allows_tf32() + ) + want = F.conv1d(x, weight, bias, padding=1) + return got.shape == want.shape and bool(torch.allclose(got, want)) + except (AttributeError, TypeError, RuntimeError): # removed, or arguments no longer accepted + return False + + +#: Checked once at import, so a torch upgrade that changes the private API makes +#: Kokoro fall back to torch's convolutions instead of failing at inference. +_PER_CALL_BENCHMARK = per_call_benchmark_supported() + + +class _Conv1dNoAutotune(nn.Conv1d): + def _conv_forward(self, input: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor | None) -> torch.Tensor: + padding = self.padding + if self.padding_mode != "zeros" or isinstance(padding, str) or input.dim() != 3: + return super()._conv_forward(input, weight, bias) + return _convolution(self, input, weight, bias, padding, transposed=False, output_padding=[0]) + + +class _ConvTranspose1dNoAutotune(nn.ConvTranspose1d): + def forward(self, input: torch.Tensor, output_size: list[int] | None = None) -> torch.Tensor: + padding = self.padding + if self.padding_mode != "zeros" or isinstance(padding, str) or input.dim() != 3: + return super().forward(input, output_size) + output_padding = self._output_padding( + input, output_size, list(self.stride), list(padding), list(self.kernel_size), 1, list(self.dilation) + ) + return _convolution( + self, input, self.weight, self.bias, padding, transposed=True, output_padding=list(output_padding) + ) + + +_NO_AUTOTUNE: dict[type[nn.Module], type[nn.Module]] = { + nn.Conv1d: _Conv1dNoAutotune, + nn.ConvTranspose1d: _ConvTranspose1dNoAutotune, +} + + +def skip_conv_autotuning(model: nn.Module) -> int: + """Run every 1-D convolution in ``model`` without cuDNN autotuning; returns how many were switched. + + Only the layers' forward changes: parameters, buffers, hooks (weight + normalization) and state-dict names stay as they are. If this torch build + lacks the private functions the per-call path needs, nothing is switched. + """ + if not _PER_CALL_BENCHMARK: + logger.warning( + "torch._convolution or torch._C._get_fp32_precision_getter is missing or changed in torch %s; " + "Kokoro keeps torch's convolutions, so cuDNN autotunes each new input shape", + torch.__version__, + ) + return 0 + switched = 0 + for module in model.modules(): + replacement = _NO_AUTOTUNE.get(type(module)) + if replacement is not None: + module.__class__ = replacement + switched += 1 + return switched class KModel(nn.Module): @@ -56,6 +195,7 @@ def __init__(self, config: str | Path | dict[str, Any], model: str | Path) -> No dim_in=config["hidden_dim"], style_dim=config["style_dim"], dim_out=config["n_mels"], **config["istftnet"] ) self._load_checkpoint(model) + skip_conv_autotuning(self) def _load_checkpoint(self, model: str | Path) -> None: """Load every component's weights, refusing a checkpoint that does not fit the model.""" diff --git a/packages/sie_server/tests/adapters/test_kokoro_conv.py b/packages/sie_server/tests/adapters/test_kokoro_conv.py new file mode 100644 index 000000000..58b09b58d --- /dev/null +++ b/packages/sie_server/tests/adapters/test_kokoro_conv.py @@ -0,0 +1,291 @@ +"""Kokoro's convolutions run without cuDNN autotuning and leave the process setting alone.""" + +from __future__ import annotations + +from collections.abc import Iterator +from typing import Any + +import pytest +import torch +from sie_server.adapters.kokoro import model as kokoro_model +from sie_server.adapters.kokoro.istftnet import AdainResBlk1d +from sie_server.adapters.kokoro.model import KModel, cudnn_conv_allows_tf32, skip_conv_autotuning +from torch import nn +from torch.nn.utils import weight_norm + + +@pytest.fixture(autouse=True) +def _restore_cudnn_flags() -> Iterator[None]: + benchmark = torch.backends.cudnn.benchmark + legacy_tf32 = torch.backends.cudnn.allow_tf32 + conv = torch.backends.cudnn.conv.fp32_precision + rnn = torch.backends.cudnn.rnn.fp32_precision + yield + torch.backends.cudnn.benchmark = benchmark + # The legacy flag is stored apart from the precision settings; restore it + # first, or a later read of it (and ``cudnn.flags()``) raises. + torch.backends.cudnn.allow_tf32 = legacy_tf32 + torch.backends.cudnn.conv.fp32_precision = conv + torch.backends.cudnn.rnn.fp32_precision = rnn + + +@pytest.fixture +def convolution_calls(monkeypatch: pytest.MonkeyPatch) -> list[tuple[Any, ...]]: + calls: list[tuple[Any, ...]] = [] + real = torch._convolution + + def recording(*args: Any) -> torch.Tensor: + calls.append(args) + return real(*args) + + monkeypatch.setattr(kokoro_model.torch, "_convolution", recording) + return calls + + +def _layers() -> nn.ModuleDict: + torch.manual_seed(0) + return nn.ModuleDict( + { + "plain": nn.Conv1d(4, 6, 5, padding=2), + "dilated": weight_norm(nn.Conv1d(6, 6, 3, dilation=3, padding=3)), + "strided": weight_norm(nn.Conv1d(1, 1, 3, stride=2, padding=1)), + "no_bias": nn.Conv1d(6, 3, 1, bias=False), + "transposed": weight_norm( + nn.ConvTranspose1d(6, 6, kernel_size=3, stride=2, groups=6, padding=1, output_padding=1) + ), + "upsample": weight_norm(nn.ConvTranspose1d(6, 4, 20, 10, padding=5)), + } + ) + + +def _inputs() -> dict[str, torch.Tensor]: + torch.manual_seed(1) + return { + "plain": torch.randn(1, 4, 37), + "dilated": torch.randn(1, 6, 37), + "strided": torch.randn(1, 1, 41), + "no_bias": torch.randn(1, 6, 29), + "transposed": torch.randn(1, 6, 23), + "upsample": torch.randn(1, 6, 17), + } + + +def test_switched_layers_compute_the_same_output_as_torch() -> None: + reference, switched = _layers(), _layers() + assert skip_conv_autotuning(switched) == 6 + with torch.inference_mode(): + for name, x in _inputs().items(): + torch.testing.assert_close(switched[name](x), reference[name](x), rtol=0, atol=0) + + +def test_switch_keeps_parameters_hooks_and_state_dict_names() -> None: + layers = _layers() + names = list(layers.state_dict()) + skip_conv_autotuning(layers) + assert list(layers.state_dict()) == names + assert {"weight_g", "weight_v"} <= set(dict(layers["dilated"].named_parameters())) + assert layers["dilated"]._forward_pre_hooks + assert isinstance(layers["plain"], nn.Conv1d) + assert isinstance(layers["upsample"], nn.ConvTranspose1d) + + +def test_every_call_turns_the_autotuner_off_and_leaves_the_process_setting_on( + convolution_calls: list[tuple[Any, ...]], +) -> None: + torch.backends.cudnn.benchmark = True + layers = _layers() + skip_conv_autotuning(layers) + with torch.inference_mode(): + for name, x in _inputs().items(): + layers[name](x) + assert len(convolution_calls) == 6 + # Positional arguments of aten::_convolution: ... transposed, output_padding, + # groups, benchmark, deterministic, cudnn_enabled, allow_tf32. + assert [call[9] for call in convolution_calls] == [False] * 6 + assert [call[6] for call in convolution_calls] == [False, False, False, False, True, True] + assert torch.backends.cudnn.benchmark is True + + +def test_other_models_layers_still_follow_the_process_setting(convolution_calls: list[tuple[Any, ...]]) -> None: + torch.backends.cudnn.benchmark = True + kokoro, other = _layers(), _layers() + skip_conv_autotuning(kokoro) + x = _inputs()["plain"] + with torch.inference_mode(): + kokoro["plain"](x) + other["plain"](x) + # Only Kokoro's layer goes through the per-call path; the other layer runs + # torch's own convolution, which reads the process-wide benchmark flag. + assert len(convolution_calls) == 1 + assert type(other["plain"]) is nn.Conv1d + assert torch.backends.cudnn.benchmark is True + + +def test_other_cudnn_settings_are_passed_through(convolution_calls: list[tuple[Any, ...]]) -> None: + layer = nn.Conv1d(2, 2, 3) + skip_conv_autotuning(nn.Sequential(layer)) + x = torch.randn(1, 2, 8) + with torch.inference_mode(): + torch.backends.cudnn.allow_tf32 = False + layer(x) + torch.backends.cudnn.allow_tf32 = True + layer(x) + with torch.backends.cudnn.flags(enabled=False, deterministic=True): + layer(x) + assert [call[12] for call in convolution_calls] == [False, True, True] + assert [call[11] for call in convolution_calls] == [True, True, False] + assert [call[10] for call in convolution_calls] == [False, False, True] + + +@pytest.mark.parametrize("allow", [True, False]) +def test_tf32_matches_the_legacy_flag_the_server_sets(allow: bool) -> None: + torch.backends.cudnn.allow_tf32 = allow + assert cudnn_conv_allows_tf32() is allow + + +def test_tf32_follows_the_convolution_setting_when_rnn_differs() -> None: + torch.backends.cudnn.conv.fp32_precision = "tf32" + torch.backends.cudnn.rnn.fp32_precision = "ieee" + assert cudnn_conv_allows_tf32() is True + torch.backends.cudnn.conv.fp32_precision = "ieee" + torch.backends.cudnn.rnn.fp32_precision = "tf32" + assert cudnn_conv_allows_tf32() is False + + +def test_layers_outside_the_switch_are_left_alone() -> None: + model = nn.Sequential(nn.Conv2d(1, 1, 3), nn.Linear(2, 2), nn.Conv1d(1, 1, 3)) + assert skip_conv_autotuning(model) == 1 + assert type(model[0]) is nn.Conv2d + assert type(model[1]) is nn.Linear + + +def test_unbatched_input_falls_back_to_torch(convolution_calls: list[tuple[Any, ...]]) -> None: + layer = nn.Conv1d(2, 2, 3) + reference = nn.Conv1d(2, 2, 3) + reference.load_state_dict(layer.state_dict()) + skip_conv_autotuning(nn.Sequential(layer)) + x = torch.randn(2, 9) + torch.testing.assert_close(layer(x), reference(x), rtol=0, atol=0) + assert convolution_calls == [] + + +def test_kokoro_blocks_have_no_autotuned_convolution_left() -> None: + block = AdainResBlk1d(8, 4, style_dim=6, upsample=True) + assert skip_conv_autotuning(block) == 4 + assert not [m for m in block.modules() if type(m) in (nn.Conv1d, nn.ConvTranspose1d)] + + +_PRIVATE_API_CHANGED = ( + "torch changed a private function Kokoro's convolutions call " + "(torch._convolution or torch._C._get_fp32_precision_getter); " + "update _convolution / cudnn_conv_allows_tf32 in sie_server.adapters.kokoro.model" +) + + +def test_private_convolution_op_keeps_the_signature_kokoro_calls() -> None: + schemas = torch._C._jit_get_schemas_for_operator("aten::_convolution") + default = [s for s in schemas if not s.overload_name] + assert len(default) == 1, _PRIVATE_API_CHANGED + assert [argument.name for argument in default[0].arguments] == [ + "input", + "weight", + "bias", + "stride", + "padding", + "dilation", + "transposed", + "output_padding", + "groups", + "benchmark", + "deterministic", + "cudnn_enabled", + "allow_tf32", + ], _PRIVATE_API_CHANGED + + +def test_private_precision_getter_answers_for_every_level_kokoro_reads() -> None: + for backend, op in (("cuda", "conv"), ("cuda", "all"), ("generic", "all")): + assert torch._C._get_fp32_precision_getter(backend, op) in {"none", "ieee", "tf32"}, _PRIVATE_API_CHANGED + + +def test_this_torch_build_supports_the_per_call_path() -> None: + assert kokoro_model.per_call_benchmark_supported() is True, _PRIVATE_API_CHANGED + assert kokoro_model._PER_CALL_BENCHMARK is True, _PRIVATE_API_CHANGED + + +@pytest.mark.parametrize("owner_name", ["torch._convolution", "torch._C._get_fp32_precision_getter"]) +def test_a_missing_private_function_is_detected(monkeypatch: pytest.MonkeyPatch, owner_name: str) -> None: + owner, name = owner_name.rsplit(".", 1) + monkeypatch.delattr(torch._C if owner == "torch._C" else torch, name) + assert kokoro_model.per_call_benchmark_supported() is False + + +def test_a_changed_convolution_signature_is_detected(monkeypatch: pytest.MonkeyPatch) -> None: + def twelve_arguments(*args: Any) -> torch.Tensor: + if len(args) != 12: + raise TypeError(f"_convolution() takes 12 positional arguments but {len(args)} were given") + return torch.zeros(1) + + monkeypatch.setattr(torch, "_convolution", twelve_arguments) + assert kokoro_model.per_call_benchmark_supported() is False + + +def test_without_the_private_api_kokoro_keeps_torchs_convolutions( + monkeypatch: pytest.MonkeyPatch, convolution_calls: list[tuple[Any, ...]] +) -> None: + monkeypatch.setattr(kokoro_model, "_PER_CALL_BENCHMARK", False) + layers, reference = _layers(), _layers() + assert skip_conv_autotuning(layers) == 0 + assert not [ + m + for m in layers.modules() + if type(m) in (kokoro_model._Conv1dNoAutotune, kokoro_model._ConvTranspose1dNoAutotune) + ] + with torch.inference_mode(): + for name, x in _inputs().items(): + torch.testing.assert_close(layers[name](x), reference[name](x), rtol=0, atol=0) + assert convolution_calls == [] + + +def test_kmodel_switches_every_convolution_after_loading(monkeypatch: pytest.MonkeyPatch) -> None: + order: list[str] = [] + monkeypatch.setattr(KModel, "_load_checkpoint", lambda self, model: order.append("load")) + real_switch = kokoro_model.skip_conv_autotuning + monkeypatch.setattr( + kokoro_model, "skip_conv_autotuning", lambda model: order.append("switch") or real_switch(model) + ) + model = KModel(config=_tiny_config(), model="unused.pth") + assert order == ["load", "switch"] + convolutions = [m for m in model.modules() if isinstance(m, (nn.Conv1d, nn.ConvTranspose1d))] + assert convolutions + assert not [m for m in convolutions if type(m) in (nn.Conv1d, nn.ConvTranspose1d)] + + +def _tiny_config() -> dict[str, Any]: + return { + "vocab": {"a": 1, "b": 2}, + "n_token": 8, + "plbert": { + "hidden_size": 16, + "num_attention_heads": 2, + "intermediate_size": 32, + "max_position_embeddings": 32, + "num_hidden_layers": 1, + }, + "hidden_dim": 16, + "style_dim": 8, + "n_layer": 1, + "max_dur": 4, + "dropout": 0.0, + "text_encoder_kernel_size": 3, + "n_mels": 8, + "istftnet": { + "upsample_kernel_sizes": [4], + "upsample_rates": [2], + "gen_istft_hop_size": 2, + "gen_istft_n_fft": 4, + "resblock_dilation_sizes": [[1]], + "resblock_kernel_sizes": [3], + "upsample_initial_channel": 8, + }, + }