minicpc 0.1.0__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.
- minicpc/__init__.py +4 -0
- minicpc/__main__.py +64 -0
- minicpc/augmentation.py +46 -0
- minicpc/config.py +80 -0
- minicpc/convert.py +144 -0
- minicpc/data.py +234 -0
- minicpc/features.py +31 -0
- minicpc/ipl_index.jsonl.zst +0 -0
- minicpc/kernels.py +171 -0
- minicpc/loss.py +89 -0
- minicpc/model.py +287 -0
- minicpc/registry.py +214 -0
- minicpc/train.py +243 -0
- minicpc/utils.py +175 -0
- minicpc-0.1.0.dist-info/METADATA +16 -0
- minicpc-0.1.0.dist-info/RECORD +17 -0
- minicpc-0.1.0.dist-info/WHEEL +4 -0
minicpc/__init__.py
ADDED
minicpc/__main__.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
from importlib.metadata import version
|
|
3
|
+
|
|
4
|
+
from .config import read_config
|
|
5
|
+
from .features import extract_features
|
|
6
|
+
from .registry import fetch_pretrained, list_pretrained
|
|
7
|
+
from .train import train
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def list_models(pattern: str) -> None:
|
|
11
|
+
models = list_pretrained(pattern)
|
|
12
|
+
width = max(map(len, models), default=0)
|
|
13
|
+
for name, entry in models.items():
|
|
14
|
+
source = entry.url if entry.member is None else f"{entry.url} ({entry.member})"
|
|
15
|
+
print(f"{name:<{width}} {entry.description}\n{'':<{width}} {source}")
|
|
16
|
+
if pattern == "*":
|
|
17
|
+
print("\nModels of Poli et al. (2025), Modeling the initial state of early phonetic learning in infants:")
|
|
18
|
+
print("python -m minicpc list 'ipl:*'")
|
|
19
|
+
elif not models:
|
|
20
|
+
print(f"No model matches {pattern!r}")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def download_models(patterns: list[str], parser: argparse.ArgumentParser) -> None:
|
|
24
|
+
names = []
|
|
25
|
+
for pattern in patterns:
|
|
26
|
+
if not (models := list_pretrained(pattern)):
|
|
27
|
+
parser.error(f"no model matches {pattern!r} (see `python -m minicpc list`)")
|
|
28
|
+
names += models
|
|
29
|
+
for name in dict.fromkeys(names):
|
|
30
|
+
print(f"{name}\t{fetch_pretrained(name)}")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def main() -> None:
|
|
34
|
+
parser = argparse.ArgumentParser(description="Minimal implementation of CPC training")
|
|
35
|
+
parser.add_argument("-V", "--version", action="version", version=version("minicpc"), help="show the version")
|
|
36
|
+
subparsers = parser.add_subparsers(dest="command", help="command to run")
|
|
37
|
+
train_parser = subparsers.add_parser("train", description="Train a CPC model")
|
|
38
|
+
train_parser.add_argument("config", type=str, help="path to the TOML training configuration")
|
|
39
|
+
extract_parser = subparsers.add_parser("extract", description="Extract features with a pretrained CPC model")
|
|
40
|
+
extract_parser.add_argument("model", type=str, help="path, URL or name (see `list`) of the model checkpoint")
|
|
41
|
+
extract_parser.add_argument("manifest", type=str, help="path to the manifest file (CSV or JSONL)")
|
|
42
|
+
extract_parser.add_argument("output", type=str, help="path to the output directory")
|
|
43
|
+
list_parser = subparsers.add_parser("list", description="List the pretrained models")
|
|
44
|
+
list_parser.add_argument("pattern", nargs="?", default="*", help="shell-style pattern, e.g. 'ipl:scratch_eng-*'")
|
|
45
|
+
download_parser = subparsers.add_parser(
|
|
46
|
+
"download", description="Download pretrained models into the torch.hub cache, and print their paths"
|
|
47
|
+
)
|
|
48
|
+
download_parser.add_argument("patterns", nargs="+", help="model names or shell-style patterns (see `list`)")
|
|
49
|
+
args = parser.parse_args()
|
|
50
|
+
|
|
51
|
+
if args.command == "train":
|
|
52
|
+
train(read_config(args.config))
|
|
53
|
+
elif args.command == "extract":
|
|
54
|
+
extract_features(args.model, args.manifest, args.output)
|
|
55
|
+
elif args.command == "list":
|
|
56
|
+
list_models(args.pattern)
|
|
57
|
+
elif args.command == "download":
|
|
58
|
+
download_models(args.patterns, download_parser)
|
|
59
|
+
else:
|
|
60
|
+
parser.print_help()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
if __name__ == "__main__":
|
|
64
|
+
main()
|
minicpc/augmentation.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
from sox_effects import EffectChain
|
|
3
|
+
from torch import Tensor
|
|
4
|
+
from torch.nn import functional as F
|
|
5
|
+
|
|
6
|
+
__all__ = ["PitchReverbAugment"]
|
|
7
|
+
|
|
8
|
+
SAMPLE_RATE = 16_000
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def forced_length(waveform: Tensor, num_samples: int) -> Tensor:
|
|
12
|
+
return F.pad(waveform[:, :num_samples], (0, max(0, num_samples - waveform.shape[1])))
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class PitchReverbAugment:
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
*,
|
|
19
|
+
max_pitch_shift: int = 300,
|
|
20
|
+
max_room_scale: int = 100,
|
|
21
|
+
reverberance: int = 100,
|
|
22
|
+
high_frequency_damping: int = 100,
|
|
23
|
+
) -> None:
|
|
24
|
+
self.max_pitch_shift = max_pitch_shift
|
|
25
|
+
self.max_room_scale = max_room_scale
|
|
26
|
+
self.reverberance = reverberance
|
|
27
|
+
self.high_frequency_damping = high_frequency_damping
|
|
28
|
+
|
|
29
|
+
def sample_parameters(self, generator: torch.Generator) -> tuple[int, int]:
|
|
30
|
+
cents = torch.randint(-self.max_pitch_shift, self.max_pitch_shift, (), generator=generator)
|
|
31
|
+
room_scale = torch.randint(0, self.max_room_scale, (), generator=generator)
|
|
32
|
+
return int(cents), int(room_scale)
|
|
33
|
+
|
|
34
|
+
def chains(self, cents: int, room_scale: int) -> tuple[EffectChain, EffectChain]:
|
|
35
|
+
pitch = EffectChain().pitch(cents).rate(SAMPLE_RATE)
|
|
36
|
+
reverb = EffectChain().reverb(self.reverberance, self.high_frequency_damping, room_scale).channels(1)
|
|
37
|
+
return pitch, reverb
|
|
38
|
+
|
|
39
|
+
def __call__(self, waveform: Tensor, generator: torch.Generator) -> Tensor:
|
|
40
|
+
if waveform.ndim != 2 or waveform.shape[0] != 1:
|
|
41
|
+
raise ValueError(f"Expected a mono waveform of shape (1, num_samples), got {tuple(waveform.shape)}")
|
|
42
|
+
num_samples = waveform.shape[1]
|
|
43
|
+
waveform = waveform.float()
|
|
44
|
+
for chain in self.chains(*self.sample_parameters(generator)):
|
|
45
|
+
waveform = forced_length(chain.apply(waveform, SAMPLE_RATE)[0], num_samples)
|
|
46
|
+
return waveform
|
minicpc/config.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import dataclasses
|
|
2
|
+
import tomllib
|
|
3
|
+
from os import PathLike
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Literal
|
|
6
|
+
|
|
7
|
+
__all__ = ["CONFIG_FILE", "CPCConfig", "Config", "read_config"]
|
|
8
|
+
|
|
9
|
+
CONFIG_FILE = "config.json"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclasses.dataclass(frozen=True)
|
|
13
|
+
class CPCConfig:
|
|
14
|
+
"""Architecture of `CPC`. Defaults follow the CPC3 recipe (2-layer LSTM, multihead predictor)."""
|
|
15
|
+
|
|
16
|
+
hidden_size: int = 256
|
|
17
|
+
window_size: int = 20480
|
|
18
|
+
num_predictions: int = 12
|
|
19
|
+
num_lstm_layers: int = 2
|
|
20
|
+
predictor_ffn_dim: int = 2048
|
|
21
|
+
predictor_num_heads: int = 8
|
|
22
|
+
predictor_dropout: float = 0.1 # In the attention and feed-forward layers of the predictor
|
|
23
|
+
predictor_output_dropout: float = 0.0 # On the predictions (CPC3 `--dropout`: 0.5)
|
|
24
|
+
|
|
25
|
+
@classmethod
|
|
26
|
+
def from_dict(cls, data: dict[str, Any]) -> "CPCConfig":
|
|
27
|
+
"""Model configuration from a full training configuration (with a "model" entry) or a bare model one."""
|
|
28
|
+
return cls(**data.get("model", data))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclasses.dataclass(frozen=True)
|
|
32
|
+
class Config:
|
|
33
|
+
run_dir: str
|
|
34
|
+
train_manifest: str
|
|
35
|
+
val_manifest: str
|
|
36
|
+
seed: int = 1234
|
|
37
|
+
model: CPCConfig = dataclasses.field(default_factory=CPCConfig)
|
|
38
|
+
|
|
39
|
+
# Loss
|
|
40
|
+
num_negatives: int = 128
|
|
41
|
+
group_size: int = 8 # Windows of one speaker that draw their negatives among themselves
|
|
42
|
+
|
|
43
|
+
# Optimization
|
|
44
|
+
learning_rate: float = 2e-4
|
|
45
|
+
lr_warmup_epochs: int = 10 # LR is multiplied by min(1, (epoch + 1) / lr_warmup_epochs), as in CPC3
|
|
46
|
+
batch_size: int = 64 # Global: split evenly over the GPUs with DDP
|
|
47
|
+
num_epochs: int = 200
|
|
48
|
+
|
|
49
|
+
# Speed (CUDA only, ignored on CPU)
|
|
50
|
+
precision: Literal["auto", "bf16", "fp16", "fp32"] = "auto"
|
|
51
|
+
compile: bool = True
|
|
52
|
+
|
|
53
|
+
# Data
|
|
54
|
+
augment_past: bool = False
|
|
55
|
+
random_offset: bool = True # Shift all training windows by a random offset in [0, window_size // 2] each epoch
|
|
56
|
+
num_workers: int = 8
|
|
57
|
+
|
|
58
|
+
# Logging and checkpointing
|
|
59
|
+
log_interval_steps: int = 1000
|
|
60
|
+
save_interval_steps: int = 5000
|
|
61
|
+
val_interval_epochs: int = 5
|
|
62
|
+
profile_at_step: int = 1000 # Chrome trace of a few steps from this one
|
|
63
|
+
|
|
64
|
+
def __post_init__(self) -> None:
|
|
65
|
+
if self.precision not in {"auto", "bf16", "fp16", "fp32"}:
|
|
66
|
+
raise ValueError(f"precision must be auto, bf16, fp16 or fp32, got {self.precision!r}")
|
|
67
|
+
if self.group_size < 1 or self.batch_size % self.group_size:
|
|
68
|
+
raise ValueError(f"group_size must divide batch_size ({self.batch_size}), got {self.group_size}")
|
|
69
|
+
if self.val_interval_epochs < 1:
|
|
70
|
+
raise ValueError(f"val_interval_epochs must be >= 1, got {self.val_interval_epochs}")
|
|
71
|
+
|
|
72
|
+
@classmethod
|
|
73
|
+
def from_dict(cls, data: dict[str, Any]) -> "Config":
|
|
74
|
+
data = data | {"model": CPCConfig(**data.get("model", {}))}
|
|
75
|
+
return cls(**data)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def read_config(path: str | PathLike) -> Config:
|
|
79
|
+
"""Read a TOML training configuration. The model configuration is in the optional `[model]` table."""
|
|
80
|
+
return Config.from_dict(tomllib.loads(Path(path).read_text(encoding="utf-8")))
|
minicpc/convert.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Conversion of CPC3 checkpoints (https://github.com/bootphon/CPC3) to minicpc.
|
|
2
|
+
|
|
3
|
+
Two layouts are supported:
|
|
4
|
+
- CPC3 training checkpoints `checkpoint_{epoch}.pt`: {"gEncoder", "cpcCriterion", "optimizer", "best"},
|
|
5
|
+
with the configuration in `checkpoint_args.json` in the same directory.
|
|
6
|
+
- Older CPC_audio / libri-light checkpoints: {"weights", "config"}. They have no prediction network.
|
|
7
|
+
|
|
8
|
+
Checkpoints from before CPC3 commit 7866bb0 (Oct 2020, e.g. the ZeroSpeech 2021 baselines) have no `last_linear` layer
|
|
9
|
+
in the predictor: it computed `LayerNorm(x + y)` instead of `LayerNorm(last_linear(x + y))`. The layer is then set to
|
|
10
|
+
the identity, which gives exactly the same predictions.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from collections.abc import Mapping
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
import torch
|
|
17
|
+
from torch import Tensor
|
|
18
|
+
|
|
19
|
+
__all__ = ["CPC3_ARGS_FILE", "cpc3_config", "cpc3_to_state_dict", "is_cpc3_checkpoint"]
|
|
20
|
+
|
|
21
|
+
CPC3_ARGS_FILE = "checkpoint_args.json"
|
|
22
|
+
|
|
23
|
+
# CPC3 defaults (cpc/cpc_default_config.py) for the options that change the architecture.
|
|
24
|
+
_CPC3_DEFAULTS = {
|
|
25
|
+
"hiddenEncoder": 256,
|
|
26
|
+
"hiddenGar": 256,
|
|
27
|
+
"nPredicts": 12,
|
|
28
|
+
"sizeWindow": 20480,
|
|
29
|
+
"nLevelsGRU": 1,
|
|
30
|
+
"arMode": "LSTM",
|
|
31
|
+
"normMode": "layerNorm",
|
|
32
|
+
"encoder_type": "cpc",
|
|
33
|
+
"cpc_mode": None,
|
|
34
|
+
"rnnMode": "transformer",
|
|
35
|
+
"multihead_rnn": False,
|
|
36
|
+
"abspos": False,
|
|
37
|
+
"dropout": False,
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
_PREDICTOR_RENAMES = {
|
|
41
|
+
"multihead.Wo.weight": "multihead.proj.weight",
|
|
42
|
+
"multihead.Att.Krelpos": "multihead.relpos",
|
|
43
|
+
"ffnetwork.lin1.weight": "fully_connected.0.weight",
|
|
44
|
+
"ffnetwork.lin1.bias": "fully_connected.0.bias",
|
|
45
|
+
"ffnetwork.lin2.weight": "fully_connected.3.weight",
|
|
46
|
+
"ffnetwork.lin2.bias": "fully_connected.3.bias",
|
|
47
|
+
"ln_ffnetwork.weight": "ln_fully_connected.weight",
|
|
48
|
+
"ln_ffnetwork.bias": "ln_fully_connected.bias",
|
|
49
|
+
"ln_multihead.weight": "ln_multihead.weight",
|
|
50
|
+
"ln_multihead.bias": "ln_multihead.bias",
|
|
51
|
+
"last_linear.weight": "last_linear.weight",
|
|
52
|
+
"last_linear.bias": "last_linear.bias",
|
|
53
|
+
}
|
|
54
|
+
_PREDICTOR_DROPPED = {"multihead.Att.mask", "multihead.Att.z"} # Constant buffers
|
|
55
|
+
_MODEL_DROPPED = {"mask_emb"}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class UnsupportedCPC3CheckpointError(ValueError):
|
|
59
|
+
pass
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def is_cpc3_checkpoint(checkpoint: Mapping[str, Any]) -> bool:
|
|
63
|
+
return "gEncoder" in checkpoint or ("weights" in checkpoint and "config" in checkpoint)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _strip_module_prefix(state_dict: Mapping[str, Tensor]) -> dict[str, Tensor]:
|
|
67
|
+
return {key.removeprefix("module."): value for key, value in state_dict.items()}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def cpc3_config(args: Mapping[str, Any], *, with_predictor: bool = True) -> dict[str, Any]:
|
|
71
|
+
"""Map CPC3 arguments to `CPC` keyword arguments. Raise if the architecture is not supported."""
|
|
72
|
+
args = _CPC3_DEFAULTS | dict(args)
|
|
73
|
+
expected: dict[str, str | bool] = {"arMode": "LSTM", "normMode": "layerNorm", "encoder_type": "cpc"}
|
|
74
|
+
if with_predictor:
|
|
75
|
+
expected |= {"rnnMode": "transformer", "multihead_rnn": True, "abspos": False}
|
|
76
|
+
errors = [f"{key}={args[key]!r} (expected {value!r})" for key, value in expected.items() if args[key] != value]
|
|
77
|
+
if args["cpc_mode"] not in (None, "none"):
|
|
78
|
+
errors.append(f"cpc_mode={args['cpc_mode']!r} (expected None)")
|
|
79
|
+
if args["hiddenEncoder"] != args["hiddenGar"]:
|
|
80
|
+
errors.append(f"hiddenEncoder={args['hiddenEncoder']} != hiddenGar={args['hiddenGar']}")
|
|
81
|
+
if errors:
|
|
82
|
+
raise UnsupportedCPC3CheckpointError("Unsupported CPC3 architecture: " + ", ".join(errors))
|
|
83
|
+
return {
|
|
84
|
+
"hidden_size": args["hiddenEncoder"],
|
|
85
|
+
"window_size": args["sizeWindow"],
|
|
86
|
+
"num_predictions": args["nPredicts"],
|
|
87
|
+
"num_lstm_layers": args["nLevelsGRU"],
|
|
88
|
+
"predictor_output_dropout": 0.5 if bool(args["dropout"]) else 0.0,
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _convert_model(model: Mapping[str, Tensor]) -> dict[str, Tensor]:
|
|
93
|
+
state_dict = {}
|
|
94
|
+
for key, value in _strip_module_prefix(model).items():
|
|
95
|
+
if key.startswith("gEncoder.conv"):
|
|
96
|
+
index, name = key.removeprefix("gEncoder.conv").split(".", 1)
|
|
97
|
+
state_dict[f"encoder.{index}.conv.{name}"] = value
|
|
98
|
+
elif key.startswith("gEncoder.batchNorm"):
|
|
99
|
+
index, name = key.removeprefix("gEncoder.batchNorm").split(".", 1)
|
|
100
|
+
state_dict[f"encoder.{index}.norm.{name}"] = value.reshape(-1)
|
|
101
|
+
elif key.startswith("gAR.baseNet."):
|
|
102
|
+
state_dict["auto_regressive." + key.removeprefix("gAR.baseNet.")] = value
|
|
103
|
+
elif key not in _MODEL_DROPPED:
|
|
104
|
+
msg = f"Unexpected key in CPC3 model: {key}"
|
|
105
|
+
raise UnsupportedCPC3CheckpointError(msg)
|
|
106
|
+
return state_dict
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _convert_predictor(criterion: Mapping[str, Tensor]) -> dict[str, Tensor]:
|
|
110
|
+
prefix = "wPrediction.predictor.0."
|
|
111
|
+
criterion = _strip_module_prefix(criterion)
|
|
112
|
+
predictor = {key.removeprefix(prefix): value for key, value in criterion.items() if key.startswith(prefix)}
|
|
113
|
+
if len(predictor) != len(criterion):
|
|
114
|
+
others = sorted(key for key in criterion if not key.startswith(prefix))
|
|
115
|
+
msg = f"Unexpected keys in CPC3 criterion (expected a single-layer multihead transformer): {others}"
|
|
116
|
+
raise UnsupportedCPC3CheckpointError(msg)
|
|
117
|
+
qkv = [predictor.pop(f"multihead.W{name}.weight") for name in "qkv"]
|
|
118
|
+
state_dict = {"predictor.multihead.qkv.weight": torch.cat(qkv, dim=0)}
|
|
119
|
+
for key, value in predictor.items():
|
|
120
|
+
if key in _PREDICTOR_DROPPED:
|
|
121
|
+
continue
|
|
122
|
+
if key not in _PREDICTOR_RENAMES:
|
|
123
|
+
msg = f"Unexpected key in CPC3 predictor: {key}"
|
|
124
|
+
raise UnsupportedCPC3CheckpointError(msg)
|
|
125
|
+
state_dict["predictor." + _PREDICTOR_RENAMES[key]] = value
|
|
126
|
+
if "last_linear.weight" not in predictor and "last_linear.bias" not in predictor: # Before CPC3 7866bb0
|
|
127
|
+
norm = predictor["ln_ffnetwork.weight"]
|
|
128
|
+
state_dict["predictor.last_linear.weight"] = torch.eye(norm.shape[0], dtype=norm.dtype)
|
|
129
|
+
state_dict["predictor.last_linear.bias"] = torch.zeros_like(norm)
|
|
130
|
+
return state_dict
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def cpc3_to_state_dict(checkpoint: Mapping[str, Any]) -> dict[str, Tensor]:
|
|
134
|
+
"""Convert a loaded CPC3 checkpoint to a minicpc `CPC` state dict.
|
|
135
|
+
|
|
136
|
+
The prediction network is converted only if the checkpoint has one ("cpcCriterion").
|
|
137
|
+
"""
|
|
138
|
+
if not is_cpc3_checkpoint(checkpoint):
|
|
139
|
+
msg = "Not a CPC3 checkpoint: no 'gEncoder' or 'weights' entry"
|
|
140
|
+
raise UnsupportedCPC3CheckpointError(msg)
|
|
141
|
+
state_dict = _convert_model(checkpoint["gEncoder"] if "gEncoder" in checkpoint else checkpoint["weights"])
|
|
142
|
+
if "cpcCriterion" in checkpoint:
|
|
143
|
+
state_dict |= _convert_predictor(checkpoint["cpcCriterion"])
|
|
144
|
+
return state_dict
|
minicpc/data.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
from collections.abc import Callable, Iterator
|
|
2
|
+
from itertools import chain
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Literal, NotRequired, TypedDict
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import polars as pl
|
|
8
|
+
import torch
|
|
9
|
+
from more_itertools import chunked
|
|
10
|
+
from torch import Tensor
|
|
11
|
+
from torch.utils.data import DataLoader, Dataset, Sampler
|
|
12
|
+
from torchcodec.decoders import AudioDecoder, WavDecoder
|
|
13
|
+
|
|
14
|
+
from .augmentation import SAMPLE_RATE, PitchReverbAugment
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"AudioWindowDataset",
|
|
18
|
+
"SameSpeakerBatchSampler",
|
|
19
|
+
"SequentialBatchSampler",
|
|
20
|
+
"build_dataloader",
|
|
21
|
+
"load_audio",
|
|
22
|
+
"num_samples",
|
|
23
|
+
"read_manifest",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
type Transform = Callable[[Tensor, torch.Generator], Tensor]
|
|
27
|
+
type WindowKey = tuple[int, int, int] # (file index, offset in samples, augmentation seed)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class AudioFile(TypedDict):
|
|
31
|
+
fileid: str
|
|
32
|
+
path: str
|
|
33
|
+
num_samples: int
|
|
34
|
+
speaker: NotRequired[str] # Needed for training (same-speaker batches) only
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class InvalidAudioError(ValueError):
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _decoder(path: str | Path) -> AudioDecoder | WavDecoder:
|
|
42
|
+
return WavDecoder(path) if Path(path).suffix.lower() == ".wav" else AudioDecoder(path)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def num_samples(path: str | Path) -> int:
|
|
46
|
+
metadata = _decoder(path).metadata
|
|
47
|
+
if metadata.duration_seconds_from_header is None or metadata.sample_rate is None:
|
|
48
|
+
return _decoder(path).get_all_samples().data.shape[1]
|
|
49
|
+
return round(metadata.duration_seconds_from_header * metadata.sample_rate)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def load_audio(path: str | Path, offset: int = 0, num_samples: int | None = None) -> Tensor:
|
|
53
|
+
decoder = _decoder(path)
|
|
54
|
+
if decoder.metadata.sample_rate != SAMPLE_RATE or decoder.metadata.num_channels != 1:
|
|
55
|
+
raise InvalidAudioError(f"Expected mono {SAMPLE_RATE} Hz audio: {path}")
|
|
56
|
+
stop = None if num_samples is None else (offset + num_samples) / SAMPLE_RATE
|
|
57
|
+
waveform = decoder.get_samples_played_in_range(offset / SAMPLE_RATE, stop).data
|
|
58
|
+
if num_samples is not None and waveform.shape[1] != num_samples:
|
|
59
|
+
raise InvalidAudioError(f"Expected {num_samples} samples at offset {offset}, got {waveform.shape[1]}: {path}")
|
|
60
|
+
return waveform
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def read_manifest(manifest_path: str | Path) -> list[AudioFile]:
|
|
64
|
+
path = Path(manifest_path)
|
|
65
|
+
if path.suffix == ".csv":
|
|
66
|
+
manifest = pl.read_csv(path, schema_overrides={"fileid": pl.Utf8, "speaker": pl.Utf8})
|
|
67
|
+
elif path.suffix == ".jsonl":
|
|
68
|
+
manifest = pl.read_ndjson(path)
|
|
69
|
+
else:
|
|
70
|
+
raise ValueError(f"Manifest must be a .csv or .jsonl file: {path}")
|
|
71
|
+
if "num_frames" in manifest.columns:
|
|
72
|
+
if "num_samples" in manifest.columns and not manifest["num_frames"].equals(manifest["num_samples"]):
|
|
73
|
+
raise ValueError(f"Columns num_samples and num_frames disagree in {path}")
|
|
74
|
+
manifest = manifest.drop("num_samples", strict=False).rename({"num_frames": "num_samples"})
|
|
75
|
+
if missing := {"fileid", "path", "num_samples"} - set(manifest.columns):
|
|
76
|
+
raise ValueError(f"Missing columns {sorted(missing)} in manifest {path}")
|
|
77
|
+
if manifest["fileid"].n_unique() != len(manifest):
|
|
78
|
+
raise ValueError(f"Duplicate file identifier in {path}")
|
|
79
|
+
names = ["fileid", "path"] + (["speaker"] if "speaker" in manifest.columns else [])
|
|
80
|
+
return manifest.select(pl.col(names).cast(pl.Utf8), pl.col("num_samples").cast(pl.Int64)).to_dicts() # ty: ignore[invalid-explicit-return]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def window_offsets(num_samples: int, window_size: int, offset: int = 0) -> range:
|
|
84
|
+
return range(offset, num_samples - window_size + 1, window_size)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class AudioWindowDataset(Dataset):
|
|
88
|
+
def __init__(self, files: list[AudioFile], window_size: int, transform: Transform | None = None) -> None:
|
|
89
|
+
super().__init__()
|
|
90
|
+
self.files = files
|
|
91
|
+
self.window_size = window_size
|
|
92
|
+
self.transform = transform
|
|
93
|
+
|
|
94
|
+
def __getitem__(self, key: WindowKey) -> tuple[Tensor, ...]: # ty: ignore[lost-keyword-for-regular-parameter]
|
|
95
|
+
file_index, offset, seed = key
|
|
96
|
+
waveform = load_audio(self.files[file_index]["path"], offset, self.window_size)
|
|
97
|
+
if self.transform is None:
|
|
98
|
+
return (waveform,)
|
|
99
|
+
return self.transform(waveform, torch.Generator().manual_seed(seed)), waveform
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def local_batch_size(batch_size: int, world_size: int) -> int:
|
|
103
|
+
if batch_size % world_size:
|
|
104
|
+
raise ValueError(f"Batch size {batch_size} is not divisible by the number of processes {world_size}")
|
|
105
|
+
return batch_size // world_size
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class SameSpeakerBatchSampler(Sampler[list[WindowKey]]):
|
|
109
|
+
def __init__(
|
|
110
|
+
self,
|
|
111
|
+
files: list[AudioFile],
|
|
112
|
+
batch_size: int,
|
|
113
|
+
window_size: int,
|
|
114
|
+
seed: int,
|
|
115
|
+
max_offset: int,
|
|
116
|
+
*,
|
|
117
|
+
group_size: int,
|
|
118
|
+
rank: int = 0,
|
|
119
|
+
world_size: int = 1,
|
|
120
|
+
) -> None:
|
|
121
|
+
self.files = files
|
|
122
|
+
self.batch_size = batch_size
|
|
123
|
+
self.window_size = window_size
|
|
124
|
+
self.seed = seed
|
|
125
|
+
self.max_offset = max_offset
|
|
126
|
+
local_size = local_batch_size(batch_size, world_size)
|
|
127
|
+
self.group_size = group_size
|
|
128
|
+
if local_size % group_size:
|
|
129
|
+
raise ValueError(f"Batch size per process {local_size} is not a multiple of the group size {group_size}")
|
|
130
|
+
self.local_slice = slice(rank * local_size, (rank + 1) * local_size)
|
|
131
|
+
if any("speaker" not in file for file in files):
|
|
132
|
+
raise ValueError("Same-speaker batches need a speaker column in the training manifest")
|
|
133
|
+
self.speaker_to_files: dict[str, list[int]] = {}
|
|
134
|
+
for index, file in enumerate(files):
|
|
135
|
+
self.speaker_to_files.setdefault(file["speaker"], []).append(index)
|
|
136
|
+
self.set_epoch(0)
|
|
137
|
+
|
|
138
|
+
def set_epoch(self, epoch: int, start: int = 0) -> None:
|
|
139
|
+
"""Same global batches in every process: they only depend on (seed, epoch)."""
|
|
140
|
+
self.start = start
|
|
141
|
+
rng = np.random.default_rng((self.seed, epoch))
|
|
142
|
+
offset = int(rng.integers(0, self.max_offset, endpoint=True))
|
|
143
|
+
groups = []
|
|
144
|
+
for file_indices in self.speaker_to_files.values():
|
|
145
|
+
windows = [
|
|
146
|
+
(index, start)
|
|
147
|
+
for index in file_indices
|
|
148
|
+
for start in window_offsets(self.files[index]["num_samples"], self.window_size, offset)
|
|
149
|
+
]
|
|
150
|
+
rng.shuffle(windows)
|
|
151
|
+
groups += [group for group in chunked(windows, self.group_size) if len(group) == self.group_size]
|
|
152
|
+
rng.shuffle(groups)
|
|
153
|
+
num_groups = self.batch_size // self.group_size
|
|
154
|
+
batches = [list(chain(*batch)) for batch in chunked(groups, num_groups) if len(batch) == num_groups]
|
|
155
|
+
seeds = rng.integers(0, 2**63, size=(len(batches), self.batch_size))
|
|
156
|
+
local = self.local_slice
|
|
157
|
+
self.batches = [
|
|
158
|
+
[(index, start, int(seed)) for (index, start), seed in zip(batch[local], batch_seeds[local], strict=True)] # ty: ignore[invalid-argument-type]
|
|
159
|
+
for batch, batch_seeds in zip(batches, seeds, strict=True)
|
|
160
|
+
]
|
|
161
|
+
|
|
162
|
+
@property
|
|
163
|
+
def duration_in_seconds(self) -> float:
|
|
164
|
+
return len(self) * self.batch_size * self.window_size / SAMPLE_RATE
|
|
165
|
+
|
|
166
|
+
def __iter__(self) -> Iterator[list[WindowKey]]:
|
|
167
|
+
return iter(self.batches[self.start :])
|
|
168
|
+
|
|
169
|
+
def __len__(self) -> int:
|
|
170
|
+
return len(self.batches)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class SequentialBatchSampler(Sampler[list[WindowKey]]):
|
|
174
|
+
def __init__(
|
|
175
|
+
self,
|
|
176
|
+
files: list[AudioFile],
|
|
177
|
+
batch_size: int,
|
|
178
|
+
window_size: int,
|
|
179
|
+
*,
|
|
180
|
+
rank: int = 0,
|
|
181
|
+
world_size: int = 1,
|
|
182
|
+
) -> None:
|
|
183
|
+
windows = [
|
|
184
|
+
(index, start, 0)
|
|
185
|
+
for index, file in enumerate(files)
|
|
186
|
+
for start in window_offsets(file["num_samples"], window_size)
|
|
187
|
+
]
|
|
188
|
+
num_batches = len(windows) // batch_size
|
|
189
|
+
local_size = local_batch_size(batch_size, world_size)
|
|
190
|
+
self.batches = [
|
|
191
|
+
[windows[i + j * num_batches] for j in range(rank * local_size, (rank + 1) * local_size)]
|
|
192
|
+
for i in range(num_batches)
|
|
193
|
+
]
|
|
194
|
+
|
|
195
|
+
def __iter__(self) -> Iterator[list[WindowKey]]:
|
|
196
|
+
return iter(self.batches)
|
|
197
|
+
|
|
198
|
+
def __len__(self) -> int:
|
|
199
|
+
return len(self.batches)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def build_dataloader(
|
|
203
|
+
manifest: str | Path,
|
|
204
|
+
split: Literal["train", "validation"],
|
|
205
|
+
*,
|
|
206
|
+
window_size: int,
|
|
207
|
+
batch_size: int,
|
|
208
|
+
num_workers: int,
|
|
209
|
+
group_size: int,
|
|
210
|
+
seed: int = 0,
|
|
211
|
+
max_offset: int = 0,
|
|
212
|
+
augment_past: bool = False,
|
|
213
|
+
rank: int = 0,
|
|
214
|
+
world_size: int = 1,
|
|
215
|
+
) -> DataLoader:
|
|
216
|
+
files = read_manifest(manifest)
|
|
217
|
+
if split == "train":
|
|
218
|
+
transform = PitchReverbAugment() if augment_past else None
|
|
219
|
+
sampler = SameSpeakerBatchSampler(
|
|
220
|
+
files, batch_size, window_size, seed, max_offset, group_size=group_size, rank=rank, world_size=world_size
|
|
221
|
+
)
|
|
222
|
+
elif split == "validation":
|
|
223
|
+
transform = None
|
|
224
|
+
sampler = SequentialBatchSampler(files, batch_size, window_size, rank=rank, world_size=world_size)
|
|
225
|
+
else:
|
|
226
|
+
raise ValueError(f"Unknown split {split!r}, expected 'train' or 'validation'")
|
|
227
|
+
return DataLoader(
|
|
228
|
+
AudioWindowDataset(files, window_size, transform),
|
|
229
|
+
batch_sampler=sampler,
|
|
230
|
+
num_workers=num_workers,
|
|
231
|
+
pin_memory=torch.cuda.is_available(),
|
|
232
|
+
persistent_workers=num_workers > 0,
|
|
233
|
+
generator=torch.Generator(), # Do not draw worker seeds from the global RNG (used by dropout)
|
|
234
|
+
)
|
minicpc/features.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
from tqdm import tqdm
|
|
5
|
+
|
|
6
|
+
from .data import load_audio, read_manifest
|
|
7
|
+
from .model import CPC
|
|
8
|
+
|
|
9
|
+
__all__ = ["extract_features"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@torch.inference_mode()
|
|
13
|
+
def extract_features(model_path: str, manifest: str, output: str) -> None:
|
|
14
|
+
"""Extract features (output of the convolutional encoder and of each LSTM layer) of each file of the manifest.
|
|
15
|
+
|
|
16
|
+
The output of the encoder is saved as `{output}/0/{fileid}.pt`, and the output of LSTM layer `k` (1-indexed)
|
|
17
|
+
as `{output}/{k}/{fileid}.pt`.
|
|
18
|
+
|
|
19
|
+
The model can be a minicpc checkpoint or a CPC3 checkpoint, local or remote (URL).
|
|
20
|
+
The manifest has the same format as for training (CSV or JSONL, the speaker column is not needed).
|
|
21
|
+
"""
|
|
22
|
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
23
|
+
model = CPC.from_pretrained(model_path).to(device)
|
|
24
|
+
dest = Path(output).resolve()
|
|
25
|
+
for file in tqdm(read_manifest(manifest)):
|
|
26
|
+
waveform = load_audio(file["path"])
|
|
27
|
+
layers = model.extract_features(waveform.to(device).unsqueeze(0))
|
|
28
|
+
for k, features in enumerate(layers):
|
|
29
|
+
dest_path = dest / str(k) / f"{file['fileid']}.pt"
|
|
30
|
+
dest_path.parent.mkdir(parents=True, exist_ok=True)
|
|
31
|
+
torch.save(features.squeeze(0).cpu(), dest_path)
|
|
Binary file
|