Download src/tiny_voca_gr/backend.py from ComputationalLinguisticsPlatform/tiny-voca-gr: direct link, hf CLI and curl.
- Browser
- Download file 6.43 kB
-
https://huggingface.co/ComputationalLinguisticsPlatform/tiny-voca-gr/resolve/main/src/tiny_voca_gr/backend.py
- Command line
-
hf download hf://ComputationalLinguisticsPlatform/tiny-voca-gr/src/tiny_voca_gr/backend.py
-
curl -L -o backend.py https://huggingface.co/ComputationalLinguisticsPlatform/tiny-voca-gr/resolve/main/src/tiny_voca_gr/backend.py
6.43 kB
| """MPS neural layers with differentiable CPU waveform/spectral operations.""" | |
| from functools import wraps | |
| import os | |
| import sys | |
| BACKEND_VERSION = 4 | |
| _cpu_waveform_calls = 0 | |
| def configure_environment(device): | |
| """Enable PyTorch's remaining MPS operator fallbacks before torch imports.""" | |
| if device != "mps": | |
| return | |
| if "torch" in sys.modules and os.environ.get("PYTORCH_ENABLE_MPS_FALLBACK") != "1": | |
| raise RuntimeError("Restart Python with PYTORCH_ENABLE_MPS_FALLBACK=1 before importing torch") | |
| os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" | |
| def status(): | |
| from tiny_voca import model, losses | |
| return {"backend_version": BACKEND_VERSION, "adapter_file": __file__, | |
| "model_file": model.__file__, "mps_fallback": os.environ.get("PYTORCH_ENABLE_MPS_FALLBACK"), | |
| "waveform_bridge_installed": bool(getattr(model.SourceFilter.forward, "_greek_mps_bridge", False)), | |
| "spectral_bridge_installed": bool(getattr(losses.magnitude, "_greek_mps_bridge", False)), | |
| "attention_layout_patch_installed": getattr(model.Attention.forward, "_greek_backend_version", None) == BACKEND_VERSION, | |
| "cpu_waveform_calls": _cpu_waveform_calls} | |
| def pulse_train_on_cpu(original, f0, sample_rate, hop, limit=0.47, phase=None): | |
| """Keep float64 phase accumulation on CPU, returning float32 to the caller. | |
| Tensor.to() keeps the autograd graph across devices. Do not detach or use | |
| no_grad here: pitch/phase derivatives must remain available to the caller. | |
| """ | |
| wave = original(f0.to("cpu"), sample_rate, hop, limit, | |
| None if phase is None else phase.to("cpu")) | |
| return wave.to(f0.device) | |
| def module_on_cpu(module, args): | |
| """Functional CPU execution; parameter copies stay connected to the optimizer. | |
| Do not move the live module or create a detached CPU replica. functional_call | |
| temporarily substitutes differentiable copies and restores the original | |
| parameters, preserving optimizer references and checkpoint device placement. | |
| """ | |
| import torch | |
| state = {name: value.to("cpu") for name, value in module.named_parameters()} | |
| state.update({name: value.to("cpu") for name, value in module.named_buffers()}) | |
| cpu_args = tuple(value.to("cpu") if isinstance(value, torch.Tensor) else value for value in args) | |
| return torch.func.functional_call(module, state, cpu_args, strict=True).to(args[0].device) | |
| def magnitude_on_cpu(original, wave, fft, hop, window): | |
| # Return only real magnitudes to MPS; complex STFT tensors and their backward | |
| # graphs stay on CPU. This also covers the spectrogram discriminators. | |
| return original(wave.to("cpu"), fft, hop, window.to("cpu")).to(wave.device) | |
| def contiguous_attention(module, x, mask, table): | |
| """Equivalent rotary attention using contiguous tensors and explicit matmuls. | |
| Avoid the MPS fused SDPA backward path with packed/permuted QKV views. | |
| Used only on MPS; CPU/CUDA keep upstream's optimized implementation. | |
| """ | |
| import torch | |
| from tiny_voca.model import rotate | |
| batch, length, channels = x.shape | |
| width = channels // module.heads | |
| packed = module.qkv(x.contiguous()).reshape(batch, length, 3, module.heads, width) | |
| q, k, v = (item.permute(0, 2, 1, 3).contiguous() for item in packed.unbind(dim=2)) | |
| q, k = rotate(q, table).contiguous(), rotate(k, table).contiguous() | |
| scores = torch.matmul(q, k.transpose(-2, -1).contiguous()) * (width ** -0.5) | |
| scores = scores.masked_fill(~mask[:, None, None, :], float("-inf")) | |
| weights = scores.softmax(dim=-1) | |
| weights = torch.nn.functional.dropout(weights, p=module.dropout, training=module.training) | |
| y = torch.matmul(weights.contiguous(), v) | |
| return module.out(y.transpose(1, 2).contiguous().reshape(batch, length, channels)) | |
| def install(): | |
| """Call after frontend.install(), before training or inference.""" | |
| from tiny_voca import model, losses | |
| functions = (model.pulse_train, model.SourceFilter.forward, losses.magnitude, model.Attention.forward) | |
| if all(getattr(f, "_greek_backend_version", None) == BACKEND_VERSION for f in functions): | |
| return | |
| # Recover originals on reinstall instead of accumulating wrapper layers. | |
| original = getattr(model.pulse_train, "_greek_original", model.pulse_train) | |
| def pulse_train(f0, sample_rate, hop, limit=0.47, phase=None): | |
| if f0.device.type == "mps": | |
| return pulse_train_on_cpu(original, f0, sample_rate, hop, limit, phase) | |
| return original(f0, sample_rate, hop, limit, phase) | |
| pulse_train._greek_mps_bridge = True | |
| pulse_train._greek_backend_version = BACKEND_VERSION | |
| pulse_train._greek_original = original | |
| model.pulse_train = pulse_train | |
| original_forward = getattr(model.SourceFilter.forward, "_greek_original", model.SourceFilter.forward) | |
| def source_filter(self, hidden, f0, lengths, noise=None, phase=None): | |
| global _cpu_waveform_calls | |
| if hidden.device.type == "mps": | |
| _cpu_waveform_calls += 1 | |
| return module_on_cpu(self, (hidden, f0, lengths, noise, phase)) | |
| return original_forward(self, hidden, f0, lengths, noise, phase) | |
| source_filter._greek_mps_bridge = True | |
| source_filter._greek_backend_version = BACKEND_VERSION | |
| source_filter._greek_original = original_forward | |
| model.SourceFilter.forward = source_filter | |
| original_magnitude = getattr(losses.magnitude, "_greek_original", losses.magnitude) | |
| def magnitude(wave, fft, hop, window): | |
| if wave.device.type == "mps": | |
| return magnitude_on_cpu(original_magnitude, wave, fft, hop, window) | |
| return original_magnitude(wave, fft, hop, window) | |
| magnitude._greek_mps_bridge = True | |
| magnitude._greek_backend_version = BACKEND_VERSION | |
| magnitude._greek_original = original_magnitude | |
| losses.magnitude = magnitude | |
| original_attention = getattr(model.Attention.forward, "_greek_original", model.Attention.forward) | |
| def attention(self, x, mask, table): | |
| if x.device.type == "mps": | |
| return contiguous_attention(self, x, mask, table) | |
| return original_attention(self, x, mask, table) | |
| attention._greek_backend_version = BACKEND_VERSION | |
| attention._greek_original = original_attention | |
| model.Attention.forward = attention | |