minicpc 0.1.0__tar.gz

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-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.5
2
+ Name: minicpc
3
+ Version: 0.1.0
4
+ Summary: Minimal implementation of CPC training
5
+ Author: Maxime Poli
6
+ Requires-Python: >=3.12
7
+ Requires-Dist: more-itertools>=10.6.0
8
+ Requires-Dist: numpy>=2.2.3
9
+ Requires-Dist: orjson>=3.13.0
10
+ Requires-Dist: polars>=1.24.0
11
+ Requires-Dist: sox-effects>=0.2.0
12
+ Requires-Dist: torch>=2.11.0
13
+ Requires-Dist: torchaudio>=2.11.0
14
+ Requires-Dist: torchcodec>=0.17.0
15
+ Requires-Dist: tqdm>=4.67.1
16
+ Import-Name: minicpc
@@ -0,0 +1,111 @@
1
+ [project]
2
+ name = "minicpc"
3
+ version = "0.1.0"
4
+ description = "Minimal implementation of CPC training"
5
+ requires-python = ">=3.12"
6
+ authors = [{ name = "Maxime Poli" }]
7
+ dependencies = [
8
+ "more-itertools>=10.6.0",
9
+ "numpy>=2.2.3",
10
+ "orjson>=3.13.0",
11
+ "polars>=1.24.0",
12
+ "sox-effects>=0.2.0",
13
+ "torch>=2.11.0",
14
+ "torchaudio>=2.11.0",
15
+ "torchcodec>=0.17.0",
16
+ "tqdm>=4.67.1",
17
+ ]
18
+
19
+ [dependency-groups]
20
+ dev = [
21
+ "hypothesis>=6.170.15",
22
+ "prek>=0.5.10",
23
+ "pytest>=9.2.0",
24
+ ]
25
+ abx = [
26
+ "fastabx>=0.10.0",
27
+ "filelock>=4.2.9",
28
+ ]
29
+
30
+ [build-system]
31
+ requires = ["flit_core>=4.2.0,<5"]
32
+ build-backend = "flit_core.buildapi"
33
+
34
+ [tool.pytest]
35
+ addopts = ["--strict-markers"]
36
+ filterwarnings = [
37
+ "error",
38
+ # Raised by Triton's code generator on Python 3.14 when compiling a new kernel (cold cache): as an error, it makes
39
+ # the Inductor kernel compilation fail.
40
+ "ignore:AnnAssign.__init__ missing 1 required positional argument:DeprecationWarning",
41
+ # Raised by torch.compile when it inspects a non-leaf input (the predictor gets the LSTM output). Dynamo hides it
42
+ # with `torch._logging.hide_warnings`, which only works when warnings are displayed, not turned into errors.
43
+ "ignore:The .grad attribute of a Tensor that is not a leaf Tensor:UserWarning",
44
+ ]
45
+ markers = ["slow: end-to-end tests (training, resuming)"]
46
+ norecursedirs = ["*.egg", ".*", "CPC3", "build", "dist", "venv"]
47
+ pythonpath = ["tests", "tests/CPC3"]
48
+ testpaths = ["tests"]
49
+
50
+ [tool.ruff]
51
+ line-length = 119
52
+ extend-exclude = ["tests/CPC3"]
53
+
54
+ [tool.ruff.lint]
55
+ preview = true
56
+ select = [
57
+ "correctness",
58
+ "suspicious",
59
+ "complexity",
60
+ "performance",
61
+ "style",
62
+ "security",
63
+ "ANN", # flake8-annotations
64
+ "FBT", # flake8-boolean-trap
65
+ "B", # flake8-bugbear
66
+ "A", # flake8-builtins
67
+ "PT", # flake8-pytest-style
68
+ "RET", # flake8-return
69
+ "SIM", # flake8-simplify
70
+ "TC", # flake8-type-checking
71
+ "ARG", # flake8-unused-arguments
72
+ "PTH", # flake8-use-pathlib
73
+ "N", # pep8-naming
74
+ "PERF", # Perflint
75
+ "E", # pycodestyle
76
+ "PLW", # Pylint
77
+ "UP", # pyupgrade
78
+ "FURB", # refurb
79
+ "RUF", # Ruff
80
+ ]
81
+ ignore = ["any-type"]
82
+
83
+ [tool.ruff.lint.per-file-ignores]
84
+ "tests/*" = [
85
+ "boolean-type-hint-positional-argument",
86
+ ]
87
+ "src/minicpc/kernels.py" = [
88
+ "boolean-type-hint-positional-argument",
89
+ "invalid-argument-name",
90
+ "missing-type-function-argument",
91
+ ]
92
+
93
+ [tool.ruff.lint.pep8-naming]
94
+ extend-ignore-names = ["F"] # from torch.nn import functional as F
95
+
96
+ [tool.ty.src]
97
+ exclude = ["tests/CPC3"]
98
+
99
+ [[tool.ty.overrides]]
100
+ include = ["src/minicpc/kernels.py"]
101
+ rules = { invalid-argument-type = "ignore", missing-direct-dependency = "ignore" }
102
+
103
+ [tool.ty.environment]
104
+ extra-paths = ["tests", "tests/CPC3"]
105
+
106
+ [tool.typos.default.extend-words]
107
+ dout = "dout"
108
+ NCE = "NCE"
109
+
110
+ [tool.typos.files]
111
+ extend-exclude = ["tests/CPC3"]
@@ -0,0 +1,4 @@
1
+ from .model import CPC, CPCConfig
2
+ from .registry import PRETRAINED
3
+
4
+ __all__ = ["CPC", "PRETRAINED", "CPCConfig"]
@@ -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()
@@ -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
@@ -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")))
@@ -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