File size: 6,434 Bytes
927ea15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
"""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)

    @wraps(original)
    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)

    @wraps(original_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)

    @wraps(original_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)

    @wraps(original_attention)
    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