Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 142 additions & 2 deletions packages/sie_server/src/sie_server/adapters/kokoro/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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):
Expand Down Expand Up @@ -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."""
Expand Down
Loading
Loading