File size: 5,776 Bytes
49670c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# MIT License
# 
# Copyright (c) 2026 audio-embeddings contributors
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from __future__ import annotations

from typing import Sequence

import torch
from einops import rearrange
from einops.layers.torch import Rearrange
from torch import nn


def _parse_conv_layers_spec(
    conv_layers_spec: str | Sequence[Sequence[int]] | Sequence[tuple[int, int, int]],
) -> list[tuple[int, int, int]]:
    if isinstance(conv_layers_spec, str):
        # Config-driven expression style used by wavjepa, e.g.
        # "[(512, 10, 5)] + [(512, 3, 2)] * 4 + [(512, 2, 2)]"
        parsed = eval(conv_layers_spec, {"__builtins__": {}}, {})  # noqa: S307
    else:
        parsed = conv_layers_spec

    out: list[tuple[int, int, int]] = []
    for layer in parsed:
        if len(layer) != 3:
            raise ValueError(f"Invalid conv layer spec {layer}, expected (dim, k, s)")
        dim, kernel, stride = layer
        out.append((int(dim), int(kernel), int(stride)))
    if len(out) == 0:
        raise ValueError("conv_layers_spec must contain at least one layer")
    return out


class WaveformFeatureEncoder(nn.Module):
    """
    Convolutional waveform feature encoder that outputs a token sequence.

    Input shape: [B, C, T]
    Output shape: [B, N, F]
    """

    def __init__(
        self,
        conv_layers_spec: str
        | Sequence[Sequence[int]]
        | Sequence[
            tuple[int, int, int]
        ] = "[(512, 10, 5)] + [(512, 3, 2)] * 4 + [(512, 2, 2)]",
        in_channels: int = 1,
        dropout: float = 0.0,
        mode: str = "default",
        conv_bias: bool = False,
        depthwise: bool = False,
    ) -> None:
        super().__init__()
        if mode not in {"default", "layer_norm"}:
            raise ValueError(
                f"Unknown mode='{mode}', expected 'default' or 'layer_norm'"
            )
        self.conv_layers_spec = _parse_conv_layers_spec(conv_layers_spec)
        self.in_channels = in_channels
        self.depthwise = depthwise

        layers: list[nn.Module] = []
        in_dim = in_channels
        for idx, (out_dim, kernel, stride) in enumerate(self.conv_layers_spec):
            layers.append(
                self._make_block(
                    in_dim=in_dim,
                    out_dim=out_dim,
                    kernel=kernel,
                    stride=stride,
                    dropout=dropout,
                    mode=mode,
                    conv_bias=conv_bias,
                    depthwise=depthwise,
                    is_first=idx == 0,
                )
            )
            in_dim = out_dim

        self.cnn = nn.Sequential(*layers)
        self.embedding_dim = self.conv_layers_spec[-1][0]

    @staticmethod
    def _make_block(
        in_dim: int,
        out_dim: int,
        kernel: int,
        stride: int,
        dropout: float,
        mode: str,
        conv_bias: bool,
        depthwise: bool,
        is_first: bool,
    ) -> nn.Module:
        if depthwise:
            if out_dim % in_dim != 0:
                raise ValueError(
                    "Depthwise mode requires out_dim to be a multiple of in_dim, "
                    f"got out_dim={out_dim}, in_dim={in_dim}"
                )
            conv = nn.Conv1d(
                in_dim,
                out_dim,
                kernel_size=kernel,
                stride=stride,
                bias=conv_bias,
                groups=in_dim,
            )
        else:
            conv = nn.Conv1d(
                in_dim,
                out_dim,
                kernel_size=kernel,
                stride=stride,
                bias=conv_bias,
            )
        nn.init.kaiming_normal_(conv.weight)

        if mode == "layer_norm":
            return nn.Sequential(
                conv,
                nn.Dropout(p=dropout),
                Rearrange("... c t -> ... t c"),
                nn.LayerNorm(out_dim, elementwise_affine=True),
                Rearrange("... t c -> ... c t"),
                nn.GELU(),
            )

        if mode == "default" and is_first:
            return nn.Sequential(
                conv,
                nn.Dropout(p=dropout),
                nn.GroupNorm(out_dim, out_dim, affine=True),
                nn.GELU(),
            )

        return nn.Sequential(conv, nn.Dropout(p=dropout), nn.GELU())

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = self.cnn(x)
        return rearrange(x, "b f n -> b n f")

    def total_patches(self, time_samples: int) -> int:
        n = int(time_samples)
        for _, kernel, stride in self.conv_layers_spec:
            if n < kernel:
                return 0
            n = (n - kernel) // stride + 1
        return int(n)