m3l-toolkit 2026.10.0__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. m3l/__init__.py +3 -0
  2. m3l/audio/common/datasets/__init__.py +8 -0
  3. m3l/audio/common/datasets/cliplabeled_hdf5_dataset.py +45 -0
  4. m3l/audio/common/datasets/framelabeled_hdf5_dataset.py +47 -0
  5. m3l/audio/common/datasets/unlabeled_hdf5_dataset.py +43 -0
  6. m3l/audio/common/encoders/__init__.py +8 -0
  7. m3l/audio/common/encoders/beats.py +60 -0
  8. m3l/audio/common/encoders/cnn14.py +90 -0
  9. m3l/audio/common/encoders/dcase_crnn.py +102 -0
  10. m3l/audio/common/postprocessors/__init__.py +6 -0
  11. m3l/audio/common/postprocessors/median_filter.py +29 -0
  12. m3l/audio/common/preprocessors/__init__.py +26 -0
  13. m3l/audio/common/preprocessors/batch_normalize.py +26 -0
  14. m3l/audio/common/preprocessors/clamp.py +21 -0
  15. m3l/audio/common/preprocessors/gaussian_noise.py +28 -0
  16. m3l/audio/common/preprocessors/mixup.py +40 -0
  17. m3l/audio/common/preprocessors/normalize.py +37 -0
  18. m3l/audio/common/preprocessors/preprocessor.py +73 -0
  19. m3l/audio/common/preprocessors/scale.py +47 -0
  20. m3l/audio/common/preprocessors/spec_augment.py +24 -0
  21. m3l/audio/common/preprocessors/time_roll.py +31 -0
  22. m3l/audio/common/preprocessors/time_warp.py +36 -0
  23. m3l/audio/sed/callbacks/__init__.py +6 -0
  24. m3l/audio/sed/callbacks/visualizer.py +61 -0
  25. m3l/audio/sed/detect.py +69 -0
  26. m3l/audio/sed/heads/__init__.py +7 -0
  27. m3l/audio/sed/heads/attention_head.py +25 -0
  28. m3l/audio/sed/heads/linear_head.py +16 -0
  29. m3l/audio/sed/models/__init__.py +7 -0
  30. m3l/audio/sed/models/strong_model.py +29 -0
  31. m3l/audio/sed/models/strong_weak_model.py +43 -0
  32. m3l/audio/sed/tasks/__init__.py +7 -0
  33. m3l/audio/sed/tasks/sed_task.py +277 -0
  34. m3l/audio/sed/tasks/weak_ema_sed_task.py +166 -0
  35. m3l/audio/tagging/callbacks/__init__.py +6 -0
  36. m3l/audio/tagging/callbacks/visualizer.py +65 -0
  37. m3l/audio/tagging/models/__init__.py +7 -0
  38. m3l/audio/tagging/models/cnn14.py +92 -0
  39. m3l/audio/tagging/models/tagging_model.py +37 -0
  40. m3l/audio/tagging/tasks/tagging_task.py +137 -0
  41. m3l/audiotext/ov_sed/audio_backbone/cnn_beats_encoder.py +47 -0
  42. m3l/audiotext/ov_sed/gradio/_spaces.py +19 -0
  43. m3l/audiotext/ov_sed/gradio/_temporary_files.py +30 -0
  44. m3l/audiotext/ov_sed/gradio/_video.py +190 -0
  45. m3l/audiotext/ov_sed/gradio/config/default.yaml +91 -0
  46. m3l/audiotext/ov_sed/gradio/detect.py +241 -0
  47. m3l/audiotext/ov_sed/models/ovsed.py +147 -0
  48. m3l/audiotext/ov_sed/pipelines/detect.py +91 -0
  49. m3l/audiotext/ov_sed/tasks/doom_sed_task.py +180 -0
  50. m3l/audiotext/ov_sed/text_backbone/laion_clap_text_encoder.py +44 -0
  51. m3l/audiovisual/avc/callbacks/__init__.py +3 -0
  52. m3l/audiovisual/avc/tasks/__init__.py +6 -0
  53. m3l/audiovisual/avc/tasks/avc_task.py +119 -0
  54. m3l/audiovisual/common/datasets/__init__.py +6 -0
  55. m3l/audiovisual/common/datasets/unlabeled_hdf5_dataset.py +74 -0
  56. m3l/common/callbacks/__init__.py +7 -0
  57. m3l/common/callbacks/exponential_warmup_annealer.py +37 -0
  58. m3l/common/callbacks/visualizer.py +61 -0
  59. m3l/common/datamodules/__init__.py +7 -0
  60. m3l/common/datamodules/multi_datamodule.py +107 -0
  61. m3l/common/datamodules/single_datamodule.py +117 -0
  62. m3l/common/lr_schedulers/__init__.py +6 -0
  63. m3l/common/lr_schedulers/exponential_warmup.py +49 -0
  64. m3l/common/nn/__init__.py +46 -0
  65. m3l/common/nn/transformer.py +251 -0
  66. m3l/third/beats/BEATs.py +179 -0
  67. m3l/third/beats/LICENSE +21 -0
  68. m3l/third/beats/README.md +257 -0
  69. m3l/third/beats/Tokenizers.py +173 -0
  70. m3l/third/beats/backbone.py +783 -0
  71. m3l/third/beats/beats_README.md +127 -0
  72. m3l/third/beats/modules.py +219 -0
  73. m3l/third/beats/quantizer.py +215 -0
  74. m3l/utils/__init__.py +7 -0
  75. m3l/utils/balanced_sampler.py +62 -0
  76. m3l/utils/inference.py +68 -0
  77. m3l/utils/label_loader.py +18 -0
  78. m3l/visual/common/__init__.py +6 -0
  79. m3l/visual/common/encoders/__init__.py +8 -0
  80. m3l/visual/common/encoders/resnet50.py +48 -0
  81. m3l/visual/common/encoders/resnet50_multiscale.py +90 -0
  82. m3l/visual/common/encoders/vgglike8.py +59 -0
  83. m3l/visual/common/metrics/mean_ap.py +42 -0
  84. m3l/visual/common/nest_collator.py +58 -0
  85. m3l/visual/common/transforms/__init__.py +20 -0
  86. m3l/visual/common/transforms/compose.py +19 -0
  87. m3l/visual/common/transforms/convert_boundingboxes_format.py +29 -0
  88. m3l/visual/common/transforms/filter_crowd_boundingbox.py +35 -0
  89. m3l/visual/common/transforms/labels_getter.py +38 -0
  90. m3l/visual/common/transforms/normalize_boundingboxes.py +39 -0
  91. m3l/visual/common/transforms/random_choice.py +24 -0
  92. m3l/visual/common/transforms/range_random_crop.py +42 -0
  93. m3l_toolkit-2026.10.0.dist-info/METADATA +127 -0
  94. m3l_toolkit-2026.10.0.dist-info/RECORD +98 -0
  95. m3l_toolkit-2026.10.0.dist-info/WHEEL +5 -0
  96. m3l_toolkit-2026.10.0.dist-info/licenses/LICENSE +21 -0
  97. m3l_toolkit-2026.10.0.dist-info/licenses/LICENSE-BEATS +21 -0
  98. m3l_toolkit-2026.10.0.dist-info/licenses/LICENSE-PYTORCH +84 -0
