coolpoodle commited on
Commit
b9dc61d
·
verified ·
1 Parent(s): 90884df

code and training scripts (part 2)

Browse files
THIRD_PARTY.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Third-party components
2
+
3
+ Music3Lab's own source is Apache-2.0. It depends on, interoperates with, and
4
+ references the following third-party works. **None of their code, weights, or
5
+ audio is bundled in this repository.** You obtain each from its original source
6
+ under its own license.
7
+
8
+ | Component | Role | Obtained from | License (verify at source) |
9
+ |---|---|---|---|
10
+ | **MiniMax-Music3** (weights + reference code) | The base model this toolkit extends. Not modified, not redistributed. | `MiniMaxAI/MiniMax-Music3` on Hugging Face | **See the model repo's own license.** Adapters trained through its frozen decoder / on its captured state may be governed by it — see below and MODEL_CARD.md. |
11
+ | **Hugging Face Diffusers** | Provides the MiniMax-Music3 generation pipeline used for capture/generation. | `git+https://github.com/huggingface/diffusers.git@90b4e34e79a86ec5e7f2437634fe95ecd2108796` | Apache-2.0 |
12
+ | **Hugging Face Transformers** | LM backbone / cache utilities. | PyPI / GitHub | Apache-2.0 |
13
+ | **PyTorch** (`torch`, `torchaudio`) | Tensor / model runtime. | PyPI | BSD-3-Clause |
14
+ | **safetensors, accelerate, huggingface-hub** | Weight IO, device placement, hub access. | PyPI | Apache-2.0 |
15
+ | **numpy, scipy, soundfile, PyYAML, pydantic, psutil** | Numerics, audio IO, config, validation. | PyPI | BSD / MIT / other permissive |
16
+ | **yt-dlp** | Optional dataset downloader (`scripts/data/laion_ingest.py`). Pinned `2026.07.04`. | PyPI / GitHub | The Unlicense (public domain) |
17
+ | **FFmpeg** (`ffmpeg`/`ffprobe`) | External binary invoked for decode/resample. Not bundled or linked. | System package manager | LGPL/GPL depending on build |
18
+ | **LAION-DISCO-12M** | Dataset *index/metadata* (YouTube IDs, tags). Audio is **not** part of the dataset and is **not** included here. | `laion/LAION-DISCO-12M`, revision `6e7bf3758a77301e46a715af894fefd79bb1da53` | Apache-2.0 (metadata only) — see DATA.md |
19
+
20
+ ## Derivative-weight caveat (important)
21
+
22
+ The trained adapters/encoders in this project were trained *through* the frozen
23
+ MiniMax-Music3 decoder and/or on state/latents *captured from* MiniMax-Music3
24
+ generations. They may therefore constitute **derivative works of MiniMax-Music3**
25
+ and be subject to that model's license.
26
+
27
+ Before publishing or redistributing any checkpoint (e.g. to Hugging Face),
28
+ **read the MiniMax-Music3 license and confirm derivative-weight redistribution is
29
+ permitted and under what terms.** This repository ships only *pointers* to those
30
+ checkpoints (see `checkpoints/README.md`), never the weights themselves, so that
31
+ this decision is made explicitly and separately from the code release.
32
+
33
+ ## Trademarks
34
+
35
+ "MiniMax", "MiniMax-Music3", "LAION", "Hugging Face", and other names are the
36
+ marks of their respective owners and are used here only for identification and
37
+ attribution. Music3Lab is an independent project and is not affiliated with or
38
+ endorsed by any of them.
TRAINING.md ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Training
2
+
3
+ Every trainable component in Music3Lab ships with its training script, config,
4
+ and tests so the community can reproduce results **and build on the open
5
+ problems** (native tokenization, arbitrary-audio editing). The base
6
+ MiniMax-Music3 model is **always frozen** — only the small adapters/encoders/heads
7
+ below are trained.
8
+
9
+ ## Prerequisites
10
+
11
+ - `pip install -e ".[capture]"` (adds the pinned diffusers fork + transformers).
12
+ - The base model downloaded locally (see [REPRODUCING.md](REPRODUCING.md)).
13
+ - An NVIDIA GPU (H100 80 GB used for all published runs; most adapters need
14
+ only ~6–12 GB — they are compute-bound, not memory-bound).
15
+ - A **teacher corpus** for most tasks. These are WAV/latent/token pairs *captured
16
+ from* the frozen model and are not shipped (derivatives + size). Regenerate them
17
+ with the capture scripts (`scripts/capture_generation_state.py`,
18
+ `scripts/run_flow_encoder_pilot.py --dataset-root ...`, the native-state
19
+ capture runners, etc.). For external real music, build the corpus with
20
+ `scripts/data/laion_ingest.py` (see [DATA.md](DATA.md)).
21
+
22
+ ## Common invocation
23
+
24
+ Training scripts share a `--config` entrypoint plus path flags. Always check
25
+ `--help` for the exact flags of each script:
26
+
27
+ ```bash
28
+ python scripts/run_<task>.py --config configs/<task>.yaml \
29
+ --snapshot ./models/minimax-music3 \
30
+ --diffusers-root <path-to-pinned-diffusers> \
31
+ --teacher-root <captured-teacher-corpus> \
32
+ --evidence-root ./runs/<task>
33
+ ```
34
+
35
+ Each run writes checkpoints, a `metrics.json`, and a `report.md` with the
36
+ preregistered gate result and artifact SHA-256s. Gates are objective only; a run
37
+ that misses its gate is recorded as a failure, not tuned into a pass.
38
+
39
+ ## Trainable components
40
+
41
+ | Component | Script | Config | Trains | Result |
42
+ |---|---|---|---|---|
43
+ | Continuous encoder (pilot) | `run_flow_encoder_pilot.py` | `flow-encoder-v1.yaml` | WAV→Flow-latent encoder (~1M) | ✅ pilot pass (~1.34 ms) |
44
+ | External encoder fine-tune | `run_external_encoder_finetune.py` | `external-flow-encoder-interim-678-v1.yaml` | same encoder on 542 LAION tracks | 🟡 rejected specialist (+13.2% teacher regression) |
45
+ | Masked-Flow inpaint | `run_masked_flow_inpaint.py` | `flow-inpaint-v1.yaml` | rank-4 Flow LoRA (1,775,616) | ✅ captured-condition pass |
46
+ | Learned audio continuation | `run_learned_audio_continuation.py` | `learned-audio-continuation-v1.yaml` | arbitrary-WAV continuation LoRA | ❌ lost to repeat/roll |
47
+ | Acoustic FIM v2 | `run_acoustic_fim_v2.py` | `acoustic-fim-v2.yaml` | 2-sided waveform U-Net (4.06M) | ❌ +5.9% vs +10% gate |
48
+ | Audio FIM | `run_audio_fim.py` | `audio-fim-v1.yaml` | earlier FIM variant | ❌ below gate |
49
+ | Audio prepend | `run_audio_prepend.py` | `audio-prepend-v1.yaml` | right-context prepend | ❌ seam/anti-copy |
50
+ | Flow prepend | `run_flow_prepend.py` | `flow-prepend-v1.yaml` | suffix-conditioned prefix (Flow) | 🟡 local pilot only |
51
+ | Waveform causal continuation | `run_waveform_causal_continuation.py` | `waveform-causal-continuation-v1.yaml` | causal waveform net | ❌ collapsed to repeat |
52
+ | Waveform right-context prepend | `run_waveform_right_context_prepend.py` | `waveform-right-context-prepend-v1.yaml` | spectral/attention prepend | ❌ seam/anti-copy |
53
+ | Native-state Stage 0 | `run_native_state_stage0.py` | `native-state-stage0.yaml` | 3-branch posterior (one clip) | ✅ one-clip (interpolation) |
54
+ | Native-state c0 distillation | `run_native_state_distill.py` | `native-state-distill.yaml` | c0 soft-logit head | 🟡 bounded pass |
55
+ | Native-state multiclip | `run_native_state_multiclip.py` | `native-state-multiclip.yaml` | hard-label c0 | ❌ CE 10.54 |
56
+ | Native Stage 1 (residual) | `run_native_stage1.py` | `native-state-stage1.yaml` | autoregressive c1–c7 heads | ❌ near-modal, 0 exact rows |
57
+ | Native Stage 1 (local hidden) | `run_native_stage1_local.py` | `native-state-stage1-local.yaml` | Local-state posterior variant | ❌ near-modal |
58
+ | Native token adapter | `run_native_token_adapter.py` | `native-token-adapter-v1.yaml` | WAV→8-codebook heads | ❌ residual CE regressed |
59
+ | Latent inversion (research) | `run_latent_inversion.py` / `_v2.py` / `_e3.py` | `inversion-*.yaml` | per-clip latent optimization (no training) | ✅ 22 dB SI-SDR, but ~208 s/1 s |
60
+ | Autonomous round | `run_autonomous_round.py` | `autonomous-interim678-v1.yaml` | champion/challenger promotion + rollback | ✅ rejection/rollback demonstrated |
61
+
62
+ ## Where to push the open problems
63
+
64
+ The most valuable unsolved directions, with the most training scaffolding already
65
+ in place:
66
+
67
+ 1. **Native WAV→token encoding** (`native-state/*`, `native_token_adapter`): c0
68
+ semantic codes are learnable via distillation; **c1–c7 residual codes are not**
69
+ from the corpora tried. Needs either far more data or a fundamentally different
70
+ residual-conditioning approach. Start from `run_native_stage1.py`.
71
+ 2. **Arbitrary-WAV history-aware continuation**: the continuous representation
72
+ lacks the causal predictability to beat repeat/roll. Start from
73
+ `run_learned_audio_continuation.py`.
74
+ 3. **Two-sided arbitrary-WAV FIM**: `run_acoustic_fim_v2.py` got +5.9%; the +10%
75
+ boundary-continuity gate is the wall.
76
+
77
+ See [reports/](reports/) for each experiment's full metrics and failure analysis.
tests/test_native_token_adapter.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CPU contract for an in-domain captured-Music3 token-prediction experiment.
2
+
3
+ This is deliberately not a native Music3 tokenizer and it makes no claim for
4
+ arbitrary external music. Its only eligible teachers are paired captured
5
+ Music3 waveforms, tokens, priming rows, and re-emitted waveforms.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import pytest
10
+ import torch
11
+
12
+ from music3lab.codec import native_token_adapter as adapter
13
+
14
+
15
+ SAMPLES = 44_032
16
+ FRAMES = 25
17
+ SPLIT_SEEDS = {
18
+ "train": tuple(range(1000, 1064)),
19
+ "validation": tuple(range(2000, 2016)),
20
+ "heldout": tuple(range(3000, 3016)),
21
+ }
22
+
23
+
24
+ def _sidecar(split: str) -> adapter.TokenTeacherSidecar:
25
+ seeds = SPLIT_SEEDS[split]
26
+ count = len(seeds)
27
+ audio = torch.zeros(count, 2, SAMPLES)
28
+ audio[:, 0, 0] = torch.tensor(seeds, dtype=audio.dtype)
29
+ semantic = torch.arange(count * FRAMES, dtype=torch.int64).reshape(count, FRAMES) % 16_384
30
+ residual = torch.arange(count * FRAMES * 7, dtype=torch.int64).reshape(count, FRAMES, 7) % 1_024
31
+ priming = torch.arange(count * 8, dtype=torch.int64).reshape(count, 8) % 1_024
32
+ return adapter.TokenTeacherSidecar(
33
+ split=split,
34
+ seeds=seeds,
35
+ audio=audio,
36
+ semantic=semantic,
37
+ residual=residual,
38
+ priming=priming,
39
+ reemitted_audio=audio.clone(),
40
+ source_domain="captured_music3",
41
+ )
42
+
43
+
44
+ def test_teacher_sidecars_have_exact_64_16_16_seed_pairing_and_reemission() -> None:
45
+ sidecars = tuple(_sidecar(name) for name in ("train", "validation", "heldout"))
46
+ report = adapter.validate_token_teacher_sidecars(sidecars)
47
+ assert report.split_counts == {"train": 64, "validation": 16, "heldout": 16}
48
+ assert report.seed_sets == SPLIT_SEEDS
49
+ assert report.source_domain == "captured_music3_only"
50
+
51
+ missing = _sidecar("train")
52
+ missing.reemitted_audio = None
53
+ with pytest.raises(ValueError, match="reemitted_audio"):
54
+ adapter.validate_token_teacher_sidecars((missing,))
55
+
56
+ mismatched = _sidecar("train")
57
+ mismatched.reemitted_audio[0, 0, 0] += 1
58
+ with pytest.raises(ValueError, match="re-emitted audio"):
59
+ adapter.validate_token_teacher_sidecars((mismatched,))
60
+
61
+
62
+ def test_waveform_adapter_emits_all_codebook_logits_and_per_code_cross_entropy() -> None:
63
+ batch = _sidecar("validation")
64
+ model = adapter.CapturedMusic3TokenAdapter(adapter.TokenAdapterConfig(hidden_channels=8))
65
+ semantic_logits, residual_logits = model(batch.audio[:2])
66
+ assert semantic_logits.shape == (2, FRAMES, 16_384)
67
+ assert residual_logits.shape == (2, FRAMES, 7, 1_024)
68
+
69
+ loss = adapter.token_cross_entropy(
70
+ semantic_logits,
71
+ residual_logits,
72
+ batch.semantic[:2],
73
+ batch.residual[:2],
74
+ )
75
+ assert set(loss) == {"semantic", "residual", "total"}
76
+ assert loss["total"].isfinite() and loss["total"] > 0
77
+ loss["total"].backward()
78
+ assert any(parameter.grad is not None for parameter in model.parameters())
79
+
80
+
81
+ def test_modes_teacher_forcing_and_predicted_tokens_are_range_valid_and_renderable() -> None:
82
+ batch = _sidecar("validation")
83
+ modes = adapter.per_position_mode_tokens(batch.semantic, batch.residual)
84
+ assert modes.shape == (FRAMES, 8)
85
+ adapter.validate_predicted_tokens(modes.unsqueeze(0))
86
+
87
+ backend = _TinyCapturedFuser()
88
+ captured_fused = backend.expected(batch.semantic[:1], batch.residual[:1], batch.priming[:1])
89
+ replayed = adapter.teacher_force_captured_rows(
90
+ backend, batch.semantic[:1], batch.residual[:1], batch.priming[:1]
91
+ )
92
+ assert torch.equal(replayed, captured_fused)
93
+ assert backend.sampling_rng is None
94
+
95
+ logits = torch.full((1, FRAMES, 16_384), -20.0)
96
+ logits[..., 7] = 20.0
97
+ residual_logits = torch.full((1, FRAMES, 7, 1_024), -20.0)
98
+ residual_logits[..., 9] = 20.0
99
+ predicted = adapter.predict_tokens(logits, residual_logits)
100
+ adapter.validate_predicted_tokens(predicted)
101
+ rendered = adapter.render_predicted_tokens(_TinyRenderer(), predicted)
102
+ assert rendered.shape == (1, 2, SAMPLES)
103
+
104
+ capability = adapter.describe_capability()
105
+ assert capability["native_tokenizer"] is False
106
+ assert capability["arbitrary_external_music"] is False
107
+ assert capability["domain"] == "captured_music3_only"
108
+
109
+
110
+ class _TinyCapturedFuser:
111
+ sampling_rng = "not-called"
112
+
113
+ @staticmethod
114
+ def expected(semantic: torch.Tensor, residual: torch.Tensor, priming: torch.Tensor) -> torch.Tensor:
115
+ rows = torch.cat((semantic.unsqueeze(-1), residual), dim=-1).to(torch.float32)
116
+ return rows.mean(dim=-1, keepdim=True).expand(-1, -1, 32_768).contiguous()
117
+
118
+ def teacher_force(self, semantic: torch.Tensor, residual: torch.Tensor, priming: torch.Tensor, *, sampling_rng=None) -> torch.Tensor:
119
+ self.sampling_rng = sampling_rng
120
+ return self.expected(semantic, residual, priming)
121
+
122
+
123
+ class _TinyRenderer:
124
+ def render(self, tokens: torch.Tensor) -> torch.Tensor:
125
+ assert tokens.shape[1:] == (FRAMES, 8)
126
+ return torch.zeros(tokens.shape[0], 2, SAMPLES)
127
+
128
+ def test_frozen_native_token_config_and_cli_are_cpu_safe() -> None:
129
+ import os
130
+ import subprocess
131
+ import sys
132
+ from pathlib import Path
133
+
134
+ loaded = adapter.load_native_token_config(
135
+ Path(__file__).parents[1] / "configs/native-token-adapter-v1.yaml"
136
+ )
137
+ assert loaded.config.teacher.split_seeds() == SPLIT_SEEDS
138
+ assert loaded.config.native_tokenizer is False
139
+ result = subprocess.run(
140
+ [
141
+ sys.executable,
142
+ "-B",
143
+ str(Path(__file__).parents[1] / "scripts/run_native_token_adapter.py"),
144
+ "--help",
145
+ ],
146
+ check=True,
147
+ capture_output=True,
148
+ text=True,
149
+ env={
150
+ "PATH": os.environ["PATH"],
151
+ "PYTHONPATH": str(Path(__file__).parents[1] / "src"),
152
+ "CUDA_VISIBLE_DEVICES": "-1",
153
+ "PYTHONDONTWRITEBYTECODE": "1",
154
+ },
155
+ )
156
+ assert "not a native tokenizer" in " ".join(result.stdout.split())
tests/test_native_token_compatibility.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+
5
+ import numpy as np
6
+ import pytest
7
+
8
+ from native_token_compatibility import (
9
+ compare_native_tokens,
10
+ main,
11
+ validate_native_tokens,
12
+ )
13
+
14
+
15
+ def _valid_tokens(frames: int = 5) -> np.ndarray:
16
+ tokens = np.zeros((frames, 8), dtype=np.int64)
17
+ tokens[:, 0] = np.arange(frames) % 16_384
18
+ for index in range(1, 8):
19
+ tokens[:, index] = (np.arange(frames) + index) % 1_024
20
+ return tokens
21
+
22
+
23
+ def test_exact_cross_layout_comparison():
24
+ tokens = _valid_tokens()
25
+ result = compare_native_tokens(
26
+ tokens,
27
+ tokens.T,
28
+ reference_layout="frames_first",
29
+ recovered_layout="codebooks_first",
30
+ )
31
+
32
+ assert result["exact_match"] is True
33
+ assert result["reference_shape_frames_first"] == [5, 8]
34
+ assert result["duration_seconds_at_25hz"] == pytest.approx(0.2)
35
+ assert all(item["agreement"] == 1.0 for item in result["per_codebook"])
36
+
37
+
38
+ def test_mismatch_reports_exact_per_codebook_agreement():
39
+ reference = _valid_tokens(4)
40
+ recovered = reference.copy()
41
+ recovered[0, 3] += 1
42
+
43
+ result = compare_native_tokens(
44
+ reference,
45
+ recovered,
46
+ reference_layout="frames_first",
47
+ recovered_layout="frames_first",
48
+ )
49
+
50
+ assert result["exact_match"] is False
51
+ assert result["per_codebook"][2]["agreement"] == 1.0
52
+ assert result["per_codebook"][3]["matching_frames"] == 3
53
+ assert result["per_codebook"][3]["agreement"] == 0.75
54
+
55
+
56
+ def test_shape_mismatch_is_not_truncated_or_aligned():
57
+ result = compare_native_tokens(
58
+ _valid_tokens(4),
59
+ _valid_tokens(3),
60
+ reference_layout="frames_first",
61
+ recovered_layout="frames_first",
62
+ )
63
+ assert result["shape_match"] is False
64
+ assert result["frames"] is None
65
+ assert all(item["agreement"] is None for item in result["per_codebook"])
66
+
67
+
68
+ @pytest.mark.parametrize(
69
+ ("codebook", "value", "message"),
70
+ [(0, 16_384, "c0"), (1, 1_024, "c1"), (7, -1, "c7")],
71
+ )
72
+ def test_codebook_ranges_are_enforced(codebook, value, message):
73
+ tokens = _valid_tokens()
74
+ tokens[0, codebook] = value
75
+ with pytest.raises(ValueError, match=message):
76
+ validate_native_tokens(tokens, layout="frames_first")
77
+
78
+
79
+ def test_layout_must_match_declared_axis():
80
+ with pytest.raises(ValueError, match="frames_first"):
81
+ validate_native_tokens(_valid_tokens().T, layout="frames_first")
82
+
83
+
84
+ def test_floating_point_tokens_are_rejected():
85
+ with pytest.raises(TypeError, match="integer dtype"):
86
+ validate_native_tokens(_valid_tokens().astype(np.float32), layout="frames_first")
87
+
88
+
89
+ def test_malformed_torch_token_file_json_cli_returns_structured_error(tmp_path, capsys):
90
+ malformed = tmp_path / "malformed.pt"
91
+ malformed.write_bytes(b"not a torch token file")
92
+ valid = tmp_path / "valid.npy"
93
+ np.save(valid, _valid_tokens())
94
+
95
+ result = main(
96
+ [
97
+ str(malformed),
98
+ str(valid),
99
+ "--reference-layout",
100
+ "frames_first",
101
+ "--recovered-layout",
102
+ "frames_first",
103
+ "--json",
104
+ ]
105
+ )
106
+ assert result == 2
107
+ payload = json.loads(capsys.readouterr().out)
108
+ assert payload["status"] == "ERROR"
109
+ assert "unable to safely load token file" in payload["error"]
tests/test_objective_seed_search.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compact CPU gates for objective-only sequential prefix seed search."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import subprocess
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ import torch
11
+
12
+ from music3lab.editing.prefix_seed_search import (
13
+ SEARCH_CAPABILITY,
14
+ candidate_measurements,
15
+ load_prefix_seed_search_config,
16
+ select_candidate,
17
+ splice_measurements,
18
+ )
19
+
20
+
21
+ ROOT = Path(__file__).resolve().parents[1]
22
+ CONFIG = ROOT / "configs" / "prefix-seed-search-v1.yaml"
23
+
24
+
25
+ def _record(seed: int, derivative: float, ratio: float, digest: str):
26
+ gates = {
27
+ "finite": True,
28
+ "expected_length": True,
29
+ "known_suffix_latent_exact": True,
30
+ "known_suffix_audio_exact": True,
31
+ "minimum_rms": True,
32
+ "maximum_peak": True,
33
+ "maximum_clipped_fraction": True,
34
+ }
35
+ return {
36
+ "seed": seed,
37
+ "audio_sha256": digest,
38
+ "join_max_abs_derivative": derivative,
39
+ "join_edge_rms_ratio": ratio,
40
+ "gates": gates,
41
+ "eligible_before_uniqueness": True,
42
+ }
43
+
44
+
45
+ def test_frozen_search_config_has_exact_four_seeds_and_narrow_claim() -> None:
46
+ loaded = load_prefix_seed_search_config(CONFIG)
47
+ config = loaded.config
48
+ assert config.search.seeds == (101, 103, 107, 109)
49
+ assert config.search.sequential_single_model_load
50
+ assert config.search.expected_prefix_frames == 22
51
+ assert config.capability == SEARCH_CAPABILITY
52
+ assert not config.artistic_quality_claim and not config.stock_win_claim
53
+ for prohibited in ("artistic", "quality", "stock", "llm"):
54
+ assert prohibited not in config.capability.lower()
55
+
56
+
57
+ def test_splice_metrics_use_fixed_join_derivative_and_edge_rms_windows() -> None:
58
+ audio = torch.zeros(1, 2, 44032)
59
+ join = 22 * 512
60
+ audio[:, :, join - 1024 : join] = 0.1
61
+ audio[:, :, join : join + 1024] = 0.2
62
+ metrics = splice_measurements(
63
+ audio,
64
+ join_sample=join,
65
+ derivative_half_window_samples=512,
66
+ edge_rms_window_samples=1024,
67
+ epsilon=1e-8,
68
+ )
69
+ assert metrics["join_max_abs_derivative"] == torch.tensor(0.1).item()
70
+ assert metrics["join_left_edge_rms"] == torch.tensor(0.1).item()
71
+ assert metrics["join_right_edge_rms"] == torch.tensor(0.2).item()
72
+ assert 1.9999 < metrics["join_edge_rms_ratio"] < 2.0001
73
+
74
+
75
+ def test_candidate_gates_bind_shape_signal_and_exact_known_suffix() -> None:
76
+ config = load_prefix_seed_search_config(CONFIG).config
77
+ mask = torch.zeros(1, 1, 86, dtype=torch.bool)
78
+ mask[:, :, :22] = True
79
+ source_latent = torch.zeros(1, 128, 86)
80
+ latent = source_latent.clone()
81
+ source_audio = torch.full((1, 2, 44032), 0.05)
82
+ audio = source_audio.clone()
83
+ audio[:, :, : 22 * 512] = 0.1
84
+ value = candidate_measurements(
85
+ seed=101,
86
+ audio=audio,
87
+ latent=latent,
88
+ source_audio=source_audio,
89
+ source_latent=source_latent,
90
+ mask=mask,
91
+ config=config,
92
+ )
93
+ assert value["eligible_before_uniqueness"]
94
+ assert all(value["gates"].values())
95
+ broken = audio.clone()
96
+ broken[:, :, 22 * 512] += 1
97
+ bad = candidate_measurements(
98
+ seed=101,
99
+ audio=broken,
100
+ latent=latent,
101
+ source_audio=source_audio,
102
+ source_latent=source_latent,
103
+ mask=mask,
104
+ config=config,
105
+ )
106
+ assert not bad["gates"]["known_suffix_audio_exact"]
107
+ assert not bad["eligible_before_uniqueness"]
108
+
109
+
110
+ def test_selector_retains_four_rows_and_uses_lexicographic_seed_tie_break() -> None:
111
+ values = [
112
+ _record(101, 0.25, 1.0, "a" * 64),
113
+ _record(103, 0.25, 1.0, "b" * 64),
114
+ _record(107, 0.35, 1.0, "c" * 64),
115
+ _record(109, 0.45, 1.0, "d" * 64),
116
+ ]
117
+ index, selected = select_candidate(values)
118
+ assert selected and index == 0
119
+ assert [value["seed"] for value in values] == [101, 103, 107, 109]
120
+ assert all(value["eligible"] for value in values)
121
+
122
+
123
+ def test_selector_rejects_invalid_and_later_duplicate_but_keeps_valid_rows() -> None:
124
+ values = [
125
+ _record(101, 0.25, 1.0, "a" * 64),
126
+ _record(103, 0.10, 1.0, "a" * 64),
127
+ _record(107, 0.35, 1.0, "c" * 64),
128
+ _record(109, 0.45, 1.0, "d" * 64),
129
+ ]
130
+ values[2]["gates"]["finite"] = False
131
+ values[2]["eligible_before_uniqueness"] = False
132
+ index, selected = select_candidate(values)
133
+ assert selected and index == 0
134
+ assert not values[1]["eligible"]
135
+ assert "duplicate_audio_sha256" in values[1]["rejection_reasons"]
136
+ assert not values[2]["eligible"] and "finite" in values[2]["rejection_reasons"]
137
+ assert values[3]["eligible"]
138
+
139
+
140
+ def test_selector_reports_no_selection_when_every_candidate_fails() -> None:
141
+ values = [
142
+ _record(seed, 0.1 + index, 1.0, f"{index + 1:064x}")
143
+ for index, seed in enumerate((101, 103, 107, 109))
144
+ ]
145
+ for value in values:
146
+ value["gates"]["minimum_rms"] = False
147
+ value["eligible_before_uniqueness"] = False
148
+ index, selected = select_candidate(values)
149
+ assert not selected and index == -1
150
+ assert len(values) == 4 and not any(value["eligible"] for value in values)
151
+
152
+
153
+ def test_cli_help_is_cpu_safe_and_states_the_only_supported_claim() -> None:
154
+ result = subprocess.run(
155
+ [
156
+ sys.executable,
157
+ "-B",
158
+ str(ROOT / "scripts" / "run_prefix_seed_search.py"),
159
+ "--help",
160
+ ],
161
+ check=True,
162
+ capture_output=True,
163
+ text=True,
164
+ env={
165
+ "PATH": os.environ["PATH"],
166
+ "PYTHONPATH": str(ROOT / "src"),
167
+ "PYTHONDONTWRITEBYTECODE": "1",
168
+ "CUDA_VISIBLE_DEVICES": "-1",
169
+ },
170
+ )
171
+ text = " ".join(result.stdout.lower().split())
172
+ assert "sequential n=4" in text
173
+ assert "least measurable splice discontinuity" in text
174
+ assert "not artistic quality" in text
175
+ assert "stock-model win" in text
tests/test_prompt_free_contract.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Focused CPU contract for deferred prompt-free Music3 conditioning.
2
+
3
+ This is intentionally an expected-red contract until the prompt-free module is
4
+ implemented. It specifies an internal text bridge, not null conditioning or a
5
+ quality/diversity claim.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ from pathlib import Path
12
+ import wave
13
+
14
+ import numpy as np
15
+
16
+ from music3lab import autocondition as prompt_free
17
+ from music3lab.__main__ import build_parser
18
+
19
+
20
+ def _click_track(path: Path, *, bpm: float = 120.0, seconds: float = 4.0) -> None:
21
+ sample_rate = 44_100
22
+ audio = np.zeros(int(sample_rate * seconds), dtype=np.float32)
23
+ for offset in np.arange(0.0, seconds, 60.0 / bpm):
24
+ start = int(offset * sample_rate)
25
+ audio[start : start + 96] = np.hanning(192)[:96]
26
+ _write_mono_pcm(path, audio, sample_rate)
27
+
28
+
29
+ def _write_mono_pcm(path: Path, audio: np.ndarray, sample_rate: int) -> None:
30
+ pcm = np.clip(audio, -1.0, 1.0)
31
+ with wave.open(str(path), "wb") as handle:
32
+ handle.setnchannels(1)
33
+ handle.setsampwidth(2)
34
+ handle.setframerate(sample_rate)
35
+ handle.writeframes((pcm * 32767).astype("<i2").tobytes())
36
+
37
+
38
+ def _permitted_records() -> list[dict[str, object]]:
39
+ return [
40
+ {
41
+ "source_sha256": f"{index:064x}",
42
+ "permitted": True,
43
+ "title": "MUST NOT LEAK",
44
+ "artist": "MUST NOT LEAK",
45
+ "features": {
46
+ "tempo_bpm": 92 + index * 7,
47
+ "key": "C major",
48
+ "meter": 4,
49
+ "energy": 0.2 + index * 0.1,
50
+ "instrumental_probability": 0.9,
51
+ },
52
+ }
53
+ for index in range(4)
54
+ ]
55
+
56
+
57
+ def test_click_analysis_is_deterministic_and_reports_mir_schema(tmp_path: Path) -> None:
58
+ source = tmp_path / "click-120.wav"
59
+ _click_track(source)
60
+ first = prompt_free.analyze_audio(source)
61
+ second = prompt_free.analyze_audio(source)
62
+ assert first.to_dict() == second.to_dict()
63
+ payload = first.to_dict()
64
+ assert payload["backend"] == "numpy+ffmpeg"
65
+ assert abs(payload["tempo_bpm"] - 120.0) <= 3.0
66
+ assert payload["tempo_confidence"] > 0.5 and payload["beat_times_seconds"]
67
+ assert {"meter", "key", "mode", "energy_curve", "silence", "uncertainty"} <= set(payload)
68
+ assert payload["source_audio_sha256"] == hashlib.sha256(source.read_bytes()).hexdigest()
69
+
70
+
71
+ def test_silence_is_marked_uncertain_not_described_as_music(tmp_path: Path) -> None:
72
+ source = tmp_path / "silence.wav"
73
+ _write_mono_pcm(source, np.zeros(44_100, dtype=np.float32), 44_100)
74
+ payload = prompt_free.analyze_audio(source).to_dict()
75
+ assert payload["silence"] is True
76
+ assert payload["tempo_confidence"] == 0.0
77
+ assert payload["uncertainty"]["tempo"] == "high"
78
+ assert payload["uncertainty"]["key"] == "high"
79
+
80
+
81
+ def test_permitted_feature_prior_excludes_titles_and_artists_and_seed_is_reproducible() -> None:
82
+ prior = prompt_free.CorpusPrior.from_permitted_records(_permitted_records())
83
+ serialized = json.dumps(prior.to_dict(), sort_keys=True).lower()
84
+ assert "must not leak" not in serialized and "title" not in serialized and "artist" not in serialized
85
+ assert set(prior.to_dict()["source_hashes"]) == {record["source_sha256"] for record in _permitted_records()}
86
+ first = prompt_free.sample_internal_plan(prior, seed=17, duration_seconds=12)
87
+ assert first.to_dict() == prompt_free.sample_internal_plan(prior, seed=17, duration_seconds=12).to_dict()
88
+ plans = [prompt_free.sample_internal_plan(prior, seed=seed, duration_seconds=12).to_dict() for seed in range(8)]
89
+ assert len({json.dumps(plan, sort_keys=True) for plan in plans}) > 1
90
+
91
+
92
+ def test_prompt_free_cli_has_no_required_user_text() -> None:
93
+ args = build_parser().parse_args(
94
+ ["generate", "--duration", "12", "--seed", "17", "--prior", "prior.json", "--output", "song.wav"]
95
+ )
96
+ assert args.duration == 12 and args.seed == 17
97
+ assert args.prior == "prior.json" and args.output == "song.wav"
98
+ assert not hasattr(args, "prompt") and not hasattr(args, "lyrics")
99
+
100
+
101
+ def test_mocked_pipeline_receives_generated_text_and_sidecar_has_no_user_text(tmp_path: Path) -> None:
102
+ class Pipeline:
103
+ def __init__(self) -> None:
104
+ self.calls: list[dict[str, object]] = []
105
+
106
+ def __call__(self, **kwargs: object) -> np.ndarray:
107
+ self.calls.append(kwargs)
108
+ return np.zeros((2, 44_100), dtype=np.float32)
109
+
110
+ output = tmp_path / "generated.wav"
111
+ pipeline = Pipeline()
112
+ result = prompt_free.generate_prompt_free(
113
+ pipeline=pipeline,
114
+ duration_seconds=1,
115
+ seed=17,
116
+ prior=prompt_free.CorpusPrior.from_permitted_records(_permitted_records()),
117
+ output=output,
118
+ )
119
+ assert result.output == output
120
+ call = pipeline.calls[0]
121
+ assert call["prompt"] and call["lyrics"] == "[instrumental]"
122
+ assert call["text_origin"] == "generated" and call["lyrics_origin"] == "generated"
123
+ sidecar = json.loads(output.with_suffix(".wav.json").read_text())
124
+ assert {"prior_sha256", "analysis_sha256", "text_sha256"} <= set(sidecar)
125
+ assert "must not leak" not in json.dumps(sidecar, sort_keys=True).lower()
126
+ assert "user_prompt" not in sidecar and "user_lyrics" not in sidecar
tests/test_promptfree_bestofn.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+ import pytest
8
+
9
+ from music3lab.__main__ import build_parser
10
+ from music3lab.autocondition import CorpusPrior
11
+ from music3lab import promptfree_bestofn as best
12
+
13
+
14
+ def _prior() -> CorpusPrior:
15
+ return CorpusPrior.from_permitted_records([
16
+ {
17
+ "source_sha256": f"{index:064x}", "permitted": True,
18
+ "features": {"tempo_bpm": 100 + index, "key": "C major", "energy": 0.4},
19
+ }
20
+ for index in range(32)
21
+ ])
22
+
23
+
24
+ def _analysis(_: Path) -> dict[str, object]:
25
+ return {"tempo_bpm": 120.0, "key": "C", "mode": "major", "energy_curve": [0.4]}
26
+
27
+
28
+ def _record(index: int, *, wav: str | None = None, pcm: str | None = None, **metrics: object) -> dict[str, object]:
29
+ values: dict[str, object] = {
30
+ "finite": True, "duration_within_native_frame": True, "rms": 0.1,
31
+ "clipped_fraction": 0.0, "silence_100ms_fraction": 0.0,
32
+ "spectral_collapse": False, "absolute_dc": 0.0,
33
+ "repetition_2s_log_magnitude": 0.1, "spectral_variance": 0.2,
34
+ "peak": 0.2, "stereo_width": 0.2, "stereo_correlation": 0.1,
35
+ "spectral_flatness": 0.2, "spectral_centroid_hz": 2000.0,
36
+ "spectral_rolloff_hz": 6000.0,
37
+ }
38
+ values.update(metrics)
39
+ return {
40
+ "index": index, "wav_sha256": wav or f"{index + 1:064x}",
41
+ "decoded_pcm_sha256": pcm or f"{index + 101:064x}", "metrics": values,
42
+ "plan_adherence": {"penalty": 0.2, "tempo_octave_error": 0.1,
43
+ "key_mode_error": 0.0, "energy_log_error": 0.1},
44
+ }
45
+
46
+
47
+ def test_exact_policy_map_defaults_and_duration_bounds() -> None:
48
+ config = best.load_bestofn_config("configs/promptfree-bestofn-v1.yaml").config
49
+ assert {name: best.resolve_policy(config, name, None) for name in best.POLICIES} == {
50
+ "fast": (2, 30.0), "balanced": (4, 60.0), "maximum": (8, 90.0)
51
+ }
52
+ assert best.resolve_policy(config, "maximum", 360) == (8, 360.0)
53
+ for invalid in (0.99, 361):
54
+ with pytest.raises(ValueError): best.resolve_policy(config, "fast", invalid)
55
+
56
+
57
+ def test_cli_has_policy_but_no_prompt_or_lyrics_and_rejects_them() -> None:
58
+ parser = build_parser()
59
+ args = parser.parse_args(["generate", "--policy", "balanced", "--prior", "p.json", "--output", "x.wav"])
60
+ assert args.policy == "balanced" and args.duration is None and args.seed == 17
61
+ assert not hasattr(args, "prompt") and not hasattr(args, "lyrics")
62
+ with pytest.raises(SystemExit):
63
+ parser.parse_args(["generate", "--prior", "p", "--output", "x.wav", "--prompt", "text"])
64
+
65
+
66
+ def test_seed_and_plan_inventory_is_deterministic_and_separated() -> None:
67
+ first = [best.derive_candidate_seeds(17, index) for index in range(8)]
68
+ assert first == [best.derive_candidate_seeds(17, index) for index in range(8)]
69
+ assert len({item["plan_seed"] for item in first}) == 8
70
+ assert len({item["ar_flow_seed"] for item in first}) == 8
71
+ assert all(item["independent_ar_flow_seed_supported"] is False for item in first)
72
+
73
+
74
+ def test_mocked_one_loaded_pipeline_makes_n_calls_and_persists_every_raw(tmp_path: Path) -> None:
75
+ class Pipeline:
76
+ def __init__(self) -> None:
77
+ self.calls: list[dict[str, object]] = []
78
+ self.telemetry = {"generation_seconds": 0.01}
79
+ def __call__(self, **kwargs: object) -> np.ndarray:
80
+ self.calls.append(kwargs)
81
+ t = np.arange(44_032, dtype=np.float64) / 44_100
82
+ frequency = 200 + len(self.calls) * 17
83
+ return np.stack((0.08*np.sin(2*np.pi*frequency*t), 0.07*np.sin(2*np.pi*(frequency+3)*t)))
84
+ pipeline = Pipeline()
85
+ config = best.load_bestofn_config("configs/promptfree-bestofn-v1.yaml").config
86
+ result = best.generate_bestofn(
87
+ pipeline=pipeline, prior=_prior(), config=config, policy="fast",
88
+ duration_seconds=1, root_seed=17, output=tmp_path / "selected.wav",
89
+ load_telemetry={"pipeline_load_count": 1}, analysis_fn=_analysis,
90
+ )
91
+ assert len(pipeline.calls) == 2 and result.output.exists()
92
+ assert all((result.candidate_root / f"candidate-{index:03d}.wav").exists() for index in range(2))
93
+ assert all((result.candidate_root / f"candidate-{index:03d}.raw.wav").exists() for index in range(2))
94
+ assert len(list(result.candidate_root.glob("candidate-*.json"))) == 2
95
+ payload = json.loads(result.sidecar.read_text())
96
+ assert payload["pipeline"]["pipeline_load_count"] == 1
97
+ assert payload["completed_candidates"] == 2 and payload["selected_index"] in (0, 1)
98
+ assert len({item["wav_sha256"] for item in payload["candidates"]}) == 2
99
+
100
+
101
+ def test_eligibility_duplicate_is_later_only_and_rank_ties_by_index() -> None:
102
+ shared = "a" * 64
103
+ records = [_record(0, wav=shared), _record(1, wav=shared), _record(2)]
104
+ best.apply_eligibility(records)
105
+ assert records[0]["eligible"] is True
106
+ assert records[1]["rejections"] == ["exact_duplicate_later_candidate"]
107
+ assert min((records[0], records[2]), key=best.rank_key)["index"] == 0
108
+
109
+
110
+ def test_silence_clipping_and_duration_gates() -> None:
111
+ silence = best.audio_metrics(np.zeros((2, 44_100), np.float32), requested_duration_seconds=1)
112
+ clipped = best.audio_metrics(np.ones((2, 44_100), np.float32), requested_duration_seconds=1)
113
+ wrong = best.audio_metrics(np.ones((2, 40_000), np.float32) * 0.1, requested_duration_seconds=1)
114
+ records = [_record(0, **silence), _record(1, **clipped), _record(2, **wrong)]
115
+ best.apply_eligibility(records)
116
+ assert {"silence_rms", "silence_blocks", "spectral_collapse"} <= set(records[0]["rejections"])
117
+ assert "clipping" in records[1]["rejections"]
118
+ assert "duration" in records[2]["rejections"]
119
+
120
+
121
+ def test_full_length_decoder_overrun_is_trimmed_but_early_eos_is_never_padded() -> None:
122
+ long = np.ones((2, 44_100 + 4632), np.float32) * 0.1
123
+ normalized, detail = best.normalize_full_length_candidate(long, requested_duration_seconds=1)
124
+ assert normalized.shape == (2, 44_100)
125
+ assert detail["trimmed_trailing_samples"] == 4632 and detail["padded_samples"] == 0
126
+ short = np.ones((2, 20_000), np.float32) * 0.1
127
+ unchanged, detail = best.normalize_full_length_candidate(short, requested_duration_seconds=1)
128
+ assert unchanged.shape == short.shape and detail["early_eos_left_unchanged"] is True
129
+ assert detail["padded_samples"] == 0
130
+
131
+
132
+ def test_repetition_and_pairwise_diversity_are_deterministic() -> None:
133
+ segment = np.sin(2*np.pi*220*np.arange(88_200)/44_100)
134
+ repeated = np.tile(segment, 2)
135
+ repetition, windows = best._repetition_metric(repeated)
136
+ assert windows == 2 and repetition > 0.999
137
+ records = [_record(0), _record(1, spectral_centroid_hz=8000.0)]
138
+ first = best.pairwise_diversity(records)
139
+ assert first == best.pairwise_diversity(records)
140
+ assert first["matrix"][0][1] > best.DIVERSITY_EPSILON
141
+
142
+
143
+ def test_octave_tempo_adherence_and_energy_are_diagnostic() -> None:
144
+ plan = best.sample_internal_plan(_prior(), seed=17, duration_seconds=8)
145
+ analysis = {"tempo_bpm": plan.tempo_bpm / 2, "key": plan.key,
146
+ "mode": plan.mode, "energy_curve": [plan.energy]}
147
+ result = best.plan_adherence(plan, analysis)
148
+ assert result["tempo_octave_error"] < 1e-12
149
+ assert result["key_mode_error"] == 0 and result["diagnostic_only"] is True
150
+
151
+
152
+ def test_official_chunk_starts_and_maximum_geometry() -> None:
153
+ short = best.chunk_geometry(1)
154
+ assert short["requested_frames"] == 25 and short["official_chunk_starts"] == [0]
155
+ maximum = best.chunk_geometry(90)
156
+ assert maximum["requested_frames"] == 2250
157
+ assert maximum["official_chunk_count"] == 22
158
+ assert maximum["official_chunk_starts"] == list(range(0, 2200, 100))
159
+
160
+
161
+ def test_help_and_config_expose_frozen_contract() -> None:
162
+ help_text = build_parser()._subparsers._group_actions[0].choices["generate"].format_help()
163
+ assert "--policy {fast,balanced,maximum}" in help_text
164
+ raw = Path("configs/promptfree-bestofn-v1.yaml").read_text()
165
+ assert "independent_ar_flow_seed_supported: false" in raw
166
+ assert "artistic_quality_claim: false" in raw
tests/test_real_dav_integration.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+
5
+ import pytest
6
+
7
+ from encode_audio import NativeTokenizerUnavailableError, encode_audio
8
+ from inspect_dav import inspect_checkpoint
9
+
10
+
11
+ DAV_PATH = os.environ.get("MINIMAX_DAV_PATH")
12
+ pytestmark = pytest.mark.skipif(not DAV_PATH, reason="set MINIMAX_DAV_PATH to run released-checkpoint integration")
13
+
14
+
15
+ def test_released_dav_structure_and_fail_fast_contract(tmp_path):
16
+ report = inspect_checkpoint(DAV_PATH, include_sha256=True)
17
+
18
+ assert report["checkpoint"]["sha256"] == "52adde6c6c52cca872f549449cd7b608677d1e69f4a98eee22da3403e63b56e8"
19
+ assert report["checkpoint"]["size_bytes"] == 491_817_450
20
+ assert report["state_dict"]["tensor_count"] == 548
21
+ assert report["state_dict"]["total_numel"] == 122_904_034
22
+ assert report["state_dict"]["tensor_bytes"] == 491_616_136
23
+ assert report["state_dict"]["dtypes"] == {"float32": 548}
24
+ assert {name: group["tensor_count"] for name, group in report["prefix_groups"].items()} == {
25
+ "dec_in_proj": 2,
26
+ "decoder": 119,
27
+ "encoder": 119,
28
+ "flow": 304,
29
+ "logs_proj": 2,
30
+ "mean_proj": 2,
31
+ }
32
+ assert report["searches"]["generator"]["present"] is False
33
+ assert report["searches"]["62000_generator"]["present"] is False
34
+ assert report["capabilities"]["waveform_analysis_encoder_weights"] is True
35
+ assert report["capabilities"]["rvq_or_vq_quantizer_weights"] is False
36
+ assert report["capabilities"]["codebook_embedding_weights"] is False
37
+ assert report["capabilities"]["can_encode_native_music3_tokens"] is False
38
+
39
+ # The nonexistent WAV proves the checkpoint gate happens before audio I/O.
40
+ with pytest.raises(NativeTokenizerUnavailableError):
41
+ encode_audio(tmp_path / "not-opened.wav", dav_path=DAV_PATH)
tests/test_reference_guided_append.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import shutil
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import pytest
10
+ import soundfile as sf
11
+
12
+ from music3lab import reference_guided_append as rga
13
+ from music3lab.__main__ import build_parser
14
+
15
+
16
+ def _sha(path: Path) -> str:
17
+ return hashlib.sha256(path.read_bytes()).hexdigest()
18
+
19
+
20
+ def _write_float(path: Path, audio: np.ndarray) -> None:
21
+ sf.write(path, audio.T, rga.SAMPLE_RATE, subtype="FLOAT", format="WAV")
22
+
23
+
24
+ def _fixture_bundle(tmp_path: Path) -> tuple[Path, Path]:
25
+ source = tmp_path / "source.wav"
26
+ t = np.arange(5000, dtype=np.float32) / rga.SAMPLE_RATE
27
+ source_audio = np.stack((0.1 * np.sin(2*np.pi*110*t), 0.09*np.sin(2*np.pi*113*t)))
28
+ sf.write(source, source_audio.T, rga.SAMPLE_RATE, subtype="PCM_16", format="WAV")
29
+ bundle = tmp_path / "candidates.reference-style"
30
+ bundle.mkdir()
31
+ candidates = []
32
+ profiles = []
33
+ for index in range(8):
34
+ phase = np.arange(rga.CANDIDATE_FRAMES, dtype=np.float32) / rga.SAMPLE_RATE
35
+ audio = np.stack((
36
+ 0.04 * np.sin(2*np.pi*(220+index)*phase),
37
+ 0.035 * np.sin(2*np.pi*(223+index)*phase),
38
+ )).astype(np.float32)
39
+ path = bundle / f"candidate-{index:02d}-seed-{101+index}.wav"
40
+ _write_float(path, audio)
41
+ decoded = sf.read(path, dtype="float32", always_2d=True)[0].T.copy()
42
+ candidates.append({
43
+ "index": index, "seed": 101 + index, "wav_sha256": _sha(path),
44
+ "decoded_pcm_sha256": hashlib.sha256(decoded.astype("<f4").tobytes()).hexdigest(),
45
+ "eligible": index < 3, "rejections": [] if index < 3 else ["tempo drift"],
46
+ "final_score": [0.3, 0.2, 0.2][index] if index < 3 else 0.5 + index / 100,
47
+ "source_correlation": 0.1,
48
+ "metrics": {"rms": 0.03, "clipped_fraction": 0.0, "tempo_bpm": 120.0,
49
+ "key": "C", "mode": "major", "stereo_width": 0.5},
50
+ })
51
+ profiles.append({"profile_sha256": f"{index:064x}", "finite": True})
52
+ source_decoded = sf.read(source, dtype="float32", always_2d=True)[0].T.copy()
53
+ manifest = {
54
+ "schema_version": "music3lab.reference-style-render.v1",
55
+ "capability": "reference_style_direct_latent_scorer_internal_text_bridge",
56
+ "reference": {
57
+ "source_audio_sha256": _sha(source),
58
+ "decoded_pcm_sha256": hashlib.sha256(source_decoded.astype("<f4").tobytes()).hexdigest(),
59
+ "tempo_bpm": 120.0, "key": "C", "mode": "major", "stereo_width": 0.5,
60
+ "profile": {"profile_sha256": "f" * 64},
61
+ },
62
+ "candidates": candidates,
63
+ "candidate_profiles": profiles,
64
+ "semantic_digest": "a" * 64,
65
+ }
66
+ (bundle / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")
67
+ return source, bundle
68
+
69
+
70
+ def test_seam_formula_is_bounded_deterministic_and_combines_both_terms() -> None:
71
+ x = np.zeros((2, rga.CROSSFADE_FRAMES), dtype=np.float32)
72
+ y = np.linspace(-0.2, 0.2, rga.CROSSFADE_FRAMES, dtype=np.float32)[None].repeat(2, 0)
73
+ first = rga.seam_cost(x, y)
74
+ second = rga.seam_cost(x, y)
75
+ assert first == second
76
+ assert first["seam_cost"] == pytest.approx(
77
+ 0.5 * (first["waveform_mismatch"] + first["first_difference_mismatch"])
78
+ )
79
+ assert all(0.0 <= value <= 1.0 for value in first.values())
80
+
81
+
82
+ def test_equal_power_append_has_exact_geometry_and_exact_outside_guard() -> None:
83
+ rng = np.random.default_rng(7)
84
+ source = rng.normal(0, 0.05, (2, 6000)).astype(np.float32)
85
+ candidate = rng.normal(0, 0.04, (2, rga.CANDIDATE_FRAMES)).astype(np.float32)
86
+ output = rga.equal_power_append(source, candidate)
87
+ assert output.shape == (2, 6000 + rga.CANDIDATE_FRAMES - rga.CROSSFADE_FRAMES)
88
+ assert np.array_equal(output[:, : 6000-rga.CROSSFADE_FRAMES], source[:, :-rga.CROSSFADE_FRAMES])
89
+ assert np.array_equal(output[:, 6000:], candidate[:, rga.CROSSFADE_FRAMES:])
90
+ assert np.array_equal(output[:, 6000-rga.CROSSFADE_FRAMES], source[:, -rga.CROSSFADE_FRAMES])
91
+ assert np.allclose(output[:, 5999], candidate[:, rga.CROSSFADE_FRAMES-1], atol=2e-7)
92
+
93
+
94
+ def test_ranking_uses_frozen_composite_and_candidate_index_tie() -> None:
95
+ records = [
96
+ {"index": 2, "eligible": True, "composite_score": 0.3},
97
+ {"index": 1, "eligible": True, "composite_score": 0.3},
98
+ {"index": 0, "eligible": False, "composite_score": 0.1},
99
+ ]
100
+ assert rga.select_evaluated(records)["index"] == 1
101
+
102
+
103
+ def test_manifest_source_and_candidate_swap_are_rejected(tmp_path: Path) -> None:
104
+ source, bundle = _fixture_bundle(tmp_path)
105
+ wrong_source = tmp_path / "wrong.wav"
106
+ sf.write(wrong_source, np.zeros((6000, 2), dtype=np.float32), rga.SAMPLE_RATE, subtype="PCM_16")
107
+ with pytest.raises(ValueError, match="provenance"):
108
+ rga.evaluate_bundle(source=wrong_source, bundle=bundle, negative="")
109
+ first = bundle / "candidate-00-seed-101.wav"
110
+ second = bundle / "candidate-01-seed-102.wav"
111
+ saved = first.read_bytes()
112
+ first.write_bytes(second.read_bytes())
113
+ with pytest.raises(ValueError, match="file hash"):
114
+ rga.evaluate_bundle(source=source, bundle=bundle, negative="")
115
+ first.write_bytes(saved)
116
+
117
+
118
+ def test_negative_truth_and_cli_surface(tmp_path: Path) -> None:
119
+ source, bundle = _fixture_bundle(tmp_path)
120
+ _, _, records, constraints, _ = rga.evaluate_bundle(
121
+ source=source, bundle=bundle, negative="no vocals, no clipping, no tempo drift"
122
+ )
123
+ status = {item["name"]: item["status"] for item in constraints.to_dict()["items"]}
124
+ assert status == {"vocals": "NOT_ENFORCEABLE", "clipping": "ENFORCEABLE", "tempo drift": "ENFORCEABLE"}
125
+ assert constraints.to_dict()["native_negative_prompt_used"] is False
126
+ assert [record["index"] for record in records if record["eligible"]] == [0, 1, 2]
127
+ args = build_parser().parse_args([
128
+ "reference-guided-append", "--audio", "a.wav", "--bundle", "b", "--output", "o.wav"
129
+ ])
130
+ assert args.config == "configs/reference-guided-append-v1.yaml" and not hasattr(args, "prompt")
131
+
132
+
133
+ def test_synthetic_end_to_end_roundtrip_and_retained_originals(tmp_path: Path) -> None:
134
+ source, bundle = _fixture_bundle(tmp_path)
135
+ result = rga.run_reference_guided_append(
136
+ source_audio=source, candidate_bundle=bundle, output=tmp_path / "joined.wav",
137
+ negative="no vocals, no clipping, no source copy",
138
+ config_path="configs/reference-guided-append-v1.yaml",
139
+ )
140
+ payload = json.loads(result.sidecar.read_text())
141
+ assert payload["status"] == "PASS" and len(payload["candidates"]) == 8
142
+ assert result.selected_index == 1
143
+ assert payload["geometry"]["net_appended_duration_seconds"] == pytest.approx(7.952834467120181)
144
+ assert payload["validation"]["float_wav_roundtrip_sample_exact"]
145
+ report_lines = result.report.read_text().splitlines()
146
+ assert all(any(line.startswith(f"| {index} |") for line in report_lines) for index in range(8))
147
+ assert _sha(result.evidence_bundle / "source-original.wav") == _sha(source)
148
+ assert _sha(result.evidence_bundle / "candidate-01-seed-102.wav") == _sha(bundle / "candidate-01-seed-102.wav")
149
+
150
+
151
+ def test_retained_real_bundle_integrates_when_present() -> None:
152
+ source = Path("/home/ubuntu/minimax-user-audio/incoming/loveonme_x_osh.wav")
153
+ bundle = Path("/home/ubuntu/minimax-reference-style-evidence/user-loveonme-f040ab1-seed101.reference-style")
154
+ if not source.exists() or not bundle.exists():
155
+ pytest.skip("retained measured bundle unavailable")
156
+ _, _, records, constraints, provenance = rga.evaluate_bundle(
157
+ source=source, bundle=bundle,
158
+ negative="no clipping, no source copy, no tempo drift, no vocals",
159
+ )
160
+ assert provenance["source"]["wav_sha256"] == "ff777c257a9f8044bbe08eb2933d6f4073a22770cf04ae527b8fe768982e6fea"
161
+ assert provenance["manifest_sha256"] == "2ada3a88bc57936810e7c8b8cf920d722225d438ca697745d9869ff4eeaa7485"
162
+ assert [record["index"] for record in records if record["eligible"]] == [0, 1, 2]
163
+ assert rga.select_evaluated(records)["index"] == 0
164
+ assert {item.name: item.status for item in constraints.items}["vocals"] == "NOT_ENFORCEABLE"
tests/test_reference_ranked_long_pool.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CPU-only contract for ranking the retained, preeligible long-form pool."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import importlib
7
+ from copy import deepcopy
8
+
9
+ import numpy as np
10
+ import pytest
11
+
12
+
13
+ rrp = importlib.import_module("music3lab.reference_ranked_pool")
14
+
15
+
16
+ def _sha(label: str) -> str:
17
+ return hashlib.sha256(label.encode("ascii")).hexdigest()
18
+
19
+
20
+ def _audio(value: float) -> np.ndarray:
21
+ # Toy finite 44.1 kHz stereo data: no file, model, or GPU is involved.
22
+ return np.full((2, 96), value, dtype=np.float32)
23
+
24
+
25
+ def _source() -> dict[str, object]:
26
+ return {
27
+ "id": "source-001", "path": "toy/source.wav",
28
+ "wav_sha256": _sha("source-wav"), "decoded_pcm_sha256": _sha("source-pcm"),
29
+ "audio": _audio(0.20), "sample_rate": 44100, "channels": 2,
30
+ "duration_seconds": 90.0, "tempo_bpm": 120.0, "key": "D", "mode": "minor",
31
+ "chroma": [1.0] + [0.0] * 11, "energy": 0.20, "stereo_width": 0.25,
32
+ }
33
+
34
+
35
+ def _candidate(identifier: str, index: int, value: float) -> dict[str, object]:
36
+ return {
37
+ "id": identifier, "index": index, "seed": 7100 + index,
38
+ "path": f"retained/{identifier}.wav", "wav_sha256": _sha(f"{identifier}-wav"),
39
+ "decoded_pcm_sha256": _sha(f"{identifier}-pcm"), "audio": _audio(value),
40
+ "sample_rate": 44100, "channels": 2, "duration_seconds": 90.0,
41
+ "preeligible_exact90": True, "early_eos": False, "finite": True,
42
+ "clipped_fraction": 0.0, "rms": 0.10, "source_correlation": 0.10,
43
+ "tempo_bpm": 120.0, "key": "D", "mode": "minor",
44
+ "chroma": [1.0] + [0.0] * 11, "energy": 0.20, "stereo_width": 0.25,
45
+ }
46
+
47
+
48
+ def _pool() -> list[dict[str, object]]:
49
+ return [_candidate("002", 2, 0.22), _candidate("003", 3, 0.24), _candidate("007", 7, 0.26)]
50
+
51
+
52
+ class _CpuScorer:
53
+ """Injected toy scorer; a production ranker must never replace it."""
54
+
55
+ device = "cpu"
56
+
57
+ def __init__(self) -> None:
58
+ self.calls: list[tuple[str, tuple[int, ...]]] = []
59
+
60
+ def profile(self, *, record: dict[str, object], crops: np.ndarray) -> np.ndarray:
61
+ assert self.device == "cpu"
62
+ assert crops.shape[0] == 8
63
+ assert not getattr(self, "generated", False)
64
+ assert not getattr(self, "trained", False)
65
+ self.calls.append((str(record["id"]), tuple(crops.shape)))
66
+ return np.full((3,), float(np.mean(crops)), dtype=np.float64)
67
+
68
+
69
+ def _rank(*, candidates: list[dict[str, object]], scorer: _CpuScorer | None = None):
70
+ return rrp.rank_retained_pool(
71
+ source=_source(), candidates=candidates, scorer=scorer or _CpuScorer(),
72
+ negative="no clipping, no source copy, no tempo drift, no vocals", require_tempo=True,
73
+ )
74
+
75
+
76
+ def test_retained_pool_is_exactly_three_preeligible_exact90_rows_and_preserves_identity() -> None:
77
+ scorer = _CpuScorer()
78
+ candidates = _pool()
79
+ result = _rank(candidates=candidates, scorer=scorer)
80
+
81
+ assert result.capability == "reference_ranked_long_form_pool_not_direct_audio_conditioning"
82
+ assert [row["id"] for row in result.candidates] == ["002", "003", "007"]
83
+ assert [row["path"] for row in result.candidates] == [item["path"] for item in candidates]
84
+ assert [row["wav_sha256"] for row in result.candidates] == [item["wav_sha256"] for item in candidates]
85
+ assert [row["decoded_pcm_sha256"] for row in result.candidates] == [item["decoded_pcm_sha256"] for item in candidates]
86
+ assert result.selected["id"] in {"002", "003", "007"}
87
+ assert result.selected["path"] == next(item["path"] for item in candidates if item["id"] == result.selected["id"])
88
+ assert result.selected_wav_sha256 == result.selected["wav_sha256"]
89
+ assert result.nonclaims == {
90
+ "artistic_quality": False, "native_style_transfer": False, "direct_audio_conditioning": False,
91
+ }
92
+
93
+ # Profiles must have an inventory of eight deterministic crops for source + every row.
94
+ assert [record_id for record_id, _ in scorer.calls] == ["source-001", "002", "003", "007"]
95
+ assert all(shape[0] == 8 for _, shape in scorer.calls)
96
+ assert result.profile_inventory["source-001"]["crop_count"] == 8
97
+ assert all(result.profile_inventory[item["id"]]["crop_count"] == 8 for item in candidates)
98
+
99
+
100
+ @pytest.mark.parametrize(
101
+ ("mutate", "match"),
102
+ [
103
+ (lambda rows: rows.__setitem__(0, {**rows[0], "preeligible_exact90": False}), "preeligible"),
104
+ (lambda rows: rows.__setitem__(0, {**rows[0], "duration_seconds": 90.0 + 2048 / 44100 + 0.01}), "duration"),
105
+ (lambda rows: rows.__setitem__(0, {**rows[0], "early_eos": True}), "early-eos"),
106
+ (lambda rows: rows.append(_candidate("004", 4, 0.28)), "unlisted"),
107
+ (lambda rows: rows.pop(), "exactly"),
108
+ ],
109
+ )
110
+ def test_raw_excess_early_eos_unlisted_or_incomplete_pool_is_rejected(mutate, match: str) -> None:
111
+ candidates = _pool()
112
+ mutate(candidates)
113
+ with pytest.raises(ValueError, match=match):
114
+ _rank(candidates=candidates)
115
+
116
+
117
+ def test_cpu_injected_ranking_keeps_f040_scores_gates_ties_and_negative_nonclaims() -> None:
118
+ candidates = _pool()
119
+ result = _rank(candidates=candidates)
120
+ repeat = _rank(candidates=deepcopy(candidates))
121
+
122
+ # f040 scorer weights: latent .42, tempo .18, chroma .10, energy .10, width .10;
123
+ # creativity is the .10 median eligible latent-distance bonus.
124
+ for row in result.candidates:
125
+ expected = (0.42 * row["latent_style_distance"] + 0.18 * min(row["tempo_octave_error"], 1.0)
126
+ + 0.10 * min(row["chroma_distance"], 1.0) + 0.10 * min(row["energy_log_error"], 1.0)
127
+ + 0.10 * min(row["stereo_width_log_error"], 1.0))
128
+ assert row["compatibility"] == pytest.approx(expected)
129
+ assert row["creativity_bonus"] == pytest.approx(0.10 * row["creativity_distance"])
130
+ assert row["finite"] and row["sample_rate"] == 44100 and row["channels"] == 2
131
+ assert abs(row["duration_seconds"] - 90.0) <= 2048 / 44100
132
+ assert row["clipped_fraction"] <= 0.05 and row["rms"] >= 1e-4
133
+ assert row["source_correlation"] < 0.75 and row["profile_finite"]
134
+ assert row["tempo_octave_error"] <= 0.20
135
+
136
+ assert result.selected["id"] == repeat.selected["id"]
137
+ assert result.tie_break == "(final_score, sha256(seed:wav_sha), index)"
138
+ negatives = result.negative_constraints
139
+ assert negatives["native_negative_prompt_used"] is False
140
+ assert negatives["items"]["vocals"]["status"] == "NOT_ENFORCEABLE"
141
+ assert all("cuda" not in value.casefold() and "h100" not in value.casefold() for value in result.execution.values())
142
+ assert result.execution == {"device": "cpu", "generated": False, "trained": False}
tests/test_reference_style_contract.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+
8
+ from music3lab import reference_style as rs
9
+ from music3lab.__main__ import build_parser
10
+
11
+
12
+ def _profile(value: float) -> rs.LatentProfile:
13
+ latent = np.full((2, 128, 86), value, dtype=np.float32)
14
+ latent[:, :, 1::2] += value * 0.25
15
+ return rs.LatentProfile.from_latents(latent)
16
+
17
+
18
+ def _reference() -> dict[str, object]:
19
+ return {
20
+ "source_audio_sha256": "a" * 64,
21
+ "decoded_pcm_sha256": "b" * 64,
22
+ "analysis_sha256": "c" * 64,
23
+ "tempo_bpm": 126.0, "tempo_confidence": 0.8,
24
+ "key": "D", "mode": "minor", "key_confidence": 0.5,
25
+ "energy_curve": [0.3, 0.4], "rms": 0.2,
26
+ "chroma": [1.0] + [0.0] * 11,
27
+ "filename": "PRIVATE-NAME.wav", "artist": "PRIVATE ARTIST",
28
+ }
29
+
30
+
31
+ def _observation(index: int, **updates: object) -> dict[str, object]:
32
+ value: dict[str, object] = {
33
+ "index": index, "seed": 101 + index,
34
+ "wav_sha256": f"{index + 1:064x}",
35
+ "decoded_pcm_sha256": f"{index + 100:064x}",
36
+ "tempo_bpm": 126.0, "key": "D", "mode": "minor",
37
+ "chroma": [1.0] + [0.0] * 11, "energy": 0.35,
38
+ "stereo_width": 0.25, "rms": 0.2, "clipped_fraction": 0.0,
39
+ "source_correlation": 0.1, "finite": True, "geometry_ok": True,
40
+ }
41
+ value.update(updates)
42
+ return value
43
+
44
+
45
+ def test_deterministic_equally_spaced_nonsilent_crops_and_short_padding() -> None:
46
+ audio = np.ones((2, 44032 * 10), dtype=np.float32) * 0.1
47
+ first = rs.select_profile_crops(audio)
48
+ second = rs.select_profile_crops(audio)
49
+ assert first.starts == second.starts and len(first.starts) == 8
50
+ assert first.starts[0] == 0 and first.starts[-1] == audio.shape[1] - 44032
51
+ short = rs.select_profile_crops(audio[:, :12000])
52
+ assert short.crops.shape == (1, 2, 44032) and short.padded_short_audio
53
+
54
+
55
+ def test_latent_profile_is_deterministic_and_sensitive_to_statistics() -> None:
56
+ a, b = _profile(0.2), _profile(0.7)
57
+ assert a.to_dict() == _profile(0.2).to_dict()
58
+ assert rs.latent_profile_distance(a, a) == 0.0
59
+ assert 0.0 < rs.latent_profile_distance(a, b) <= 1.0
60
+ assert len(a.mean) == len(a.std) == len(a.delta_std) == 128
61
+
62
+
63
+ def test_prompt_uses_measured_fields_only_and_cli_defaults_to_eight() -> None:
64
+ caption = rs._caption(_reference(), 0.3, seed=101, duration=8)
65
+ assert "private" not in caption.casefold() and "126.0" in caption
66
+ args = build_parser().parse_args([
67
+ "reference-style", "--audio", "x.wav", "--output", "y.wav",
68
+ "--negative", "no clipping, no vocals",
69
+ ])
70
+ assert args.duration == 8 and args.candidates == 8 and args.seed == 101
71
+ assert not hasattr(args, "prompt") and not hasattr(args, "lyrics")
72
+
73
+
74
+ def test_gate_order_and_point_seven_five_anti_copy() -> None:
75
+ observations = [
76
+ _observation(0),
77
+ _observation(1, finite=False, geometry_ok=False, clipped_fraction=0.2,
78
+ rms=0.0, wav_sha256=f"{1:064x}",
79
+ decoded_pcm_sha256="b" * 64, source_correlation=0.75,
80
+ tempo_bpm=90.0, key="C"),
81
+ ]
82
+ records = rs.score_candidates(
83
+ reference_analysis=_reference(), reference_profile=_profile(0.2),
84
+ reference_width=0.25, reference_pcm_sha256="b" * 64,
85
+ observations=observations, profiles=[_profile(0.25), None],
86
+ negatives=rs.parse_negative_constraints("no tempo drift, no key drift"),
87
+ )
88
+ assert records[0].eligible
89
+ assert records[1].rejections == (
90
+ "nonfinite", "wrong geometry", "clipping", "silence", "duplicate bytes",
91
+ "exact source PCM", "copy source", "nonfinite profile", "tempo drift", "key drift",
92
+ )
93
+
94
+
95
+ def test_negative_classification_preserves_every_unmatched_clause() -> None:
96
+ parsed = rs.parse_negative_constraints(
97
+ "no clipping, no source copy, no tempo drift, no key drift, "
98
+ "no mono/stereo collapse, no vocals, no genre, dark mood, no artist, no lyrics, no AI sound"
99
+ ).to_dict()
100
+ statuses = {item["name"]: item["status"] for item in parsed["items"]}
101
+ assert all(statuses[name] == "ENFORCEABLE" for name in (
102
+ "clipping", "copy source", "tempo drift", "key drift", "stereo collapse"
103
+ ))
104
+ assert all(statuses[name] == "NOT_ENFORCEABLE" for name in (
105
+ "vocals", "no genre", "dark mood", "no artist", "no lyrics", "no ai sound"
106
+ ))
107
+ assert parsed["native_negative_prompt_used"] is False
108
+
109
+
110
+ def test_diversity_bonus_never_selects_ineligible_candidate() -> None:
111
+ observations = [_observation(0), _observation(1, source_correlation=0.80), _observation(2)]
112
+ records = rs.score_candidates(
113
+ reference_analysis=_reference(), reference_profile=_profile(0.2),
114
+ reference_width=0.25, reference_pcm_sha256="b" * 64,
115
+ observations=observations, profiles=[_profile(0.2), _profile(0.9), _profile(0.3)],
116
+ negatives=rs.parse_negative_constraints(""),
117
+ )
118
+ assert records[1].creativity_bonus == 0.0 and not records[1].eligible
119
+ assert rs.select_candidate(records, seed=101).index in (0, 2)
120
+
121
+
122
+ def test_exact_weights_and_scorer_role_are_explicit() -> None:
123
+ records = rs.score_candidates(
124
+ reference_analysis=_reference(), reference_profile=_profile(0.2),
125
+ reference_width=0.25, reference_pcm_sha256="b" * 64,
126
+ observations=[_observation(0)], profiles=[_profile(0.4)],
127
+ negatives=rs.parse_negative_constraints(""),
128
+ )
129
+ record = records[0]
130
+ expected = (0.42 * record.latent_style_distance + 0.18 * record.tempo_octave_error
131
+ + 0.10 * record.chroma_distance + 0.10 * record.energy_log_error
132
+ + 0.10 * record.stereo_width_log_error)
133
+ assert np.isclose(record.compatibility, expected)
134
+ loaded = rs.load_reference_style_config("configs/reference-style-v1.yaml")
135
+ assert loaded.config.specialist_role == rs.SPECIALIST_ROLE
136
+ assert loaded.config.specialist_checkpoint_sha256 == rs.SPECIALIST_SHA256
137
+
138
+
139
+ def test_mocked_path_makes_eight_seeded_calls_and_selects_automatically(tmp_path: Path) -> None:
140
+ class Pipeline:
141
+ def __init__(self) -> None: self.calls: list[dict[str, object]] = []
142
+ def __call__(self, **kwargs: object) -> np.ndarray:
143
+ self.calls.append(kwargs)
144
+ seed = int(kwargs["seed"])
145
+ t = np.arange(44100 * 8, dtype=np.float32) / 44100
146
+ left = 0.08 * np.sin(2 * np.pi * (220 + seed) * t)
147
+ right = 0.07 * np.sin(2 * np.pi * (223 + seed) * t)
148
+ return np.stack((left, right))
149
+ class Scorer:
150
+ def profile(self, audio: np.ndarray) -> tuple[rs.LatentProfile, rs.CropSelection]:
151
+ crops = rs.select_profile_crops(audio)
152
+ rms = float(np.sqrt(np.mean(crops.crops.astype(np.float64) ** 2)))
153
+ return _profile(rms + 0.1), crops
154
+ def identity(self) -> dict[str, object]:
155
+ return {"role": rs.SPECIALIST_ROLE, "checkpoint_sha256": rs.SPECIALIST_SHA256}
156
+ source_t = np.arange(44100 * 9, dtype=np.float32) / 44100
157
+ source = np.stack((0.1 * np.sin(2*np.pi*110*source_t), 0.1 * np.sin(2*np.pi*113*source_t)))
158
+ pipeline = Pipeline()
159
+ result = rs.generate_reference_style(
160
+ pipeline=pipeline, scorer=Scorer(), source_audio=source,
161
+ reference_analysis=_reference(), duration_seconds=8, candidates=8,
162
+ seed=101, negative="no clipping, no source copy, no vocals",
163
+ output=tmp_path / "selected.wav",
164
+ )
165
+ assert [call["seed"] for call in pipeline.calls] == list(range(101, 109))
166
+ assert result.output.exists() and result.selected.eligible
167
+ payload = json.loads(result.sidecar.read_text())
168
+ assert len(payload["candidates"]) == 8
169
+ assert len(payload["candidate_profiles"]) == 8
170
+ assert all(profile["finite"] for profile in payload["candidate_profiles"])
171
+ assert payload["telemetry"]["reference_profile_generation_scoring_seconds"] > 0
172
+ assert payload["scorer"]["role"] == rs.SPECIALIST_ROLE
173
+ assert payload["negative_constraints"]["native_negative_prompt_used"] is False
tests/test_release_preflight.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import subprocess
7
+ from pathlib import Path
8
+
9
+ import pytest
10
+ import yaml
11
+
12
+ from music3lab.release import wrapper_preflight
13
+
14
+
15
+ ROOT = Path(__file__).resolve().parents[1]
16
+ SYSTEM_PYTHON = Path("/usr/bin/python3")
17
+ MODEL_REVISION = "fbdf52fbaaca799592917417eb05f1899f1255ec"
18
+ DIFFUSERS_REVISION = "90b4e34e79a86ec5e7f2437634fe95ecd2108796"
19
+ BASE_ID = "05c0cdd43a6374b6959cd561e8de4cd6a3327133f8763312d41b1d2b6549c53d"
20
+
21
+
22
+ def _sha(path: Path) -> str:
23
+ return hashlib.sha256(path.read_bytes()).hexdigest()
24
+
25
+
26
+ def _fixtures(tmp_path: Path) -> dict[str, object]:
27
+ source = tmp_path / "source.wav"
28
+ source.write_bytes(b"RIFF-static-preflight")
29
+ bundle = tmp_path / "bundle.reference-style"
30
+ bundle.mkdir()
31
+ candidates = []
32
+ for index in range(8):
33
+ seed = 101 + index
34
+ (bundle / f"candidate-{index:02d}-seed-{seed}.wav").write_bytes(
35
+ f"candidate-{index}".encode()
36
+ )
37
+ candidates.append({"index": index, "seed": seed})
38
+ (bundle / "manifest.json").write_text(json.dumps({
39
+ "schema_version": "music3lab.reference-style-render.v1",
40
+ "capability": "reference_style_direct_latent_scorer_internal_text_bridge",
41
+ "reference": {"source_audio_sha256": _sha(source)},
42
+ "candidates": candidates,
43
+ "candidate_profiles": [{} for _ in range(8)],
44
+ }))
45
+
46
+ checkpoint = tmp_path / "checkpoint"
47
+ checkpoint.mkdir()
48
+ state = checkpoint / "state.safetensors"
49
+ state.write_bytes(b"static-checkpoint-state")
50
+ state_sha = _sha(state)
51
+ (checkpoint / "manifest.json").write_text(json.dumps({
52
+ "schema_version": "music3lab.full-state-resume.v1",
53
+ "checkpoint_after_frame": 299,
54
+ "checkpoint_before_pending_feedback": True,
55
+ "sequence_length": 404,
56
+ "layer_count": 36,
57
+ "safetensors_sha256": state_sha,
58
+ "execution_policy": {
59
+ "policy_name": "production_deterministic_from_frame0",
60
+ "deterministic_algorithms": True,
61
+ "native_sdpa": False,
62
+ "dtype": "bfloat16",
63
+ },
64
+ }))
65
+ prefix = tmp_path / "prefix.safetensors"
66
+ specialist = tmp_path / "specialist.safetensors"
67
+ prefix.write_bytes(b"static-prefix")
68
+ specialist.write_bytes(b"static-specialist")
69
+ captured_config = yaml.safe_load(
70
+ (ROOT / "configs/captured-state-style-continuation-v1.yaml").read_bytes()
71
+ )
72
+ captured_config["checkpoint_state_sha256"] = state_sha
73
+ captured_config["prefix_fused_bundle_sha256"] = _sha(prefix)
74
+ captured_config["specialist_checkpoint_sha256"] = _sha(specialist)
75
+ captured_config_path = tmp_path / "captured.yaml"
76
+ captured_config_path.write_text(yaml.safe_dump(captured_config, sort_keys=False))
77
+
78
+ snapshot = tmp_path / "snapshot"
79
+ diffusers = tmp_path / "diffusers"
80
+ snapshot.mkdir()
81
+ diffusers.mkdir()
82
+ base_manifest = tmp_path / "base.json"
83
+ base_manifest.write_text(json.dumps({
84
+ "schema_version": "music3lab.base-freeze.v1",
85
+ "model_id": "MiniMaxAI/MiniMax-Music3",
86
+ "revision": MODEL_REVISION,
87
+ "semantic_digest": BASE_ID,
88
+ }))
89
+ return {
90
+ "source": source,
91
+ "bundle": bundle,
92
+ "checkpoint": checkpoint,
93
+ "prefix": prefix,
94
+ "specialist": specialist,
95
+ "captured_config": captured_config_path,
96
+ "snapshot": snapshot,
97
+ "base_manifest": base_manifest,
98
+ "diffusers": diffusers,
99
+ }
100
+
101
+
102
+ def _append_arguments(items: dict[str, object], tmp_path: Path) -> list[str]:
103
+ return [
104
+ "--audio", str(items["source"]),
105
+ "--bundle", str(items["bundle"]),
106
+ "--output", str(tmp_path / "append-output.wav"),
107
+ ]
108
+
109
+
110
+ def _captured_arguments(items: dict[str, object], tmp_path: Path) -> list[str]:
111
+ return [
112
+ "--checkpoint", str(items["checkpoint"]),
113
+ "--prefix-bundle", str(items["prefix"]),
114
+ "--specialist-checkpoint", str(items["specialist"]),
115
+ "--flow-config", str(ROOT / "configs/flow-encoder-v1.yaml"),
116
+ "--snapshot", str(items["snapshot"]),
117
+ "--base-manifest", str(items["base_manifest"]),
118
+ "--diffusers-root", str(items["diffusers"]),
119
+ "--output", str(tmp_path / "captured-output"),
120
+ "--ffmpeg", "/usr/bin/ffmpeg",
121
+ ]
122
+
123
+
124
+ def test_both_new_static_preflights_are_cpu_only(tmp_path: Path) -> None:
125
+ items = _fixtures(tmp_path)
126
+ append = wrapper_preflight(
127
+ project_root=ROOT,
128
+ capability="reference-guided-append",
129
+ config=ROOT / "configs/reference-guided-append-v1.yaml",
130
+ arguments=_append_arguments(items, tmp_path),
131
+ execute=False,
132
+ )
133
+ captured = wrapper_preflight(
134
+ project_root=ROOT,
135
+ capability="captured-style-continue",
136
+ config=items["captured_config"],
137
+ arguments=_captured_arguments(items, tmp_path),
138
+ execute=False,
139
+ )
140
+ for payload in (append, captured):
141
+ assert payload["mode"] == "preflight"
142
+ assert payload["checks"]["status"] == "PASS"
143
+ assert payload["checks"]["kind"] == "static_cpu_only"
144
+ assert payload["checks"]["models_loaded"] is False
145
+ assert payload["checks"]["gpu_accessed"] is False
146
+ assert payload["command"][2:4] == ["--config", str(Path(payload["config"]))]
147
+ assert append["checks"]["candidate_files"] == 8
148
+ assert captured["checks"]["static_geometry"] == {
149
+ "prefix_frames": 300,
150
+ "new_frames": 100,
151
+ "output_samples": 705600,
152
+ "cache_sequence_length": 404,
153
+ "layer_count": 36,
154
+ }
155
+
156
+
157
+ @pytest.mark.parametrize(
158
+ "command", (
159
+ "reference-ranked-pool", "reference-guided-append",
160
+ "captured-style-continue",
161
+ )
162
+ )
163
+ def test_bare_system_python_help_imports_no_audio_or_model_extras(command: str) -> None:
164
+ if not SYSTEM_PYTHON.exists():
165
+ pytest.skip("bare system Python unavailable")
166
+ code = (
167
+ "import runpy,sys;"
168
+ f"sys.argv=['music3lab','{command}','--help'];"
169
+ "\ntry: runpy.run_module('music3lab',run_name='__main__')"
170
+ "\nexcept SystemExit as e: assert e.code == 0"
171
+ "\nassert 'soundfile' not in sys.modules"
172
+ "\nassert 'torch' not in sys.modules"
173
+ )
174
+ completed = subprocess.run(
175
+ [str(SYSTEM_PYTHON), "-c", code],
176
+ cwd=ROOT,
177
+ env={**os.environ, "PYTHONPATH": str(ROOT / "src")},
178
+ text=True,
179
+ capture_output=True,
180
+ check=False,
181
+ )
182
+ assert completed.returncode == 0, completed.stderr
183
+
184
+
185
+ def test_retained_ranker_static_preflight_is_dependency_light_and_cpu_only() -> None:
186
+ config = ROOT / "configs/reference-ranked-pool-v1.yaml"
187
+ raw = yaml.safe_load(config.read_bytes())
188
+ if not Path(raw["source_audio"]).is_file():
189
+ pytest.skip("authoritative retained-pool artifacts unavailable")
190
+ payload = wrapper_preflight(
191
+ project_root=ROOT,
192
+ capability="reference-ranked-pool",
193
+ config=config,
194
+ arguments=[],
195
+ execute=False,
196
+ )
197
+ checks = payload["checks"]
198
+ assert checks["status"] == "PASS"
199
+ assert checks["kind"] == "static_cpu_only"
200
+ assert checks["models_loaded"] is False
201
+ assert checks["gpu_accessed"] is False
202
+ assert checks["generation"] is False
203
+ assert checks["training"] is False
204
+ assert checks["post_generation_only"] is True
205
+ assert checks["native_tokens"] is False
206
+ assert checks["direct_model_audio_conditioning"] is False
207
+ assert checks["semantic_style_transfer"] is False
208
+ assert checks["artistic_quality_claim"] is False
209
+ assert checks["native_negative_prompt_used"] is False
210
+ assert checks["vocal_exclusion"] == "NOT_ENFORCEABLE"
211
+ assert checks["candidate_wav_sha256"]["007"] == (
212
+ "d5cbd5c920745e106b14aaf6659d95255f8b0f8d73a8b9f97ab47ecc00f72207"
213
+ )
214
+ assert Path(payload["command"][0]).resolve() == SYSTEM_PYTHON.resolve()
215
+
216
+
217
+ def test_bare_system_python_runs_both_static_preflights(tmp_path: Path) -> None:
218
+ if not SYSTEM_PYTHON.exists():
219
+ pytest.skip("bare system Python unavailable")
220
+ items = _fixtures(tmp_path)
221
+ commands = [
222
+ [
223
+ "preflight", "reference-guided-append",
224
+ "--config", str(ROOT / "configs/reference-guided-append-v1.yaml"),
225
+ "--project-root", str(ROOT),
226
+ *_append_arguments(items, tmp_path),
227
+ ],
228
+ [
229
+ "preflight", "captured-style-continue",
230
+ "--config", str(items["captured_config"]),
231
+ "--project-root", str(ROOT),
232
+ *_captured_arguments(items, tmp_path),
233
+ ],
234
+ ]
235
+ code = (
236
+ "import sys;"
237
+ "from music3lab.__main__ import main;"
238
+ f"commands={commands!r};"
239
+ "\nfor command in commands: assert main(command) == 0"
240
+ "\nassert 'soundfile' not in sys.modules"
241
+ "\nassert 'torch' not in sys.modules"
242
+ )
243
+ completed = subprocess.run(
244
+ [str(SYSTEM_PYTHON), "-c", code],
245
+ cwd=ROOT,
246
+ env={**os.environ, "PYTHONPATH": str(ROOT / "src")},
247
+ text=True,
248
+ capture_output=True,
249
+ check=False,
250
+ )
251
+ assert completed.returncode == 0, completed.stderr
252
+ lines = [json.loads(line) for line in completed.stdout.splitlines()]
253
+ assert [line["checks"]["status"] for line in lines] == ["PASS", "PASS"]
tests/test_release_surface.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+ import pytest
8
+ import soundfile as sf
9
+ import torch
10
+ from safetensors.torch import load_file, save_file
11
+
12
+ from music3lab.__main__ import main
13
+ from music3lab.codec.flow_encoder import ContinuousFlowEncoder, load_flow_encoder_config
14
+ from music3lab.release import CAPABILITIES, encode_continuous_flow_latent, wrapper_preflight
15
+
16
+
17
+ ROOT = Path(__file__).resolve().parents[1]
18
+
19
+
20
+ def test_status_json_is_truthful_and_machine_readable(capsys: pytest.CaptureFixture[str]) -> None:
21
+ assert main(["status", "--json"]) == 0
22
+ payload = json.loads(capsys.readouterr().out)
23
+ caps = payload["capabilities"]
24
+ assert caps == CAPABILITIES
25
+ assert caps["continuous_encode"]["native_rvq"] is False
26
+ assert caps["prompt_free"]["null_conditioning"] is False
27
+ assert caps["native_state_stage0"]["status"] == "one_clip_alignment_pass_not_tokenizer"
28
+ assert caps["native_state_stage0"]["native_encoder"] is False
29
+ assert caps["native_state_multiclip"]["status"] == "experimental_functional_fail"
30
+ assert caps["native_state_c0_distill"]["status"] == "bounded_captured_multiclip_pass"
31
+ assert caps["native_state_c0_distill"]["native_tokenizer"] is False
32
+ assert caps["native_stage1_residual"]["mean_cross_entropy"] == 6.83402695
33
+ assert caps["native_stage1_residual"]["exact_full_rows"] == 0
34
+ assert caps["captured_style_continuation"]["status"] == "available_captured_state_only"
35
+ assert caps["captured_style_continuation"]["arbitrary_wav"] is False
36
+ assert caps["reference_guided_append"]["status"] == "available_cpu"
37
+ assert caps["reference_guided_append"]["model_or_gpu_run"] is False
38
+ ranker = caps["reference_ranked_long_form_pool"]
39
+ assert ranker["status"] == "available_cpu_only_retained_pool_ranker"
40
+ assert ranker["candidate_generation"] is False
41
+ assert ranker["direct_model_audio_conditioning"] is False
42
+ assert ranker["semantic_style_transfer"] is False
43
+ assert ranker["artistic_quality_claim"] is False
44
+ assert ranker["native_tokens"] is False
45
+ assert ranker["vocal_exclusion"] == "NOT_ENFORCEABLE"
46
+ for key in ("arbitrary_wav_continuation", "arbitrary_wav_fim", "arbitrary_wav_prepend"):
47
+ assert caps[key]["status"] == "experimental_functional_fail"
48
+ for key in (
49
+ "acoustic_fim_v2", "waveform_causal_continuation",
50
+ "waveform_right_context_prepend",
51
+ ):
52
+ assert caps[key]["status"] == "experimental_functional_fail"
53
+ assert caps[key]["available"] is False
54
+
55
+
56
+ def test_continuous_encode_emits_real_latent_and_metadata(tmp_path: Path) -> None:
57
+ config_path = ROOT / "configs" / "flow-encoder-v1.yaml"
58
+ config = load_flow_encoder_config(config_path).config
59
+ torch.manual_seed(7)
60
+ encoder = ContinuousFlowEncoder(config.model, latent_mean=config.loss.latent_mean)
61
+ checkpoint = tmp_path / "encoder.safetensors"
62
+ save_file({k: v.detach().cpu() for k, v in encoder.state_dict().items()}, checkpoint)
63
+ audio = tmp_path / "source.wav"
64
+ sf.write(audio, np.zeros((44032, 2), dtype=np.float32), 44100, subtype="FLOAT")
65
+ output = tmp_path / "latent.safetensors"
66
+ payload = encode_continuous_flow_latent(
67
+ audio=audio, checkpoint=checkpoint, output=output, config=config_path
68
+ )
69
+ latent = load_file(output)["continuous_flow_latent"]
70
+ assert tuple(latent.shape) == (1, 128, 86)
71
+ assert torch.isfinite(latent).all()
72
+ assert payload["native_rvq"] is False
73
+ metadata = json.loads((tmp_path / "latent.safetensors.json").read_text())
74
+ assert metadata["output_sha256"] == payload["output_sha256"]
75
+
76
+
77
+ def test_continuous_encode_rejects_noncanonical_audio(tmp_path: Path) -> None:
78
+ audio = tmp_path / "bad.wav"
79
+ sf.write(audio, np.zeros((44032, 1), dtype=np.float32), 44100)
80
+ checkpoint = tmp_path / "empty.safetensors"
81
+ checkpoint.touch()
82
+ with pytest.raises(ValueError, match="canonical"):
83
+ encode_continuous_flow_latent(
84
+ audio=audio,
85
+ checkpoint=checkpoint,
86
+ output=tmp_path / "x.safetensors",
87
+ config=ROOT / "configs" / "flow-encoder-v1.yaml",
88
+ )
89
+
90
+
91
+ @pytest.mark.parametrize(
92
+ ("capability", "config"),
93
+ [
94
+ ("generate", "prompt-free-v1.yaml"),
95
+ ("sample", "sample-bridge-v1.yaml"),
96
+ ("captured-continue", "continuation-tier-a.yaml"),
97
+ ("full-state-continue", "continuation-tier-a.yaml"),
98
+ ("continue", "audio-continuation-v1.yaml"),
99
+ ("inpaint", "audio-fim-v1.yaml"),
100
+ ("prepend", "audio-prepend-v1.yaml"),
101
+ ("evaluate", "objective-only-v1.yaml"),
102
+ ("self-improve", "autonomous-interim678-v1.yaml"),
103
+ ],
104
+ )
105
+ def test_every_release_delegate_preflights(capability: str, config: str) -> None:
106
+ payload = wrapper_preflight(
107
+ project_root=ROOT,
108
+ capability=capability,
109
+ config=ROOT / "configs" / config,
110
+ arguments=["--", "--help"],
111
+ execute=False,
112
+ )
113
+ assert payload["mode"] == "preflight"
114
+ assert Path(payload["script"]).is_file()
115
+ assert payload["command"][-1] == "--help"
116
+
117
+
118
+ def test_cli_preflight_prints_delegate(capsys: pytest.CaptureFixture[str]) -> None:
119
+ assert main([
120
+ "preflight", "inpaint", "--config", str(ROOT / "configs" / "audio-fim-v1.yaml"),
121
+ "--project-root", str(ROOT),
122
+ ]) == 0
123
+ payload = json.loads(capsys.readouterr().out)
124
+ assert payload["capability"] == "inpaint"
125
+ assert payload["mode"] == "preflight"
tests/test_sample_bridge_contract.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CPU contract for the deferred WAV/sample-to-Music3 internal text bridge.
2
+
3
+ This is intentionally expected-red until ``music3lab.sample_bridge`` exists.
4
+ It defines a MIR-conditioned compatibility bridge, not direct audio embeddings,
5
+ full style matching, or a reconstruction/copyright claim.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from pathlib import Path
11
+
12
+ import numpy as np
13
+
14
+ from music3lab import sample_bridge
15
+ from music3lab.__main__ import build_parser
16
+
17
+
18
+ def _reference_raw() -> dict[str, object]:
19
+ return {
20
+ "source_audio_sha256": "a" * 64,
21
+ "tempo_bpm": 126.0,
22
+ "key": "D",
23
+ "mode": "minor",
24
+ "energy_curve": [0.40, 0.56, 0.72, 0.68],
25
+ # Deliberate metadata traps: this API must not use them.
26
+ "filename": "private-song-final-v9.wav",
27
+ "title": "PRIVATE TITLE MUST NOT LEAK",
28
+ "artist": "PRIVATE ARTIST MUST NOT LEAK",
29
+ "tags": ["PRIVATE TAG MUST NOT LEAK"],
30
+ }
31
+
32
+
33
+ def _candidate(
34
+ digest: str,
35
+ *,
36
+ tempo: float = 126.0,
37
+ key: str = "D",
38
+ mode: str = "minor",
39
+ energy: float = 0.62,
40
+ clipped_fraction: float = 0.0,
41
+ silence: bool = False,
42
+ ) -> dict[str, object]:
43
+ return {
44
+ "candidate_sha256": digest * 64,
45
+ "tempo_bpm": tempo,
46
+ "key": key,
47
+ "mode": mode,
48
+ "energy": energy,
49
+ "clipped_fraction": clipped_fraction,
50
+ "silence": silence,
51
+ }
52
+
53
+
54
+ def test_reference_plan_uses_only_measured_mir_and_internal_instrumental_text() -> None:
55
+ conditioning = sample_bridge.AudioConditioning.from_analysis(_reference_raw())
56
+ plan = sample_bridge.derive_reference_plan(
57
+ conditioning, duration_seconds=12, seed=17
58
+ )
59
+ payload = plan.to_dict()
60
+ encoded = json.dumps(payload, sort_keys=True).lower()
61
+ assert "private" not in encoded and "filename" not in encoded and "artist" not in encoded
62
+ assert payload["source_audio_sha256"] == "a" * 64
63
+ assert payload["tempo_bpm"] == 126.0 and payload["key"] == "D"
64
+ assert payload["mode"] == "minor" and payload["energy"] == 0.59
65
+ assert payload["lyrics"] == "[instrumental]" and payload["caption"]
66
+ assert payload["capability"] == "mir_conditioned_internal_text_bridge_not_direct_audio_embedding"
67
+
68
+
69
+ def test_negative_constraints_are_explicitly_enforceable_or_not_enforceable() -> None:
70
+ parsed = sample_bridge.parse_negative_constraints(
71
+ "clipping, silence, tempo drift, key drift, copy source, vocals, nebulous thing"
72
+ )
73
+ payload = parsed.to_dict()
74
+ statuses = {item["name"]: item["status"] for item in payload["items"]}
75
+ assert {"clipping", "silence", "tempo drift", "key drift", "copy source"} <= set(statuses)
76
+ assert all(statuses[name] == "ENFORCEABLE" for name in {
77
+ "clipping", "silence", "tempo drift", "key drift", "copy source"
78
+ })
79
+ assert statuses["vocals"] == "NOT_ENFORCEABLE"
80
+ assert statuses["nebulous thing"] == "NOT_ENFORCEABLE"
81
+
82
+
83
+ def test_candidate_scoring_enforces_technical_floors_and_rejects_source_copy() -> None:
84
+ reference = sample_bridge.derive_reference_plan(
85
+ sample_bridge.AudioConditioning.from_analysis(_reference_raw()),
86
+ duration_seconds=8,
87
+ seed=1,
88
+ )
89
+ negatives = sample_bridge.parse_negative_constraints("clipping, silence, copy source")
90
+ records = sample_bridge.score_candidates(
91
+ reference,
92
+ [
93
+ _candidate("b"),
94
+ _candidate("a", clipped_fraction=0.10),
95
+ _candidate("a", silence=True),
96
+ {**_candidate("c"), "candidate_sha256": "a" * 64},
97
+ ],
98
+ negatives=negatives,
99
+ )
100
+ assert records[0].eligible is True and np.isfinite(records[0].score)
101
+ assert records[1].eligible is False and "clipping" in records[1].rejections
102
+ assert records[2].eligible is False and "silence" in records[2].rejections
103
+ assert records[3].eligible is False and "copy source" in records[3].rejections
104
+
105
+
106
+ def test_selection_is_seeded_and_rejects_duplicate_content_without_human_input() -> None:
107
+ reference = sample_bridge.derive_reference_plan(
108
+ sample_bridge.AudioConditioning.from_analysis(_reference_raw()),
109
+ duration_seconds=8,
110
+ seed=4,
111
+ )
112
+ candidates = [_candidate("b"), _candidate("b"), _candidate("c", tempo=98.0)]
113
+ first = sample_bridge.select_candidate(reference, candidates, seed=91)
114
+ second = sample_bridge.select_candidate(reference, candidates, seed=91)
115
+ assert first.to_dict() == second.to_dict()
116
+ assert first.candidate_sha256 == "b" * 64
117
+ assert first.duplicate_count == 1
118
+
119
+
120
+ def test_mocked_sampling_pipeline_receives_only_derived_internal_text(tmp_path: Path) -> None:
121
+ class Pipeline:
122
+ def __init__(self) -> None:
123
+ self.calls: list[dict[str, object]] = []
124
+
125
+ def __call__(self, **kwargs: object) -> np.ndarray:
126
+ self.calls.append(kwargs)
127
+ return np.zeros((2, 44_100), dtype=np.float32)
128
+
129
+ pipeline = Pipeline()
130
+ result = sample_bridge.sample_from_audio(
131
+ pipeline=pipeline,
132
+ conditioning=sample_bridge.AudioConditioning.from_analysis(_reference_raw()),
133
+ candidates=[_candidate("b")],
134
+ duration_seconds=1,
135
+ seed=3,
136
+ negative="copy source, clipping",
137
+ output=tmp_path / "new-song.wav",
138
+ )
139
+ call = pipeline.calls[0]
140
+ assert call["prompt"] and call["lyrics"] == "[instrumental]"
141
+ assert "private" not in json.dumps(call, sort_keys=True).lower()
142
+ assert result.output == tmp_path / "new-song.wav"
143
+ assert result.plan.capability == "mir_conditioned_internal_text_bridge_not_direct_audio_embedding"
144
+
145
+
146
+ def test_sample_cli_accepts_audio_controls_but_no_prompt_or_lyrics() -> None:
147
+ args = build_parser().parse_args(
148
+ [
149
+ "sample", "--audio", "reference.wav", "--duration", "12",
150
+ "--output", "new.wav", "--negative", "clipping, copy source",
151
+ "--candidates", "4", "--seed", "17",
152
+ ]
153
+ )
154
+ assert (args.audio, args.duration, args.output, args.candidates, args.seed) == (
155
+ "reference.wav", 12, "new.wav", 4, 17
156
+ )
157
+ assert args.negative == "clipping, copy source"
158
+ assert not hasattr(args, "prompt") and not hasattr(args, "lyrics")
tests/test_vocoder_phase2.py ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import os
5
+ from pathlib import Path
6
+
7
+ import pytest
8
+ import soundfile as sf
9
+ import torch
10
+
11
+ import music3lab.vocoder as vocoder_module
12
+ from music3lab.checkpoint_audit_schema import (
13
+ BASE_ID,
14
+ CONVERTER_SHA256,
15
+ DIFFUSERS_REVISION,
16
+ MODEL_REVISION,
17
+ )
18
+ from music3lab.manifests import ArtifactRecord, semantic_digest
19
+ from music3lab.vocoder import (
20
+ VOCODER_SOURCE_SHA256,
21
+ DifferentiableFrozenVocoder,
22
+ FlowVocoderLatents,
23
+ FrozenVocoderLoadReport,
24
+ LatentGradientProbe,
25
+ OracleChunk,
26
+ OracleDescriptor,
27
+ VocoderReplayManifest,
28
+ crop_and_stitch,
29
+ deterministic_float_wav_bytes,
30
+ load_frozen_vocoder,
31
+ load_phase0_vocoder_oracle,
32
+ probe_latent_gradient,
33
+ publish_replay_session_root,
34
+ verify_replay_session_tree,
35
+ )
36
+
37
+
38
+ def _report() -> FrozenVocoderLoadReport:
39
+ return FrozenVocoderLoadReport.create(
40
+ base_id=BASE_ID,
41
+ model_revision=MODEL_REVISION,
42
+ diffusers_revision=DIFFUSERS_REVISION,
43
+ converter_sha256=CONVERTER_SHA256,
44
+ implementation_sha256=VOCODER_SOURCE_SHA256,
45
+ dav_file_sha256="1" * 64,
46
+ project_git_commit="4" * 40,
47
+ project_source_sha256="5" * 64,
48
+ project_git_dirty=False,
49
+ converted_vocoder_file_sha256="2" * 64,
50
+ raw_tensor_count=548,
51
+ raw_numel=122_904_034,
52
+ mapped_tensor_count=121,
53
+ known_unmapped_tensor_count=427,
54
+ unknown_tensor_count=0,
55
+ target_tensor_count=121,
56
+ exact_target_count=121,
57
+ mapping_semantic_digest="3" * 64,
58
+ )
59
+
60
+
61
+ def _tiny_adapter() -> DifferentiableFrozenVocoder:
62
+ from diffusers.models.autoencoders.minimax_music3_vocoder import (
63
+ MiniMaxMusic3Vocoder,
64
+ )
65
+
66
+ model = MiniMaxMusic3Vocoder(
67
+ latent_channels=4,
68
+ decoder_input_dim=8,
69
+ decoder_hidden_dim=16,
70
+ upsampling_ratios=(2,),
71
+ sampling_rate=44_100,
72
+ )
73
+ return DifferentiableFrozenVocoder(model, _report())
74
+
75
+
76
+ def _chunk(index: int, *, left: int, right: int) -> OracleChunk:
77
+ return OracleChunk(
78
+ index=index,
79
+ latent_key=f"chunks.{index}.final_latents",
80
+ latent_shape=(1, 4, 3),
81
+ latent_dtype="float32",
82
+ latent_content_sha256=str(index + 1) * 64,
83
+ latent_length=3,
84
+ crop_left_latent_frames=left,
85
+ crop_right_latent_frames=right,
86
+ crop_left_samples=left * 2,
87
+ crop_right_samples=right * 2,
88
+ )
89
+
90
+
91
+ def _create_replay_session_tree(root: Path) -> None:
92
+ root.mkdir(mode=0o777)
93
+ for kind in ("short", "multi"):
94
+ intermediate = root / kind
95
+ intermediate.mkdir(mode=0o777)
96
+ for mode in ("fp32_reference", "bf16_pipeline"):
97
+ leaf = intermediate / mode
98
+ leaf.mkdir(mode=0o700)
99
+ for name in ("audio.safetensors", "audio.wav", "manifest.json"):
100
+ artifact = leaf / name
101
+ artifact.write_bytes(f"{kind}/{mode}/{name}".encode())
102
+ artifact.chmod(0o644)
103
+ session = root / "session.json"
104
+ session.write_bytes(b"{}")
105
+ session.chmod(0o644)
106
+
107
+
108
+ def test_flow_latent_type_rejects_native_integer_tokens() -> None:
109
+ with pytest.raises(TypeError, match="floating point"):
110
+ FlowVocoderLatents(torch.zeros(1, 25, 8, dtype=torch.int64))
111
+ with pytest.raises(ValueError, match="shape"):
112
+ FlowVocoderLatents(torch.zeros(4, 8, dtype=torch.float32))
113
+
114
+
115
+ def test_deterministic_float_wav_is_byte_stable_and_tensor_exact() -> None:
116
+ audio = torch.tensor(
117
+ [
118
+ [
119
+ [-0.75, -0.125, 0.0, 0.5],
120
+ [0.75, 0.125, 0.0, -0.5],
121
+ ]
122
+ ],
123
+ dtype=torch.float32,
124
+ )
125
+ first = deterministic_float_wav_bytes(audio, sampling_rate=44_100)
126
+ second = deterministic_float_wav_bytes(audio, sampling_rate=44_100)
127
+ decoded, sampling_rate = sf.read(
128
+ io.BytesIO(first), dtype="float32", always_2d=True
129
+ )
130
+
131
+ assert first == second
132
+ assert sampling_rate == 44_100
133
+ assert torch.equal(torch.from_numpy(decoded.T.copy()).unsqueeze(0), audio)
134
+
135
+
136
+ def test_replay_session_publication_modes_ignore_umask_0002(
137
+ tmp_path: Path,
138
+ ) -> None:
139
+ parent = tmp_path / "artifacts"
140
+ previous_umask = os.umask(0o002)
141
+ try:
142
+ parent.mkdir(mode=0o777)
143
+ candidate = parent / ".candidate.tmp"
144
+ _create_replay_session_tree(candidate)
145
+ finally:
146
+ os.umask(previous_umask)
147
+
148
+ assert (parent.stat().st_mode & 0o777) == 0o775
149
+ assert (candidate.stat().st_mode & 0o777) == 0o775
150
+ assert (candidate / "short").stat().st_mode & 0o777 == 0o775
151
+
152
+ output = parent / "evidence"
153
+ verified = publish_replay_session_root(candidate, output)
154
+
155
+ assert not candidate.exists()
156
+ assert len(verified.file_paths) == 13
157
+ assert len(verified.directory_paths) == 6
158
+ assert (parent.stat().st_mode & 0o777) == 0o755
159
+ assert (output.stat().st_mode & 0o777) == 0o755
160
+ for kind in ("short", "multi"):
161
+ assert ((output / kind).stat().st_mode & 0o777) == 0o755
162
+ for mode in ("fp32_reference", "bf16_pipeline"):
163
+ leaf = output / kind / mode
164
+ assert (leaf.stat().st_mode & 0o777) == 0o700
165
+ for artifact in leaf.iterdir():
166
+ assert (artifact.stat().st_mode & 0o777) == 0o644
167
+
168
+ (output / "short").chmod(0o775)
169
+ with pytest.raises(RuntimeError, match="safely permissioned"):
170
+ verify_replay_session_tree(output)
171
+
172
+
173
+ def test_replay_session_publication_rolls_back_after_rename_fsync_failure(
174
+ tmp_path: Path,
175
+ monkeypatch: pytest.MonkeyPatch,
176
+ ) -> None:
177
+ parent = tmp_path / "artifacts"
178
+ previous_umask = os.umask(0o002)
179
+ try:
180
+ parent.mkdir(mode=0o777)
181
+ candidate = parent / ".candidate.tmp"
182
+ _create_replay_session_tree(candidate)
183
+ finally:
184
+ os.umask(previous_umask)
185
+ output = parent / "evidence"
186
+ candidate_inode = candidate.stat().st_ino
187
+ original_fsync = vocoder_module._fsync_directory_path
188
+ calls = 0
189
+
190
+ def fail_once(path: Path) -> None:
191
+ nonlocal calls
192
+ calls += 1
193
+ if calls == 1:
194
+ raise OSError("injected parent fsync failure")
195
+ original_fsync(path)
196
+
197
+ monkeypatch.setattr(vocoder_module, "_fsync_directory_path", fail_once)
198
+ with pytest.raises(OSError, match="injected parent fsync failure"):
199
+ publish_replay_session_root(candidate, output)
200
+
201
+ assert calls == 2
202
+ assert not output.exists()
203
+ assert candidate.exists()
204
+ assert candidate.stat().st_ino == candidate_inode
205
+ verify_replay_session_tree(candidate)
206
+
207
+
208
+ def test_replay_manifest_hashes_defaults_and_accepts_h100_capability() -> None:
209
+ descriptor = OracleDescriptor.create(
210
+ oracle_kind="short",
211
+ case_name="short_parity",
212
+ run_id=(
213
+ "2a1bc3404f7a0c1c7bc03fc3813df5e8a3769aa9b413121f"
214
+ "1669edd097353368"
215
+ ),
216
+ base_id=BASE_ID,
217
+ contract_id="7" * 64,
218
+ run_manifest_file_sha256="8" * 64,
219
+ run_manifest_semantic_digest="9" * 64,
220
+ state_manifest_file_sha256="a" * 64,
221
+ state_manifest_semantic_digest="b" * 64,
222
+ latent_hop_length=512,
223
+ sampling_rate=44_100,
224
+ chunks=(
225
+ OracleChunk(
226
+ index=0,
227
+ latent_key="chunks.0.final_latents",
228
+ latent_shape=(1, 128, 86),
229
+ latent_dtype="float32",
230
+ latent_content_sha256="c" * 64,
231
+ latent_length=86,
232
+ crop_left_latent_frames=0,
233
+ crop_right_latent_frames=0,
234
+ crop_left_samples=0,
235
+ crop_right_samples=0,
236
+ ),
237
+ ),
238
+ expected_audio_shape=(1, 2, 44_032),
239
+ expected_audio_file_sha256="d" * 64,
240
+ expected_audio_content_sha256="e" * 64,
241
+ )
242
+ probe = LatentGradientProbe(
243
+ dtype="float32",
244
+ input_shape=(1, 128, 1),
245
+ output_shape=(1, 2, 512),
246
+ input_content_sha256="1" * 64,
247
+ gradient_content_sha256="2" * 64,
248
+ loss=1.0,
249
+ gradient_max_abs=1.0,
250
+ gradient_mean_abs=1.0,
251
+ gradient_finite=True,
252
+ gradient_nonzero=True,
253
+ weight_state_sha256_before="3" * 64,
254
+ weight_state_sha256_after="3" * 64,
255
+ parameter_gradient_count=0,
256
+ )
257
+ report = _report()
258
+ manifest = VocoderReplayManifest.create(
259
+ mode="fp32_reference",
260
+ oracle_semantic_digest=descriptor.semantic_digest,
261
+ adapter_semantic_digest=report.semantic_digest,
262
+ adapter_report=report,
263
+ oracle_descriptor=descriptor,
264
+ device_name="NVIDIA H100 80GB HBM3",
265
+ device_capability=(9, 0),
266
+ cuda_runtime="12.8",
267
+ peak_cuda_allocated_bytes=1,
268
+ peak_cuda_reserved_bytes=1,
269
+ gradient_probe=probe,
270
+ device="cuda:0",
271
+ dtype="float32",
272
+ chunk_output_sha256=("4" * 64,),
273
+ output_shape=(1, 2, 44_032),
274
+ output_content_sha256="5" * 64,
275
+ output_artifact=ArtifactRecord(
276
+ path="audio.safetensors",
277
+ sha256="6" * 64,
278
+ size=1,
279
+ ),
280
+ output_wav_artifact=ArtifactRecord(
281
+ path="audio.wav",
282
+ sha256="7" * 64,
283
+ size=1,
284
+ ),
285
+ expected_shape=(1, 2, 44_032),
286
+ expected_content_sha256="5" * 64,
287
+ weight_state_sha256_before="8" * 64,
288
+ weight_state_sha256_after="8" * 64,
289
+ trainable_parameter_count=0,
290
+ parameter_gradient_count=0,
291
+ exact_oracle_audio=True,
292
+ max_abs_error=0.0,
293
+ mean_abs_error=0.0,
294
+ )
295
+
296
+ payload = manifest.model_dump(mode="json", exclude={"semantic_digest"})
297
+ assert manifest.device_capability == (9, 0)
298
+ assert manifest.latent_gradient_mode == "inference_not_applicable"
299
+ assert semantic_digest(payload) == manifest.semantic_digest
300
+
301
+
302
+ def test_tiny_official_vocoder_is_frozen_but_latent_gradient_flows() -> None:
303
+ torch.manual_seed(4)
304
+ adapter = _tiny_adapter()
305
+ latent_tensor = torch.randn(1, 4, 5, requires_grad=True)
306
+ output = adapter(FlowVocoderLatents(latent_tensor))
307
+
308
+ assert output.shape == (1, 2, 10)
309
+ output.square().mean().backward()
310
+ assert latent_tensor.grad is not None
311
+ assert torch.isfinite(latent_tensor.grad).all()
312
+ assert torch.count_nonzero(latent_tensor.grad)
313
+ assert all(not item.requires_grad for item in adapter.model.parameters())
314
+ assert all(item.grad is None for item in adapter.model.parameters())
315
+ with pytest.raises(TypeError, match="FlowVocoderLatents"):
316
+ adapter(latent_tensor) # type: ignore[arg-type]
317
+
318
+
319
+ def test_tiny_real_decoder_gradient_probe_is_content_bound() -> None:
320
+ torch.manual_seed(8)
321
+ adapter = _tiny_adapter()
322
+ latents = FlowVocoderLatents(torch.randn(1, 4, 3))
323
+ probe = probe_latent_gradient(
324
+ adapter,
325
+ latents,
326
+ device=torch.device("cpu"),
327
+ dtype=torch.float32,
328
+ )
329
+
330
+ assert probe.input_shape == (1, 4, 1)
331
+ assert probe.output_shape == (1, 2, 2)
332
+
333
+ assert probe.gradient_finite and probe.gradient_nonzero
334
+ assert probe.weight_state_sha256_before == probe.weight_state_sha256_after
335
+ assert probe.parameter_gradient_count == 0
336
+
337
+ def test_crop_and_stitch_exact_geometry_preserves_gradient() -> None:
338
+ first = torch.linspace(-0.9, 0.9, 12, dtype=torch.float32).reshape(1, 2, 6)
339
+ second = torch.linspace(-0.8, 0.8, 12, dtype=torch.float32).reshape(
340
+ 1, 2, 6
341
+ )
342
+ first.requires_grad_()
343
+ second.requires_grad_()
344
+
345
+ output = crop_and_stitch(
346
+ (first, second),
347
+ (_chunk(0, left=0, right=1), _chunk(1, left=1, right=0)),
348
+ latent_hop_length=2,
349
+ )
350
+
351
+ expected = torch.cat((first[..., :4], second[..., 2:]), dim=-1)
352
+ assert torch.equal(output, expected)
353
+ output.sum().backward()
354
+ assert torch.equal(first.grad[..., :4], torch.ones_like(first.grad[..., :4]))
355
+ assert torch.count_nonzero(first.grad[..., 4:]) == 0
356
+ assert torch.count_nonzero(second.grad[..., :2]) == 0
357
+ assert torch.equal(second.grad[..., 2:], torch.ones_like(second.grad[..., 2:]))
358
+
359
+
360
+ @pytest.mark.skipif(
361
+ not all(
362
+ os.environ.get(name)
363
+ for name in (
364
+ "MINIMAX_BASE_SNAPSHOT",
365
+ "MINIMAX_BASE_MANIFEST",
366
+ "MINIMAX_DIFFUSERS_ROOT",
367
+ )
368
+ ),
369
+ reason="real frozen-vocoder paths are not configured",
370
+ )
371
+ def test_real_frozen_vocoder_mapping_is_exact_and_cpu_only() -> None:
372
+ adapter = load_frozen_vocoder(
373
+ snapshot=Path(os.environ["MINIMAX_BASE_SNAPSHOT"]),
374
+ base_manifest=Path(os.environ["MINIMAX_BASE_MANIFEST"]),
375
+ diffusers_root=Path(os.environ["MINIMAX_DIFFUSERS_ROOT"]),
376
+ )
377
+
378
+ assert adapter.report.mapped_tensor_count == 121
379
+ assert adapter.report.exact_target_count == 121
380
+ assert adapter.report.unknown_tensor_count == 0
381
+ assert len(adapter.model.state_dict()) == 121
382
+ assert all(item.device.type == "cpu" for item in adapter.model.parameters())
383
+ assert all(not item.requires_grad for item in adapter.model.parameters())
384
+
385
+
386
+ @pytest.mark.skipif(
387
+ not os.environ.get("MINIMAX_PHASE0_ARTIFACTS_ROOT"),
388
+ reason="Phase-0 baseline artifacts are not configured",
389
+ )
390
+ def test_real_phase0_oracles_verify_exact_geometry_and_content() -> None:
391
+ artifacts = Path(os.environ["MINIMAX_PHASE0_ARTIFACTS_ROOT"])
392
+ short = load_phase0_vocoder_oracle(artifacts, "short")
393
+ multi = load_phase0_vocoder_oracle(artifacts, "multi")
394
+
395
+ assert tuple(item.tensor.shape for item in short.latents) == ((1, 128, 86),)
396
+ assert short.expected_audio.shape == (1, 2, 44_032)
397
+ assert tuple(item.tensor.shape for item in multi.latents) == (
398
+ (1, 128, 689),
399
+ (1, 128, 689),
400
+ )
401
+ assert tuple(
402
+ (item.crop_left_latent_frames, item.crop_right_latent_frames)
403
+ for item in multi.descriptor.chunks
404
+ ) == ((0, 258), (86, 0))
405
+ assert multi.expected_audio.shape == (1, 2, 529_408)
406
+ assert all(
407
+ item.tensor.device.type == "cpu"
408
+ for item in (*short.latents, *multi.latents)
409
+ )
tests/test_waveform_causal_continuation.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Expected-red CPU contract for short, arbitrary-WAV causal continuation.
2
+
3
+ This is deliberately an acoustic continuation contract: it never supplies
4
+ future audio, text, tokens, native state, or Flow latents to prediction.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import inspect
9
+
10
+ import pytest
11
+ import torch
12
+
13
+ from music3lab.editing.waveform_causal_continuation import ( # expected red until implemented
14
+ CAPABILITY,
15
+ END_GUARD_SAMPLES,
16
+ HISTORY_SAMPLES,
17
+ PREDICTION_SAMPLES,
18
+ CausalContinuationError,
19
+ WaveformCausalContinuation,
20
+ append_causal_continuation,
21
+ build_source_exclusive_pairs,
22
+ evaluate_causal_continuation_gate,
23
+ )
24
+
25
+
26
+ def _source(samples: int = 320_000) -> torch.Tensor:
27
+ time = torch.arange(samples, dtype=torch.float32)
28
+ return torch.stack((torch.sin(time / 29), torch.cos(time / 47))).mul_(0.2)
29
+
30
+
31
+ def test_contract_is_history_only_and_predicts_an_8192_sample_residual() -> None:
32
+ assert (HISTORY_SAMPLES, PREDICTION_SAMPLES, END_GUARD_SAMPLES) == (65_536, 8_192, 220_500)
33
+ model = WaveformCausalContinuation(base_channels=4, blocks=1)
34
+ forbidden = {"target", "future", "right", "text", "tokens", "native_state", "flow_latents", "latents"}
35
+ assert not (forbidden & set(inspect.signature(model.forward).parameters))
36
+ history = _source(HISTORY_SAMPLES).unsqueeze(0)
37
+ residual = model(history)
38
+ assert residual.shape == (1, 2, PREDICTION_SAMPLES)
39
+ assert torch.isfinite(residual).all()
40
+
41
+
42
+ def test_prediction_is_causal_under_a_future_mutation_with_an_injected_toy_model() -> None:
43
+ class Toy(torch.nn.Module):
44
+ def forward(self, history: torch.Tensor) -> torch.Tensor:
45
+ return history[:, :, -1:].expand(-1, -1, PREDICTION_SAMPLES)
46
+
47
+ source = _source(HISTORY_SAMPLES + PREDICTION_SAMPLES + 64)
48
+ history = source[:, :HISTORY_SAMPLES].unsqueeze(0)
49
+ future_mutated = source.clone()
50
+ future_mutated[:, HISTORY_SAMPLES:] = 91
51
+ model = WaveformCausalContinuation(predictor=Toy())
52
+ assert torch.equal(model(history), model(future_mutated[:, :HISTORY_SAMPLES].unsqueeze(0)))
53
+
54
+
55
+ def test_pair_builder_is_deterministic_source_exclusive_and_targets_immediately_follow_history() -> None:
56
+ tracks = [f"track-{index:03d}" for index in range(678)]
57
+ first = build_source_exclusive_pairs(tracks, seed=19, pairs_per_split=(542, 68, 68))
58
+ second = build_source_exclusive_pairs(list(reversed(tracks)), seed=19, pairs_per_split=(542, 68, 68))
59
+ assert first == second
60
+ assert {split: len(first[split]) for split in ("train", "validation", "held_out")} == {
61
+ "train": 542, "validation": 68, "held_out": 68,
62
+ }
63
+ owners = [{pair.source_id for pair in first[split]} for split in first]
64
+ assert not owners[0] & owners[1] and not owners[0] & owners[2] and not owners[1] & owners[2]
65
+ for pairs in first.values():
66
+ for pair in pairs:
67
+ assert pair.target_start == pair.history_start + HISTORY_SAMPLES
68
+ assert pair.target_stop == pair.target_start + PREDICTION_SAMPLES
69
+ assert pair.end_guard_samples == END_GUARD_SAMPLES
70
+
71
+
72
+ def test_append_uses_repeat_tail_baseline_adds_residual_and_preserves_source_exactly() -> None:
73
+ source = _source(HISTORY_SAMPLES + 5_000)
74
+ residual = torch.full((1, 2, PREDICTION_SAMPLES), 0.125)
75
+ result = append_causal_continuation(source, residual)
76
+ assert torch.equal(result[:, :, :source.shape[-1]], source.unsqueeze(0))
77
+ repeat = source[:, -PREDICTION_SAMPLES:].unsqueeze(0)
78
+ assert torch.equal(result[:, :, source.shape[-1]:], repeat + residual)
79
+ with pytest.raises(CausalContinuationError, match="residual|8192"):
80
+ append_causal_continuation(source, residual[:, :, :-1])
81
+
82
+
83
+ def test_frozen_gate_requires_beating_all_baselines_boundaries_and_nontrivial_audio() -> None:
84
+ metrics = {
85
+ "ruler_candidate": 0.80, "ruler_repeat": 1.0, "ruler_roll": 1.0,
86
+ "ruler_zero": 0.90, "ruler_unrelated": 0.90, "l1_candidate": 0.20,
87
+ "l1_repeat": 0.21, "l1_roll": 0.22, "derivative_ratio": 2.0,
88
+ "join_rms_log_error": 1.5, "finite": True, "nonsilent": True,
89
+ "noncopy": True, "median_abs_repeat_correlation": 0.994,
90
+ }
91
+ accepted = evaluate_causal_continuation_gate(metrics)
92
+ assert accepted.accepted
93
+ assert CAPABILITY == "arbitrary_waveform_causal_short_continuation_not_native_tokens_not_semantic_style"
94
+ for bad in (
95
+ {"ruler_candidate": 0.801}, {"ruler_candidate": 0.901},
96
+ {"l1_candidate": 0.21}, {"derivative_ratio": 2.001},
97
+ {"join_rms_log_error": 1.501}, {"finite": False},
98
+ {"median_abs_repeat_correlation": 0.995},
99
+ ):
100
+ assert not evaluate_causal_continuation_gate(metrics | bad).accepted
tests/test_waveform_right_context_prepend.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Expected-red CPU contract for short arbitrary-WAV right-context prepend.
2
+
3
+ The predictor is deliberately acoustic-only: it receives a fixed suffix and
4
+ predicts its missing immediate prefix. It is not a native-token or semantic
5
+ prepend path.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import inspect
10
+
11
+ import pytest
12
+ import torch
13
+
14
+ from music3lab.editing.waveform_right_context_prepend import ( # expected red until implemented
15
+ CAPABILITY,
16
+ END_GUARD_SAMPLES,
17
+ PREFIX_SAMPLES,
18
+ RIGHT_CONTEXT_SAMPLES,
19
+ RightContextPrependError,
20
+ WaveformRightContextPrepend,
21
+ build_right_context_prepend_pairs,
22
+ evaluate_right_context_prepend_gate,
23
+ make_right_context_pair,
24
+ prepend_with_right_context,
25
+ )
26
+
27
+
28
+ def _source(samples: int = PREFIX_SAMPLES + RIGHT_CONTEXT_SAMPLES) -> torch.Tensor:
29
+ time = torch.arange(samples, dtype=torch.float32)
30
+ return torch.stack((torch.sin(time / 31), torch.cos(time / 43))).mul_(0.2)
31
+
32
+
33
+ def test_pair_and_model_are_right_context_only_with_fixed_stft_conditioning() -> None:
34
+ source = _source()
35
+ target, suffix = make_right_context_pair(source)
36
+ assert target.shape == (2, 8_192)
37
+ assert suffix.shape == (2, 65_536)
38
+
39
+ model = WaveformRightContextPrepend()
40
+ forbidden = {"target", "future", "text", "tokens", "latents", "state", "native_state"}
41
+ assert not (forbidden & set(inspect.signature(model.forward).parameters))
42
+ assert len(inspect.signature(model.forward).parameters) == 1
43
+ assert model.conditioning_stft(suffix.unsqueeze(0)).shape == (1, 4, 513, 253)
44
+ prediction = model(suffix.unsqueeze(0))
45
+ assert prediction.shape == (1, 2, PREFIX_SAMPLES)
46
+ assert 4_000_000 <= sum(parameter.numel() for parameter in model.parameters()) <= 6_500_000
47
+
48
+
49
+ def test_withheld_prefix_mutation_cannot_change_prediction_and_cpu_smoke_is_deterministic() -> None:
50
+ source = _source()
51
+ _, suffix = make_right_context_pair(source)
52
+ altered = source.clone()
53
+ altered[:, :PREFIX_SAMPLES] = 37
54
+ _, same_suffix = make_right_context_pair(altered)
55
+ assert torch.equal(suffix, same_suffix)
56
+
57
+ torch.manual_seed(7)
58
+ model = WaveformRightContextPrepend().eval()
59
+ with torch.no_grad():
60
+ first = model(suffix.unsqueeze(0))
61
+ second = model(same_suffix.unsqueeze(0))
62
+ assert torch.equal(first, second)
63
+
64
+
65
+ def test_input_rejection_and_source_exclusive_end_guard_pair_contract() -> None:
66
+ model = WaveformRightContextPrepend()
67
+ with pytest.raises(RightContextPrependError, match="shape|65536"):
68
+ model(torch.zeros(1, 2, RIGHT_CONTEXT_SAMPLES - 1))
69
+ nonfinite = torch.zeros(1, 2, RIGHT_CONTEXT_SAMPLES)
70
+ nonfinite[:, :, 0] = float("nan")
71
+ with pytest.raises(RightContextPrependError, match="finite"):
72
+ model(nonfinite)
73
+
74
+ tracks = [f"track-{index:03d}" for index in range(678)]
75
+ first = build_right_context_prepend_pairs(tracks, seed=19, pairs_per_split=(542, 68, 68))
76
+ second = build_right_context_prepend_pairs(list(reversed(tracks)), seed=19, pairs_per_split=(542, 68, 68))
77
+ assert first == second
78
+ owners = [{pair.source_id for pair in pairs} for pairs in first.values()]
79
+ assert not owners[0] & owners[1] and not owners[0] & owners[2] and not owners[1] & owners[2]
80
+ for pairs in first.values():
81
+ for pair in pairs:
82
+ assert pair.prefix_stop == pair.suffix_start
83
+ assert pair.suffix_stop - pair.suffix_start == RIGHT_CONTEXT_SAMPLES
84
+ assert pair.end_guard_samples == END_GUARD_SAMPLES
85
+
86
+
87
+ def test_prepend_composer_preserves_every_source_sample_bit_exactly_without_crossfade() -> None:
88
+ source = _source(90_000)
89
+ prefix = torch.full((1, 2, PREFIX_SAMPLES), 0.125)
90
+ result = prepend_with_right_context(source, prefix)
91
+ assert torch.equal(result[:, :, PREFIX_SAMPLES:], source.unsqueeze(0))
92
+ assert torch.equal(result[:, :, :PREFIX_SAMPLES], prefix)
93
+ with pytest.raises(RightContextPrependError, match="prefix|8192"):
94
+ prepend_with_right_context(source, prefix[:, :, :-1])
95
+
96
+
97
+ def test_frozen_gate_requires_real_short_prefix_improvement_over_every_baseline() -> None:
98
+ metrics = {
99
+ "ruler_candidate": 0.80, "ruler_zero": 0.90, "ruler_constant": 0.90,
100
+ "ruler_repeat_first": 0.90, "ruler_reverse_first": 0.90,
101
+ "l1_candidate": 0.20, "l1_repeat_first": 0.21, "l1_reverse_first": 0.22,
102
+ "join_derivative_error": 0.18, "constant_join_derivative_error": 0.20,
103
+ "join_rms_log_error": 1.5, "finite": True, "nonsilent": True,
104
+ "no_exact_baseline_copy": True, "median_abs_suffix_baseline_correlation": 0.994,
105
+ "max_abs_suffix_baseline_correlation": 0.994,
106
+ }
107
+ accepted = evaluate_right_context_prepend_gate(metrics)
108
+ assert accepted.accepted
109
+ assert CAPABILITY == "arbitrary_waveform_right_context_short_precursor_not_native_tokens_not_semantic_prepend"
110
+ for bad in (
111
+ {"ruler_candidate": 0.856}, {"l1_candidate": 0.21},
112
+ {"join_derivative_error": 0.181}, {"join_rms_log_error": 1.501},
113
+ {"finite": False}, {"nonsilent": False}, {"no_exact_baseline_copy": False},
114
+ {"median_abs_suffix_baseline_correlation": 0.995},
115
+ {"max_abs_suffix_baseline_correlation": 0.995},
116
+ ):
117
+ assert not evaluate_right_context_prepend_gate(metrics | bad).accepted