Smart Turn v3.2 fine-tuned for phone lines: ONNX and PyTorch weights, with tests and scripts
6daf493 Download scripts/smartturn.py from matthiastl/smart-turn-telephony: direct link, hf CLI and curl.
- Browser
- Download file 9.6 kB
-
https://huggingface.co/matthiastl/smart-turn-telephony/resolve/main/scripts/smartturn.py
- Command line
-
hf download hf://matthiastl/smart-turn-telephony/scripts/smartturn.py
-
curl -L -o smartturn.py https://huggingface.co/matthiastl/smart-turn-telephony/resolve/main/scripts/smartturn.py
9.6 kB
| """pipecat's Smart Turn v3 in plain PyTorch, loaded from its ONNX file. | |
| The architecture follows ``SmartTurnV3Model`` in pipecat-ai/smart-turn (BSD-2-Clause): a Whisper | |
| tiny encoder cut to 8 s of audio (400 positions), attention pooling over time and a small | |
| classifier. This file rebuilds it without ``transformers`` so the weights can be trained, and reads | |
| the weights straight from pipecat's float32 ONNX export. | |
| model = smartturn.from_onnx("smart-turn-v3.2-gpu.onnx") | |
| logits = model(smartturn.features(smartturn.windows([clip]))) # P(turn complete) = sigmoid | |
| """ | |
| from __future__ import annotations | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| from torch import nn | |
| from torch.nn import functional | |
| RATE = 16000 | |
| SECONDS = 8 | |
| LENGTH = SECONDS * RATE | |
| WIDTH, HEADS, LAYERS, FFN, POSITIONS = 384, 6, 4, 1536, 400 | |
| class EncoderLayer(nn.Module): | |
| """One Whisper encoder layer: pre-norm self-attention, then a pre-norm GELU feed-forward.""" | |
| def __init__(self): | |
| super().__init__() | |
| self.self_attn_layer_norm = nn.LayerNorm(WIDTH) | |
| self.q_proj = nn.Linear(WIDTH, WIDTH) | |
| self.k_proj = nn.Linear(WIDTH, WIDTH, bias=False) | |
| self.v_proj = nn.Linear(WIDTH, WIDTH) | |
| self.out_proj = nn.Linear(WIDTH, WIDTH) | |
| self.final_layer_norm = nn.LayerNorm(WIDTH) | |
| self.fc1 = nn.Linear(WIDTH, FFN) | |
| self.fc2 = nn.Linear(FFN, WIDTH) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| batch, steps, _ = x.shape | |
| h = self.self_attn_layer_norm(x) | |
| q, k, v = (proj(h).view(batch, steps, HEADS, WIDTH // HEADS).transpose(1, 2) for proj in (self.q_proj, self.k_proj, self.v_proj)) | |
| attended = functional.scaled_dot_product_attention(q, k, v).transpose(1, 2).reshape(batch, steps, WIDTH) | |
| x = x + self.out_proj(attended) | |
| return x + self.fc2(functional.gelu(self.fc1(self.final_layer_norm(x)))) | |
| class SmartTurn(nn.Module): | |
| """``features [B, 80, 800] -> logit [B]``: has the speaker finished their turn at the clip's end?""" | |
| def __init__(self): | |
| super().__init__() | |
| self.conv1 = nn.Conv1d(80, WIDTH, 3, padding=1) | |
| self.conv2 = nn.Conv1d(WIDTH, WIDTH, 3, stride=2, padding=1) | |
| self.register_buffer("embed_positions", torch.zeros(POSITIONS, WIDTH)) | |
| self.layers = nn.ModuleList(EncoderLayer() for _ in range(LAYERS)) | |
| self.layer_norm = nn.LayerNorm(WIDTH) | |
| self.pool_attention = nn.Sequential(nn.Linear(WIDTH, 256), nn.Tanh(), nn.Linear(256, 1)) | |
| self.classifier = nn.Sequential( | |
| nn.Linear(WIDTH, 256), nn.LayerNorm(256), nn.GELU(), nn.Dropout(0.1), nn.Linear(256, 64), nn.GELU(), nn.Linear(64, 1) | |
| ) | |
| def forward(self, features: torch.Tensor) -> torch.Tensor: | |
| x = functional.gelu(self.conv2(functional.gelu(self.conv1(features)))).transpose(1, 2) + self.embed_positions | |
| for layer in self.layers: | |
| x = layer(x) | |
| x = self.layer_norm(x) | |
| weights = torch.softmax(self.pool_attention(x), dim=1) | |
| return self.classifier((x * weights).sum(dim=1))[:, 0] | |
| def from_onnx(path: str | Path) -> SmartTurn: | |
| """The weights of pipecat's float32 ONNX export (``smart-turn-v3.2-gpu.onnx``) in a ``SmartTurn``. | |
| The exporter named the biases, norms and convolutions after the PyTorch modules and left the | |
| matrix-product weights anonymous and transposed. Each of those is identified by the named bias | |
| added to its product (``...q_proj.bias`` and so on). The key projection has no bias, so it is | |
| the unbiased product that reads the same layer norm as its layer's query projection. | |
| """ | |
| import onnx | |
| from onnx import numpy_helper | |
| graph = onnx.load(str(path)).graph | |
| named = {t.name: torch.from_numpy(numpy_helper.to_array(t).copy()) for t in graph.initializer} | |
| readers: dict[str, list] = {} | |
| for node in graph.node: | |
| for name in node.input: | |
| readers.setdefault(name, []).append(node) | |
| state = {} | |
| for key, value in named.items(): | |
| if not key.startswith("inner."): | |
| continue | |
| key = key.removeprefix("inner.").removeprefix("encoder.").replace("self_attn.", "") | |
| state[key.removesuffix(".weight") if key == "embed_positions.weight" else key] = value | |
| unbiased = [] # (MatMul's other input, weight) for products no bias is added to | |
| query_input = {} # the layer-norm output each layer's query projection reads -> layer prefix | |
| for node in graph.node: | |
| if node.op_type != "MatMul": | |
| continue | |
| weights = [name for name in node.input if name in named and not name.startswith("inner.")] | |
| if not weights: | |
| continue | |
| (weight,) = weights | |
| (source,) = [name for name in node.input if name != weight] | |
| bias = [ | |
| name | |
| for reader in readers.get(node.output[0], []) | |
| if reader.op_type == "Add" | |
| for name in reader.input | |
| if name.startswith("inner.") and name.endswith(".bias") | |
| ] | |
| if not bias: | |
| unbiased.append((source, named[weight])) | |
| continue | |
| key = bias[0].removeprefix("inner.").removeprefix("encoder.").replace("self_attn.", "").removesuffix(".bias") + ".weight" | |
| state[key] = named[weight].T.contiguous() | |
| if key.endswith("q_proj.weight"): | |
| query_input[source] = key.removesuffix("q_proj.weight") | |
| for source, weight in unbiased: | |
| state[query_input[source] + "k_proj.weight"] = weight.T.contiguous() | |
| model = SmartTurn() | |
| model.load_state_dict(state, strict=True) | |
| return model.eval() | |
| def from_safetensors(path: str | Path) -> SmartTurn: | |
| """A ``SmartTurn`` from weights saved by ``finetune_smartturn.py``.""" | |
| from safetensors.torch import load_file | |
| model = SmartTurn() | |
| model.load_state_dict(load_file(str(path)), strict=True) | |
| return model.eval() | |
| def windows(clips: list[np.ndarray]) -> torch.Tensor: | |
| """Each clip's last 8 s, zero-padded at the front, as pipecat's inference code feeds the model.""" | |
| out = torch.zeros(len(clips), LENGTH) | |
| for row, clip in enumerate(clips): | |
| tail = clip[-LENGTH:] | |
| out[row, LENGTH - tail.size :] = torch.from_numpy(np.ascontiguousarray(tail, dtype=np.float32)) | |
| return out | |
| _FILTERS: dict = {} | |
| def features(wave: torch.Tensor) -> torch.Tensor: | |
| """``[B, 128000]`` audio -> ``[B, 80, 800]`` Whisper log-mel features, on the audio's device. | |
| Each window is normalised to zero mean and unit variance first, as pipecat does. | |
| """ | |
| from inworld.sava import mel | |
| key = (wave.device, wave.dtype) | |
| if key not in _FILTERS: | |
| _FILTERS[key] = ( | |
| mel.mel_filterbank(num_bins=80).to(wave.device, wave.dtype), | |
| torch.hann_window(400, dtype=wave.dtype, device=wave.device), | |
| ) | |
| filters, window = _FILTERS[key] | |
| wave = (wave - wave.mean(dim=1, keepdim=True)) / torch.sqrt(wave.var(dim=1, unbiased=False, keepdim=True) + 1e-7) | |
| power = torch.stft(wave, 400, 160, window=window, center=True, pad_mode="reflect", return_complex=True).abs() ** 2 | |
| log_spec = torch.clamp(filters @ power[..., :-1], min=1e-10).log10() | |
| log_spec = torch.maximum(log_spec, log_spec.amax(dim=(1, 2), keepdim=True) - 8.0) | |
| return (log_spec + 4.0) / 4.0 | |
| class Exported(nn.Module): | |
| """The ONNX interface pipecat ships: ``input_features [B, 80, 800] -> logits [B, 1]``. | |
| Despite the output's name, pipecat's file returns the probability, so this one does too. | |
| """ | |
| def __init__(self, model: SmartTurn): | |
| super().__init__() | |
| self.model = model | |
| def forward(self, input_features: torch.Tensor) -> torch.Tensor: | |
| return torch.sigmoid(self.model(input_features))[:, None] | |
| def strip_metadata(path: Path) -> None: | |
| """Remove the exporter's per-node metadata and doc strings. | |
| They can hold the Python stack trace of the export, with this machine's file paths and user | |
| name; nothing in them is needed to run the graph. | |
| """ | |
| import onnx | |
| graph = onnx.load(str(path)) | |
| for node in list(graph.graph.node) + [node for function in graph.functions for node in function.node]: | |
| del node.metadata_props[:] | |
| node.doc_string = "" | |
| graph.graph.doc_string = "" | |
| onnx.save(graph, str(path)) | |
| if str(Path.home()).encode() in Path(path).read_bytes(): | |
| raise RuntimeError(f"{path} still contains this machine's home path") | |
| def export(model: SmartTurn, path: Path) -> None: | |
| """Write ``model`` as an ONNX file with the same input, output and batch axis as pipecat's.""" | |
| model = model.cpu().eval() | |
| example = torch.randn(2, 80, 800) | |
| torch.onnx.export( | |
| Exported(model), | |
| (example,), | |
| str(path), | |
| input_names=["input_features"], | |
| output_names=["logits"], | |
| dynamic_axes={"input_features": {0: "batch"}, "logits": {0: "batch"}}, | |
| opset_version=18, | |
| dynamo=False, | |
| ) | |
| strip_metadata(path) | |
| if __name__ == "__main__": | |
| import argparse | |
| import sys | |
| sys.path.insert(0, str(Path(__file__).parent)) # for export when run with python -I | |
| parser = argparse.ArgumentParser(description="Export fine-tuned Smart Turn weights to ONNX.") | |
| parser.add_argument("weights", type=Path, help="a .safetensors file from finetune_smartturn.py") | |
| parser.add_argument("out", type=Path, help="the .onnx file to write") | |
| args = parser.parse_args() | |
| args.out.parent.mkdir(parents=True, exist_ok=True) | |
| export(from_safetensors(args.weights), args.out) | |
| print(f"wrote {args.out}") | |