File size: 8,993 Bytes
86dc2b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# 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 collections.abc import Sequence
from math import prod

import torch
import torch.nn as nn
from timm.layers import PatchEmbed as TimmPatchEmbed


def _is_power_of_two(value: int) -> bool:
    return value > 0 and value & (value - 1) == 0


def _build_hmlp_kernel_schedule(
    patch_size: tuple[int, int],
) -> tuple[tuple[int, int], ...]:
    """Build non-overlapping aggregation steps for one target patch.

    The paper starts from 4x4 subpatches and doubles both axes until reaching
    16x16. For rectangular patches, an axis stops growing once it reaches its
    target while the other axis keeps doubling.
    """
    patch_height, patch_width = patch_size
    if not _is_power_of_two(patch_height) or not _is_power_of_two(patch_width):
        raise ValueError(
            "hMLP patch dimensions must be powers of two so each axis can be "
            f"doubled exactly, got {patch_size}"
        )

    first_kernel = (min(4, patch_height), min(4, patch_width))
    schedule = [first_kernel]
    current_height, current_width = first_kernel

    while (current_height, current_width) != patch_size:
        kernel_height = 2 if current_height < patch_height else 1
        kernel_width = 2 if current_width < patch_width else 1
        schedule.append((kernel_height, kernel_width))
        current_height *= kernel_height
        current_width *= kernel_width

    return tuple(schedule)


def _resolve_hmlp_kernel_schedule(
    patch_size: tuple[int, int],
    kernel_schedule: Sequence[Sequence[int]] | None,
) -> tuple[tuple[int, int], ...]:
    if kernel_schedule is None:
        return _build_hmlp_kernel_schedule(patch_size)

    schedule: list[tuple[int, int]] = []
    for stage_index, stage in enumerate(kernel_schedule):
        try:
            stage_values = tuple(stage)
        except TypeError as error:
            raise ValueError(
                "Each hMLP stage must contain [kernel_height, kernel_width], "
                f"stage {stage_index} has {stage}"
            ) from error
        if len(stage_values) != 2:
            raise ValueError(
                "Each hMLP stage must contain [kernel_height, kernel_width], "
                f"stage {stage_index} has {stage}"
            )
        try:
            kernel_size = tuple(int(value) for value in stage_values)
        except (TypeError, ValueError) as error:
            raise ValueError(
                f"hMLP stage kernels must be integers, got {stage_values}"
            ) from error
        if any(
            isinstance(original, bool) or normalized != original
            for normalized, original in zip(kernel_size, stage_values)
        ):
            raise ValueError(f"hMLP stage kernels must be integers, got {stage_values}")
        if any(value <= 0 for value in kernel_size):
            raise ValueError(f"hMLP stage kernels must be positive, got {kernel_size}")
        schedule.append(kernel_size)

    if not schedule:
        raise ValueError("hMLP kernel_schedule must contain at least one stage")

    aggregated_patch_size = tuple(
        prod(kernel_size[axis] for kernel_size in schedule) for axis in range(2)
    )
    if aggregated_patch_size != patch_size:
        raise ValueError(
            "hMLP kernel_schedule stages must multiply to patch_size; "
            f"got {aggregated_patch_size} from {tuple(schedule)}, expected {patch_size}"
        )

    return tuple(schedule)


class HierarchicalMLPPatchEmbed(nn.Module):
    """hMLP patch stem with independent, hierarchical patch aggregation."""

    def __init__(
        self,
        img_size: tuple[int, int] = (128, 256),
        patch_size: tuple[int, int] = (16, 16),
        in_chans: int = 1,
        embed_dim: int = 768,
        bias: bool = True,
        kernel_schedule: Sequence[Sequence[int]] | None = None,
    ) -> None:
        super().__init__()
        self.img_size = tuple(img_size)
        self.patch_size = tuple(patch_size)
        self.in_chans = in_chans
        self.embed_dim = embed_dim
        self.bias = bias
        self.kernel_schedule = _resolve_hmlp_kernel_schedule(
            self.patch_size,
            kernel_schedule,
        )
        self.num_patches = (self.img_size[0] // self.patch_size[0]) * (
            self.img_size[1] // self.patch_size[1]
        )

        hidden_dim = max(1, embed_dim // 4)
        layers: list[nn.Module] = []
        input_dim = in_chans
        for stage_index, kernel_size in enumerate(self.kernel_schedule):
            is_last = stage_index == len(self.kernel_schedule) - 1
            output_dim = embed_dim if is_last else hidden_dim
            layers.extend(
                [
                    nn.Conv2d(
                        input_dim,
                        output_dim,
                        kernel_size=kernel_size,
                        stride=kernel_size,
                        bias=bias,
                    ),
                    nn.SyncBatchNorm(output_dim),
                ]
            )
            if not is_last:
                layers.append(nn.GELU())
            input_dim = output_dim

        self.proj = nn.Sequential(*layers)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        if x.ndim != 4:
            raise ValueError(f"Expected input with shape [B, C, H, W], got {x.shape}")
        if x.shape[1] != self.in_chans:
            raise ValueError(
                f"Expected {self.in_chans} input channels, got {x.shape[1]}"
            )
        if x.shape[2] % self.patch_size[0] != 0 or x.shape[3] % self.patch_size[1] != 0:
            raise ValueError(
                "Input spatial dimensions must be divisible by the hMLP patch "
                f"size {self.patch_size}, got {tuple(x.shape[2:])}"
            )

        return self.proj(x).flatten(2).transpose(1, 2)


class PatchEmbed(nn.Module):
    """
    2D Image to Patch Embedding.

    Args:
        img_size (tuple[int, int]): Input image size (H, W).
        patch_size (tuple[int, int]): Patch size (H, W).
        in_chans (int): Number of input channels.
        embed_dim (int): Embedding dimension.
    """

    def __init__(
        self,
        img_size: tuple[int, int] = (128, 256),
        patch_size: tuple[int, int] = (16, 16),
        in_chans: int = 1,
        embed_dim: int = 768,
        bias: bool = True,
        stem_type: str = "linear",
        hmlp_kernel_schedule: Sequence[Sequence[int]] | None = None,
    ):
        super().__init__()
        self.img_size = tuple(img_size)
        self.patch_size = tuple(patch_size)
        self.in_chans = in_chans
        self.embed_dim = embed_dim
        self.bias = bias
        self.stem_type = stem_type.strip().lower().replace("-", "_")

        if self.stem_type == "linear":
            self.patch_embed = TimmPatchEmbed(
                img_size=img_size,
                patch_size=patch_size,
                in_chans=in_chans,
                embed_dim=embed_dim,
                flatten=True,
                bias=bias,
                strict_img_size=False,
            )
        elif self.stem_type == "hmlp":
            self.patch_embed = HierarchicalMLPPatchEmbed(
                img_size=img_size,
                patch_size=patch_size,
                in_chans=in_chans,
                embed_dim=embed_dim,
                bias=bias,
                kernel_schedule=hmlp_kernel_schedule,
            )
        else:
            raise ValueError(
                f"Unknown stem_type={stem_type!r}; expected 'linear' or 'hmlp'"
            )
        self.num_patches = self.patch_embed.num_patches

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Forward pass.

        Args:
            x (torch.Tensor): Input tensor [B, C, H, W].

        Returns:
            torch.Tensor: Patch embeddings [B, N, D].
        """
        return self.patch_embed(x)