m3l/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ # Copyright (C) 2025 National Institute of Advanced Industrial Science and Technology (AIST)
2
+ # SPDX-License-Identifier: MIT
3
+
@@ -0,0 +1,8 @@
1
+ # Copyright (C) 2025 National Institute of Advanced Industrial Science and Technology (AIST)
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ from m3l.audio.common.datasets.cliplabeled_hdf5_dataset import ClipLabeledHDF5Dataset
5
+ from m3l.audio.common.datasets.framelabeled_hdf5_dataset import FrameLabeledHDF5Dataset
6
+ from m3l.audio.common.datasets.unlabeled_hdf5_dataset import UnlabeledHDF5Dataset
7
+
8
+ __all__ = ["UnlabeledHDF5Dataset", "ClipLabeledHDF5Dataset", "FrameLabeledHDF5Dataset"]
@@ -0,0 +1,45 @@
1
+ # Copyright (C) 2025 National Institute of Advanced Industrial Science and Technology (AIST)
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ from pathlib import Path
5
+
6
+ import torch
7
+ from torch.utils.data import Dataset
8
+
9
+ from aiaccel.torch.datasets import CachedDataset, HDF5Dataset
10
+
11
+
12
+ class ClipLabeledHDF5Dataset(Dataset):
13
+ """
14
+ A PyTorch Dataset wrapper for loading audio clips and labels from an HDF5 file.
15
+
16
+ This dataset uses `HDF5Dataset` wrapped with `CachedDataset` to efficiently
17
+ access waveform tensors (`wav`) and their corresponding labels. Each item
18
+ also provides the group name from the original HDF5 dataset.
19
+
20
+ Args:
21
+ dataset_path (Path | str): Path to the HDF5 dataset file.
22
+ grp_list (Path | str | list[str] | None, optional):
23
+ A list of group names, a path to a file containing group names,
24
+ or `None` to use all groups. Defaults to None.
25
+
26
+ Returns:
27
+ tuple[torch.Tensor, torch.Tensor, str]:
28
+ - wav (torch.Tensor): The waveform tensor.
29
+ - label (torch.Tensor): The label tensor (float32).
30
+ - group_name (str): The group name corresponding to the sample.
31
+ """
32
+
33
+ def __init__(self, dataset_path: Path | str, grp_list: Path | str | list[str] | None = None) -> None:
34
+ self._dataset = CachedDataset(HDF5Dataset(dataset_path, grp_list))
35
+
36
+ def __len__(self):
37
+ return len(self._dataset)
38
+
39
+ def __getitem__(self, index: int) -> tuple[torch.Tensor, torch.Tensor, str]: # type: ignore
40
+ item = self._dataset[index]
41
+
42
+ wav = item["wav"]
43
+ label = item["label"].to(torch.float32)
44
+
45
+ return wav, label, self._dataset.dataset.grp_list[index]
@@ -0,0 +1,47 @@
1
+ # Copyright (C) 2025 National Institute of Advanced Industrial Science and Technology (AIST)
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ from pathlib import Path
5
+
6
+ import torch
7
+ from torch.utils.data import Dataset
8
+
9
+ from aiaccel.torch.datasets import CachedDataset, HDF5Dataset
10
+
11
+
12
+ class FrameLabeledHDF5Dataset(Dataset):
13
+ """
14
+ A PyTorch Dataset wrapper for loading frame-level labeled audio data
15
+ from an HDF5 file.
16
+
17
+ This dataset uses `HDF5Dataset` wrapped with `CachedDataset` to provide
18
+ efficient access to audio waveform tensors (`wav`) along with
19
+ frame-level labels. Each item also returns the group name from the
20
+ original HDF5 dataset.
21
+
22
+ Args:
23
+ dataset_path (Path | str): Path to the HDF5 dataset file.
24
+ grp_list (Path | str | list[str] | None, optional):
25
+ A list of group names, a path to a file containing group names,
26
+ or `None` to use all groups. Defaults to None.
27
+
28
+ Returns:
29
+ tuple[torch.Tensor, torch.Tensor, str]:
30
+ - wav (torch.Tensor): The waveform tensor.
31
+ - label (torch.Tensor): The frame-level label tensor (float32).
32
+ - group_name (str): The group name corresponding to the sample.
33
+ """
34
+
35
+ def __init__(self, dataset_path: Path | str, grp_list: Path | str | list[str] | None = None) -> None:
36
+ self._dataset = CachedDataset(HDF5Dataset(dataset_path, grp_list))
37
+
38
+ def __len__(self):
39
+ return len(self._dataset)
40
+
41
+ def __getitem__(self, index: int) -> tuple[torch.Tensor, torch.Tensor, str]: # type: ignore
42
+ item = self._dataset[index]
43
+
44
+ wav = item["wav"]
45
+ label = item["label"].to(torch.float32)
46
+
47
+ return wav, label, self._dataset.dataset.grp_list[index]
@@ -0,0 +1,43 @@
1
+ # Copyright (C) 2025 National Institute of Advanced Industrial Science and Technology (AIST)
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ from pathlib import Path
5
+
6
+ import torch
7
+ from torch.utils.data import Dataset
8
+
9
+ from aiaccel.torch.datasets import CachedDataset, HDF5Dataset
10
+
11
+
12
+ class UnlabeledHDF5Dataset(Dataset):
13
+ """
14
+ A PyTorch Dataset wrapper for loading unlabeled audio clips from an HDF5 file.
15
+
16
+ This dataset uses `HDF5Dataset` wrapped with `CachedDataset` to efficiently
17
+ access waveform tensors (`wav`). Unlike the labeled version, this class
18
+ does not return labels - only the waveform and the corresponding group name.
19
+
20
+ Args:
21
+ dataset_path (Path | str): Path to the HDF5 dataset file.
22
+ grp_list (Path | str | list[str] | None, optional):
23
+ A list of group names, a path to a file containing group names,
24
+ or `None` to use all groups. Defaults to None.
25
+
26
+ Returns:
27
+ tuple[torch.Tensor, str]:
28
+ - wav (torch.Tensor): The waveform tensor.
29
+ - group_name (str): The group name corresponding to the sample.
30
+ """
31
+
32
+ def __init__(self, dataset_path: Path | str, grp_list: Path | str | list[str] | None = None) -> None:
33
+ self._dataset = CachedDataset(HDF5Dataset(dataset_path, grp_list))
34
+
35
+ def __len__(self):
36
+ return len(self._dataset)
37
+
38
+ def __getitem__(self, index: int) -> tuple[torch.Tensor, str]: # type: ignore
39
+ item = self._dataset[index]
40
+
41
+ wav = item["wav"]
42
+
43
+ return wav, self._dataset.dataset.grp_list[index]
@@ -0,0 +1,8 @@
1
+ # Copyright (C) 2025 National Institute of Advanced Industrial Science and Technology (AIST)
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ from m3l.audio.common.encoders.beats import BEATsModel
5
+ from m3l.audio.common.encoders.cnn14 import CNN14
6
+ from m3l.audio.common.encoders.dcase_crnn import CRNN
7
+
8
+ __all__ = ["BEATsModel", "CNN14", "CRNN"]
@@ -0,0 +1,60 @@
1
+ # Copyright (C) 2025 National Institute of Advanced Industrial Science and Technology (AIST)
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ from pathlib import Path
5
+
6
+ import torch
7
+ from torch import nn
8
+ from torch.nn.utils import remove_weight_norm as _remove_weight_norm
9
+
10
+
11
+ class BEATsModel(nn.Module):
12
+ """
13
+ Wrapper class for the BEATs audio representation model.
14
+
15
+ This class loads a pretrained BEATs model for extracting features from raw audio waveforms.
16
+ """
17
+
18
+ def __init__(
19
+ self,
20
+ checkpoint_path: str | Path = "./3rd/unilm/beats/BEATs_iter3_plus_AS2M.pt",
21
+ freeze: bool = True,
22
+ overwrite_encoder_layerdrop: float | None = None,
23
+ remove_weight_norm: bool = False,
24
+ ):
25
+ """
26
+ Initializes the BEATs model with the specified configuration and checkpoint.
27
+
28
+ Args:
29
+ beats_path (str | Path): Path to the BEATs source directory.
30
+ checkpoint_path (str | Path): Path to the pretrained BEATs model checkpoint.
31
+ freeze (bool): Whether to freeze the pretrained model weights.
32
+ overwrite_encoder_layerdrop (float | None): Override value for the encoder layerdrop ratio.
33
+ remove_weight_norm (bool): Whether to remove weight normalization from the model.
34
+ """
35
+
36
+ super().__init__()
37
+ self.freeze = freeze
38
+
39
+ from m3l.third.beats.BEATs import BEATs, BEATsConfig
40
+
41
+ checkpoint = torch.load(checkpoint_path)
42
+
43
+ cfg = BEATsConfig(checkpoint["cfg"])
44
+
45
+ if overwrite_encoder_layerdrop is not None:
46
+ cfg.encoder_layerdrop = overwrite_encoder_layerdrop # override encoder layerdrop ratio
47
+
48
+ self.beats = BEATs(cfg) # .cuda()
49
+ self.beats.load_state_dict(checkpoint["model"])
50
+
51
+ if remove_weight_norm:
52
+ _remove_weight_norm(self.beats.encoder.pos_conv[0], name="weight")
53
+
54
+ if freeze:
55
+ for param in self.beats.parameters():
56
+ param.requires_grad = False
57
+
58
+ def forward(self, feats: dict[str, torch.Tensor]):
59
+ with torch.set_grad_enabled(torch.is_grad_enabled() and not self.freeze):
60
+ return self.beats.extract_features(feats["wav"])[0]
@@ -0,0 +1,90 @@
1
+ # Copyright (C) 2025 National Institute of Advanced Industrial Science and Technology (AIST)
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ from torch import nn
5
+ from torch.nn.common_types import _size_1_t, _size_2_t
6
+
7
+ from einops.layers.torch import Rearrange
8
+
9
+
10
+ class ConvBlock2d(nn.Sequential):
11
+ def __init__(
12
+ self,
13
+ in_channels: int,
14
+ out_channels: int,
15
+ kernel_size: _size_2_t,
16
+ pool_size: _size_2_t,
17
+ dropout: float,
18
+ ):
19
+ super().__init__(
20
+ nn.Conv2d(in_channels, out_channels, kernel_size, padding="same", bias=False),
21
+ nn.BatchNorm2d(out_channels),
22
+ nn.ReLU(),
23
+ nn.Conv2d(out_channels, out_channels, kernel_size, padding="same", bias=False),
24
+ nn.BatchNorm2d(out_channels),
25
+ nn.ReLU(),
26
+ nn.AvgPool2d(pool_size),
27
+ nn.Dropout(dropout),
28
+ )
29
+
30
+
31
+ class AvgMaxPool1d(nn.Module):
32
+ def __init__(
33
+ self,
34
+ kernel_size: _size_1_t,
35
+ stride: _size_1_t,
36
+ padding: _size_1_t = 0,
37
+ ):
38
+ super().__init__()
39
+
40
+ self.max_pool = nn.MaxPool1d(kernel_size, stride, padding)
41
+ self.avg_pool = nn.AvgPool1d(kernel_size, stride, padding)
42
+
43
+ def forward(self, x):
44
+ return self.max_pool(x) + self.avg_pool(x)
45
+
46
+
47
+ class CNN14(nn.Sequential):
48
+ """CNN14 model for audio feature extraction.
49
+
50
+ This model is based on the PANNs CNN14 architecture. It applies a series
51
+ of convolutional blocks followed by global pooling and a final 1D
52
+ convolution to produce latent representations of input spectrograms.
53
+
54
+ Args:
55
+ dim_latent (int, optional): Dimension of the latent feature space.
56
+ Defaults to 512.
57
+ dropout (float, optional): Dropout rate applied in intermediate layers.
58
+ Defaults to 0.2.
59
+ dropout_last (float, optional): Dropout rate applied before the final
60
+ projection layer. Defaults to 0.5.
61
+
62
+ Returns:
63
+ torch.Tensor: Latent feature tensor of shape ``[B, dim_latent, T]``.
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ dim_latent: int = 512,
69
+ dropout: float = 0.2,
70
+ dropout_last: float = 0.5,
71
+ ):
72
+ super().__init__()
73
+
74
+ self.cnn = nn.Sequential(
75
+ Rearrange("b f t -> b 1 f t"),
76
+ #
77
+ ConvBlock2d(1, ch := 64, 3, 2, dropout),
78
+ ConvBlock2d(ch, ch := 128, 3, 2, dropout),
79
+ ConvBlock2d(ch, ch := 256, 3, 2, dropout),
80
+ ConvBlock2d(ch, ch := 512, 3, 2, dropout),
81
+ ConvBlock2d(ch, ch := 1024, 3, 2, dropout),
82
+ ConvBlock2d(ch, ch := 2048, 3, 1, dropout),
83
+ #
84
+ nn.AdaptiveAvgPool2d((1, None)),
85
+ Rearrange("b c 1 t -> b c t"),
86
+ AvgMaxPool1d(3, 1, 1),
87
+ #
88
+ nn.Dropout(dropout_last),
89
+ nn.Conv1d(2048, dim_latent, 1),
90
+ )
@@ -0,0 +1,102 @@
1
+ # Copyright (C) 2025 National Institute of Advanced Industrial Science and Technology (AIST)
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ from einops import rearrange
5
+
6
+ import torch
7
+ from torch import nn
8
+ from torch.nn import functional as fn
9
+
10
+ from einops.layers.torch import Rearrange
11
+
12
+ from m3l.common.nn import SingleOutputGRU
13
+
14
+
15
+ class GLU(nn.Conv2d):
16
+ def __init__(self, io_channels: int):
17
+ super().__init__(io_channels, io_channels, 1)
18
+
19
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
20
+ return fn.sigmoid(input) * super().forward(input)
21
+
22
+
23
+ class Conv2dBlock(nn.Sequential):
24
+ def __init__(self, in_channels: int, out_channels: int, pool_size: tuple[int, int], dropout: float):
25
+ super().__init__(
26
+ nn.Conv2d(in_channels, out_channels, 3, padding="same"),
27
+ nn.BatchNorm2d(out_channels),
28
+ GLU(out_channels),
29
+ nn.Dropout(dropout),
30
+ nn.AvgPool2d(pool_size),
31
+ )
32
+
33
+
34
+ class CRNN(nn.Module):
35
+ """Convolutional Recurrent Neural Network (CRNN) for audio sequence modeling.
36
+
37
+ This model first applies a series of 2D convolutional blocks with gated
38
+ linear units (GLU) and pooling, followed by a recurrent GRU encoder to
39
+ capture temporal dependencies. Optionally, external embeddings can be
40
+ integrated into the convolutional features.
41
+
42
+ Args:
43
+ dropout (float, optional): Dropout probability applied after CNN and GRU layers.
44
+ Defaults to 0.5.
45
+ dropout_rnn (float, optional): Dropout probability applied within GRU layers.
46
+ Defaults to 0.0.
47
+ dim_emb (int | None, optional): Dimension of external embedding features.
48
+ If provided, embeddings are concatenated to convolutional features.
49
+ Defaults to None.
50
+ dropout_emb (float, optional): Dropout probability applied after embedding projection.
51
+ Defaults to 0.5.
52
+
53
+ Returns:
54
+ torch.Tensor: Encoded feature sequence of shape ``[B, C, T]``, where
55
+ ``B`` is the batch size, ``C`` is the channel dimension, and ``T`` is
56
+ the temporal length.
57
+ """
58
+
59
+ def __init__(
60
+ self,
61
+ dropout: float = 0.5,
62
+ dropout_rnn: float = 0.0,
63
+ dim_emb: int | None = None,
64
+ dropout_emb: float = 0.5,
65
+ ):
66
+ super().__init__()
67
+
68
+ self.cnn = nn.Sequential(
69
+ Rearrange("b (c f) t -> b c f t", c=1),
70
+ Conv2dBlock(1, 16, (2, 2), dropout), # F=64
71
+ Conv2dBlock(16, 32, (2, 2), dropout), # F=32
72
+ Conv2dBlock(32, 64, (2, 1), dropout), # F=16
73
+ Conv2dBlock(64, 128, (2, 1), dropout), # F=8
74
+ Conv2dBlock(128, 128, (2, 1), dropout), # F=4
75
+ Conv2dBlock(128, 128, (2, 1), dropout), # F=2
76
+ Conv2dBlock(128, 128, (2, 1), dropout), # F=1
77
+ Rearrange("b c 1 t -> b c t"),
78
+ )
79
+
80
+ self.dim_emb = dim_emb
81
+ if dim_emb is not None:
82
+ self.lin_emb = nn.Sequential(nn.Conv1d(128 + dim_emb, 128, 1), nn.Dropout(dropout_emb))
83
+
84
+ self.gru = nn.Sequential(
85
+ Rearrange("b c t -> b t c"),
86
+ SingleOutputGRU(128, 128, 2, batch_first=True, dropout=dropout_rnn, bidirectional=True),
87
+ Rearrange("b t c -> b c t"),
88
+ nn.Dropout(dropout),
89
+ )
90
+
91
+ def forward(self, feats: dict[str, torch.Tensor]) -> torch.Tensor:
92
+ h = self.cnn(feats["logx"])
93
+
94
+ if self.dim_emb is not None:
95
+ h_emb = rearrange(feats["emb"], "b t c -> b c t")
96
+ h_emb = fn.adaptive_avg_pool1d(h_emb, h.shape[-1]) # [B, C, T]
97
+
98
+ h = self.lin_emb(torch.concat((h, h_emb), dim=1))
99
+
100
+ h = self.gru(h)
101
+
102
+ return h
@@ -0,0 +1,6 @@
1
+ # Copyright (C) 2025 National Institute of Advanced Industrial Science and Technology (AIST)
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ from m3l.audio.common.postprocessors.median_filter import MedianFilter
5
+
6
+ __all__ = ["MedianFilter"]
@@ -0,0 +1,29 @@
1
+ # Copyright (C) 2025 National Institute of Advanced Industrial Science and Technology (AIST)
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ from torch import nn
5
+
6
+ from einops.layers.torch import Rearrange
7
+
8
+ from kornia.filters import MedianBlur
9
+
10
+
11
+ class MedianFilter(nn.Sequential):
12
+ """1D median filter for temporal signals.
13
+
14
+ This module applies a median blur along the temporal axis of the input
15
+ tensor. Internally, the input is reshaped to 2D to apply Kornia's
16
+ ``MedianBlur`` operation and then reshaped back.
17
+
18
+ Args:
19
+ filter_size (int): Size of the median filter kernel applied along
20
+ the temporal dimension.
21
+
22
+ Returns:
23
+ torch.Tensor: Filtered tensor of shape ``[B, C, T]``, where
24
+ ``B`` is the batch size, ``C`` is the channel dimension, and
25
+ ``T`` is the temporal length.
26
+ """
27
+
28
+ def __init__(self, filter_size: int):
29
+ super().__init__(Rearrange("b c t -> b c t 1"), MedianBlur((filter_size, 1)), Rearrange("b c t 1 -> b c t"))
@@ -0,0 +1,26 @@
1
+ # Copyright (C) 2025 National Institute of Advanced Industrial Science and Technology (AIST)
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ from m3l.audio.common.preprocessors.batch_normalize import BatchNormalize
5
+ from m3l.audio.common.preprocessors.clamp import Clamp
6
+ from m3l.audio.common.preprocessors.gaussian_noise import GaussianNoise
7
+ from m3l.audio.common.preprocessors.mixup import Mixup
8
+ from m3l.audio.common.preprocessors.normalize import Normalize
9
+ from m3l.audio.common.preprocessors.preprocessor import Preprocessor
10
+ from m3l.audio.common.preprocessors.scale import Scale
11
+ from m3l.audio.common.preprocessors.spec_augment import SpecAugment
12
+ from m3l.audio.common.preprocessors.time_roll import TimeRoll
13
+ from m3l.audio.common.preprocessors.time_warp import TimeWarp
14
+
15
+ __all__ = [
16
+ "BatchNormalize",
17
+ "Clamp",
18
+ "GaussianNoise",
19
+ "Mixup",
20
+ "Normalize",
21
+ "Preprocessor",
22
+ "Scale",
23
+ "SpecAugment",
24
+ "TimeRoll",
25
+ "TimeWarp",
26
+ ]
@@ -0,0 +1,26 @@
1
+ # Copyright (C) 2025 National Institute of Advanced Industrial Science and Technology (AIST)
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ import torch
5
+ from torch import nn
6
+
7
+
8
+ class BatchNormalize(nn.Module):
9
+ """Apply 1D batch normalization to the input tensor while keeping the label unchanged.
10
+
11
+ Args:
12
+ num_channels (int): Number of feature channels in the input tensor.
13
+
14
+ Returns:
15
+ tuple[torch.Tensor, torch.Tensor | None]:
16
+ - Normalized tensor with the same shape as the input.
17
+ - Unchanged label tensor (if provided).
18
+ """
19
+
20
+ def __init__(self, num_channels):
21
+ super().__init__()
22
+
23
+ self.bn = nn.BatchNorm1d(num_channels)
24
+
25
+ def forward(self, logx: torch.Tensor, y: torch.Tensor | None = None):
26
+ return self.bn(logx), y
@@ -0,0 +1,21 @@
1
+ # Copyright (C) 2025 National Institute of Advanced Industrial Science and Technology (AIST)
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ import torch
5
+ from torch import nn
6
+
7
+
8
+ class Clamp(nn.Module):
9
+ """
10
+ Clamp the values of the log-mel spectrogram to a specified range.
11
+
12
+ Args:
13
+ value (float): The value to clamp the log-mel spectrogram values to. Default is 6.
14
+ """
15
+
16
+ def __init__(self, value: float = 6):
17
+ super().__init__()
18
+ self.value = value
19
+
20
+ def forward(self, logx: torch.Tensor, y: torch.Tensor | None = None):
21
+ return logx.clip(-self.value, self.value), y
@@ -0,0 +1,28 @@
1
+ # Copyright (C) 2025 National Institute of Advanced Industrial Science and Technology (AIST)
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ import torch
5
+ from torch import nn
6
+
7
+
8
+ class GaussianNoise(nn.Module):
9
+ """
10
+ Add Gaussian noise to the log-mel spectrogram during training.
11
+
12
+ Args:
13
+ max_scale (float): Maximum scale of the Gaussian noise to be added. Default is 0.2.
14
+ """
15
+
16
+ def __init__(self, max_scale: float = 0.2):
17
+ super().__init__()
18
+
19
+ self.max_scale = max_scale
20
+
21
+ def forward(self, logx: torch.Tensor, y: torch.Tensor | None = None):
22
+ if self.training:
23
+ B, *shape_ = logx.shape
24
+
25
+ scale = self.max_scale * torch.rand([B] + [1] * len(shape_), device=logx.device)
26
+ logx = logx + scale * torch.randn(logx.shape, device=logx.device)
27
+
28
+ return logx, y
@@ -0,0 +1,40 @@
1
+ # Copyright (C) 2025 National Institute of Advanced Industrial Science and Technology (AIST)
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ import numpy as np
5
+
6
+ import torch
7
+ from torch import nn
8
+
9
+
10
+ class Mixup(nn.Module):
11
+ """
12
+ Mixup data augmentation for audio data.
13
+
14
+ Args:
15
+ beta (float): Beta parameter for the beta distribution used in mixup.
16
+ hard (bool): If True, use hard mixup (max of labels), otherwise use soft mixup (weighted average).
17
+ """
18
+
19
+ def __init__(self, beta: float = 0.2, hard: bool = False):
20
+ super().__init__()
21
+
22
+ self.beta = beta
23
+ self.hard = hard
24
+
25
+ def forward(self, x: torch.Tensor, y: torch.Tensor | None):
26
+ if self.training and np.random.random() > 0.5:
27
+ B, *_ = x.shape
28
+ assert B >= 2 and B % 2 == 0
29
+
30
+ perm = torch.arange(B).flip(-1)
31
+ lm = torch.from_numpy(np.random.beta(self.beta, self.beta, size=[B])).to(x)
32
+ x = torch.einsum("b,b...->b...", lm, x) + torch.einsum("b,b...->b...", 1 - lm, x[perm])
33
+
34
+ if y is not None:
35
+ if self.hard:
36
+ y = torch.maximum(y, y[perm])
37
+ else:
38
+ y = torch.einsum("b,b...->b...", lm, y) + torch.einsum("b,b...->b...", 1 - lm, y[perm])
39
+
40
+ return x, y
@@ -0,0 +1,37 @@
1
+ # Copyright (C) 2025 National Institute of Advanced Industrial Science and Technology (AIST)
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ import torch
5
+ from torch import nn
6
+
7
+
8
+ class Normalize(nn.Module):
9
+ """
10
+ Normalize the log-mel spectrogram using running mean and power.
11
+ Args:
12
+ num_channels (int): Number of channels in the log-mel spectrogram.
13
+ momentum (float): Momentum for updating running statistics. Default is 0.99.
14
+ """
15
+
16
+ def __init__(self, num_channels, momentum=0.99):
17
+ super().__init__()
18
+
19
+ self.momentum = momentum
20
+
21
+ self.register_buffer("running_mean", torch.zeros([1, num_channels, 1]))
22
+ self.register_buffer("running_power", torch.ones([1, num_channels, 1]))
23
+
24
+ def forward(self, logx: torch.Tensor, y: torch.Tensor | None = None):
25
+ if self.training:
26
+ mean_ = logx.mean(axis=(0, 2), keepdims=True).detach()
27
+ power_ = logx.square().mean(axis=(0, 2), keepdims=True).detach()
28
+
29
+ torch.distributed.all_reduce(mean_, torch.distributed.ReduceOp.AVG)
30
+ torch.distributed.all_reduce(power_, torch.distributed.ReduceOp.AVG)
31
+
32
+ self.running_mean = self.momentum * self.running_mean + (1 - self.momentum) * mean_
33
+ self.running_power = self.momentum * self.running_power + (1 - self.momentum) * power_
34
+
35
+ scale = (self.running_power - self.running_mean**2).clip(1e-6).sqrt()
36
+
37
+ return (logx - self.running_mean) / scale, y