Spaces:
Running
Running
Release Model P chart generation demo for osu!taiko and TJA
Browse files- .gitattributes +2 -35
- LICENSE +21 -0
- README.md +24 -8
- app.py +66 -0
- assets/demo.mp3 +3 -0
- assets/eighth-gate.json +4 -0
- assets/r-calibration.json +48 -0
- chartgen/__init__.py +0 -0
- chartgen/beattrack.py +264 -0
- chartgen/data/__init__.py +0 -0
- chartgen/data/osu.py +327 -0
- chartgen/dataset.py +528 -0
- chartgen/disteval.py +1587 -0
- chartgen/features.py +71 -0
- chartgen/gapstats.py +109 -0
- chartgen/gen_mapset.py +342 -0
- chartgen/generate.py +348 -0
- chartgen/infer.py +247 -0
- chartgen/latent_align.py +241 -0
- chartgen/latent_stats.py +219 -0
- chartgen/model.py +392 -0
- chartgen/plan_decide.py +232 -0
- chartgen/prep.py +137 -0
- chartgen/rhythm_eval.py +461 -0
- chartgen/rhythm_eval2.py +536 -0
- chartgen/song_planner.py +366 -0
- chartgen/timing.py +215 -0
- chartgen/train.py +374 -0
- chartgen/v11/__init__.py +0 -0
- chartgen/v11/gen_new.py +245 -0
- chartgen/v11/patterns.py +243 -0
- chartgen/v11/pmap.py +1130 -0
- chartgen/v11/rmap.py +518 -0
- chartgen/v11/rmap_data.py +290 -0
- chartgen/v11/rmap_eval.py +735 -0
- chartgen/v11/rmap_pseudo.py +244 -0
- chartgen/v11/s1_arms.py +278 -0
- chartgen/v11/s2_arms.py +512 -0
- chartgen/v11/s2_osz.py +124 -0
- chartgen/v11/s4c_sampler.py +236 -0
- chartgen/v11/s5a.py +132 -0
- chartgen/v11/s5d_osz.py +350 -0
- chartgen/v11/song_signature.py +745 -0
- chartgen/v11/writer.py +1002 -0
- chartgen/v11/writer_data.py +258 -0
- packages.txt +1 -0
- pipeline.py +269 -0
- reports/figs/v11_s0_vocab.json +1 -0
- requirements.txt +7 -0
- tja_export.py +123 -0
.gitattributes
CHANGED
|
@@ -1,35 +1,2 @@
|
|
| 1 |
-
*.
|
| 2 |
-
*.
|
| 3 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
-
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 1 |
+
*.wav filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.mp3 filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 JacobLinCool
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
README.md
CHANGED
|
@@ -1,13 +1,29 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version: 6.
|
| 8 |
-
python_version:
|
| 9 |
app_file: app.py
|
| 10 |
-
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Model P · Taiko Chart Generator
|
| 3 |
+
emoji: 🥁
|
| 4 |
+
colorFrom: yellow
|
| 5 |
+
colorTo: red
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 6.30.0
|
| 8 |
+
python_version: "3.12"
|
| 9 |
app_file: app.py
|
| 10 |
+
license: mit
|
| 11 |
+
models:
|
| 12 |
+
- JacobLinCool/internal-model-p
|
| 13 |
---
|
| 14 |
|
| 15 |
+
# Model P
|
| 16 |
+
|
| 17 |
+
Model P places drum hits on a beat grid and generates two osu!taiko courses for the same song. The demo produces a playable `.osz` with Oni and Inner Oni, and a TJA ZIP with the corresponding Oni and Edit courses. Both packages include the supplied audio as MP3.
|
| 18 |
+
|
| 19 |
+
Add an 8–180 second audio file or use the original synthetic drum loop. Automatic timing handles tempo changes. The optional BPM and downbeat controls set a constant 4/4 grid when automatic timing needs correction.
|
| 20 |
+
|
| 21 |
+
The checkpoint comes from the stage 5d osu!taiko experiment. Model R supplies the fine-subdivision gate. The b9fix model estimates timing, colours the positions written by P, and predicts shared kiai sections. Short drumrolls come from the P HOLD token. The release uses a bar plan based on P's hits and preserves their grid positions when adding colours. Stage 5d evaluation measured placements before this rendering stage. See the [model card](https://huggingface.co/JacobLinCool/internal-model-p) for the results and scope.
|
| 22 |
+
|
| 23 |
+
Generated Edit courses reflect the osu!taiko Inner Oni setting. TJA export adds format-specific course names and timing metadata. The study evaluated osu!taiko charts and did not measure TJA play quality or native Taiko course conventions.
|
| 24 |
+
|
| 25 |
+
## Local use
|
| 26 |
+
|
| 27 |
+
Install FFmpeg and the packages in `requirements.txt`, then run `python app.py`. The CLI supports batch scripting through `python pipeline.py path/to/audio --title "Track name" --bpm 120`. Weights are fetched from the Hugging Face model revision pinned in `pipeline.py`. Set `MODEL_P_DIR` to a locally downloaded snapshot to run offline.
|
| 28 |
+
|
| 29 |
+
The bundled demo is generated from sine-wave percussion and melody, and is dedicated to the public domain under CC0. No songs or maps from the training corpus are included.
|
app.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from tempfile import TemporaryDirectory
|
| 6 |
+
|
| 7 |
+
import gradio as gr
|
| 8 |
+
from gradio.processing_utils import get_upload_folder, save_file_to_cache
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
from pipeline import AudioInputError, generate_package
|
| 12 |
+
|
| 13 |
+
torch.set_num_threads(min(4, os.cpu_count() or 1))
|
| 14 |
+
ROOT = Path(__file__).resolve().parent
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def run(audio, title, artist, seed, bpm, downbeat):
|
| 18 |
+
if audio is None:
|
| 19 |
+
raise gr.Error("Upload audio or use the synthetic demo track.")
|
| 20 |
+
if seed is None:
|
| 21 |
+
raise gr.Error("Enter an integer seed.")
|
| 22 |
+
try:
|
| 23 |
+
with TemporaryDirectory(prefix="model-p-") as directory:
|
| 24 |
+
osz, tja, counts = generate_package(
|
| 25 |
+
Path(audio), Path(directory), title=title or "Generated taiko chart", artist=artist or "",
|
| 26 |
+
seed=seed, bpm=bpm, downbeat_ms=downbeat or 0,
|
| 27 |
+
)
|
| 28 |
+
downloads = [save_file_to_cache(path, get_upload_folder()) for path in (osz, tja)]
|
| 29 |
+
note_counts = " · ".join(f"{course}: {count:,} hits" for course, count in counts.items())
|
| 30 |
+
return note_counts, *downloads
|
| 31 |
+
except AudioInputError as exc:
|
| 32 |
+
raise gr.Error(str(exc)) from exc
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
with gr.Blocks(title="Model P · Taiko chart generator", delete_cache=(300, 3600)) as demo:
|
| 36 |
+
gr.Markdown(
|
| 37 |
+
"# Model P\n"
|
| 38 |
+
"Generate an Oni and Inner Oni chartset from audio. "
|
| 39 |
+
"Download an osu!taiko package or a TJA package with both courses. "
|
| 40 |
+
"The default audio is a synthetic drum loop."
|
| 41 |
+
)
|
| 42 |
+
with gr.Row():
|
| 43 |
+
with gr.Column():
|
| 44 |
+
audio = gr.Audio(
|
| 45 |
+
value=str(ROOT / "assets/demo.mp3"), sources=["upload"], type="filepath",
|
| 46 |
+
label="Audio",
|
| 47 |
+
)
|
| 48 |
+
with gr.Accordion("Chart details and timing", open=False):
|
| 49 |
+
with gr.Row():
|
| 50 |
+
title = gr.Textbox(label="Track title")
|
| 51 |
+
artist = gr.Textbox(label="Artist")
|
| 52 |
+
with gr.Row():
|
| 53 |
+
seed = gr.Number(label="Seed", value=0, precision=0)
|
| 54 |
+
bpm = gr.Number(label="BPM (optional)", minimum=60, maximum=320)
|
| 55 |
+
downbeat = gr.Number(label="First downbeat (ms)", value=0, minimum=0)
|
| 56 |
+
gr.Markdown("Leave BPM blank for automatic timing. If you enter a BPM, the grid uses a constant 4/4 meter.")
|
| 57 |
+
generate = gr.Button("Generate charts", variant="primary")
|
| 58 |
+
with gr.Column():
|
| 59 |
+
result = gr.Markdown("Upload audio between 8 seconds and 3 minutes.")
|
| 60 |
+
osz = gr.File(label="osu!taiko · OSZ")
|
| 61 |
+
tja = gr.File(label="Taiko simulators · TJA and audio")
|
| 62 |
+
generate.click(run, [audio, title, artist, seed, bpm, downbeat], [result, osz, tja], api_name="generate")
|
| 63 |
+
gr.Markdown("Model P was trained on osu!taiko. TJA uses the same generated hit positions and maps Inner Oni to Edit.")
|
| 64 |
+
|
| 65 |
+
if __name__ == "__main__":
|
| 66 |
+
demo.queue(max_size=8, default_concurrency_limit=1).launch(max_file_size="24mb")
|
assets/demo.mp3
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f4e49b60937a81c35befb80276b7d181d0bc28ea680b86e76909d27d877f8ed0
|
| 3 |
+
size 121701
|
assets/eighth-gate.json
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"3": 0.018385151157122488,
|
| 3 |
+
"4": 0.02396908591767234
|
| 4 |
+
}
|
assets/r-calibration.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"calib": {
|
| 3 |
+
"3": {
|
| 4 |
+
"beat": [
|
| 5 |
+
1.1515520384467,
|
| 6 |
+
0.25591023340762725
|
| 7 |
+
],
|
| 8 |
+
"1/2": [
|
| 9 |
+
1.1347013810365862,
|
| 10 |
+
0.11471494737755498
|
| 11 |
+
],
|
| 12 |
+
"1/4": [
|
| 13 |
+
1.088733870376013,
|
| 14 |
+
-0.05492892305691505
|
| 15 |
+
],
|
| 16 |
+
"triplet": [
|
| 17 |
+
0.9303047381983037,
|
| 18 |
+
0.34052884689492746
|
| 19 |
+
],
|
| 20 |
+
"eighth": [
|
| 21 |
+
1.0897128110772945,
|
| 22 |
+
0.0
|
| 23 |
+
]
|
| 24 |
+
},
|
| 25 |
+
"4": {
|
| 26 |
+
"beat": [
|
| 27 |
+
1.1473306318548182,
|
| 28 |
+
0.08883469574105975
|
| 29 |
+
],
|
| 30 |
+
"1/2": [
|
| 31 |
+
1.1638353374925268,
|
| 32 |
+
0.08875733433717763
|
| 33 |
+
],
|
| 34 |
+
"1/4": [
|
| 35 |
+
1.1007410056600582,
|
| 36 |
+
-0.030524747570119134
|
| 37 |
+
],
|
| 38 |
+
"triplet": [
|
| 39 |
+
1.114957341066888,
|
| 40 |
+
-0.34271769313728934
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Beat-by-beat timing decoder for songs whose tempo changes often or continuously.
|
| 2 |
+
|
| 3 |
+
``timing.decode_timing`` fits constant tempos over long windows, which cannot follow an
|
| 4 |
+
accelerando, a ritardando or quick alternation between tempos. This decoder instead tracks
|
| 5 |
+
individual beats with dynamic programming over (beat time, interval to the previous beat), so
|
| 6 |
+
the interval may drift a little at every beat or jump at a cost. The beat sequence is then
|
| 7 |
+
written as osu! red lines the way mappers do it: runs of beats with a steady interval become one
|
| 8 |
+
section fitted by least squares (sub-millisecond accuracy), and passages where the interval keeps
|
| 9 |
+
changing get one red line per beat, with the bar line hidden on lines that are not bar starts.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
from .timing import _choose_meter, _score, fit_constant_tempo
|
| 17 |
+
|
| 18 |
+
RES_MS = 2.0 # DP time resolution
|
| 19 |
+
MAX_BPM = 320.0
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _upsample(act: np.ndarray, t0_ms: float, t1_ms: float) -> tuple[np.ndarray, np.ndarray]:
|
| 23 |
+
t = np.arange(t0_ms, t1_ms, RES_MS)
|
| 24 |
+
return t, np.interp(t / 10.0, np.arange(len(act)), act.astype(np.float64))
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def track_beats(beat_act: np.ndarray, t0_ms: float, t1_ms: float, period_ms: float,
|
| 28 |
+
span: tuple[float, float] = (0.55, 1.8), jump_cost: float = 2.0,
|
| 29 |
+
drift: int = 2, smooth: float = 400.0) -> np.ndarray:
|
| 30 |
+
"""Return beat times (ms). ``period_ms`` sets the beat level; intervals may range over
|
| 31 |
+
``span`` times it. Between consecutive beats the interval may change by up to ``drift``
|
| 32 |
+
grid steps (2 ms each) almost freely (cost ``smooth`` * (log ratio)^2), or jump anywhere for
|
| 33 |
+
``jump_cost`` plus a mild squared-log cost."""
|
| 34 |
+
t, a = _upsample(beat_act, t0_ms, t1_ms)
|
| 35 |
+
r = a - a.mean() # zero expected reward for a beat placed at random
|
| 36 |
+
min_tau = max(period_ms * span[0], 60000 / MAX_BPM) # charts essentially never exceed MAX_BPM
|
| 37 |
+
taus = np.arange(int(min_tau / RES_MS), int(period_ms * span[1] / RES_MS) + 1)
|
| 38 |
+
K, T = len(taus), len(t)
|
| 39 |
+
logt = np.log(taus)
|
| 40 |
+
S = np.full((T, K), -np.inf)
|
| 41 |
+
back = np.full((T, K), -1, dtype=np.int64)
|
| 42 |
+
first = int(period_ms * span[1] / RES_MS) + 1
|
| 43 |
+
S[:first] = r[:first, None] # a path may start anywhere in the first beat
|
| 44 |
+
# banded transition (small drift) and global best (jump) per previous row
|
| 45 |
+
d = np.arange(-drift, drift + 1)
|
| 46 |
+
band_cost = smooth * (logt[:, None] - logt[np.clip(np.arange(K)[:, None] + d[None], 0, K - 1)]) ** 2
|
| 47 |
+
jump_pen = (logt[:, None] - logt[None, :]) ** 2 + jump_cost
|
| 48 |
+
for i in range(first, T):
|
| 49 |
+
prev = i - taus # row of the previous beat for each interval
|
| 50 |
+
ok = prev >= 0
|
| 51 |
+
if not ok.any():
|
| 52 |
+
continue
|
| 53 |
+
rows = S[np.where(ok, prev, 0)] # [K, K]: previous scores for every previous interval
|
| 54 |
+
rows[~ok] = -np.inf
|
| 55 |
+
cols = np.clip(np.arange(K)[:, None] + d[None], 0, K - 1)
|
| 56 |
+
band = rows[np.arange(K)[:, None], cols] - band_cost
|
| 57 |
+
bj = np.argmax(band, 1)
|
| 58 |
+
best_band = band[np.arange(K), bj]
|
| 59 |
+
jump = rows - jump_pen
|
| 60 |
+
jj = np.argmax(jump, 1)
|
| 61 |
+
best_jump = jump[np.arange(K), jj]
|
| 62 |
+
use_jump = best_jump > best_band
|
| 63 |
+
S[i] = r[i] + np.where(use_jump, best_jump, best_band)
|
| 64 |
+
back[i] = np.where(use_jump, jj, cols[np.arange(K), bj])
|
| 65 |
+
# end anywhere in the last beat
|
| 66 |
+
last = max(0, T - first)
|
| 67 |
+
i, k = np.unravel_index(np.argmax(S[last:]), S[last:].shape)
|
| 68 |
+
i += last
|
| 69 |
+
beats = []
|
| 70 |
+
while i >= 0 and k >= 0:
|
| 71 |
+
beats.append(i)
|
| 72 |
+
pk = back[i, k]
|
| 73 |
+
i, k = i - taus[k], pk
|
| 74 |
+
if pk < 0:
|
| 75 |
+
break
|
| 76 |
+
idx = np.array(beats[::-1])
|
| 77 |
+
idx = idx[idx >= 0]
|
| 78 |
+
# sub-grid refinement: parabolic peak of the activation within +/-6 ms
|
| 79 |
+
out = []
|
| 80 |
+
for j in idx:
|
| 81 |
+
lo, hi = max(0, j - 3), min(T, j + 4)
|
| 82 |
+
m = lo + int(np.argmax(a[lo:hi]))
|
| 83 |
+
if 0 < m < T - 1:
|
| 84 |
+
y0, y1, y2 = a[m - 1], a[m], a[m + 1]
|
| 85 |
+
den = y0 - 2 * y1 + y2
|
| 86 |
+
off = 0.5 * (y0 - y2) / den if den < 0 else 0.0
|
| 87 |
+
out.append(t[m] + np.clip(off, -1, 1) * RES_MS)
|
| 88 |
+
else:
|
| 89 |
+
out.append(t[m])
|
| 90 |
+
return np.array(out)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def beats_to_sections(beats: np.ndarray, down_act: np.ndarray, tol_ms: float = 4.0,
|
| 94 |
+
min_run: int = 8) -> np.ndarray:
|
| 95 |
+
"""Convert beat times into sections [n, 5] (time, beat_length, meter, start_beat, omit)."""
|
| 96 |
+
n = len(beats)
|
| 97 |
+
if n < 2:
|
| 98 |
+
return np.array([[beats[0] if n else 0.0, 500.0, 4, 0.0, 0.0]])
|
| 99 |
+
# greedy runs of steady interval (linear fit of time on beat index within tol)
|
| 100 |
+
runs = []
|
| 101 |
+
i = 0
|
| 102 |
+
while i < n - 1:
|
| 103 |
+
j = i + 2
|
| 104 |
+
best = None
|
| 105 |
+
while j <= n:
|
| 106 |
+
k = np.arange(i, j)
|
| 107 |
+
A = np.c_[np.ones(len(k)), k - i]
|
| 108 |
+
coef, *_ = np.linalg.lstsq(A, beats[i:j], rcond=None)
|
| 109 |
+
res = np.abs(A @ coef - beats[i:j])
|
| 110 |
+
# robust: tolerate isolated misplaced beats, but never a drift beyond 2.5 tol
|
| 111 |
+
if np.percentile(res, 90) > tol_ms or res.max() > 2.5 * tol_ms:
|
| 112 |
+
break
|
| 113 |
+
best = (j, coef)
|
| 114 |
+
j += 1
|
| 115 |
+
j, coef = best
|
| 116 |
+
# trim trailing beats the robust fit tolerated but that already belong to the next tempo
|
| 117 |
+
while j - i > 2:
|
| 118 |
+
k = np.arange(i, j)
|
| 119 |
+
A = np.c_[np.ones(len(k)), k - i]
|
| 120 |
+
coef, *_ = np.linalg.lstsq(A, beats[i:j], rcond=None)
|
| 121 |
+
if abs(A[-1] @ coef - beats[j - 1]) <= tol_ms:
|
| 122 |
+
break
|
| 123 |
+
j -= 1
|
| 124 |
+
runs.append((i, j, coef)) # beats i..j-1 follow t = coef0 + coef1*(idx-i)
|
| 125 |
+
i = j - 1 if j - i >= min_run else i + 1
|
| 126 |
+
if i >= n - 1:
|
| 127 |
+
break
|
| 128 |
+
meter, phase = _choose_meter(down_act, beats)
|
| 129 |
+
bar_of = (np.arange(n) - phase) % meter # position of each beat in its bar
|
| 130 |
+
sections = [] # (time, beat_length, meter, omit) per starting beat index
|
| 131 |
+
covered = 0
|
| 132 |
+
for (i0, j, coef) in runs:
|
| 133 |
+
if j - i0 < min_run:
|
| 134 |
+
continue
|
| 135 |
+
i = max(i0, covered)
|
| 136 |
+
# per-beat lines up to the first bar start, then one steady section
|
| 137 |
+
first_bar = next((b for b in range(i, j) if bar_of[b] == 0), i)
|
| 138 |
+
for b in range(covered, first_bar):
|
| 139 |
+
sections.append((b, beats[b], beats[b + 1] - beats[b], bar_of[b] != 0))
|
| 140 |
+
sections.append((first_bar, coef[0] + coef[1] * (first_bar - i0), coef[1], bar_of[first_bar] != 0))
|
| 141 |
+
covered = j - 1
|
| 142 |
+
for b in range(covered, n - 1):
|
| 143 |
+
if not sections or b > sections[-1][0]:
|
| 144 |
+
sections.append((b, beats[b], beats[b + 1] - beats[b], bar_of[b] != 0))
|
| 145 |
+
sections.sort(key=lambda s: s[0])
|
| 146 |
+
out = []
|
| 147 |
+
for bi, t, bl, omit in sections:
|
| 148 |
+
if out:
|
| 149 |
+
pt, pbl, _, pbi, _ = out[-1]
|
| 150 |
+
# same tempo and continuous phase: the previous line already covers this one
|
| 151 |
+
if abs(bl / pbl - 1) < 0.002 and abs(pt + (bi - pbi) * pbl - t) < 2.0 and (bi - pbi) % meter == 0:
|
| 152 |
+
continue
|
| 153 |
+
out.append([t, bl, meter, float(bi), float(omit)])
|
| 154 |
+
return np.array(out, dtype=np.float64)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def decode_timing_dp(beat_act: np.ndarray, down_act: np.ndarray, t0_ms: float, t1_ms: float) -> np.ndarray:
|
| 158 |
+
p, _, _ = fit_constant_tempo(beat_act, t0_ms, t1_ms)
|
| 159 |
+
beats = track_beats(beat_act, t0_ms, t1_ms, p)
|
| 160 |
+
# beat level check: if the points halfway between tracked beats are as strong as the beats,
|
| 161 |
+
# the tracker is running at half the beat rate somewhere; track again at the faster level
|
| 162 |
+
if len(beats) > 8:
|
| 163 |
+
mids = (beats[1:] + beats[:-1]) / 2
|
| 164 |
+
on = np.interp(beats / 10.0, np.arange(len(beat_act)), beat_act.astype(np.float64))
|
| 165 |
+
mid = np.interp(mids / 10.0, np.arange(len(beat_act)), beat_act.astype(np.float64))
|
| 166 |
+
if np.mean(mid > 0.5 * np.median(on)) > 0.25 and 60000 / (p / 2) <= MAX_BPM:
|
| 167 |
+
beats = track_beats(beat_act, t0_ms, t1_ms, p / 2)
|
| 168 |
+
return beats_to_sections(beats, down_act)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def _smooth_beats(beats: np.ndarray, half: int = 3) -> np.ndarray:
|
| 172 |
+
"""Local quadratic fit of beat time on beat index (+/- half beats) to remove frame jitter."""
|
| 173 |
+
out = beats.copy()
|
| 174 |
+
n = len(beats)
|
| 175 |
+
for i in range(n):
|
| 176 |
+
lo, hi = max(0, i - half), min(n, i + half + 1)
|
| 177 |
+
iv = np.diff(beats[lo:hi])
|
| 178 |
+
if hi - lo >= 4 and iv.max() / iv.min() < 1.1: # never smooth across a tempo jump
|
| 179 |
+
k = np.arange(lo, hi) - i
|
| 180 |
+
out[i] = np.polyval(np.polyfit(k, beats[lo:hi], 2), 0)
|
| 181 |
+
return out
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def decode_timing_hybrid(beat_act: np.ndarray, down_act: np.ndarray, t0_ms: float, t1_ms: float,
|
| 185 |
+
steady_tol: float = 0.015, min_steady: int = 8) -> np.ndarray:
|
| 186 |
+
"""Beat tracking for the tempo structure, then a precise constant-tempo fit on every
|
| 187 |
+
steady stretch; one smoothed red line per beat only where the tempo keeps changing."""
|
| 188 |
+
p, _, _ = fit_constant_tempo(beat_act, t0_ms, t1_ms)
|
| 189 |
+
beats = track_beats(beat_act, t0_ms, t1_ms, p)
|
| 190 |
+
if len(beats) > 8:
|
| 191 |
+
mids = (beats[1:] + beats[:-1]) / 2
|
| 192 |
+
on = np.interp(beats / 10.0, np.arange(len(beat_act)), beat_act.astype(np.float64))
|
| 193 |
+
mid = np.interp(mids / 10.0, np.arange(len(beat_act)), beat_act.astype(np.float64))
|
| 194 |
+
if np.mean(mid > 0.5 * np.median(on)) > 0.25 and 60000 / (p / 2) <= MAX_BPM:
|
| 195 |
+
beats = track_beats(beat_act, t0_ms, t1_ms, p / 2)
|
| 196 |
+
n = len(beats)
|
| 197 |
+
if n < min_steady:
|
| 198 |
+
return decode_timing_dp(beat_act, down_act, t0_ms, t1_ms)
|
| 199 |
+
iv = np.diff(beats)
|
| 200 |
+
loc = np.array([np.median(iv[max(0, i - 4): i + 5]) for i in range(len(iv))]) # local interval per gap
|
| 201 |
+
# steady regions: maximal runs of gaps whose local interval stays within tol of the run median
|
| 202 |
+
regions = []
|
| 203 |
+
i = 0
|
| 204 |
+
while i < len(loc):
|
| 205 |
+
j = i + 1
|
| 206 |
+
while j < len(loc) and abs(loc[j] / np.median(loc[i:j + 1]) - 1) < steady_tol:
|
| 207 |
+
j += 1
|
| 208 |
+
if j - i >= min_steady:
|
| 209 |
+
regions.append((i, j)) # beats i..j (gaps i..j-1)
|
| 210 |
+
i = j
|
| 211 |
+
else:
|
| 212 |
+
i += 1
|
| 213 |
+
meter, phase = _choose_meter(down_act, beats)
|
| 214 |
+
bar_of = (np.arange(n) - phase) % meter
|
| 215 |
+
smooth = _smooth_beats(beats)
|
| 216 |
+
lines = [] # (beat_idx, time, beat_length, omit)
|
| 217 |
+
covered = 0
|
| 218 |
+
for a, b in regions:
|
| 219 |
+
first_bar = next((k for k in range(max(a, covered), b) if bar_of[k] == 0), max(a, covered))
|
| 220 |
+
for k in range(covered, first_bar):
|
| 221 |
+
lines.append((k, smooth[k], smooth[k + 1] - smooth[k], bar_of[k] != 0))
|
| 222 |
+
# precise fit on this stretch: least squares on the tracked beats (edges trimmed, since
|
| 223 |
+
# the local interval lags a tempo change by a few beats), then a narrow template search
|
| 224 |
+
lo, hi = min(a + 4, first_bar), b - 4 if b - 4 > a + 8 else b
|
| 225 |
+
k = np.arange(lo, hi + 1)
|
| 226 |
+
coef = np.polyfit(k - first_bar, beats[lo:hi + 1], 1) # time at first_bar, period
|
| 227 |
+
res = beats[lo:hi + 1] - np.polyval(coef, k - first_bar)
|
| 228 |
+
good = np.abs(res) < 3 * max(np.median(np.abs(res)), 1.0)
|
| 229 |
+
coef = np.polyfit((k - first_bar)[good], beats[lo:hi + 1][good], 1)
|
| 230 |
+
start, sp = float(coef[1]), float(coef[0])
|
| 231 |
+
periods = sp * (1 + np.arange(-0.001, 0.001, 0.00005))
|
| 232 |
+
phases = np.arange(-4, 4, 0.25)
|
| 233 |
+
t_lo = start - (first_bar - a) * sp
|
| 234 |
+
sc = _score(beat_act, t_lo, beats[b], periods, (start - t_lo) % sp + phases)
|
| 235 |
+
pi, fi = np.unravel_index(np.argmax(sc), sc.shape)
|
| 236 |
+
sp = float(periods[pi])
|
| 237 |
+
start = float(start + phases[fi])
|
| 238 |
+
lines.append((first_bar, start, sp, bar_of[first_bar] != 0))
|
| 239 |
+
covered = b
|
| 240 |
+
for k in range(covered, n - 1):
|
| 241 |
+
lines.append((k, smooth[k], smooth[k + 1] - smooth[k], bar_of[k] != 0))
|
| 242 |
+
out = []
|
| 243 |
+
for bi, t, bl, omit in lines:
|
| 244 |
+
out.append([t, bl, meter, float(bi), float(omit)])
|
| 245 |
+
return np.array(out, dtype=np.float64)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def grid_score(beat_act: np.ndarray, sections: np.ndarray, t0_ms: float, t1_ms: float) -> float:
|
| 249 |
+
from .timing import beat_times
|
| 250 |
+
b, _ = beat_times(sections, t0_ms, t1_ms)
|
| 251 |
+
if len(b) == 0:
|
| 252 |
+
return 0.0
|
| 253 |
+
return float(np.interp(b / 10.0, np.arange(len(beat_act)), beat_act.astype(np.float64)).mean())
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def decode_timing_auto(beat_act: np.ndarray, down_act: np.ndarray, t0_ms: float, t1_ms: float,
|
| 257 |
+
margin: float = 0.05) -> np.ndarray:
|
| 258 |
+
"""Use the simple windowed constant-tempo map unless the beat-tracked hybrid map explains the
|
| 259 |
+
beat activations clearly better (songs whose tempo really changes)."""
|
| 260 |
+
from .timing import decode_timing
|
| 261 |
+
simple = decode_timing(beat_act, down_act, t0_ms, t1_ms)
|
| 262 |
+
hybrid = decode_timing_hybrid(beat_act, down_act, t0_ms, t1_ms)
|
| 263 |
+
s0, s1 = grid_score(beat_act, simple, t0_ms, t1_ms), grid_score(beat_act, hybrid, t0_ms, t1_ms)
|
| 264 |
+
return hybrid if s1 > s0 * (1 + margin) else simple
|
chartgen/data/__init__.py
ADDED
|
File without changes
|
chartgen/data/osu.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Parse osu!taiko ``.osu`` files into beat-grid note events.
|
| 2 |
+
|
| 3 |
+
Each note becomes an event ``(t, tau, ell, delta)`` as defined in README:
|
| 4 |
+
|
| 5 |
+
* ``t`` -- position on the beat grid, in beats from the first timing point,
|
| 6 |
+
snapped to a 1/48-beat grid (covers 1/16 and 1/12 divisions).
|
| 7 |
+
* ``tau`` -- note type (see :class:`NoteType`).
|
| 8 |
+
* ``ell`` -- length of rolls and balloons, in beats (0 for hits).
|
| 9 |
+
* ``delta`` -- actual time minus grid time, in milliseconds.
|
| 10 |
+
|
| 11 |
+
Taiko encoding in ``.osu``:
|
| 12 |
+
|
| 13 |
+
* hit circle: Don, or Ka if the hitsound has whistle (2) or clap (8);
|
| 14 |
+
finish (4) makes it a big note.
|
| 15 |
+
* slider: drumroll (big with finish); its length follows from pixel length,
|
| 16 |
+
slider velocity and beat length.
|
| 17 |
+
* spinner: balloon, ending at ``endTime``.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import bisect
|
| 23 |
+
import math
|
| 24 |
+
from dataclasses import dataclass, field
|
| 25 |
+
from enum import IntEnum
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
GRID = 48 # sub-beat resolution: lcm of 16 and 12
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class NoteType(IntEnum):
|
| 32 |
+
DON = 0
|
| 33 |
+
KA = 1
|
| 34 |
+
BIG_DON = 2
|
| 35 |
+
BIG_KA = 3
|
| 36 |
+
ROLL = 4
|
| 37 |
+
BIG_ROLL = 5
|
| 38 |
+
BALLOON = 6
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@dataclass
|
| 42 |
+
class TimingPoint:
|
| 43 |
+
time: float # ms
|
| 44 |
+
beat_length: float # ms per beat (uninherited) or negative SV value (inherited)
|
| 45 |
+
meter: int
|
| 46 |
+
uninherited: bool
|
| 47 |
+
kiai: bool
|
| 48 |
+
omit_barline: bool = False # effects bit 8: hide the first bar line of this section (red lines)
|
| 49 |
+
|
| 50 |
+
@property
|
| 51 |
+
def sv(self) -> float | None:
|
| 52 |
+
"""Slider-velocity multiplier of an inherited (green) point."""
|
| 53 |
+
if self.uninherited or self.beat_length >= 0:
|
| 54 |
+
return None
|
| 55 |
+
return min(max(-100.0 / self.beat_length, 0.1), 10.0)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@dataclass
|
| 59 |
+
class Section:
|
| 60 |
+
"""A stretch of constant tempo starting at an uninherited timing point."""
|
| 61 |
+
|
| 62 |
+
time: float
|
| 63 |
+
beat_length: float
|
| 64 |
+
meter: int
|
| 65 |
+
start_beat: float # global beat index of this section's start
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@dataclass
|
| 69 |
+
class Note:
|
| 70 |
+
time: float # ms, as written in the file
|
| 71 |
+
type: NoteType
|
| 72 |
+
end_time: float # ms; equals time for hits
|
| 73 |
+
beat: float # snapped global beat position
|
| 74 |
+
grid_index: int # snapped position in 1/GRID beats within the section
|
| 75 |
+
divisor: int # smallest beat division that represents the position (1, 2, 3, 4, 6, ...)
|
| 76 |
+
beat_in_measure: float
|
| 77 |
+
length_beats: float
|
| 78 |
+
delta_ms: float
|
| 79 |
+
sv: float = 1.0 # effective slider-velocity (scroll) multiplier at this note
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@dataclass
|
| 83 |
+
class TaikoChart:
|
| 84 |
+
metadata: dict[str, str]
|
| 85 |
+
difficulty: dict[str, float]
|
| 86 |
+
audio_filename: str
|
| 87 |
+
mode: int
|
| 88 |
+
sections: list[Section]
|
| 89 |
+
timing_points: list[TimingPoint]
|
| 90 |
+
notes: list[Note] = field(default_factory=list)
|
| 91 |
+
kiai: list[tuple[float, float]] = field(default_factory=list) # (start, end) ms
|
| 92 |
+
|
| 93 |
+
@property
|
| 94 |
+
def beatmap_id(self) -> int | None:
|
| 95 |
+
v = self.metadata.get("BeatmapID")
|
| 96 |
+
return int(v) if v not in (None, "") else None
|
| 97 |
+
|
| 98 |
+
@property
|
| 99 |
+
def beatmapset_id(self) -> int | None:
|
| 100 |
+
v = self.metadata.get("BeatmapSetID")
|
| 101 |
+
return int(v) if v not in (None, "") else None
|
| 102 |
+
|
| 103 |
+
@property
|
| 104 |
+
def version(self) -> str:
|
| 105 |
+
return self.metadata.get("Version", "")
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class OsuParseError(ValueError):
|
| 109 |
+
pass
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _read_sections(text: str) -> dict[str, list[str]]:
|
| 113 |
+
out: dict[str, list[str]] = {}
|
| 114 |
+
current = None
|
| 115 |
+
for raw in text.splitlines():
|
| 116 |
+
line = raw.strip()
|
| 117 |
+
if not line or line.startswith("//"):
|
| 118 |
+
continue
|
| 119 |
+
if line.startswith("[") and line.endswith("]"):
|
| 120 |
+
current = line[1:-1]
|
| 121 |
+
out.setdefault(current, [])
|
| 122 |
+
elif current is not None:
|
| 123 |
+
out[current].append(line)
|
| 124 |
+
return out
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _kv(lines: list[str]) -> dict[str, str]:
|
| 128 |
+
d = {}
|
| 129 |
+
for line in lines:
|
| 130 |
+
if ":" in line:
|
| 131 |
+
k, v = line.split(":", 1)
|
| 132 |
+
d[k.strip()] = v.strip()
|
| 133 |
+
return d
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _parse_timing_points(lines: list[str]) -> list[TimingPoint]:
|
| 137 |
+
tps = []
|
| 138 |
+
for line in lines:
|
| 139 |
+
p = line.split(",")
|
| 140 |
+
if len(p) < 2:
|
| 141 |
+
continue
|
| 142 |
+
time = float(p[0])
|
| 143 |
+
beat_length = float(p[1])
|
| 144 |
+
meter = int(p[2]) if len(p) > 2 and p[2] else 4
|
| 145 |
+
uninherited = (p[6] != "0") if len(p) > 6 and p[6] else True
|
| 146 |
+
effects = int(p[7]) if len(p) > 7 and p[7] else 0
|
| 147 |
+
tps.append(TimingPoint(time, beat_length, meter if meter > 0 else 4, uninherited, bool(effects & 1), bool(effects & 8)))
|
| 148 |
+
tps.sort(key=lambda t: (t.time, not t.uninherited))
|
| 149 |
+
return tps
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _build_sections(tps: list[TimingPoint]) -> list[Section]:
|
| 153 |
+
red = [t for t in tps if t.uninherited and t.beat_length > 0]
|
| 154 |
+
if not red:
|
| 155 |
+
raise OsuParseError("no uninherited timing point")
|
| 156 |
+
sections: list[Section] = []
|
| 157 |
+
for tp in red:
|
| 158 |
+
if sections:
|
| 159 |
+
prev = sections[-1]
|
| 160 |
+
if tp.time == prev.time: # duplicate red line at same time: later one wins
|
| 161 |
+
sections[-1] = Section(tp.time, tp.beat_length, tp.meter, prev.start_beat)
|
| 162 |
+
continue
|
| 163 |
+
# A red line restarts the bar in osu!, so each section starts on a whole global beat;
|
| 164 |
+
# otherwise the 1/48 grid and metrical phase would be misaligned after tempo changes.
|
| 165 |
+
raw = prev.start_beat + (tp.time - prev.time) / prev.beat_length
|
| 166 |
+
start = float(round(raw)) if abs(raw - round(raw)) < 1e-3 else float(math.ceil(raw))
|
| 167 |
+
else:
|
| 168 |
+
start = 0.0
|
| 169 |
+
sections.append(Section(tp.time, tp.beat_length, tp.meter, start))
|
| 170 |
+
return sections
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _section_at(sections: list[Section], times: list[float], t: float) -> Section:
|
| 174 |
+
# Notes before the first red line belong to the first section (extrapolated backwards).
|
| 175 |
+
i = bisect.bisect_right(times, t) - 1
|
| 176 |
+
return sections[max(i, 0)]
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def _sv_table(tps: list[TimingPoint]) -> tuple[list[float], list[float]]:
|
| 180 |
+
"""(times, sv) step function: red lines reset SV to 1, green lines set it."""
|
| 181 |
+
times, vals = [], []
|
| 182 |
+
for tp in tps: # sorted by (time, red first), so a green line at the same time wins
|
| 183 |
+
v = 1.0 if tp.uninherited else (tp.sv if tp.sv is not None else None)
|
| 184 |
+
if v is None:
|
| 185 |
+
continue
|
| 186 |
+
times.append(tp.time)
|
| 187 |
+
vals.append(v)
|
| 188 |
+
return times, vals
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def _sv_at(table: tuple[list[float], list[float]], t: float) -> float:
|
| 192 |
+
times, vals = table
|
| 193 |
+
i = bisect.bisect_right(times, t + 1e-6) - 1
|
| 194 |
+
return vals[i] if i >= 0 else 1.0
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def _snap(sec: Section, t: float) -> tuple[int, float, float]:
|
| 198 |
+
"""Return (grid index within section, snapped global beat, delta ms)."""
|
| 199 |
+
local = (t - sec.time) / sec.beat_length
|
| 200 |
+
n = round(local * GRID)
|
| 201 |
+
grid_time = sec.time + n / GRID * sec.beat_length
|
| 202 |
+
return n, sec.start_beat + n / GRID, t - grid_time
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def _divisor(n: int) -> int:
|
| 206 |
+
return GRID // math.gcd(n % GRID, GRID) if n % GRID else 1
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def _kiai_ranges(tps: list[TimingPoint]) -> list[tuple[float, float]]:
|
| 210 |
+
ranges, start = [], None
|
| 211 |
+
for tp in tps:
|
| 212 |
+
if tp.kiai and start is None:
|
| 213 |
+
start = tp.time
|
| 214 |
+
elif not tp.kiai and start is not None:
|
| 215 |
+
ranges.append((start, tp.time))
|
| 216 |
+
start = None
|
| 217 |
+
if start is not None:
|
| 218 |
+
ranges.append((start, math.inf))
|
| 219 |
+
return ranges
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def parse_osu(text: str) -> TaikoChart:
|
| 223 |
+
secs = _read_sections(text)
|
| 224 |
+
general = _kv(secs.get("General", []))
|
| 225 |
+
metadata = _kv(secs.get("Metadata", []))
|
| 226 |
+
difficulty = {k: float(v) for k, v in _kv(secs.get("Difficulty", [])).items() if _isfloat(v)}
|
| 227 |
+
mode = int(general.get("Mode", "0"))
|
| 228 |
+
|
| 229 |
+
tps = _parse_timing_points(secs.get("TimingPoints", []))
|
| 230 |
+
sections = _build_sections(tps)
|
| 231 |
+
sec_times = [s.time for s in sections]
|
| 232 |
+
slider_mult = difficulty.get("SliderMultiplier", 1.4)
|
| 233 |
+
|
| 234 |
+
sv_table = _sv_table(tps)
|
| 235 |
+
notes: list[Note] = []
|
| 236 |
+
for line in secs.get("HitObjects", []):
|
| 237 |
+
p = line.split(",")
|
| 238 |
+
if len(p) < 5:
|
| 239 |
+
continue
|
| 240 |
+
time = float(p[2])
|
| 241 |
+
kind = int(p[3])
|
| 242 |
+
hs = int(p[4]) if p[4] else 0
|
| 243 |
+
big = bool(hs & 4)
|
| 244 |
+
sec = _section_at(sections, sec_times, time)
|
| 245 |
+
|
| 246 |
+
if kind & 1:
|
| 247 |
+
ka = bool(hs & (2 | 8))
|
| 248 |
+
ntype = (NoteType.BIG_KA if big else NoteType.KA) if ka else (NoteType.BIG_DON if big else NoteType.DON)
|
| 249 |
+
end = time
|
| 250 |
+
elif kind & 2:
|
| 251 |
+
ntype = NoteType.BIG_ROLL if big else NoteType.ROLL
|
| 252 |
+
slides = int(p[6]) if len(p) > 6 and p[6] else 1
|
| 253 |
+
length = float(p[7]) if len(p) > 7 and p[7] else 0.0
|
| 254 |
+
sv = _sv_at(sv_table, time)
|
| 255 |
+
end = time + length * slides / (slider_mult * 100.0 * sv) * sec.beat_length
|
| 256 |
+
elif kind & 8:
|
| 257 |
+
ntype = NoteType.BALLOON
|
| 258 |
+
end = float(p[5]) if len(p) > 5 and p[5] else time
|
| 259 |
+
else:
|
| 260 |
+
continue
|
| 261 |
+
|
| 262 |
+
n, beat, delta = _snap(sec, time)
|
| 263 |
+
local_beat = n / GRID
|
| 264 |
+
length_beats = (end - time) / sec.beat_length if end > time else 0.0
|
| 265 |
+
notes.append(
|
| 266 |
+
Note(
|
| 267 |
+
time=time,
|
| 268 |
+
type=ntype,
|
| 269 |
+
end_time=end,
|
| 270 |
+
beat=beat,
|
| 271 |
+
grid_index=n,
|
| 272 |
+
divisor=_divisor(n),
|
| 273 |
+
beat_in_measure=local_beat % sec.meter,
|
| 274 |
+
length_beats=length_beats,
|
| 275 |
+
delta_ms=delta,
|
| 276 |
+
sv=_sv_at(sv_table, time),
|
| 277 |
+
)
|
| 278 |
+
)
|
| 279 |
+
notes.sort(key=lambda x: x.time)
|
| 280 |
+
|
| 281 |
+
return TaikoChart(
|
| 282 |
+
metadata=metadata,
|
| 283 |
+
difficulty=difficulty,
|
| 284 |
+
audio_filename=general.get("AudioFilename", ""),
|
| 285 |
+
mode=mode,
|
| 286 |
+
sections=sections,
|
| 287 |
+
timing_points=tps,
|
| 288 |
+
notes=notes,
|
| 289 |
+
kiai=_kiai_ranges(tps),
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def time_to_beat(sections: list[Section], t: float) -> float:
|
| 294 |
+
"""Continuous global beat position of time t (ms)."""
|
| 295 |
+
i = max(bisect.bisect_right([s.time for s in sections], t) - 1, 0)
|
| 296 |
+
s = sections[i]
|
| 297 |
+
return s.start_beat + (t - s.time) / s.beat_length
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def beat_to_time(sections: list[Section], b: float) -> float:
|
| 301 |
+
i = max(bisect.bisect_right([s.start_beat for s in sections], b) - 1, 0)
|
| 302 |
+
s = sections[i]
|
| 303 |
+
return s.time + (b - s.start_beat) * s.beat_length
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def parse_osu_file(path: str | Path) -> TaikoChart:
|
| 307 |
+
return parse_osu(Path(path).read_text(encoding="utf-8-sig", errors="replace"))
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def read_mode(path: str | Path) -> int:
|
| 311 |
+
"""Read only the Mode field, for fast filtering of large .osu collections."""
|
| 312 |
+
with open(path, encoding="utf-8-sig", errors="replace") as f:
|
| 313 |
+
for line in f:
|
| 314 |
+
s = line.strip()
|
| 315 |
+
if s.startswith("Mode:"):
|
| 316 |
+
return int(s.split(":", 1)[1].strip() or 0)
|
| 317 |
+
if s == "[Metadata]" or s == "[HitObjects]":
|
| 318 |
+
break
|
| 319 |
+
return 0
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def _isfloat(v: str) -> bool:
|
| 323 |
+
try:
|
| 324 |
+
float(v)
|
| 325 |
+
return True
|
| 326 |
+
except ValueError:
|
| 327 |
+
return False
|
chartgen/dataset.py
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 2 |
+
|
| 3 |
+
A training example is a 20 s window of one chart:
|
| 4 |
+
|
| 5 |
+
* audio: log-Mel frames plus beat-phase features from the chart's timing points
|
| 6 |
+
(an oracle beat grid for now; inference will need a beat tracker);
|
| 7 |
+
* events: the notes in the window as decoder tokens;
|
| 8 |
+
* plan: per 16-beat section, note density (rho) and finest subdivision class (r).
|
| 9 |
+
|
| 10 |
+
Decoder step k reads tokens [BOS, e_1..e_k] and predicts where e_{k+1} is: how many beats
|
| 11 |
+
ahead (0..MAX_AHEAD, or END) and its absolute 1/48 phase within that beat. Positions are
|
| 12 |
+
anchored to the grid, so one wrong prediction does not shift every later note (as relative
|
| 13 |
+
gaps would). Given the position, it predicts the note's type, length, SV and delta.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import math
|
| 19 |
+
import os
|
| 20 |
+
import pickle
|
| 21 |
+
import random
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
import torch
|
| 27 |
+
|
| 28 |
+
GRID = 48
|
| 29 |
+
MAX_GAP = 32 * GRID # largest representable distance between notes
|
| 30 |
+
N_GAP = MAX_GAP + 1
|
| 31 |
+
MAX_AHEAD = 32 # beats ahead classes 0..MAX_AHEAD
|
| 32 |
+
AHEAD_END = MAX_AHEAD + 1 # end of window
|
| 33 |
+
N_AHEAD = MAX_AHEAD + 2
|
| 34 |
+
N_TYPE = 7
|
| 35 |
+
N_LEN = 65 # length in quarter beats, 0..64
|
| 36 |
+
SECTION_BEATS = 16
|
| 37 |
+
DIVISORS = [1, 2, 3, 4, 6, 8, 12, 16] # anything finer -> class 8
|
| 38 |
+
N_SUBDIV = len(DIVISORS) + 1
|
| 39 |
+
WINDOW = 2000 # frames (100 fps) = 20 s
|
| 40 |
+
MAX_EVENTS = 384
|
| 41 |
+
MAX_BARS = 40 # measures per window for the per-measure plan (a 20 s window stretched by 15% holds up to 35)
|
| 42 |
+
BAR_F = 17 # per-measure plan features, see bar_plan()
|
| 43 |
+
SUSTAIN = 16 # plan column: share of the measure covered by a roll / balloon body
|
| 44 |
+
# Coordinates of the note heads' audio-frame and bar-position lookups in training: "true" = the note's real time
|
| 45 |
+
# (residual included; the behaviour up to b9), "grid" = its grid time, as generation uses (verification report §9.2;
|
| 46 |
+
# stage 4b). Set from train.py --note-coord.
|
| 47 |
+
NOTE_COORD = "true"
|
| 48 |
+
GAP0 = 6 # plan columns GAP0 .. GAP0 + N_GAP_BINS - 1: gap histogram
|
| 49 |
+
REP_F = 9 # per-bar repetition hint: offset to the most similar earlier bar (1..8, one-hot) + similarity
|
| 50 |
+
MAX_SECTIONS = 16
|
| 51 |
+
SV_STEPS = 12 # SV classes: log2(sv) in 1/12-octave steps over [-2, 2]
|
| 52 |
+
N_SV = 4 * SV_STEPS + 1
|
| 53 |
+
SV_ONE = 2 * SV_STEPS # class of SV = 1.0
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def sv_class(sv: np.ndarray) -> np.ndarray:
|
| 57 |
+
return np.clip(np.round(np.log2(np.maximum(sv, 1e-3)) * SV_STEPS) + SV_ONE, 0, N_SV - 1).astype(np.int64)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def sv_value(cls: np.ndarray) -> np.ndarray:
|
| 61 |
+
return 2.0 ** ((np.asarray(cls) - SV_ONE) / SV_STEPS)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def load_songs(paths: list[Path], mmap: bool = False) -> list[dict]:
|
| 65 |
+
"""Load feature shards. With mmap, each shard's mel spectrograms are written once to a
|
| 66 |
+
sibling .mel.npy file and replaced by read-only memory-mapped slices, so the full corpus
|
| 67 |
+
does not have to fit in RAM (the OS page cache keeps the hot part)."""
|
| 68 |
+
songs = []
|
| 69 |
+
for p in paths:
|
| 70 |
+
p = Path(p)
|
| 71 |
+
with open(p, "rb") as f:
|
| 72 |
+
shard = pickle.load(f)
|
| 73 |
+
if mmap and shard:
|
| 74 |
+
npy = p.with_suffix(".mel.npy")
|
| 75 |
+
lens = [len(s["mel"]) for s in shard]
|
| 76 |
+
if not npy.exists():
|
| 77 |
+
tmp = npy.with_suffix(f".{os.getpid()}.tmp.npy") # per process: concurrent loaders may race
|
| 78 |
+
mm = np.lib.format.open_memmap(tmp, mode="w+", dtype=np.float16, shape=(sum(lens), shard[0]["mel"].shape[1]))
|
| 79 |
+
o = 0
|
| 80 |
+
for s, n in zip(shard, lens):
|
| 81 |
+
mm[o:o + n] = s["mel"]
|
| 82 |
+
o += n
|
| 83 |
+
mm.flush()
|
| 84 |
+
del mm
|
| 85 |
+
os.replace(tmp, npy)
|
| 86 |
+
mm = np.load(npy, mmap_mode="r")
|
| 87 |
+
o = 0
|
| 88 |
+
for s, n in zip(shard, lens):
|
| 89 |
+
s["mel"] = mm[o:o + n]
|
| 90 |
+
o += n
|
| 91 |
+
songs.extend(shard)
|
| 92 |
+
return songs
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _beats_at(sections: np.ndarray, t_ms: np.ndarray) -> np.ndarray:
|
| 96 |
+
idx = np.clip(np.searchsorted(sections[:, 0], t_ms, side="right") - 1, 0, len(sections) - 1)
|
| 97 |
+
s = sections[idx]
|
| 98 |
+
return s[:, 3] + (t_ms - s[:, 0]) / s[:, 1]
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _measure_pos(sections: np.ndarray, t_ms: np.ndarray) -> np.ndarray:
|
| 102 |
+
idx = np.clip(np.searchsorted(sections[:, 0], t_ms, side="right") - 1, 0, len(sections) - 1)
|
| 103 |
+
s = sections[idx]
|
| 104 |
+
local = (t_ms - s[:, 0]) / s[:, 1]
|
| 105 |
+
return np.mod(local, s[:, 2]) / s[:, 2] # 0..1 within the bar
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _measure_table(sections: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 109 |
+
"""(section start beats, meters, index of each section's first measure). A red line restarts the bar in
|
| 110 |
+
osu!, so measures run from each section's start in steps of its meter; the last measure of a section can be
|
| 111 |
+
partial (it ends where the next section starts)."""
|
| 112 |
+
sb = np.asarray(sections[:, 3], np.float64)
|
| 113 |
+
meter = np.where(sections[:, 2] > 0, sections[:, 2], 4).astype(np.float64)
|
| 114 |
+
n = np.ceil(np.maximum(np.diff(sb), 0) / meter[:-1] - 1e-9).astype(np.int64)
|
| 115 |
+
return sb, meter, np.concatenate([[0], np.cumsum(n)]).astype(np.int64)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def measure_at(sections: np.ndarray, beats: np.ndarray) -> np.ndarray:
|
| 119 |
+
"""Global measure index (real measures, see _measure_table) of global beat positions. Beats before the first
|
| 120 |
+
section extend its measures backwards (negative indices)."""
|
| 121 |
+
sb, meter, first = _measure_table(sections)
|
| 122 |
+
b = np.asarray(beats, np.float64)
|
| 123 |
+
j = np.clip(np.searchsorted(sb, b + 1e-9, side="right") - 1, 0, len(sb) - 1)
|
| 124 |
+
return first[j] + np.floor((b - sb[j]) / meter[j] + 1e-9).astype(np.int64)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def measure_span(sections: np.ndarray, idx: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
| 128 |
+
"""(start beat, end beat) of global measures; the end is cut at the next section's start."""
|
| 129 |
+
sb, meter, first = _measure_table(sections)
|
| 130 |
+
idx = np.asarray(idx, np.int64)
|
| 131 |
+
j = np.clip(np.searchsorted(first, idx, side="right") - 1, 0, len(sb) - 1)
|
| 132 |
+
# several sections can share a first index when a section is empty; take the last one whose range holds idx
|
| 133 |
+
start = sb[j] + (idx - first[j]) * meter[j]
|
| 134 |
+
nxt = np.where(j + 1 < len(sb), sb[np.minimum(j + 1, len(sb) - 1)], np.inf)
|
| 135 |
+
return start, np.minimum(start + meter[j], nxt)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def beat_ms(sections: np.ndarray, beats: np.ndarray) -> np.ndarray:
|
| 139 |
+
"""ms of global beat positions (inverse of _beats_at)."""
|
| 140 |
+
b = np.asarray(beats, np.float64)
|
| 141 |
+
j = np.clip(np.searchsorted(sections[:, 3], b + 1e-9, side="right") - 1, 0, len(sections) - 1)
|
| 142 |
+
return sections[j, 0] + (b - sections[j, 3]) * sections[j, 1]
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def roll_end_beats(sections: np.ndarray, start_beats: np.ndarray, lengths: np.ndarray) -> np.ndarray:
|
| 146 |
+
"""Global beat where a roll / balloon ends. length_beats is counted in the beats of the section where the note
|
| 147 |
+
starts (osu.data), so the end is found in ms and mapped back; this matters when the body crosses a red line."""
|
| 148 |
+
sb = np.asarray(start_beats, np.float64)
|
| 149 |
+
j = np.clip(np.searchsorted(sections[:, 3], sb + 1e-9, side="right") - 1, 0, len(sections) - 1)
|
| 150 |
+
end_ms = beat_ms(sections, sb) + np.maximum(np.asarray(lengths, np.float64), 0.0) * sections[j, 1]
|
| 151 |
+
return np.maximum(_beats_at(sections, end_ms), sb)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def plan_active(plan: np.ndarray) -> np.ndarray:
|
| 155 |
+
"""Measures that are not rests under a (human or predicted) plan: a hit note, a roll / balloon starting in the
|
| 156 |
+
measure, or a sustained note covering part of it. The rest mask allows notes only in these measures."""
|
| 157 |
+
return (plan[..., 0] > 0.5) | (plan[..., 3] > 0.5) | (plan[..., SUSTAIN] > 0.1)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def section_gap_dists(all_g: np.ndarray, hit: np.ndarray, all_sec: np.ndarray) -> np.ndarray:
|
| 161 |
+
"""Per section: distribution of gaps between consecutive hit notes (bin of the later note's section)
|
| 162 |
+
and of consecutive-gap ratios (section of the last note of the pair); zero rows where undefined."""
|
| 163 |
+
from .gapstats import N_GAP_BINS, N_RATIO_BINS, gap_bins, ratio_bins
|
| 164 |
+
out = np.zeros((MAX_SECTIONS, N_GAP_BINS + N_RATIO_BINS), np.float32)
|
| 165 |
+
g, sec = all_g[hit], all_sec[hit]
|
| 166 |
+
if len(g) < 2:
|
| 167 |
+
return out
|
| 168 |
+
gaps = np.diff(g) / GRID
|
| 169 |
+
gb, s1 = gap_bins(gaps), sec[1:]
|
| 170 |
+
ok = (s1 >= 0) & (s1 < MAX_SECTIONS)
|
| 171 |
+
np.add.at(out, (s1[ok], gb[ok]), 1.0)
|
| 172 |
+
rb, s2 = ratio_bins(gaps), sec[2:]
|
| 173 |
+
ok = (rb >= 0) & (s2 >= 0) & (s2 < MAX_SECTIONS)
|
| 174 |
+
np.add.at(out, (s2[ok], N_GAP_BINS + rb[ok]), 1.0)
|
| 175 |
+
for a, b in ((0, N_GAP_BINS), (N_GAP_BINS, N_GAP_BINS + N_RATIO_BINS)):
|
| 176 |
+
tot = out[:, a:b].sum(1, keepdims=True)
|
| 177 |
+
out[:, a:b] = np.where(tot > 0, out[:, a:b] / np.maximum(tot, 1), 0)
|
| 178 |
+
return out
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def bar_plan(all_g: np.ndarray, types: np.ndarray, bar0: int, sections: np.ndarray, lengths: np.ndarray | None = None,
|
| 182 |
+
n_bars: int = MAX_BARS) -> np.ndarray:
|
| 183 |
+
"""Per measure (real measures from the chart's timing sections, index relative to bar0) of a chart:
|
| 184 |
+
[play (has a hit note), log1p(hit notes per beat), big-note share, roll start, triplet-grid share (1/3, 1/6, 1/12),
|
| 185 |
+
1/8-or-finer share, gap histogram (10 bins of gapstats, gaps ending in the measure, normalised),
|
| 186 |
+
sustain (share of the measure covered by a roll / balloon body)]. A measure is a rest when it has neither a hit
|
| 187 |
+
note nor a sustained note: play = 0 and sustain = 0."""
|
| 188 |
+
from .gapstats import N_GAP_BINS, gap_bins
|
| 189 |
+
out = np.zeros((n_bars, BAR_F), np.float32)
|
| 190 |
+
bar = measure_at(sections, all_g / GRID) - bar0
|
| 191 |
+
st, en = measure_span(sections, np.arange(n_bars) + bar0)
|
| 192 |
+
mlen = np.maximum(en - st, 1e-6)
|
| 193 |
+
hit = types <= 3
|
| 194 |
+
div = subdiv_class(all_g)
|
| 195 |
+
trip = np.isin(div, [DIVISORS.index(3), DIVISORS.index(6), DIVISORS.index(12)])
|
| 196 |
+
fine = div >= DIVISORS.index(8)
|
| 197 |
+
gh = all_g[hit]
|
| 198 |
+
gb = gap_bins(np.diff(gh) / GRID) if len(gh) > 1 else np.zeros(0, np.int64)
|
| 199 |
+
gbar = bar[hit][1:]
|
| 200 |
+
for k in range(n_bars):
|
| 201 |
+
m = (bar == k)
|
| 202 |
+
mh = m & hit
|
| 203 |
+
if not m.any():
|
| 204 |
+
continue
|
| 205 |
+
n = int(mh.sum())
|
| 206 |
+
out[k, 0] = float(n > 0)
|
| 207 |
+
out[k, 1] = np.log1p(n / mlen[k])
|
| 208 |
+
if n:
|
| 209 |
+
out[k, 2] = float((types[mh] >= 2).mean())
|
| 210 |
+
out[k, 4] = float(trip[mh].mean())
|
| 211 |
+
out[k, 5] = float(fine[mh].mean())
|
| 212 |
+
out[k, 3] = float(((types >= 4) & m).any())
|
| 213 |
+
sel = gb[gbar == k]
|
| 214 |
+
if len(sel):
|
| 215 |
+
out[k, GAP0:GAP0 + N_GAP_BINS] = np.bincount(sel, minlength=N_GAP_BINS) / len(sel)
|
| 216 |
+
if lengths is not None: # roll / balloon bodies: overlap of [start, end] beats with each measure
|
| 217 |
+
b = all_g / GRID
|
| 218 |
+
rb = b[types >= 4]
|
| 219 |
+
for x, e in zip(rb, roll_end_beats(sections, rb, np.asarray(lengths, np.float64)[types >= 4])):
|
| 220 |
+
ov = np.minimum(en, e) - np.maximum(st, x)
|
| 221 |
+
cover = np.where(ov > 0, ov, 0.0) / mlen
|
| 222 |
+
cover[(st <= x) & (x < en)] = np.maximum(cover[(st <= x) & (x < en)], 1e-3) # a zero-length start still marks its measure
|
| 223 |
+
out[:, SUSTAIN] = np.minimum(out[:, SUSTAIN] + cover, 1.0)
|
| 224 |
+
return out
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def rep_hint(mel: np.ndarray, frame_bar: np.ndarray, phase: np.ndarray) -> np.ndarray:
|
| 228 |
+
"""For each measure of the window: which earlier measure (1..8 back) sounds most alike, and how much.
|
| 229 |
+
Profile: full-band positive spectral flux at 48 slots of the measure (phase within the measure, 12 per beat in
|
| 230 |
+
4/4); cosine similarity. Uses the audio only, so it is available at generation time."""
|
| 231 |
+
m = np.asarray(mel, np.float32)
|
| 232 |
+
flux = np.maximum(np.diff(m, axis=0, prepend=m[:1]), 0).mean(1)
|
| 233 |
+
flux = (flux - flux.mean()) / (flux.std() + 1e-6)
|
| 234 |
+
out = np.zeros((MAX_BARS, REP_F), np.float32)
|
| 235 |
+
prof = {}
|
| 236 |
+
for k in range(MAX_BARS):
|
| 237 |
+
fr = np.where(frame_bar == k)[0]
|
| 238 |
+
if len(fr) < 8:
|
| 239 |
+
continue
|
| 240 |
+
pos = np.clip((phase[fr] * 48).astype(np.int64), 0, 47)
|
| 241 |
+
v = np.full(48, np.nan, np.float32)
|
| 242 |
+
for q in range(48):
|
| 243 |
+
sel = flux[fr][pos == q]
|
| 244 |
+
if len(sel):
|
| 245 |
+
v[q] = sel.max()
|
| 246 |
+
if np.isnan(v).mean() < 0.3:
|
| 247 |
+
v = np.nan_to_num(v, nan=float(np.nanmean(v)))
|
| 248 |
+
prof[k] = (v - v.mean()) / (np.linalg.norm(v - v.mean()) + 1e-6)
|
| 249 |
+
for k, v in prof.items():
|
| 250 |
+
best, off = -1.0, 0
|
| 251 |
+
for o in range(1, 9):
|
| 252 |
+
if k - o in prof:
|
| 253 |
+
c = float(v @ prof[k - o])
|
| 254 |
+
if c > best:
|
| 255 |
+
best, off = c, o
|
| 256 |
+
if off:
|
| 257 |
+
out[k, off - 1] = 1.0
|
| 258 |
+
out[k, 8] = best
|
| 259 |
+
return out
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def stretch(song: dict, chart: dict, start_frame: int, r: float):
|
| 263 |
+
"""Tempo augmentation: the window starting at start_frame played r times faster (r > 1) or slower.
|
| 264 |
+
Returns (song-like dict, chart dict, 0): mel resampled in time; note times, timing sections and kiai
|
| 265 |
+
rescaled around the window start; beat positions and lengths in beats unchanged."""
|
| 266 |
+
mel = song["mel"]
|
| 267 |
+
src = start_frame + np.arange(WINDOW) * r
|
| 268 |
+
i0 = np.clip(np.floor(src).astype(np.int64), 0, len(mel) - 1)
|
| 269 |
+
i1 = np.clip(i0 + 1, 0, len(mel) - 1)
|
| 270 |
+
w = (src - np.floor(src))[:, None].astype(np.float32)
|
| 271 |
+
seg = (np.asarray(mel[i0], np.float32) * (1 - w) + np.asarray(mel[i1], np.float32) * w).astype(mel.dtype)
|
| 272 |
+
t0 = start_frame * 10.0
|
| 273 |
+
c = dict(chart)
|
| 274 |
+
c["time"] = (chart["time"] - t0) / r
|
| 275 |
+
sec = chart["sections"].copy()
|
| 276 |
+
sec[:, 0] = (sec[:, 0] - t0) / r
|
| 277 |
+
sec[:, 1] = sec[:, 1] / r
|
| 278 |
+
c["sections"] = sec
|
| 279 |
+
c["delta_ms"] = chart["delta_ms"] / r
|
| 280 |
+
if "kiai" in chart and len(chart["kiai"]):
|
| 281 |
+
c["kiai"] = (np.asarray(chart["kiai"], float) - t0) / r
|
| 282 |
+
return {"mel": seg}, c, 0
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def subdiv_class(grid_idx: np.ndarray) -> np.ndarray:
|
| 286 |
+
r = np.mod(grid_idx, GRID)
|
| 287 |
+
div = np.where(r == 0, 1, GRID // np.gcd(r, GRID))
|
| 288 |
+
out = np.full(div.shape, len(DIVISORS), dtype=np.int64)
|
| 289 |
+
for i, d in enumerate(DIVISORS):
|
| 290 |
+
out[div == d] = i
|
| 291 |
+
return out
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
@dataclass
|
| 295 |
+
class Example:
|
| 296 |
+
mel: np.ndarray # [W, 128] float16
|
| 297 |
+
beat_feat: np.ndarray # [W, 4]
|
| 298 |
+
frame_section: np.ndarray # [W] section index or -1
|
| 299 |
+
tier: int
|
| 300 |
+
gap: np.ndarray # [N+1] grid distance to next note (last = 0, end of window); kept for analysis
|
| 301 |
+
ev_gap: np.ndarray # [N] grid distance from the previous note
|
| 302 |
+
tgt_ahead: np.ndarray # [N+1] beats ahead of the next note (last = AHEAD_END)
|
| 303 |
+
tgt_phase: np.ndarray # [N+1] absolute phase (0..47) of the next note (last = -100)
|
| 304 |
+
ev_ahead: np.ndarray # [N] beats ahead of each event relative to the previous one
|
| 305 |
+
ev_type: np.ndarray # [N]
|
| 306 |
+
ev_len: np.ndarray # [N]
|
| 307 |
+
ev_delta: np.ndarray # [N] ms
|
| 308 |
+
ev_frame: np.ndarray # [N] frame within window
|
| 309 |
+
ev_phase: np.ndarray # [N] grid index mod 48
|
| 310 |
+
ev_bar: np.ndarray # [N] position in bar, 0..15 (sixteenths of the bar)
|
| 311 |
+
ev_section: np.ndarray # [N]
|
| 312 |
+
plan_rho: np.ndarray # [S] notes per beat
|
| 313 |
+
plan_r: np.ndarray # [S] subdivision class
|
| 314 |
+
ref_time: np.ndarray # [N] ms relative to window start (for F1)
|
| 315 |
+
start_grid: int # grid index the first gap is measured from
|
| 316 |
+
start_ms: float
|
| 317 |
+
grid_time: np.ndarray # [G] ms (relative to window start) of grid index start_grid + k
|
| 318 |
+
grid_bar: np.ndarray # [G] bar position in sixteenths
|
| 319 |
+
grid_section: np.ndarray # [G]
|
| 320 |
+
ev_sv: np.ndarray # [N] SV class
|
| 321 |
+
beat_tgt: np.ndarray # [W] soft beat target (linear interpolation onto frames)
|
| 322 |
+
down_tgt: np.ndarray # [W] soft downbeat target
|
| 323 |
+
beat_mask: np.ndarray # [W] frames where the chart's timing is defined
|
| 324 |
+
kiai_tgt: np.ndarray # [W]
|
| 325 |
+
kiai_mask: np.ndarray # [W]
|
| 326 |
+
plan_gap: np.ndarray | None = None # [S, N_GAP_BINS + N_RATIO_BINS] per-section gap and ratio distributions (gapstats)
|
| 327 |
+
bar_plan: np.ndarray | None = None # [MAX_BARS, BAR_F] per-bar plan of the chart (bar_plan())
|
| 328 |
+
frame_bar: np.ndarray | None = None # [W] bar index of each frame (-1 outside)
|
| 329 |
+
rep_hint: np.ndarray | None = None # [MAX_BARS, REP_F] repetition hint from the audio (rep_hint())
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def make_example(song: dict, chart: dict, start_frame: int) -> Example:
|
| 333 |
+
W = WINDOW
|
| 334 |
+
mel = song["mel"][start_frame:start_frame + W]
|
| 335 |
+
if len(mel) < W:
|
| 336 |
+
mel = np.concatenate([mel, np.full((W - len(mel), mel.shape[1]), mel.min(), dtype=mel.dtype)])
|
| 337 |
+
sec = chart["sections"]
|
| 338 |
+
start_ms = start_frame * 10.0
|
| 339 |
+
t = start_ms + np.arange(W) * 10.0
|
| 340 |
+
beats = _beats_at(sec, t)
|
| 341 |
+
bar = _measure_pos(sec, t)
|
| 342 |
+
beat_feat = np.stack([np.sin(2 * np.pi * beats), np.cos(2 * np.pi * beats),
|
| 343 |
+
np.sin(2 * np.pi * bar), np.cos(2 * np.pi * bar)], 1).astype(np.float32)
|
| 344 |
+
|
| 345 |
+
b0 = beats[0]
|
| 346 |
+
start_grid = math.ceil(b0 * GRID) - 1
|
| 347 |
+
sec0 = math.floor(b0 / SECTION_BEATS)
|
| 348 |
+
frame_section = np.floor(beats / SECTION_BEATS).astype(np.int64) - sec0
|
| 349 |
+
frame_section[(frame_section < 0) | (frame_section >= MAX_SECTIONS)] = -1
|
| 350 |
+
|
| 351 |
+
# notes in window
|
| 352 |
+
times = chart["time"]
|
| 353 |
+
sel = (times >= start_ms) & (times < start_ms + W * 10.0)
|
| 354 |
+
g = np.round(chart["beat"][sel] * GRID).astype(np.int64)
|
| 355 |
+
prev = np.concatenate([[start_grid], g])
|
| 356 |
+
gaps = np.diff(prev)
|
| 357 |
+
ahead_all = np.floor_divide(prev[1:], GRID) - np.floor_divide(prev[:-1], GRID)
|
| 358 |
+
keep = np.cumsum((gaps < 1) | (ahead_all > MAX_AHEAD)) == 0 # truncate at the first unrepresentable step
|
| 359 |
+
n = min(int(keep.sum()), MAX_EVENTS)
|
| 360 |
+
g, gaps, ahead = g[:n], gaps[:n], ahead_all[:n]
|
| 361 |
+
ev_time = times[sel][:n]
|
| 362 |
+
ev_type = chart["type"][sel][:n].astype(np.int64)
|
| 363 |
+
ev_len = np.clip(np.round(chart["length_beats"][sel][:n] * 4), 0, N_LEN - 1).astype(np.int64)
|
| 364 |
+
ev_delta = chart["delta_ms"][sel][:n].astype(np.float32)
|
| 365 |
+
coord_t = ev_time
|
| 366 |
+
if NOTE_COORD == "grid": # the note's grid time, exactly as generation's lookup tables (grid_time, grid_bar)
|
| 367 |
+
gb_ev = g / GRID
|
| 368 |
+
si_ev = np.clip(np.searchsorted(sec[:, 3], gb_ev, side="right") - 1, 0, len(sec) - 1)
|
| 369 |
+
coord_t = sec[si_ev, 0] + (gb_ev - sec[si_ev, 3]) * sec[si_ev, 1]
|
| 370 |
+
if NOTE_COORD == "grid": # float32 relative time, as generation rounds grid_time
|
| 371 |
+
ev_frame = np.clip(np.round((coord_t - start_ms).astype(np.float32) / np.float32(10.0)), 0, W - 1).astype(np.int64)
|
| 372 |
+
else:
|
| 373 |
+
ev_frame = np.clip(np.round((coord_t - start_ms) / 10.0), 0, W - 1).astype(np.int64)
|
| 374 |
+
ev_bar = np.clip(np.floor(_measure_pos(sec, coord_t) * 16), 0, 15).astype(np.int64)
|
| 375 |
+
ev_section = np.clip(np.floor(g / GRID / SECTION_BEATS).astype(np.int64) - sec0, 0, MAX_SECTIONS - 1)
|
| 376 |
+
|
| 377 |
+
# plan targets over full sections (whole chart, not just the window)
|
| 378 |
+
all_g = np.round(chart["beat"] * GRID).astype(np.int64)
|
| 379 |
+
all_sec = np.floor(all_g / GRID / SECTION_BEATS).astype(np.int64) - sec0
|
| 380 |
+
all_sub = subdiv_class(all_g)
|
| 381 |
+
plan_rho = np.zeros(MAX_SECTIONS, dtype=np.float32)
|
| 382 |
+
plan_r = np.zeros(MAX_SECTIONS, dtype=np.int64)
|
| 383 |
+
for j in range(MAX_SECTIONS):
|
| 384 |
+
m = all_sec == j
|
| 385 |
+
if m.any():
|
| 386 |
+
plan_rho[j] = m.sum() / SECTION_BEATS
|
| 387 |
+
plan_r[j] = all_sub[m].max()
|
| 388 |
+
plan_gap = section_gap_dists(all_g, chart["type"] <= 3, all_sec)
|
| 389 |
+
bar0 = int(measure_at(sec, np.array([b0]))[0])
|
| 390 |
+
# the window's measures described by all of the chart's notes, so the measures cut by the window edges get the same
|
| 391 |
+
# plan rows as the song-level plan the planner predicts for generation
|
| 392 |
+
bplan = bar_plan(all_g, chart["type"], bar0, sec, chart["length_beats"])
|
| 393 |
+
frame_bar = measure_at(sec, beats) - bar0
|
| 394 |
+
fst, fen = measure_span(sec, frame_bar + bar0)
|
| 395 |
+
phase = np.clip((beats - fst) / np.maximum(fen - fst, 1e-6), 0.0, 1.0 - 1e-6)
|
| 396 |
+
frame_bar[(frame_bar < 0) | (frame_bar >= MAX_BARS)] = -1
|
| 397 |
+
rhint = rep_hint(mel, frame_bar, phase)
|
| 398 |
+
|
| 399 |
+
# beat / downbeat / kiai targets from the chart's timing (mapper-set, ms-accurate)
|
| 400 |
+
beat_tgt = np.zeros(W, np.float32)
|
| 401 |
+
down_tgt = np.zeros(W, np.float32)
|
| 402 |
+
lo_t = sec[0, 0]
|
| 403 |
+
hi_t = times[-1] + 2000.0
|
| 404 |
+
for b in range(int(math.ceil(beats[0])), int(math.floor(beats[-1])) + 1):
|
| 405 |
+
si = int(np.clip(np.searchsorted(sec[:, 3], b, side="right") - 1, 0, len(sec) - 1))
|
| 406 |
+
tb = sec[si, 0] + (b - sec[si, 3]) * sec[si, 1]
|
| 407 |
+
if tb < max(lo_t, start_ms) or tb > min(hi_t, start_ms + (W - 1) * 10.0):
|
| 408 |
+
continue
|
| 409 |
+
f = (tb - start_ms) / 10.0
|
| 410 |
+
f0 = int(math.floor(f))
|
| 411 |
+
w1 = f - f0
|
| 412 |
+
is_down = abs(((b - sec[si, 3]) % sec[si, 2])) < 1e-6
|
| 413 |
+
for fi, wv in ((f0, 1 - w1), (f0 + 1, w1)):
|
| 414 |
+
if 0 <= fi < W:
|
| 415 |
+
beat_tgt[fi] = max(beat_tgt[fi], wv)
|
| 416 |
+
if is_down:
|
| 417 |
+
down_tgt[fi] = max(down_tgt[fi], wv)
|
| 418 |
+
beat_mask = ((t >= lo_t) & (t <= hi_t)).astype(np.float32)
|
| 419 |
+
kiai_tgt = np.zeros(W, np.float32)
|
| 420 |
+
for a, b2 in chart.get("kiai", np.zeros((0, 2))):
|
| 421 |
+
kiai_tgt[(t >= a) & (t < b2)] = 1.0
|
| 422 |
+
kiai_mask = ((t >= times[0] - 2000.0) & (t <= times[-1] + 2000.0)).astype(np.float32)
|
| 423 |
+
|
| 424 |
+
# grid lookup tables for generation: grid index -> time, bar position, section
|
| 425 |
+
G = int(math.ceil(beats[-1] * GRID)) - start_grid + 2
|
| 426 |
+
gb = (start_grid + np.arange(G)) / GRID
|
| 427 |
+
si = np.clip(np.searchsorted(sec[:, 3], gb, side="right") - 1, 0, len(sec) - 1)
|
| 428 |
+
s = sec[si]
|
| 429 |
+
gt = s[:, 0] + (gb - s[:, 3]) * s[:, 1]
|
| 430 |
+
grid_bar = np.clip(np.floor(_measure_pos(sec, gt) * 16), 0, 15).astype(np.int64)
|
| 431 |
+
grid_section = np.clip(np.floor(gb / SECTION_BEATS).astype(np.int64) - sec0, 0, MAX_SECTIONS - 1)
|
| 432 |
+
|
| 433 |
+
ev_sv = sv_class(chart["sv"][sel][:n]) if "sv" in chart else np.full(n, SV_ONE, np.int64)
|
| 434 |
+
|
| 435 |
+
return Example(
|
| 436 |
+
ev_sv=ev_sv, beat_tgt=beat_tgt, down_tgt=down_tgt, beat_mask=beat_mask, kiai_tgt=kiai_tgt, kiai_mask=kiai_mask,
|
| 437 |
+
grid_time=(gt - start_ms).astype(np.float32), grid_bar=grid_bar, grid_section=grid_section,
|
| 438 |
+
mel=mel, beat_feat=beat_feat, frame_section=frame_section, tier=chart["tier"],
|
| 439 |
+
gap=np.concatenate([gaps, [0]]).astype(np.int64), ev_gap=gaps.astype(np.int64),
|
| 440 |
+
tgt_ahead=np.concatenate([ahead, [AHEAD_END]]).astype(np.int64),
|
| 441 |
+
tgt_phase=np.concatenate([np.mod(g, GRID), [-100]]).astype(np.int64),
|
| 442 |
+
ev_ahead=ahead.astype(np.int64),
|
| 443 |
+
ev_type=ev_type, ev_len=ev_len, ev_delta=ev_delta, ev_frame=ev_frame,
|
| 444 |
+
ev_phase=np.mod(g, GRID), ev_bar=ev_bar, ev_section=ev_section,
|
| 445 |
+
plan_rho=plan_rho, plan_r=plan_r, plan_gap=plan_gap, bar_plan=bplan, frame_bar=frame_bar, rep_hint=rhint, ref_time=(ev_time - start_ms).astype(np.float32),
|
| 446 |
+
start_grid=start_grid, start_ms=start_ms,
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
class WindowSampler(torch.utils.data.IterableDataset):
|
| 451 |
+
"""Infinite random windows; charts drawn uniformly, start frames uniform over the song."""
|
| 452 |
+
|
| 453 |
+
def __init__(self, songs: list[dict], seed: int = 0, stretch_p: float = 0.0, stretch_range: float = 0.15):
|
| 454 |
+
self.songs = songs
|
| 455 |
+
self.index = [(i, j) for i, s in enumerate(songs) for j in range(len(s["charts"]))]
|
| 456 |
+
self.seed = seed
|
| 457 |
+
self.stretch_p, self.stretch_range = stretch_p, stretch_range
|
| 458 |
+
|
| 459 |
+
def __iter__(self):
|
| 460 |
+
info = torch.utils.data.get_worker_info()
|
| 461 |
+
rng = random.Random(self.seed + (info.id if info else 0) * 9973 + random.randrange(1 << 30))
|
| 462 |
+
while True:
|
| 463 |
+
i, j = rng.choice(self.index)
|
| 464 |
+
song = self.songs[i]
|
| 465 |
+
frames = len(song["mel"])
|
| 466 |
+
start = rng.randrange(0, max(1, frames - WINDOW // 2))
|
| 467 |
+
if self.stretch_p and rng.random() < self.stretch_p:
|
| 468 |
+
r = 1.0 + rng.uniform(-self.stretch_range, self.stretch_range)
|
| 469 |
+
yield make_example(*stretch(song, song["charts"][j], start, r))
|
| 470 |
+
else:
|
| 471 |
+
yield make_example(song, song["charts"][j], start)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def fixed_windows(songs: list[dict], n: int, seed: int = 1) -> list[Example]:
|
| 475 |
+
"""Deterministic evaluation windows that contain at least a few notes."""
|
| 476 |
+
rng = random.Random(seed)
|
| 477 |
+
index = [(i, j) for i, s in enumerate(songs) for j in range(len(s["charts"]))]
|
| 478 |
+
out = []
|
| 479 |
+
while len(out) < n and index:
|
| 480 |
+
i, j = rng.choice(index)
|
| 481 |
+
song, chart = songs[i], songs[i]["charts"][j]
|
| 482 |
+
first, last = chart["time"][0], chart["time"][-1]
|
| 483 |
+
lo = int(first // 10)
|
| 484 |
+
hi = max(lo + 1, int(last // 10) - WINDOW)
|
| 485 |
+
ex = make_example(song, chart, rng.randrange(lo, hi))
|
| 486 |
+
if len(ex.ev_type) >= 8:
|
| 487 |
+
out.append(ex)
|
| 488 |
+
return out
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def collate(batch: list[Example]) -> dict[str, torch.Tensor]:
|
| 492 |
+
B = len(batch)
|
| 493 |
+
N = max(1, max(len(e.ev_type) for e in batch))
|
| 494 |
+
def pad(key, length, dtype, fill=0):
|
| 495 |
+
out = torch.full((B, length), fill, dtype=dtype)
|
| 496 |
+
for b, e in enumerate(batch):
|
| 497 |
+
v = getattr(e, key)
|
| 498 |
+
out[b, :len(v)] = torch.as_tensor(v, dtype=dtype)
|
| 499 |
+
return out
|
| 500 |
+
return {
|
| 501 |
+
"mel": torch.from_numpy(np.stack([e.mel for e in batch])),
|
| 502 |
+
"beat_feat": torch.from_numpy(np.stack([e.beat_feat for e in batch])),
|
| 503 |
+
"frame_section": torch.from_numpy(np.stack([e.frame_section for e in batch])),
|
| 504 |
+
"tier": torch.tensor([e.tier for e in batch]),
|
| 505 |
+
"tgt_ahead": pad("tgt_ahead", N + 1, torch.long, -100),
|
| 506 |
+
"tgt_phase": pad("tgt_phase", N + 1, torch.long, -100),
|
| 507 |
+
"ev_ahead": pad("ev_ahead", N, torch.long),
|
| 508 |
+
"ev_type": pad("ev_type", N, torch.long, -100),
|
| 509 |
+
"ev_len": pad("ev_len", N, torch.long, -100),
|
| 510 |
+
"ev_delta": pad("ev_delta", N, torch.float32),
|
| 511 |
+
"ev_frame": pad("ev_frame", N, torch.long),
|
| 512 |
+
"ev_phase": pad("ev_phase", N, torch.long),
|
| 513 |
+
"ev_bar": pad("ev_bar", N, torch.long),
|
| 514 |
+
"ev_section": pad("ev_section", N, torch.long),
|
| 515 |
+
"ev_sv": pad("ev_sv", N, torch.long, -100),
|
| 516 |
+
"beat_tgt": torch.from_numpy(np.stack([e.beat_tgt for e in batch])),
|
| 517 |
+
"down_tgt": torch.from_numpy(np.stack([e.down_tgt for e in batch])),
|
| 518 |
+
"beat_mask": torch.from_numpy(np.stack([e.beat_mask for e in batch])),
|
| 519 |
+
"kiai_tgt": torch.from_numpy(np.stack([e.kiai_tgt for e in batch])),
|
| 520 |
+
"kiai_mask": torch.from_numpy(np.stack([e.kiai_mask for e in batch])),
|
| 521 |
+
"ev_mask": torch.stack([torch.arange(N) < len(e.ev_type) for e in batch]),
|
| 522 |
+
"plan_rho": torch.from_numpy(np.stack([e.plan_rho for e in batch])),
|
| 523 |
+
"plan_r": torch.from_numpy(np.stack([e.plan_r for e in batch])),
|
| 524 |
+
"plan_gap": torch.from_numpy(np.stack([e.plan_gap for e in batch])),
|
| 525 |
+
"bar_plan": torch.from_numpy(np.stack([e.bar_plan for e in batch])),
|
| 526 |
+
"frame_bar": torch.from_numpy(np.stack([e.frame_bar for e in batch])),
|
| 527 |
+
"rep_hint": torch.from_numpy(np.stack([e.rep_hint for e in batch])),
|
| 528 |
+
}
|
chartgen/disteval.py
ADDED
|
@@ -0,0 +1,1587 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Evaluation of whole-mapset generation by distribution matching.
|
| 2 |
+
|
| 3 |
+
Spec: reports/v10 評估設計:整組譜面的分布匹配.md. Each generated mapset (every difficulty of one song, written in one
|
| 4 |
+
run of the system) is treated as one more independent team of mappers for that song. Nine families of checks test,
|
| 5 |
+
each at the level where the property is decided, whether the system's mapsets and the human mapsets of the same
|
| 6 |
+
songs can be exchanged:
|
| 7 |
+
|
| 8 |
+
F1 chart settings, per tier: distribution shape (energy distance on normal scores, Wasserstein-1 per setting)
|
| 9 |
+
F2 song x tier: where the human chart falls among the system's K draws (randomized PIT)
|
| 10 |
+
F3 song x tier: how much song information the draws carry (fair CRPS skill; 0 = right amounts on a random song,
|
| 11 |
+
1 = another human team)
|
| 12 |
+
F4 whole mapset: spread of the mapset across songs, sharing between tiers, distribution of signed tier-to-tier
|
| 13 |
+
steps, density inversions between adjacent tiers
|
| 14 |
+
F5 mapset x measure: rest / roll / big-note layout agreement of adjacent tiers and nesting of rests
|
| 15 |
+
F6 measures of a chart: are rests in the quiet parts of the song (AUC; needs per-measure loudness)
|
| 16 |
+
F7 structure of a chart: rest runs, their phase, roll length, section density contrast
|
| 17 |
+
F8 song x tier: layout agreement between two draws, capped by the agreement of two independent human mapsets
|
| 18 |
+
F9 novelty: share of a chart's 4-measure patterns found in one single training chart
|
| 19 |
+
|
| 20 |
+
Data format
|
| 21 |
+
-----------
|
| 22 |
+
chart dict with 'sections' [n, >=4] (ms, ms per beat, meter, start beat, ...), 'time' (ms), 'type' (0-3 hit
|
| 23 |
+
notes, 4+ roll / balloon) and 'length_beats'. Optional: 'beat' (computed from time and sections when
|
| 24 |
+
missing), 'offset_ms' (added to the times to put the chart on the song's common time axis; 0 by default)
|
| 25 |
+
and metadata such as 'beatmap_id', 'beatmapset_id', 'mapper', 'year'.
|
| 26 |
+
mapset dict {tier: chart}, tier 0..4.
|
| 27 |
+
collection {song_key: {'human': [mapset, ...], 'draws': [mapset, ...]}}. human[0] is the reference mapset: its
|
| 28 |
+
tiers are the scored tiers of the song (other tiers of the draws are only counted), the timing of its
|
| 29 |
+
hardest chart is the song's measure grid, and its audio is the time axis of the loudness curve. More
|
| 30 |
+
human mapsets are optional (independent teams aligned with 'offset_ms'). 'draws' holds the K mapsets
|
| 31 |
+
the system wrote for the song.
|
| 32 |
+
|
| 33 |
+
Every chart, human or generated, goes through the same labelling path (label_measures): notes are snapped to the
|
| 34 |
+
1/48-beat grid, assigned to real measures with dataset.measure_at, and a measure is active when it has a hit note,
|
| 35 |
+
a roll / balloon starts in it, or a roll / balloon body covers more than 10% of it (dataset.plan_active). The nine
|
| 36 |
+
chart settings are latent_stats.chart_settings of the resulting per-measure plan.
|
| 37 |
+
|
| 38 |
+
Zero-heavy values
|
| 39 |
+
-----------------
|
| 40 |
+
Many settings are exactly 0 for a large share of charts (no rolls, no triplets, no 1/8 notes). When at least
|
| 41 |
+
ZERO_HEAVY of a tier's training values are 0, a value is compared in two parts: whether it is 0, and, when it is
|
| 42 |
+
not, its normal score among the non-zero training values. F1 and F7 add the difference of the zero shares to the
|
| 43 |
+
non-zero share times the Wasserstein-1 distance of the non-zero parts, and F1's energy distance gets a 0 / 1
|
| 44 |
+
coordinate for each such setting. F2 breaks ties (for example a human 0 among draws that are 0) uniformly at random
|
| 45 |
+
(randomized PIT). F3 skips settings with fewer than F3_MIN_NONZERO non-zero training values in the tier.
|
| 46 |
+
|
| 47 |
+
Statistics
|
| 48 |
+
----------
|
| 49 |
+
Every family has one pre-chosen primary statistic and possibly more statistics; for each, larger is worse. Two
|
| 50 |
+
kinds:
|
| 51 |
+
swap noise floor = median of the statistic when the human / system labels are swapped at random within each
|
| 52 |
+
song (all mapsets of a song exchangeable under the null); excess = statistic - floor; p = share of
|
| 53 |
+
swaps at least as large.
|
| 54 |
+
anchor the statistic is already measured against a human anchor (F3: shortfall of the CRPS skill from the
|
| 55 |
+
independent-human anchor; F8: draw agreement minus the human cross-mapset agreement); floor = 0;
|
| 56 |
+
p = share of bootstrap replicates at or below 0.
|
| 57 |
+
Confidence intervals come from a song bootstrap (a song is resampled with its human mapsets and its draws); for
|
| 58 |
+
swap statistics each replicate subtracts its own swap floor (median of `boot_swaps` swaps with the same weights).
|
| 59 |
+
Anchor replicates (reference_info, one weight per pair song shared by all tiers) are drawn alongside. A statistic
|
| 60 |
+
passes (draft) when the upper end of the 95% CI of the pooled excess is at most its margin and no single tier (or
|
| 61 |
+
tier pair) has the lower end of its CI above the margin. A family passes when all its statistics pass (REPORT_ONLY
|
| 62 |
+
ones excepted); it does not pass when any of them fails, and it is not available when none fails but its primary
|
| 63 |
+
statistic cannot be computed. The gate (summary 'all_pass') passes only when every family passes and no scored
|
| 64 |
+
(song, tier, draw) unit lacks a valid chart (such a draw would drop out of every statistic). A family fails
|
| 65 |
+
when its primary p, Holm-adjusted over the families, is below alpha.
|
| 66 |
+
|
| 67 |
+
Draft margins and thresholds live in DRAFT_MARGINS and the constants below; they are frozen only after the
|
| 68 |
+
validation experiments of the spec (B2) pass.
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
from __future__ import annotations
|
| 72 |
+
|
| 73 |
+
import hashlib
|
| 74 |
+
import pickle
|
| 75 |
+
import warnings
|
| 76 |
+
from collections import defaultdict
|
| 77 |
+
from pathlib import Path
|
| 78 |
+
|
| 79 |
+
import numpy as np
|
| 80 |
+
import torch
|
| 81 |
+
|
| 82 |
+
from .dataset import (BAR_F, DIVISORS, GAP0, GRID, SUSTAIN, _beats_at, beat_ms, measure_at, measure_span,
|
| 83 |
+
plan_active, roll_end_beats, subdiv_class)
|
| 84 |
+
from .gapstats import N_GAP_BINS, gap_bins
|
| 85 |
+
from .latent_align import best_offset, onset_f1
|
| 86 |
+
from .latent_stats import NAMES as SETTING_NAMES, chart_settings
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------------------------------------------------ constants
|
| 89 |
+
|
| 90 |
+
REPO = Path(__file__).resolve().parents[2]
|
| 91 |
+
DEFAULT_CHARTS = REPO / "data/hfruns/runs/charts/charts_all.pkl"
|
| 92 |
+
DEFAULT_CATALOG = REPO / "data/catalog/taiko_beatmaps.parquet"
|
| 93 |
+
|
| 94 |
+
N_TIERS = 5
|
| 95 |
+
MODERN_YEAR = 2022 # modern mapset: latest chart approved in this year or later
|
| 96 |
+
ERA_BANDS = ((0, 2016), (2017, 2021), (2022, 9999))
|
| 97 |
+
MIN_NOTES = 16 # human charts with fewer notes are dropped (as in the design scripts)
|
| 98 |
+
MAX_MEASURES = 2000 # charts spanning more measures are treated as broken
|
| 99 |
+
STRUCT_NAMES = ("rest_blocks_per100", "rest_block_len", "roll_len", "dens_cv")
|
| 100 |
+
VALUE_NAMES = tuple(SETTING_NAMES) + STRUCT_NAMES # 9 chart settings + 4 structure values
|
| 101 |
+
N_SET = len(SETTING_NAMES) # F1, F2, F3 use the 9 settings
|
| 102 |
+
F4_NAMES = tuple(SETTING_NAMES[:6]) # F4 uses the 6 main settings (rest, roll, triplet, eighth, big, density)
|
| 103 |
+
ZERO_HEAVY = 0.2 # two-part handling when at least this share of training values is exactly 0
|
| 104 |
+
F3_MIN_NONZERO = 0.2 # F3 skips (tier, setting) with fewer non-zero training values
|
| 105 |
+
F3_MIN_ROOM = 0.02 # ... or with less room between the climatology and the human anchor
|
| 106 |
+
MIN_ANCHOR_SONGS = 30 # fewer modern pair songs in a tier -> also use pairs within 2 years
|
| 107 |
+
COPY_CUT = 0.6 # F9: a chart counts as copied when one training chart holds this share of
|
| 108 |
+
# its distinct 4-measure patterns (draft; above every modern validation
|
| 109 |
+
# human chart: max 0.53 in tier 0, p99 at most 0.19 per tier)
|
| 110 |
+
GRAM_N = 4 # F9 pattern length in measures
|
| 111 |
+
GRAM_SLOTS = 12 # F9 positions per beat
|
| 112 |
+
MIN_GRAMS = 8 # F9 needs at least this many distinct patterns
|
| 113 |
+
RUN_BINS = 9 # F7 rest run lengths 1..8 and 9+
|
| 114 |
+
MIN_SONGS = 3 # a statistic needs at least this many songs on each side
|
| 115 |
+
MIN_LAYOUT = 20 # a layout F1 (F5, F8, F8 cap) needs this many labelled measures (a + b)
|
| 116 |
+
MIN_OVERLAP = 16 # a pair of charts (F8 cap and F8 draw pairs) needs this many common measures
|
| 117 |
+
ALIGN_MIN_F1 = 0.5 # two teams count as lined up when their hardest charts share at least this
|
| 118 |
+
ALIGN_MIN_OVERLAP_MS = 30000.0 # onset F1 over a common stretch of at least this length (same-timing real
|
| 119 |
+
# pairs never go below 0.74)
|
| 120 |
+
ALPHA = 0.05
|
| 121 |
+
|
| 122 |
+
TRIP_CLASSES = (DIVISORS.index(3), DIVISORS.index(6), DIVISORS.index(12))
|
| 123 |
+
FINE_CLASS = DIVISORS.index(8)
|
| 124 |
+
|
| 125 |
+
# Draft margins: largest excess over the floor that still counts as "the same as human" (equivalence bound).
|
| 126 |
+
# Units: F1 energy distance and W1 in normal-score units; F2 W1 between the PIT values and the uniform; F3 skill
|
| 127 |
+
# shortfall (1 - skill); F4 steps / F7 W1 in normal-score units, shares and F1 / AUC / TV in their own units.
|
| 128 |
+
DRAFT_MARGINS = {
|
| 129 |
+
"F1": {"energy": 0.02, "w1_mean": 0.05},
|
| 130 |
+
"F2": {"pit_w1": 0.03},
|
| 131 |
+
"F3": {"shortfall": 0.5},
|
| 132 |
+
"F4": {"steps": 0.05, "inversions": 0.02, "spread": 0.10, "sharing": 0.05},
|
| 133 |
+
"F5": {"rest_f1": 0.08, "roll_f1": 0.08, "big_f1": 0.08, "nesting": 0.08}, # null CI half-width ~0.05 at 395 songs
|
| 134 |
+
"F6": {"auc": 0.03},
|
| 135 |
+
"F7": {"run_length": 0.05, "blocks_per100": 0.10, "block_len": 0.10, "phase4": 0.05, "roll_len": 0.10,
|
| 136 |
+
"dens_cv": 0.10},
|
| 137 |
+
"F8": {"rest": 0.10, "rest_within_song": 0.05, "roll": 0.10, "big": 0.10}, # the rest cap alone: SD ~0.03 pooled
|
| 138 |
+
"F9": {"copy_share": 0.005, "best_single": 0.05, "seen_share": 0.05},
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
# family -> (title, primary statistic, [(statistic, kind)]); kind "swap" or "anchor" (see module docstring)
|
| 142 |
+
FAMILIES = {
|
| 143 |
+
"F1": ("chart settings per tier", "energy", [("energy", "swap"), ("w1_mean", "swap")]),
|
| 144 |
+
"F2": ("human chart among the draws (PIT)", "pit_w1", [("pit_w1", "swap")]),
|
| 145 |
+
"F3": ("song information (fair CRPS skill)", "shortfall", [("shortfall", "anchor")]),
|
| 146 |
+
"F4": ("whole mapset: spread, sharing, steps", "steps",
|
| 147 |
+
[("steps", "swap"), ("inversions", "swap"), ("spread", "swap"), ("sharing", "swap")]),
|
| 148 |
+
"F5": ("adjacent-tier layout", "rest_f1",
|
| 149 |
+
[("rest_f1", "swap"), ("roll_f1", "swap"), ("big_f1", "swap"), ("nesting", "swap")]),
|
| 150 |
+
"F6": ("rests in quiet measures", "auc", [("auc", "swap")]),
|
| 151 |
+
"F7": ("chart structure", "run_length",
|
| 152 |
+
[("run_length", "swap"), ("blocks_per100", "swap"), ("block_len", "swap"), ("phase4", "swap"),
|
| 153 |
+
("roll_len", "swap"), ("dens_cv", "swap")]),
|
| 154 |
+
"F8": ("draw-to-draw layout agreement", "rest",
|
| 155 |
+
[("rest", "anchor"), ("rest_within_song", "swap"), ("roll", "anchor"), ("big", "anchor")]),
|
| 156 |
+
"F9": ("novelty against training charts", "copy_share",
|
| 157 |
+
[("copy_share", "swap"), ("best_single", "swap"), ("seen_share", "swap")]),
|
| 158 |
+
}
|
| 159 |
+
# strata of each family's vector: chart tiers or adjacent tier pairs
|
| 160 |
+
PAIR_FAMILIES = {"F4", "F5"}
|
| 161 |
+
# statistics reported but left out of the family's pass flag: the F8 roll and big caps rest on few independent
|
| 162 |
+
# human pairs (bootstrap SD 0.05-0.12 per tier on the real modern pairs), too wide for an equivalence margin
|
| 163 |
+
REPORT_ONLY = {("F8", "roll"), ("F8", "big")}
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def era_band(year: int) -> int:
|
| 167 |
+
"""Index of the era band (<=2016, 2017-2021, 2022 and later) of an approval year."""
|
| 168 |
+
for k, (lo, hi) in enumerate(ERA_BANDS):
|
| 169 |
+
if lo <= year <= hi:
|
| 170 |
+
return k
|
| 171 |
+
return len(ERA_BANDS) - 1
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
# ------------------------------------------------------------------------------------------------ labelling
|
| 175 |
+
|
| 176 |
+
def _note_grid(sections, time, type_, length_beats, beat=None):
|
| 177 |
+
"""Notes sorted by time and snapped to the 1/48-beat grid of `sections`: (grid index, measure index, type,
|
| 178 |
+
length in beats). Beats come from `beat` when given, else from the times in this timing."""
|
| 179 |
+
sec = np.asarray(sections, np.float64)
|
| 180 |
+
t = np.asarray(time, np.float64)
|
| 181 |
+
order = np.argsort(t, kind="stable")
|
| 182 |
+
ty = np.asarray(type_)[order].astype(np.int64)
|
| 183 |
+
ln = np.asarray(length_beats, np.float64)[order]
|
| 184 |
+
b = _beats_at(sec, t[order]) if beat is None else np.asarray(beat, np.float64)[order]
|
| 185 |
+
g = np.round(b * GRID).astype(np.int64)
|
| 186 |
+
return g, measure_at(sec, g / GRID), ty, ln
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def label_measures(sections, time, type_, length_beats, beat=None, lo_m=None, hi_m=None) -> dict | None:
|
| 190 |
+
"""Per-measure labels of a chart's notes on the real measures of `sections` (the chart's own timing, or another
|
| 191 |
+
chart's timing when the times have been moved into it). Measures lo_m .. hi_m - 1; by default from the first
|
| 192 |
+
note's measure to the measure of the last note or roll end.
|
| 193 |
+
|
| 194 |
+
Returns dict: lo_m, n, H [n, BAR_F] (the per-measure plan of dataset.bar_plan, vectorised), active (plan_active),
|
| 195 |
+
play (hit notes), big (more than half big notes), trip (at least 30% of hits on the 1/3, 1/6, 1/12 grid), roll
|
| 196 |
+
(active only through a roll / balloon), st / en (measure start / end beats), and per note: measure (relative to
|
| 197 |
+
lo_m), slot (position in 1/12 beats from the measure start), type."""
|
| 198 |
+
if len(time) == 0:
|
| 199 |
+
return None
|
| 200 |
+
sec = np.asarray(sections, np.float64)
|
| 201 |
+
g, m, ty, ln = _note_grid(sec, time, type_, length_beats, beat)
|
| 202 |
+
bq = g / GRID
|
| 203 |
+
roll = ty >= 4
|
| 204 |
+
ends = roll_end_beats(sec, bq[roll], ln[roll]) if roll.any() else np.zeros(0)
|
| 205 |
+
if lo_m is None:
|
| 206 |
+
lo_m = int(m.min())
|
| 207 |
+
if hi_m is None:
|
| 208 |
+
last = int(m.max())
|
| 209 |
+
if len(ends):
|
| 210 |
+
last = max(last, int(measure_at(sec, ends).max()))
|
| 211 |
+
hi_m = last + 1
|
| 212 |
+
n = int(hi_m - lo_m)
|
| 213 |
+
if n <= 0 or n > MAX_MEASURES:
|
| 214 |
+
return None
|
| 215 |
+
st, en = measure_span(sec, np.arange(lo_m, hi_m))
|
| 216 |
+
mlen = np.maximum(en - st, 1e-6)
|
| 217 |
+
idx = m - lo_m
|
| 218 |
+
ok = (idx >= 0) & (idx < n)
|
| 219 |
+
hit = ty <= 3
|
| 220 |
+
hk = ok & hit
|
| 221 |
+
nh = np.bincount(idx[hk], minlength=n).astype(np.float64)
|
| 222 |
+
div = subdiv_class(g)
|
| 223 |
+
H = np.zeros((n, BAR_F), np.float32)
|
| 224 |
+
H[:, 0] = nh > 0
|
| 225 |
+
H[:, 1] = np.log1p(nh / mlen)
|
| 226 |
+
H[:, 2] = np.bincount(idx[hk], weights=(ty[hk] >= 2).astype(float), minlength=n) / np.maximum(nh, 1)
|
| 227 |
+
H[:, 3] = np.bincount(idx[ok & roll], minlength=n) > 0
|
| 228 |
+
H[:, 4] = np.bincount(idx[hk], weights=np.isin(div[hk], TRIP_CLASSES).astype(float), minlength=n) / np.maximum(nh, 1)
|
| 229 |
+
H[:, 5] = np.bincount(idx[hk], weights=(div[hk] >= FINE_CLASS).astype(float), minlength=n) / np.maximum(nh, 1)
|
| 230 |
+
# gap histogram: gaps between consecutive hit notes, counted in the measure of the later note, normalised
|
| 231 |
+
gh, mh = g[hit], idx[hit]
|
| 232 |
+
if len(gh) > 1:
|
| 233 |
+
gb = gap_bins(np.diff(gh) / GRID)
|
| 234 |
+
later = mh[1:]
|
| 235 |
+
okg = (later >= 0) & (later < n)
|
| 236 |
+
G = np.zeros((n, N_GAP_BINS))
|
| 237 |
+
np.add.at(G, (later[okg], gb[okg]), 1.0)
|
| 238 |
+
H[:, GAP0:GAP0 + N_GAP_BINS] = G / np.maximum(G.sum(1, keepdims=True), 1)
|
| 239 |
+
# roll / balloon bodies: share of each measure they cover (a start marks its measure even with zero length)
|
| 240 |
+
if roll.any():
|
| 241 |
+
rb = bq[roll]
|
| 242 |
+
ov = np.minimum(en[None, :], ends[:, None]) - np.maximum(st[None, :], rb[:, None])
|
| 243 |
+
cover = np.where(ov > 0, ov, 0.0) / mlen[None, :]
|
| 244 |
+
inm = (st[None, :] <= rb[:, None]) & (rb[:, None] < en[None, :])
|
| 245 |
+
cover = np.where(inm, np.maximum(cover, 1e-3), cover)
|
| 246 |
+
H[:, SUSTAIN] = np.minimum(cover.sum(0), 1.0)
|
| 247 |
+
play = H[:, 0] > 0.5
|
| 248 |
+
active = plan_active(H)
|
| 249 |
+
slot = np.round((bq - st[np.clip(idx, 0, n - 1)]) * GRAM_SLOTS).astype(np.int64)
|
| 250 |
+
return {"lo_m": int(lo_m), "n": n, "H": H, "active": active, "play": play,
|
| 251 |
+
"big": play & (H[:, 2] > 0.5), "trip": play & (H[:, 4] >= 0.3), "roll": active & ~play,
|
| 252 |
+
"st": st, "en": en, "note_m": idx, "note_slot": slot, "note_type": ty, "note_ok": ok}
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def _runs(mask: np.ndarray):
|
| 256 |
+
"""(start, length) arrays of the runs of True in a boolean array."""
|
| 257 |
+
if not mask.any():
|
| 258 |
+
return np.zeros(0, np.int64), np.zeros(0, np.int64)
|
| 259 |
+
d = np.diff(np.concatenate([[0], mask.astype(np.int8), [0]]))
|
| 260 |
+
s, e = np.where(d == 1)[0], np.where(d == -1)[0]
|
| 261 |
+
return s, e - s
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
_P_MEASURE = 0x100000001B3 # multipliers of the polynomial hashes (64-bit wrap-around)
|
| 265 |
+
_P_GRAM = 0x9E3779B97F4A7C15
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def _gram_hashes(lab: dict) -> np.ndarray:
|
| 269 |
+
"""Distinct 4-measure patterns of a labelled chart (rhythm and note type, positions in 1/12 beats, so tempo
|
| 270 |
+
does not matter), as sorted int64 hashes. Only windows of 4 consecutive measures that all have notes count."""
|
| 271 |
+
ok = lab["note_ok"]
|
| 272 |
+
m, slot, ty = lab["note_m"][ok], lab["note_slot"][ok], lab["note_type"][ok]
|
| 273 |
+
n = lab["n"]
|
| 274 |
+
if len(m) == 0 or n < GRAM_N:
|
| 275 |
+
return np.zeros(0, np.int64)
|
| 276 |
+
code = (np.clip(slot, 0, 4095).astype(np.uint64) * np.uint64(16) + ty.astype(np.uint64) + np.uint64(1))
|
| 277 |
+
order = np.lexsort((code, m))
|
| 278 |
+
ms, cs = m[order], code[order]
|
| 279 |
+
first = np.concatenate([[True], ms[1:] != ms[:-1]])
|
| 280 |
+
rank = np.arange(len(ms)) - np.maximum.accumulate(np.where(first, np.arange(len(ms)), 0))
|
| 281 |
+
powers = np.array([pow(_P_MEASURE, k, 1 << 64) for k in range(int(rank.max()) + 1)], np.uint64)
|
| 282 |
+
h = np.zeros(n, np.uint64)
|
| 283 |
+
np.add.at(h, ms, cs * powers[rank])
|
| 284 |
+
has = np.bincount(ms, minlength=n) > 0
|
| 285 |
+
k = n - GRAM_N + 1
|
| 286 |
+
gh = np.zeros(k, np.uint64)
|
| 287 |
+
okw = np.ones(k, bool)
|
| 288 |
+
for i in range(GRAM_N):
|
| 289 |
+
gh = gh * np.uint64(_P_GRAM) + h[i:i + k]
|
| 290 |
+
okw &= has[i:i + k]
|
| 291 |
+
return np.unique(gh[okw].view(np.int64))
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def chart_grams(chart: dict) -> np.ndarray:
|
| 295 |
+
"""4-measure pattern hashes of a chart on its own timing (F9)."""
|
| 296 |
+
lab = label_measures(chart["sections"], chart["time"], chart["type"], chart["length_beats"], chart.get("beat"))
|
| 297 |
+
return np.zeros(0, np.int64) if lab is None else _gram_hashes(lab)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def chart_values(chart: dict) -> dict | None:
|
| 301 |
+
"""Per-chart values on the chart's own timing, or None when the chart has too few active or played measures.
|
| 302 |
+
|
| 303 |
+
values [13]: the 9 chart settings (latent_stats.chart_settings) and 4 structure values: rest runs per 100
|
| 304 |
+
inside measures, mean rest-run length (measures), median roll / balloon length (beats), and the
|
| 305 |
+
contrast of mean density over 8-measure sections (SD / mean).
|
| 306 |
+
run_hist [9] counts of inside rest runs of length 1..8, 9+
|
| 307 |
+
phase_hist [4] counts of rest-run starts by (start - first active measure) mod 4
|
| 308 |
+
grams distinct 4-measure pattern hashes (F9)"""
|
| 309 |
+
lab = label_measures(chart["sections"], chart["time"], chart["type"], chart["length_beats"], chart.get("beat"))
|
| 310 |
+
if lab is None:
|
| 311 |
+
return None
|
| 312 |
+
s = chart_settings(lab["H"])
|
| 313 |
+
if s is None:
|
| 314 |
+
return None
|
| 315 |
+
act = lab["active"]
|
| 316 |
+
ia = np.where(act)[0]
|
| 317 |
+
inside = np.zeros(lab["n"], bool)
|
| 318 |
+
inside[ia[0]: ia[-1] + 1] = True
|
| 319 |
+
rest = ~act & inside
|
| 320 |
+
rs, rl = _runs(rest)
|
| 321 |
+
n_in = int(inside.sum())
|
| 322 |
+
dens = lab["H"][inside, 1].astype(np.float64)
|
| 323 |
+
k = len(dens) // 8
|
| 324 |
+
secd = dens[: k * 8].reshape(k, 8).mean(1) if k >= 2 else np.array([dens.mean()])
|
| 325 |
+
ty = np.asarray(chart["type"])
|
| 326 |
+
rolls = np.asarray(chart["length_beats"], np.float64)[ty >= 4]
|
| 327 |
+
struct = [len(rl) / max(n_in, 1) * 100.0, float(rl.mean()) if len(rl) else 0.0,
|
| 328 |
+
float(np.median(rolls)) if len(rolls) else 0.0, float(secd.std() / max(secd.mean(), 1e-6))]
|
| 329 |
+
return {"values": np.concatenate([s, struct]).astype(np.float64),
|
| 330 |
+
"run_hist": np.bincount(np.minimum(rl, RUN_BINS) - 1, minlength=RUN_BINS)[:RUN_BINS].astype(np.float64),
|
| 331 |
+
"phase_hist": np.bincount((rs - ia[0]) % 4, minlength=4).astype(np.float64),
|
| 332 |
+
"grams": _gram_hashes(lab), "n_inside": n_in}
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def _grid_labels(chart: dict, grid_sec: np.ndarray, grid_offset: float) -> dict | None:
|
| 336 |
+
"""Labels of a chart on the song's measure grid (another chart's timing): times moved by the offset difference,
|
| 337 |
+
beats recomputed in the grid timing. Keeps what the layout checks need; st_ms / en_ms are on the song axis."""
|
| 338 |
+
t = np.asarray(chart["time"], np.float64) + float(chart.get("offset_ms", 0.0)) - grid_offset
|
| 339 |
+
lab = label_measures(grid_sec, t, chart["type"], chart["length_beats"])
|
| 340 |
+
if lab is None or not lab["active"].any():
|
| 341 |
+
return None
|
| 342 |
+
return {"lo_m": lab["lo_m"], "n": lab["n"], "active": lab["active"], "roll": lab["roll"], "big": lab["big"],
|
| 343 |
+
"st_ms": beat_ms(grid_sec, lab["st"]) + grid_offset, "en_ms": beat_ms(grid_sec, lab["en"]) + grid_offset}
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def _pair_counts(a: dict, b: dict, window: str = "union") -> np.ndarray | None:
|
| 347 |
+
"""Layout agreement counts of two charts labelled on the same grid: [rest tp, rest a, rest b, roll tp, roll a,
|
| 348 |
+
roll b, big tp, big a, big b, measures]. F1 = 2 tp / (a + b); nesting of b's rests in a's = tp / b.
|
| 349 |
+
window 'union': measures from the first to the last active measure of either chart (same audio: a chart that
|
| 350 |
+
starts later really rests there). 'common': from the later first active measure to the earlier last one, as in
|
| 351 |
+
latent_align.compare (two mapsets may use different cuts of the song, e.g. a short version)."""
|
| 352 |
+
lo = min(a["lo_m"], b["lo_m"])
|
| 353 |
+
hi = max(a["lo_m"] + a["n"], b["lo_m"] + b["n"])
|
| 354 |
+
n = hi - lo
|
| 355 |
+
|
| 356 |
+
def put(lab, key):
|
| 357 |
+
out = np.zeros(n, bool)
|
| 358 |
+
s = lab["lo_m"] - lo
|
| 359 |
+
out[s: s + lab["n"]] = lab[key]
|
| 360 |
+
return out
|
| 361 |
+
|
| 362 |
+
aa, ab = put(a, "active"), put(b, "active")
|
| 363 |
+
ia, ib = np.where(aa)[0], np.where(ab)[0]
|
| 364 |
+
if len(ia) == 0 or len(ib) == 0:
|
| 365 |
+
return None
|
| 366 |
+
lo_i, hi_i = (min(ia[0], ib[0]), max(ia[-1], ib[-1])) if window == "union" else (max(ia[0], ib[0]), min(ia[-1], ib[-1]))
|
| 367 |
+
if hi_i < lo_i:
|
| 368 |
+
return None
|
| 369 |
+
inside = np.zeros(n, bool)
|
| 370 |
+
inside[lo_i: hi_i + 1] = True
|
| 371 |
+
out = []
|
| 372 |
+
for xa, xb in ((~aa & inside, ~ab & inside), (put(a, "roll") & inside, put(b, "roll") & inside),
|
| 373 |
+
(put(a, "big") & inside, put(b, "big") & inside)):
|
| 374 |
+
out += [(xa & xb).sum(), xa.sum(), xb.sum()]
|
| 375 |
+
out.append(inside.sum())
|
| 376 |
+
return np.array(out, np.float64)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
# ------------------------------------------------------------------------------------------------ data helpers
|
| 380 |
+
|
| 381 |
+
def _norm_mapset(ms: dict) -> dict:
|
| 382 |
+
return {int(t): c for t, c in ms.items() if c is not None}
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def load_catalog(path=None) -> dict:
|
| 386 |
+
"""beatmap_id -> {'mapper', 'year', 'star'} from the beatmap catalog."""
|
| 387 |
+
import pyarrow.parquet as pq
|
| 388 |
+
cols = ["beatmap_id", "mapper_user_id", "approved_date", "star_rating"]
|
| 389 |
+
out = {}
|
| 390 |
+
for r in pq.read_table(Path(path or DEFAULT_CATALOG), columns=cols).to_pylist():
|
| 391 |
+
out[r["beatmap_id"]] = {"mapper": r["mapper_user_id"], "year": int((r["approved_date"] or "0")[:4] or 0),
|
| 392 |
+
"star": r["star_rating"]}
|
| 393 |
+
return out
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def load_charts_all(path=None) -> list:
|
| 397 |
+
return pickle.load(open(Path(path or DEFAULT_CHARTS), "rb"))
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def _sha(x) -> int:
|
| 401 |
+
return int(hashlib.sha1(str(x).encode()).hexdigest(), 16)
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def _entry_mapset(entry: dict, catalog: dict | None) -> dict:
|
| 405 |
+
"""One chart per tier of a charts_all entry (charts with at least MIN_NOTES notes; when a tier has several
|
| 406 |
+
charts, a fixed arbitrary one: the smallest sha1 of the beatmap id), with mapper and year attached."""
|
| 407 |
+
by_tier = defaultdict(list)
|
| 408 |
+
for c in entry["charts"]:
|
| 409 |
+
if len(c["time"]) >= MIN_NOTES:
|
| 410 |
+
by_tier[int(c["tier"])].append(c)
|
| 411 |
+
out = {}
|
| 412 |
+
for t, cs in by_tier.items():
|
| 413 |
+
c = min(cs, key=lambda x: _sha(x["beatmap_id"]))
|
| 414 |
+
meta = (catalog or {}).get(c["beatmap_id"], {})
|
| 415 |
+
out[t] = {**c, "mapper": meta.get("mapper"), "beatmapset_id": entry["beatmapset_id"], "offset_ms": 0.0}
|
| 416 |
+
return out
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def _entry_year(entry: dict) -> int:
|
| 420 |
+
"""Approval year of the mapset's latest chart (charts_all 'year' is the approval year)."""
|
| 421 |
+
return max(int(c["year"]) for c in entry["charts"])
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def _mappers(ms: dict) -> set:
|
| 425 |
+
return {c.get("mapper") for c in ms.values() if c.get("mapper") is not None}
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def group_songs(charts_all: list) -> dict:
|
| 429 |
+
"""song_key -> list of charts_all entries (one entry per mapset)."""
|
| 430 |
+
by = defaultdict(list)
|
| 431 |
+
for s in charts_all:
|
| 432 |
+
by[s.get("song_key") or str(s["beatmapset_id"])].append(s)
|
| 433 |
+
return by
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
def _hardest_hits(ms: dict):
|
| 437 |
+
c = ms[max(ms)]
|
| 438 |
+
t = np.asarray(c["time"], np.float64)
|
| 439 |
+
return c, t[np.asarray(c["type"]) <= 3] + float(c.get("offset_ms", 0.0))
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
def _same_timing(a: dict, b: dict) -> bool:
|
| 443 |
+
sa, sb = np.asarray(a["sections"]), np.asarray(b["sections"])
|
| 444 |
+
return sa.shape == sb.shape and np.allclose(sa[:, :2], sb[:, :2])
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def _overlap_f1(ta: np.ndarray, tb: np.ndarray) -> float:
|
| 448 |
+
"""Onset F1 of two hit-note time lists inside their common time stretch; NaN when that stretch is shorter than
|
| 449 |
+
ALIGN_MIN_OVERLAP_MS."""
|
| 450 |
+
if len(ta) == 0 or len(tb) == 0:
|
| 451 |
+
return np.nan
|
| 452 |
+
lo, hi = max(ta.min(), tb.min()), min(ta.max(), tb.max())
|
| 453 |
+
if hi - lo < ALIGN_MIN_OVERLAP_MS:
|
| 454 |
+
return np.nan
|
| 455 |
+
return float(onset_f1(ta[(ta >= lo) & (ta <= hi)], tb[(tb >= lo) & (tb <= hi)]))
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
def align_mapsets(a: dict, b: dict, align: str = "auto"):
|
| 459 |
+
"""Offset (ms) that moves mapset b's times (after its own offset_ms) onto mapset a's axis, and whether the pair
|
| 460 |
+
is usable. 'none': same audio, offset 0, no check. 'auto': 0 when the hardest charts share their timing, else
|
| 461 |
+
latent_align.best_offset on the hardest charts' hit notes; the pair is kept when the hardest charts share an
|
| 462 |
+
onset F1 of at least ALIGN_MIN_F1 over a common stretch of at least 30 s (lined up) and the onset F1 of the
|
| 463 |
+
whole charts is below 0.9 (higher = a likely copy, not an independent team).
|
| 464 |
+
|
| 465 |
+
latent_align.grid_fit is not used as the alignment check: every time lies within its 20 ms tolerance of the
|
| 466 |
+
1/48-beat grid at any tempo above 31 BPM, so it accepted every offset (checked on all modern pairs with offsets
|
| 467 |
+
moved by 37-251 ms: grid fit 1.0 everywhere)."""
|
| 468 |
+
ca, ta = _hardest_hits(a)
|
| 469 |
+
cb, tb = _hardest_hits(b)
|
| 470 |
+
if align == "none" or _same_timing(ca, cb):
|
| 471 |
+
d = float(ca.get("offset_ms", 0.0)) - float(cb.get("offset_ms", 0.0)) # same audio: only the offsets differ
|
| 472 |
+
else:
|
| 473 |
+
d, _ = best_offset(ta, tb)
|
| 474 |
+
if align != "none" and not _overlap_f1(ta, tb + d) >= ALIGN_MIN_F1: # NaN (short overlap) is rejected too
|
| 475 |
+
return d, False
|
| 476 |
+
return d, onset_f1(ta, tb + d) < 0.9
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def build_human_collection(charts_all: list, songs=None, modern_only: bool = True, catalog: dict | None = None,
|
| 480 |
+
split: str = "val", extra_mapsets: bool = True) -> dict:
|
| 481 |
+
"""Collection with the human mapsets of the given songs (song keys; default: every song of `split`) and empty
|
| 482 |
+
draws. Modern only: mapsets whose latest chart was approved in 2022 or later. human[0] = the mapset with the
|
| 483 |
+
most tiers (then the latest, then the smallest beatmapset id); other mapsets of the song that share no mapper
|
| 484 |
+
with the ones already chosen and line up in time are added as independent human teams (offset_ms set).
|
| 485 |
+
The test split is refused."""
|
| 486 |
+
from .train import song_split
|
| 487 |
+
if split == "test":
|
| 488 |
+
raise ValueError("the test split is never used here")
|
| 489 |
+
by = group_songs(charts_all)
|
| 490 |
+
keys = sorted(k for k in by if song_split(k) == split) if songs is None else list(songs)
|
| 491 |
+
out = {}
|
| 492 |
+
for key in keys:
|
| 493 |
+
if song_split(key) == "test":
|
| 494 |
+
raise ValueError(f"song {key!r} is in the test split")
|
| 495 |
+
cands = []
|
| 496 |
+
for e in by.get(key, []):
|
| 497 |
+
if modern_only and _entry_year(e) < MODERN_YEAR:
|
| 498 |
+
continue
|
| 499 |
+
ms = _entry_mapset(e, catalog)
|
| 500 |
+
if ms:
|
| 501 |
+
cands.append((e, ms))
|
| 502 |
+
if not cands:
|
| 503 |
+
continue
|
| 504 |
+
cands.sort(key=lambda x: (-len(x[1]), -_entry_year(x[0]), x[0]["beatmapset_id"]))
|
| 505 |
+
primary = cands[0][1]
|
| 506 |
+
human, used, meta = [primary], set(_mappers(primary)), [cands[0][0]]
|
| 507 |
+
if extra_mapsets:
|
| 508 |
+
for e, ms in cands[1:]:
|
| 509 |
+
if catalog is not None and (_mappers(ms) & used or not _mappers(ms)):
|
| 510 |
+
continue
|
| 511 |
+
d, ok = align_mapsets(primary, ms)
|
| 512 |
+
if not ok:
|
| 513 |
+
continue
|
| 514 |
+
human.append({t: {**c, "offset_ms": float(c.get("offset_ms", 0.0)) + d} for t, c in ms.items()})
|
| 515 |
+
used |= _mappers(ms)
|
| 516 |
+
meta.append(e)
|
| 517 |
+
out[key] = {"human": human, "draws": [],
|
| 518 |
+
"meta": {"beatmapset_ids": [e["beatmapset_id"] for e in meta],
|
| 519 |
+
"years": [_entry_year(e) for e in meta],
|
| 520 |
+
"era_band": era_band(_entry_year(meta[0]))}}
|
| 521 |
+
return out
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def loudness_from_rows(rows, charts_all: list, collection: dict, column: int = -2) -> dict:
|
| 525 |
+
"""Per-measure loudness of each song's reference audio from the planner rows (ps9 rows.pkl: per split, a list of
|
| 526 |
+
(features, plan, tier, (beatmapset_id, beatmap_id, b0, song_key)); the features end with the measure's loudness
|
| 527 |
+
z-score and rank within the song). Returns {song_key: {'t0', 't1', 'loud', 'beatmapset_id'}} on the song axis
|
| 528 |
+
(human[0]'s own audio clock plus its offset_ms, the axis _grid_labels puts the measures on), only for songs
|
| 529 |
+
whose reference mapset has rows."""
|
| 530 |
+
if isinstance(rows, (str, Path)):
|
| 531 |
+
rows = pickle.load(open(rows, "rb"))
|
| 532 |
+
want, offset = {}, {}
|
| 533 |
+
for key, e in collection.items():
|
| 534 |
+
c0 = next(iter(_norm_mapset(e["human"][0]).values()))
|
| 535 |
+
if c0.get("beatmapset_id") is not None:
|
| 536 |
+
want[c0["beatmapset_id"]] = key
|
| 537 |
+
offset[key] = float(c0.get("offset_ms", 0.0)) # one mapset, one audio: one offset for all tiers
|
| 538 |
+
sections = {c["beatmap_id"]: c["sections"] for s in charts_all if s["beatmapset_id"] in want for c in s["charts"]}
|
| 539 |
+
out = {}
|
| 540 |
+
for split in rows:
|
| 541 |
+
for feat, _, _, meta in rows[split]:
|
| 542 |
+
key = want.get(meta[0])
|
| 543 |
+
sec = sections.get(meta[1])
|
| 544 |
+
if key is None or key in out or sec is None:
|
| 545 |
+
continue
|
| 546 |
+
n = len(feat)
|
| 547 |
+
st, en = measure_span(sec, np.arange(n) + int(meta[2]))
|
| 548 |
+
out[key] = {"t0": beat_ms(sec, st) + offset[key], "t1": beat_ms(sec, en) + offset[key],
|
| 549 |
+
"loud": np.asarray(feat[:, column], np.float64), "beatmapset_id": meta[0]}
|
| 550 |
+
return out
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
# ------------------------------------------------------------------------------------------------ normal scores
|
| 554 |
+
|
| 555 |
+
def _ndtri(q: np.ndarray) -> np.ndarray:
|
| 556 |
+
return torch.special.ndtri(torch.as_tensor(np.asarray(q, np.float64))).numpy()
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
def normal_scores(v: np.ndarray, ref_sorted: np.ndarray) -> np.ndarray:
|
| 560 |
+
"""Mid-rank of v in the sorted reference, mapped to a standard normal value (ties share their mid-rank, so a
|
| 561 |
+
mass of zeros maps to one point). NaN stays NaN; an empty reference gives 0."""
|
| 562 |
+
v = np.asarray(v, np.float64)
|
| 563 |
+
out = np.full(v.shape, np.nan)
|
| 564 |
+
ok = np.isfinite(v)
|
| 565 |
+
n = len(ref_sorted)
|
| 566 |
+
if n == 0:
|
| 567 |
+
out[ok] = 0.0
|
| 568 |
+
return out
|
| 569 |
+
lo = np.searchsorted(ref_sorted, v[ok], "left")
|
| 570 |
+
hi = np.searchsorted(ref_sorted, v[ok], "right")
|
| 571 |
+
out[ok] = _ndtri(np.clip((lo + hi) / 2 / n, 0.5 / n, 1 - 0.5 / n))
|
| 572 |
+
return out
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
def _zscore(V: np.ndarray, tiers: np.ndarray, ref: dict):
|
| 576 |
+
"""(Z, Zpos, zero): plain normal scores within tier, positive-part normal scores (against the non-zero training
|
| 577 |
+
values; NaN for zeros) and the zero flags, for value columns VALUE_NAMES."""
|
| 578 |
+
Z = np.full(V.shape, np.nan)
|
| 579 |
+
Zp = np.full(V.shape, np.nan)
|
| 580 |
+
for t in range(N_TIERS):
|
| 581 |
+
r = tiers == t
|
| 582 |
+
if not r.any():
|
| 583 |
+
continue
|
| 584 |
+
for j, name in enumerate(VALUE_NAMES):
|
| 585 |
+
Z[r, j] = normal_scores(V[r, j], ref["z_ref"][t][name])
|
| 586 |
+
pos = r & (V[:, j] > 0)
|
| 587 |
+
Zp[pos, j] = normal_scores(V[pos, j], ref["z_ref_pos"][t][name])
|
| 588 |
+
return Z, Zp, V == 0
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
# ------------------------------------------------------------------------------------------------ reference info
|
| 592 |
+
|
| 593 |
+
def _crps_pool(t_z: np.ndarray):
|
| 594 |
+
"""Sorted pool (z) with prefix sums and its half mean absolute difference 0.5 E|X - X'| (climatology)."""
|
| 595 |
+
x = np.sort(t_z[np.isfinite(t_z)])
|
| 596 |
+
n = len(x)
|
| 597 |
+
if n == 0:
|
| 598 |
+
return None
|
| 599 |
+
w = 2 * np.arange(1, n + 1) - n - 1
|
| 600 |
+
return {"x": x, "cs": np.concatenate([[0.0], np.cumsum(x)]), "half": float((w * x).sum() / (n * n))}
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
def _crps_clim(y: np.ndarray, pool: dict) -> np.ndarray:
|
| 604 |
+
"""Climatology CRPS of observations y against the pool: E|X - y| - 0.5 E|X - X'| (exact)."""
|
| 605 |
+
x, cs = pool["x"], pool["cs"]
|
| 606 |
+
n = len(x)
|
| 607 |
+
out = np.full(y.shape, np.nan)
|
| 608 |
+
ok = np.isfinite(y)
|
| 609 |
+
k = np.searchsorted(x, y[ok], "right")
|
| 610 |
+
out[ok] = (y[ok] * k - cs[k] + (cs[n] - cs[k]) - y[ok] * (n - k)) / n - pool["half"]
|
| 611 |
+
return out
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
def build_gram_index(charts) -> dict:
|
| 615 |
+
"""F9 index of training charts: sorted (pattern hash, chart id) pairs."""
|
| 616 |
+
hs, ids, n = [], [], 0
|
| 617 |
+
for c in charts:
|
| 618 |
+
g = chart_grams(c)
|
| 619 |
+
if len(g):
|
| 620 |
+
hs.append(g)
|
| 621 |
+
ids.append(np.full(len(g), n, np.int32))
|
| 622 |
+
n += 1
|
| 623 |
+
if not hs:
|
| 624 |
+
return {"hashes": np.zeros(0, np.int64), "ids": np.zeros(0, np.int32), "n_charts": n}
|
| 625 |
+
h, i = np.concatenate(hs), np.concatenate(ids)
|
| 626 |
+
o = np.argsort(h, kind="stable")
|
| 627 |
+
return {"hashes": h[o], "ids": i[o], "n_charts": n}
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def gram_novelty(grams: np.ndarray, index: dict):
|
| 631 |
+
"""(share of the chart's distinct patterns found in any training chart, largest share found in one single
|
| 632 |
+
training chart); NaN when the chart has fewer than MIN_GRAMS patterns."""
|
| 633 |
+
if len(grams) < MIN_GRAMS or len(index["hashes"]) == 0:
|
| 634 |
+
return np.nan, np.nan
|
| 635 |
+
lo = np.searchsorted(index["hashes"], grams, "left")
|
| 636 |
+
hi = np.searchsorted(index["hashes"], grams, "right")
|
| 637 |
+
cnt = hi - lo
|
| 638 |
+
seen = float((cnt > 0).mean())
|
| 639 |
+
if cnt.sum() == 0:
|
| 640 |
+
return seen, 0.0
|
| 641 |
+
# gather the chart ids of every match: repeat each range start and add the offsets inside the range
|
| 642 |
+
starts = np.repeat(lo, cnt)
|
| 643 |
+
offs = np.arange(cnt.sum()) - np.repeat(np.cumsum(cnt) - cnt, cnt)
|
| 644 |
+
best = np.bincount(index["ids"][starts + offs]).max()
|
| 645 |
+
return seen, float(best / len(grams))
|
| 646 |
+
|
| 647 |
+
|
| 648 |
+
def build_reference_from_mapsets(train_songs: dict, pairs=None, f9_charts=None, loudness=None, n_boot: int = 500,
|
| 649 |
+
seed: int = 0, min_anchor_songs: int = MIN_ANCHOR_SONGS, align: str = "auto") -> dict:
|
| 650 |
+
"""Reference information for run_families.
|
| 651 |
+
|
| 652 |
+
train_songs {song_key: [mapset, ...]} training mapsets: normal-score maps per tier (all VALUE_NAMES), zero
|
| 653 |
+
shares, and the F3 climatology pool (anchor C) are the training charts of each tier.
|
| 654 |
+
pairs [{'song', 'a', 'b', 'tag'}] independent human mapsets of the same song (tag 'modern' or another
|
| 655 |
+
label): anchor F of F3 (0.5 * mean |z_a - z_b| per tier and setting, a song mean first) and the F8
|
| 656 |
+
cap (pooled rest / roll / big F1 of the time-aligned pair, per tier). A tier uses the 'modern'
|
| 657 |
+
pairs when they cover at least min_anchor_songs songs, else every pair.
|
| 658 |
+
f9_charts iterable of training charts for the F9 pattern index.
|
| 659 |
+
loudness {song_key: {'t0', 't1', 'loud'}} per-measure loudness on the reference audio (F6).
|
| 660 |
+
Bootstrap replicates over songs (n_boot) are kept for the anchors."""
|
| 661 |
+
rng = np.random.default_rng(seed)
|
| 662 |
+
vals = {t: [] for t in range(N_TIERS)}
|
| 663 |
+
for msets in train_songs.values():
|
| 664 |
+
for ms in msets:
|
| 665 |
+
for t, c in _norm_mapset(ms).items():
|
| 666 |
+
rec = chart_values(c)
|
| 667 |
+
if rec is not None:
|
| 668 |
+
vals[t].append(rec["values"])
|
| 669 |
+
z_ref, z_ref_pos, zero_share, n_train = {}, {}, {}, {}
|
| 670 |
+
for t in range(N_TIERS):
|
| 671 |
+
A = np.array(vals[t]) if vals[t] else np.zeros((0, len(VALUE_NAMES)))
|
| 672 |
+
n_train[t] = len(A)
|
| 673 |
+
z_ref[t] = {nm: np.sort(A[:, j]) for j, nm in enumerate(VALUE_NAMES)}
|
| 674 |
+
z_ref_pos[t] = {nm: np.sort(A[A[:, j] > 0, j]) for j, nm in enumerate(VALUE_NAMES)}
|
| 675 |
+
zero_share[t] = {nm: float((A[:, j] == 0).mean()) if len(A) else 0.0 for j, nm in enumerate(VALUE_NAMES)}
|
| 676 |
+
ref = {"value_names": VALUE_NAMES, "z_ref": z_ref, "z_ref_pos": z_ref_pos, "zero_share": zero_share,
|
| 677 |
+
"n_train": n_train}
|
| 678 |
+
|
| 679 |
+
# anchors F (F3) and the F8 cap from independent human pairs
|
| 680 |
+
per = defaultdict(lambda: defaultdict(lambda: {"dz": [], "cnt": [], "tag": set()})) # tier -> song -> data
|
| 681 |
+
n_pairs_used = 0
|
| 682 |
+
for p in pairs or []:
|
| 683 |
+
a, b = _norm_mapset(p["a"]), _norm_mapset(p["b"])
|
| 684 |
+
common = sorted(set(a) & set(b))
|
| 685 |
+
if not common:
|
| 686 |
+
continue
|
| 687 |
+
d, aligned = align_mapsets(a, b, align)
|
| 688 |
+
if not aligned:
|
| 689 |
+
continue
|
| 690 |
+
n_pairs_used += 1
|
| 691 |
+
for t in common:
|
| 692 |
+
ra, rb = chart_values(a[t]), chart_values(b[t])
|
| 693 |
+
if ra is None or rb is None:
|
| 694 |
+
continue
|
| 695 |
+
V = np.stack([ra["values"], rb["values"]])
|
| 696 |
+
Z, _, _ = _zscore(V, np.array([t, t]), ref)
|
| 697 |
+
grid = np.asarray(a[t]["sections"], np.float64)
|
| 698 |
+
off = float(a[t].get("offset_ms", 0.0))
|
| 699 |
+
ga = _grid_labels(a[t], grid, off)
|
| 700 |
+
gb = _grid_labels({**b[t], "offset_ms": float(b[t].get("offset_ms", 0.0)) + d}, grid, off)
|
| 701 |
+
cnt = _pair_counts(ga, gb, "common") if ga is not None and gb is not None else None
|
| 702 |
+
if cnt is not None and cnt[-1] < MIN_OVERLAP: # too short an overlap to say anything
|
| 703 |
+
cnt = None
|
| 704 |
+
dd = per[t][p["song"]]
|
| 705 |
+
dd["dz"].append(np.abs(Z[0, :N_SET] - Z[1, :N_SET]))
|
| 706 |
+
if cnt is not None:
|
| 707 |
+
dd["cnt"].append(cnt)
|
| 708 |
+
dd["tag"].add(p.get("tag", "modern"))
|
| 709 |
+
J = N_SET
|
| 710 |
+
F_point = np.full((N_TIERS, J), np.nan)
|
| 711 |
+
F_boot = np.full((n_boot, N_TIERS, J), np.nan)
|
| 712 |
+
cap_point = np.full((N_TIERS, 3), np.nan)
|
| 713 |
+
cap_boot = np.full((n_boot, N_TIERS, 3), np.nan)
|
| 714 |
+
anchor_meta = {}
|
| 715 |
+
uses = {}
|
| 716 |
+
for t in range(N_TIERS):
|
| 717 |
+
songs = per[t]
|
| 718 |
+
modern = [s for s, v in songs.items() if "modern" in v["tag"]]
|
| 719 |
+
uses[t] = modern if len(modern) >= min_anchor_songs else list(songs)
|
| 720 |
+
rule = "modern" if len(modern) >= min_anchor_songs else "all_pairs"
|
| 721 |
+
anchor_meta[t] = {"rule": rule, "n_songs_F": sum(bool(songs[s]["dz"]) for s in uses[t]),
|
| 722 |
+
"n_songs_cap": sum(bool(songs[s]["cnt"]) for s in uses[t]), "n_modern_songs": len(modern)}
|
| 723 |
+
# Bootstrap over pair songs: one weight per song per replicate, shared by every tier. A pair song feeds the
|
| 724 |
+
# anchors of all its tiers and F3 / F8 pool over tiers, so resampling each tier on its own would make the
|
| 725 |
+
# pooled intervals too narrow.
|
| 726 |
+
boot_songs = sorted({s for t in range(N_TIERS) for s in uses[t]})
|
| 727 |
+
sidx = {s: i for i, s in enumerate(boot_songs)}
|
| 728 |
+
W = (rng.multinomial(len(boot_songs), np.full(len(boot_songs), 1.0 / len(boot_songs)), size=n_boot).astype(float)
|
| 729 |
+
if boot_songs else np.zeros((n_boot, 0)))
|
| 730 |
+
|
| 731 |
+
def caps(X, w):
|
| 732 |
+
"""Pooled rest / roll / big F1 of pair-count rows X with row weights w."""
|
| 733 |
+
den = [(w * (X[:, 3 * k + 1] + X[:, 3 * k + 2])).sum() for k in range(3)]
|
| 734 |
+
return np.array([2 * (w * X[:, 3 * k]).sum() / den[k] if den[k] >= MIN_LAYOUT else np.nan for k in range(3)])
|
| 735 |
+
|
| 736 |
+
for t in range(N_TIERS):
|
| 737 |
+
songs = per[t]
|
| 738 |
+
sd = [s for s in uses[t] if songs[s]["dz"]]
|
| 739 |
+
sc = [s for s in uses[t] if songs[s]["cnt"]]
|
| 740 |
+
if sd:
|
| 741 |
+
D = np.array([np.mean(songs[s]["dz"], 0) for s in sd])
|
| 742 |
+
F_point[t] = 0.5 * D.mean(0)
|
| 743 |
+
Wd = W[:, [sidx[s] for s in sd]]
|
| 744 |
+
tot = Wd.sum(1)
|
| 745 |
+
ok = tot > 0
|
| 746 |
+
F_boot[ok, t] = 0.5 * (Wd[ok] @ D) / tot[ok, None]
|
| 747 |
+
if sc:
|
| 748 |
+
C = np.array([np.mean(songs[s]["cnt"], 0) for s in sc])
|
| 749 |
+
cap_point[t] = caps(C, np.ones(len(C)))
|
| 750 |
+
Wc = W[:, [sidx[s] for s in sc]]
|
| 751 |
+
for b in range(n_boot):
|
| 752 |
+
cap_boot[b, t] = caps(C, Wc[b])
|
| 753 |
+
ref["anchor_F"] = {"point": F_point, "boot": F_boot, "meta": anchor_meta, "n_pairs": n_pairs_used}
|
| 754 |
+
ref["f8_cap"] = {"point": cap_point, "boot": cap_boot, "kinds": ("rest", "roll", "big")}
|
| 755 |
+
ref["f9_index"] = build_gram_index(f9_charts) if f9_charts is not None else build_gram_index([])
|
| 756 |
+
ref["loudness"] = dict(loudness or {})
|
| 757 |
+
return ref
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
def build_reference_info(charts_all: list, catalog: dict | None = None, modern_only: bool = True, loudness=None,
|
| 761 |
+
n_boot: int = 500, seed: int = 0, min_anchor_songs: int = MIN_ANCHOR_SONGS,
|
| 762 |
+
f9_all_eras: bool = True) -> dict:
|
| 763 |
+
"""Reference information from charts_all: training mapsets of the train split (modern only by default) for the
|
| 764 |
+
normal scores and the F3 climatology; independent mapset pairs of non-test songs (no shared mapper, aligned in
|
| 765 |
+
time) for anchor F and the F8 cap, tagged 'modern' when both mapsets are modern and 'era2' when their years are
|
| 766 |
+
within 2 of each other; every training chart (all eras by default: the model trains on them) for F9."""
|
| 767 |
+
from .train import song_split
|
| 768 |
+
catalog = catalog if catalog is not None else load_catalog()
|
| 769 |
+
by = group_songs(charts_all)
|
| 770 |
+
train_songs, pairs, f9 = {}, [], []
|
| 771 |
+
for key, entries in by.items():
|
| 772 |
+
split = song_split(key)
|
| 773 |
+
if split == "test":
|
| 774 |
+
continue
|
| 775 |
+
mss = [(e, _entry_mapset(e, catalog)) for e in entries]
|
| 776 |
+
mss = [(e, ms) for e, ms in mss if ms]
|
| 777 |
+
if split == "train":
|
| 778 |
+
keep = [ms for e, ms in mss if not modern_only or _entry_year(e) >= MODERN_YEAR]
|
| 779 |
+
if keep:
|
| 780 |
+
train_songs[key] = keep
|
| 781 |
+
for e in entries:
|
| 782 |
+
if f9_all_eras or _entry_year(e) >= MODERN_YEAR:
|
| 783 |
+
f9 += [c for c in e["charts"] if len(c["time"]) >= MIN_NOTES]
|
| 784 |
+
for i in range(len(mss)):
|
| 785 |
+
for j in range(i + 1, len(mss)):
|
| 786 |
+
(ea, a), (eb, b) = mss[i], mss[j]
|
| 787 |
+
if _mappers(a) & _mappers(b) or not _mappers(a) or not _mappers(b):
|
| 788 |
+
continue
|
| 789 |
+
ya, yb = _entry_year(ea), _entry_year(eb)
|
| 790 |
+
if min(ya, yb) >= MODERN_YEAR:
|
| 791 |
+
tag = "modern"
|
| 792 |
+
elif abs(ya - yb) <= 2:
|
| 793 |
+
tag = "era2"
|
| 794 |
+
else:
|
| 795 |
+
continue
|
| 796 |
+
pairs.append({"song": key, "a": a, "b": b, "tag": tag})
|
| 797 |
+
ref = build_reference_from_mapsets(train_songs, pairs, f9, loudness, n_boot, seed, min_anchor_songs, "auto")
|
| 798 |
+
ref["meta"] = {"modern_only": modern_only, "n_train_songs": len(train_songs), "n_pairs": len(pairs),
|
| 799 |
+
"n_f9_charts": ref["f9_index"]["n_charts"]}
|
| 800 |
+
return ref
|
| 801 |
+
|
| 802 |
+
|
| 803 |
+
# ------------------------------------------------------------------------------------------------ unit statistics
|
| 804 |
+
|
| 805 |
+
def compute_unit_stats(collection: dict) -> dict:
|
| 806 |
+
"""Per-chart and per-set statistics of a collection that do not depend on the reference: chart values on the
|
| 807 |
+
chart's own timing, labels on the song's measure grid (human[0]'s hardest chart), layout counts of adjacent
|
| 808 |
+
tiers within each mapset (F5) and of every pair of mapsets per tier (F8)."""
|
| 809 |
+
U = {"songs": [], "sets": [], "charts": [], "f5": [], "f8": [], "extra_tiers": 0, "skipped_songs": []}
|
| 810 |
+
for key in sorted(collection):
|
| 811 |
+
e = collection[key]
|
| 812 |
+
humans = [_norm_mapset(m) for m in e.get("human") or []]
|
| 813 |
+
draws = [_norm_mapset(m) for m in e.get("draws") or []]
|
| 814 |
+
if not humans or not humans[0]:
|
| 815 |
+
U["skipped_songs"].append(key)
|
| 816 |
+
continue
|
| 817 |
+
tiers = sorted(humans[0])
|
| 818 |
+
grid_chart = humans[0][tiers[-1]]
|
| 819 |
+
grid_sec = np.asarray(grid_chart["sections"], np.float64)
|
| 820 |
+
grid_off = float(grid_chart.get("offset_ms", 0.0))
|
| 821 |
+
si = len(U["songs"])
|
| 822 |
+
U["songs"].append({"key": key, "tiers": tiers, "n_human": len(humans), "n_draws": len(draws)})
|
| 823 |
+
by_tier = defaultdict(list) # tier -> [(set row, grid labels)]
|
| 824 |
+
for j, ms in enumerate(humans + draws):
|
| 825 |
+
row = len(U["sets"])
|
| 826 |
+
U["sets"].append({"song": si, "pos": j, "human": j < len(humans)})
|
| 827 |
+
if j >= len(humans):
|
| 828 |
+
U["extra_tiers"] += len(set(ms) - set(tiers))
|
| 829 |
+
grid = {}
|
| 830 |
+
for t in tiers:
|
| 831 |
+
c = ms.get(t)
|
| 832 |
+
rec = chart_values(c) if c is not None else None
|
| 833 |
+
if rec is None:
|
| 834 |
+
continue
|
| 835 |
+
gl = _grid_labels(c, grid_sec, grid_off)
|
| 836 |
+
U["charts"].append({"song": si, "set": row, "tier": t, **rec, "grid": gl})
|
| 837 |
+
if gl is not None:
|
| 838 |
+
grid[t] = gl
|
| 839 |
+
by_tier[t].append((row, gl))
|
| 840 |
+
for t in tiers:
|
| 841 |
+
if t in grid and t + 1 in grid:
|
| 842 |
+
cnt = _pair_counts(grid[t], grid[t + 1])
|
| 843 |
+
if cnt is not None:
|
| 844 |
+
U["f5"].append((row, t, cnt))
|
| 845 |
+
for t, lst in by_tier.items():
|
| 846 |
+
for x in range(len(lst)):
|
| 847 |
+
for y in range(x + 1, len(lst)):
|
| 848 |
+
cnt = _pair_counts(lst[x][1], lst[y][1], "common") # the window of the F8 cap
|
| 849 |
+
if cnt is not None and cnt[-1] >= MIN_OVERLAP: # the overlap rule of the F8 cap
|
| 850 |
+
U["f8"].append((si, t, lst[x][0], lst[y][0], cnt))
|
| 851 |
+
return U
|
| 852 |
+
|
| 853 |
+
|
| 854 |
+
# ------------------------------------------------------------------------------------------------ small statistics
|
| 855 |
+
|
| 856 |
+
def _weights(key: np.ndarray, member: np.ndarray, base: np.ndarray) -> np.ndarray:
|
| 857 |
+
"""Weight base[i] / (number of members sharing key[i]) for members, 0 otherwise: each key counts once."""
|
| 858 |
+
if len(key) == 0:
|
| 859 |
+
return np.zeros(0)
|
| 860 |
+
cnt = np.bincount(key[member], minlength=int(key.max()) + 1)
|
| 861 |
+
return np.where(member, base / np.maximum(cnt[key], 1), 0.0)
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
def _n_songs(song: np.ndarray, w: np.ndarray) -> int:
|
| 865 |
+
return len(np.unique(song[w > 0]))
|
| 866 |
+
|
| 867 |
+
|
| 868 |
+
def _sorted_support(x: np.ndarray):
|
| 869 |
+
"""Order of the finite entries of x and the gaps between consecutive sorted values (fixed support for W1)."""
|
| 870 |
+
idx = np.where(np.isfinite(x))[0]
|
| 871 |
+
o = idx[np.argsort(x[idx], kind="stable")]
|
| 872 |
+
return o, np.diff(x[o])
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
def _w1_sorted(wa: np.ndarray, wb: np.ndarray, o: np.ndarray, dx: np.ndarray) -> float:
|
| 876 |
+
"""Wasserstein-1 between two weighted samples living on the same sorted support."""
|
| 877 |
+
a, b = wa[o], wb[o]
|
| 878 |
+
sa, sb = a.sum(), b.sum()
|
| 879 |
+
if sa <= 0 or sb <= 0:
|
| 880 |
+
return np.nan
|
| 881 |
+
return float((np.abs(np.cumsum(a) / sa - np.cumsum(b) / sb)[:-1] * dx).sum())
|
| 882 |
+
|
| 883 |
+
|
| 884 |
+
def _w1_two_part(wa: np.ndarray, wb: np.ndarray, sup: dict) -> float:
|
| 885 |
+
"""W1 of normal scores; for zero-heavy values: |difference of zero shares| + non-zero share x W1 of the
|
| 886 |
+
positive-part normal scores."""
|
| 887 |
+
if not sup["two_part"]:
|
| 888 |
+
return _w1_sorted(wa, wb, *sup["plain"])
|
| 889 |
+
sa, sb = wa.sum(), wb.sum()
|
| 890 |
+
if sa <= 0 or sb <= 0:
|
| 891 |
+
return np.nan
|
| 892 |
+
za, zb = (wa * sup["zero"]).sum() / sa, (wb * sup["zero"]).sum() / sb
|
| 893 |
+
pos = _w1_sorted(wa * ~sup["zero"], wb * ~sup["zero"], *sup["pos"])
|
| 894 |
+
return float(abs(za - zb) + (1 - (za + zb) / 2) * (0.0 if np.isnan(pos) else pos))
|
| 895 |
+
|
| 896 |
+
|
| 897 |
+
def _w1_uniform(u: np.ndarray, w: np.ndarray) -> float:
|
| 898 |
+
"""W1 between the weighted sample u in [0, 1] and the uniform distribution: integral of |F(x) - x|."""
|
| 899 |
+
if len(u) == 0 or w.sum() <= 0:
|
| 900 |
+
return np.nan
|
| 901 |
+
o = np.argsort(u)
|
| 902 |
+
e = np.concatenate([[0.0], u[o], [1.0]])
|
| 903 |
+
c = np.concatenate([[0.0], np.cumsum(w[o]) / w.sum()])
|
| 904 |
+
a, b = e[:-1], e[1:]
|
| 905 |
+
v = np.where(c <= a, ((b - c) ** 2 - (a - c) ** 2) / 2,
|
| 906 |
+
np.where(c >= b, ((c - a) ** 2 - (c - b) ** 2) / 2, ((c - a) ** 2 + (b - c) ** 2) / 2))
|
| 907 |
+
return float(v.sum())
|
| 908 |
+
|
| 909 |
+
|
| 910 |
+
def _wcorr_sym(x: np.ndarray, y: np.ndarray, w: np.ndarray) -> float:
|
| 911 |
+
"""Weighted correlation of the pairs (x, y) taken in both orders (symmetric in the two members)."""
|
| 912 |
+
xx, yy, ww = np.concatenate([x, y]), np.concatenate([y, x]), np.concatenate([w, w])
|
| 913 |
+
if ww.sum() <= 0:
|
| 914 |
+
return np.nan
|
| 915 |
+
mx = (ww * xx).sum() / ww.sum()
|
| 916 |
+
my = (ww * yy).sum() / ww.sum()
|
| 917 |
+
cov = (ww * (xx - mx) * (yy - my)).sum()
|
| 918 |
+
den = np.sqrt((ww * (xx - mx) ** 2).sum() * (ww * (yy - my) ** 2).sum())
|
| 919 |
+
return float(cov / den) if den > 1e-12 else np.nan
|
| 920 |
+
|
| 921 |
+
|
| 922 |
+
def _wsd(x: np.ndarray, w: np.ndarray) -> float:
|
| 923 |
+
if w.sum() <= 0:
|
| 924 |
+
return np.nan
|
| 925 |
+
m = (w * x).sum() / w.sum()
|
| 926 |
+
return float(np.sqrt((w * (x - m) ** 2).sum() / w.sum()))
|
| 927 |
+
|
| 928 |
+
|
| 929 |
+
def _auc(score: np.ndarray, pos: np.ndarray) -> float:
|
| 930 |
+
"""P(score of a positive > score of a negative), ties counted 1/2 (Mann-Whitney with mid-ranks)."""
|
| 931 |
+
n1, n0 = int(pos.sum()), int((~pos).sum())
|
| 932 |
+
if n1 == 0 or n0 == 0:
|
| 933 |
+
return np.nan
|
| 934 |
+
_, inv, cnt = np.unique(score, return_inverse=True, return_counts=True)
|
| 935 |
+
start = np.concatenate([[0], np.cumsum(cnt)[:-1]])
|
| 936 |
+
mid = start + (cnt + 1) / 2.0
|
| 937 |
+
r = mid[inv]
|
| 938 |
+
return float((r[pos].sum() - n1 * (n1 + 1) / 2) / (n1 * n0))
|
| 939 |
+
|
| 940 |
+
|
| 941 |
+
def _vec() -> np.ndarray:
|
| 942 |
+
return np.full(1 + N_TIERS, np.nan)
|
| 943 |
+
|
| 944 |
+
|
| 945 |
+
# ------------------------------------------------------------------------------------------------ preparation
|
| 946 |
+
|
| 947 |
+
def _prepare(U: dict, ref: dict) -> dict:
|
| 948 |
+
"""Arrays for the fast evaluation of every family under any role assignment and song weights."""
|
| 949 |
+
ctx = {"n_songs": len(U["songs"]), "song_keys": [s["key"] for s in U["songs"]]}
|
| 950 |
+
S = len(U["sets"])
|
| 951 |
+
ctx["set_song"] = np.array([s["song"] for s in U["sets"]], np.int64)
|
| 952 |
+
ctx["set_human"] = np.array([s["human"] for s in U["sets"]], bool)
|
| 953 |
+
ctx["n_human"] = np.array([s["n_human"] for s in U["songs"]], np.int64)
|
| 954 |
+
ch = U["charts"]
|
| 955 |
+
C = len(ch)
|
| 956 |
+
ctx["ch_song"] = np.array([c["song"] for c in ch], np.int64)
|
| 957 |
+
ctx["ch_set"] = np.array([c["set"] for c in ch], np.int64)
|
| 958 |
+
ctx["ch_tier"] = np.array([c["tier"] for c in ch], np.int64)
|
| 959 |
+
V = np.array([c["values"] for c in ch]) if C else np.zeros((0, len(VALUE_NAMES)))
|
| 960 |
+
Z, Zp, Zero = _zscore(V, ctx["ch_tier"], ref)
|
| 961 |
+
ctx.update(V=V, Z=Z)
|
| 962 |
+
ctx["key_st"] = ctx["ch_song"] * N_TIERS + ctx["ch_tier"]
|
| 963 |
+
ctx["tier_rows"] = [np.where(ctx["ch_tier"] == t)[0] for t in range(N_TIERS)]
|
| 964 |
+
heavy = {t: {j: ref["zero_share"][t][nm] >= ZERO_HEAVY for j, nm in enumerate(VALUE_NAMES)}
|
| 965 |
+
for t in range(N_TIERS)}
|
| 966 |
+
ctx["heavy"] = heavy
|
| 967 |
+
|
| 968 |
+
# F1 / F7: per tier, sorted supports for (two-part) W1 and the distance matrix for the energy distance
|
| 969 |
+
ctx["sup"], ctx["D"] = {}, {}
|
| 970 |
+
for t in range(N_TIERS):
|
| 971 |
+
rows = ctx["tier_rows"][t]
|
| 972 |
+
ctx["sup"][t] = {}
|
| 973 |
+
for j in range(len(VALUE_NAMES)):
|
| 974 |
+
sup = {"two_part": heavy[t][j], "plain": _sorted_support(Z[rows, j]), "zero": Zero[rows, j]}
|
| 975 |
+
if heavy[t][j]:
|
| 976 |
+
sup["pos"] = _sorted_support(np.where(Zero[rows, j], np.nan, Zp[rows, j]))
|
| 977 |
+
ctx["sup"][t][j] = sup
|
| 978 |
+
if len(rows):
|
| 979 |
+
flags = [Zero[rows, j][:, None].astype(float) for j in range(N_SET) if heavy[t][j]]
|
| 980 |
+
E = np.concatenate([Z[rows, :N_SET]] + flags, 1)
|
| 981 |
+
E = np.nan_to_num(E)
|
| 982 |
+
sq = (E ** 2).sum(1)
|
| 983 |
+
ctx["D"][t] = np.sqrt(np.maximum(sq[:, None] + sq[None, :] - 2 * E @ E.T, 0.0))
|
| 984 |
+
|
| 985 |
+
# F2 / F3: units = (song, tier) with the members (all mapsets of the song) padded to M columns
|
| 986 |
+
units = defaultdict(list)
|
| 987 |
+
for i in range(C):
|
| 988 |
+
units[(ctx["ch_song"][i], ctx["ch_tier"][i])].append(i)
|
| 989 |
+
ukeys = sorted(units)
|
| 990 |
+
M = max((len(v) for v in units.values()), default=1)
|
| 991 |
+
UR = np.full((len(ukeys), M), -1, np.int64)
|
| 992 |
+
for u, k in enumerate(ukeys):
|
| 993 |
+
UR[u, : len(units[k])] = units[k]
|
| 994 |
+
ctx["UR"] = UR
|
| 995 |
+
ctx["u_song"] = np.array([k[0] for k in ukeys], np.int64)
|
| 996 |
+
ctx["u_tier"] = np.array([k[1] for k in ukeys], np.int64)
|
| 997 |
+
present = UR >= 0
|
| 998 |
+
UV = np.where(present[..., None], V[np.maximum(UR, 0)][..., :N_SET] if C else 0.0, np.nan)
|
| 999 |
+
UZ = np.where(present[..., None], Z[np.maximum(UR, 0)][..., :N_SET] if C else 0.0, np.nan)
|
| 1000 |
+
ctx["LESS"] = UV[:, None, :, :] < UV[:, :, None, :] # [u, h, m, j]: member m below member h
|
| 1001 |
+
ctx["EQ"] = UV[:, None, :, :] == UV[:, :, None, :]
|
| 1002 |
+
ctx["PD"] = np.nan_to_num(np.abs(UZ[:, None, :, :] - UZ[:, :, None, :])) # [u, h, m, j] |z_h - z_m|
|
| 1003 |
+
pools = {t: [_crps_pool(normal_scores(ref["z_ref"][t][nm], ref["z_ref"][t][nm])) for nm in SETTING_NAMES]
|
| 1004 |
+
for t in range(N_TIERS)}
|
| 1005 |
+
UC = np.full(UZ.shape, np.nan)
|
| 1006 |
+
for t in range(N_TIERS):
|
| 1007 |
+
uu = ctx["u_tier"] == t
|
| 1008 |
+
for j in range(N_SET):
|
| 1009 |
+
if pools[t][j] is not None:
|
| 1010 |
+
UC[uu, :, j] = _crps_clim(UZ[uu, :, j], pools[t][j])
|
| 1011 |
+
ctx["UC"] = np.nan_to_num(UC)
|
| 1012 |
+
aF = ref["anchor_F"]
|
| 1013 |
+
ctx["F_point"], ctx["F_boot"] = aF["point"], aF["boot"]
|
| 1014 |
+
elig = np.zeros((N_TIERS, N_SET), bool)
|
| 1015 |
+
for t in range(N_TIERS):
|
| 1016 |
+
for j, nm in enumerate(SETTING_NAMES):
|
| 1017 |
+
room = (pools[t][j]["half"] if pools[t][j] is not None else 0.0) - aF["point"][t, j]
|
| 1018 |
+
elig[t, j] = (1 - ref["zero_share"][t][nm] >= F3_MIN_NONZERO) and np.isfinite(room) and room >= F3_MIN_ROOM
|
| 1019 |
+
ctx["f3_elig"] = elig
|
| 1020 |
+
ctx["f3_half"] = np.array([[p["half"] if p is not None else np.nan for p in pools[t]] for t in range(N_TIERS)])
|
| 1021 |
+
|
| 1022 |
+
# F4: per set, normal scores of the 6 main settings and raw density per tier
|
| 1023 |
+
J4 = len(F4_NAMES)
|
| 1024 |
+
SZ = np.full((S, N_TIERS, J4), np.nan)
|
| 1025 |
+
SD = np.full((S, N_TIERS), np.nan)
|
| 1026 |
+
for i in range(C):
|
| 1027 |
+
SZ[ctx["ch_set"][i], ctx["ch_tier"][i]] = Z[i, :J4]
|
| 1028 |
+
SD[ctx["ch_set"][i], ctx["ch_tier"][i]] = V[i, SETTING_NAMES.index("density")]
|
| 1029 |
+
dz = SZ[:, 1:] - SZ[:, :-1] # [S, 4, J4] signed steps t -> t+1
|
| 1030 |
+
pres = np.isfinite(dz).all(2) # [S, 4]
|
| 1031 |
+
inv = np.where(pres, (SD[:, 1:] <= SD[:, :-1]).astype(float), np.nan)
|
| 1032 |
+
ctx.update(SZ=SZ, f4_dz=dz, f4_pres=pres, f4_inv=inv)
|
| 1033 |
+
ctx["f4_sup"] = [[_sorted_support(np.where(pres[:, p], dz[:, p, j], np.nan)) for j in range(J4)]
|
| 1034 |
+
for p in range(N_TIERS - 1)]
|
| 1035 |
+
n_t = np.isfinite(SZ[:, :, 0]).sum(1)
|
| 1036 |
+
ctx["f4_m3"] = n_t >= 3
|
| 1037 |
+
ctx["f4_mean"] = np.where(ctx["f4_m3"][:, None], _nanmean_tiers(SZ), np.nan)
|
| 1038 |
+
|
| 1039 |
+
# F5 and F8 count tables
|
| 1040 |
+
ctx["f5_set"] = np.array([r[0] for r in U["f5"]], np.int64)
|
| 1041 |
+
ctx["f5_pair"] = np.array([r[1] for r in U["f5"]], np.int64)
|
| 1042 |
+
ctx["f5_cnt"] = np.array([r[2] for r in U["f5"]]) if U["f5"] else np.zeros((0, 10))
|
| 1043 |
+
ctx["f8_song"] = np.array([r[0] for r in U["f8"]], np.int64)
|
| 1044 |
+
ctx["f8_tier"] = np.array([r[1] for r in U["f8"]], np.int64)
|
| 1045 |
+
ctx["f8_a"] = np.array([r[2] for r in U["f8"]], np.int64)
|
| 1046 |
+
ctx["f8_b"] = np.array([r[3] for r in U["f8"]], np.int64)
|
| 1047 |
+
ctx["f8_cnt"] = np.array([r[4] for r in U["f8"]]) if U["f8"] else np.zeros((0, 10))
|
| 1048 |
+
ctx["cap_point"], ctx["cap_boot"] = ref["f8_cap"]["point"], ref["f8_cap"]["boot"]
|
| 1049 |
+
|
| 1050 |
+
# F6: AUC of quietness for rest vs active measures inside each chart (songs with loudness only)
|
| 1051 |
+
auc = np.full(C, np.nan)
|
| 1052 |
+
loud = ref.get("loudness") or {}
|
| 1053 |
+
for i, c in enumerate(ch):
|
| 1054 |
+
cur = loud.get(ctx["song_keys"][c["song"]])
|
| 1055 |
+
g = c["grid"]
|
| 1056 |
+
if cur is None or g is None:
|
| 1057 |
+
continue
|
| 1058 |
+
q = -_measure_loudness(cur, g["st_ms"], g["en_ms"])
|
| 1059 |
+
act = g["active"]
|
| 1060 |
+
ia = np.where(act)[0]
|
| 1061 |
+
ins = np.zeros(len(act), bool)
|
| 1062 |
+
ins[ia[0]: ia[-1] + 1] = True
|
| 1063 |
+
ok = ins & np.isfinite(q)
|
| 1064 |
+
auc[i] = _auc(q[ok], ~act[ok])
|
| 1065 |
+
ctx["auc"] = auc
|
| 1066 |
+
ctx["n_loud_songs"] = len({ctx["song_keys"][c["song"]] for c, a in zip(ch, auc) if np.isfinite(a)})
|
| 1067 |
+
|
| 1068 |
+
# F7 histograms; F9 novelty against the training index
|
| 1069 |
+
ctx["run_hist"] = np.array([c["run_hist"] for c in ch]) if C else np.zeros((0, RUN_BINS))
|
| 1070 |
+
ctx["phase_hist"] = np.array([c["phase_hist"] for c in ch]) if C else np.zeros((0, 4))
|
| 1071 |
+
nov = np.array([gram_novelty(c["grams"], ref["f9_index"]) for c in ch]) if C else np.zeros((0, 2))
|
| 1072 |
+
ctx["seen"], ctx["best"] = nov[:, 0], nov[:, 1]
|
| 1073 |
+
ctx["f9_sup"] = [_sorted_support(np.where(np.isin(np.arange(C), ctx["tier_rows"][t]), ctx["best"], np.nan))
|
| 1074 |
+
for t in range(N_TIERS)]
|
| 1075 |
+
return ctx
|
| 1076 |
+
|
| 1077 |
+
|
| 1078 |
+
def _nanmean_tiers(SZ: np.ndarray) -> np.ndarray:
|
| 1079 |
+
"""Mean over the present tiers of a set ([S, tiers, J] with NaN for missing tiers)."""
|
| 1080 |
+
ok = np.isfinite(SZ)
|
| 1081 |
+
return np.where(ok, SZ, 0.0).sum(1) / np.maximum(ok.sum(1), 1)
|
| 1082 |
+
|
| 1083 |
+
|
| 1084 |
+
def _measure_loudness(cur: dict, st_ms: np.ndarray, en_ms: np.ndarray, k: int = 8) -> np.ndarray:
|
| 1085 |
+
"""Mean loudness over each measure's time span, sampled at k points; NaN outside the loudness curve."""
|
| 1086 |
+
x = st_ms[:, None] + (en_ms - st_ms)[:, None] * ((np.arange(k) + 0.5) / k)[None, :]
|
| 1087 |
+
j = np.searchsorted(cur["t0"], x, "right") - 1
|
| 1088 |
+
jc = np.clip(j, 0, len(cur["t0"]) - 1)
|
| 1089 |
+
ok = (j >= 0) & (x < cur["t1"][jc])
|
| 1090 |
+
cnt = ok.sum(1)
|
| 1091 |
+
tot = np.where(ok, cur["loud"][jc], 0.0).sum(1)
|
| 1092 |
+
return np.where(cnt > 0, tot / np.maximum(cnt, 1), np.nan)
|
| 1093 |
+
|
| 1094 |
+
|
| 1095 |
+
# ------------------------------------------------------------------------------------------------ families
|
| 1096 |
+
|
| 1097 |
+
def _f1(ctx, ch_h, ch_s, wsong):
|
| 1098 |
+
energy, w1 = _vec(), _vec()
|
| 1099 |
+
for t in range(N_TIERS):
|
| 1100 |
+
rows = ctx["tier_rows"][t]
|
| 1101 |
+
if len(rows) == 0:
|
| 1102 |
+
continue
|
| 1103 |
+
base, key = wsong[ctx["ch_song"][rows]], ctx["key_st"][rows]
|
| 1104 |
+
wh, ws = _weights(key, ch_h[rows], base), _weights(key, ch_s[rows], base)
|
| 1105 |
+
song = ctx["ch_song"][rows]
|
| 1106 |
+
if _n_songs(song, wh) < MIN_SONGS or _n_songs(song, ws) < MIN_SONGS:
|
| 1107 |
+
continue
|
| 1108 |
+
a, b = wh / wh.sum(), ws / ws.sum()
|
| 1109 |
+
D = ctx["D"][t]
|
| 1110 |
+
energy[1 + t] = 2 * a @ D @ b - a @ D @ a - b @ D @ b
|
| 1111 |
+
w1[1 + t] = np.nanmean([_w1_two_part(wh, ws, ctx["sup"][t][j]) for j in range(N_SET)])
|
| 1112 |
+
for v in (energy, w1):
|
| 1113 |
+
if np.isfinite(v[1:]).any():
|
| 1114 |
+
v[0] = np.nanmean(v[1:])
|
| 1115 |
+
return {"energy": energy, "w1_mean": w1}
|
| 1116 |
+
|
| 1117 |
+
|
| 1118 |
+
def _unit_roles(ctx, roles):
|
| 1119 |
+
UR = ctx["UR"]
|
| 1120 |
+
P = UR >= 0
|
| 1121 |
+
r = np.zeros(UR.shape, bool)
|
| 1122 |
+
r[P] = roles[ctx["ch_set"][UR[P]]]
|
| 1123 |
+
return P & r, P & ~r
|
| 1124 |
+
|
| 1125 |
+
|
| 1126 |
+
def _f2(ctx, roles, wsong, rng):
|
| 1127 |
+
RH, RS = _unit_roles(ctx, roles)
|
| 1128 |
+
nS = RS.sum(1)
|
| 1129 |
+
below = np.einsum("um,uhmj->uhj", RS.astype(float), ctx["LESS"].astype(float))
|
| 1130 |
+
ties = np.einsum("um,uhmj->uhj", RS.astype(float), ctx["EQ"].astype(float))
|
| 1131 |
+
u = (below + (ties + 1) * rng.random(below.shape)) / (nS[:, None, None] + 1)
|
| 1132 |
+
valid = RH & (nS >= 1)[:, None]
|
| 1133 |
+
w = np.where(valid, (wsong[ctx["u_song"]] / np.maximum(RH.sum(1), 1))[:, None], 0.0)
|
| 1134 |
+
out = _vec()
|
| 1135 |
+
for k in range(1 + N_TIERS):
|
| 1136 |
+
sel = valid & ((ctx["u_tier"] == k - 1)[:, None] if k else True)
|
| 1137 |
+
if _n_songs(ctx["u_song"], (w * sel).sum(1)) < MIN_SONGS:
|
| 1138 |
+
continue
|
| 1139 |
+
out[k] = np.mean([_w1_uniform(u[..., j][sel], w[sel]) for j in range(N_SET)])
|
| 1140 |
+
return {"pit_w1": out}, u, valid, w
|
| 1141 |
+
|
| 1142 |
+
|
| 1143 |
+
def _f3(ctx, roles, wsong, rep, per_setting=False):
|
| 1144 |
+
RH, RS = _unit_roles(ctx, roles)
|
| 1145 |
+
RSf = RS.astype(float)
|
| 1146 |
+
nS = RSf.sum(1)
|
| 1147 |
+
PD = ctx["PD"]
|
| 1148 |
+
t1 = np.einsum("um,uhmj->uhj", RSf, PD) / np.maximum(nS, 1)[:, None, None]
|
| 1149 |
+
# PD[u, h, m] holds |z_h - z_m| for every member pair, so the ensemble spread uses it with h, m both drawn
|
| 1150 |
+
spread = np.einsum("uh,um,uhmj->uj", RSf, RSf, PD) / np.maximum(nS * (nS - 1), 1)[:, None]
|
| 1151 |
+
S = t1 - 0.5 * spread[:, None, :]
|
| 1152 |
+
valid = RH & (nS >= 2)[:, None]
|
| 1153 |
+
w = np.where(valid, (wsong[ctx["u_song"]] / np.maximum(RH.sum(1), 1))[:, None], 0.0) # [u, h]
|
| 1154 |
+
F = ctx["F_point"] if rep is None else ctx["F_boot"][rep % len(ctx["F_boot"])]
|
| 1155 |
+
Fu = F[ctx["u_tier"]] # [u, j]
|
| 1156 |
+
E = ctx["f3_elig"][ctx["u_tier"]].astype(float) # [u, j]
|
| 1157 |
+
Cw = np.einsum("uh,uhj,uj->uj", w, ctx["UC"], E)
|
| 1158 |
+
Sw = np.einsum("uh,uhj,uj->uj", w, S, E)
|
| 1159 |
+
Fw = np.einsum("uh,uj,uj->uj", w, np.nan_to_num(Fu), E)
|
| 1160 |
+
out = _vec()
|
| 1161 |
+
for k in range(1 + N_TIERS):
|
| 1162 |
+
sel = (ctx["u_tier"] == k - 1) if k else np.ones(len(Cw), bool)
|
| 1163 |
+
c, s, f = Cw[sel].sum(), Sw[sel].sum(), Fw[sel].sum()
|
| 1164 |
+
if c - f > 1e-9 and _n_songs(ctx["u_song"][sel], w[sel].sum(1)) >= MIN_SONGS:
|
| 1165 |
+
out[k] = 1 - (c - s) / (c - f)
|
| 1166 |
+
if not per_setting:
|
| 1167 |
+
return {"shortfall": out}
|
| 1168 |
+
sk = [(Cw[:, j].sum() - Sw[:, j].sum()) / (Cw[:, j].sum() - Fw[:, j].sum())
|
| 1169 |
+
if Cw[:, j].sum() - Fw[:, j].sum() > 1e-9 else np.nan for j in range(N_SET)]
|
| 1170 |
+
return {"shortfall": out}, sk
|
| 1171 |
+
|
| 1172 |
+
|
| 1173 |
+
def _set_weights(ctx, member, wsong, pair):
|
| 1174 |
+
key = ctx["set_song"] * (N_TIERS - 1) + pair
|
| 1175 |
+
return _weights(key, member, wsong[ctx["set_song"]])
|
| 1176 |
+
|
| 1177 |
+
|
| 1178 |
+
def _f4(ctx, roles, wsong):
|
| 1179 |
+
steps, inv, share = _vec(), _vec(), _vec()
|
| 1180 |
+
J4 = len(F4_NAMES)
|
| 1181 |
+
acc_inv = {True: [0.0, 0.0], False: [0.0, 0.0]}
|
| 1182 |
+
acc_xy = {True: ([], [], []), False: ([], [], [])}
|
| 1183 |
+
for p in range(N_TIERS - 1):
|
| 1184 |
+
pres = ctx["f4_pres"][:, p]
|
| 1185 |
+
wh = _set_weights(ctx, pres & roles, wsong, p)
|
| 1186 |
+
ws = _set_weights(ctx, pres & ~roles, wsong, p)
|
| 1187 |
+
if _n_songs(ctx["set_song"], wh) < MIN_SONGS or _n_songs(ctx["set_song"], ws) < MIN_SONGS:
|
| 1188 |
+
continue
|
| 1189 |
+
steps[1 + p] = np.nanmean([_w1_sorted(wh, ws, *ctx["f4_sup"][p][j]) for j in range(J4)])
|
| 1190 |
+
iv = np.nan_to_num(ctx["f4_inv"][:, p])
|
| 1191 |
+
inv[1 + p] = (ws * iv).sum() / ws.sum() - (wh * iv).sum() / wh.sum()
|
| 1192 |
+
rs = []
|
| 1193 |
+
for j in range(J4):
|
| 1194 |
+
x, y = ctx["SZ"][:, p, j], ctx["SZ"][:, p + 1, j]
|
| 1195 |
+
x, y = np.nan_to_num(x), np.nan_to_num(y)
|
| 1196 |
+
rs.append(abs(_wcorr_sym(x, y, ws) - _wcorr_sym(x, y, wh)))
|
| 1197 |
+
share[1 + p] = np.nanmean(rs)
|
| 1198 |
+
for role, w in ((True, wh), (False, ws)):
|
| 1199 |
+
acc_inv[role][0] += (w * iv).sum()
|
| 1200 |
+
acc_inv[role][1] += w.sum()
|
| 1201 |
+
acc_xy[role][0].append(np.nan_to_num(ctx["SZ"][:, p]))
|
| 1202 |
+
acc_xy[role][1].append(np.nan_to_num(ctx["SZ"][:, p + 1]))
|
| 1203 |
+
acc_xy[role][2].append(w)
|
| 1204 |
+
if np.isfinite(steps[1:]).any():
|
| 1205 |
+
steps[0] = np.nanmean(steps[1:])
|
| 1206 |
+
inv[0] = acc_inv[False][0] / acc_inv[False][1] - acc_inv[True][0] / acc_inv[True][1]
|
| 1207 |
+
rs = []
|
| 1208 |
+
for j in range(J4):
|
| 1209 |
+
r = {}
|
| 1210 |
+
for role in (True, False):
|
| 1211 |
+
X = np.concatenate([x[:, j] for x in acc_xy[role][0]])
|
| 1212 |
+
Y = np.concatenate([y[:, j] for y in acc_xy[role][1]])
|
| 1213 |
+
r[role] = _wcorr_sym(X, Y, np.concatenate(acc_xy[role][2]))
|
| 1214 |
+
rs.append(abs(r[False] - r[True]))
|
| 1215 |
+
share[0] = np.nanmean(rs)
|
| 1216 |
+
# spread of the mapset mean across songs (mapsets with at least 3 tiers)
|
| 1217 |
+
spread = _vec()
|
| 1218 |
+
m3 = ctx["f4_m3"]
|
| 1219 |
+
wh = _weights(ctx["set_song"], m3 & roles, wsong[ctx["set_song"]])
|
| 1220 |
+
ws = _weights(ctx["set_song"], m3 & ~roles, wsong[ctx["set_song"]])
|
| 1221 |
+
if _n_songs(ctx["set_song"], wh) >= MIN_SONGS and _n_songs(ctx["set_song"], ws) >= MIN_SONGS:
|
| 1222 |
+
Mx = np.nan_to_num(ctx["f4_mean"])
|
| 1223 |
+
lr = [abs(np.log(max(_wsd(Mx[:, j], ws), 1e-9) / max(_wsd(Mx[:, j], wh), 1e-9))) for j in range(J4)]
|
| 1224 |
+
spread[0] = np.mean(lr)
|
| 1225 |
+
return {"steps": steps, "inversions": inv, "spread": spread, "sharing": share}
|
| 1226 |
+
|
| 1227 |
+
|
| 1228 |
+
def _f5(ctx, roles, wsong):
|
| 1229 |
+
out = {k: _vec() for k in ("rest_f1", "roll_f1", "big_f1", "nesting")}
|
| 1230 |
+
if len(ctx["f5_set"]) == 0:
|
| 1231 |
+
return out
|
| 1232 |
+
song = ctx["set_song"][ctx["f5_set"]]
|
| 1233 |
+
role = roles[ctx["f5_set"]]
|
| 1234 |
+
key = song * (N_TIERS - 1) + ctx["f5_pair"]
|
| 1235 |
+
base = wsong[song]
|
| 1236 |
+
wh, ws = _weights(key, role, base), _weights(key, ~role, base)
|
| 1237 |
+
X = ctx["f5_cnt"]
|
| 1238 |
+
for k in range(N_TIERS):
|
| 1239 |
+
sel = (ctx["f5_pair"] == k - 1) if k else np.ones(len(X), bool)
|
| 1240 |
+
a, b = wh * sel, ws * sel
|
| 1241 |
+
if _n_songs(song, a) < MIN_SONGS or _n_songs(song, b) < MIN_SONGS:
|
| 1242 |
+
continue
|
| 1243 |
+
for name, q in (("rest_f1", 0), ("roll_f1", 1), ("big_f1", 2)):
|
| 1244 |
+
out[name][k] = abs(_pooled_f1(X, q, b) - _pooled_f1(X, q, a))
|
| 1245 |
+
nest = [(w * X[:, 0]).sum() / (w * X[:, 2]).sum() if (np.sign(w) * X[:, 2]).sum() >= MIN_LAYOUT / 2 else np.nan
|
| 1246 |
+
for w in (a, b)]
|
| 1247 |
+
out["nesting"][k] = abs(nest[1] - nest[0])
|
| 1248 |
+
return out
|
| 1249 |
+
|
| 1250 |
+
|
| 1251 |
+
def _pooled_f1(X, q, w):
|
| 1252 |
+
"""Pooled F1 of layout kind q (0 rest, 1 roll, 2 big) over weighted pair rows; NaN when the rows (unweighted)
|
| 1253 |
+
hold fewer than MIN_LAYOUT labelled measures."""
|
| 1254 |
+
if (np.sign(w) * (X[:, 3 * q + 1] + X[:, 3 * q + 2])).sum() < MIN_LAYOUT:
|
| 1255 |
+
return np.nan
|
| 1256 |
+
return 2 * (w * X[:, 3 * q]).sum() / (w * (X[:, 3 * q + 1] + X[:, 3 * q + 2])).sum()
|
| 1257 |
+
|
| 1258 |
+
|
| 1259 |
+
def _f6(ctx, ch_h, ch_s, wsong):
|
| 1260 |
+
out = _vec()
|
| 1261 |
+
ok = np.isfinite(ctx["auc"])
|
| 1262 |
+
key, base = ctx["key_st"], wsong[ctx["ch_song"]]
|
| 1263 |
+
wh, ws = _weights(key, ch_h & ok, base), _weights(key, ch_s & ok, base)
|
| 1264 |
+
a = np.nan_to_num(ctx["auc"])
|
| 1265 |
+
for k in range(1 + N_TIERS):
|
| 1266 |
+
sel = (ctx["ch_tier"] == k - 1) if k else np.ones(len(a), bool)
|
| 1267 |
+
h, s = wh * sel, ws * sel
|
| 1268 |
+
if _n_songs(ctx["ch_song"], h) < MIN_SONGS or _n_songs(ctx["ch_song"], s) < MIN_SONGS:
|
| 1269 |
+
continue
|
| 1270 |
+
out[k] = abs((s * a).sum() / s.sum() - (h * a).sum() / h.sum())
|
| 1271 |
+
return {"auc": out}
|
| 1272 |
+
|
| 1273 |
+
|
| 1274 |
+
def _f7(ctx, ch_h, ch_s, wsong):
|
| 1275 |
+
names = {"blocks_per100": VALUE_NAMES.index("rest_blocks_per100"), "block_len": VALUE_NAMES.index("rest_block_len"),
|
| 1276 |
+
"roll_len": VALUE_NAMES.index("roll_len"), "dens_cv": VALUE_NAMES.index("dens_cv")}
|
| 1277 |
+
out = {k: _vec() for k in ("run_length", "phase4", *names)}
|
| 1278 |
+
acc = {"run_length": [np.zeros(RUN_BINS), np.zeros(RUN_BINS)], "phase4": [np.zeros(4), np.zeros(4)]}
|
| 1279 |
+
any_tier = False
|
| 1280 |
+
for t in range(N_TIERS):
|
| 1281 |
+
rows = ctx["tier_rows"][t]
|
| 1282 |
+
if len(rows) == 0:
|
| 1283 |
+
continue
|
| 1284 |
+
base, key = wsong[ctx["ch_song"][rows]], ctx["key_st"][rows]
|
| 1285 |
+
wh, ws = _weights(key, ch_h[rows], base), _weights(key, ch_s[rows], base)
|
| 1286 |
+
song = ctx["ch_song"][rows]
|
| 1287 |
+
if _n_songs(song, wh) < MIN_SONGS or _n_songs(song, ws) < MIN_SONGS:
|
| 1288 |
+
continue
|
| 1289 |
+
any_tier = True
|
| 1290 |
+
for name, j in names.items():
|
| 1291 |
+
out[name][1 + t] = _w1_two_part(wh, ws, ctx["sup"][t][j])
|
| 1292 |
+
for name, Hc in (("run_length", ctx["run_hist"][rows]), ("phase4", ctx["phase_hist"][rows])):
|
| 1293 |
+
hh, hs = wh @ Hc, ws @ Hc
|
| 1294 |
+
acc[name][0] += hh
|
| 1295 |
+
acc[name][1] += hs
|
| 1296 |
+
out[name][1 + t] = _tv_hist(hh, hs)
|
| 1297 |
+
for name in names:
|
| 1298 |
+
if np.isfinite(out[name][1:]).any():
|
| 1299 |
+
out[name][0] = np.nanmean(out[name][1:])
|
| 1300 |
+
for name in acc:
|
| 1301 |
+
if any_tier:
|
| 1302 |
+
out[name][0] = _tv_hist(*acc[name])
|
| 1303 |
+
return out
|
| 1304 |
+
|
| 1305 |
+
|
| 1306 |
+
def _tv_hist(hh: np.ndarray, hs: np.ndarray) -> float:
|
| 1307 |
+
"""Total variation distance of two count histograms. When only one side has any count (for example a system
|
| 1308 |
+
that never writes a rest run), the two differ completely: 1. NaN when neither side has a count."""
|
| 1309 |
+
if hh.sum() > 0 and hs.sum() > 0:
|
| 1310 |
+
return float(0.5 * np.abs(hh / hh.sum() - hs / hs.sum()).sum())
|
| 1311 |
+
return 1.0 if hh.sum() > 0 or hs.sum() > 0 else np.nan
|
| 1312 |
+
|
| 1313 |
+
|
| 1314 |
+
def _f8(ctx, roles, wsong, rep, details=False):
|
| 1315 |
+
out = {k: _vec() for k in ("rest", "roll", "big", "rest_within_song")}
|
| 1316 |
+
if len(ctx["f8_a"]) == 0:
|
| 1317 |
+
return (out, {}) if details else out
|
| 1318 |
+
ra, rb = roles[ctx["f8_a"]], roles[ctx["f8_b"]]
|
| 1319 |
+
ss, hs = ~ra & ~rb, ra ^ rb
|
| 1320 |
+
song, tier = ctx["f8_song"], ctx["f8_tier"]
|
| 1321 |
+
key, base = song * N_TIERS + tier, wsong[song]
|
| 1322 |
+
wss, whs = _weights(key, ss, base), _weights(key, hs, base)
|
| 1323 |
+
X = ctx["f8_cnt"]
|
| 1324 |
+
cap = ctx["cap_point"] if rep is None else ctx["cap_boot"][rep % len(ctx["cap_boot"])]
|
| 1325 |
+
info = {}
|
| 1326 |
+
for q, name in enumerate(("rest", "roll", "big")):
|
| 1327 |
+
num, den, exc = [], [], []
|
| 1328 |
+
for t in range(N_TIERS):
|
| 1329 |
+
w = wss * (tier == t)
|
| 1330 |
+
agree = _pooled_f1(X, q, w)
|
| 1331 |
+
if _n_songs(song, w) < MIN_SONGS or not np.isfinite(agree) or not np.isfinite(cap[t, q]):
|
| 1332 |
+
continue
|
| 1333 |
+
d = (w * (X[:, 3 * q + 1] + X[:, 3 * q + 2])).sum()
|
| 1334 |
+
out[name][1 + t] = agree - cap[t, q]
|
| 1335 |
+
num.append(d * (agree - cap[t, q]))
|
| 1336 |
+
den.append(d)
|
| 1337 |
+
info[(name, t)] = (agree, cap[t, q])
|
| 1338 |
+
if den:
|
| 1339 |
+
out[name][0] = sum(num) / sum(den)
|
| 1340 |
+
for k in range(1 + N_TIERS):
|
| 1341 |
+
sel = (tier == k - 1) if k else np.ones(len(tier), bool)
|
| 1342 |
+
a, b = wss * sel, whs * sel
|
| 1343 |
+
if _n_songs(song, a) < MIN_SONGS or _n_songs(song, b) < MIN_SONGS:
|
| 1344 |
+
continue
|
| 1345 |
+
out["rest_within_song"][k] = _pooled_f1(X, 0, a) - _pooled_f1(X, 0, b)
|
| 1346 |
+
return (out, info) if details else out
|
| 1347 |
+
|
| 1348 |
+
|
| 1349 |
+
def _f9(ctx, ch_h, ch_s, wsong):
|
| 1350 |
+
out = {k: _vec() for k in ("copy_share", "best_single", "seen_share")}
|
| 1351 |
+
ok = np.isfinite(ctx["best"])
|
| 1352 |
+
key, base = ctx["key_st"], wsong[ctx["ch_song"]]
|
| 1353 |
+
wh, ws = _weights(key, ch_h & ok, base), _weights(key, ch_s & ok, base)
|
| 1354 |
+
copy = (np.nan_to_num(ctx["best"]) >= COPY_CUT).astype(float)
|
| 1355 |
+
seen = np.nan_to_num(ctx["seen"])
|
| 1356 |
+
w1s = []
|
| 1357 |
+
for k in range(1 + N_TIERS):
|
| 1358 |
+
sel = (ctx["ch_tier"] == k - 1) if k else np.ones(len(copy), bool)
|
| 1359 |
+
h, s = wh * sel, ws * sel
|
| 1360 |
+
if _n_songs(ctx["ch_song"], h) < MIN_SONGS or _n_songs(ctx["ch_song"], s) < MIN_SONGS:
|
| 1361 |
+
continue
|
| 1362 |
+
out["copy_share"][k] = (s * copy).sum() / s.sum() - (h * copy).sum() / h.sum()
|
| 1363 |
+
out["seen_share"][k] = abs((s * seen).sum() / s.sum() - (h * seen).sum() / h.sum())
|
| 1364 |
+
if k:
|
| 1365 |
+
out["best_single"][k] = _w1_sorted(h, s, *ctx["f9_sup"][k - 1])
|
| 1366 |
+
w1s.append(out["best_single"][k])
|
| 1367 |
+
if w1s:
|
| 1368 |
+
out["best_single"][0] = np.nanmean(w1s)
|
| 1369 |
+
return out
|
| 1370 |
+
|
| 1371 |
+
|
| 1372 |
+
def _evaluate(ctx, roles, wsong, rng, rep):
|
| 1373 |
+
"""All family statistics ({family: {part: [pooled, stratum 1..5]}}) for one role assignment (True = human set)
|
| 1374 |
+
and one set of song weights."""
|
| 1375 |
+
ch_h = roles[ctx["ch_set"]]
|
| 1376 |
+
ch_s = ~ch_h
|
| 1377 |
+
return {"F1": _f1(ctx, ch_h, ch_s, wsong), "F2": _f2(ctx, roles, wsong, rng)[0],
|
| 1378 |
+
"F3": _f3(ctx, roles, wsong, rep), "F4": _f4(ctx, roles, wsong), "F5": _f5(ctx, roles, wsong),
|
| 1379 |
+
"F6": _f6(ctx, ch_h, ch_s, wsong), "F7": _f7(ctx, ch_h, ch_s, wsong), "F8": _f8(ctx, roles, wsong, rep),
|
| 1380 |
+
"F9": _f9(ctx, ch_h, ch_s, wsong)}
|
| 1381 |
+
|
| 1382 |
+
|
| 1383 |
+
def _swap_roles(ctx, rng):
|
| 1384 |
+
"""Random relabelling within each song: n_human of the song's mapsets, chosen uniformly, become 'human'."""
|
| 1385 |
+
keys = rng.random(len(ctx["set_song"]))
|
| 1386 |
+
order = np.lexsort((keys, ctx["set_song"]))
|
| 1387 |
+
ss = ctx["set_song"][order]
|
| 1388 |
+
first = np.concatenate([[True], ss[1:] != ss[:-1]])
|
| 1389 |
+
rank = np.arange(len(ss)) - np.maximum.accumulate(np.where(first, np.arange(len(ss)), 0))
|
| 1390 |
+
roles = np.zeros(len(ss), bool)
|
| 1391 |
+
roles[order] = rank < ctx["n_human"][ss]
|
| 1392 |
+
return roles
|
| 1393 |
+
|
| 1394 |
+
|
| 1395 |
+
# ------------------------------------------------------------------------------------------------ run
|
| 1396 |
+
|
| 1397 |
+
def _f(x):
|
| 1398 |
+
"""JSON-friendly float (None for NaN)."""
|
| 1399 |
+
x = float(x)
|
| 1400 |
+
return None if not np.isfinite(x) else round(x, 6)
|
| 1401 |
+
|
| 1402 |
+
|
| 1403 |
+
def _holm(p: dict) -> dict:
|
| 1404 |
+
keys = sorted((k for k, v in p.items() if v is not None), key=lambda k: p[k])
|
| 1405 |
+
m, out, run = len(keys), {}, 0.0
|
| 1406 |
+
for i, k in enumerate(keys):
|
| 1407 |
+
run = max(run, min(1.0, (m - i) * p[k]))
|
| 1408 |
+
out[k] = run
|
| 1409 |
+
return out
|
| 1410 |
+
|
| 1411 |
+
|
| 1412 |
+
def run_families(collection: dict, reference_info: dict, n_swap: int = 500, n_boot: int = 500, seed: int = 0,
|
| 1413 |
+
units: dict | None = None, margins: dict | None = None, boot_swaps: int = 3,
|
| 1414 |
+
alpha: float = ALPHA) -> dict:
|
| 1415 |
+
"""Evaluate a collection (human mapsets and the system's draws per song) with all nine families.
|
| 1416 |
+
|
| 1417 |
+
Returns a JSON-able dict: per family the primary statistic, its swap / bootstrap p, the Holm-adjusted p, 'fail'
|
| 1418 |
+
(adjusted p < alpha), 'pass' (draft equivalence of all its statistics), 'details' (descriptions under the real
|
| 1419 |
+
labels), and under 'statistics' for each: statistic, floor (swap median, or 0 for anchor statistics), swap
|
| 1420 |
+
median, excess, 95% CI of the excess, p, margin, pass, and the same per tier (or per adjacent tier pair for F4
|
| 1421 |
+
and F5) under 'by_stratum'. `units` reuses compute_unit_stats(collection); `margins` overrides
|
| 1422 |
+
DRAFT_MARGINS entries ({family: {part: margin}}).
|
| 1423 |
+
|
| 1424 |
+
The smallest p a swap part can reach is 1 / (n_swap + 1), and 1 / (n_boot + 1) for an anchor part; Holm over
|
| 1425 |
+
nine families needs p <= alpha / 9, so keep n_swap and n_boot at 200 or more (500 by default)."""
|
| 1426 |
+
U = units if units is not None else compute_unit_stats(collection)
|
| 1427 |
+
mg = {f: {**DRAFT_MARGINS[f], **(margins or {}).get(f, {})} for f in DRAFT_MARGINS}
|
| 1428 |
+
ctx = _prepare(U, reference_info)
|
| 1429 |
+
rng = np.random.default_rng(seed)
|
| 1430 |
+
n = ctx["n_songs"]
|
| 1431 |
+
roles0 = ctx["set_human"].copy()
|
| 1432 |
+
ones = np.ones(n)
|
| 1433 |
+
obs = _evaluate(ctx, roles0, ones, rng, None)
|
| 1434 |
+
swaps = [_evaluate(ctx, _swap_roles(ctx, rng), ones, rng, None) for _ in range(n_swap)]
|
| 1435 |
+
boots, bfloor = [], []
|
| 1436 |
+
for b in range(n_boot):
|
| 1437 |
+
w = rng.multinomial(n, np.full(n, 1.0 / n)).astype(np.float64)
|
| 1438 |
+
boots.append(_evaluate(ctx, roles0, w, rng, b))
|
| 1439 |
+
bfloor.append([_evaluate(ctx, _swap_roles(ctx, rng), w, rng, b) for _ in range(boot_swaps)])
|
| 1440 |
+
|
| 1441 |
+
fams, primary_p = {}, {}
|
| 1442 |
+
for fam, (title, primary, parts) in FAMILIES.items():
|
| 1443 |
+
pairs = fam in PAIR_FAMILIES
|
| 1444 |
+
labels = [f"{t}-{t + 1}" for t in range(N_TIERS - 1)] if pairs else [str(t) for t in range(N_TIERS)]
|
| 1445 |
+
pres = {}
|
| 1446 |
+
for part, kind in parts:
|
| 1447 |
+
o = obs[fam][part]
|
| 1448 |
+
sw = np.array([s[fam][part] for s in swaps]) if swaps else np.full((0, len(o)), np.nan)
|
| 1449 |
+
bt = np.array([s[fam][part] for s in boots]) if boots else np.full((0, len(o)), np.nan)
|
| 1450 |
+
with warnings.catch_warnings():
|
| 1451 |
+
warnings.simplefilter("ignore", RuntimeWarning) # all-NaN strata stay NaN
|
| 1452 |
+
swap_med = np.nanmedian(sw, 0) if len(sw) else np.full(len(o), np.nan)
|
| 1453 |
+
if kind == "swap":
|
| 1454 |
+
floor = swap_med
|
| 1455 |
+
bf = np.array([[s[fam][part] for s in r] for r in bfloor]) if bfloor else np.zeros((0, 1, len(o)))
|
| 1456 |
+
ex_b = bt - np.nanmedian(bf, 1) if len(bt) else bt
|
| 1457 |
+
p = (1 + np.sum(sw >= o, 0)) / (1 + np.sum(np.isfinite(sw), 0))
|
| 1458 |
+
else:
|
| 1459 |
+
floor = np.zeros(len(o))
|
| 1460 |
+
ex_b = bt
|
| 1461 |
+
p = (1 + np.sum(bt <= 0, 0)) / (1 + np.sum(np.isfinite(bt), 0))
|
| 1462 |
+
lo, hi = (np.nanpercentile(ex_b, [2.5, 97.5], 0) if len(ex_b)
|
| 1463 |
+
else (np.full(len(o), np.nan), np.full(len(o), np.nan)))
|
| 1464 |
+
exc = o - floor
|
| 1465 |
+
m = mg[fam][part]
|
| 1466 |
+
ok_pool = np.isfinite(o[0]) and np.isfinite(hi[0])
|
| 1467 |
+
severe = [labels[k - 1] for k in range(1, len(o)) if np.isfinite(lo[k]) and lo[k] > m]
|
| 1468 |
+
passed = (bool(hi[0] <= m) and not severe) if ok_pool else None
|
| 1469 |
+
|
| 1470 |
+
def entry(k):
|
| 1471 |
+
return {"statistic": _f(o[k]), "floor": _f(floor[k]), "swap_median": _f(swap_med[k]),
|
| 1472 |
+
"excess": _f(exc[k]), "ci": [_f(lo[k]), _f(hi[k])],
|
| 1473 |
+
"p": _f(p[k]) if np.isfinite(o[k]) else None}
|
| 1474 |
+
pres[part] = {**entry(0), "floor_kind": "swap_median" if kind == "swap" else "anchor", "margin": m,
|
| 1475 |
+
"pass": passed, "in_family_pass": (fam, part) not in REPORT_ONLY, "severe_strata": severe,
|
| 1476 |
+
"by_stratum": {labels[k - 1]: {**entry(k), "pass": (bool(hi[k] <= m) if np.isfinite(hi[k]) else None)}
|
| 1477 |
+
for k in range(1, len(o)) if np.isfinite(o[k])}}
|
| 1478 |
+
prim = pres[primary]
|
| 1479 |
+
primary_p[fam] = prim["p"]
|
| 1480 |
+
part_pass = [v["pass"] for v in pres.values() if v["in_family_pass"]]
|
| 1481 |
+
# a failing statistic makes the family not pass even when the primary one cannot be computed (for example
|
| 1482 |
+
# rest statistics of a system that never rests); without a failing one, an undefined primary leaves the
|
| 1483 |
+
# family not available
|
| 1484 |
+
if any(x is False for x in part_pass):
|
| 1485 |
+
fpass = False
|
| 1486 |
+
else:
|
| 1487 |
+
fpass = None if prim["pass"] is None else True
|
| 1488 |
+
fams[fam] = {"title": title, "primary": primary, "p": prim["p"], "pass": fpass, "statistics": pres,
|
| 1489 |
+
"strata": "adjacent tier pairs" if pairs else "tiers"}
|
| 1490 |
+
holm = _holm(primary_p)
|
| 1491 |
+
for fam in fams:
|
| 1492 |
+
fams[fam]["p_holm"] = _f(holm[fam]) if fam in holm else None
|
| 1493 |
+
fams[fam]["fail"] = (holm[fam] < alpha) if fam in holm else None
|
| 1494 |
+
fams_details = _details(ctx, U, rng)
|
| 1495 |
+
for fam, d in fams_details.items():
|
| 1496 |
+
fams[fam]["details"] = d
|
| 1497 |
+
counts = {"songs": n, "skipped_songs": len(U["skipped_songs"]),
|
| 1498 |
+
"human_sets": int(ctx["set_human"].sum()), "draw_sets": int((~ctx["set_human"]).sum()),
|
| 1499 |
+
"human_charts": int(ctx["set_human"][ctx["ch_set"]].sum()),
|
| 1500 |
+
"draw_charts": int((~ctx["set_human"][ctx["ch_set"]]).sum()),
|
| 1501 |
+
"missing_draw_units": _missing_draw_units(ctx, U), "extra_draw_tiers": U["extra_tiers"],
|
| 1502 |
+
"songs_with_loudness": ctx["n_loud_songs"]}
|
| 1503 |
+
avail = {f: v["pass"] for f, v in fams.items()}
|
| 1504 |
+
return {"config": {"n_swap": n_swap, "n_boot": n_boot, "boot_swaps": boot_swaps, "seed": seed, "alpha": alpha,
|
| 1505 |
+
"margins": mg, "copy_cut": COPY_CUT, "zero_heavy": ZERO_HEAVY},
|
| 1506 |
+
"counts": counts, "families": fams,
|
| 1507 |
+
# the gate passes only when every family passes (a family that cannot be computed is not a pass) and
|
| 1508 |
+
# every scored unit of every draw has a valid chart: a draw without one drops out of every statistic,
|
| 1509 |
+
# which would be the same as discarding draws after the fact
|
| 1510 |
+
"summary": {"all_pass": all(v is True for v in avail.values()) and counts["missing_draw_units"] == 0,
|
| 1511 |
+
"missing_draw_units": counts["missing_draw_units"],
|
| 1512 |
+
"not_available": [f for f, v in avail.items() if v is None],
|
| 1513 |
+
"not_passed": [f for f, v in avail.items() if v is False],
|
| 1514 |
+
"failed": [f for f, v in fams.items() if v["fail"]]}}
|
| 1515 |
+
|
| 1516 |
+
|
| 1517 |
+
def _missing_draw_units(ctx, U) -> int:
|
| 1518 |
+
"""Scored (song, tier, draw) units without a valid chart."""
|
| 1519 |
+
have = set(zip(ctx["ch_set"].tolist(), ctx["ch_tier"].tolist()))
|
| 1520 |
+
miss = 0
|
| 1521 |
+
for row, s in enumerate(U["sets"]):
|
| 1522 |
+
if not s["human"]:
|
| 1523 |
+
miss += sum((row, t) not in have for t in U["songs"][s["song"]]["tiers"])
|
| 1524 |
+
return miss
|
| 1525 |
+
|
| 1526 |
+
|
| 1527 |
+
def _details(ctx, U, rng) -> dict:
|
| 1528 |
+
"""Per-setting and per-stratum descriptions under the real labels (no resampling)."""
|
| 1529 |
+
roles = ctx["set_human"]
|
| 1530 |
+
ch_h = roles[ctx["ch_set"]]
|
| 1531 |
+
ch_s = ~ch_h
|
| 1532 |
+
ones = np.ones(ctx["n_songs"])
|
| 1533 |
+
out = {}
|
| 1534 |
+
# F1: two-part W1 and zero shares per tier and setting
|
| 1535 |
+
f1 = {}
|
| 1536 |
+
for t in range(N_TIERS):
|
| 1537 |
+
rows = ctx["tier_rows"][t]
|
| 1538 |
+
if len(rows) == 0:
|
| 1539 |
+
continue
|
| 1540 |
+
key, base = ctx["key_st"][rows], ones[ctx["ch_song"][rows]]
|
| 1541 |
+
wh, ws = _weights(key, ch_h[rows], base), _weights(key, ch_s[rows], base)
|
| 1542 |
+
if wh.sum() <= 0 or ws.sum() <= 0:
|
| 1543 |
+
continue
|
| 1544 |
+
V = ctx["V"][rows]
|
| 1545 |
+
f1[str(t)] = {nm: {"w1": _f(_w1_two_part(wh, ws, ctx["sup"][t][j])), "two_part": bool(ctx["heavy"][t][j]),
|
| 1546 |
+
"zero_share_human": _f((wh * (V[:, j] == 0)).sum() / wh.sum()),
|
| 1547 |
+
"zero_share_system": _f((ws * (V[:, j] == 0)).sum() / ws.sum()),
|
| 1548 |
+
"mean_human": _f((wh * V[:, j]).sum() / wh.sum()),
|
| 1549 |
+
"mean_system": _f((ws * V[:, j]).sum() / ws.sum())}
|
| 1550 |
+
for j, nm in enumerate(SETTING_NAMES)}
|
| 1551 |
+
out["F1"] = {"per_tier_setting": f1}
|
| 1552 |
+
# F2: bias, dispersion and outside share of the PIT per setting
|
| 1553 |
+
_, u, valid, w = _f2(ctx, roles, ones, rng)
|
| 1554 |
+
nS = _unit_roles(ctx, roles)[1].sum(1)
|
| 1555 |
+
f2 = {}
|
| 1556 |
+
for j, nm in enumerate(SETTING_NAMES):
|
| 1557 |
+
x, ww = u[..., j][valid], w[valid]
|
| 1558 |
+
if ww.sum() <= 0:
|
| 1559 |
+
continue
|
| 1560 |
+
mu = (ww * x).sum() / ww.sum()
|
| 1561 |
+
k = np.repeat(nS[:, None], valid.shape[1], 1)[valid]
|
| 1562 |
+
outside = (x < 1 / (k + 1)) | (x > k / (k + 1))
|
| 1563 |
+
f2[nm] = {"bias": _f(mu - 0.5), "dispersion_12var": _f(12 * (ww * (x - mu) ** 2).sum() / ww.sum()),
|
| 1564 |
+
"outside": _f((ww * outside).sum() / ww.sum()), "outside_expected": _f((ww * 2 / (k + 1)).sum() / ww.sum())}
|
| 1565 |
+
out["F2"] = {"per_setting": f2, "note": "uniform PIT: bias 0, dispersion 1; dispersion > 1 = draws too narrow"}
|
| 1566 |
+
# F3: skill per setting, eligibility and anchors
|
| 1567 |
+
res, sk = _f3(ctx, roles, ones, None, per_setting=True)
|
| 1568 |
+
out["F3"] = {"skill_pooled": _f(1 - res["shortfall"][0]) if np.isfinite(res["shortfall"][0]) else None,
|
| 1569 |
+
"skill_per_setting": {nm: _f(v) for nm, v in zip(SETTING_NAMES, sk)},
|
| 1570 |
+
"eligible": {str(t): [nm for j, nm in enumerate(SETTING_NAMES) if ctx["f3_elig"][t, j]]
|
| 1571 |
+
for t in range(N_TIERS)},
|
| 1572 |
+
"anchor_F": {str(t): {nm: _f(ctx["F_point"][t, j]) for j, nm in enumerate(SETTING_NAMES)}
|
| 1573 |
+
for t in range(N_TIERS)},
|
| 1574 |
+
"climatology_half_spread": {str(t): {nm: _f(ctx["f3_half"][t, j]) for j, nm in enumerate(SETTING_NAMES)}
|
| 1575 |
+
for t in range(N_TIERS)}}
|
| 1576 |
+
# F6 / F8 / F9 descriptions
|
| 1577 |
+
out["F6"] = {"songs_with_loudness": ctx["n_loud_songs"],
|
| 1578 |
+
"mean_auc_human": _f(np.nanmean(np.where(ch_h, ctx["auc"], np.nan))) if np.isfinite(ctx["auc"][ch_h]).any() else None,
|
| 1579 |
+
"mean_auc_system": _f(np.nanmean(np.where(ch_s, ctx["auc"], np.nan))) if np.isfinite(ctx["auc"][ch_s]).any() else None}
|
| 1580 |
+
_, info = _f8(ctx, roles, ones, None, details=True)
|
| 1581 |
+
out["F8"] = {"agreement_and_cap": {f"{k[0]}_{k[1]}": {"agreement": _f(v[0]), "cap": _f(v[1])} for k, v in info.items()}}
|
| 1582 |
+
copies = [{"song": ctx["song_keys"][ctx["ch_song"][i]], "set": int(U["sets"][ctx["ch_set"][i]]["pos"]),
|
| 1583 |
+
"tier": int(ctx["ch_tier"][i]), "best_single": _f(ctx["best"][i]), "human": bool(ch_h[i])}
|
| 1584 |
+
for i in np.where(np.nan_to_num(ctx["best"]) >= COPY_CUT)[0]]
|
| 1585 |
+
out["F9"] = {"copies": copies[:200], "n_copies_system": int(sum(not c["human"] for c in copies)),
|
| 1586 |
+
"n_copies_human": int(sum(c["human"] for c in copies))}
|
| 1587 |
+
return out
|
chartgen/features.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Audio decoding and log-Mel features.
|
| 2 |
+
|
| 3 |
+
Frame rate is fixed at 100 fps (24 kHz, hop 240) so a frame index is time in 10 ms units.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import subprocess
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
SAMPLE_RATE = 24_000
|
| 13 |
+
HOP = 240
|
| 14 |
+
N_FFT = 2048
|
| 15 |
+
N_MELS = 128
|
| 16 |
+
FMIN, FMAX = 20.0, 12_000.0
|
| 17 |
+
FPS = SAMPLE_RATE // HOP # 100
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def decode_audio(path_or_bytes: str | bytes, sr: int = SAMPLE_RATE) -> np.ndarray:
|
| 21 |
+
"""Decode to mono float32 with ffmpeg. ffmpeg applies gapless trimming of MP3 encoder delay
|
| 22 |
+
when a LAME/Xing header is present; any remaining offset is measured in Stage 0."""
|
| 23 |
+
src = "pipe:0" if isinstance(path_or_bytes, bytes) else path_or_bytes
|
| 24 |
+
out = subprocess.run(
|
| 25 |
+
["ffmpeg", "-v", "error", "-i", src, "-vn", "-ac", "1", "-ar", str(sr), "-f", "f32le", "pipe:1"],
|
| 26 |
+
input=path_or_bytes if isinstance(path_or_bytes, bytes) else None,
|
| 27 |
+
capture_output=True,
|
| 28 |
+
check=False,
|
| 29 |
+
)
|
| 30 |
+
if out.returncode != 0:
|
| 31 |
+
raise RuntimeError(out.stderr.decode(errors="replace")[:300])
|
| 32 |
+
return np.frombuffer(out.stdout, dtype=np.float32).copy()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _hz_to_mel(f):
|
| 36 |
+
# Slaney scale
|
| 37 |
+
f = np.asarray(f, dtype=np.float64)
|
| 38 |
+
lin = f / (200.0 / 3)
|
| 39 |
+
log = 15.0 + np.log(np.maximum(f, 1e-10) / 1000.0) / (np.log(6.4) / 27.0)
|
| 40 |
+
return np.where(f >= 1000.0, log, lin)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _mel_to_hz(m):
|
| 44 |
+
m = np.asarray(m, dtype=np.float64)
|
| 45 |
+
lin = m * (200.0 / 3)
|
| 46 |
+
log = 1000.0 * np.exp((np.log(6.4) / 27.0) * (m - 15.0))
|
| 47 |
+
return np.where(m >= 15.0, log, lin)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def mel_filterbank(sr=SAMPLE_RATE, n_fft=N_FFT, n_mels=N_MELS, fmin=FMIN, fmax=FMAX) -> np.ndarray:
|
| 51 |
+
freqs = np.linspace(0, sr / 2, n_fft // 2 + 1)
|
| 52 |
+
pts = _mel_to_hz(np.linspace(_hz_to_mel(fmin), _hz_to_mel(fmax), n_mels + 2))
|
| 53 |
+
fb = np.zeros((n_mels, len(freqs)), dtype=np.float32)
|
| 54 |
+
for i in range(n_mels):
|
| 55 |
+
lo, c, hi = pts[i], pts[i + 1], pts[i + 2]
|
| 56 |
+
up = (freqs - lo) / (c - lo)
|
| 57 |
+
down = (hi - freqs) / (hi - c)
|
| 58 |
+
fb[i] = np.maximum(0, np.minimum(up, down)) * (2.0 / (hi - lo))
|
| 59 |
+
return fb
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def log_mel(audio: np.ndarray, device: str = "cpu") -> np.ndarray:
|
| 63 |
+
"""Return log-Mel [frames, N_MELS] float16, frame k centered at k * 10 ms."""
|
| 64 |
+
import torch
|
| 65 |
+
|
| 66 |
+
x = torch.from_numpy(audio).to(device)
|
| 67 |
+
win = torch.hann_window(N_FFT, device=device)
|
| 68 |
+
spec = torch.stft(x, N_FFT, HOP, window=win, center=True, return_complex=True).abs() ** 2
|
| 69 |
+
fb = torch.from_numpy(mel_filterbank()).to(device)
|
| 70 |
+
mel = torch.log(fb @ spec + 1e-6).T # [frames, mels]
|
| 71 |
+
return mel.to(torch.float16).cpu().numpy()
|
chartgen/gapstats.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Note-gap statistics of a chart: which inter-onset intervals it uses, and how consecutive gaps relate.
|
| 2 |
+
|
| 3 |
+
gap histogram -- gaps between consecutive hit notes in beats, binned to the usual note values
|
| 4 |
+
(1/8, 1/6, 1/4, 1/3, 1/2, 2/3, 3/4, 1), other gaps under one beat, and rests (> 1 beat)
|
| 5 |
+
ratio histogram -- next gap / this gap for consecutive gaps both within one beat: equal, x2, /2, x3, /3,
|
| 6 |
+
x1.5, /1.5, other. It describes the shape of the rhythm (long-short-short ...)
|
| 7 |
+
independently of the note value.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
|
| 14 |
+
GAPS = np.array([1 / 8, 1 / 6, 1 / 4, 1 / 3, 1 / 2, 2 / 3, 3 / 4, 1.0])
|
| 15 |
+
GAP_NAMES = ["1/8", "1/6", "1/4", "1/3", "1/2", "2/3", "3/4", "1", "other<1", "rest"]
|
| 16 |
+
RATIOS = np.array([1.0, 2.0, 0.5, 3.0, 1 / 3, 1.5, 2 / 3])
|
| 17 |
+
RATIO_NAMES = ["1:1", "x2", "/2", "x3", "/3", "x1.5", "/1.5", "other"]
|
| 18 |
+
N_GAP_BINS, N_RATIO_BINS = len(GAP_NAMES), len(RATIO_NAMES)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def gap_bins(gaps_beats: np.ndarray) -> np.ndarray:
|
| 22 |
+
"""Bin index per gap (in beats)."""
|
| 23 |
+
g = np.asarray(gaps_beats, float)
|
| 24 |
+
rel = np.abs(g[:, None] - GAPS[None]) / GAPS[None]
|
| 25 |
+
k = rel.argmin(1)
|
| 26 |
+
out = np.where(rel[np.arange(len(g)), k] < 0.08, k, N_GAP_BINS - 2)
|
| 27 |
+
return np.where(g > 1.05, N_GAP_BINS - 1, out)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def ratio_bins(gaps_beats: np.ndarray) -> np.ndarray:
|
| 31 |
+
"""Bin index per consecutive gap pair, -1 where either gap is a rest."""
|
| 32 |
+
g = np.asarray(gaps_beats, float)
|
| 33 |
+
if len(g) < 2:
|
| 34 |
+
return np.zeros(0, np.int64)
|
| 35 |
+
a, b = g[:-1], g[1:]
|
| 36 |
+
ok = (a <= 1.05) & (b <= 1.05) & (a > 0) & (b > 0)
|
| 37 |
+
r = np.log(np.where(ok, b, 1.0) / np.where(ok, a, 1.0))
|
| 38 |
+
d = np.abs(r[:, None] - np.log(RATIOS)[None])
|
| 39 |
+
k = d.argmin(1)
|
| 40 |
+
out = np.where(d[np.arange(len(r)), k] < 0.08, k, N_RATIO_BINS - 1)
|
| 41 |
+
return np.where(ok, out, -1)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def hists(t_ms: np.ndarray, beat_ms: float) -> tuple[np.ndarray, np.ndarray]:
|
| 45 |
+
"""(gap histogram, ratio histogram) as counts, from hit-note times in ms."""
|
| 46 |
+
t = np.sort(np.asarray(t_ms, float))
|
| 47 |
+
g = np.diff(t) / beat_ms
|
| 48 |
+
hg = np.bincount(gap_bins(g), minlength=N_GAP_BINS).astype(float) if len(g) else np.zeros(N_GAP_BINS)
|
| 49 |
+
rb = ratio_bins(g)
|
| 50 |
+
rb = rb[rb >= 0]
|
| 51 |
+
hr = np.bincount(rb, minlength=N_RATIO_BINS).astype(float) if len(rb) else np.zeros(N_RATIO_BINS)
|
| 52 |
+
return hg, hr
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def tv(a: np.ndarray, b: np.ndarray) -> float:
|
| 56 |
+
"""Total-variation distance between two count histograms (0 when either is empty)."""
|
| 57 |
+
sa, sb = a.sum(), b.sum()
|
| 58 |
+
if sa == 0 or sb == 0:
|
| 59 |
+
return 0.0
|
| 60 |
+
return float(0.5 * np.abs(a / sa - b / sb).sum())
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# Finer binning for evaluation: 1/16 and 1/12 get their own bins (generated charts use 1/16 doubles where
|
| 64 |
+
# mappers use 1/6 runs, and the 10-bin version above merged both into "other"). The 10-bin version stays
|
| 65 |
+
# the model's plan format.
|
| 66 |
+
GAPS_FINE = np.array([1 / 16, 1 / 12, 1 / 8, 1 / 6, 1 / 4, 1 / 3, 1 / 2, 2 / 3, 3 / 4, 1.0])
|
| 67 |
+
GAP_NAMES_FINE = ["1/16", "1/12", "1/8", "1/6", "1/4", "1/3", "1/2", "2/3", "3/4", "1", "other<1", "rest"]
|
| 68 |
+
N_GAP_BINS_FINE = len(GAP_NAMES_FINE)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def gap_bins_fine(gaps_beats: np.ndarray) -> np.ndarray:
|
| 72 |
+
g = np.asarray(gaps_beats, float)
|
| 73 |
+
if len(g) == 0:
|
| 74 |
+
return np.zeros(0, np.int64)
|
| 75 |
+
rel = np.abs(g[:, None] - GAPS_FINE[None]) / GAPS_FINE[None]
|
| 76 |
+
k = rel.argmin(1)
|
| 77 |
+
out = np.where(rel[np.arange(len(g)), k] < 0.08, k, N_GAP_BINS_FINE - 2)
|
| 78 |
+
return np.where(g > 1.05, N_GAP_BINS_FINE - 1, out)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def beat_positions(t_ms: np.ndarray, sections: np.ndarray) -> np.ndarray:
|
| 82 |
+
"""Exact beat coordinate of each time from the chart's timing sections (columns: time, beat length,
|
| 83 |
+
meter, beat index at the section start, ...); follows tempo changes."""
|
| 84 |
+
t = np.asarray(t_ms, float)
|
| 85 |
+
idx = np.clip(np.searchsorted(sections[:, 0], t + 1, side="right") - 1, 0, len(sections) - 1)
|
| 86 |
+
s = sections[idx]
|
| 87 |
+
return s[:, 3] + (t - s[:, 0]) / s[:, 1]
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def bar_hists(t_ms: np.ndarray, sections: np.ndarray):
|
| 91 |
+
"""{measure index: (fine gap histogram, ratio histogram)} for hit-note times; a gap (and a ratio) belongs
|
| 92 |
+
to the measure of its later note. Real measures of the timing sections, as in dataset.bar_plan."""
|
| 93 |
+
from .dataset import measure_at
|
| 94 |
+
b = np.sort(beat_positions(t_ms, sections))
|
| 95 |
+
if len(b) < 2:
|
| 96 |
+
return {}
|
| 97 |
+
g = np.diff(b)
|
| 98 |
+
gb = gap_bins_fine(g)
|
| 99 |
+
rb = ratio_bins(g)
|
| 100 |
+
bar_g = measure_at(sections, np.round(b[1:] * 48) / 48) # snapped to the 1/48 grid, like dataset.bar_plan
|
| 101 |
+
bar_r = bar_g[1:]
|
| 102 |
+
out = {}
|
| 103 |
+
for k in np.unique(bar_g):
|
| 104 |
+
hg = np.bincount(gb[bar_g == k], minlength=N_GAP_BINS_FINE).astype(float)
|
| 105 |
+
r = rb[bar_r == k]
|
| 106 |
+
r = r[r >= 0]
|
| 107 |
+
hr = np.bincount(r, minlength=N_RATIO_BINS).astype(float) if len(r) else np.zeros(N_RATIO_BINS)
|
| 108 |
+
out[int(k)] = (hg, hr)
|
| 109 |
+
return out
|
chartgen/gen_mapset.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Whole-mapset generation: every difficulty of a song, from the song-level planner and the bar-planned generator,
|
| 2 |
+
written as .osz files for play-testing (and as a pickle for the distribution evaluation).
|
| 3 |
+
|
| 4 |
+
For each beatmap set:
|
| 5 |
+
* timing: the red lines of the set's human chart with the most notes (oracle timing: this tests the charts, not
|
| 6 |
+
beat tracking);
|
| 7 |
+
* plan: the song planner on the whole song for each tier, decided like song_planner --predict (P(play) > 0.5; roll
|
| 8 |
+
start and sustain by the calibrated thresholds in thresholds.json) and with rolls as objects (plan_decide);
|
| 9 |
+
* notes: the generator over consecutive 20 s windows with the song-level plan, the rest mask and --plan-continue
|
| 10 |
+
(no END before the plan's last measure with hit notes); N candidates per window, the one that agrees most with the
|
| 11 |
+
others (MBR on onset F1) is kept;
|
| 12 |
+
* kiai from the generator's kiai head.
|
| 13 |
+
The .osz holds the audio, the generated difficulties ("AI ..."), and the set's human difficulties for comparison.
|
| 14 |
+
|
| 15 |
+
python -m chartgen.gen_mapset --data f*.pkl --audio-dir /content/audio --model b9.pt --encoder best_v1.pt \
|
| 16 |
+
--planner sp9/best.pt --thresholds sp9/thresholds.json --sets 123 456 --out osz/ --label "v9.1"
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import argparse
|
| 22 |
+
import io
|
| 23 |
+
import json
|
| 24 |
+
import os
|
| 25 |
+
import pickle
|
| 26 |
+
import zipfile
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
from . import song_planner as sp
|
| 33 |
+
from .dataset import BAR_F, GRID, MAX_BARS, SUSTAIN, WINDOW, _beats_at, load_songs, make_example, measure_at, plan_active
|
| 34 |
+
from .generate import generate, match_count
|
| 35 |
+
from .infer import TIER_NAMES, GeneratedChart, _dummy_chart, decode_kiai, frame_activations, load_model, to_osu
|
| 36 |
+
from .plan_decide import count_then_place, roll_objects
|
| 37 |
+
|
| 38 |
+
CANDS = (("greedy", 0.0, 1.0), ("t0.7", 0.7, 1.0), ("t0.9", 0.9, 1.0), ("t0.9b", 0.9, 1.0)) # N = 4
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def planner_rows(enc, mel, sections, device):
|
| 42 |
+
"""Planner input rows of the whole song (same features as training) and the first measure index."""
|
| 43 |
+
mem = sp.song_memory(enc, mel, device)
|
| 44 |
+
ons = sp.onset_bands(mel)
|
| 45 |
+
lm = np.asarray(mel, np.float32).mean(1)
|
| 46 |
+
ons = np.concatenate([ons, ((lm - lm.mean()) / (lm.std() + 1e-6))[:, None]], 1)
|
| 47 |
+
dummy = {"sections": sections, "beat": np.zeros(0), "type": np.zeros(0, np.int8), "length_beats": np.zeros(0, np.float32)}
|
| 48 |
+
feat, _, b0 = sp.chart_rows(mem, dummy, ons, True)
|
| 49 |
+
return feat, b0
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def song_property_amounts(o, tier=None, cutoffs=None, use=None, rng=None):
|
| 53 |
+
"""Triplet and 1/8 measure shares from the planner's own outputs (expected share over its hit measures).
|
| 54 |
+
Stage 0a: these amounts are song properties (independent mapsets agree as much as mappers of one set), and the
|
| 55 |
+
planner's expectation tracks them far better than the prior's music regression (validation: triplet corr 0.76 vs
|
| 56 |
+
0.37; 1/8 0.24 vs 0.10), so they are taken from the music, not drawn."""
|
| 57 |
+
sig = lambda v: 1 / (1 + np.exp(-v)) # noqa: E731
|
| 58 |
+
hit = sig(o[:, 0]) > 0.5
|
| 59 |
+
if not hit.any():
|
| 60 |
+
return 0.0, 0.0
|
| 61 |
+
trip, eighth = float(np.clip(sig(o[hit, 4]) / 0.47, 0, 1).mean()), float(np.clip(sig(o[hit, 5]) / 0.5, 0, 1).mean())
|
| 62 |
+
if use is not None and tier is not None and rng is not None:
|
| 63 |
+
# v10d: whether the chart uses them at all is drawn from P(use | expected share) (per-tier logistic fit on
|
| 64 |
+
# pre-2022 validation charts, reports/figs/song_prop_use.py): a fixed cutoff makes every draw of a song agree,
|
| 65 |
+
# far more sure than the data allow (1/8 use is barely predictable from the music in the hard tiers)
|
| 66 |
+
u = use[str(tier)]
|
| 67 |
+
for nm in ("triplet", "eighth"):
|
| 68 |
+
a, b = u[nm]
|
| 69 |
+
e = trip if nm == "triplet" else eighth
|
| 70 |
+
p_use = 1 / (1 + np.exp(-(a + b * np.log(e + 1e-3))))
|
| 71 |
+
if rng.random() >= p_use:
|
| 72 |
+
if nm == "triplet":
|
| 73 |
+
trip = 0.0
|
| 74 |
+
else:
|
| 75 |
+
eighth = 0.0
|
| 76 |
+
return trip, eighth
|
| 77 |
+
if cutoffs is not None and tier is not None:
|
| 78 |
+
# humans either use triplets / 1/8 notes clearly or not at all; an expectation is never exactly 0, so below a
|
| 79 |
+
# per-tier cutoff (set so the share of charts that use them matches the human share; calibrated on pre-2022
|
| 80 |
+
# validation songs, not the modern evaluation songs) the amount is 0
|
| 81 |
+
c = cutoffs[str(tier)] if str(tier) in cutoffs else cutoffs[tier]
|
| 82 |
+
trip = trip if trip >= c["triplet"] else 0.0
|
| 83 |
+
eighth = eighth if eighth >= c["eighth"] else 0.0
|
| 84 |
+
return trip, eighth
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def planner_out(planner, feat, tier, device):
|
| 88 |
+
X = torch.from_numpy(feat.astype(np.float32))[None].to(device)
|
| 89 |
+
M = torch.ones(1, len(feat), dtype=torch.bool, device=device)
|
| 90 |
+
with torch.no_grad():
|
| 91 |
+
return planner(X, torch.tensor([tier], device=device), M)[0].cpu().numpy()
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def song_plan(planner, enc, mel, sections, tier, th_roll, th_sus, device):
|
| 95 |
+
"""(first measure index, [n, BAR_F] decided plan) for the whole song at this tier (v9.1 decoding)."""
|
| 96 |
+
mem = sp.song_memory(enc, mel, device)
|
| 97 |
+
ons = sp.onset_bands(mel)
|
| 98 |
+
lm = np.asarray(mel, np.float32).mean(1)
|
| 99 |
+
ons = np.concatenate([ons, ((lm - lm.mean()) / (lm.std() + 1e-6))[:, None]], 1)
|
| 100 |
+
dummy = {"sections": sections, "beat": np.zeros(0), "type": np.zeros(0, np.int8), "length_beats": np.zeros(0, np.float32)}
|
| 101 |
+
feat, _, b0 = sp.chart_rows(mem, dummy, ons, True)
|
| 102 |
+
X = torch.from_numpy(feat.astype(np.float32))[None].to(device)
|
| 103 |
+
M = torch.ones(1, len(feat), dtype=torch.bool, device=device)
|
| 104 |
+
with torch.no_grad():
|
| 105 |
+
pl = sp.SongPlanner.to_plan(planner(X, torch.tensor([tier], device=device), M))[0].cpu().numpy()
|
| 106 |
+
pl[:, 3] = (pl[:, 3] >= th_roll).astype(np.float32)
|
| 107 |
+
pl[:, SUSTAIN] = np.where(pl[:, SUSTAIN] >= th_sus, np.maximum(pl[:, SUSTAIN], 0.11), 0.0)
|
| 108 |
+
return b0, roll_objects(pl)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def window_plan(plan, b_song, sections, start_f):
|
| 112 |
+
bar0 = int(measure_at(sections, _beats_at(sections, np.array([start_f * 10.0])))[0])
|
| 113 |
+
w = np.zeros((MAX_BARS, BAR_F), np.float32)
|
| 114 |
+
k0 = bar0 - b_song
|
| 115 |
+
seg = plan[max(k0, 0): max(k0, 0) + MAX_BARS - max(-k0, 0)]
|
| 116 |
+
w[max(-k0, 0): max(-k0, 0) + len(seg)] = seg
|
| 117 |
+
covered = np.zeros(MAX_BARS, bool)
|
| 118 |
+
covered[max(-k0, 0): max(-k0, 0) + len(seg)] = True
|
| 119 |
+
return w, covered, bar0
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def masks(ex, sections, w, covered, bar0):
|
| 123 |
+
gb = (ex.start_grid + np.arange(len(ex.grid_time))) / GRID
|
| 124 |
+
bi = measure_at(sections, gb) - bar0
|
| 125 |
+
inside = (bi >= 0) & (bi < MAX_BARS)
|
| 126 |
+
al = np.ones(len(gb), bool)
|
| 127 |
+
act = plan_active(w) | ~covered
|
| 128 |
+
al[inside] = act[bi[inside]]
|
| 129 |
+
hitm = np.where((w[:, 0] > 0.5) & covered)[0]
|
| 130 |
+
pos = np.where(inside & np.isin(bi, hitm))[0] if len(hitm) else np.zeros(0, np.int64)
|
| 131 |
+
cont = int(pos[bi[pos] == bi[pos].max()].min()) if len(pos) else 0
|
| 132 |
+
return al, cont
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def mbr_pick(preds):
|
| 136 |
+
"""Index of the candidate with the highest mean onset F1 to the others (ties: higher logp)."""
|
| 137 |
+
hits = [p["time"][p["type"] <= 3] for p in preds]
|
| 138 |
+
n = len(preds)
|
| 139 |
+
score = np.zeros(n)
|
| 140 |
+
for i in range(n):
|
| 141 |
+
for j in range(n):
|
| 142 |
+
if i != j:
|
| 143 |
+
score[i] += 2 * match_count(hits[i], hits[j], 25.0) / max(len(hits[i]) + len(hits[j]), 1)
|
| 144 |
+
lp = np.array([p["logp"] / max(p["n_events"], 1.0) for p in preds])
|
| 145 |
+
return int(np.lexsort((lp, score))[-1])
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def generate_tier(model, planner, enc, mel, sections, tier, t0, t1, th_roll, th_sus, device, seed, plan_override=None):
|
| 149 |
+
b_song, plan = plan_override if plan_override is not None else song_plan(planner, enc, mel, sections, tier, th_roll, th_sus, device)
|
| 150 |
+
chart = _dummy_chart(sections, tier)
|
| 151 |
+
song = {"mel": mel}
|
| 152 |
+
starts = list(range(int(max(t0, 0) // 10), int(t1 // 10), WINDOW))
|
| 153 |
+
times, types, lens, svs = [], [], [], []
|
| 154 |
+
for gi in range(0, len(starts), 24):
|
| 155 |
+
exs, bplans, allowed, conts, temps, scales, meta = [], [], [], [], [], [], []
|
| 156 |
+
for st in starts[gi:gi + 24]:
|
| 157 |
+
ex = make_example(song, chart, st)
|
| 158 |
+
w, cov, bar0 = window_plan(plan, b_song, sections, st)
|
| 159 |
+
al, cont = masks(ex, sections, w, cov, bar0)
|
| 160 |
+
for name, temp, sc in CANDS:
|
| 161 |
+
exs.append(ex); bplans.append(w); allowed.append(al); conts.append(cont); temps.append(temp); scales.append(sc)
|
| 162 |
+
meta.append(ex)
|
| 163 |
+
torch.manual_seed(seed + gi)
|
| 164 |
+
preds = generate(model, exs, device, temperature=temps, rho_scale=scales, plan_source="pred",
|
| 165 |
+
bar_plan=np.stack(bplans), allowed=allowed, continue_until=conts)
|
| 166 |
+
for k, ex in enumerate(meta):
|
| 167 |
+
group = preds[k * len(CANDS):(k + 1) * len(CANDS)]
|
| 168 |
+
p = group[mbr_pick(group)]
|
| 169 |
+
t = p["time"] + ex.start_ms
|
| 170 |
+
keep = (t < ex.start_ms + WINDOW * 10.0) & (t <= t1 + 2000)
|
| 171 |
+
times.append(t[keep]); types.append(p["type"][keep]); lens.append(p["length"][keep]); svs.append(p["sv"][keep])
|
| 172 |
+
time = np.concatenate(times) if times else np.zeros(0)
|
| 173 |
+
order = np.argsort(time, kind="stable")
|
| 174 |
+
time = time[order]
|
| 175 |
+
keep = np.r_[True, np.diff(time) > 1.0] if len(time) else np.zeros(0, bool)
|
| 176 |
+
_, _, kiai_p = frame_activations(model, mel, device, sections, tier)
|
| 177 |
+
first, last = (time[0], time[-1]) if len(time) else (t0, t1)
|
| 178 |
+
kiai = decode_kiai(kiai_p, sections, first, last)
|
| 179 |
+
return GeneratedChart(sections=sections, kiai=kiai, time=time[keep],
|
| 180 |
+
type=np.concatenate(types)[order][keep] if types else np.zeros(0, int),
|
| 181 |
+
length_beats=np.concatenate(lens)[order][keep] if lens else np.zeros(0),
|
| 182 |
+
sv=np.concatenate(svs)[order][keep] if svs else np.zeros(0), tier=tier), (b_song, plan)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def human_chart(c, sections):
|
| 186 |
+
return GeneratedChart(sections=c["sections"], kiai=[tuple(x) for x in np.asarray(c.get("kiai", np.zeros((0, 2))))],
|
| 187 |
+
time=np.asarray(c["time"], float), type=np.asarray(c["type"]),
|
| 188 |
+
length_beats=np.asarray(c["length_beats"], float), sv=np.asarray(c.get("sv", np.ones(len(c["time"])))),
|
| 189 |
+
tier=int(c["tier"]))
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def make_draw(model, planner, enc, mel, sections, t0, t1, tiers, cal, device, seed, prior=None, protos=None, sure_rest=0.05,
|
| 193 |
+
feat=None, b_song=None, rest_band=None, cutoffs=None, coordinate=False, use=None, sample_place=False):
|
| 194 |
+
"""One draw of the whole set: {tier: chart dict}, settings per tier (v10a) and the mapset offset.
|
| 195 |
+
coordinate (v10c): tiers are decided from the hardest down, each guided by the next harder tier's plan.
|
| 196 |
+
use, sample_place (v10d): triplet / 1/8 use drawn from P(use | expected share); places sampled, not ranked."""
|
| 197 |
+
overrides, settings, bvec = {}, {}, None
|
| 198 |
+
if prior is not None:
|
| 199 |
+
rng = np.random.default_rng(seed)
|
| 200 |
+
draw, bvec = prior.sample_set({t: feat for t in tiers}, rng)
|
| 201 |
+
guide = None
|
| 202 |
+
for t in (sorted(tiers, reverse=True) if coordinate else tiers):
|
| 203 |
+
o_t = planner_out(planner, feat, t, device)
|
| 204 |
+
d = np.array(draw[t], float)
|
| 205 |
+
d[2], d[3] = song_property_amounts(o_t, t, cutoffs, use, rng) # song properties from the music
|
| 206 |
+
plan_t, log = count_then_place(o_t, d, t, protos, cal["th_sustain"], sure_rest=sure_rest, rest_band=rest_band,
|
| 207 |
+
guide=guide, rng=rng if sample_place else None)
|
| 208 |
+
if coordinate:
|
| 209 |
+
guide = plan_t
|
| 210 |
+
overrides[t] = (b_song, plan_t)
|
| 211 |
+
settings[t] = (d, log)
|
| 212 |
+
charts = {}
|
| 213 |
+
for tier in tiers:
|
| 214 |
+
g, plan = generate_tier(model, planner, enc, mel, sections, tier, t0, t1, cal["th_roll"], cal["th_sustain"], device,
|
| 215 |
+
seed + 1000 * tier, plan_override=overrides.get(tier))
|
| 216 |
+
charts[tier] = {"tier": tier, "sections": sections, "time": g.time, "type": g.type, "length_beats": g.length_beats,
|
| 217 |
+
"sv": g.sv, "kiai": g.kiai}
|
| 218 |
+
return charts, settings, bvec
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def main(argv=None):
|
| 222 |
+
p = argparse.ArgumentParser()
|
| 223 |
+
p.add_argument("--data", nargs="+", type=Path, required=True)
|
| 224 |
+
p.add_argument("--audio-dir", type=Path, help="audio/taiko/<shard>.tar (downloaded on demand; needed for .osz)")
|
| 225 |
+
p.add_argument("--model", type=Path, required=True, help="bar-planned generator (b9)")
|
| 226 |
+
p.add_argument("--encoder", type=Path, required=True, help="B0 checkpoint for the planner's music memory")
|
| 227 |
+
p.add_argument("--planner", type=Path, required=True)
|
| 228 |
+
p.add_argument("--thresholds", type=Path, required=True, help="song_planner thresholds.json (calibration)")
|
| 229 |
+
p.add_argument("--sets", nargs="*", type=int, default=[])
|
| 230 |
+
p.add_argument("--sets-file", type=Path, help="file with set ids (whitespace separated)")
|
| 231 |
+
p.add_argument("--catalog", type=Path, default=Path("data/catalog/taiko_beatmaps.parquet"))
|
| 232 |
+
p.add_argument("--tiers", nargs="+", type=int, default=[0, 1, 2, 3, 4])
|
| 233 |
+
p.add_argument("--label", default="AI")
|
| 234 |
+
p.add_argument("--seed", type=int, default=0)
|
| 235 |
+
p.add_argument("--draws", type=int, default=1, help="independent draws of every set (distribution evaluation: 4)")
|
| 236 |
+
p.add_argument("--no-osz", action="store_true", help="only the pickle (no audio, no .osz)")
|
| 237 |
+
p.add_argument("--no-human", action="store_true", help="do not add the human difficulties to the .osz")
|
| 238 |
+
p.add_argument("--prior", type=Path, help="v10a: chart_prior.ChartPrior pickle; amounts drawn per set, count-then-place")
|
| 239 |
+
p.add_argument("--protos", type=Path, help="v10a: plan_decide.prototypes pickle")
|
| 240 |
+
p.add_argument("--sure-rest", type=float, default=0.05)
|
| 241 |
+
p.add_argument("--rest-band", type=float, nargs=2, help="v10b: calibrated P(rest) band (lo hi): sure rests follow the music")
|
| 242 |
+
p.add_argument("--song-cutoffs", type=Path, help="v10b: per-tier cutoffs for triplet / 1/8 amounts (json)")
|
| 243 |
+
p.add_argument("--coordinate", action="store_true", help="v10c: each tier's rests and rolls guided by the next harder tier")
|
| 244 |
+
p.add_argument("--song-use", type=Path, help="v10d: P(use) of triplets / 1/8 per tier (json, reports/figs/song_prop_use.py)")
|
| 245 |
+
p.add_argument("--sample-place", action="store_true", help="v10d: sample places from the calibrated probabilities")
|
| 246 |
+
p.add_argument("--save-every", type=int, default=10, help="sets between pickle saves (resume after a reclaim)")
|
| 247 |
+
p.add_argument("--out", type=Path, required=True)
|
| 248 |
+
a = p.parse_args(argv)
|
| 249 |
+
import pyarrow.parquet as pq
|
| 250 |
+
from .prep import read_shard
|
| 251 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 252 |
+
model = load_model(a.model, device)
|
| 253 |
+
enc = load_model(a.encoder, device).eval()
|
| 254 |
+
cal = json.loads(a.thresholds.read_text())["calibration"]
|
| 255 |
+
ck = torch.load(a.planner, map_location=device)
|
| 256 |
+
planner = sp.SongPlanner(ck["d_in"]).to(device).eval()
|
| 257 |
+
planner.load_state_dict(ck["model"])
|
| 258 |
+
prior = pickle.load(open(a.prior, "rb")) if a.prior else None
|
| 259 |
+
protos = pickle.load(open(a.protos, "rb")) if a.protos else None
|
| 260 |
+
cutoffs = json.loads(a.song_cutoffs.read_text()) if a.song_cutoffs else None
|
| 261 |
+
use = json.loads(a.song_use.read_text()) if a.song_use else None
|
| 262 |
+
# artist / title only name the .osz; without the catalog the set id is used
|
| 263 |
+
cat = {r["beatmapset_id"]: r for r in pq.read_table(a.catalog, columns=["beatmapset_id", "artist", "title"]).to_pylist()} \
|
| 264 |
+
if a.catalog.exists() else {}
|
| 265 |
+
a.out.mkdir(parents=True, exist_ok=True)
|
| 266 |
+
out_pkl = a.out / f"mapsets_{a.label.replace(' ', '_')}.pkl"
|
| 267 |
+
record = pickle.load(open(out_pkl, "rb")) if out_pkl.exists() else {} # resume
|
| 268 |
+
want = set(a.sets) | (set(int(x) for x in a.sets_file.read_text().split()) if a.sets_file else set())
|
| 269 |
+
want -= set(record)
|
| 270 |
+
print(f"sets to do {len(want)} (done {len(record)})", flush=True)
|
| 271 |
+
n_new = 0
|
| 272 |
+
for f in a.data:
|
| 273 |
+
if not want:
|
| 274 |
+
break
|
| 275 |
+
songs = [s for s in load_songs([f], mmap=True) if s["beatmapset_id"] in want]
|
| 276 |
+
if not songs:
|
| 277 |
+
continue
|
| 278 |
+
audio = {}
|
| 279 |
+
if not a.no_osz:
|
| 280 |
+
tar = a.audio_dir / f"{f.stem}.tar"
|
| 281 |
+
if not tar.exists():
|
| 282 |
+
from huggingface_hub import hf_hub_download
|
| 283 |
+
tok = open("/content/.hf_env").read().strip() if Path("/content/.hf_env").exists() else None
|
| 284 |
+
got = hf_hub_download("JacobLinCool/taiko-chart-audio", f"audio/taiko/{f.stem}.tar", repo_type="dataset",
|
| 285 |
+
local_dir=str(a.audio_dir / "hf"), token=tok)
|
| 286 |
+
os.replace(got, tar)
|
| 287 |
+
audio = read_shard(tar)
|
| 288 |
+
for s in songs:
|
| 289 |
+
sid = s["beatmapset_id"]
|
| 290 |
+
mel = np.asarray(s["mel"], np.float32)
|
| 291 |
+
ref = max(s["charts"], key=lambda c: len(c["time"]))
|
| 292 |
+
sections = np.asarray(ref["sections"], np.float64)
|
| 293 |
+
t0 = min(float(c["time"][0]) for c in s["charts"]) - 2000.0
|
| 294 |
+
t1 = max(float(c["time"][-1]) for c in s["charts"])
|
| 295 |
+
feat, b_song = planner_rows(enc, mel, sections, device) if prior is not None else (None, None)
|
| 296 |
+
rec = {"song_key": s.get("song_key"), "sections": sections, "draws": []}
|
| 297 |
+
for k in range(a.draws):
|
| 298 |
+
charts, settings, bvec = make_draw(model, planner, enc, mel, sections, t0, t1, a.tiers, cal, device,
|
| 299 |
+
a.seed + int(sid) + 7919 * k, prior, protos, a.sure_rest, feat, b_song,
|
| 300 |
+
tuple(a.rest_band) if a.rest_band else None, cutoffs, a.coordinate, use,
|
| 301 |
+
a.sample_place)
|
| 302 |
+
rec["draws"].append({"charts": charts, "settings": settings, "b": bvec})
|
| 303 |
+
print(f"{sid} draw {k}: " + ", ".join(f"{TIER_NAMES[t]} {len(c['time'])} notes/{int((c['type'] >= 4).sum())} rolls"
|
| 304 |
+
for t, c in charts.items()), flush=True)
|
| 305 |
+
record[sid] = rec
|
| 306 |
+
n_new += 1
|
| 307 |
+
if not a.no_osz:
|
| 308 |
+
ameta, files = audio.get(int(sid), ({}, {}))
|
| 309 |
+
if s.get("audio_member") not in files:
|
| 310 |
+
print(sid, "no audio: no .osz", flush=True)
|
| 311 |
+
else:
|
| 312 |
+
artist, title = cat.get(sid, {}).get("artist", "Unknown"), cat.get(sid, {}).get("title", str(sid))
|
| 313 |
+
aname = (ameta.get("audio") or [{}])[0].get("name") or f"audio.{s['audio_member'].split('.')[-1]}"
|
| 314 |
+
zbuf = io.BytesIO()
|
| 315 |
+
with zipfile.ZipFile(zbuf, "w", zipfile.ZIP_DEFLATED) as z:
|
| 316 |
+
z.writestr(aname, files[s["audio_member"]])
|
| 317 |
+
for tier, c in rec["draws"][0]["charts"].items():
|
| 318 |
+
g = GeneratedChart(sections=sections, kiai=c["kiai"], time=c["time"], type=c["type"],
|
| 319 |
+
length_beats=c["length_beats"], sv=c["sv"], tier=tier)
|
| 320 |
+
osu = to_osu(g, aname, title, artist).replace(f"Version:{TIER_NAMES[tier]}", f"Version:{a.label} {TIER_NAMES[tier]}")
|
| 321 |
+
osu = osu.replace("Creator:chartgen", f"Creator:chartgen {a.label}")
|
| 322 |
+
z.writestr(f"{artist} - {title} (chartgen) [{a.label} {TIER_NAMES[tier]}].osu".replace("/", "_"), osu)
|
| 323 |
+
if not a.no_human:
|
| 324 |
+
for c in s["charts"]:
|
| 325 |
+
h = human_chart(c, sections)
|
| 326 |
+
osu = to_osu(h, aname, title, artist).replace(f"Version:{TIER_NAMES[h.tier]}", f"Version:Human {TIER_NAMES[h.tier]} #{c['beatmap_id']}")
|
| 327 |
+
z.writestr(f"{artist} - {title} (chartgen) [Human {TIER_NAMES[h.tier]} {c['beatmap_id']}].osu".replace("/", "_"), osu)
|
| 328 |
+
name = f"{sid} {artist} - {title} ({a.label}).osz".replace("/", "_")
|
| 329 |
+
(a.out / name).write_bytes(zbuf.getvalue())
|
| 330 |
+
print(f"{sid} -> {name}", flush=True)
|
| 331 |
+
if n_new % a.save_every == 0:
|
| 332 |
+
pickle.dump(record, open(out_pkl, "wb"))
|
| 333 |
+
if audio:
|
| 334 |
+
del audio
|
| 335 |
+
(a.audio_dir / f"{f.stem}.tar").unlink(missing_ok=True)
|
| 336 |
+
want -= set(record)
|
| 337 |
+
pickle.dump(record, open(out_pkl, "wb"))
|
| 338 |
+
print("done", len(record), flush=True)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
if __name__ == "__main__":
|
| 342 |
+
main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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Batched autoregressive generation and event-level evaluation."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from .model import DecodeCache
|
| 9 |
+
from .dataset import AHEAD_END, GRID, MAX_EVENTS, Example, collate, sv_value
|
| 10 |
+
|
| 11 |
+
DON_LIKE, KA_LIKE = {0, 2}, {1, 3}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@torch.no_grad()
|
| 15 |
+
def generate(model, examples: list[Example], device, temperature: float | list[float] = 0.0, plan_source: str = "pred",
|
| 16 |
+
max_events: int = MAX_EVENTS, allowed: list[np.ndarray] | None = None,
|
| 17 |
+
required: list[np.ndarray] | None = None, forced_type: list[dict] | None = None,
|
| 18 |
+
rho_scale: float | list[float] = 1.0, use_cache: bool = True, type_temperature: float | None = None,
|
| 19 |
+
bar_plan: np.ndarray | None = None, type_bias: np.ndarray | None = None,
|
| 20 |
+
continue_until: list[int] | None = None, min_gap_ms: float | list[float] | None = None,
|
| 21 |
+
phase_ok: list[np.ndarray | None] | None = None) -> list[dict]:
|
| 22 |
+
"""Autoregressive generation for a batch of windows.
|
| 23 |
+
|
| 24 |
+
Optional constraints (per example, positions are offsets into the example's grid table):
|
| 25 |
+
allowed -- bool mask; notes may only be placed where it is True (derive an easier chart)
|
| 26 |
+
required -- sorted offsets that must all be placed (derive a harder chart)
|
| 27 |
+
forced_type -- {offset: type} for notes whose type is kept from a source chart
|
| 28 |
+
rho_scale -- multiplies the planned note density (continuous difficulty control)
|
| 29 |
+
continue_until -- grid offset per example before which the window may not end (the plan still has measures with
|
| 30 |
+
hit notes after it); without it a model can stop early, e.g. after a balloon, because many charts
|
| 31 |
+
end with one
|
| 32 |
+
min_gap_ms -- shortest allowed time (ms) from the previous event of the window to the next one (stage 4b:
|
| 33 |
+
the tier's human floor); positions closer than this are masked, and a beat with no position
|
| 34 |
+
left is masked as a choice of 'beats ahead'. None or 0 = no limit
|
| 35 |
+
phase_ok -- per example a bool mask over the GRID positions of a beat (stage 5a: with the 1/8 family switched
|
| 36 |
+
off, only the 1/12-beat positions stay open); events are placed on open positions only, and a
|
| 37 |
+
beat with no open position left is masked as a choice of 'beats ahead'. None = all open
|
| 38 |
+
temperature and rho_scale may also be per-example lists (several candidate kinds in one batch).
|
| 39 |
+
bar_plan -- [B, MAX_BARS, BAR_F] per-bar plan for a bar-planned model (e.g. from a song-level planner);
|
| 40 |
+
plan_source oracle_bar uses the human chart's bar plan instead
|
| 41 |
+
type_bias -- added to the note-type logits; -log(training class weights) undoes the class-weighted type
|
| 42 |
+
loss (train.type_weights), which otherwise inflates rare types such as rolls and big notes
|
| 43 |
+
type_temperature -- cap on the temperature of the note-type choice (0 = most likely type); rare types
|
| 44 |
+
(rolls, big notes) are over-sampled when types share the position temperature
|
| 45 |
+
plan_source -- pred (planner argmax), sample (subdivision class sampled from the planner), oracle_r (human
|
| 46 |
+
subdivision class, predicted density), oracle_gap (human gap distributions), oracle (human plan);
|
| 47 |
+
the oracle modes need examples built from the human chart
|
| 48 |
+
"""
|
| 49 |
+
model.eval()
|
| 50 |
+
batch = {k: v.to(device) for k, v in collate(examples).items()}
|
| 51 |
+
hi, mem = model.encode(batch["mel"])
|
| 52 |
+
mem = model.with_grid(mem, batch["beat_feat"])
|
| 53 |
+
rho, r_logits, sec_mask, gap_logits, ratio_logits = model.plan_full(mem, batch["frame_section"], batch["tier"])
|
| 54 |
+
gap_pred = model.gap_probs(gap_logits, ratio_logits) if gap_logits is not None else None
|
| 55 |
+
B = len(examples)
|
| 56 |
+
if not isinstance(rho_scale, (int, float)):
|
| 57 |
+
rho_scale = torch.as_tensor(rho_scale, dtype=torch.float32, device=device).view(B, *([1] * (rho.dim() - 1)))
|
| 58 |
+
rho_p = rho.expm1().clamp(min=0) * rho_scale
|
| 59 |
+
if plan_source == "pred":
|
| 60 |
+
plan_emb = model.plan_embedding(rho_p, r_logits.argmax(-1), gap_pred)
|
| 61 |
+
elif plan_source == "sample": # subdivision class drawn from the planner per example (candidate), not its argmax
|
| 62 |
+
r = torch.distributions.Categorical(logits=r_logits.float()).sample()
|
| 63 |
+
plan_emb = model.plan_embedding(rho_p, r, gap_pred)
|
| 64 |
+
elif plan_source == "oracle_r": # the human chart's subdivision class, predicted density
|
| 65 |
+
plan_emb = model.plan_embedding(rho_p, batch["plan_r"], gap_pred)
|
| 66 |
+
elif plan_source == "oracle_gap": # the human chart's gap / ratio distributions, the rest predicted
|
| 67 |
+
plan_emb = model.plan_embedding(rho_p, r_logits.argmax(-1), batch["plan_gap"])
|
| 68 |
+
else:
|
| 69 |
+
plan_emb = model.plan_embedding(batch["plan_rho"] * rho_scale, batch["plan_r"], batch["plan_gap"])
|
| 70 |
+
mem = model.with_rep_hint(mem, batch.get("rep_hint"), batch["frame_bar"])
|
| 71 |
+
if plan_source == "oracle_bar":
|
| 72 |
+
plan_emb = model.plan_embedding(rho_p, r_logits.argmax(-1), gap_pred)
|
| 73 |
+
mem = model.with_bar_plan(mem, batch["bar_plan"], batch["frame_bar"])
|
| 74 |
+
elif bar_plan is not None:
|
| 75 |
+
mem = model.with_bar_plan(mem, torch.as_tensor(bar_plan, device=device), batch["frame_bar"])
|
| 76 |
+
elif getattr(model.c, "bar_plan", False):
|
| 77 |
+
mem = model.with_bar_plan(mem, batch["bar_plan"], batch["frame_bar"],
|
| 78 |
+
torch.zeros(B, dtype=torch.bool, device=device)) # no plan given
|
| 79 |
+
# window-level predicted gap / ratio distribution (sections weighted by predicted density), for selection energies
|
| 80 |
+
win_gap = None
|
| 81 |
+
if gap_pred is not None:
|
| 82 |
+
wsec = rho_p * sec_mask.float()
|
| 83 |
+
win_gap = ((gap_pred * wsec.unsqueeze(-1)).sum(1) / wsec.sum(1, keepdim=True).clamp(min=1e-6)).cpu().numpy()
|
| 84 |
+
temp = torch.as_tensor(temperature, dtype=torch.float32, device=device).expand(B)
|
| 85 |
+
tables = [(torch.as_tensor(e.grid_time, device=device), torch.as_tensor(e.grid_bar, device=device),
|
| 86 |
+
torch.as_tensor(e.grid_section, device=device), e.start_grid) for e in examples]
|
| 87 |
+
keys = ["ev_ahead", "ev_type", "ev_len", "ev_sv", "ev_phase", "ev_bar", "ev_frame", "ev_section"]
|
| 88 |
+
seq = {k: torch.zeros(B, 0, dtype=torch.long, device=device) for k in keys}
|
| 89 |
+
delta = torch.zeros(B, 0, device=device)
|
| 90 |
+
start_grid = torch.tensor([tb[3] for tb in tables], device=device)
|
| 91 |
+
cur = start_grid.clone() # absolute grid index of the last event
|
| 92 |
+
done = torch.zeros(B, dtype=torch.bool, device=device)
|
| 93 |
+
logp = torch.zeros(B, device=device) # log-probability of the decoded sequence (for L1 reranking)
|
| 94 |
+
n_ev = torch.zeros(B, device=device)
|
| 95 |
+
G = torch.tensor([len(t[0]) for t in tables], device=device)
|
| 96 |
+
phases = torch.arange(GRID, device=device)
|
| 97 |
+
alive_steps: list[torch.Tensor] = []
|
| 98 |
+
offs_steps: list[torch.Tensor] = []
|
| 99 |
+
|
| 100 |
+
Gmax = int(G.max())
|
| 101 |
+
allow_cum = None
|
| 102 |
+
if allowed is not None:
|
| 103 |
+
am = torch.zeros(B, Gmax + GRID * (AHEAD_END + 2), dtype=torch.long, device=device)
|
| 104 |
+
for b, a in enumerate(allowed):
|
| 105 |
+
am[b, : len(a)] = torch.as_tensor(a, device=device).long()
|
| 106 |
+
allow_cum = torch.cat([torch.zeros(B, 1, dtype=torch.long, device=device), am.cumsum(1)], 1)
|
| 107 |
+
# first forbidden grid offset at or after each offset (for capping roll bodies before planned rests)
|
| 108 |
+
next_bad = []
|
| 109 |
+
for a in allowed:
|
| 110 |
+
a = np.asarray(a, bool)
|
| 111 |
+
bad = np.where(~a)[0]
|
| 112 |
+
j = np.searchsorted(bad, np.arange(len(a) + 1))
|
| 113 |
+
next_bad.append(np.where(j < len(bad), bad[np.minimum(j, max(len(bad) - 1, 0))] if len(bad) else len(a), len(a)))
|
| 114 |
+
req = None
|
| 115 |
+
if required is not None:
|
| 116 |
+
req = [torch.as_tensor(np.sort(r), device=device).long() for r in required]
|
| 117 |
+
aheads = torch.arange(AHEAD_END, device=device)
|
| 118 |
+
mg = None
|
| 119 |
+
if min_gap_ms is not None:
|
| 120 |
+
mg = torch.as_tensor(min_gap_ms, dtype=torch.float32, device=device).expand(B).clone()
|
| 121 |
+
if not bool((mg > 0).any()):
|
| 122 |
+
mg = None
|
| 123 |
+
if mg is not None:
|
| 124 |
+
# grid times per example, padded with +inf (searchsorted gives the first offset at or after a time)
|
| 125 |
+
tab = torch.full((B, Gmax), float("inf"), device=device)
|
| 126 |
+
for b, tb in enumerate(tables):
|
| 127 |
+
tab[b, : len(tb[0])] = tb[0].float()
|
| 128 |
+
prev_t = torch.full((B,), float("-inf"), device=device)
|
| 129 |
+
|
| 130 |
+
pk = None
|
| 131 |
+
if phase_ok is not None:
|
| 132 |
+
pk = torch.as_tensor(np.stack([np.ones(GRID, bool) if q is None else np.asarray(q, bool) for q in phase_ok]),
|
| 133 |
+
device=device) # [B, GRID]
|
| 134 |
+
if bool(pk.all()):
|
| 135 |
+
pk = None
|
| 136 |
+
|
| 137 |
+
def pick(logits, tt=None):
|
| 138 |
+
tt = temp if tt is None else tt
|
| 139 |
+
greedy = logits.argmax(-1)
|
| 140 |
+
if not bool((tt > 0).any()):
|
| 141 |
+
return greedy
|
| 142 |
+
sampled = torch.multinomial(torch.softmax(logits / tt.clamp(min=1e-3)[:, None], -1), 1)[:, 0]
|
| 143 |
+
return torch.where(tt > 0, sampled, greedy)
|
| 144 |
+
type_temp = temp if type_temperature is None else temp.clamp(max=type_temperature)
|
| 145 |
+
|
| 146 |
+
cache = DecodeCache(model, mem) if use_cache else None
|
| 147 |
+
for _ in range(max_events):
|
| 148 |
+
if cache is not None:
|
| 149 |
+
n_ev_seen = seq["ev_ahead"].shape[1]
|
| 150 |
+
# token of the newest event only (BOS at the first step); positions match event_tokens()
|
| 151 |
+
tok = model.event_tokens(mem, plan_emb, batch["tier"], {k: v[:, -1:] for k, v in seq.items()}) if n_ev_seen else None
|
| 152 |
+
if tok is None:
|
| 153 |
+
x = model.bos.expand(B, -1, -1) + model.tier_emb(batch["tier"])[:, None] + model.dec_pos[:, :1]
|
| 154 |
+
else:
|
| 155 |
+
x = tok[:, 1:] - model.dec_pos[:, 1:2] + model.dec_pos[:, n_ev_seen:n_ev_seen + 1]
|
| 156 |
+
h = cache.step(x)
|
| 157 |
+
else:
|
| 158 |
+
tok = model.event_tokens(mem, plan_emb, batch["tier"], seq)
|
| 159 |
+
h = model.decode(tok, mem, None)[:, -1:]
|
| 160 |
+
ahead_logits = model.ahead_head(h)[:, 0].float()
|
| 161 |
+
# a note in the same beat must come after the current phase: if none is left, ahead 0 is impossible
|
| 162 |
+
no_room = (cur % GRID) >= GRID - 1
|
| 163 |
+
ahead_logits[:, 0] = torch.where(no_room, torch.full_like(ahead_logits[:, 0], -1e9), ahead_logits[:, 0])
|
| 164 |
+
rel_beat0 = torch.div(cur, GRID, rounding_mode="floor") * GRID - start_grid # offset of current beat start
|
| 165 |
+
if allow_cum is not None:
|
| 166 |
+
lo = rel_beat0[:, None] + aheads[None] * GRID
|
| 167 |
+
lo = torch.where(aheads[None] == 0, (cur - start_grid)[:, None] + 1, lo).clamp(0, allow_cum.shape[1] - 1)
|
| 168 |
+
up = (rel_beat0[:, None] + (aheads[None] + 1) * GRID).clamp(0, allow_cum.shape[1] - 1)
|
| 169 |
+
cnt = allow_cum.gather(1, up) - allow_cum.gather(1, lo)
|
| 170 |
+
ahead_logits[:, :AHEAD_END] = ahead_logits[:, :AHEAD_END].masked_fill(cnt <= 0, -1e9)
|
| 171 |
+
min_t = None
|
| 172 |
+
if mg is not None:
|
| 173 |
+
# time-based (the grid-time table is not monotonic next to close red lines, verification report §3.2):
|
| 174 |
+
# a position is open when its time is at least min_gap after the previous event of the window
|
| 175 |
+
min_t = torch.where(torch.isfinite(prev_t), prev_t + mg, torch.full_like(prev_t, float("-inf")))
|
| 176 |
+
offs = rel_beat0[:, None] + torch.arange(AHEAD_END * GRID, device=device)[None] # [B, A * GRID]
|
| 177 |
+
t_off = tab.gather(1, offs.clamp(0, Gmax - 1))
|
| 178 |
+
t_off = torch.where(offs >= Gmax, torch.full_like(t_off, float("inf")), t_off)
|
| 179 |
+
open_ = (t_off >= min_t[:, None]) & (offs > (cur - start_grid)[:, None])
|
| 180 |
+
if allow_cum is not None:
|
| 181 |
+
c = offs.clamp(0, allow_cum.shape[1] - 2)
|
| 182 |
+
open_ &= (allow_cum.gather(1, c + 1) - allow_cum.gather(1, c)) > 0
|
| 183 |
+
if pk is not None:
|
| 184 |
+
open_ &= pk.repeat(1, AHEAD_END) # offs starts at a beat boundary, so its phase is offs % GRID
|
| 185 |
+
room = open_.view(B, AHEAD_END, GRID).any(-1)
|
| 186 |
+
ahead_logits[:, :AHEAD_END] = ahead_logits[:, :AHEAD_END].masked_fill(~room, -1e9)
|
| 187 |
+
elif pk is not None:
|
| 188 |
+
offs = rel_beat0[:, None] + torch.arange(AHEAD_END * GRID, device=device)[None] # [B, A * GRID]
|
| 189 |
+
open_ = (offs > (cur - start_grid)[:, None]) & pk.repeat(1, AHEAD_END)
|
| 190 |
+
if allow_cum is not None:
|
| 191 |
+
c = offs.clamp(0, allow_cum.shape[1] - 2)
|
| 192 |
+
open_ &= (allow_cum.gather(1, c + 1) - allow_cum.gather(1, c)) > 0
|
| 193 |
+
room = open_.view(B, AHEAD_END, GRID).any(-1)
|
| 194 |
+
ahead_logits[:, :AHEAD_END] = ahead_logits[:, :AHEAD_END].masked_fill(~room, -1e9)
|
| 195 |
+
nreq = None
|
| 196 |
+
if req is not None:
|
| 197 |
+
nreq = torch.full((B,), -1, dtype=torch.long, device=device)
|
| 198 |
+
for b in range(B):
|
| 199 |
+
later = req[b][req[b] > (cur[b] - start_grid[b])]
|
| 200 |
+
if len(later):
|
| 201 |
+
nreq[b] = later[0]
|
| 202 |
+
has = nreq >= 0
|
| 203 |
+
req_beat = torch.div(nreq + start_grid, GRID, rounding_mode="floor") - torch.div(cur, GRID, rounding_mode="floor")
|
| 204 |
+
too_far = has[:, None] & (aheads[None] > req_beat[:, None])
|
| 205 |
+
ahead_logits[:, :AHEAD_END] = ahead_logits[:, :AHEAD_END].masked_fill(too_far, -1e9)
|
| 206 |
+
ahead_logits[:, AHEAD_END] = torch.where(has, torch.full_like(ahead_logits[:, 0], -1e9), ahead_logits[:, AHEAD_END])
|
| 207 |
+
if continue_until is not None:
|
| 208 |
+
cu = torch.as_tensor(continue_until, device=device)
|
| 209 |
+
can_place = (ahead_logits[:, :AHEAD_END] > -1e8).any(1) # keep END when nothing else is possible
|
| 210 |
+
no_end = ((cur - start_grid) < cu) & can_place
|
| 211 |
+
ahead_logits[:, AHEAD_END] = torch.where(no_end, torch.full_like(ahead_logits[:, 0], -1e9), ahead_logits[:, AHEAD_END])
|
| 212 |
+
ahead = pick(ahead_logits)
|
| 213 |
+
live = ~done
|
| 214 |
+
logp += torch.where(live, torch.log_softmax(ahead_logits, -1).gather(1, ahead[:, None])[:, 0], torch.zeros_like(logp))
|
| 215 |
+
end = ahead == AHEAD_END
|
| 216 |
+
ah = ahead.clamp(max=AHEAD_END - 1)
|
| 217 |
+
ph_logits = model.phase_logits(h, ah[:, None])[:, 0].float()
|
| 218 |
+
same_beat = (ah == 0)[:, None]
|
| 219 |
+
invalid = same_beat & (phases[None, :] <= (cur % GRID)[:, None])
|
| 220 |
+
ph_logits = ph_logits.masked_fill(invalid, -1e9)
|
| 221 |
+
beat_off = rel_beat0 + ah * GRID # offset of the chosen beat's phase 0
|
| 222 |
+
if allow_cum is not None:
|
| 223 |
+
idx = (beat_off[:, None] + phases[None]).clamp(0, allow_cum.shape[1] - 2)
|
| 224 |
+
ok = (allow_cum.gather(1, idx + 1) - allow_cum.gather(1, idx)) > 0
|
| 225 |
+
ph_logits = ph_logits.masked_fill(~ok, -1e9)
|
| 226 |
+
if nreq is not None:
|
| 227 |
+
on_req_beat = (nreq >= 0) & (ah == req_beat.clamp(min=0))
|
| 228 |
+
beyond = on_req_beat[:, None] & ((beat_off[:, None] + phases[None]) > nreq[:, None])
|
| 229 |
+
ph_logits = ph_logits.masked_fill(beyond, -1e9)
|
| 230 |
+
if min_t is not None:
|
| 231 |
+
po = beat_off[:, None] + phases[None]
|
| 232 |
+
t_ph = tab.gather(1, po.clamp(0, Gmax - 1))
|
| 233 |
+
t_ph = torch.where(po >= Gmax, torch.full_like(t_ph, float("inf")), t_ph)
|
| 234 |
+
ph_logits = ph_logits.masked_fill(t_ph < min_t[:, None], -1e9)
|
| 235 |
+
if pk is not None:
|
| 236 |
+
ph_logits = ph_logits.masked_fill(~pk, -1e9)
|
| 237 |
+
phase = pick(ph_logits)
|
| 238 |
+
live_note = live & (ahead != AHEAD_END)
|
| 239 |
+
logp += torch.where(live_note, torch.log_softmax(ph_logits, -1).gather(1, phase[:, None])[:, 0], torch.zeros_like(logp))
|
| 240 |
+
nxt = (torch.div(cur, GRID, rounding_mode="floor") + ah) * GRID + phase
|
| 241 |
+
off = nxt - start_grid
|
| 242 |
+
done |= end | (off >= G - 1)
|
| 243 |
+
if done.all():
|
| 244 |
+
break
|
| 245 |
+
off = torch.where(done, torch.zeros_like(off), off)
|
| 246 |
+
t = torch.stack([tables[b][0][off[b]] for b in range(B)])
|
| 247 |
+
bar = torch.stack([tables[b][1][off[b]] for b in range(B)])
|
| 248 |
+
sec = torch.stack([tables[b][2][off[b]] for b in range(B)])
|
| 249 |
+
frame = (t / 10).round().long().clamp(0, hi.shape[1] - 1)
|
| 250 |
+
tl, ll, svl, dl = model.note_heads(h, hi, plan_emb, ah[:, None], phase[:, None], bar[:, None], frame[:, None], sec[:, None])
|
| 251 |
+
if type_bias is not None:
|
| 252 |
+
tl = tl + torch.as_tensor(type_bias, dtype=tl.dtype, device=tl.device)
|
| 253 |
+
ntype = pick(tl[:, 0].float(), type_temp)
|
| 254 |
+
keep_ev = ~done
|
| 255 |
+
if mg is not None:
|
| 256 |
+
prev_t = torch.where(keep_ev, t.float(), prev_t)
|
| 257 |
+
logp += torch.where(keep_ev, torch.log_softmax(tl[:, 0].float(), -1).gather(1, ntype[:, None])[:, 0], torch.zeros_like(logp))
|
| 258 |
+
n_ev += keep_ev.float()
|
| 259 |
+
if forced_type is not None:
|
| 260 |
+
for b in range(B):
|
| 261 |
+
ft = forced_type[b].get(int(off[b]))
|
| 262 |
+
if ft is not None:
|
| 263 |
+
ntype[b] = ft
|
| 264 |
+
# hit notes have no length; a roll / balloon takes its most likely non-zero length (the head is trained on rolls).
|
| 265 |
+
# With a rest mask the body must end before the next forbidden grid position: lengths are in quarter beats of the
|
| 266 |
+
# local tempo, so the limit is converted through the grid times (ms).
|
| 267 |
+
len_logits = ll[:, 0, 1:].float()
|
| 268 |
+
if allow_cum is not None and bool(((ntype >= 4) & ~done).any()):
|
| 269 |
+
for b in torch.where((ntype >= 4) & ~done)[0].tolist():
|
| 270 |
+
o = int(off[b]); gt = tables[b][0]
|
| 271 |
+
nb = int(next_bad[b][min(o + 1, len(next_bad[b]) - 1)])
|
| 272 |
+
if nb >= len(gt) or o + 1 >= len(gt):
|
| 273 |
+
continue
|
| 274 |
+
beat_ms = float(gt[o + 1] - gt[o]) * GRID
|
| 275 |
+
# tolerance of half a grid step (1/24 quarter beat): above the float32 error of the grid times, below the
|
| 276 |
+
# 1/12-quarter-beat grid resolution, so a whole number of quarter beats is not rounded down
|
| 277 |
+
q = int(np.floor(float(gt[nb] - gt[o]) / max(beat_ms, 1e-6) * 4 + 1.0 / 24))
|
| 278 |
+
if q < len_logits.shape[1]:
|
| 279 |
+
len_logits[b, max(q, 1):] = -1e9 # at least a quarter beat
|
| 280 |
+
nlen = torch.where(ntype >= 4, len_logits.argmax(-1) + 1, torch.zeros_like(ntype))
|
| 281 |
+
nsv = svl[:, 0].argmax(-1)
|
| 282 |
+
for k, v in zip(keys, [ah, ntype, nlen, nsv, phase, bar, frame, sec]):
|
| 283 |
+
seq[k] = torch.cat([seq[k], v[:, None]], 1)
|
| 284 |
+
delta = torch.cat([delta, dl[:, 0:1].float()], 1)
|
| 285 |
+
alive_steps.append(~done)
|
| 286 |
+
offs_steps.append(off)
|
| 287 |
+
cur = torch.where(done, cur, nxt)
|
| 288 |
+
|
| 289 |
+
alive = torch.stack(alive_steps, 1) if alive_steps else torch.zeros(B, 0, dtype=torch.bool, device=device)
|
| 290 |
+
offs_all = torch.stack(offs_steps, 1) if offs_steps else torch.zeros(B, 0, dtype=torch.long, device=device)
|
| 291 |
+
out = []
|
| 292 |
+
for b, e in enumerate(examples):
|
| 293 |
+
m = alive[b].cpu().numpy().astype(bool)
|
| 294 |
+
offs = offs_all[b].cpu().numpy()[m]
|
| 295 |
+
times = e.grid_time[np.minimum(offs, len(e.grid_time) - 1)] + delta[b].cpu().numpy()[m]
|
| 296 |
+
out.append({"time": times, "type": seq["ev_type"][b].cpu().numpy()[m],
|
| 297 |
+
"length": seq["ev_len"][b].cpu().numpy()[m] / 4.0, "frame": seq["ev_frame"][b].cpu().numpy()[m],
|
| 298 |
+
"sv": sv_value(seq["ev_sv"][b].cpu().numpy()[m]), "grid_offset": offs,
|
| 299 |
+
"logp": float(logp[b]), "n_events": float(n_ev[b]),
|
| 300 |
+
"gap_pred": None if win_gap is None else win_gap[b]})
|
| 301 |
+
return out
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def match_count(pred: np.ndarray, ref: np.ndarray, tol: float) -> int:
|
| 305 |
+
"""Maximum one-to-one matching of sorted 1-D onsets within +/- tol (two-pointer greedy is optimal)."""
|
| 306 |
+
i = j = n = 0
|
| 307 |
+
pred, ref = np.sort(pred), np.sort(ref)
|
| 308 |
+
while i < len(pred) and j < len(ref):
|
| 309 |
+
d = pred[i] - ref[j]
|
| 310 |
+
if abs(d) <= tol:
|
| 311 |
+
n += 1
|
| 312 |
+
i += 1
|
| 313 |
+
j += 1
|
| 314 |
+
elif d < 0:
|
| 315 |
+
i += 1
|
| 316 |
+
else:
|
| 317 |
+
j += 1
|
| 318 |
+
return n
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def evaluate_generation(preds: list[dict], examples: list[Example], tols=(10, 25, 50)) -> dict[str, float]:
|
| 322 |
+
res = {}
|
| 323 |
+
tot_p = sum(len(p["time"]) for p in preds)
|
| 324 |
+
tot_r = sum(len(e.ref_time) for e in examples)
|
| 325 |
+
for tol in tols:
|
| 326 |
+
tp = sum(match_count(p["time"], e.ref_time, tol) for p, e in zip(preds, examples))
|
| 327 |
+
prec, rec = tp / max(tot_p, 1), tp / max(tot_r, 1)
|
| 328 |
+
res[f"f1@{tol}"] = 2 * prec * rec / max(prec + rec, 1e-9)
|
| 329 |
+
res[f"p@{tol}"], res[f"r@{tol}"] = prec, rec
|
| 330 |
+
# colour-aware F1 at 25 ms: Don-like and Ka-like matched separately
|
| 331 |
+
tp = 0
|
| 332 |
+
for p, e in zip(preds, examples):
|
| 333 |
+
for group in (DON_LIKE, KA_LIKE):
|
| 334 |
+
pm = np.isin(p["type"], list(group))
|
| 335 |
+
rm = np.isin(e.ev_type, list(group))
|
| 336 |
+
tp += match_count(p["time"][pm], e.ref_time[rm], 25)
|
| 337 |
+
prec, rec = tp / max(tot_p, 1), tp / max(tot_r, 1)
|
| 338 |
+
res["color_f1@25"] = 2 * prec * rec / max(prec + rec, 1e-9)
|
| 339 |
+
res["density_ratio"] = tot_p / max(tot_r, 1)
|
| 340 |
+
# scroll speed (reading load): share of notes off SV 1 and SV changes per minute, generated vs reference
|
| 341 |
+
def sv_stats(svs, seconds):
|
| 342 |
+
allv = np.concatenate(svs) if svs else np.zeros(0)
|
| 343 |
+
changes = sum(int(np.sum(np.abs(np.diff(np.log2(v))) > 1e-3)) for v in svs if len(v) > 1)
|
| 344 |
+
return float(np.mean(np.abs(np.log2(allv)) > 1e-3)) if len(allv) else 0.0, changes / max(seconds / 60, 1e-6)
|
| 345 |
+
secs = sum(float(e.grid_time[-1]) / 1000 for e in examples)
|
| 346 |
+
res["sv_off1_gen"], res["sv_changes_per_min_gen"] = sv_stats([p["sv"] for p in preds], secs)
|
| 347 |
+
res["sv_off1_ref"], res["sv_changes_per_min_ref"] = sv_stats([sv_value(e.ev_sv) for e in examples], secs)
|
| 348 |
+
return res
|
chartgen/infer.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Whole-song inference: audio -> timing map -> notes + SV + kiai -> .osu file."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
from .dataset import WINDOW, make_example
|
| 13 |
+
from .features import decode_audio, log_mel
|
| 14 |
+
from .generate import generate
|
| 15 |
+
from .model import B0, B0Config
|
| 16 |
+
from .timing import beat_times, decode_timing
|
| 17 |
+
|
| 18 |
+
TIER_NAMES = ["Kantan", "Futsuu", "Muzukashii", "Oni", "Inner Oni"]
|
| 19 |
+
TIER_OD = [4.0, 5.0, 5.5, 6.0, 6.5]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class GeneratedChart:
|
| 24 |
+
sections: np.ndarray # [n, 5] time, beat_length, meter, start_beat, omit_barline
|
| 25 |
+
kiai: list[tuple[float, float]]
|
| 26 |
+
time: np.ndarray # ms
|
| 27 |
+
type: np.ndarray
|
| 28 |
+
length_beats: np.ndarray
|
| 29 |
+
sv: np.ndarray
|
| 30 |
+
tier: int
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def load_model(path: str | Path, device) -> B0:
|
| 34 |
+
ck = torch.load(path, map_location=device, weights_only=False)
|
| 35 |
+
cfg = B0Config(**ck["config"])
|
| 36 |
+
model = B0(cfg).to(device)
|
| 37 |
+
model.load_state_dict(ck["model"])
|
| 38 |
+
model.eval()
|
| 39 |
+
return model
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _windows(n_frames: int, hop: int):
|
| 43 |
+
starts = list(range(0, max(1, n_frames - WINDOW // 2), hop))
|
| 44 |
+
return starts
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _dummy_chart(sections: np.ndarray, tier: int) -> dict:
|
| 48 |
+
"""A chart with timing only (one far-away note) so make_example can build grid inputs."""
|
| 49 |
+
far = 1e9
|
| 50 |
+
return {"tier": tier, "sections": sections, "time": np.array([far]), "beat": np.array([1e7]),
|
| 51 |
+
"type": np.zeros(1, np.int8), "length_beats": np.zeros(1, np.float32),
|
| 52 |
+
"delta_ms": np.zeros(1, np.float32), "sv": np.ones(1, np.float32), "kiai": np.zeros((0, 2))}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@torch.no_grad()
|
| 56 |
+
def frame_activations(model: B0, mel: np.ndarray, device, sections: np.ndarray | None = None, tier: int = 3):
|
| 57 |
+
"""Average sigmoid outputs over 50%-overlapping windows. Returns beat, downbeat, kiai (kiai needs sections)."""
|
| 58 |
+
n = len(mel)
|
| 59 |
+
acc = np.zeros((n, 3))
|
| 60 |
+
cnt = np.zeros(n)
|
| 61 |
+
song = {"mel": mel}
|
| 62 |
+
chart = _dummy_chart(sections if sections is not None else np.array([[0.0, 500.0, 4, 0, 0]]), tier)
|
| 63 |
+
starts = _windows(n, WINDOW // 2)
|
| 64 |
+
for i in range(0, len(starts), 16):
|
| 65 |
+
exs = [make_example(song, chart, s) for s in starts[i:i + 16]]
|
| 66 |
+
mel_b = torch.from_numpy(np.stack([e.mel for e in exs])).to(device)
|
| 67 |
+
bf = torch.from_numpy(np.stack([e.beat_feat for e in exs])).to(device)
|
| 68 |
+
hi, mem = model.encode(mel_b)
|
| 69 |
+
tl = torch.sigmoid(model.timing_logits(hi, mem).float()).cpu().numpy()
|
| 70 |
+
kl = torch.sigmoid(model.kiai_logits(hi, model.with_grid(mem, bf)).float()).cpu().numpy()
|
| 71 |
+
for e, s, t, k in zip(exs, starts[i:i + 16], tl, kl):
|
| 72 |
+
m = min(WINDOW, n - s)
|
| 73 |
+
acc[s:s + m, :2] += t[:m]
|
| 74 |
+
acc[s:s + m, 2] += k[:m]
|
| 75 |
+
cnt[s:s + m] += 1
|
| 76 |
+
acc /= np.maximum(cnt, 1)[:, None]
|
| 77 |
+
return acc[:, 0], acc[:, 1], acc[:, 2]
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def music_span(mel: np.ndarray) -> tuple[float, float]:
|
| 81 |
+
energy = mel.astype(np.float32).mean(1)
|
| 82 |
+
loud = np.where(energy > np.percentile(energy, 20))[0]
|
| 83 |
+
return (loud[0] * 10.0, loud[-1] * 10.0) if len(loud) else (0.0, len(mel) * 10.0)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def predict_timing(model: B0, mel: np.ndarray, device, t0: float | None = None, t1: float | None = None) -> np.ndarray:
|
| 87 |
+
beat_p, down_p, _ = frame_activations(model, mel, device)
|
| 88 |
+
if t0 is None or t1 is None:
|
| 89 |
+
t0, t1 = music_span(mel)
|
| 90 |
+
return decode_timing(beat_p, down_p, t0, t1)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def decode_kiai(kiai_p: np.ndarray, sections: np.ndarray, t0: float, t1: float, min_bars: int = 4, max_gap_bars: int = 2,
|
| 94 |
+
thr: float = 0.5):
|
| 95 |
+
"""Kiai intervals: a measure is on when its mean kiai probability is above thr (0.5 before stage 4b; stage 4b
|
| 96 |
+
calibrates thr per tier on tune songs), short gaps are filled, short runs dropped."""
|
| 97 |
+
_, downs = beat_times(sections, t0, t1)
|
| 98 |
+
downs = np.r_[downs, t1]
|
| 99 |
+
if len(downs) < 2:
|
| 100 |
+
return []
|
| 101 |
+
def bar_on(a, b):
|
| 102 |
+
seg = kiai_p[int(a / 10):max(int(a / 10) + 1, int(b / 10))]
|
| 103 |
+
return len(seg) > 0 and seg.mean() > thr
|
| 104 |
+
on = np.array([bar_on(a, b) for a, b in zip(downs[:-1], downs[1:])])
|
| 105 |
+
# fill short gaps, then drop short runs
|
| 106 |
+
runs = []
|
| 107 |
+
i = 0
|
| 108 |
+
while i < len(on):
|
| 109 |
+
if on[i]:
|
| 110 |
+
j = i
|
| 111 |
+
while j < len(on) and on[j]:
|
| 112 |
+
j += 1
|
| 113 |
+
runs.append([i, j])
|
| 114 |
+
i = j
|
| 115 |
+
else:
|
| 116 |
+
i += 1
|
| 117 |
+
merged = []
|
| 118 |
+
for r in runs:
|
| 119 |
+
if merged and r[0] - merged[-1][1] <= max_gap_bars:
|
| 120 |
+
merged[-1][1] = r[1]
|
| 121 |
+
else:
|
| 122 |
+
merged.append(r)
|
| 123 |
+
return [(float(downs[a]), float(downs[b])) for a, b in merged if b - a >= min_bars]
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
@torch.no_grad()
|
| 127 |
+
def generate_chart(model: B0, mel: np.ndarray, tier: int, device, sections: np.ndarray | None = None,
|
| 128 |
+
temperature: float = 0.0) -> GeneratedChart:
|
| 129 |
+
n_ms = len(mel) * 10.0
|
| 130 |
+
# timing span: where the music is (skip leading/trailing silence)
|
| 131 |
+
t0, t1 = music_span(mel)
|
| 132 |
+
if sections is None:
|
| 133 |
+
sections = predict_timing(model, mel, device, t0, t1)
|
| 134 |
+
_, _, kiai_p = frame_activations(model, mel, device, sections, tier)
|
| 135 |
+
chart = _dummy_chart(sections, tier)
|
| 136 |
+
song = {"mel": mel}
|
| 137 |
+
starts = list(range(int(t0 // 10), int(t1 // 10), WINDOW))
|
| 138 |
+
times, types, lens, svs = [], [], [], []
|
| 139 |
+
for i in range(0, len(starts), 32):
|
| 140 |
+
exs = [make_example(song, chart, s) for s in starts[i:i + 32]]
|
| 141 |
+
preds = generate(model, exs, device, temperature=temperature)
|
| 142 |
+
for e, p in zip(exs, preds):
|
| 143 |
+
t = p["time"] + e.start_ms
|
| 144 |
+
keep = t < e.start_ms + WINDOW * 10.0
|
| 145 |
+
times.append(t[keep]); types.append(p["type"][keep]); lens.append(p["length"][keep]); svs.append(p["sv"][keep])
|
| 146 |
+
time = np.concatenate(times) if times else np.zeros(0)
|
| 147 |
+
order = np.argsort(time)
|
| 148 |
+
time = time[order]
|
| 149 |
+
keep = np.r_[True, np.diff(time) > 1.0] # drop duplicates across window seams
|
| 150 |
+
first_note, last_note = (time[0], time[-1]) if len(time) else (t0, t1)
|
| 151 |
+
kiai = decode_kiai(kiai_p, sections, first_note, last_note)
|
| 152 |
+
return GeneratedChart(sections=sections, kiai=kiai, time=time[keep],
|
| 153 |
+
type=np.concatenate(types)[order][keep] if types else np.zeros(0, int),
|
| 154 |
+
length_beats=np.concatenate(lens)[order][keep] if lens else np.zeros(0),
|
| 155 |
+
sv=np.concatenate(svs)[order][keep] if svs else np.zeros(0), tier=tier)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def to_osu(c: GeneratedChart, audio_filename: str, title: str = "Unknown", artist: str = "Unknown",
|
| 159 |
+
slider_multiplier: float = 1.4) -> str:
|
| 160 |
+
"""Write a playable osu!taiko file (format v14)."""
|
| 161 |
+
secs = c.sections
|
| 162 |
+
|
| 163 |
+
def section_at(t):
|
| 164 |
+
i = max(int(np.searchsorted(secs[:, 0], t, side="right")) - 1, 0)
|
| 165 |
+
return secs[i]
|
| 166 |
+
|
| 167 |
+
def in_kiai(t):
|
| 168 |
+
return any(a <= t < b for a, b in c.kiai)
|
| 169 |
+
|
| 170 |
+
# timing points: red lines, then green lines where SV or kiai changes
|
| 171 |
+
events = [] # (time, is_red, beat_length or sv, meter, kiai, omit)
|
| 172 |
+
for s in secs:
|
| 173 |
+
events.append((float(s[0]), True, float(s[1]), int(s[2]), in_kiai(s[0]), bool(s[4])))
|
| 174 |
+
changes = sorted({t for a, b in c.kiai for t in (a, b)} | {float(t) for t in c.time})
|
| 175 |
+
cur_sv, cur_kiai = 1.0, False
|
| 176 |
+
red_times = set(float(s[0]) for s in secs)
|
| 177 |
+
for t in changes:
|
| 178 |
+
idx = np.searchsorted(c.time, t)
|
| 179 |
+
sv = float(c.sv[idx]) if idx < len(c.time) and abs(c.time[idx] - t) < 1e-6 else cur_sv
|
| 180 |
+
k = in_kiai(t)
|
| 181 |
+
last_red = max((rt for rt in red_times if rt <= t), default=None)
|
| 182 |
+
if last_red is not None and abs(last_red - t) < 1e-6:
|
| 183 |
+
cur_sv, cur_kiai = 1.0, k
|
| 184 |
+
if abs(sv - cur_sv) > 1e-3 or k != cur_kiai:
|
| 185 |
+
events.append((t, False, sv, int(section_at(t)[2]), k, False))
|
| 186 |
+
cur_sv, cur_kiai = sv, k
|
| 187 |
+
events.sort(key=lambda e: (e[0], not e[1]))
|
| 188 |
+
tp_lines = []
|
| 189 |
+
for t, red, v, m, k, omit in events:
|
| 190 |
+
eff = (1 if k else 0) | (8 if (red and omit) else 0)
|
| 191 |
+
if red:
|
| 192 |
+
tp_lines.append(f"{t:.3f},{v:.12g},{m},1,0,100,1,{eff}")
|
| 193 |
+
else:
|
| 194 |
+
tp_lines.append(f"{t:.3f},{-100.0 / v:.12g},{m},1,0,100,0,{eff}")
|
| 195 |
+
|
| 196 |
+
ho = []
|
| 197 |
+
for i, (t, ty, lb, sv) in enumerate(zip(c.time, c.type, c.length_beats, c.sv)):
|
| 198 |
+
ti = int(round(t))
|
| 199 |
+
if ty in (0, 1, 2, 3):
|
| 200 |
+
hs = (8 if ty in (1, 3) else 0) | (4 if ty in (2, 3) else 0)
|
| 201 |
+
ho.append(f"256,192,{ti},1,{hs},0:0:0:0:")
|
| 202 |
+
else:
|
| 203 |
+
bl = float(section_at(t)[1])
|
| 204 |
+
lb = max(lb, 0.25)
|
| 205 |
+
if i + 1 < len(c.time): # do not run into the next note
|
| 206 |
+
lb = min(lb, max(0.25, (c.time[i + 1] - t) / bl - 0.25))
|
| 207 |
+
if ty in (4, 5):
|
| 208 |
+
px = lb * slider_multiplier * 100.0 * sv
|
| 209 |
+
ho.append(f"256,192,{ti},2,{4 if ty == 5 else 0},L|{256 + int(px)}:192,1,{px:.4f}")
|
| 210 |
+
else:
|
| 211 |
+
ho.append(f"256,192,{ti},12,0,{int(round(t + lb * bl))},0:0:0:0:")
|
| 212 |
+
name = TIER_NAMES[c.tier]
|
| 213 |
+
return "\n".join([
|
| 214 |
+
"osu file format v14", "",
|
| 215 |
+
"[General]", f"AudioFilename: {audio_filename}", "AudioLeadIn: 0", "PreviewTime: -1", "Countdown: 0",
|
| 216 |
+
"SampleSet: Normal", "StackLeniency: 0.7", "Mode: 1", "LetterboxInBreaks: 0", "WidescreenStoryboard: 0", "",
|
| 217 |
+
"[Editor]", "BeatDivisor: 4", "",
|
| 218 |
+
"[Metadata]", f"Title:{title}", f"TitleUnicode:{title}", f"Artist:{artist}", f"ArtistUnicode:{artist}",
|
| 219 |
+
"Creator:chartgen", f"Version:{name}", "Source:", "Tags:generated", "BeatmapID:0", "BeatmapSetID:-1", "",
|
| 220 |
+
"[Difficulty]", "HPDrainRate:5", "CircleSize:5", f"OverallDifficulty:{TIER_OD[c.tier]}", "ApproachRate:5",
|
| 221 |
+
f"SliderMultiplier:{slider_multiplier}", "SliderTickRate:1", "",
|
| 222 |
+
"[Events]", "//Background and Video events", "",
|
| 223 |
+
"[TimingPoints]", *tp_lines, "",
|
| 224 |
+
"[HitObjects]", *ho, "",
|
| 225 |
+
])
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def main(argv=None):
|
| 229 |
+
p = argparse.ArgumentParser(description="Generate an osu!taiko chart from audio")
|
| 230 |
+
p.add_argument("audio", type=Path)
|
| 231 |
+
p.add_argument("--model", type=Path, required=True)
|
| 232 |
+
p.add_argument("--tier", type=int, default=3, help="0 Kantan .. 4 Inner Oni")
|
| 233 |
+
p.add_argument("--out", type=Path)
|
| 234 |
+
p.add_argument("--title", default=None)
|
| 235 |
+
p.add_argument("--artist", default="Unknown")
|
| 236 |
+
a = p.parse_args(argv)
|
| 237 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 238 |
+
model = load_model(a.model, device)
|
| 239 |
+
mel = log_mel(decode_audio(str(a.audio)), device=str(device))
|
| 240 |
+
c = generate_chart(model, mel, a.tier, device)
|
| 241 |
+
out = a.out or a.audio.with_suffix(f".{TIER_NAMES[a.tier].replace(' ', '')}.osu")
|
| 242 |
+
out.write_text(to_osu(c, a.audio.name, a.title or a.audio.stem, a.artist))
|
| 243 |
+
print(out, f"{len(c.time)} notes, {len(c.sections)} timing sections, {len(c.kiai)} kiai")
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
if __name__ == "__main__":
|
| 247 |
+
main()
|
chartgen/latent_align.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stage 0b of the latent design (reports/v10 設計:多層 latent.md): do two INDEPENDENT mapsets of the same song agree on
|
| 2 |
+
where to rest (and where to roll, use big notes or triplets) as much as two mappers of the same mapset do?
|
| 3 |
+
|
| 4 |
+
If they do, the agreement comes from the music (and the work belongs to the music-to-plan model). If they agree much
|
| 5 |
+
less, it comes from coordination inside a mapset (and a mapset-level layout latent is justified).
|
| 6 |
+
|
| 7 |
+
For every song with two or more mapsets (charts-only file from colab/charts_only.py, catalog for mapper ids):
|
| 8 |
+
* cross pairs: same tier, different mapsets, no shared mapper;
|
| 9 |
+
* within pairs: same tier, same mapset, different mappers (same songs, and all songs as a second line).
|
| 10 |
+
Cross pairs are aligned in time: the offset is the mode of note-time differences, refined by onset F1 at +-25 ms; a
|
| 11 |
+
pair is kept when the overlap is at least 60 s and at least 90% of B's hit notes fall within 20 ms of A's 1/48 grid.
|
| 12 |
+
Pairs with onset F1 >= 0.9 are flagged as possible copies and reported with and without.
|
| 13 |
+
Then, on A's real measures inside the overlap: A's labels from its own notes, B's from its notes moved into A's time.
|
| 14 |
+
A measure is active when it has a hit note or a roll / balloon covers at least 10% of it; inside = between A's first
|
| 15 |
+
and last active measure. Agreement: F1 of rest measures, of roll-covered measures, of big-note measures (more than
|
| 16 |
+
half big notes), of triplet measures (at least 30% of hits on the 1/3, 1/6, 1/12 grid of A).
|
| 17 |
+
|
| 18 |
+
python -m chartgen.latent_align --charts charts.pkl --out stage0b.json
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import argparse
|
| 24 |
+
import json
|
| 25 |
+
import pickle
|
| 26 |
+
from collections import defaultdict
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
|
| 31 |
+
from .dataset import GRID, _beats_at, measure_at, measure_span, roll_end_beats
|
| 32 |
+
|
| 33 |
+
KINDS = ("rest", "roll", "big", "triplet")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def onset_f1(a, b, tol=25.0):
|
| 37 |
+
if len(a) == 0 or len(b) == 0:
|
| 38 |
+
return 0.0
|
| 39 |
+
b = np.sort(b)
|
| 40 |
+
j = np.clip(np.searchsorted(b, a), 1, len(b) - 1)
|
| 41 |
+
hit = np.minimum(np.abs(a - b[j - 1]), np.abs(a - b[j])) <= tol
|
| 42 |
+
return 2 * hit.sum() / (len(a) + len(b))
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def best_offset(ta, tb, lim=3000.0):
|
| 46 |
+
"""Offset d (ms) so that tb + d lines up with ta: mode of pairwise differences, then refined twice by the median of
|
| 47 |
+
the matched notes' residuals (an onset F1 with a 25 ms window cannot tell offsets within 25 ms apart, and a few ms
|
| 48 |
+
already move notes to other grid positions). Returns (d, onset F1 at d)."""
|
| 49 |
+
d = (ta[:, None] - tb[None, :]).ravel()
|
| 50 |
+
d = d[np.abs(d) <= lim]
|
| 51 |
+
if len(d) == 0:
|
| 52 |
+
return 0.0, 0.0
|
| 53 |
+
h, e = np.histogram(d, bins=np.arange(-lim, lim + 2, 2.0))
|
| 54 |
+
off = float(e[np.argmax(h)] + 1.0)
|
| 55 |
+
sa = np.sort(ta)
|
| 56 |
+
for _ in range(2):
|
| 57 |
+
x = tb + off
|
| 58 |
+
j = np.clip(np.searchsorted(sa, x), 1, len(sa) - 1)
|
| 59 |
+
nn = np.where(np.abs(sa[j - 1] - x) < np.abs(sa[j] - x), sa[j - 1], sa[j])
|
| 60 |
+
res = nn - x
|
| 61 |
+
ok = np.abs(res) <= 25
|
| 62 |
+
if ok.sum() < 8:
|
| 63 |
+
break
|
| 64 |
+
off += float(np.median(res[ok]))
|
| 65 |
+
return off, float(onset_f1(ta, tb + off))
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def measure_labels(sec, t, ty, ln, lo_m, hi_m):
|
| 69 |
+
"""Per measure lo_m..hi_m-1 of the timing `sec`: active, roll-covered, big, triplet flags for notes (t ms, type,
|
| 70 |
+
length in beats of the section where the note starts; note beats computed from t in this timing)."""
|
| 71 |
+
n = hi_m - lo_m
|
| 72 |
+
b = _beats_at(sec, t)
|
| 73 |
+
hit = ty <= 3
|
| 74 |
+
m = measure_at(sec, np.round(b * GRID) / GRID) - lo_m
|
| 75 |
+
st, en = measure_span(sec, np.arange(lo_m, hi_m))
|
| 76 |
+
L = np.maximum(en - st, 1e-6)
|
| 77 |
+
has_hit = np.zeros(n, bool); big = np.zeros(n); nh = np.zeros(n); trip = np.zeros(n)
|
| 78 |
+
sub = np.round(b * GRID).astype(np.int64) % GRID
|
| 79 |
+
on_trip = (sub % 4 == 0) & (sub % 3 != 0) # on the 1/3, 1/6, 1/12 grid and not on a binary subdivision
|
| 80 |
+
for k in range(n):
|
| 81 |
+
mk = (m == k) & hit
|
| 82 |
+
if mk.any():
|
| 83 |
+
has_hit[k] = True; nh[k] = mk.sum(); big[k] = (ty[mk] >= 2).mean(); trip[k] = on_trip[mk].mean()
|
| 84 |
+
cover = np.zeros(n)
|
| 85 |
+
rb = b[ty >= 4]
|
| 86 |
+
if len(rb):
|
| 87 |
+
for x, e in zip(rb, roll_end_beats(sec, rb, np.asarray(ln, float)[ty >= 4])):
|
| 88 |
+
ov = np.minimum(en, e) - np.maximum(st, x)
|
| 89 |
+
cover += np.where(ov > 0, ov, 0) / L
|
| 90 |
+
cover[(st <= x) & (x < en)] = np.maximum(cover[(st <= x) & (x < en)], 0.11)
|
| 91 |
+
rolled = cover >= 0.1
|
| 92 |
+
active = has_hit | rolled
|
| 93 |
+
return {"active": active, "roll": rolled & ~has_hit, "big": has_hit & (big > 0.5), "triplet": has_hit & (trip >= 0.3)}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def f1(x, y):
|
| 97 |
+
tp = (x & y).sum()
|
| 98 |
+
return 2 * tp / max(x.sum() + y.sum(), 1), int(x.sum()), int(y.sum()), int(tp)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def compare(A, B, delta):
|
| 102 |
+
"""Agreement of chart B (times moved by delta into A's time) with chart A on A's measures inside the overlap."""
|
| 103 |
+
secA = A["sections"]
|
| 104 |
+
ta, tb = np.asarray(A["time"], float), np.asarray(B["time"], float) + delta
|
| 105 |
+
lo, hi = max(ta.min(), tb.min()), min(ta.max(), tb.max())
|
| 106 |
+
if hi - lo < 60000:
|
| 107 |
+
return None
|
| 108 |
+
ma = measure_at(secA, _beats_at(secA, np.array([lo, hi])))
|
| 109 |
+
lo_m, hi_m = int(ma[0]) + 1, int(ma[1]) # complete measures inside the overlap
|
| 110 |
+
if hi_m - lo_m < 16:
|
| 111 |
+
return None
|
| 112 |
+
selA = (ta >= lo - 1) & (ta <= hi + 1); selB = (tb >= lo - 1) & (tb <= hi + 1)
|
| 113 |
+
la = measure_labels(secA, ta[selA], np.asarray(A["type"])[selA], np.asarray(A["length_beats"])[selA], lo_m, hi_m)
|
| 114 |
+
lb = measure_labels(secA, tb[selB], np.asarray(B["type"])[selB], np.asarray(B["length_beats"])[selB], lo_m, hi_m)
|
| 115 |
+
act = np.where(la["active"])[0]
|
| 116 |
+
if len(act) < 8:
|
| 117 |
+
return None
|
| 118 |
+
ins = np.zeros(hi_m - lo_m, bool); ins[act.min(): act.max() + 1] = True
|
| 119 |
+
out = {"n_measures": int(ins.sum())}
|
| 120 |
+
out["rest"] = f1(~la["active"][ins], ~lb["active"][ins])
|
| 121 |
+
for k in ("roll", "big", "triplet"):
|
| 122 |
+
out[k] = f1(la[k][ins], lb[k][ins])
|
| 123 |
+
return out
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def grid_fit(A, tb):
|
| 127 |
+
"""Share of B's hit-note times within 20 ms of A's 1/48 grid."""
|
| 128 |
+
sec = A["sections"]
|
| 129 |
+
b = _beats_at(sec, tb)
|
| 130 |
+
snapped = np.round(b * GRID) / GRID
|
| 131 |
+
j = np.clip(np.searchsorted(sec[:, 3], snapped + 1e-9, side="right") - 1, 0, len(sec) - 1)
|
| 132 |
+
t_s = sec[j, 0] + (snapped - sec[j, 3]) * sec[j, 1]
|
| 133 |
+
return float((np.abs(t_s - tb) <= 20).mean()) if len(tb) else 0.0
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def main(argv=None):
|
| 137 |
+
p = argparse.ArgumentParser()
|
| 138 |
+
p.add_argument("--charts", type=Path, required=True)
|
| 139 |
+
p.add_argument("--catalog", type=Path, default=Path("data/catalog/taiko_beatmaps.parquet"))
|
| 140 |
+
p.add_argument("--out", type=Path, required=True)
|
| 141 |
+
p.add_argument("--n-boot", type=int, default=1000)
|
| 142 |
+
a = p.parse_args(argv)
|
| 143 |
+
import pyarrow.parquet as pq
|
| 144 |
+
from .train import song_split
|
| 145 |
+
cat = {r["beatmap_id"]: r for r in pq.read_table(a.catalog, columns=["beatmap_id", "mapper_user_id", "approved_date"]).to_pylist()}
|
| 146 |
+
mapper = {b: r["mapper_user_id"] for b, r in cat.items()}
|
| 147 |
+
year = lambda b: int((cat[b]["approved_date"] or "0")[:4] or 0) # noqa: E731
|
| 148 |
+
songs = pickle.load(open(a.charts, "rb"))
|
| 149 |
+
by_key = defaultdict(list)
|
| 150 |
+
for s in songs:
|
| 151 |
+
key = s.get("song_key") or str(s["beatmapset_id"])
|
| 152 |
+
if song_split(key) == "test":
|
| 153 |
+
continue
|
| 154 |
+
by_key[key].append(s)
|
| 155 |
+
rows = {"cross": [], "within_same_songs": [], "within_all": []}
|
| 156 |
+
n_cand = n_kept = n_copy = 0
|
| 157 |
+
for key, sets in by_key.items():
|
| 158 |
+
charts = [(s["beatmapset_id"], c) for s in sets for c in s["charts"] if len(c["time"]) >= 16 and mapper.get(c["beatmap_id"]) is not None]
|
| 159 |
+
multi = len({sid for sid, _ in charts}) >= 2
|
| 160 |
+
for i in range(len(charts)):
|
| 161 |
+
for j in range(len(charts)):
|
| 162 |
+
if i == j:
|
| 163 |
+
continue
|
| 164 |
+
(si, A), (sj, B) = charts[i], charts[j]
|
| 165 |
+
if int(A["tier"]) != int(B["tier"]) or mapper[A["beatmap_id"]] == mapper[B["beatmap_id"]]:
|
| 166 |
+
continue
|
| 167 |
+
hA, hB = np.asarray(A["type"]) <= 3, np.asarray(B["type"]) <= 3
|
| 168 |
+
ta, tb = np.asarray(A["time"], float)[hA], np.asarray(B["time"], float)[hB]
|
| 169 |
+
if si == sj:
|
| 170 |
+
r = compare(A, B, 0.0)
|
| 171 |
+
if r is not None:
|
| 172 |
+
r.update(song=key, copy=False, dy=abs(year(A["beatmap_id"]) - year(B["beatmap_id"])))
|
| 173 |
+
rows["within_all"].append(r)
|
| 174 |
+
if multi:
|
| 175 |
+
rows["within_same_songs"].append(r)
|
| 176 |
+
continue
|
| 177 |
+
n_cand += 1
|
| 178 |
+
d, fbest = best_offset(ta, tb)
|
| 179 |
+
if grid_fit(A, tb + d) < 0.9:
|
| 180 |
+
continue
|
| 181 |
+
r = compare(A, B, d)
|
| 182 |
+
if r is None:
|
| 183 |
+
continue
|
| 184 |
+
n_kept += 1
|
| 185 |
+
r.update(song=key, copy=fbest >= 0.9, offset=d, onset_f1=fbest, dy=abs(year(A["beatmap_id"]) - year(B["beatmap_id"])))
|
| 186 |
+
n_copy += r["copy"]
|
| 187 |
+
rows["cross"].append(r)
|
| 188 |
+
rng = np.random.default_rng(0)
|
| 189 |
+
|
| 190 |
+
def summary(rs):
|
| 191 |
+
if not rs:
|
| 192 |
+
return None
|
| 193 |
+
songs_ = sorted({r["song"] for r in rs}); idx = {s: [i for i, r in enumerate(rs) if r["song"] == s] for s in songs_}
|
| 194 |
+
def pooled(ii): # pooled F1 over measures of the chosen pairs
|
| 195 |
+
out = {}
|
| 196 |
+
for k in KINDS:
|
| 197 |
+
tp = sum(rs[i][k][3] for i in ii); nx = sum(rs[i][k][1] for i in ii); ny = sum(rs[i][k][2] for i in ii)
|
| 198 |
+
out[k] = 2 * tp / max(nx + ny, 1)
|
| 199 |
+
return out
|
| 200 |
+
est = pooled(range(len(rs)))
|
| 201 |
+
bs = [pooled([i for s in rng.choice(songs_, len(songs_)) for i in idx[s]]) for _ in range(a.n_boot)]
|
| 202 |
+
return {"n_pairs": len(rs), "n_songs": len(songs_), **{k: [est[k], *np.percentile([b[k] for b in bs], [2.5, 97.5]).tolist()] for k in KINDS}}
|
| 203 |
+
def paired(cross, within):
|
| 204 |
+
"""Songs with both kinds of pairs: pooled F1 of cross minus within, song bootstrap of the difference."""
|
| 205 |
+
both = sorted({r["song"] for r in cross} & {r["song"] for r in within})
|
| 206 |
+
if len(both) < 5:
|
| 207 |
+
return None
|
| 208 |
+
def pf(rs, ss):
|
| 209 |
+
ss = set(ss); rs = [r for r in rs if r["song"] in ss]
|
| 210 |
+
return {k: 2 * sum(r[k][3] for r in rs) / max(sum(r[k][1] + r[k][2] for r in rs), 1) for k in KINDS}
|
| 211 |
+
est_c, est_w = pf(cross, both), pf(within, both)
|
| 212 |
+
bs = []
|
| 213 |
+
for _ in range(a.n_boot):
|
| 214 |
+
pick = list(rng.choice(both, len(both)))
|
| 215 |
+
# duplicates count: expand the pair lists by the multiplicity of their song
|
| 216 |
+
mult = {s_: pick.count(s_) for s_ in set(pick)}
|
| 217 |
+
c = [r for r in cross if r["song"] in mult for _ in range(mult[r["song"]])]
|
| 218 |
+
w = [r for r in within if r["song"] in mult for _ in range(mult[r["song"]])]
|
| 219 |
+
fc, fw = pf(c, mult), pf(w, mult)
|
| 220 |
+
bs.append({k: fc[k] - fw[k] for k in KINDS})
|
| 221 |
+
return {"n_songs": len(both), **{k: {"cross": est_c[k], "within": est_w[k], "diff": [est_c[k] - est_w[k], *np.percentile([b[k] for b in bs], [2.5, 97.5]).tolist()]} for k in KINDS}}
|
| 222 |
+
cross_nc = [r for r in rows["cross"] if not r["copy"]]
|
| 223 |
+
res = {"paired_same_songs": paired(cross_nc, rows["within_same_songs"]),
|
| 224 |
+
"paired_same_songs_era2": paired([r for r in cross_nc if r["dy"] <= 2], rows["within_same_songs"]),
|
| 225 |
+
"candidates_cross": n_cand, "kept_cross": n_kept, "possible_copies": n_copy,
|
| 226 |
+
"cross": summary(rows["cross"]), "cross_no_copies": summary([r for r in rows["cross"] if not r["copy"]]),
|
| 227 |
+
"within_same_songs": summary(rows["within_same_songs"]), "within_all": summary(rows["within_all"])}
|
| 228 |
+
a.out.write_text(json.dumps(res, indent=1))
|
| 229 |
+
print(f"cross candidates {n_cand}, kept {n_kept}, possible copies {n_copy}")
|
| 230 |
+
for k in ("paired_same_songs", "paired_same_songs_era2"):
|
| 231 |
+
v = res[k]
|
| 232 |
+
if v:
|
| 233 |
+
print(f"{k} ({v['n_songs']} songs): " + " ".join(f"{q} cross {v[q]['cross']:.3f} within {v[q]['within']:.3f} diff {v[q]['diff'][0]:+.3f} [{v[q]['diff'][1]:+.3f},{v[q]['diff'][2]:+.3f}]" for q in KINDS))
|
| 234 |
+
for k in ("cross", "cross_no_copies", "within_same_songs", "within_all"):
|
| 235 |
+
v = res[k]
|
| 236 |
+
if v:
|
| 237 |
+
print(f"{k:18s} pairs {v['n_pairs']:5d} songs {v['n_songs']:4d} " + " ".join(f"{q} {v[q][0]:.3f} [{v[q][1]:.3f},{v[q][2]:.3f}]" for q in KINDS))
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
if __name__ == "__main__":
|
| 241 |
+
main()
|
chartgen/latent_stats.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stage 0a of the latent design (reports/v10 設計:多層 latent.md): at which level does the part of a chart that the
|
| 2 |
+
music does not decide live?
|
| 3 |
+
|
| 4 |
+
Per chart, six chart settings c (and three gap shares) are computed from the per-measure plan labels (rows cache of
|
| 5 |
+
plan_search, fixed labels). Each value is mapped to a normal score within its difficulty tier (training charts set the
|
| 6 |
+
map) and, in the main line, residualised against a music-only prediction mu0 (ridge on pooled planner inputs, log
|
| 7 |
+
measure count, tier and era; 4-fold out-of-fold by song). Then correlations of the residuals are measured for pairs
|
| 8 |
+
of charts that share exactly one level:
|
| 9 |
+
|
| 10 |
+
WS same mapset, same tier, different mappers WM same mapset, same tier, same mapper
|
| 11 |
+
WT same mapset, different tiers XS different mapsets of the same song, same tier, no shared mapper
|
| 12 |
+
MS same mapper, different songs, same tier BL different mapper, different song, same tier (control, ~0)
|
| 13 |
+
|
| 14 |
+
Under a random-effects model the correlation of a pair type is the share of variance of the levels the pair has in
|
| 15 |
+
common, so (method of moments): music not extracted = r(XS); mapset coordination = r(WS) - r(XS); mapper habit = r(MS).
|
| 16 |
+
Cluster bootstrap over songs (over mappers for MS) gives 95% CIs.
|
| 17 |
+
|
| 18 |
+
python -m chartgen.latent_stats --rows rows.pkl --catalog data/catalog/taiko_beatmaps.parquet --out stage0a.json
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import argparse
|
| 24 |
+
import json
|
| 25 |
+
import pickle
|
| 26 |
+
from collections import defaultdict
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
|
| 31 |
+
from .dataset import GAP0, SUSTAIN, plan_active
|
| 32 |
+
|
| 33 |
+
SETTINGS = ("rest", "roll", "triplet", "eighth", "big", "density")
|
| 34 |
+
GAPS = ("gap_1/4", "gap_1/2", "gap_1")
|
| 35 |
+
NAMES = SETTINGS + GAPS
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def chart_settings(H: np.ndarray) -> np.ndarray | None:
|
| 39 |
+
"""[9] chart-level values from a [n, BAR_F] plan: inside-rest share, roll starts per active measure, triplet and 1/8
|
| 40 |
+
measure shares of measures with hit notes, big-note share, mean log density, and the 1/4, 1/2, 1 beat gap shares."""
|
| 41 |
+
act = plan_active(H)
|
| 42 |
+
if act.sum() < 8:
|
| 43 |
+
return None
|
| 44 |
+
idx = np.where(act)[0]
|
| 45 |
+
inside = np.zeros(len(H), bool)
|
| 46 |
+
inside[idx.min(): idx.max() + 1] = True
|
| 47 |
+
play = H[:, 0] > 0.5
|
| 48 |
+
if play.sum() < 8:
|
| 49 |
+
return None
|
| 50 |
+
g = H[play, GAP0:GAP0 + 10]
|
| 51 |
+
gs = g.sum(1, keepdims=True)
|
| 52 |
+
gm = (g / np.maximum(gs, 1e-9))[gs[:, 0] > 0].mean(0) if (gs > 0).any() else np.zeros(10)
|
| 53 |
+
return np.array([
|
| 54 |
+
float((~act[inside]).mean()),
|
| 55 |
+
float((H[act, 3] > 0.5).mean()),
|
| 56 |
+
float((H[play, 4] > 0.3).mean()),
|
| 57 |
+
float((H[play, 5] > 0.25).mean()),
|
| 58 |
+
float(H[play, 2].mean()),
|
| 59 |
+
float(H[play, 1].mean()),
|
| 60 |
+
float(gm[2]), float(gm[4]), float(gm[7]),
|
| 61 |
+
])
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def normal_scores(v: np.ndarray, ref: np.ndarray) -> np.ndarray:
|
| 65 |
+
"""Rank of v within the reference sample, mapped to a standard normal value (ties averaged)."""
|
| 66 |
+
from statistics import NormalDist
|
| 67 |
+
nd = NormalDist()
|
| 68 |
+
r = np.sort(ref)
|
| 69 |
+
lo = np.searchsorted(r, v, side="left"); hi = np.searchsorted(r, v, side="right")
|
| 70 |
+
q = np.clip((lo + hi) / 2 / len(r), 0.5 / len(r), 1 - 0.5 / len(r))
|
| 71 |
+
return np.array([nd.inv_cdf(float(x)) for x in q])
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def ridge_oof(X, Y, folds, lam=10.0):
|
| 75 |
+
"""Out-of-fold ridge predictions (features standardised on the training part of each fold)."""
|
| 76 |
+
P = np.zeros_like(Y)
|
| 77 |
+
for k in np.unique(folds):
|
| 78 |
+
tr, te = folds != k, folds == k
|
| 79 |
+
mu, sd = X[tr].mean(0), X[tr].std(0) + 1e-6
|
| 80 |
+
A, B = (X[tr] - mu) / sd, (X[te] - mu) / sd
|
| 81 |
+
ym = Y[tr].mean(0)
|
| 82 |
+
W = np.linalg.solve(A.T @ A + lam * len(A) * np.eye(A.shape[1]) / 100, A.T @ (Y[tr] - ym))
|
| 83 |
+
P[te] = B @ W + ym
|
| 84 |
+
return P
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def pair_corr(R, pairs, clusters, n_boot=1000, seed=0):
|
| 88 |
+
"""Per column: correlation over pairs (both orders, so it is symmetric), with a cluster bootstrap CI."""
|
| 89 |
+
if len(pairs) < 10:
|
| 90 |
+
return None
|
| 91 |
+
a = np.array([p[0] for p in pairs]); b = np.array([p[1] for p in pairs]); cl = np.array(clusters)
|
| 92 |
+
def corr(ii):
|
| 93 |
+
x = np.concatenate([R[a[ii]], R[b[ii]]]); y = np.concatenate([R[b[ii]], R[a[ii]]])
|
| 94 |
+
x = x - x.mean(0); y = y - y.mean(0)
|
| 95 |
+
return (x * y).sum(0) / np.sqrt((x ** 2).sum(0) * (y ** 2).sum(0) + 1e-12)
|
| 96 |
+
est = corr(np.arange(len(a)))
|
| 97 |
+
uc = np.unique(cl); byc = {c: np.where(cl == c)[0] for c in uc}
|
| 98 |
+
rng = np.random.default_rng(seed)
|
| 99 |
+
bs = []
|
| 100 |
+
for _ in range(n_boot):
|
| 101 |
+
pick = rng.choice(uc, len(uc))
|
| 102 |
+
bs.append(corr(np.concatenate([byc[c] for c in pick])))
|
| 103 |
+
lo, hi = np.percentile(np.array(bs), [2.5, 97.5], axis=0)
|
| 104 |
+
return {"n_pairs": int(len(a)), "n_clusters": int(len(uc)), "r": est.tolist(), "lo": lo.tolist(), "hi": hi.tolist()}
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def main(argv=None):
|
| 108 |
+
p = argparse.ArgumentParser()
|
| 109 |
+
p.add_argument("--rows", type=Path, required=True)
|
| 110 |
+
p.add_argument("--catalog", type=Path, default=Path("data/catalog/taiko_beatmaps.parquet"))
|
| 111 |
+
p.add_argument("--out", type=Path, required=True)
|
| 112 |
+
p.add_argument("--max-ms-pairs", type=int, default=20000, help="cap on same-mapper / baseline pairs (random sample)")
|
| 113 |
+
a = p.parse_args(argv)
|
| 114 |
+
import pyarrow.parquet as pq
|
| 115 |
+
cat = {r["beatmap_id"]: r for r in pq.read_table(a.catalog, columns=["beatmap_id", "beatmapset_id", "mapper_user_id", "approved_date"]).to_pylist()}
|
| 116 |
+
rows = pickle.load(open(a.rows, "rb"))
|
| 117 |
+
recs = []
|
| 118 |
+
for split in ("train", "val"):
|
| 119 |
+
for x in rows[split]:
|
| 120 |
+
H = x[1]
|
| 121 |
+
if H.shape[1] <= SUSTAIN:
|
| 122 |
+
raise ValueError("rows cache has the old plan format (no sustain column); rebuild it with the fixed labels")
|
| 123 |
+
c = chart_settings(H)
|
| 124 |
+
meta = cat.get(x[3][1])
|
| 125 |
+
if c is None or meta is None or meta["mapper_user_id"] is None:
|
| 126 |
+
continue
|
| 127 |
+
feat = x[0].astype(np.float32)
|
| 128 |
+
pooled = np.concatenate([feat.mean(0), feat.std(0), feat.max(0)])
|
| 129 |
+
year = int((meta["approved_date"] or "0")[:4] or 0)
|
| 130 |
+
recs.append(dict(split=split, set=x[3][0], bid=x[3][1], song=x[3][3] or str(x[3][0]), tier=int(x[2]),
|
| 131 |
+
mapper=int(meta["mapper_user_id"]), year=year, c=c, pooled=pooled, n=len(H)))
|
| 132 |
+
print("charts", len(recs), {s: sum(r["split"] == s for r in recs) for s in ("train", "val")}, flush=True)
|
| 133 |
+
C = np.stack([r["c"] for r in recs]); tiers = np.array([r["tier"] for r in recs])
|
| 134 |
+
Z = np.zeros_like(C)
|
| 135 |
+
for t in range(5):
|
| 136 |
+
m = tiers == t
|
| 137 |
+
ref = m & np.array([r["split"] == "train" for r in recs])
|
| 138 |
+
for j in range(C.shape[1]):
|
| 139 |
+
Z[m, j] = normal_scores(C[m, j], C[ref, j])
|
| 140 |
+
# music-only prediction mu0, out of fold by song (4 folds, hashed song key)
|
| 141 |
+
songs = np.array([r["song"] for r in recs])
|
| 142 |
+
import hashlib
|
| 143 |
+
folds = np.array([int(hashlib.sha1(f"fold:{s}".encode()).hexdigest(), 16) % 4 for s in songs])
|
| 144 |
+
years = np.array([r["year"] for r in recs], float)
|
| 145 |
+
X = np.concatenate([np.stack([r["pooled"] for r in recs]), np.log(np.array([[r["n"]] for r in recs], float)),
|
| 146 |
+
np.eye(5)[tiers], ((years - 2014) / 5)[:, None]], 1)
|
| 147 |
+
Mu = ridge_oof(X, Z, folds)
|
| 148 |
+
R_main = Z - Mu
|
| 149 |
+
music_r2 = 1 - ((Z - Mu) ** 2).sum(0) / ((Z - Z.mean(0)) ** 2).sum(0)
|
| 150 |
+
# pair types
|
| 151 |
+
by_set_tier, by_song_tier, by_mapper_tier = defaultdict(list), defaultdict(list), defaultdict(list)
|
| 152 |
+
for i, r in enumerate(recs):
|
| 153 |
+
by_set_tier[(r["set"], r["tier"])].append(i)
|
| 154 |
+
by_song_tier[(r["song"], r["tier"])].append(i)
|
| 155 |
+
by_mapper_tier[(r["mapper"], r["tier"])].append(i)
|
| 156 |
+
P = {k: ([], []) for k in ("WS", "WM", "WT", "XS", "MS", "BL")}
|
| 157 |
+
for (s_, t), ii in by_set_tier.items():
|
| 158 |
+
for x in range(len(ii)):
|
| 159 |
+
for y in range(x + 1, len(ii)):
|
| 160 |
+
i, j = ii[x], ii[y]
|
| 161 |
+
k = "WM" if recs[i]["mapper"] == recs[j]["mapper"] else "WS"
|
| 162 |
+
P[k][0].append((i, j)); P[k][1].append(recs[i]["song"])
|
| 163 |
+
by_set = defaultdict(list)
|
| 164 |
+
for i, r in enumerate(recs):
|
| 165 |
+
by_set[r["set"]].append(i)
|
| 166 |
+
for s_, ii in by_set.items():
|
| 167 |
+
for x in range(len(ii)):
|
| 168 |
+
for y in range(x + 1, len(ii)):
|
| 169 |
+
i, j = ii[x], ii[y]
|
| 170 |
+
if recs[i]["tier"] != recs[j]["tier"]:
|
| 171 |
+
P["WT"][0].append((i, j)); P["WT"][1].append(recs[i]["song"])
|
| 172 |
+
for (song, t), ii in by_song_tier.items():
|
| 173 |
+
for x in range(len(ii)):
|
| 174 |
+
for y in range(x + 1, len(ii)):
|
| 175 |
+
i, j = ii[x], ii[y]
|
| 176 |
+
if recs[i]["set"] != recs[j]["set"] and recs[i]["mapper"] != recs[j]["mapper"]:
|
| 177 |
+
P["XS"][0].append((i, j)); P["XS"][1].append(song)
|
| 178 |
+
rng = np.random.default_rng(0)
|
| 179 |
+
ms = []
|
| 180 |
+
for (mp, t), ii in by_mapper_tier.items():
|
| 181 |
+
for x in range(len(ii)):
|
| 182 |
+
for y in range(x + 1, len(ii)):
|
| 183 |
+
i, j = ii[x], ii[y]
|
| 184 |
+
if recs[i]["song"] != recs[j]["song"]:
|
| 185 |
+
ms.append((i, j, mp))
|
| 186 |
+
if len(ms) > a.max_ms_pairs:
|
| 187 |
+
ms = [ms[k] for k in rng.choice(len(ms), a.max_ms_pairs, replace=False)]
|
| 188 |
+
P["MS"] = ([(i, j) for i, j, _ in ms], [mp for _, _, mp in ms])
|
| 189 |
+
by_tier = defaultdict(list)
|
| 190 |
+
for i, r in enumerate(recs):
|
| 191 |
+
by_tier[r["tier"]].append(i)
|
| 192 |
+
bl = []
|
| 193 |
+
while len(bl) < min(a.max_ms_pairs, 20000):
|
| 194 |
+
t = rng.integers(5)
|
| 195 |
+
if len(by_tier[t]) < 2:
|
| 196 |
+
continue
|
| 197 |
+
i, j = rng.choice(by_tier[t], 2, replace=False)
|
| 198 |
+
if recs[i]["song"] != recs[j]["song"] and recs[i]["mapper"] != recs[j]["mapper"] and abs(recs[i]["year"] - recs[j]["year"]) <= 2:
|
| 199 |
+
bl.append((int(i), int(j), recs[i]["song"]))
|
| 200 |
+
P["BL"] = ([(i, j) for i, j, _ in bl], [s for _, _, s in bl])
|
| 201 |
+
out = {"names": list(NAMES), "n_charts": len(recs), "music_r2_mu0": music_r2.tolist(), "lines": {}}
|
| 202 |
+
for line, R in (("residual", R_main), ("raw", Z)):
|
| 203 |
+
res = {k: pair_corr(R, v[0], v[1]) for k, v in P.items()}
|
| 204 |
+
g = lambda k: np.array(res[k]["r"]) if res[k] else np.full(len(NAMES), np.nan) # noqa: E731
|
| 205 |
+
shares = {"music_not_extracted (XS)": g("XS").tolist(), "mapset_coordination (WS-XS)": (g("WS") - g("XS")).tolist(),
|
| 206 |
+
"mapper_habit (MS)": g("MS").tolist(), "chart_own_and_noise (1-WM)": (1 - g("WM")).tolist()}
|
| 207 |
+
out["lines"][line] = {"pairs": res, "shares": shares}
|
| 208 |
+
a.out.write_text(json.dumps(out, indent=1))
|
| 209 |
+
for line in ("residual", "raw"):
|
| 210 |
+
print(f"\n== {line} (rows: pair type; columns: {', '.join(NAMES)})")
|
| 211 |
+
for k, v in out["lines"][line]["pairs"].items():
|
| 212 |
+
if v is None:
|
| 213 |
+
print(f"{k:3s} (too few pairs)"); continue
|
| 214 |
+
print(f"{k:3s} n={v['n_pairs']:6d} cl={v['n_clusters']:5d} " + " ".join(f"{r:+.2f}[{l:+.2f},{h:+.2f}]" for r, l, h in zip(v["r"], v["lo"], v["hi"])))
|
| 215 |
+
print("\nmusic R^2 of mu0:", " ".join(f"{n}={r:.2f}" for n, r in zip(NAMES, music_r2)))
|
| 216 |
+
|
| 217 |
+
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""B0: supervised hierarchical autoregressive model of a complete chart (README section 2).
|
| 2 |
+
|
| 3 |
+
A chart has three parts and the model predicts all of them:
|
| 4 |
+
|
| 5 |
+
* timing map -- beat and downbeat activations from audio alone (grid-free encoder);
|
| 6 |
+
decoded into BPM / offset / meter sections by :mod:`chartgen.timing`;
|
| 7 |
+
* notes -- per step, the next note's position on the beat grid (beats ahead, then
|
| 8 |
+
absolute 1/48 phase), then its type, length, scroll speed (SV) and residual;
|
| 9 |
+
* effects -- kiai per frame; SV per note; bar lines follow the decoded sections.
|
| 10 |
+
|
| 11 |
+
The encoder never sees the beat grid, so its music representation can be replaced by the
|
| 12 |
+
Stage A (JEPA + VICReg) encoder. Grid information is added after the encoder for the
|
| 13 |
+
planner, decoder and kiai head.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.nn as nn
|
| 22 |
+
import torch.nn.functional as F
|
| 23 |
+
|
| 24 |
+
from .dataset import BAR_F, GRID, REP_F, MAX_EVENTS, MAX_SECTIONS, N_AHEAD, N_LEN, N_SUBDIV, N_SV, N_TYPE
|
| 25 |
+
from .gapstats import N_GAP_BINS, N_RATIO_BINS
|
| 26 |
+
|
| 27 |
+
N_TIERS = 5
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@dataclass
|
| 31 |
+
class B0Config:
|
| 32 |
+
n_mels: int = 128
|
| 33 |
+
d_model: int = 224
|
| 34 |
+
enc_layers: int = 3
|
| 35 |
+
dec_layers: int = 4
|
| 36 |
+
n_heads: int = 8
|
| 37 |
+
d_plan: int = 128
|
| 38 |
+
plan_layers: int = 2
|
| 39 |
+
branch_ch: int = 96
|
| 40 |
+
local_frames: int = 2 # +/- frames of high-resolution audio read by the note heads
|
| 41 |
+
dropout: float = 0.1
|
| 42 |
+
max_frames: int = 1024 # after 2x downsampling
|
| 43 |
+
gap_plan: bool = False # planner also predicts each section's note-gap and gap-ratio distributions (gapstats),
|
| 44 |
+
# and the decoder is conditioned on them
|
| 45 |
+
bar_plan: bool = False # decoder memory is conditioned on a per-bar plan (dataset.bar_plan); planner input is not
|
| 46 |
+
bar_plan_drop: float = 0.3 # training: probability of hiding the bar plan of a window (model also works without)
|
| 47 |
+
bar_plan_corrupt: float = 0.0 # training: probability that a given bar plan is corrupted like a predicted one
|
| 48 |
+
rep_hint: bool = False # decoder memory also gets the per-bar repetition hint from the audio (dataset.rep_hint)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _enc_layer(d, h, drop):
|
| 52 |
+
return nn.TransformerEncoderLayer(d, h, 4 * d, drop, activation="gelu", batch_first=True, norm_first=True)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class Frontend(nn.Module):
|
| 56 |
+
"""Multi-scale temporal CNN over log-Mel. Returns 100 fps and 50 fps features."""
|
| 57 |
+
|
| 58 |
+
def __init__(self, c: B0Config):
|
| 59 |
+
super().__init__()
|
| 60 |
+
self.norm = nn.LayerNorm(c.n_mels)
|
| 61 |
+
self.branches = nn.ModuleList(
|
| 62 |
+
nn.Sequential(nn.Conv1d(c.n_mels, c.branch_ch, k, padding=k // 2), nn.GELU()) for k in (3, 9, 27)
|
| 63 |
+
)
|
| 64 |
+
self.hires_dim = 3 * c.branch_ch
|
| 65 |
+
self.down = nn.Conv1d(self.hires_dim, c.d_model, 4, stride=2, padding=1)
|
| 66 |
+
|
| 67 |
+
def forward(self, mel):
|
| 68 |
+
x = self.norm(mel).transpose(1, 2)
|
| 69 |
+
hi = torch.cat([b(x) for b in self.branches], 1)
|
| 70 |
+
lo = self.down(hi)
|
| 71 |
+
return hi.transpose(1, 2), lo.transpose(1, 2)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class B0(nn.Module):
|
| 75 |
+
def __init__(self, c: B0Config = B0Config()):
|
| 76 |
+
super().__init__()
|
| 77 |
+
self.c = c
|
| 78 |
+
d = c.d_model
|
| 79 |
+
self.frontend = Frontend(c)
|
| 80 |
+
hd = self.frontend.hires_dim
|
| 81 |
+
self.enc_pos = nn.Parameter(torch.zeros(1, c.max_frames, d))
|
| 82 |
+
self.encoder = nn.TransformerEncoder(_enc_layer(d, c.n_heads, c.dropout), c.enc_layers, enable_nested_tensor=False)
|
| 83 |
+
self.enc_norm = nn.LayerNorm(d)
|
| 84 |
+
self.beat_proj = nn.Linear(4, d)
|
| 85 |
+
|
| 86 |
+
# frame-level heads (100 fps)
|
| 87 |
+
self.timing_head = nn.Sequential(nn.Linear(hd + d, d), nn.GELU(), nn.Linear(d, 2)) # beat, downbeat
|
| 88 |
+
self.kiai_head = nn.Sequential(nn.Linear(hd + d, d // 2), nn.GELU(), nn.Linear(d // 2, 1))
|
| 89 |
+
|
| 90 |
+
# section planner
|
| 91 |
+
self.plan_in = nn.Linear(d, c.d_plan)
|
| 92 |
+
self.plan_tier = nn.Embedding(N_TIERS, c.d_plan)
|
| 93 |
+
self.plan_pos = nn.Parameter(torch.zeros(1, MAX_SECTIONS, c.d_plan))
|
| 94 |
+
self.planner = nn.TransformerEncoder(_enc_layer(c.d_plan, 4, c.dropout), c.plan_layers, enable_nested_tensor=False)
|
| 95 |
+
self.rho_head = nn.Linear(c.d_plan, 1)
|
| 96 |
+
self.r_head = nn.Linear(c.d_plan, N_SUBDIV)
|
| 97 |
+
self.plan_r_emb = nn.Embedding(N_SUBDIV, d)
|
| 98 |
+
self.plan_rho_proj = nn.Linear(1, d)
|
| 99 |
+
if c.gap_plan:
|
| 100 |
+
self.gap_head = nn.Linear(c.d_plan, N_GAP_BINS)
|
| 101 |
+
self.ratio_head = nn.Linear(c.d_plan, N_RATIO_BINS)
|
| 102 |
+
self.plan_gap_proj = nn.Linear(N_GAP_BINS + N_RATIO_BINS, d)
|
| 103 |
+
nn.init.zeros_(self.plan_gap_proj.weight) # starts as B0: fine-tuning from a B0 checkpoint is a no-op at step 0
|
| 104 |
+
nn.init.zeros_(self.plan_gap_proj.bias)
|
| 105 |
+
if c.rep_hint:
|
| 106 |
+
self.rep_proj = nn.Linear(REP_F, d)
|
| 107 |
+
nn.init.zeros_(self.rep_proj.weight)
|
| 108 |
+
nn.init.zeros_(self.rep_proj.bias)
|
| 109 |
+
if c.bar_plan:
|
| 110 |
+
self.bar_plan_proj = nn.Linear(BAR_F + 1, d) # + "plan given" flag
|
| 111 |
+
nn.init.zeros_(self.bar_plan_proj.weight)
|
| 112 |
+
nn.init.zeros_(self.bar_plan_proj.bias)
|
| 113 |
+
|
| 114 |
+
# decoder
|
| 115 |
+
self.bos = nn.Parameter(torch.zeros(1, 1, d))
|
| 116 |
+
self.tier_emb = nn.Embedding(N_TIERS, d)
|
| 117 |
+
self.ahead_emb = nn.Embedding(N_AHEAD, d)
|
| 118 |
+
self.type_emb = nn.Embedding(N_TYPE, d)
|
| 119 |
+
self.len_emb = nn.Embedding(N_LEN, d)
|
| 120 |
+
self.sv_emb = nn.Embedding(N_SV, d)
|
| 121 |
+
self.phase_emb = nn.Embedding(GRID, d)
|
| 122 |
+
self.bar_emb = nn.Embedding(16, d)
|
| 123 |
+
self.audio_proj = nn.Linear(d, d)
|
| 124 |
+
self.dec_pos = nn.Parameter(torch.zeros(1, MAX_EVENTS + 1, d))
|
| 125 |
+
layer = nn.TransformerDecoderLayer(d, c.n_heads, 4 * d, c.dropout, activation="gelu", batch_first=True, norm_first=True)
|
| 126 |
+
self.decoder = nn.TransformerDecoder(layer, c.dec_layers)
|
| 127 |
+
self.dec_norm = nn.LayerNorm(d)
|
| 128 |
+
self.ahead_head = nn.Linear(d, N_AHEAD)
|
| 129 |
+
self.phase_head = nn.Sequential(nn.Linear(d, d), nn.GELU(), nn.Linear(d, GRID))
|
| 130 |
+
|
| 131 |
+
self.local_proj = nn.Linear((2 * c.local_frames + 1) * hd, d)
|
| 132 |
+
self.note_mlp = nn.Sequential(nn.Linear(d, d), nn.GELU(), nn.LayerNorm(d))
|
| 133 |
+
self.type_head = nn.Linear(d, N_TYPE)
|
| 134 |
+
self.len_head = nn.Linear(d, N_LEN)
|
| 135 |
+
self.sv_head = nn.Linear(d, N_SV)
|
| 136 |
+
self.delta_head = nn.Linear(d, 1)
|
| 137 |
+
|
| 138 |
+
for p in (self.enc_pos, self.plan_pos, self.dec_pos, self.bos):
|
| 139 |
+
nn.init.normal_(p, std=0.02)
|
| 140 |
+
|
| 141 |
+
# ---- encoder ---------------------------------------------------------------
|
| 142 |
+
def encode(self, mel):
|
| 143 |
+
"""Grid-free music representation."""
|
| 144 |
+
hi, lo = self.frontend(mel.float())
|
| 145 |
+
T = lo.shape[1]
|
| 146 |
+
mem = self.enc_norm(self.encoder(lo + self.enc_pos[:, :T]))
|
| 147 |
+
return hi, mem
|
| 148 |
+
|
| 149 |
+
def with_grid(self, mem, beat_feat):
|
| 150 |
+
return mem + self.beat_proj(beat_feat[:, ::2][:, : mem.shape[1]])
|
| 151 |
+
|
| 152 |
+
def _up(self, x, W):
|
| 153 |
+
return x.repeat_interleave(2, 1)[:, :W]
|
| 154 |
+
|
| 155 |
+
def timing_logits(self, hi, mem):
|
| 156 |
+
return self.timing_head(torch.cat([hi, self._up(mem, hi.shape[1])], -1)) # [B, W, 2]
|
| 157 |
+
|
| 158 |
+
def kiai_logits(self, hi, mem_g):
|
| 159 |
+
return self.kiai_head(torch.cat([hi, self._up(mem_g, hi.shape[1])], -1)).squeeze(-1)
|
| 160 |
+
|
| 161 |
+
# ---- planner -----------------------------------------------------------------
|
| 162 |
+
def plan(self, mem_g, frame_section, tier):
|
| 163 |
+
return self.plan_full(mem_g, frame_section, tier)[:3]
|
| 164 |
+
|
| 165 |
+
def plan_full(self, mem_g, frame_section, tier):
|
| 166 |
+
"""(log1p density, subdivision logits, section mask, gap logits, ratio logits); the last two are None
|
| 167 |
+
without gap_plan."""
|
| 168 |
+
fs = frame_section[:, ::2][:, : mem_g.shape[1]]
|
| 169 |
+
onehot = F.one_hot((fs + 1).clamp(min=0), MAX_SECTIONS + 1)[..., 1:].float() # [B, T, S]
|
| 170 |
+
count = onehot.sum(1)
|
| 171 |
+
pooled = torch.einsum("bts,btd->bsd", onehot, mem_g) / count.clamp(min=1).unsqueeze(-1)
|
| 172 |
+
h = self.plan_in(pooled) + self.plan_pos + self.plan_tier(tier)[:, None]
|
| 173 |
+
h = self.planner(h)
|
| 174 |
+
gl, rl = (self.gap_head(h), self.ratio_head(h)) if self.c.gap_plan else (None, None)
|
| 175 |
+
return self.rho_head(h).squeeze(-1), self.r_head(h), count > 0, gl, rl
|
| 176 |
+
|
| 177 |
+
@staticmethod
|
| 178 |
+
def gap_probs(gap_logits, ratio_logits):
|
| 179 |
+
return torch.cat([torch.softmax(gap_logits.float(), -1), torch.softmax(ratio_logits.float(), -1)], -1)
|
| 180 |
+
|
| 181 |
+
def with_rep_hint(self, mem_g, rep_hint, frame_bar):
|
| 182 |
+
if not getattr(self.c, "rep_hint", False) or rep_hint is None:
|
| 183 |
+
return mem_g
|
| 184 |
+
e = self.rep_proj(rep_hint.to(mem_g.dtype))
|
| 185 |
+
fb = frame_bar[:, ::2][:, : mem_g.shape[1]]
|
| 186 |
+
g = torch.gather(e, 1, fb.clamp(min=0).unsqueeze(-1).expand(-1, -1, e.shape[-1]))
|
| 187 |
+
return mem_g + g * (fb >= 0).unsqueeze(-1).to(g.dtype)
|
| 188 |
+
|
| 189 |
+
@staticmethod
|
| 190 |
+
def corrupt_bar_plan(bp, p):
|
| 191 |
+
"""Make a human bar plan look like a predicted one (for windows chosen with probability p):
|
| 192 |
+
density noise, gap histogram blended toward the window mean, triplet / 1/8 / big / roll / sustain shares
|
| 193 |
+
shrunk, 5% of play flags flipped. Roll start and sustain are not gated by play (rolls can start or run in a
|
| 194 |
+
measure without hit notes)."""
|
| 195 |
+
from .dataset import GAP0, SUSTAIN
|
| 196 |
+
from .gapstats import N_GAP_BINS
|
| 197 |
+
B, n, _ = bp.shape
|
| 198 |
+
sel = (torch.rand(B, 1, 1, device=bp.device) < p).float()
|
| 199 |
+
play = bp[..., :1]
|
| 200 |
+
x = bp.clone()
|
| 201 |
+
x[..., 1:2] = bp[..., 1:2] * torch.exp(0.25 * torch.randn_like(bp[..., 1:2]))
|
| 202 |
+
x[..., 2:6] = bp[..., 2:6] * torch.rand(B, 1, 4, device=bp.device)
|
| 203 |
+
x[..., SUSTAIN] = bp[..., SUSTAIN] * (0.5 + 0.5 * torch.rand(B, 1, device=bp.device))
|
| 204 |
+
g = bp[..., GAP0:GAP0 + N_GAP_BINS]
|
| 205 |
+
gm = (g * play).sum(1, keepdim=True) / play.sum(1, keepdim=True).clamp(min=1)
|
| 206 |
+
a = 0.6 * torch.rand(B, 1, 1, device=bp.device)
|
| 207 |
+
x[..., GAP0:GAP0 + N_GAP_BINS] = ((1 - a) * g + a * gm) * play
|
| 208 |
+
flip = (torch.rand(B, n, 1, device=bp.device) < 0.05).float()
|
| 209 |
+
x[..., :1] = play * (1 - flip) + (1 - play) * flip
|
| 210 |
+
hit_cols = [1, 2, 4, 5] + list(range(GAP0, GAP0 + N_GAP_BINS))
|
| 211 |
+
x[..., hit_cols] = x[..., hit_cols] * x[..., :1] # measures without hit notes carry no hit-note features
|
| 212 |
+
x[..., :1] = x[..., :1].clamp(max=1)
|
| 213 |
+
return sel * x + (1 - sel) * bp
|
| 214 |
+
|
| 215 |
+
def with_bar_plan(self, mem_g, bar_plan, frame_bar, given=None):
|
| 216 |
+
"""Decoder memory + the plan of the bar each (50 fps) frame belongs to. given: [B] bool, False = no plan."""
|
| 217 |
+
if not self.c.bar_plan or bar_plan is None:
|
| 218 |
+
return mem_g
|
| 219 |
+
B = bar_plan.shape[0]
|
| 220 |
+
given = torch.ones(B, dtype=torch.bool, device=mem_g.device) if given is None else given
|
| 221 |
+
bp = bar_plan.float() * given[:, None, None]
|
| 222 |
+
flag = given[:, None, None].float().expand(-1, bp.shape[1], 1)
|
| 223 |
+
e = self.bar_plan_proj(torch.cat([bp, flag], -1).to(mem_g.dtype)) # [B, MAX_BARS, d]
|
| 224 |
+
fb = frame_bar[:, ::2][:, : mem_g.shape[1]]
|
| 225 |
+
g = torch.gather(e, 1, fb.clamp(min=0).unsqueeze(-1).expand(-1, -1, e.shape[-1]))
|
| 226 |
+
return mem_g + g * (fb >= 0).unsqueeze(-1).to(g.dtype)
|
| 227 |
+
|
| 228 |
+
def plan_embedding(self, rho, r, gap=None):
|
| 229 |
+
e = self.plan_r_emb(r) + self.plan_rho_proj(torch.log1p(rho.clamp(min=0)).unsqueeze(-1))
|
| 230 |
+
if self.c.gap_plan and gap is not None:
|
| 231 |
+
e = e + self.plan_gap_proj(gap.to(e.dtype))
|
| 232 |
+
return e
|
| 233 |
+
|
| 234 |
+
# ---- decoder -----------------------------------------------------------------
|
| 235 |
+
def _gather(self, x, idx):
|
| 236 |
+
return torch.gather(x, 1, idx.unsqueeze(-1).expand(-1, -1, x.shape[-1]))
|
| 237 |
+
|
| 238 |
+
def event_tokens(self, mem_g, plan_emb, tier, ev):
|
| 239 |
+
frames50 = (ev["ev_frame"] // 2).clamp(max=mem_g.shape[1] - 1)
|
| 240 |
+
x = (self.ahead_emb(ev["ev_ahead"].clamp(0, N_AHEAD - 1)) + self.type_emb(ev["ev_type"].clamp(min=0))
|
| 241 |
+
+ self.len_emb(ev["ev_len"].clamp(min=0)) + self.sv_emb(ev["ev_sv"].clamp(min=0))
|
| 242 |
+
+ self.phase_emb(ev["ev_phase"]) + self.bar_emb(ev["ev_bar"])
|
| 243 |
+
+ self.audio_proj(self._gather(mem_g, frames50)) + self._gather(plan_emb, ev["ev_section"]))
|
| 244 |
+
B = x.shape[0]
|
| 245 |
+
x = torch.cat([self.bos.expand(B, -1, -1), x], 1) + self.tier_emb(tier)[:, None]
|
| 246 |
+
return x + self.dec_pos[:, : x.shape[1]]
|
| 247 |
+
|
| 248 |
+
def decode(self, tokens, mem_g, key_padding):
|
| 249 |
+
L = tokens.shape[1]
|
| 250 |
+
causal = torch.triu(torch.ones(L, L, dtype=torch.bool, device=tokens.device), 1)
|
| 251 |
+
return self.dec_norm(self.decoder(tokens, mem_g, tgt_mask=causal, tgt_key_padding_mask=key_padding))
|
| 252 |
+
|
| 253 |
+
def local_audio(self, hi, frames):
|
| 254 |
+
k = self.c.local_frames
|
| 255 |
+
offs = torch.arange(-k, k + 1, device=frames.device)
|
| 256 |
+
idx = (frames.unsqueeze(-1) + offs).clamp(0, hi.shape[1] - 1)
|
| 257 |
+
B, N, K = idx.shape
|
| 258 |
+
g = torch.gather(hi, 1, idx.reshape(B, N * K, 1).expand(-1, -1, hi.shape[-1]))
|
| 259 |
+
return self.local_proj(g.reshape(B, N, K * hi.shape[-1]))
|
| 260 |
+
|
| 261 |
+
def phase_logits(self, h, next_ahead):
|
| 262 |
+
return self.phase_head(h + self.ahead_emb(next_ahead.clamp(0, N_AHEAD - 1)))
|
| 263 |
+
|
| 264 |
+
def note_heads(self, h, hi, plan_emb, next_ahead, next_phase, next_bar, next_frame, next_section):
|
| 265 |
+
q = (h + self.ahead_emb(next_ahead.clamp(0, N_AHEAD - 1)) + self.phase_emb(next_phase) + self.bar_emb(next_bar)
|
| 266 |
+
+ self.local_audio(hi, next_frame) + self._gather(plan_emb, next_section))
|
| 267 |
+
q = self.note_mlp(q)
|
| 268 |
+
return self.type_head(q), self.len_head(q), self.sv_head(q), self.delta_head(q).squeeze(-1)
|
| 269 |
+
|
| 270 |
+
def forward(self, batch, plan_source: str = "target"):
|
| 271 |
+
hi, mem = self.encode(batch["mel"])
|
| 272 |
+
mem_g = self.with_grid(mem, batch["beat_feat"])
|
| 273 |
+
timing = self.timing_logits(hi, mem)
|
| 274 |
+
kiai = self.kiai_logits(hi, mem_g)
|
| 275 |
+
rho_pred, r_logits, sec_mask, gap_logits, ratio_logits = self.plan_full(mem_g, batch["frame_section"], batch["tier"])
|
| 276 |
+
if plan_source == "target":
|
| 277 |
+
plan_emb = self.plan_embedding(batch["plan_rho"], batch["plan_r"], batch.get("plan_gap"))
|
| 278 |
+
else:
|
| 279 |
+
gp = self.gap_probs(gap_logits, ratio_logits).detach() if gap_logits is not None else None
|
| 280 |
+
plan_emb = self.plan_embedding(rho_pred.detach().expm1().clamp(min=0), r_logits.argmax(-1), gp)
|
| 281 |
+
mem_g = self.with_rep_hint(mem_g, batch.get("rep_hint"), batch["frame_bar"])
|
| 282 |
+
if self.c.bar_plan:
|
| 283 |
+
given = torch.ones(mem_g.shape[0], dtype=torch.bool, device=mem_g.device)
|
| 284 |
+
bp = batch["bar_plan"]
|
| 285 |
+
if self.training:
|
| 286 |
+
given = torch.rand(mem_g.shape[0], device=mem_g.device) >= self.c.bar_plan_drop
|
| 287 |
+
if getattr(self.c, "bar_plan_corrupt", 0.0) > 0:
|
| 288 |
+
bp = self.corrupt_bar_plan(bp.float(), self.c.bar_plan_corrupt)
|
| 289 |
+
mem_g = self.with_bar_plan(mem_g, bp, batch["frame_bar"], given)
|
| 290 |
+
tokens = self.event_tokens(mem_g, plan_emb, batch["tier"], batch)
|
| 291 |
+
pad = torch.cat([torch.zeros_like(batch["ev_mask"][:, :1]), ~batch["ev_mask"]], 1)
|
| 292 |
+
h = self.decode(tokens, mem_g, pad)
|
| 293 |
+
type_logits, len_logits, sv_logits, delta = self.note_heads(
|
| 294 |
+
h[:, :-1], hi, plan_emb, batch["ev_ahead"], batch["ev_phase"], batch["ev_bar"], batch["ev_frame"], batch["ev_section"])
|
| 295 |
+
return {"ahead_logits": self.ahead_head(h), "phase_logits": self.phase_logits(h, batch["tgt_ahead"]),
|
| 296 |
+
"type_logits": type_logits, "len_logits": len_logits,
|
| 297 |
+
"sv_logits": sv_logits, "delta": delta, "rho_pred": rho_pred, "r_logits": r_logits,
|
| 298 |
+
"sec_mask": sec_mask, "timing_logits": timing, "kiai_logits": kiai,
|
| 299 |
+
"gap_logits": gap_logits, "ratio_logits": ratio_logits}
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
DEFAULT_WEIGHTS = {"note": 1.0, "length": 0.5, "timing": 0.05, "plan": 0.5, "beat": 1.0, "kiai": 0.3, "sv": 0.3, "gap": 0.5}
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def b0_loss(out, batch, weights: dict[str, float], type_class_weight: torch.Tensor | None = None):
|
| 306 |
+
m = batch["ev_mask"]
|
| 307 |
+
L = {}
|
| 308 |
+
L["pos"] = F.cross_entropy(out["ahead_logits"].flatten(0, 1).float(), batch["tgt_ahead"].flatten(), ignore_index=-100) + \
|
| 309 |
+
F.cross_entropy(out["phase_logits"].flatten(0, 1).float(), batch["tgt_phase"].flatten(), ignore_index=-100)
|
| 310 |
+
L["note"] = F.cross_entropy(out["type_logits"].flatten(0, 1).float(), batch["ev_type"].flatten(),
|
| 311 |
+
weight=type_class_weight, ignore_index=-100)
|
| 312 |
+
# length only for rolls and balloons (type >= 4): hit notes always have length 0, so a loss over every note teaches the
|
| 313 |
+
# head that length 0 is almost always right, and a roll then gets no body at generation
|
| 314 |
+
# Divided by the number of ALL notes, so each roll gets the same gradient as before and the term stays small next to
|
| 315 |
+
# position and type (they share the note query); averaging over rolls only made it ~200x larger.
|
| 316 |
+
is_roll = batch["ev_type"] >= 4
|
| 317 |
+
len_tgt = torch.where(is_roll, batch["ev_len"], torch.full_like(batch["ev_len"], -100))
|
| 318 |
+
n_ev = (batch["ev_type"] != -100).sum().clamp(min=1)
|
| 319 |
+
L["length"] = F.cross_entropy(out["len_logits"].flatten(0, 1).float(), len_tgt.flatten(), ignore_index=-100, reduction="sum") / n_ev
|
| 320 |
+
L["sv"] = F.cross_entropy(out["sv_logits"].flatten(0, 1).float(), batch["ev_sv"].flatten(), ignore_index=-100)
|
| 321 |
+
L["timing"] = (F.huber_loss(out["delta"].float(), batch["ev_delta"], reduction="none", delta=5.0) * m).sum() / m.sum().clamp(min=1)
|
| 322 |
+
sm = out["sec_mask"]
|
| 323 |
+
rho_t = torch.log1p(batch["plan_rho"])
|
| 324 |
+
L["plan"] = ((out["rho_pred"].float() - rho_t) ** 2 * sm).sum() / sm.sum().clamp(min=1) + \
|
| 325 |
+
(F.cross_entropy(out["r_logits"].float().transpose(1, 2), batch["plan_r"], reduction="none") * sm).sum() / sm.sum().clamp(min=1)
|
| 326 |
+
if out.get("gap_logits") is not None: # soft cross-entropy to each section's gap / ratio distribution
|
| 327 |
+
from .gapstats import N_GAP_BINS
|
| 328 |
+
tg = batch["plan_gap"].float()
|
| 329 |
+
lg = 0.0
|
| 330 |
+
for logits, t in ((out["gap_logits"], tg[..., :N_GAP_BINS]), (out["ratio_logits"], tg[..., N_GAP_BINS:])):
|
| 331 |
+
mm = sm & (t.sum(-1) > 0)
|
| 332 |
+
ce = -(t * torch.log_softmax(logits.float(), -1)).sum(-1)
|
| 333 |
+
lg = lg + (ce * mm).sum() / mm.sum().clamp(min=1)
|
| 334 |
+
L["gap"] = lg
|
| 335 |
+
bm = batch["beat_mask"]
|
| 336 |
+
tl = out["timing_logits"].float()
|
| 337 |
+
pw = torch.tensor(8.0, device=tl.device) # beats are ~2% of frames
|
| 338 |
+
beat_l = F.binary_cross_entropy_with_logits(tl[..., 0], batch["beat_tgt"], pos_weight=pw, reduction="none")
|
| 339 |
+
down_l = F.binary_cross_entropy_with_logits(tl[..., 1], batch["down_tgt"], pos_weight=pw * 4, reduction="none")
|
| 340 |
+
L["beat"] = ((beat_l + down_l) * bm).sum() / bm.sum().clamp(min=1)
|
| 341 |
+
km = batch["kiai_mask"]
|
| 342 |
+
L["kiai"] = (F.binary_cross_entropy_with_logits(out["kiai_logits"].float(), batch["kiai_tgt"], reduction="none") * km).sum() / km.sum().clamp(min=1)
|
| 343 |
+
w = {**DEFAULT_WEIGHTS, **weights}
|
| 344 |
+
total = L["pos"] + sum(w[k] * L[k] for k in ("note", "length", "sv", "timing", "plan", "beat", "kiai", "gap") if k in L)
|
| 345 |
+
return total, {k: v.detach() for k, v in L.items()}
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
class DecodeCache:
|
| 349 |
+
"""Incremental decoding for B0's event decoder: keys and values of past events per layer, and
|
| 350 |
+
the cross-attention keys and values of the music memory (computed once). Gives the same
|
| 351 |
+
outputs as decode() on the full prefix (eval mode), at O(L) instead of O(L^2) per step."""
|
| 352 |
+
|
| 353 |
+
def __init__(self, model: B0, mem_g):
|
| 354 |
+
self.model, self.layers = model, list(model.decoder.layers)
|
| 355 |
+
self.k, self.v, self.ck, self.cv = [], [], [], []
|
| 356 |
+
for layer in self.layers:
|
| 357 |
+
a = layer.multihead_attn
|
| 358 |
+
d = a.embed_dim
|
| 359 |
+
w, b = a.in_proj_weight, a.in_proj_bias
|
| 360 |
+
self.ck.append(self._heads(F.linear(mem_g, w[d:2 * d], b[d:2 * d]), a.num_heads))
|
| 361 |
+
self.cv.append(self._heads(F.linear(mem_g, w[2 * d:], b[2 * d:]), a.num_heads))
|
| 362 |
+
self.k.append(None)
|
| 363 |
+
self.v.append(None)
|
| 364 |
+
|
| 365 |
+
@staticmethod
|
| 366 |
+
def _heads(x, h):
|
| 367 |
+
B, L, D = x.shape
|
| 368 |
+
return x.view(B, L, h, D // h).transpose(1, 2)
|
| 369 |
+
|
| 370 |
+
def step(self, x):
|
| 371 |
+
"""x: [B, n, d] new tokens (n >= 1, appended after the cached ones). Returns dec_norm output [B, n, d]."""
|
| 372 |
+
for i, layer in enumerate(self.layers):
|
| 373 |
+
sa = layer.self_attn
|
| 374 |
+
h, d = sa.num_heads, sa.embed_dim
|
| 375 |
+
q, k, v = F.linear(layer.norm1(x), sa.in_proj_weight, sa.in_proj_bias).chunk(3, -1)
|
| 376 |
+
q, k, v = self._heads(q, h), self._heads(k, h), self._heads(v, h)
|
| 377 |
+
n = q.shape[2]
|
| 378 |
+
if self.k[i] is not None:
|
| 379 |
+
k, v = torch.cat([self.k[i], k], 2), torch.cat([self.v[i], v], 2)
|
| 380 |
+
self.k[i], self.v[i] = k, v
|
| 381 |
+
L = k.shape[2]
|
| 382 |
+
mask = None
|
| 383 |
+
if n > 1: # causal within the new block
|
| 384 |
+
mask = torch.ones(n, L, dtype=torch.bool, device=x.device).tril(L - n)
|
| 385 |
+
o = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
|
| 386 |
+
x = x + sa.out_proj(o.transpose(1, 2).reshape(x.shape[0], n, d))
|
| 387 |
+
ca = layer.multihead_attn
|
| 388 |
+
q = self._heads(F.linear(layer.norm2(x), ca.in_proj_weight[:d], ca.in_proj_bias[:d]), h)
|
| 389 |
+
o = F.scaled_dot_product_attention(q, self.ck[i], self.cv[i])
|
| 390 |
+
x = x + ca.out_proj(o.transpose(1, 2).reshape(x.shape[0], n, d))
|
| 391 |
+
x = x + layer._ff_block(layer.norm3(x))
|
| 392 |
+
return self.model.dec_norm(x)
|
chartgen/plan_decide.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Decisive triplet plans from planner v3's per-bar output (v7, item 1).
|
| 2 |
+
|
| 3 |
+
Planner v3 ranks triplet bars well, but its triplet output is an expected value (P(triplet bar) x share), so
|
| 4 |
+
true triplet bars get small values that the generator, trained on human plans, mostly ignores. Here the
|
| 5 |
+
ranking makes the decision: a played bar whose triplet output exceeds the threshold gets the triplet share,
|
| 6 |
+
1/8 share and gap histogram of an average human triplet bar of the same tier (training charts); other bars
|
| 7 |
+
get triplet share 0. Play, density, big-note share and rolls are kept from v3.
|
| 8 |
+
|
| 9 |
+
python -m chartgen.plan_decide --rows rows.pkl --plans plans_base.pkl --threshold 0.2 --out plans_trip.pkl
|
| 10 |
+
|
| 11 |
+
--roll-objects (v9.1): rolls and balloons as objects. In decided plans (song_planner --predict) roll starts and sustained
|
| 12 |
+
measures are separate yes/no decisions, so a sustained measure that follows no start can appear on its own; the rest
|
| 13 |
+
mask then lets the generator start a new roll there (too many rolls). Here sustain is kept only in the run that
|
| 14 |
+
follows a roll start (the start measure and the following sustained measures, until a measure is not sustained or
|
| 15 |
+
another roll starts). Nothing else changes.
|
| 16 |
+
python -m chartgen.plan_decide --roll-objects --plans plans_val_t0.5.pkl --out plans_val_t0.5_obj.pkl
|
| 17 |
+
"""
|
| 18 |
+
import argparse
|
| 19 |
+
import pickle
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
|
| 23 |
+
from .dataset import BAR_F, GAP0, SUSTAIN, plan_active
|
| 24 |
+
from .gapstats import N_GAP_BINS
|
| 25 |
+
|
| 26 |
+
TRIP, EIGHTH = 4, 5 # plan columns: play, density, big, roll start, triplet, 1/8, gap histogram (10), sustain
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def roll_objects(pl: np.ndarray) -> np.ndarray:
|
| 30 |
+
"""Keep sustain only in measures reached from a roll start through consecutive sustained measures."""
|
| 31 |
+
pl = pl.copy()
|
| 32 |
+
keep = np.zeros(len(pl), bool)
|
| 33 |
+
k = 0
|
| 34 |
+
while k < len(pl):
|
| 35 |
+
if pl[k, 3] > 0.5:
|
| 36 |
+
keep[k] = True
|
| 37 |
+
j = k + 1
|
| 38 |
+
while j < len(pl) and pl[j, SUSTAIN] > 0.1 and pl[j, 3] <= 0.5:
|
| 39 |
+
keep[j] = True
|
| 40 |
+
j += 1
|
| 41 |
+
k = j
|
| 42 |
+
else:
|
| 43 |
+
k += 1
|
| 44 |
+
pl[~keep, SUSTAIN] = 0.0
|
| 45 |
+
return pl
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def main(argv=None):
|
| 49 |
+
p = argparse.ArgumentParser()
|
| 50 |
+
p.add_argument("--roll-objects", action="store_true", help="only make rolls objects (see module doc); no triplet change")
|
| 51 |
+
p.add_argument("--rows")
|
| 52 |
+
p.add_argument("--plans", required=True)
|
| 53 |
+
p.add_argument("--threshold", type=float, default=0.2)
|
| 54 |
+
p.add_argument("--rate", type=float, default=0.0,
|
| 55 |
+
help="instead of --threshold: flag this share of played bars (highest triplet output first)")
|
| 56 |
+
p.add_argument("--keep-others", action="store_true", help="leave unflagged bars at v3's value instead of 0")
|
| 57 |
+
p.add_argument("--out", required=True)
|
| 58 |
+
a = p.parse_args(argv)
|
| 59 |
+
if a.roll_objects:
|
| 60 |
+
plans = pickle.load(open(a.plans, "rb"))
|
| 61 |
+
out = {k: (b0, roll_objects(pl).astype(np.float32)) for k, (b0, pl) in plans.items()}
|
| 62 |
+
before = sum(int((pl[:, SUSTAIN] > 0.1).sum()) for _, pl in plans.values())
|
| 63 |
+
after = sum(int((pl[:, SUSTAIN] > 0.1).sum()) for _, pl in out.values())
|
| 64 |
+
starts = sum(int((pl[:, 3] > 0.5).sum()) for _, pl in plans.values())
|
| 65 |
+
orphan = sum(int(((pl[:, SUSTAIN] > 0.1) & (pl[:, 3] <= 0.5) & ~np.r_[False, (pl[:-1, 3] > 0.5) | (pl[:-1, SUSTAIN] > 0.1)]).sum()) for _, pl in plans.values())
|
| 66 |
+
pickle.dump(out, open(a.out, "wb"))
|
| 67 |
+
print(f"charts {len(out)}: roll starts {starts}; sustained measures {before} -> {after}; orphan runs started without a roll {orphan}")
|
| 68 |
+
return
|
| 69 |
+
rows = pickle.load(open(a.rows, "rb"))
|
| 70 |
+
proto = {}
|
| 71 |
+
for t in range(5):
|
| 72 |
+
P = np.concatenate([x[1] for x in rows["train"] if x[2] == t])
|
| 73 |
+
y = (P[:, 0] > 0.5) & (P[:, TRIP] > 0.3)
|
| 74 |
+
proto[t] = P[y].mean(0)
|
| 75 |
+
tier = {(x[3][0], x[3][1]): x[2] for part in ("train", "val") for x in rows[part]}
|
| 76 |
+
plans = pickle.load(open(a.plans, "rb"))
|
| 77 |
+
if a.rate:
|
| 78 |
+
v = np.concatenate([pl[pl[:, 0] > 0.5, TRIP] for _, pl in plans.values()])
|
| 79 |
+
a.threshold = float(np.quantile(v, 1 - a.rate))
|
| 80 |
+
print("threshold for rate", a.rate, "=", round(a.threshold, 4))
|
| 81 |
+
out, n_play, n_sel = {}, 0, 0
|
| 82 |
+
for k, (b0, pl) in plans.items():
|
| 83 |
+
pl = pl.copy()
|
| 84 |
+
play = pl[:, 0] > 0.5
|
| 85 |
+
sel = play & (pl[:, TRIP] > a.threshold)
|
| 86 |
+
if not a.keep_others:
|
| 87 |
+
pl[play & ~sel, TRIP] = 0.0
|
| 88 |
+
pr = proto[tier[k]]
|
| 89 |
+
pl[sel, TRIP] = pr[TRIP]
|
| 90 |
+
pl[sel, EIGHTH] = pr[EIGHTH]
|
| 91 |
+
pl[sel, GAP0:GAP0 + N_GAP_BINS] = pr[GAP0:GAP0 + N_GAP_BINS]
|
| 92 |
+
out[k] = (b0, pl.astype(np.float32))
|
| 93 |
+
n_play += play.sum(); n_sel += sel.sum()
|
| 94 |
+
pickle.dump(out, open(a.out, "wb"))
|
| 95 |
+
print(f"charts {len(out)} played bars {n_play} triplet bars {n_sel} ({n_sel / max(n_play, 1):.4f})")
|
| 96 |
+
for t in range(5):
|
| 97 |
+
print(t, "triplet prototype", np.round(proto[t][TRIP:], 3))
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
if __name__ == "__main__":
|
| 101 |
+
main()
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def prototypes(rows) -> dict:
|
| 105 |
+
"""Per tier: mean plan of training measures with triplets (share > 0.3) and with 1/8-or-finer notes (> 0.25)."""
|
| 106 |
+
out = {}
|
| 107 |
+
for t in range(5):
|
| 108 |
+
P = np.concatenate([x[1] for x in rows["train"] if x[2] == t])
|
| 109 |
+
hit = P[:, 0] > 0.5
|
| 110 |
+
out[t] = {"triplet": P[hit & (P[:, TRIP] > 0.3)].mean(0), "eighth": P[hit & (P[:, EIGHTH] > 0.25)].mean(0)}
|
| 111 |
+
return out
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def count_then_place(o: np.ndarray, settings: np.ndarray, tier: int, protos: dict, th_sus: float, floor: float = 0.9,
|
| 115 |
+
max_sustain: int = 4, sure_rest: float = 0.0, rest_band: tuple | None = None,
|
| 116 |
+
rest_weight: float = 3.0, guide: np.ndarray | None = None, rng=None) -> tuple[np.ndarray, dict]:
|
| 117 |
+
"""v10a decoding: chart settings (amounts) decide HOW MANY, the planner's per-measure scores decide WHERE.
|
| 118 |
+
|
| 119 |
+
o: raw planner output [n, BAR_F] (logits for play / shares / roll / sustain, density value, gap logits);
|
| 120 |
+
settings: raw values of latent_stats.chart_settings[:6] (inside-rest share, roll starts per active measure,
|
| 121 |
+
triplet and 1/8 measure shares of hit measures, big-note share, mean log density).
|
| 122 |
+
guide: the decided plan of the next harder tier of the same mapset, on the same measures (v10c). Human mapsets
|
| 123 |
+
keep rolls at the same places across tiers and an easier tier keeps the harder tier's rests (adjacent-tier
|
| 124 |
+
rest / roll F1 about 0.8): its roll starts are placed first, and its rests stay rests unless the music is sure
|
| 125 |
+
the measure is played (calibrated P(rest) <= lo). The amounts still come from the settings.
|
| 126 |
+
rng (v10d): places are SAMPLED instead of taken from the top of the ranking. k places are drawn without replacement
|
| 127 |
+
with weights from the calibrated probabilities (Gumbel-top-k on the logits), and a rest the music is sure about
|
| 128 |
+
(P >= hi) is a rest with that probability, not always. A draw then varies like another team of mappers instead
|
| 129 |
+
of repeating the most likely layout (distribution evaluation: draw-to-draw rest agreement far above two human
|
| 130 |
+
teams).
|
| 131 |
+
Returns the decided plan and a log of requested vs placed counts."""
|
| 132 |
+
sig = lambda v: 1 / (1 + np.exp(-v)) # noqa: E731
|
| 133 |
+
n = len(o)
|
| 134 |
+
p_play, p_roll, p_sus = sig(o[:, 0]), sig(o[:, 3]), sig(o[:, SUSTAIN])
|
| 135 |
+
trip, eighth, big = sig(o[:, TRIP]), sig(o[:, EIGHTH]), sig(o[:, 2])
|
| 136 |
+
dens = np.maximum(o[:, 1], 0.05)
|
| 137 |
+
g = np.exp(o[:, GAP0:GAP0 + N_GAP_BINS] - o[:, GAP0:GAP0 + N_GAP_BINS].max(1, keepdims=True))
|
| 138 |
+
gap = g / g.sum(1, keepdims=True)
|
| 139 |
+
r_rest, r_roll, r_trip, r_eighth, r_big, r_dens = [float(x) for x in settings[:6]]
|
| 140 |
+
act0 = p_play > 0.5
|
| 141 |
+
if not act0.any():
|
| 142 |
+
act0[np.argmax(p_play)] = True
|
| 143 |
+
idx = np.where(act0)[0]
|
| 144 |
+
inside = np.zeros(n, bool)
|
| 145 |
+
inside[idx.min(): idx.max() + 1] = True
|
| 146 |
+
log = {}
|
| 147 |
+
# rolls / balloons as objects: k starts by score inside the chart, each followed by its sustained run
|
| 148 |
+
start = np.zeros(n, bool); sus = np.zeros(n, bool)
|
| 149 |
+
k_roll = int(round(r_roll * inside.sum()))
|
| 150 |
+
g_start = (guide[:, 3] > 0.5) if guide is not None else np.zeros(n, bool)
|
| 151 |
+
g_rest = (~plan_active(guide) & inside) if guide is not None else np.zeros(n, bool)
|
| 152 |
+
# roll starts stay ranked even when sampling: sampled starts varied far more between draws than two human teams'
|
| 153 |
+
# rolls do (plan level, modern validation: roll-start F1 between draws 0.12, human cross-team cap about 0.4)
|
| 154 |
+
for j in np.argsort(-(p_roll + g_start)):
|
| 155 |
+
if start.sum() >= k_roll:
|
| 156 |
+
break
|
| 157 |
+
if not inside[j] or start[max(j - 1, 0): j + 2].any() or sus[j]:
|
| 158 |
+
continue
|
| 159 |
+
start[j] = True
|
| 160 |
+
m = j + 1
|
| 161 |
+
while m < n and m - j <= max_sustain and inside[m] and p_sus[m] >= th_sus and not start[m]:
|
| 162 |
+
sus[m] = True
|
| 163 |
+
m += 1
|
| 164 |
+
log["roll"] = (k_roll, int(start.sum()))
|
| 165 |
+
if rest_band is not None:
|
| 166 |
+
# The planner was trained with rest measures weighted rest_weight times, which multiplies its rest odds by that
|
| 167 |
+
# weight; undo it. Then the music decides the measures it is sure about (calibrated P(rest) >= hi: rest;
|
| 168 |
+
# <= lo: not a rest) and the drawn amount only decides the uncertain ones between.
|
| 169 |
+
q = 1 - p_play
|
| 170 |
+
q = q / (q + rest_weight * (1 - q))
|
| 171 |
+
lo, hi = rest_band
|
| 172 |
+
cand = inside & ~start & ~sus
|
| 173 |
+
hi_ok = (q >= hi) if rng is None else (q >= hi) & (rng.random(n) < q)
|
| 174 |
+
sure = cand & (hi_ok | (g_rest & (q > lo)))
|
| 175 |
+
mid = np.where(cand & ~sure & (q > lo) & (q < hi))[0]
|
| 176 |
+
k_rest = int(round(r_rest * inside.sum()))
|
| 177 |
+
rest = sure.copy()
|
| 178 |
+
extra = max(k_rest - int(sure.sum()), 0)
|
| 179 |
+
rest[mid[np.argsort(-_keys(q[mid], rng))][:extra]] = True
|
| 180 |
+
log["rest"] = (k_rest, int(rest.sum()))
|
| 181 |
+
play = (inside & ~rest & ~sus) | (~inside & act0) | (start & (p_play > 0.5))
|
| 182 |
+
return _finish(n, play, rest, start, sus, dens, big, gap, trip, eighth, p_sus, r_trip, r_eighth, r_big, r_dens, tier, protos, log, rng)
|
| 183 |
+
# rests: the k inside measures (not taken by a roll) with the lowest P(play), never one with P(play) >= floor.
|
| 184 |
+
# Measures the planner is sure about (P(play) < sure_rest) are rests whatever k is: the music decides those
|
| 185 |
+
# (independent human mapsets agree on the big breaks); the drawn amount decides the uncertain ones.
|
| 186 |
+
k_rest = int(round(r_rest * inside.sum()))
|
| 187 |
+
k_rest = max(k_rest, int((inside & ~start & ~sus & (p_play < sure_rest)).sum()))
|
| 188 |
+
elig = np.where(inside & ~start & ~sus & (p_play < floor))[0]
|
| 189 |
+
rest = np.zeros(n, bool)
|
| 190 |
+
rest[elig[np.argsort(p_play[elig] - g_rest[elig])][:k_rest]] = True
|
| 191 |
+
log["rest"] = (k_rest, int(rest.sum()))
|
| 192 |
+
play = (inside & ~rest & ~sus) | (~inside & act0) | (start & (p_play > 0.5))
|
| 193 |
+
return _finish(n, play, rest, start, sus, dens, big, gap, trip, eighth, p_sus, r_trip, r_eighth, r_big, r_dens, tier, protos, log, rng)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _keys(p: np.ndarray, rng=None) -> np.ndarray:
|
| 197 |
+
"""Sort keys: the probability itself (deterministic ranking), or with rng the logit plus Gumbel noise, so that the
|
| 198 |
+
top k are a draw without replacement with weights p / (1 - p) (Gumbel-top-k)."""
|
| 199 |
+
if rng is None:
|
| 200 |
+
return np.asarray(p, np.float64)
|
| 201 |
+
p = np.clip(np.asarray(p, np.float64), 1e-6, 1 - 1e-6)
|
| 202 |
+
return np.log(p / (1 - p)) + rng.gumbel(size=p.shape)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def _finish(n, play, rest, start, sus, dens, big, gap, trip, eighth, p_sus, r_trip, r_eighth, r_big, r_dens, tier, protos, log,
|
| 206 |
+
rng=None):
|
| 207 |
+
plan = np.zeros((n, BAR_F), np.float32)
|
| 208 |
+
plan[:, 0] = play
|
| 209 |
+
plan[:, 1] = dens
|
| 210 |
+
plan[:, 2] = big
|
| 211 |
+
plan[:, GAP0:GAP0 + N_GAP_BINS] = gap
|
| 212 |
+
hit = np.where(play)[0]
|
| 213 |
+
# triplet and 1/8 measures: top-k by the planner's output among hit measures, filled with the tier's prototype
|
| 214 |
+
for col, rate, key in ((TRIP, r_trip, "triplet"), (EIGHTH, r_eighth, "eighth")):
|
| 215 |
+
k = int(round(rate * len(hit)))
|
| 216 |
+
sel = hit[np.argsort(-_keys((trip if col == TRIP else eighth)[hit], rng))][:k]
|
| 217 |
+
plan[:, col] = 0.0
|
| 218 |
+
pr = protos[tier][key]
|
| 219 |
+
plan[sel, col] = pr[col]
|
| 220 |
+
plan[sel, GAP0:GAP0 + N_GAP_BINS] = pr[GAP0:GAP0 + N_GAP_BINS]
|
| 221 |
+
if col == TRIP:
|
| 222 |
+
plan[sel, EIGHTH] = np.maximum(plan[sel, EIGHTH], 0.0)
|
| 223 |
+
log[key] = (k, len(sel))
|
| 224 |
+
# big-note share and density: shift so the chart means match the requested values
|
| 225 |
+
if len(hit):
|
| 226 |
+
plan[hit, 2] = np.clip(plan[hit, 2] + (r_big - plan[hit, 2].mean()), 0, 1)
|
| 227 |
+
plan[hit, 1] = np.maximum(plan[hit, 1] + (r_dens - plan[hit, 1].mean()), 0.05)
|
| 228 |
+
plan[:, 3] = start
|
| 229 |
+
plan[:, SUSTAIN] = np.where(start | sus, np.maximum(p_sus, 0.5), 0.0)
|
| 230 |
+
hit_cols = [1, 2, TRIP, EIGHTH] + list(range(GAP0, GAP0 + N_GAP_BINS))
|
| 231 |
+
plan[np.ix_(~play, hit_cols)] = 0.0
|
| 232 |
+
return plan, log
|
chartgen/prep.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Turn audio shards + .osu files into training records.
|
| 2 |
+
|
| 3 |
+
One output file per input shard: ``{shard}.pkl`` holding a list of songs:
|
| 4 |
+
|
| 5 |
+
{"beatmapset_id", "song_key", "mel": float16 [frames, 128],
|
| 6 |
+
"charts": [{"beatmap_id", "tier", "star_rating", "year",
|
| 7 |
+
"sections": float64 [n, 5] (time_ms, beat_length_ms, meter, start_beat, omit_barline),
|
| 8 |
+
"kiai": float64 [k, 2] (start_ms, end_ms),
|
| 9 |
+
"time", "beat", "type", "length_beats", "delta_ms", "sv": per-note arrays}]}
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import re
|
| 16 |
+
import json
|
| 17 |
+
import pickle
|
| 18 |
+
import tarfile
|
| 19 |
+
from collections import defaultdict
|
| 20 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
import pyarrow.parquet as pq
|
| 25 |
+
|
| 26 |
+
from .data.osu import OsuParseError, parse_osu_file
|
| 27 |
+
from .features import decode_audio, log_mel
|
| 28 |
+
|
| 29 |
+
TIER_INDEX = {"kantan": 0, "futsuu": 1, "muzukashii": 2, "oni": 3, "inner_oni": 4}
|
| 30 |
+
_KEY_TAGS = re.compile(r"\((tv|short|game|cut|full|movie|op|ed)[^)]*\)|\[[^\]]*\]", re.I)
|
| 31 |
+
_KEY_PUNCT = re.compile(r"[^0-9a-z\u3040-\u30ff\u4e00-\u9fff]+")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def song_key(artist: str, title: str) -> str:
|
| 35 |
+
"""Normalised artist|title used to keep different mapsets of one song in the same split."""
|
| 36 |
+
norm = lambda s: _KEY_PUNCT.sub("", _KEY_TAGS.sub("", (s or "").lower())) # noqa: E731
|
| 37 |
+
return f"{norm(artist)}|{norm(title)}"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def chart_record(chart, row) -> dict | None:
|
| 41 |
+
if not chart.notes:
|
| 42 |
+
return None
|
| 43 |
+
n = chart.notes
|
| 44 |
+
return {
|
| 45 |
+
"beatmap_id": row["beatmap_id"],
|
| 46 |
+
"tier": TIER_INDEX[row["tier"]],
|
| 47 |
+
"star_rating": row["star_rating"],
|
| 48 |
+
"year": int((row["approved_date"] or "0")[:4] or 0),
|
| 49 |
+
"sections": np.array([[s.time, s.beat_length, s.meter, s.start_beat, float(_omit(chart, s))] for s in chart.sections], dtype=np.float64),
|
| 50 |
+
"kiai": np.array([[a, b] for a, b in chart.kiai], dtype=np.float64).reshape(-1, 2),
|
| 51 |
+
"time": np.array([x.time for x in n], dtype=np.float64),
|
| 52 |
+
"beat": np.array([x.beat for x in n], dtype=np.float64),
|
| 53 |
+
"type": np.array([int(x.type) for x in n], dtype=np.int8),
|
| 54 |
+
"length_beats": np.array([x.length_beats for x in n], dtype=np.float32),
|
| 55 |
+
"delta_ms": np.array([x.delta_ms for x in n], dtype=np.float32),
|
| 56 |
+
"sv": np.array([x.sv for x in n], dtype=np.float32),
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _omit(chart, section) -> bool:
|
| 61 |
+
return any(tp.uninherited and tp.time == section.time and tp.omit_barline for tp in chart.timing_points)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def read_shard(path: Path) -> dict[int, tuple[dict, dict[str, bytes]]]:
|
| 65 |
+
out: dict[int, tuple[dict, dict[str, bytes]]] = {}
|
| 66 |
+
files: dict[str, dict[str, bytes]] = defaultdict(dict)
|
| 67 |
+
metas: dict[str, dict] = {}
|
| 68 |
+
with tarfile.open(path) as tf:
|
| 69 |
+
for m in tf:
|
| 70 |
+
if not m.isfile():
|
| 71 |
+
continue
|
| 72 |
+
key, _, suffix = m.name.partition(".")
|
| 73 |
+
data = tf.extractfile(m).read()
|
| 74 |
+
if suffix == "json":
|
| 75 |
+
metas[key] = json.loads(data)
|
| 76 |
+
else:
|
| 77 |
+
files[key][suffix] = data
|
| 78 |
+
for key, meta in metas.items():
|
| 79 |
+
out[int(key)] = (meta, files.get(key, {}))
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def process_shard(shard: Path, catalog: Path, osu_dir: Path, out_dir: Path, workers: int = 4, device: str = "cpu") -> Path:
|
| 84 |
+
rows = pq.read_table(catalog / "taiko_beatmaps.parquet").to_pylist()
|
| 85 |
+
by_set = defaultdict(list)
|
| 86 |
+
for r in rows:
|
| 87 |
+
by_set[r["beatmapset_id"]].append(r)
|
| 88 |
+
sets = read_shard(shard)
|
| 89 |
+
|
| 90 |
+
def one(item):
|
| 91 |
+
set_id, (meta, files) = item
|
| 92 |
+
member_by_name = {a["name"]: a["member"] for a in meta["audio"]}
|
| 93 |
+
charts_by_audio = defaultdict(list)
|
| 94 |
+
for row in by_set.get(set_id, []):
|
| 95 |
+
try:
|
| 96 |
+
chart = parse_osu_file(osu_dir / f"{row['beatmap_id']}.osu")
|
| 97 |
+
except (OsuParseError, OSError, ValueError):
|
| 98 |
+
continue
|
| 99 |
+
if chart.mode != 1:
|
| 100 |
+
continue
|
| 101 |
+
rec = chart_record(chart, row)
|
| 102 |
+
member = member_by_name.get(chart.audio_filename)
|
| 103 |
+
if rec is not None and member in files:
|
| 104 |
+
charts_by_audio[member].append(rec)
|
| 105 |
+
songs = []
|
| 106 |
+
for member, charts in charts_by_audio.items():
|
| 107 |
+
mel = log_mel(decode_audio(files[member]), device=device)
|
| 108 |
+
row0 = by_set[set_id][0]
|
| 109 |
+
songs.append({"beatmapset_id": set_id, "song_key": song_key(row0["artist"], row0["title"]),
|
| 110 |
+
"audio_member": member, "mel": mel, "charts": charts})
|
| 111 |
+
return songs
|
| 112 |
+
|
| 113 |
+
with ThreadPoolExecutor(workers) as ex:
|
| 114 |
+
songs = [s for batch in ex.map(one, sets.items()) for s in batch]
|
| 115 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 116 |
+
out = out_dir / (shard.stem + ".pkl")
|
| 117 |
+
with open(out, "wb") as f:
|
| 118 |
+
pickle.dump(songs, f, protocol=pickle.HIGHEST_PROTOCOL)
|
| 119 |
+
return out
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def main(argv=None):
|
| 123 |
+
p = argparse.ArgumentParser()
|
| 124 |
+
p.add_argument("shards", nargs="+", type=Path)
|
| 125 |
+
p.add_argument("--catalog", type=Path, default=Path("data/catalog"))
|
| 126 |
+
p.add_argument("--osu-dir", type=Path, required=True)
|
| 127 |
+
p.add_argument("--out", type=Path, default=Path("data/features"))
|
| 128 |
+
p.add_argument("--workers", type=int, default=4)
|
| 129 |
+
p.add_argument("--device", default="cpu")
|
| 130 |
+
a = p.parse_args(argv)
|
| 131 |
+
for s in a.shards:
|
| 132 |
+
out = process_shard(s, a.catalog, a.osu_dir, a.out, a.workers, a.device)
|
| 133 |
+
print(out)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
if __name__ == "__main__":
|
| 137 |
+
main()
|
chartgen/rhythm_eval.py
ADDED
|
@@ -0,0 +1,461 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Rhythm-following metrics: does a chart's rhythm follow its song the way a human chart of that song does?
|
| 2 |
+
|
| 3 |
+
uv run python -m chartgen.rhythm_eval --out reports/figs/rhythm_eval.json
|
| 4 |
+
|
| 5 |
+
Definitions are pre-registered in reports/節奏跟隨指標設計(草案).md, section 5. Everything is compared on one beat
|
| 6 |
+
grid, the reference mapset's timing (the timing the AI used); a second human team's notes are first moved onto that
|
| 7 |
+
time axis with disteval's alignment (offset_ms). Note positions are snapped to the 1/48-beat grid; hit notes only.
|
| 8 |
+
|
| 9 |
+
A subdivision mix: share of hit notes per subdivision class (beat, 1/2, 1/3, 1/4, 1/6, 1/8, 1/12, 1/16, finer);
|
| 10 |
+
total variation distance between one candidate chart and the reference chart of the same tier.
|
| 11 |
+
B beat patterns (the set of 1/48 positions of the hit notes inside one beat):
|
| 12 |
+
foreign share of the candidate's beats whose pattern occurs in no tier of the reference mapset;
|
| 13 |
+
missing share of the reference chart's beats whose pattern the candidate chart of the same tier never uses.
|
| 14 |
+
D rhythm profile = subdivision mix (9) + gap mix (12 gap classes); distance = mean of the two TVs.
|
| 15 |
+
D1 identification: share of other songs whose reference is farther from the candidate than its own song's
|
| 16 |
+
reference (0.5 = guessing, 1 = always picks its own song);
|
| 17 |
+
D2 spread ratio: mean distance between candidates of different songs / the same for the references;
|
| 18 |
+
D3 per profile entry: across-song slope and correlation of the candidate on the reference.
|
| 19 |
+
Human floor: songs outside the test split with two or more independent teams (different mappers, lined up in time);
|
| 20 |
+
the main team is the reference, every other team a candidate. Threshold = 95th percentile of the floor per tier.
|
| 21 |
+
AI: each draw is judged on its own; the flag rate is the mean over draws, then over songs. Tempo-only baseline:
|
| 22 |
+
mean profile of training charts of the tier whose main BPM is within 10% of the song's.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import argparse
|
| 28 |
+
import hashlib
|
| 29 |
+
import json
|
| 30 |
+
import pickle
|
| 31 |
+
from collections import Counter, defaultdict
|
| 32 |
+
from pathlib import Path
|
| 33 |
+
|
| 34 |
+
import numpy as np
|
| 35 |
+
|
| 36 |
+
from . import disteval as de
|
| 37 |
+
from .dataset import DIVISORS, GRID, _beats_at, subdiv_class
|
| 38 |
+
from .train import song_split
|
| 39 |
+
|
| 40 |
+
REPO = Path(__file__).resolve().parents[2]
|
| 41 |
+
TNAMES = ["Kantan", "Futsuu", "Muzukashii", "Oni", "Inner Oni"]
|
| 42 |
+
N_SUB = len(DIVISORS) + 1
|
| 43 |
+
SUB_NAMES = [f"1/{d}" if d > 1 else "beat" for d in DIVISORS] + ["finer"]
|
| 44 |
+
GAP_VALUES = [1 / 6, 1 / 4, 1 / 3, 1 / 2, 2 / 3, 3 / 4, 1.0, 1.5, 2.0]
|
| 45 |
+
GAP_NAMES = ["<=1/8", "1/6", "1/4", "1/3", "1/2", "2/3", "3/4", "1", "3/2", "2", ">2", "other"]
|
| 46 |
+
MIN_HITS = 30
|
| 47 |
+
SYSTEMS = {"v9.1": "evalgen_v91/mapsets_AI_v9.1.pkl", "v10c": "evalgen_v10c/mapsets_AI_v10c.pkl"}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# ---------------------------------------------------------------- per-chart features
|
| 51 |
+
|
| 52 |
+
def hit_grid(chart: dict, sections, offset: float = 0.0) -> np.ndarray:
|
| 53 |
+
"""Hit-note positions on `sections`' beat grid, as 1/48-beat indices (sorted, unique)."""
|
| 54 |
+
t = np.asarray(chart["time"], np.float64) + offset
|
| 55 |
+
ty = np.asarray(chart["type"])
|
| 56 |
+
t = np.sort(t[ty <= 3])
|
| 57 |
+
if len(t) == 0:
|
| 58 |
+
return np.zeros(0, np.int64)
|
| 59 |
+
return np.unique(np.round(_beats_at(np.asarray(sections, np.float64), t) * GRID).astype(np.int64))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def sub_mix(g: np.ndarray) -> np.ndarray:
|
| 63 |
+
return np.bincount(subdiv_class(g), minlength=N_SUB)[:N_SUB] / max(len(g), 1)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def gap_mix(g: np.ndarray) -> np.ndarray:
|
| 67 |
+
d = np.diff(g) / GRID
|
| 68 |
+
k = np.full(len(d), len(GAP_NAMES) - 1)
|
| 69 |
+
k[d <= 1 / 8 + 1e-6] = 0
|
| 70 |
+
for i, v in enumerate(GAP_VALUES):
|
| 71 |
+
k[np.abs(d - v) < 1e-6] = i + 1
|
| 72 |
+
k[d > 2 + 1e-6] = len(GAP_NAMES) - 2
|
| 73 |
+
return np.bincount(k, minlength=len(GAP_NAMES)) / max(len(d), 1)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def patterns(g: np.ndarray) -> Counter:
|
| 77 |
+
beats = g // GRID
|
| 78 |
+
pos = g % GRID
|
| 79 |
+
out = Counter()
|
| 80 |
+
for b in np.unique(beats):
|
| 81 |
+
out[tuple(pos[beats == b].tolist())] += 1
|
| 82 |
+
return out
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def tv(a, b) -> float:
|
| 86 |
+
return 0.5 * float(np.abs(np.asarray(a) - np.asarray(b)).sum())
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def outside(pat: Counter, vocab) -> float:
|
| 90 |
+
n = sum(pat.values())
|
| 91 |
+
return sum(v for p, v in pat.items() if p not in vocab) / max(n, 1)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def profile(g):
|
| 95 |
+
return np.r_[sub_mix(g), gap_mix(g)]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def pdist(a, b) -> float:
|
| 99 |
+
return 0.5 * (tv(a[:N_SUB], b[:N_SUB]) + tv(a[N_SUB:], b[N_SUB:]))
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def pmat(P, Q) -> np.ndarray:
|
| 103 |
+
"""[len(P), len(Q)] profile distances (pdist for every pair)."""
|
| 104 |
+
P, Q = np.asarray(P), np.asarray(Q)
|
| 105 |
+
d = np.abs(P[:, None, :] - Q[None, :, :])
|
| 106 |
+
return 0.25 * (d[..., :N_SUB].sum(-1) + d[..., N_SUB:].sum(-1))
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def main_bpm(sections) -> float:
|
| 110 |
+
s = np.asarray(sections, np.float64)
|
| 111 |
+
if len(s) == 1:
|
| 112 |
+
return 60000 / s[0, 1]
|
| 113 |
+
span = np.diff(np.r_[s[:, 0], s[-1, 0] + 60000])
|
| 114 |
+
cover = defaultdict(float)
|
| 115 |
+
for bl, d in zip(np.round(s[:, 1], 3), span):
|
| 116 |
+
cover[bl] += d
|
| 117 |
+
return 60000 / max(cover, key=cover.get)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def common(cand_g, ref_g):
|
| 121 |
+
"""Both charts cut to the stretch where both have notes (whole beats), so a different cut of the song is not
|
| 122 |
+
counted as a different rhythm."""
|
| 123 |
+
lo = max(cand_g[0], ref_g[0]) // GRID * GRID
|
| 124 |
+
hi = (min(cand_g[-1], ref_g[-1]) // GRID + 1) * GRID
|
| 125 |
+
return cand_g[(cand_g >= lo) & (cand_g < hi)], ref_g[(ref_g >= lo) & (ref_g < hi)]
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def finer_share(grids) -> float:
|
| 129 |
+
g = np.concatenate(list(grids))
|
| 130 |
+
return float((subdiv_class(g) == N_SUB - 1).mean()) if len(g) else 0.0
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def ab(cand_g, ref_g, ref_vocab):
|
| 134 |
+
"""A, B foreign, B missing for one candidate chart against the reference chart of the same tier (common stretch)."""
|
| 135 |
+
cand_g, ref_g = common(cand_g, ref_g)
|
| 136 |
+
pc = patterns(cand_g)
|
| 137 |
+
return (tv(sub_mix(cand_g), sub_mix(ref_g)), outside(pc, ref_vocab), outside(patterns(ref_g), set(pc)))
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# ---------------------------------------------------------------- data
|
| 141 |
+
|
| 142 |
+
def mapset_grids(ms: dict, sections=None):
|
| 143 |
+
"""tier -> hit grid of a mapset ({tier: chart}); on `sections` (default: each chart's own) with its offset."""
|
| 144 |
+
out = {}
|
| 145 |
+
for t, c in ms.items():
|
| 146 |
+
g = hit_grid(c, c["sections"] if sections is None else sections, float(c.get("offset_ms", 0.0)))
|
| 147 |
+
if len(g) >= MIN_HITS:
|
| 148 |
+
out[int(t)] = g
|
| 149 |
+
return out
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def floor_pairs(E, cat, cache: Path):
|
| 153 |
+
"""[(song key, year, ref grids {tier: g}, cand grids {tier: g})] for every non-test song with independent teams."""
|
| 154 |
+
if cache.exists():
|
| 155 |
+
return pickle.load(open(cache, "rb"))
|
| 156 |
+
out = []
|
| 157 |
+
for split in ("train", "val"):
|
| 158 |
+
col = de.build_human_collection(E, modern_only=False, catalog=cat, split=split)
|
| 159 |
+
for key, v in col.items():
|
| 160 |
+
if len(v["human"]) < 2:
|
| 161 |
+
continue
|
| 162 |
+
ref = v["human"][0]
|
| 163 |
+
sec = ref[max(ref)]["sections"]
|
| 164 |
+
rg = mapset_grids(ref)
|
| 165 |
+
for j, ms in enumerate(v["human"][1:], 1):
|
| 166 |
+
cg = mapset_grids(ms, sec)
|
| 167 |
+
if set(rg) & set(cg):
|
| 168 |
+
out.append((key, v["meta"]["years"][0], rg, cg))
|
| 169 |
+
cache.parent.mkdir(parents=True, exist_ok=True)
|
| 170 |
+
pickle.dump(out, open(cache, "wb"))
|
| 171 |
+
return out
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def eval_songs(E, cat, sets):
|
| 175 |
+
"""set -> reference grids and the second teams lined up with it (when its collection's main team is this set)."""
|
| 176 |
+
by_id = {e["beatmapset_id"]: e for e in E}
|
| 177 |
+
out = {}
|
| 178 |
+
for s in sets:
|
| 179 |
+
e = by_id.get(s)
|
| 180 |
+
if e is None or song_split(e.get("song_key") or str(s)) == "test":
|
| 181 |
+
continue
|
| 182 |
+
ms = de._entry_mapset(e, cat)
|
| 183 |
+
rg = mapset_grids(ms)
|
| 184 |
+
if not rg:
|
| 185 |
+
continue
|
| 186 |
+
sec = ms[max(ms)]["sections"]
|
| 187 |
+
extra = []
|
| 188 |
+
col = de.build_human_collection(E, songs=[e.get("song_key") or str(s)], modern_only=True, catalog=cat,
|
| 189 |
+
split="val")
|
| 190 |
+
v = next(iter(col.values()), None)
|
| 191 |
+
if v and v["meta"]["beatmapset_ids"][0] == s:
|
| 192 |
+
extra = [mapset_grids(m, sec) for m in v["human"][1:]]
|
| 193 |
+
out[s] = {"ref": rg, "sec": sec, "bpm": main_bpm(sec), "extra": extra}
|
| 194 |
+
return out
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def tempo_bank(E):
|
| 198 |
+
"""tier -> (main BPMs, profiles) of training charts (one chart per tier per mapset)."""
|
| 199 |
+
bank = defaultdict(lambda: ([], []))
|
| 200 |
+
for e in E:
|
| 201 |
+
if song_split(e.get("song_key") or str(e["beatmapset_id"])) != "train":
|
| 202 |
+
continue
|
| 203 |
+
for t, c in de._entry_mapset(e, None).items():
|
| 204 |
+
g = hit_grid(c, c["sections"])
|
| 205 |
+
if len(g) >= MIN_HITS:
|
| 206 |
+
bank[int(t)][0].append(main_bpm(c["sections"]))
|
| 207 |
+
bank[int(t)][1].append(profile(g))
|
| 208 |
+
return {t: (np.array(b), np.stack(p)) for t, (b, p) in bank.items()}
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
# ---------------------------------------------------------------- corruptions (sensitivity)
|
| 212 |
+
|
| 213 |
+
def corrupt(g, kind, dose, rng, other=None):
|
| 214 |
+
g = g.copy()
|
| 215 |
+
pos = g % GRID
|
| 216 |
+
if kind == "binarize": # triplet-family notes moved to the nearest 1/4-beat position
|
| 217 |
+
cls = subdiv_class(g)
|
| 218 |
+
trip = np.isin(cls, [DIVISORS.index(3), DIVISORS.index(6), DIVISORS.index(12)])
|
| 219 |
+
sel = trip & (rng.random(len(g)) < dose)
|
| 220 |
+
g[sel] = (g[sel] // GRID) * GRID + np.round(pos[sel] / 12).astype(np.int64) * 12
|
| 221 |
+
elif kind == "drop_fine": # 1/8 and finer notes removed
|
| 222 |
+
fine = subdiv_class(g) >= DIVISORS.index(8)
|
| 223 |
+
g = g[~(fine & (rng.random(len(g)) < dose))]
|
| 224 |
+
elif kind == "shift": # off-beat notes moved by a quarter beat
|
| 225 |
+
sel = (pos != 0) & (rng.random(len(g)) < dose)
|
| 226 |
+
g[sel] = g[sel] + 12
|
| 227 |
+
elif kind == "swap": # another song's rhythm, placed from this chart's first note
|
| 228 |
+
g = other - other[0] + g[0]
|
| 229 |
+
return np.unique(g)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def eligible(g, kind):
|
| 233 |
+
cls = subdiv_class(g)
|
| 234 |
+
if kind == "binarize":
|
| 235 |
+
return np.isin(cls, [DIVISORS.index(3), DIVISORS.index(6), DIVISORS.index(12)]).mean() >= 0.05
|
| 236 |
+
if kind == "drop_fine":
|
| 237 |
+
return (cls >= DIVISORS.index(8)).mean() >= 0.02
|
| 238 |
+
return True
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
# ---------------------------------------------------------------- statistics
|
| 242 |
+
|
| 243 |
+
def boot_ci(per_song: np.ndarray, B: int, rng) -> tuple:
|
| 244 |
+
n = len(per_song)
|
| 245 |
+
idx = rng.integers(0, n, (B, n))
|
| 246 |
+
m = np.nanmean(per_song[idx], 1)
|
| 247 |
+
return float(np.nanmean(per_song)), float(np.nanpercentile(m, 2.5)), float(np.nanpercentile(m, 97.5))
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def d1_scores(cands, refs):
|
| 251 |
+
"""cands, refs: [n, P] profiles of the same n songs; per song the share of other songs' refs farther away."""
|
| 252 |
+
n = len(refs)
|
| 253 |
+
D = pmat(cands, refs)
|
| 254 |
+
own = np.diag(D)
|
| 255 |
+
return np.array([(D[i, np.arange(n) != i] > own[i]).mean() for i in range(n)]), D
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def d2_ratio(Dc, Dr, idx):
|
| 259 |
+
"""mean distance between candidates of different songs over the same for references, songs `idx` (resampled)."""
|
| 260 |
+
a, b = np.meshgrid(idx, idx, indexing="ij")
|
| 261 |
+
m = a != b
|
| 262 |
+
return Dc[a[m], b[m]].mean() / Dr[a[m], b[m]].mean()
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
# ---------------------------------------------------------------- main
|
| 266 |
+
|
| 267 |
+
def main():
|
| 268 |
+
ap = argparse.ArgumentParser()
|
| 269 |
+
ap.add_argument("--out", type=Path, default=REPO / "reports/figs/rhythm_eval.json")
|
| 270 |
+
ap.add_argument("--cache", type=Path, default=REPO / "data/eval/rhythm_floor_pairs.pkl")
|
| 271 |
+
ap.add_argument("--boot", type=int, default=1000)
|
| 272 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 273 |
+
a = ap.parse_args()
|
| 274 |
+
rng = np.random.default_rng(a.seed)
|
| 275 |
+
E = de.load_charts_all()
|
| 276 |
+
cat = de.load_catalog()
|
| 277 |
+
res = {"tiers": {}}
|
| 278 |
+
|
| 279 |
+
# ---- human floor
|
| 280 |
+
pairs = floor_pairs(E, cat, a.cache)
|
| 281 |
+
half = lambda k: int(hashlib.sha1(k.encode()).hexdigest(), 16) % 2 # noqa: E731
|
| 282 |
+
floor = defaultdict(list) # tier -> [(key, year, A, Bf, Bm, cand g, ref g)]
|
| 283 |
+
dropped = 0
|
| 284 |
+
for key, year, rg, cg in pairs:
|
| 285 |
+
both = sorted(set(rg) & set(cg))
|
| 286 |
+
# second team off the reference grid (timing not lined up, or another cut of the song): not a mapper difference
|
| 287 |
+
if finer_share(cg[t] for t in both) > finer_share(rg[t] for t in both) + 0.03:
|
| 288 |
+
dropped += 1
|
| 289 |
+
continue
|
| 290 |
+
vocab = set().union(*[set(patterns(g)) for g in rg.values()])
|
| 291 |
+
for t in both:
|
| 292 |
+
c2, r2 = common(cg[t], rg[t])
|
| 293 |
+
if len(c2) >= MIN_HITS and len(r2) >= MIN_HITS:
|
| 294 |
+
floor[t].append((key, year, *ab(cg[t], rg[t], vocab), c2, r2, vocab))
|
| 295 |
+
res["floor_pairs"] = {"all": len(pairs), "dropped_off_grid": dropped}
|
| 296 |
+
print(f"floor: {len(pairs)} team pairs, {dropped} dropped as off the reference grid; charts per tier " + ", ".join(f"{TNAMES[t]} {len(floor[t])}" for t in range(5)))
|
| 297 |
+
|
| 298 |
+
sets = [int(x) for x in open(REPO / "data/eval_modern_val_sets.txt").read().split()]
|
| 299 |
+
ev = eval_songs(E, cat, sets)
|
| 300 |
+
systems = {k: pickle.load(open(REPO / "data/hfruns/runs" / p, "rb")) for k, p in SYSTEMS.items()}
|
| 301 |
+
bank = tempo_bank(E)
|
| 302 |
+
print(f"eval songs with a reference: {len(ev)}; with a second team: {sum(1 for v in ev.values() if v['extra'])}")
|
| 303 |
+
|
| 304 |
+
for t in range(5):
|
| 305 |
+
F = floor[t]
|
| 306 |
+
if len(F) < 20:
|
| 307 |
+
continue
|
| 308 |
+
M = np.array([f[2:5] for f in F]) # [pairs, 3] A, Bf, Bm
|
| 309 |
+
thr = np.percentile(M, 95, axis=0)
|
| 310 |
+
r = {"floor_n": len(F), "floor_modern_n": int(sum(f[1] >= 2022 for f in F)),
|
| 311 |
+
"threshold": dict(zip(("A", "B_foreign", "B_missing"), thr.tolist())),
|
| 312 |
+
"floor_median": dict(zip(("A", "B_foreign", "B_missing"), np.median(M, 0).tolist()))}
|
| 313 |
+
# R1 specificity: thresholds from one half of the songs, flag rate on the other half
|
| 314 |
+
h = np.array([half(f[0]) for f in F])
|
| 315 |
+
spec = {}
|
| 316 |
+
for k in (0, 1):
|
| 317 |
+
th = np.percentile(M[h == k], 95, axis=0)
|
| 318 |
+
spec[f"half{1 - k}"] = ((M[h != k] > th).mean(0)).tolist()
|
| 319 |
+
r["specificity_false_flag"] = spec
|
| 320 |
+
# R2 sensitivity: corruptions of the held-out half's candidates, thresholds from the other half
|
| 321 |
+
th = np.percentile(M[h == 0], 95, axis=0)
|
| 322 |
+
sens = {}
|
| 323 |
+
test = [f for f, hh in zip(F, h) if hh == 1]
|
| 324 |
+
crng = np.random.default_rng(a.seed + 1)
|
| 325 |
+
for kind in ("binarize", "drop_fine", "shift", "swap"):
|
| 326 |
+
for dose in ((1.0,) if kind == "swap" else (0.25, 0.5, 1.0)):
|
| 327 |
+
flags, n = [], 0
|
| 328 |
+
for i, f in enumerate(test):
|
| 329 |
+
cg, rgt, vocab = f[5], f[6], f[7]
|
| 330 |
+
if not eligible(cg, kind):
|
| 331 |
+
continue
|
| 332 |
+
other = test[(i + 1 + crng.integers(len(test) - 1)) % len(test)][5] if kind == "swap" else None
|
| 333 |
+
g2 = corrupt(cg, kind, dose, crng, other)
|
| 334 |
+
if len(g2) < MIN_HITS:
|
| 335 |
+
continue
|
| 336 |
+
v = np.array(ab(g2, rgt, vocab))
|
| 337 |
+
flags.append(np.r_[v > th, (v > th).any()])
|
| 338 |
+
n += 1
|
| 339 |
+
if n:
|
| 340 |
+
sens[f"{kind}@{dose}"] = {"n": n, "flag_A": float(np.mean([x[0] for x in flags])),
|
| 341 |
+
"flag_Bf": float(np.mean([x[1] for x in flags])),
|
| 342 |
+
"flag_Bm": float(np.mean([x[2] for x in flags])),
|
| 343 |
+
"flag_any": float(np.mean([x[3] for x in flags]))}
|
| 344 |
+
r["sensitivity"] = sens
|
| 345 |
+
|
| 346 |
+
# ---- systems on the evaluation songs
|
| 347 |
+
songs = sorted(s for s in ev if t in ev[s]["ref"])
|
| 348 |
+
r["eval_n"] = len(songs)
|
| 349 |
+
refs = np.stack([profile(ev[s]["ref"][t]) for s in songs])
|
| 350 |
+
per = {}
|
| 351 |
+
Dr = pmat(refs, refs)
|
| 352 |
+
boot_idx = rng.integers(0, len(songs), (a.boot, len(songs)))
|
| 353 |
+
for sysn, d in systems.items():
|
| 354 |
+
vals = np.full((len(songs), 4, 3), np.nan)
|
| 355 |
+
profs = np.full((4, len(songs), refs.shape[1]), np.nan)
|
| 356 |
+
for i, s in enumerate(songs):
|
| 357 |
+
vocab = set().union(*[set(patterns(g)) for g in ev[s]["ref"].values()])
|
| 358 |
+
for k, dr in enumerate(d.get(s, {}).get("draws", [])[:4]):
|
| 359 |
+
c = dr["charts"].get(t)
|
| 360 |
+
if c is None:
|
| 361 |
+
continue
|
| 362 |
+
g = hit_grid(c, c["sections"])
|
| 363 |
+
if len(g) < MIN_HITS:
|
| 364 |
+
continue
|
| 365 |
+
vals[i, k] = ab(g, ev[s]["ref"][t], vocab)
|
| 366 |
+
profs[k, i] = profile(g)
|
| 367 |
+
flag = (vals > thr[None, None, :])
|
| 368 |
+
flag = np.where(np.isnan(vals), np.nan, flag)
|
| 369 |
+
fl_song = np.nanmean(flag, 1) # [songs, 3]
|
| 370 |
+
any_song = np.nanmean(np.where(np.isnan(vals[..., 0]), np.nan, flag.max(2)), 1)
|
| 371 |
+
ok = ~np.isnan(profs).any(2) # [4, songs]
|
| 372 |
+
d1 = np.full((4, len(songs)), np.nan)
|
| 373 |
+
Dcs = []
|
| 374 |
+
for k in range(4):
|
| 375 |
+
if ok[k].sum() < 20:
|
| 376 |
+
continue
|
| 377 |
+
sel = np.where(ok[k])[0]
|
| 378 |
+
sc, _ = d1_scores(profs[k, sel], refs[sel])
|
| 379 |
+
d1[k, sel] = sc
|
| 380 |
+
Dc = np.full((len(songs), len(songs)), np.nan)
|
| 381 |
+
Dc[np.ix_(sel, sel)] = pmat(profs[k, sel], profs[k, sel])
|
| 382 |
+
Dcs.append(Dc)
|
| 383 |
+
d1_song = np.nanmean(d1, 0)
|
| 384 |
+
Dc_mean = np.nanmean(np.stack(Dcs), 0)
|
| 385 |
+
okc = ~np.isnan(Dc_mean).all(1)
|
| 386 |
+
d2_point = d2_ratio(np.nan_to_num(Dc_mean, nan=np.nanmean(Dc_mean)), Dr, np.where(okc)[0])
|
| 387 |
+
d2_boot = [d2_ratio(np.nan_to_num(Dc_mean, nan=np.nanmean(Dc_mean)), Dr, bi[okc[bi]]) for bi in boot_idx]
|
| 388 |
+
# D3: per profile entry, across-song slope / correlation (draw-mean profile)
|
| 389 |
+
pm = np.nanmean(profs, 0)
|
| 390 |
+
d3 = {}
|
| 391 |
+
for j, name in enumerate([f"sub {x}" for x in SUB_NAMES] + [f"gap {x}" for x in GAP_NAMES]):
|
| 392 |
+
x, y = refs[:, j], pm[:, j]
|
| 393 |
+
m = ~np.isnan(y)
|
| 394 |
+
if x[m].std() > 1e-6 and y[m].std() > 1e-6:
|
| 395 |
+
d3[name] = {"slope": float(np.polyfit(x[m], y[m], 1)[0]), "corr": float(np.corrcoef(x[m], y[m])[0, 1]),
|
| 396 |
+
"human_mean": float(x[m].mean()), "ai_mean": float(y[m].mean())}
|
| 397 |
+
stat = lambda v: [float(np.nanmean(v)), float(np.nanpercentile(np.nanmean(v[boot_idx], 1), 2.5)), # noqa: E731
|
| 398 |
+
float(np.nanpercentile(np.nanmean(v[boot_idx], 1), 97.5))]
|
| 399 |
+
per[sysn] = {
|
| 400 |
+
"flag_A": stat(fl_song[:, 0]), "flag_Bf": stat(fl_song[:, 1]), "flag_Bm": stat(fl_song[:, 2]),
|
| 401 |
+
"flag_any": stat(any_song),
|
| 402 |
+
"mean_A": stat(np.nanmean(vals[..., 0], 1)), "mean_Bf": stat(np.nanmean(vals[..., 1], 1)),
|
| 403 |
+
"mean_Bm": stat(np.nanmean(vals[..., 2], 1)),
|
| 404 |
+
"D1": stat(d1_song), "D2": [float(d2_point), float(np.percentile(d2_boot, 2.5)), float(np.percentile(d2_boot, 97.5))],
|
| 405 |
+
"D3": d3,
|
| 406 |
+
"flagged": sorted([[int(s), float(fl_song[i, 0]), float(np.nanmean(vals[i, :, 0])), float(np.nanmean(vals[i, :, 1])),
|
| 407 |
+
float(np.nanmean(vals[i, :, 2]))] for i, s in enumerate(songs) if fl_song[i, 0] >= 0.5],
|
| 408 |
+
key=lambda x: -x[2]),
|
| 409 |
+
"_song": {"A": np.nanmean(vals[..., 0], 1), "flagA": fl_song[:, 0], "any": any_song, "D1": d1_song},
|
| 410 |
+
}
|
| 411 |
+
# paired differences v10c - v9.1
|
| 412 |
+
diff = {}
|
| 413 |
+
for key in ("A", "any", "D1"):
|
| 414 |
+
x = per["v10c"]["_song"][key] - per["v9.1"]["_song"][key]
|
| 415 |
+
diff[key] = stat(x)
|
| 416 |
+
diff["flag_A"] = stat(per["v10c"]["_song"]["flagA"] - per["v9.1"]["_song"]["flagA"])
|
| 417 |
+
for sysn in per:
|
| 418 |
+
per[sysn].pop("_song")
|
| 419 |
+
r["systems"] = per
|
| 420 |
+
r["v10c_minus_v91"] = diff
|
| 421 |
+
# tempo-only baseline
|
| 422 |
+
bb, bp = bank[t]
|
| 423 |
+
base = []
|
| 424 |
+
for s in songs:
|
| 425 |
+
m = np.abs(np.log(bb / ev[s]["bpm"])) < np.log(1.1)
|
| 426 |
+
base.append(bp[m].mean(0) if m.sum() >= 20 else bp[np.argsort(np.abs(np.log(bb / ev[s]["bpm"])))[:20]].mean(0))
|
| 427 |
+
base = np.stack(base)
|
| 428 |
+
bd1, _ = d1_scores(base, refs)
|
| 429 |
+
r["tempo_baseline"] = {"D1": stat(bd1), "mean_A": stat(np.array([tv(b[:N_SUB], x[:N_SUB]) for b, x in zip(base, refs)]))}
|
| 430 |
+
# human level for D1 / D2 on the floor pairs of this tier
|
| 431 |
+
fr = np.stack([profile(f[6]) for f in F])
|
| 432 |
+
fc = np.stack([profile(f[5]) for f in F])
|
| 433 |
+
keys = [f[0] for f in F]
|
| 434 |
+
first = {}
|
| 435 |
+
for i, k in enumerate(keys):
|
| 436 |
+
first.setdefault(k, i)
|
| 437 |
+
u = np.array(sorted(first.values())) # one pair per song
|
| 438 |
+
hd1, _ = d1_scores(fc[u], fr[u])
|
| 439 |
+
Dfr = pmat(fr[u], fr[u])
|
| 440 |
+
Dfc = pmat(fc[u], fc[u])
|
| 441 |
+
r["human_level"] = {"n_songs": int(len(u)), "D1": float(hd1.mean()),
|
| 442 |
+
"D2": float(d2_ratio(Dfc, Dfr, np.arange(len(u))))}
|
| 443 |
+
# second teams on the evaluation songs (sanity check of the floor on modern songs)
|
| 444 |
+
sec_vals = []
|
| 445 |
+
for s in songs:
|
| 446 |
+
vocab = set().union(*[set(patterns(g)) for g in ev[s]["ref"].values()])
|
| 447 |
+
for x in ev[s]["extra"]:
|
| 448 |
+
if t in x:
|
| 449 |
+
sec_vals.append(ab(x[t], ev[s]["ref"][t], vocab))
|
| 450 |
+
if sec_vals:
|
| 451 |
+
sv = np.array(sec_vals)
|
| 452 |
+
r["eval_second_teams"] = {"n": len(sv), "flag": (sv > thr).mean(0).tolist(), "mean": sv.mean(0).tolist()}
|
| 453 |
+
res["tiers"][TNAMES[t]] = r
|
| 454 |
+
print(f"done tier {TNAMES[t]}")
|
| 455 |
+
a.out.parent.mkdir(parents=True, exist_ok=True)
|
| 456 |
+
json.dump(res, open(a.out, "w"), ensure_ascii=False, indent=1)
|
| 457 |
+
print(f"wrote {a.out}")
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
if __name__ == "__main__":
|
| 461 |
+
main()
|
chartgen/rhythm_eval2.py
ADDED
|
@@ -0,0 +1,536 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Rhythm-following metrics, revision 2 (reports/節奏跟隨指標設計(草案).md, sections 6.6, 7 and 8).
|
| 2 |
+
|
| 3 |
+
uv run python -m chartgen.rhythm_eval2 --out reports/figs/rhythm_eval2.json
|
| 4 |
+
|
| 5 |
+
Every number is on its natural scale and shown next to the human value on the same footing.
|
| 6 |
+
|
| 7 |
+
Comparison of one candidate chart (an AI draw or a second human team) with the reference chart of the same song and
|
| 8 |
+
tier, on the reference timing and on the stretch where both have notes (rhythm_eval.common). Hit notes snapped to the
|
| 9 |
+
1/48-beat grid; a note less than 1 ms before a red line counts in the new section (AI times are not whole ms).
|
| 10 |
+
family distance sum over the family's classes of |cand share - ref share|; families: straight (beat, 1/2, 1/4),
|
| 11 |
+
triplet (1/3, 1/6, 1/12), fine (1/8, 1/16, finer)
|
| 12 |
+
B foreign / B missing as in rhythm_eval (patterns inside one beat)
|
| 13 |
+
density hits per beat; log ratio cand / ref
|
| 14 |
+
|
| 15 |
+
1. Pass rate: a song passes a test when its value is within the human floor's 95th percentile (per tier; for the
|
| 16 |
+
triplet and fine families per band of the reference's family share: < 2%, 2-5%, >= 5%). The floor is the
|
| 17 |
+
independent-team pairs outside the songs being scored, reweighted so that its density-ratio distribution matches
|
| 18 |
+
the AI's. Human reference: leave-one-song-out pass rate of the floor, and the pass rate of second teams on the
|
| 19 |
+
same-pool songs. AI: mean over draws, then over songs. CIs: floor songs and scored songs resampled together.
|
| 20 |
+
2. Song-following per family (and the gap mix): 1 - mean error / mean error of the tempo-only baseline (training
|
| 21 |
+
charts of the tier within 10% of the song's main BPM), on the same songs for AI and human (same pool) and for the
|
| 22 |
+
AI on all evaluation songs. 100% = identical to the reference; 0% = no better than the baseline.
|
| 23 |
+
3. Amount ratio per subdivision class: total share in the candidates / total share in the references, overall and
|
| 24 |
+
per tempo band (< 110, 110-170, >= 170 BPM).
|
| 25 |
+
4. Sensitivity (R2 rewritten): floor pairs, tiers 3 and 4 pooled, leave-one-song-out thresholds; only candidate notes
|
| 26 |
+
that sit on reference notes are corrupted, with one fixed random order per chart (nested doses); flag rate at
|
| 27 |
+
doses 0, 0.25, 0.5, 1 and the excess over dose 0.
|
| 28 |
+
Same pool: validation songs with an independent second team; the 395 evaluation sets plus the extra list
|
| 29 |
+
data/eval/floor_val_sets.txt (AI samples in runs/evalgen_floor_*).
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
from __future__ import annotations
|
| 33 |
+
|
| 34 |
+
import argparse
|
| 35 |
+
import json
|
| 36 |
+
import pickle
|
| 37 |
+
from collections import defaultdict
|
| 38 |
+
from pathlib import Path
|
| 39 |
+
|
| 40 |
+
import numpy as np
|
| 41 |
+
|
| 42 |
+
from . import disteval as de
|
| 43 |
+
from .dataset import DIVISORS, GRID, subdiv_class
|
| 44 |
+
from .rhythm_eval import (GAP_NAMES, MIN_HITS, N_SUB, SUB_NAMES, TNAMES, common, finer_share, floor_pairs, gap_mix,
|
| 45 |
+
main_bpm, outside, patterns, sub_mix, tempo_bank)
|
| 46 |
+
|
| 47 |
+
REPO = Path(__file__).resolve().parents[2]
|
| 48 |
+
FAM = {"straight": [0, 1, 3], "triplet": [2, 4, 6], "fine": [5, 7, 8]}
|
| 49 |
+
BANDED = ("triplet", "fine")
|
| 50 |
+
TESTS = ("straight", "triplet", "fine", "B_foreign", "B_missing")
|
| 51 |
+
SYSTEMS = {"v9.1": ("evalgen_v91/mapsets_AI_v9.1.pkl", "evalgen_floor_v91/mapsets_AI_v9.1.pkl"),
|
| 52 |
+
"v10c": ("evalgen_v10c/mapsets_AI_v10c.pkl", "evalgen_floor_v10c/mapsets_AI_v10c.pkl")}
|
| 53 |
+
TEMPO = ((0, 110), (110, 170), (170, 10000))
|
| 54 |
+
DENS_EDGES = np.array([0.1, 0.2, 0.3, 0.45, 0.7])
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# ---------------------------------------------------------------- features
|
| 58 |
+
|
| 59 |
+
def beats_tol(sections, t, tol=1.0):
|
| 60 |
+
sec = np.asarray(sections, np.float64)
|
| 61 |
+
idx = np.clip(np.searchsorted(sec[:, 0], t + tol, side="right") - 1, 0, len(sec) - 1)
|
| 62 |
+
s = sec[idx]
|
| 63 |
+
return s[:, 3] + (t - s[:, 0]) / s[:, 1]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def grid_of(chart, sections, offset=0.0):
|
| 67 |
+
t = np.asarray(chart["time"], np.float64) + offset
|
| 68 |
+
ty = np.asarray(chart["type"])
|
| 69 |
+
t = np.sort(t[ty <= 3])
|
| 70 |
+
if len(t) == 0:
|
| 71 |
+
return np.zeros(0, np.int64)
|
| 72 |
+
return np.unique(np.round(beats_tol(sections, t) * GRID).astype(np.int64))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def mapset_grid(ms, sections=None):
|
| 76 |
+
out = {}
|
| 77 |
+
for t, c in ms.items():
|
| 78 |
+
g = grid_of(c, c["sections"] if sections is None else sections, float(c.get("offset_ms", 0.0)))
|
| 79 |
+
if len(g) >= MIN_HITS:
|
| 80 |
+
out[int(t)] = g
|
| 81 |
+
return out
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def density(g):
|
| 85 |
+
return len(g) / max((g[-1] - g[0]) / GRID, 1.0)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def vocab_of(grids):
|
| 89 |
+
return set().union(*[set(patterns(g)) for g in grids.values()]) if grids else set()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def compare(cg, rg, vocab):
|
| 93 |
+
c, r = common(cg, rg)
|
| 94 |
+
if len(c) < MIN_HITS or len(r) < MIN_HITS:
|
| 95 |
+
return None
|
| 96 |
+
sc, sr, gc, gr = sub_mix(c), sub_mix(r), gap_mix(c), gap_mix(r)
|
| 97 |
+
pc = patterns(c)
|
| 98 |
+
out = {f: float(np.abs(sc[ix] - sr[ix]).sum()) for f, ix in FAM.items()}
|
| 99 |
+
out.update(B_foreign=outside(pc, vocab), B_missing=outside(patterns(r), set(pc)),
|
| 100 |
+
gap=float(np.abs(gc - gr).sum()), logdens=float(np.log(density(c) / density(r))),
|
| 101 |
+
share={f: float(sr[ix].sum()) for f, ix in FAM.items()}, sub_c=sc, sub_r=sr, gap_c=gc, gap_r=gr)
|
| 102 |
+
return out
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def band(share):
|
| 106 |
+
return 0 if share < 0.02 else (1 if share < 0.05 else 2)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def base_err(b, cmp):
|
| 110 |
+
"""errors of the tempo-only profile b (sub 9 + gap 12) against the reference of one comparison."""
|
| 111 |
+
out = {f: float(np.abs(b[ix] - cmp["sub_r"][ix]).sum()) for f, ix in FAM.items()}
|
| 112 |
+
out["gap"] = float(np.abs(b[N_SUB:] - cmp["gap_r"]).sum())
|
| 113 |
+
return out
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# ---------------------------------------------------------------- thresholds
|
| 117 |
+
|
| 118 |
+
def wquantile(v, w, q):
|
| 119 |
+
v, w = np.asarray(v, float), np.asarray(w, float)
|
| 120 |
+
m = w > 0
|
| 121 |
+
if m.sum() == 0:
|
| 122 |
+
return np.inf
|
| 123 |
+
o = np.argsort(v[m])
|
| 124 |
+
cw = np.cumsum(w[m][o])
|
| 125 |
+
return float(v[m][o][min(np.searchsorted(cw, q * cw[-1]), m.sum() - 1)])
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def dens_bin(ld):
|
| 129 |
+
return int(np.searchsorted(DENS_EDGES, abs(ld)))
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def thresholds(rows, w):
|
| 133 |
+
"""rows: list of comparison dicts; w: weights -> {test: value or [band values]}."""
|
| 134 |
+
out = {}
|
| 135 |
+
for tname in TESTS:
|
| 136 |
+
v = np.array([r[tname] for r in rows])
|
| 137 |
+
if tname in BANDED:
|
| 138 |
+
b = np.array([band(r["share"][tname]) for r in rows])
|
| 139 |
+
out[tname] = [wquantile(v[b == k], w[b == k], 0.95) if (b == k).sum() >= 10 else wquantile(v, w, 0.95)
|
| 140 |
+
for k in range(3)]
|
| 141 |
+
else:
|
| 142 |
+
out[tname] = wquantile(v, w, 0.95)
|
| 143 |
+
return out
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def thr_matrix(thr):
|
| 147 |
+
return np.array([thr[t] if t in BANDED else [thr[t]] * 3 for t in TESTS], float) # [tests, 3 bands]
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def pack(cmps_by_song):
|
| 151 |
+
"""values [n, tests], band [n, tests], song index [n] of all comparisons of a list of songs."""
|
| 152 |
+
V, B, S = [], [], []
|
| 153 |
+
for i, cs in enumerate(cmps_by_song):
|
| 154 |
+
for c in cs:
|
| 155 |
+
V.append([c[t] for t in TESTS])
|
| 156 |
+
B.append([band(c["share"][t]) if t in BANDED else 0 for t in TESTS])
|
| 157 |
+
S.append(i)
|
| 158 |
+
return np.array(V, float).reshape(-1, len(TESTS)), np.array(B, int).reshape(-1, len(TESTS)), np.array(S, int), \
|
| 159 |
+
len(cmps_by_song)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def song_pass(pk, M):
|
| 163 |
+
"""per-song pass share (mean over the song's comparisons): {test: [songs]} incl. 'any'."""
|
| 164 |
+
V, B, S, n = pk
|
| 165 |
+
f = V > M[np.arange(len(TESTS))[None, :], B]
|
| 166 |
+
cnt = np.maximum(np.bincount(S, minlength=n), 1)
|
| 167 |
+
out = {t: 1 - np.bincount(S, weights=f[:, i].astype(float), minlength=n) / cnt for i, t in enumerate(TESTS)}
|
| 168 |
+
out["any"] = 1 - np.bincount(S, weights=f.any(1).astype(float), minlength=n) / cnt
|
| 169 |
+
return out
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def fails(cmp, thr):
|
| 173 |
+
f = {}
|
| 174 |
+
for tname in TESTS:
|
| 175 |
+
t = thr[tname][band(cmp["share"][tname])] if tname in BANDED else thr[tname]
|
| 176 |
+
f[tname] = cmp[tname] > t
|
| 177 |
+
f["any"] = any(f[t] for t in TESTS)
|
| 178 |
+
return f
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
# ---------------------------------------------------------------- data
|
| 182 |
+
|
| 183 |
+
def same_pool(E, cat, sets):
|
| 184 |
+
"""set -> (reference grids, sections, main BPM, [second-team grids]) anchored on that set's mapset."""
|
| 185 |
+
by_id = {e["beatmapset_id"]: e for e in E}
|
| 186 |
+
by_song = de.group_songs(E)
|
| 187 |
+
out = {}
|
| 188 |
+
for s in sets:
|
| 189 |
+
e = by_id.get(s)
|
| 190 |
+
if e is None:
|
| 191 |
+
continue
|
| 192 |
+
ref_ms = de._entry_mapset(e, cat)
|
| 193 |
+
if not ref_ms:
|
| 194 |
+
continue
|
| 195 |
+
sec = ref_ms[max(ref_ms)]["sections"]
|
| 196 |
+
rg = mapset_grid(ref_ms)
|
| 197 |
+
used = de._mappers(ref_ms)
|
| 198 |
+
teams = []
|
| 199 |
+
for o in by_song.get(e.get("song_key") or str(s), []):
|
| 200 |
+
if o["beatmapset_id"] == s:
|
| 201 |
+
continue
|
| 202 |
+
ms = de._entry_mapset(o, cat)
|
| 203 |
+
if not ms or not de._mappers(ms) or de._mappers(ms) & used:
|
| 204 |
+
continue
|
| 205 |
+
d, ok = de.align_mapsets(ref_ms, ms)
|
| 206 |
+
if not ok:
|
| 207 |
+
continue
|
| 208 |
+
ms = {t: {**c, "offset_ms": float(c.get("offset_ms", 0.0)) + d} for t, c in ms.items()}
|
| 209 |
+
cg = mapset_grid(ms, sec)
|
| 210 |
+
both = sorted(set(rg) & set(cg))
|
| 211 |
+
if both and finer_share(cg[t] for t in both) <= finer_share(rg[t] for t in both) + 0.03:
|
| 212 |
+
teams.append(cg)
|
| 213 |
+
used |= de._mappers(ms)
|
| 214 |
+
out[s] = {"ref": rg, "sec": sec, "bpm": main_bpm(sec), "teams": teams, "key": e.get("song_key") or str(s)}
|
| 215 |
+
return out
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def load_system(paths):
|
| 219 |
+
d = {}
|
| 220 |
+
for p in paths:
|
| 221 |
+
f = REPO / "data/hfruns/runs" / p
|
| 222 |
+
if f.exists():
|
| 223 |
+
d.update(pickle.load(open(f, "rb")))
|
| 224 |
+
return d
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def ai_grids(d, s, t):
|
| 228 |
+
out = []
|
| 229 |
+
for dr in d.get(s, {}).get("draws", [])[:4]:
|
| 230 |
+
c = dr["charts"].get(t)
|
| 231 |
+
if c is not None:
|
| 232 |
+
g = grid_of(c, c["sections"])
|
| 233 |
+
if len(g) >= MIN_HITS:
|
| 234 |
+
out.append(g)
|
| 235 |
+
return out
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
# ---------------------------------------------------------------- corruption (sensitivity)
|
| 239 |
+
|
| 240 |
+
def corrupt(c, r, kind, dose, order):
|
| 241 |
+
"""Corrupt the first ceil(dose * n) of the candidate notes that sit on reference notes of the kind's class, in the
|
| 242 |
+
chart's fixed random `order` (indices into those matched notes)."""
|
| 243 |
+
c = c.copy()
|
| 244 |
+
on_ref = np.isin(c, r)
|
| 245 |
+
cls = subdiv_class(c)
|
| 246 |
+
if kind == "binarize":
|
| 247 |
+
sel = on_ref & np.isin(cls, [DIVISORS.index(3), DIVISORS.index(6), DIVISORS.index(12)])
|
| 248 |
+
elif kind == "drop_fine":
|
| 249 |
+
sel = on_ref & (cls >= DIVISORS.index(8))
|
| 250 |
+
else: # shift: off-beat notes
|
| 251 |
+
sel = on_ref & (c % GRID != 0)
|
| 252 |
+
idx = np.where(sel)[0][order]
|
| 253 |
+
k = int(np.ceil(dose * len(idx)))
|
| 254 |
+
pick = idx[:k]
|
| 255 |
+
if kind == "binarize":
|
| 256 |
+
pos = c[pick] % GRID
|
| 257 |
+
c[pick] = c[pick] - pos + np.round(pos / 12).astype(np.int64) * 12
|
| 258 |
+
elif kind == "drop_fine":
|
| 259 |
+
c = np.delete(c, pick)
|
| 260 |
+
else:
|
| 261 |
+
c[pick] = c[pick] + 12
|
| 262 |
+
return np.unique(c), int(len(idx))
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def matched(c, r, kind):
|
| 266 |
+
on_ref = np.isin(c, r)
|
| 267 |
+
cls = subdiv_class(c)
|
| 268 |
+
if kind == "binarize":
|
| 269 |
+
return int((on_ref & np.isin(cls, [DIVISORS.index(3), DIVISORS.index(6), DIVISORS.index(12)])).sum())
|
| 270 |
+
if kind == "drop_fine":
|
| 271 |
+
return int((on_ref & (cls >= DIVISORS.index(8))).sum())
|
| 272 |
+
return int((on_ref & (c % GRID != 0)).sum())
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
# ---------------------------------------------------------------- main
|
| 276 |
+
|
| 277 |
+
def main():
|
| 278 |
+
ap = argparse.ArgumentParser()
|
| 279 |
+
ap.add_argument("--out", type=Path, default=REPO / "reports/figs/rhythm_eval2.json")
|
| 280 |
+
ap.add_argument("--cache", type=Path, default=REPO / "data/eval/rhythm_floor_pairs.pkl")
|
| 281 |
+
ap.add_argument("--tiers", type=int, nargs="+", default=[3, 4])
|
| 282 |
+
ap.add_argument("--boot", type=int, default=500)
|
| 283 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 284 |
+
a = ap.parse_args()
|
| 285 |
+
rng = np.random.default_rng(a.seed)
|
| 286 |
+
E = de.load_charts_all()
|
| 287 |
+
cat = de.load_catalog()
|
| 288 |
+
bank = tempo_bank(E)
|
| 289 |
+
|
| 290 |
+
eval_sets = [int(x) for x in open(REPO / "data/eval_modern_val_sets.txt").read().split()]
|
| 291 |
+
extra_sets = [int(x) for x in open(REPO / "data/eval/floor_val_sets.txt").read().split()]
|
| 292 |
+
pool = same_pool(E, cat, eval_sets + extra_sets)
|
| 293 |
+
sp_sets = [s for s in pool if pool[s]["teams"]]
|
| 294 |
+
sp_keys = {pool[s]["key"] for s in sp_sets}
|
| 295 |
+
systems = {k: load_system(p) for k, p in SYSTEMS.items()}
|
| 296 |
+
print(f"songs: eval {len(eval_sets)}, extra {len(extra_sets)}; same pool (second team) {len(sp_sets)};"
|
| 297 |
+
f" AI coverage " + ", ".join(f"{k} {sum(s in d for s in pool)}" for k, d in systems.items()))
|
| 298 |
+
|
| 299 |
+
def baseline(t, bpm):
|
| 300 |
+
bb, bp = bank[t]
|
| 301 |
+
m = np.abs(np.log(bb / bpm)) < np.log(1.1)
|
| 302 |
+
return bp[m].mean(0) if m.sum() >= 20 else bp[np.argsort(np.abs(np.log(bb / bpm)))[:20]].mean(0)
|
| 303 |
+
|
| 304 |
+
pairs = floor_pairs(E, cat, a.cache)
|
| 305 |
+
res = {"same_pool_songs": len(sp_sets), "tiers": {}}
|
| 306 |
+
for t in a.tiers:
|
| 307 |
+
T = TNAMES[t]
|
| 308 |
+
# ---- floor comparisons (outside the same-pool songs)
|
| 309 |
+
F, Fkey = [], []
|
| 310 |
+
for key, year, rg, cg in pairs:
|
| 311 |
+
if key in sp_keys or t not in rg or t not in cg:
|
| 312 |
+
continue
|
| 313 |
+
both = sorted(set(rg) & set(cg))
|
| 314 |
+
if finer_share(cg[u] for u in both) > finer_share(rg[u] for u in both) + 0.03:
|
| 315 |
+
continue
|
| 316 |
+
cmp = compare(cg[t], rg[t], vocab_of(rg))
|
| 317 |
+
if cmp:
|
| 318 |
+
F.append(cmp)
|
| 319 |
+
Fkey.append(key)
|
| 320 |
+
Fkey = np.array(Fkey)
|
| 321 |
+
# ---- AI comparisons on every pool song; second teams on same-pool songs
|
| 322 |
+
AI = {sysn: {} for sysn in systems}
|
| 323 |
+
HU = {}
|
| 324 |
+
for s, v in pool.items():
|
| 325 |
+
if t not in v["ref"]:
|
| 326 |
+
continue
|
| 327 |
+
vocab = vocab_of(v["ref"])
|
| 328 |
+
for sysn, d in systems.items():
|
| 329 |
+
cs = [compare(g, v["ref"][t], vocab) for g in ai_grids(d, s, t)]
|
| 330 |
+
cs = [c for c in cs if c]
|
| 331 |
+
if cs:
|
| 332 |
+
AI[sysn][s] = cs
|
| 333 |
+
for tm in v["teams"]:
|
| 334 |
+
if t in tm:
|
| 335 |
+
c = compare(tm[t], v["ref"][t], vocab)
|
| 336 |
+
if c:
|
| 337 |
+
HU[s] = c
|
| 338 |
+
break
|
| 339 |
+
# ---- density matching weights for the floor (to the AI's density-ratio distribution, both systems pooled)
|
| 340 |
+
ai_ld = [c["logdens"] for sysn in AI for cs in AI[sysn].values() for c in cs]
|
| 341 |
+
p_ai = np.bincount([dens_bin(x) for x in ai_ld], minlength=len(DENS_EDGES) + 1) / len(ai_ld)
|
| 342 |
+
fb = np.array([dens_bin(c["logdens"]) for c in F])
|
| 343 |
+
p_fl = np.bincount(fb, minlength=len(DENS_EDGES) + 1) / len(F)
|
| 344 |
+
w = np.where(p_fl[fb] > 0, p_ai[fb] / np.maximum(p_fl[fb], 1e-12), 0.0)
|
| 345 |
+
thr = thresholds(F, w)
|
| 346 |
+
# leave-one-song-out human pass rate on the floor
|
| 347 |
+
uk = np.unique(Fkey)
|
| 348 |
+
loo_fail = defaultdict(list)
|
| 349 |
+
loo_thr = {}
|
| 350 |
+
for k in uk:
|
| 351 |
+
m = Fkey != k
|
| 352 |
+
loo_thr[k] = thresholds([F[i] for i in np.where(m)[0]], w[m])
|
| 353 |
+
for i in np.where(~m)[0]:
|
| 354 |
+
f = fails(F[i], loo_thr[k])
|
| 355 |
+
for tn in (*TESTS, "any"):
|
| 356 |
+
loo_fail[tn].append((f[tn], w[i]))
|
| 357 |
+
human_loo = {tn: 1 - float(np.average([x for x, _ in v], weights=[y for _, y in v])) for tn, v in loo_fail.items()}
|
| 358 |
+
|
| 359 |
+
r = {"floor_pairs": len(F), "floor_songs": int(len(uk)), "thresholds": thr, "human_loo_pass": human_loo,
|
| 360 |
+
"same_pool_n": {"human": len(HU), **{k: sum(s in AI[k] for s in HU) for k in AI}}}
|
| 361 |
+
eval_songs = [s for s in eval_sets if s in pool and t in pool[s]["ref"]]
|
| 362 |
+
r["eval_n"] = {k: sum(s in AI[k] for s in eval_songs) for k in AI}
|
| 363 |
+
hu_list = list(HU)
|
| 364 |
+
pk_h = pack([[HU[s]] for s in hu_list])
|
| 365 |
+
pk_ev = {k: pack([AI[k][s] for s in eval_songs if s in AI[k]]) for k in AI}
|
| 366 |
+
sp_ai = {k: [s for s in hu_list if s in AI[k]] for k in AI}
|
| 367 |
+
pk_sp = {k: pack([AI[k][s] for s in sp_ai[k]]) for k in AI}
|
| 368 |
+
hmask = {k: np.array([s in AI[k] for s in hu_list]) for k in AI}
|
| 369 |
+
M = thr_matrix(thr)
|
| 370 |
+
pr = {"human_same_pool": {k: float(v.mean()) for k, v in song_pass(pk_h, M).items()}}
|
| 371 |
+
for k in AI:
|
| 372 |
+
pr[k] = {"eval": {x: float(v.mean()) for x, v in song_pass(pk_ev[k], M).items()},
|
| 373 |
+
"same_pool": {x: float(v.mean()) for x, v in song_pass(pk_sp[k], M).items()}}
|
| 374 |
+
# joint bootstrap: floor songs (threshold) + scored songs, as song multiplicities
|
| 375 |
+
boot = defaultdict(list)
|
| 376 |
+
key_rows = {k: np.where(Fkey == k)[0] for k in uk}
|
| 377 |
+
for _ in range(a.boot):
|
| 378 |
+
ks = rng.choice(uk, len(uk))
|
| 379 |
+
idx = np.concatenate([key_rows[k] for k in ks])
|
| 380 |
+
Mb = thr_matrix(thresholds([F[i] for i in idx], w[idx]))
|
| 381 |
+
for k in AI:
|
| 382 |
+
n = pk_ev[k][3]
|
| 383 |
+
cnt = np.bincount(rng.integers(0, n, n), minlength=n)
|
| 384 |
+
for x, v in song_pass(pk_ev[k], Mb).items():
|
| 385 |
+
boot[f"{k}|eval|{x}"].append(float((cnt * v).sum() / n))
|
| 386 |
+
nh = len(hu_list)
|
| 387 |
+
ch = np.bincount(rng.integers(0, nh, nh), minlength=nh)
|
| 388 |
+
ph = song_pass(pk_h, Mb)
|
| 389 |
+
for x, v in ph.items():
|
| 390 |
+
boot[f"human|same_pool|{x}"].append(float((ch * v).sum() / nh))
|
| 391 |
+
for k in AI:
|
| 392 |
+
ca = ch[hmask[k]]
|
| 393 |
+
pa = song_pass(pk_sp[k], Mb)
|
| 394 |
+
for x in ph:
|
| 395 |
+
a_ = float((ca * pa[x]).sum() / max(ca.sum(), 1))
|
| 396 |
+
h_ = float((ca * ph[x][hmask[k]]).sum() / max(ca.sum(), 1))
|
| 397 |
+
boot[f"{k}|same_pool|{x}"].append(a_)
|
| 398 |
+
boot[f"{k}-human|same_pool|{x}"].append(a_ - h_)
|
| 399 |
+
ci = {k: [float(np.percentile(v, 2.5)), float(np.percentile(v, 97.5))] for k, v in boot.items()}
|
| 400 |
+
r["pass"] = pr
|
| 401 |
+
r["pass_ci"] = ci
|
| 402 |
+
|
| 403 |
+
# ---- song-following (same pool: AI and human on the same songs; eval pool: AI)
|
| 404 |
+
def follow(cmp_lists, bpms):
|
| 405 |
+
fam = list(FAM) + ["gap"]
|
| 406 |
+
e = {f: [] for f in fam}
|
| 407 |
+
eb = {f: [] for f in fam}
|
| 408 |
+
for cs, bpm in zip(cmp_lists, bpms):
|
| 409 |
+
b = baseline(t, bpm)
|
| 410 |
+
for f in fam:
|
| 411 |
+
e[f].append(np.mean([c[f] if f != "gap" else c["gap"] for c in cs]))
|
| 412 |
+
eb[f].append(np.mean([base_err(b, c)[f] for c in cs]))
|
| 413 |
+
return {f: (np.array(e[f]), np.array(eb[f])) for f in fam}
|
| 414 |
+
|
| 415 |
+
fol = {}
|
| 416 |
+
sp_common = [s for s in HU if all(s in AI[k] for k in AI)]
|
| 417 |
+
hf = follow([[HU[s]] for s in sp_common], [pool[s]["bpm"] for s in sp_common])
|
| 418 |
+
af = {k: follow([AI[k][s] for s in sp_common], [pool[s]["bpm"] for s in sp_common]) for k in AI}
|
| 419 |
+
ae = {k: follow([AI[k][s] for s in eval_songs if s in AI[k]], [pool[s]["bpm"] for s in eval_songs if s in AI[k]])
|
| 420 |
+
for k in AI}
|
| 421 |
+
for f in hf:
|
| 422 |
+
def score(x, idx=None):
|
| 423 |
+
e, eb = x[f]
|
| 424 |
+
if idx is not None:
|
| 425 |
+
e, eb = e[idx], eb[idx]
|
| 426 |
+
return 1 - e.mean() / eb.mean()
|
| 427 |
+
bs = defaultdict(list)
|
| 428 |
+
for _ in range(a.boot):
|
| 429 |
+
j = rng.integers(0, len(sp_common), len(sp_common))
|
| 430 |
+
h = score(hf, j)
|
| 431 |
+
bs["human"].append(h)
|
| 432 |
+
for k in AI:
|
| 433 |
+
bs[k].append(score(af[k], j))
|
| 434 |
+
bs[k + "-human"].append(score(af[k], j) - h)
|
| 435 |
+
je = rng.integers(0, len(ae[k][f][0]), len(ae[k][f][0]))
|
| 436 |
+
bs[k + "|eval"].append(score(ae[k], je))
|
| 437 |
+
fol[f] = {"human_same_pool": float(score(hf)), "n_same_pool": len(sp_common),
|
| 438 |
+
**{k: float(score(af[k])) for k in AI}, **{k + "|eval": float(score(ae[k])) for k in AI},
|
| 439 |
+
"ci": {k: [float(np.percentile(v, 2.5)), float(np.percentile(v, 97.5))] for k, v in bs.items()}}
|
| 440 |
+
r["follow"] = fol
|
| 441 |
+
|
| 442 |
+
# ---- amount ratio per class, overall and per tempo band
|
| 443 |
+
amt = {}
|
| 444 |
+
for name, lists, songs in [("human_same_pool", {s: [HU[s]] for s in HU}, list(HU))] + \
|
| 445 |
+
[(k + "|same_pool", AI[k], [s for s in HU if s in AI[k]]) for k in AI] + \
|
| 446 |
+
[(k + "|eval", AI[k], [s for s in eval_songs if s in AI[k]]) for k in AI]:
|
| 447 |
+
C = np.array([np.mean([c["sub_c"] for c in lists[s]], 0) for s in songs])
|
| 448 |
+
R = np.array([np.mean([c["sub_r"] for c in lists[s]], 0) for s in songs])
|
| 449 |
+
bpm = np.array([pool[s]["bpm"] for s in songs])
|
| 450 |
+
def ratio(Cx, Rx):
|
| 451 |
+
# undefined (None) when the references hardly use the class: mean share below 0.2%
|
| 452 |
+
return [float(c / r) if r >= 0.002 * len(Rx) else None for c, r in zip(Cx.sum(0), Rx.sum(0))]
|
| 453 |
+
|
| 454 |
+
row = {"all": ratio(C, R), "n": len(songs)}
|
| 455 |
+
bs = []
|
| 456 |
+
for _ in range(a.boot):
|
| 457 |
+
j = rng.integers(0, len(songs), len(songs))
|
| 458 |
+
bs.append([np.nan if x is None else x for x in ratio(C[j], R[j])])
|
| 459 |
+
bs = np.array(bs)
|
| 460 |
+
row["ci"] = [None if row["all"][k] is None else np.nanpercentile(bs[:, k], [2.5, 97.5]).tolist()
|
| 461 |
+
for k in range(bs.shape[1])]
|
| 462 |
+
for lo, hi in TEMPO:
|
| 463 |
+
m = (bpm >= lo) & (bpm < hi)
|
| 464 |
+
row[f"bpm{lo}-{hi}"] = ratio(C[m], R[m]) if m.sum() >= 5 else None
|
| 465 |
+
row[f"bpm{lo}-{hi}_n"] = int(m.sum())
|
| 466 |
+
amt[name] = row
|
| 467 |
+
r["amount"] = amt
|
| 468 |
+
r["density_within_25pct"] = {
|
| 469 |
+
"human_same_pool": float(np.mean([abs(HU[s]["logdens"]) < np.log(1.25) for s in HU])),
|
| 470 |
+
**{k: float(np.mean([np.mean([abs(c["logdens"]) < np.log(1.25) for c in AI[k][s]]) for s in eval_songs
|
| 471 |
+
if s in AI[k]])) for k in AI}}
|
| 472 |
+
res["tiers"][T] = r
|
| 473 |
+
print(f"done {T}")
|
| 474 |
+
|
| 475 |
+
# ---- sensitivity: floor pairs of the requested tiers pooled, leave-one-song-out thresholds (unweighted)
|
| 476 |
+
res["sensitivity"] = sensitivity(E, cat, pairs, sp_keys, a.tiers, rng)
|
| 477 |
+
a.out.parent.mkdir(parents=True, exist_ok=True)
|
| 478 |
+
json.dump(res, open(a.out, "w"), ensure_ascii=False, indent=1, default=float)
|
| 479 |
+
print(f"wrote {a.out}")
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def sensitivity(E, cat, pairs, sp_keys, tiers, rng):
|
| 483 |
+
out = {}
|
| 484 |
+
per_tier = {}
|
| 485 |
+
for t in tiers:
|
| 486 |
+
F, keys = [], []
|
| 487 |
+
for key, year, rg, cg in pairs:
|
| 488 |
+
if key in sp_keys or t not in rg or t not in cg:
|
| 489 |
+
continue
|
| 490 |
+
both = sorted(set(rg) & set(cg))
|
| 491 |
+
if finer_share(cg[u] for u in both) > finer_share(rg[u] for u in both) + 0.03:
|
| 492 |
+
continue
|
| 493 |
+
c, r = common(cg[t], rg[t])
|
| 494 |
+
if len(c) < MIN_HITS or len(r) < MIN_HITS:
|
| 495 |
+
continue
|
| 496 |
+
vocab = vocab_of(rg)
|
| 497 |
+
cmp = compare(cg[t], rg[t], vocab)
|
| 498 |
+
F.append((key, c, r, vocab, cmp))
|
| 499 |
+
keys.append(key)
|
| 500 |
+
keys = np.array(keys)
|
| 501 |
+
w = np.ones(len(F))
|
| 502 |
+
loo = {k: thresholds([F[i][4] for i in np.where(keys != k)[0]], w[keys != k]) for k in np.unique(keys)}
|
| 503 |
+
per_tier[t] = (F, loo)
|
| 504 |
+
for kind, test in (("binarize", "triplet"), ("drop_fine", "fine"), ("shift", "B_foreign")):
|
| 505 |
+
flags = defaultdict(list) # dose -> [(test fail, any fail)]
|
| 506 |
+
moved = []
|
| 507 |
+
n = 0
|
| 508 |
+
for t, (F, loo) in per_tier.items():
|
| 509 |
+
for key, c, r, vocab, _ in F:
|
| 510 |
+
m = matched(c, r, kind)
|
| 511 |
+
if m < 5:
|
| 512 |
+
continue
|
| 513 |
+
n += 1
|
| 514 |
+
order = rng.permutation(m)
|
| 515 |
+
for dose in (0.0, 0.25, 0.5, 1.0):
|
| 516 |
+
g, _ = corrupt(c, r, kind, dose, order)
|
| 517 |
+
cmp = compare(g, r, vocab) if len(g) >= MIN_HITS else None
|
| 518 |
+
if cmp is None:
|
| 519 |
+
continue
|
| 520 |
+
f = fails(cmp, loo[key])
|
| 521 |
+
flags[dose].append((f[test], f["any"]))
|
| 522 |
+
moved.append(m / len(c))
|
| 523 |
+
res = {"n": n, "median_share_moved_at_1": float(np.median(moved)) if moved else None}
|
| 524 |
+
for dose, v in flags.items():
|
| 525 |
+
v = np.array(v, float)
|
| 526 |
+
res[f"dose{dose}"] = {"test": float(v[:, 0].mean()), "any": float(v[:, 1].mean())}
|
| 527 |
+
if 0.0 in flags and 1.0 in flags and len(flags[0.0]) == len(flags[1.0]):
|
| 528 |
+
d = np.array(flags[1.0], float)[:, 0] - np.array(flags[0.0], float)[:, 0]
|
| 529 |
+
bs = [d[rng.integers(0, len(d), len(d))].mean() for _ in range(1000)]
|
| 530 |
+
res["excess_test_at_1"] = [float(d.mean()), float(np.percentile(bs, 2.5)), float(np.percentile(bs, 97.5))]
|
| 531 |
+
out[kind] = res
|
| 532 |
+
return out
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
if __name__ == "__main__":
|
| 536 |
+
main()
|
chartgen/song_planner.py
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Song-level bar planner: the per-bar plan (dataset.bar_plan) of a whole chart, from the whole song.
|
| 2 |
+
|
| 3 |
+
A mapper decides where to rest, how dense each passage is, when to switch to triplets and when to
|
| 4 |
+
repeat a pattern by looking at the whole song (intro, breaks, drops, repeated phrases). The B0 decoder
|
| 5 |
+
only sees 20 s. This model sees every bar of the song at once:
|
| 6 |
+
|
| 7 |
+
input per measure (real measures of the chart's timing sections, see dataset.measure_at): mean of the
|
| 8 |
+
frozen B0 music memory over the measure's frames, beat-synchronous band onsets at 48 slots of the
|
| 9 |
+
measure, loudness, the target difficulty, the measure position;
|
| 10 |
+
model transformer encoder over all measures (attention can find the measures that sound alike);
|
| 11 |
+
output the 17 per-measure plan features: play, density, big-note share, roll start, triplet share, 1/8 share,
|
| 12 |
+
gap histogram, sustain (share covered by a roll / balloon body).
|
| 13 |
+
|
| 14 |
+
The predicted plan is given to a bar-planned generator (B0Config.bar_plan) instead of the human plan.
|
| 15 |
+
|
| 16 |
+
python -m chartgen.song_planner --data f*.pkl --model b0.pt --out-dir runs/sp1
|
| 17 |
+
writes best.pt, result.json (validation: planner vs human, and human vs human for same-tier pairs) and
|
| 18 |
+
plans_val.pkl: {(beatmapset_id, beatmap_id): (first bar index, [n_bars, BAR_F] plan)} for validation charts.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import argparse
|
| 24 |
+
import json
|
| 25 |
+
import math
|
| 26 |
+
import pickle
|
| 27 |
+
import time
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
import torch
|
| 32 |
+
import torch.nn as nn
|
| 33 |
+
import torch.nn.functional as F
|
| 34 |
+
|
| 35 |
+
from .dataset import BAR_F, GAP0, GRID, SUSTAIN, WINDOW, _beats_at, bar_plan, load_songs, measure_at, measure_span, plan_active
|
| 36 |
+
from .gapstats import N_GAP_BINS
|
| 37 |
+
from .infer import load_model
|
| 38 |
+
from .model import N_TIERS
|
| 39 |
+
from .train import song_split
|
| 40 |
+
|
| 41 |
+
MAX_SONG_BARS = 384
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@torch.no_grad()
|
| 45 |
+
def song_memory(music_enc, mel, device) -> np.ndarray:
|
| 46 |
+
"""Grid-free B0 music memory of a whole song at 50 fps, encoded in 20 s windows."""
|
| 47 |
+
outs = []
|
| 48 |
+
for s in range(0, len(mel), WINDOW):
|
| 49 |
+
x = np.asarray(mel[s:s + WINDOW], np.float32)
|
| 50 |
+
n = len(x)
|
| 51 |
+
if n < WINDOW:
|
| 52 |
+
x = np.concatenate([x, np.full((WINDOW - n, x.shape[1]), x.min(), np.float32)])
|
| 53 |
+
_, mem = music_enc.encode(torch.from_numpy(x[None]).to(device))
|
| 54 |
+
outs.append(mem[0, : (n + 1) // 2].float().cpu().numpy())
|
| 55 |
+
return np.concatenate(outs).astype(np.float16)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
BANDS = ((0, 16), (16, 40), (40, 80), (80, 128), (0, 128))
|
| 59 |
+
SLOTS = 48 # 12 per beat
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def onset_bands(mel) -> np.ndarray:
|
| 63 |
+
"""[frames, len(BANDS)] positive spectral flux of log-Mel per frequency band at 100 fps, z-scored per song."""
|
| 64 |
+
m = np.asarray(mel, np.float32)
|
| 65 |
+
flux = np.maximum(np.diff(m, axis=0, prepend=m[:1]), 0)
|
| 66 |
+
out = np.stack([flux[:, a:b].mean(1) for a, b in BANDS], 1)
|
| 67 |
+
return (out - out.mean(0)) / (out.std(0) + 1e-6)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def onsets_loud(onsets: np.ndarray, n50: int) -> np.ndarray:
|
| 71 |
+
"""Per 50 fps frame: loudness (column len(BANDS) of onsets: z-scored mean log-Mel, added with
|
| 72 |
+
--loudness), smoothed over 0.5 s."""
|
| 73 |
+
lv = onsets[:, -1] if onsets.shape[1] <= len(BANDS) else onsets[:, len(BANDS)]
|
| 74 |
+
k = np.ones(50) / 50
|
| 75 |
+
sm = np.convolve(lv, k, mode="same")
|
| 76 |
+
return sm[::2][:n50] if len(sm[::2]) >= n50 else np.pad(sm[::2], (0, n50 - len(sm[::2])))
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def beat_to_ms(sections: np.ndarray, beats: np.ndarray) -> np.ndarray:
|
| 80 |
+
idx = np.clip(np.searchsorted(sections[:, 3], beats, side="right") - 1, 0, len(sections) - 1)
|
| 81 |
+
s = sections[idx]
|
| 82 |
+
return s[:, 0] + (beats - s[:, 3]) * s[:, 1]
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def beat_sync(onsets: np.ndarray, sections: np.ndarray, b0: int, n: int) -> np.ndarray:
|
| 86 |
+
"""[n, SLOTS * bands]: onset strength of each band at 48 evenly spaced slots of each measure (12 per beat in
|
| 87 |
+
4/4; max over +-1 frame). Measures b0 .. b0 + n - 1 (real measures)."""
|
| 88 |
+
st, en = measure_span(sections, np.arange(n) + b0)
|
| 89 |
+
beats = (st[:, None] + (en - st)[:, None] * (np.arange(SLOTS) / SLOTS)[None]).reshape(-1)
|
| 90 |
+
f = np.round(beat_to_ms(sections, beats) / 10.0).astype(np.int64)
|
| 91 |
+
T = len(onsets)
|
| 92 |
+
v = np.full((len(f), onsets.shape[1]), -1.0, np.float32)
|
| 93 |
+
for d in (-1, 0, 1):
|
| 94 |
+
g = f + d
|
| 95 |
+
ok = (g >= 0) & (g < T)
|
| 96 |
+
v[ok] = np.maximum(v[ok], onsets[g[ok]])
|
| 97 |
+
return v.reshape(n, SLOTS * onsets.shape[1])
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def chart_rows(mem50: np.ndarray, chart: dict, onsets: np.ndarray | None = None, loudness: bool = False):
|
| 101 |
+
"""(bar features [n, d], plan targets [n, BAR_F], first bar index) for one chart of the song.
|
| 102 |
+
With onsets (onset_bands of the song), each bar's features also hold its beat-synchronous onset profile."""
|
| 103 |
+
t = np.arange(len(mem50)) * 20.0
|
| 104 |
+
bars = measure_at(chart["sections"], _beats_at(chart["sections"], t))
|
| 105 |
+
b0 = int(bars.min())
|
| 106 |
+
n = min(int(bars.max()) - b0 + 1, MAX_SONG_BARS)
|
| 107 |
+
idx = bars - b0
|
| 108 |
+
ok = idx < n
|
| 109 |
+
feat = np.zeros((n, mem50.shape[1]), np.float32)
|
| 110 |
+
cnt = np.zeros(n, np.float32)
|
| 111 |
+
np.add.at(feat, idx[ok], mem50[ok].astype(np.float32))
|
| 112 |
+
np.add.at(cnt, idx[ok], 1.0)
|
| 113 |
+
feat /= np.maximum(cnt, 1)[:, None]
|
| 114 |
+
if onsets is not None and loudness:
|
| 115 |
+
loud = np.zeros(n, np.float32)
|
| 116 |
+
np.add.at(loud, idx[ok], onsets_loud(onsets, len(mem50))[ok])
|
| 117 |
+
loud /= np.maximum(cnt, 1)
|
| 118 |
+
z = (loud - loud.mean()) / (loud.std() + 1e-6)
|
| 119 |
+
rank = np.argsort(np.argsort(loud)) / max(n - 1, 1)
|
| 120 |
+
feat = np.concatenate([feat, beat_sync(onsets, chart["sections"], b0, n), z[:, None], rank[:, None]], 1)
|
| 121 |
+
elif onsets is not None:
|
| 122 |
+
feat = np.concatenate([feat, beat_sync(onsets, chart["sections"], b0, n)], 1)
|
| 123 |
+
all_g = np.round(chart["beat"] * GRID).astype(np.int64)
|
| 124 |
+
tgt = bar_plan(all_g, chart["type"], b0, chart["sections"], chart.get("length_beats"), n)
|
| 125 |
+
return feat, tgt, b0
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class SongPlanner(nn.Module):
|
| 129 |
+
def __init__(self, d_in: int, d: int = 192, layers: int = 4, heads: int = 4, drop: float = 0.1):
|
| 130 |
+
super().__init__()
|
| 131 |
+
self.inp = nn.Sequential(nn.LayerNorm(d_in), nn.Linear(d_in, d))
|
| 132 |
+
self.pos = nn.Embedding(MAX_SONG_BARS, d)
|
| 133 |
+
self.tier = nn.Embedding(N_TIERS, d)
|
| 134 |
+
layer = nn.TransformerEncoderLayer(d, heads, 4 * d, drop, activation="gelu", batch_first=True, norm_first=True)
|
| 135 |
+
self.enc = nn.TransformerEncoder(layer, layers, enable_nested_tensor=False)
|
| 136 |
+
self.norm = nn.LayerNorm(d)
|
| 137 |
+
self.out = nn.Linear(d, BAR_F)
|
| 138 |
+
|
| 139 |
+
def forward(self, x, tier, mask):
|
| 140 |
+
n = x.shape[1]
|
| 141 |
+
h = self.inp(x) + self.pos(torch.arange(n, device=x.device))[None] + self.tier(tier)[:, None]
|
| 142 |
+
return self.out(self.norm(self.enc(h, src_key_padding_mask=~mask)))
|
| 143 |
+
|
| 144 |
+
@staticmethod
|
| 145 |
+
def to_plan(o: torch.Tensor, sample: bool = False, threshold: float = 0.5) -> torch.Tensor:
|
| 146 |
+
"""Network output -> plan features as the generator saw them in training (play is 0/1).
|
| 147 |
+
A measure has no hit notes when P(play) < threshold; its hit-note features are then zero, while roll start
|
| 148 |
+
and sustain stay (a roll can start or run in a measure without hit notes)."""
|
| 149 |
+
p_play = torch.sigmoid(o[..., 0])
|
| 150 |
+
play = torch.bernoulli(p_play) if sample else (p_play > threshold).float()
|
| 151 |
+
dens = o[..., 1].clamp(min=0)
|
| 152 |
+
shape = torch.sigmoid(o[..., 2:6])
|
| 153 |
+
gap = torch.softmax(o[..., GAP0:GAP0 + N_GAP_BINS], -1)
|
| 154 |
+
hitf = torch.cat([play[..., None], dens[..., None], shape, gap], -1) * play[..., None]
|
| 155 |
+
hitf[..., 3] = shape[..., 1] # roll start is not gated by play
|
| 156 |
+
return torch.cat([hitf, torch.sigmoid(o[..., SUSTAIN:SUSTAIN + 1])], -1)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
REST_WEIGHT = 1.0 # loss weight of rest bars (play = 0) relative to played bars; set by --rest-weight
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def loss_fn(o, tgt, mask):
|
| 163 |
+
m = mask.float()
|
| 164 |
+
play = tgt[..., 0]
|
| 165 |
+
wr = m * (play + REST_WEIGHT * (1 - play))
|
| 166 |
+
L = {"play": (F.binary_cross_entropy_with_logits(o[..., 0], play, reduction="none") * wr).sum() / wr.sum()}
|
| 167 |
+
mp = m * play
|
| 168 |
+
L["dens"] = (((o[..., 1] - tgt[..., 1]) ** 2) * mp).sum() / mp.sum().clamp(min=1)
|
| 169 |
+
hit_cols = [2, 4, 5] # big, triplet, 1/8 shares: defined on measures with hit notes
|
| 170 |
+
L["shape"] = (F.binary_cross_entropy_with_logits(o[..., hit_cols], tgt[..., hit_cols], reduction="none").sum(-1) * mp).sum() / mp.sum().clamp(min=1)
|
| 171 |
+
# roll start and sustain: every valid measure (rolls can start or run where there are no hit notes)
|
| 172 |
+
L["roll"] = (F.binary_cross_entropy_with_logits(o[..., [3, SUSTAIN]], tgt[..., [3, SUSTAIN]], reduction="none").sum(-1) * m).sum() / m.sum()
|
| 173 |
+
tg = tgt[..., GAP0:GAP0 + N_GAP_BINS]
|
| 174 |
+
mg = m * (tg.sum(-1) > 0).float()
|
| 175 |
+
L["gap"] = (-(tg * torch.log_softmax(o[..., GAP0:GAP0 + N_GAP_BINS], -1)).sum(-1) * mg).sum() / mg.sum().clamp(min=1)
|
| 176 |
+
return L["play"] + L["dens"] + 0.5 * L["shape"] + 0.5 * L["roll"] + 0.5 * L["gap"], L
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def collate(items, device):
|
| 180 |
+
n = max(len(x[0]) for x in items)
|
| 181 |
+
B = len(items)
|
| 182 |
+
d = items[0][0].shape[1]
|
| 183 |
+
X = torch.zeros(B, n, d); T = torch.zeros(B, n, BAR_F); M = torch.zeros(B, n, dtype=torch.bool)
|
| 184 |
+
for b, (f, t, tier, _) in enumerate(items):
|
| 185 |
+
X[b, : len(f)] = torch.from_numpy(f); T[b, : len(t)] = torch.from_numpy(t); M[b, : len(f)] = True
|
| 186 |
+
tiers = torch.tensor([x[2] for x in items])
|
| 187 |
+
return X.to(device), T.to(device), M.to(device), tiers.to(device)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def agreement(P, T, M):
|
| 191 |
+
"""Plan agreement on valid bars: play accuracy, rest-bar F1, density correlation (played bars),
|
| 192 |
+
triplet-bar AUC proxy (mean predicted triplet share on human triplet bars minus on others)."""
|
| 193 |
+
P, T, M = P[M], T[M], M[M]
|
| 194 |
+
pp, tp = plan_active(P), plan_active(T) # rest = no hit note and no roll / balloon
|
| 195 |
+
rest_tp = (~pp & ~tp).sum(); rest_f1 = 2 * rest_tp / max((~pp).sum() + (~tp).sum(), 1)
|
| 196 |
+
pp, tp = P[:, 0] > 0.5, T[:, 0] > 0.5
|
| 197 |
+
both = pp & tp
|
| 198 |
+
dc = float(np.corrcoef(P[both, 1], T[both, 1])[0, 1]) if both.sum() > 2 else float("nan")
|
| 199 |
+
trip = T[:, 4] > 0.3
|
| 200 |
+
td = float(P[trip, 4].mean() - P[~trip & tp, 4].mean()) if trip.any() else float("nan")
|
| 201 |
+
return {"play_acc": float((pp == tp).mean()), "rest_f1": float(rest_f1), "density_corr": dc, "triplet_sep": td,
|
| 202 |
+
"rest_share_pred": float((~plan_active(P)).mean()), "rest_share_true": float((~plan_active(T)).mean())}
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def main(argv=None):
|
| 206 |
+
p = argparse.ArgumentParser()
|
| 207 |
+
p.add_argument("--data", nargs="+", type=Path, required=True)
|
| 208 |
+
p.add_argument("--model", type=Path, required=True, help="B0 checkpoint (frozen music encoder)")
|
| 209 |
+
p.add_argument("--out-dir", type=Path, required=True)
|
| 210 |
+
p.add_argument("--steps", type=int, default=4000)
|
| 211 |
+
p.add_argument("--batch", type=int, default=16)
|
| 212 |
+
p.add_argument("--lr", type=float, default=3e-4)
|
| 213 |
+
p.add_argument("--max-songs", type=int, default=0)
|
| 214 |
+
p.add_argument("--beat-sync", action="store_true", help="add beat-synchronous band onsets per bar (planner v2)")
|
| 215 |
+
p.add_argument("--rest-weight", type=float, default=1.0, help="loss weight of rest bars (play = 0)")
|
| 216 |
+
p.add_argument("--loudness", action="store_true", help="add per-bar loudness (z-score and rank within the song)")
|
| 217 |
+
p.add_argument("--predict", type=Path, help="no training: load this planner and only write plans (thresholds below)")
|
| 218 |
+
p.add_argument("--thresholds", type=float, nargs="*", default=[0.5],
|
| 219 |
+
help="rest threshold(s) on P(play); with several, writes plans_val_t{th}.pkl and the agreement of each")
|
| 220 |
+
a = p.parse_args(argv)
|
| 221 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 222 |
+
a.out_dir.mkdir(parents=True, exist_ok=True)
|
| 223 |
+
global REST_WEIGHT
|
| 224 |
+
REST_WEIGHT = a.rest_weight
|
| 225 |
+
t0 = time.time()
|
| 226 |
+
enc = load_model(a.model, device).eval()
|
| 227 |
+
rows = {"train": [], "val": []}
|
| 228 |
+
n_songs = 0
|
| 229 |
+
train_rates = [] # predict mode: per training chart, (measures, roll starts, sustained measures) from the labels only
|
| 230 |
+
for f in a.data:
|
| 231 |
+
for s in load_songs([f], mmap=True):
|
| 232 |
+
split = song_split(s.get("song_key") or str(s["beatmapset_id"]))
|
| 233 |
+
if a.predict and split == "train":
|
| 234 |
+
for c in s["charts"]:
|
| 235 |
+
if len(c["time"]) >= 16:
|
| 236 |
+
_, tgt, _ = chart_rows(np.zeros(((len(s["mel"]) + 1) // 2, 1), np.float32), c)
|
| 237 |
+
train_rates.append((len(tgt), float((tgt[:, 3] > 0.5).sum()), float((tgt[:, SUSTAIN] > 0.1).sum())))
|
| 238 |
+
continue
|
| 239 |
+
if split not in rows or (a.predict and split != "val"):
|
| 240 |
+
continue
|
| 241 |
+
mem = song_memory(enc, s["mel"], device)
|
| 242 |
+
ons = onset_bands(s["mel"]) if a.beat_sync else None
|
| 243 |
+
if ons is not None and a.loudness:
|
| 244 |
+
lm = np.asarray(s["mel"], np.float32).mean(1)
|
| 245 |
+
ons = np.concatenate([ons, ((lm - lm.mean()) / (lm.std() + 1e-6))[:, None]], 1)
|
| 246 |
+
for c in s["charts"]:
|
| 247 |
+
if len(c["time"]) < 16:
|
| 248 |
+
continue
|
| 249 |
+
feat, tgt, b0 = chart_rows(mem, c, ons, a.loudness)
|
| 250 |
+
rows[split].append((feat.astype(np.float16), tgt, int(c["tier"]), (s["beatmapset_id"], c.get("beatmap_id"), b0, s.get("song_key"))))
|
| 251 |
+
n_songs += 1
|
| 252 |
+
if a.max_songs and n_songs >= a.max_songs:
|
| 253 |
+
break
|
| 254 |
+
print(f"{f.name}: train {len(rows['train'])} val {len(rows['val'])} charts, {(time.time() - t0) / 60:.1f} min", flush=True)
|
| 255 |
+
if a.max_songs and n_songs >= a.max_songs:
|
| 256 |
+
break
|
| 257 |
+
d_in = rows["train"][0][0].shape[1] if rows["train"] else rows["val"][0][0].shape[1]
|
| 258 |
+
model = SongPlanner(d_in).to(device)
|
| 259 |
+
if a.predict:
|
| 260 |
+
model.load_state_dict(torch.load(a.predict, map_location=device)["model"])
|
| 261 |
+
model.eval()
|
| 262 |
+
report = {}
|
| 263 |
+
by = {}
|
| 264 |
+
for x in rows["val"]:
|
| 265 |
+
by.setdefault((x[3][0], x[2]), []).append(x)
|
| 266 |
+
pairs = [g for g in by.values() if len(g) >= 2 and g[0][3][2] == g[1][3][2] and len(g[0][1]) == len(g[1][1])]
|
| 267 |
+
outs = {}
|
| 268 |
+
with torch.no_grad():
|
| 269 |
+
for i in range(0, len(rows["val"]), 32):
|
| 270 |
+
part = [(x[0].astype(np.float32), x[1], x[2], x[3]) for x in rows["val"][i:i + 32]]
|
| 271 |
+
X, Tt, Mm, tiers = collate(part, device)
|
| 272 |
+
o = model(X, tiers, Mm).cpu()
|
| 273 |
+
for b, x in enumerate(part):
|
| 274 |
+
outs[(x[3][0], x[3][1])] = (x[3][2], o[b, : len(x[0])], x[1])
|
| 275 |
+
# roll start and sustain are expected values; like the triplet share (v7) they would almost never pass a fixed cut-off.
|
| 276 |
+
# Make them decisions whose frequency matches the human frequency in the TRAINING labels (no validation labels used).
|
| 277 |
+
tr = np.array(train_rates, float)
|
| 278 |
+
rate_roll, rate_sus = (tr[:, 1].sum() / tr[:, 0].sum(), tr[:, 2].sum() / tr[:, 0].sum()) if len(tr) else (0.0, 0.0)
|
| 279 |
+
allp = np.concatenate([SongPlanner.to_plan(o).numpy() for _, o, _ in outs.values()])
|
| 280 |
+
th_roll = float(np.quantile(allp[:, 3], 1 - rate_roll)) if rate_roll > 0 else 1.0
|
| 281 |
+
th_sus = float(np.quantile(allp[:, SUSTAIN], 1 - rate_sus)) if rate_sus > 0 else 1.0
|
| 282 |
+
report["calibration"] = {"train_rate_roll_start": rate_roll, "train_rate_sustain": rate_sus, "th_roll": th_roll, "th_sustain": th_sus}
|
| 283 |
+
print("calibration", report["calibration"], flush=True)
|
| 284 |
+
|
| 285 |
+
def decide(pl):
|
| 286 |
+
pl = pl.copy()
|
| 287 |
+
pl[:, 3] = (pl[:, 3] >= th_roll).astype(np.float32)
|
| 288 |
+
pl[:, SUSTAIN] = np.where(pl[:, SUSTAIN] >= th_sus, np.maximum(pl[:, SUSTAIN], 0.11), 0.0)
|
| 289 |
+
return pl
|
| 290 |
+
for th in a.thresholds:
|
| 291 |
+
plans = {k: (b0, decide(SongPlanner.to_plan(o, threshold=th).numpy())) for k, (b0, o, _) in outs.items()}
|
| 292 |
+
P = np.concatenate([plans[k][1] for k in outs]); T = np.concatenate([outs[k][2] for k in outs])
|
| 293 |
+
pp = [plans[(g[0][3][0], g[0][3][1])][1] for g in pairs]
|
| 294 |
+
report[str(th)] = {"all_val": agreement(P, T, np.ones(len(P), bool)),
|
| 295 |
+
"pairs": agreement(np.concatenate(pp), np.concatenate([g[0][1] for g in pairs]), np.ones(sum(len(g[0][1]) for g in pairs), bool)) if pp else None}
|
| 296 |
+
pickle.dump(plans, open(a.out_dir / f"plans_val_t{th}.pkl", "wb"))
|
| 297 |
+
print(th, json.dumps(report[str(th)]), flush=True)
|
| 298 |
+
(a.out_dir / "thresholds.json").write_text(json.dumps(report, indent=1))
|
| 299 |
+
return
|
| 300 |
+
opt = torch.optim.AdamW(model.parameters(), lr=a.lr, weight_decay=0.01)
|
| 301 |
+
rng = np.random.default_rng(0)
|
| 302 |
+
tr = rows["train"]
|
| 303 |
+
|
| 304 |
+
def as_f32(items):
|
| 305 |
+
return [(x[0].astype(np.float32), x[1], x[2], x[3]) for x in items]
|
| 306 |
+
|
| 307 |
+
def evaluate():
|
| 308 |
+
model.eval()
|
| 309 |
+
P, T, M = [], [], []
|
| 310 |
+
with torch.no_grad():
|
| 311 |
+
for i in range(0, len(rows["val"]), 32):
|
| 312 |
+
X, Tt, Mm, tiers = collate(as_f32(rows["val"][i:i + 32]), device)
|
| 313 |
+
o = model(X, tiers, Mm)
|
| 314 |
+
P.append(SongPlanner.to_plan(o).cpu().numpy().reshape(-1, BAR_F)); T.append(Tt.cpu().numpy().reshape(-1, BAR_F))
|
| 315 |
+
M.append(Mm.cpu().numpy().reshape(-1))
|
| 316 |
+
model.train()
|
| 317 |
+
return agreement(np.concatenate(P), np.concatenate(T), np.concatenate(M))
|
| 318 |
+
|
| 319 |
+
best, log = -1.0, []
|
| 320 |
+
for step in range(1, a.steps + 1):
|
| 321 |
+
lr = a.lr * min(1.0, step / 200) * 0.5 * (1 + math.cos(math.pi * step / a.steps))
|
| 322 |
+
for g in opt.param_groups:
|
| 323 |
+
g["lr"] = lr
|
| 324 |
+
X, T, M, tiers = collate(as_f32([tr[i] for i in rng.integers(len(tr), size=a.batch)]), device)
|
| 325 |
+
loss, parts = loss_fn(model(X, tiers, M), T, M)
|
| 326 |
+
opt.zero_grad(); loss.backward(); torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step()
|
| 327 |
+
if step % 500 == 0 or step == a.steps:
|
| 328 |
+
ev = evaluate()
|
| 329 |
+
rec = {"step": step, "loss": float(loss.detach()), **{k: float(v.detach()) for k, v in parts.items()}, **ev}
|
| 330 |
+
log.append(rec)
|
| 331 |
+
print(json.dumps(rec), flush=True)
|
| 332 |
+
score = ev["play_acc"] + (ev["density_corr"] if ev["density_corr"] == ev["density_corr"] else 0)
|
| 333 |
+
if score > best:
|
| 334 |
+
best = score
|
| 335 |
+
torch.save({"model": model.state_dict(), "d_in": d_in}, a.out_dir / "best.pt")
|
| 336 |
+
# human vs human on the same validation charts: same song, same tier, different mapper
|
| 337 |
+
by = {}
|
| 338 |
+
for x in rows["val"]:
|
| 339 |
+
by.setdefault((x[3][0], x[2]), []).append(x)
|
| 340 |
+
hh_P, hh_T, hh_M = [], [], []
|
| 341 |
+
for g in by.values():
|
| 342 |
+
if len(g) >= 2 and g[0][3][2] == g[1][3][2] and len(g[0][1]) == len(g[1][1]):
|
| 343 |
+
hh_P.append(g[1][1]); hh_T.append(g[0][1]); hh_M.append(np.ones(len(g[0][1]), bool))
|
| 344 |
+
hh = agreement(np.concatenate(hh_P), np.concatenate(hh_T), np.concatenate(hh_M)) if hh_P else None
|
| 345 |
+
# planner on the same pairs (predicting the first mapper)
|
| 346 |
+
model.load_state_dict(torch.load(a.out_dir / "best.pt", map_location=device)["model"])
|
| 347 |
+
model.eval()
|
| 348 |
+
plans = {}
|
| 349 |
+
with torch.no_grad():
|
| 350 |
+
for i in range(0, len(rows["val"]), 32):
|
| 351 |
+
part = rows["val"][i:i + 32]
|
| 352 |
+
X, Tt, Mm, tiers = collate(as_f32(part), device)
|
| 353 |
+
P = SongPlanner.to_plan(model(X, tiers, Mm)).cpu().numpy()
|
| 354 |
+
for b, x in enumerate(part):
|
| 355 |
+
plans[(x[3][0], x[3][1])] = (x[3][2], P[b, : len(x[0])])
|
| 356 |
+
pl_P = [plans[(g[0][3][0], g[0][3][1])][1] for g in by.values() if len(g) >= 2 and g[0][3][2] == g[1][3][2] and len(g[0][1]) == len(g[1][1])]
|
| 357 |
+
pl = agreement(np.concatenate(pl_P), np.concatenate(hh_T), np.concatenate(hh_M)) if pl_P else None
|
| 358 |
+
res = {"train_charts": len(rows["train"]), "val_charts": len(rows["val"]), "log": log, "final": log[-1],
|
| 359 |
+
"pairs": {"n": len(hh_P), "human_vs_human": hh, "planner_vs_human": pl}}
|
| 360 |
+
(a.out_dir / "result.json").write_text(json.dumps(res, indent=1))
|
| 361 |
+
pickle.dump(plans, open(a.out_dir / "plans_val.pkl", "wb"))
|
| 362 |
+
print(json.dumps(res["pairs"], indent=1), flush=True)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
if __name__ == "__main__":
|
| 366 |
+
main()
|
chartgen/timing.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Decode beat / downbeat activations (100 fps) into an osu!-style timing map.
|
| 2 |
+
|
| 3 |
+
osu! timing is a list of sections (red lines): start time, beat length, meter. Charts are
|
| 4 |
+
snapped to this grid to within ~1 ms (Stage 0), so the grid must be accurate to a few ms over
|
| 5 |
+
the whole song: a 0.01% tempo error drifts ~12 ms over two minutes. The decoder therefore fits
|
| 6 |
+
period and phase jointly over many beats instead of picking individual peaks.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
FPS = 100.0
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _interp(act: np.ndarray, frames: np.ndarray) -> np.ndarray:
|
| 17 |
+
f0 = np.floor(frames).astype(np.int64)
|
| 18 |
+
w = frames - f0
|
| 19 |
+
ok = (f0 >= 0) & (f0 + 1 < len(act))
|
| 20 |
+
out = np.zeros(frames.shape, dtype=np.float64)
|
| 21 |
+
f0c = np.clip(f0, 0, len(act) - 2)
|
| 22 |
+
out[ok] = (act[f0c] * (1 - w) + act[f0c + 1] * w)[ok]
|
| 23 |
+
return out
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _score(act, t0_ms, t1_ms, periods_ms, phases_ms):
|
| 27 |
+
"""Mean activation at beats phase + k*period inside [t0, t1], for all (period, phase) pairs."""
|
| 28 |
+
P = periods_ms[:, None, None]
|
| 29 |
+
ph = phases_ms[None, :, None] if phases_ms.ndim == 1 else phases_ms[:, :, None]
|
| 30 |
+
kmax = int(np.ceil((t1_ms - t0_ms) / periods_ms.min())) + 1
|
| 31 |
+
k = np.arange(kmax)[None, None, :]
|
| 32 |
+
t = t0_ms + ph + k * P
|
| 33 |
+
valid = t <= t1_ms
|
| 34 |
+
vals = _interp(act, t / 10.0) * valid
|
| 35 |
+
return vals.sum(-1) / np.maximum(valid.sum(-1), 1)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def fit_constant_tempo(act: np.ndarray, t0_ms: float, t1_ms: float, bpm_range=(60.0, 320.0),
|
| 39 |
+
adjust_level: bool = True) -> tuple[float, float, float]:
|
| 40 |
+
"""Return (beat_length_ms, phase_ms relative to t0, score) for one constant-tempo stretch."""
|
| 41 |
+
seg = act[int(t0_ms / 10): int(t1_ms / 10) + 1].astype(np.float64)
|
| 42 |
+
if len(seg) < 200:
|
| 43 |
+
return 500.0, 0.0, 0.0
|
| 44 |
+
x = seg - seg.mean()
|
| 45 |
+
ac = np.correlate(x, x, mode="full")[len(x) - 1:]
|
| 46 |
+
lo, hi = int(60000 / bpm_range[1] / 10), int(60000 / bpm_range[0] / 10)
|
| 47 |
+
lags = np.arange(lo, min(hi, len(ac) - 1))
|
| 48 |
+
cand = lags[np.argsort(ac[lags])[::-1][:6]] * 10.0 # ms
|
| 49 |
+
best = (500.0, 0.0, -1.0)
|
| 50 |
+
for c in cand:
|
| 51 |
+
# stage 1: +/-3% in 0.05% steps, phase in 2 ms steps
|
| 52 |
+
periods = c * (1 + np.arange(-0.03, 0.03, 0.0005))
|
| 53 |
+
phases = np.arange(0, c * 1.03, 2.0)
|
| 54 |
+
sc = _score(act, t0_ms, t1_ms, periods, phases)
|
| 55 |
+
i, j = np.unravel_index(np.argmax(sc), sc.shape)
|
| 56 |
+
p1, f1 = periods[i], phases[j]
|
| 57 |
+
# stage 2: +/-0.06% in 0.002% steps, phase +/-3 ms in 0.25 ms steps
|
| 58 |
+
periods = p1 * (1 + np.arange(-0.0006, 0.0006, 0.00002))
|
| 59 |
+
phases = f1 + np.arange(-3, 3, 0.25)
|
| 60 |
+
sc = _score(act, t0_ms, t1_ms, periods, phases)
|
| 61 |
+
i, j = np.unravel_index(np.argmax(sc), sc.shape)
|
| 62 |
+
if sc[i, j] > best[2]:
|
| 63 |
+
best = (float(periods[i]), float(phases[j] % periods[i]), float(sc[i, j]))
|
| 64 |
+
# beat level: prefer the fastest metrical level that still scores >= 80% of the best
|
| 65 |
+
p, f, s = best
|
| 66 |
+
for mult in ((0.5, 1 / 3) if adjust_level else ()):
|
| 67 |
+
q = p * mult
|
| 68 |
+
if 60000 / q > bpm_range[1]:
|
| 69 |
+
continue
|
| 70 |
+
sc = _score(act, t0_ms, t1_ms, np.array([q]), f + np.arange(-2, 2, 0.25))
|
| 71 |
+
if sc.max() >= 0.8 * s:
|
| 72 |
+
j = int(np.argmax(sc))
|
| 73 |
+
p, f, s = q, float((f + np.arange(-2, 2, 0.25)[j]) % q), float(sc.max())
|
| 74 |
+
return p, f, s
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _choose_meter(down: np.ndarray, beat_times: np.ndarray) -> tuple[int, int]:
|
| 78 |
+
best = (4, 0, -1.0)
|
| 79 |
+
vals = _interp(down, beat_times / 10.0)
|
| 80 |
+
for m in (4, 3):
|
| 81 |
+
for j in range(m):
|
| 82 |
+
v = vals[j::m]
|
| 83 |
+
sc = v.mean() if len(v) else 0.0
|
| 84 |
+
if sc > best[2] * (1.02 if m == 3 else 1.0): # mild preference for 4/4
|
| 85 |
+
best = (m, j, sc)
|
| 86 |
+
return best[0], best[1]
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def decode_timing(beat_act: np.ndarray, down_act: np.ndarray, t0_ms: float, t1_ms: float,
|
| 90 |
+
window_s: float = 24.0, change_tol: float = 0.01) -> np.ndarray:
|
| 91 |
+
"""Return sections [n, 5]: time_ms, beat_length_ms, meter, start_beat, omit_barline.
|
| 92 |
+
|
| 93 |
+
Fits a global tempo, then local tempos on overlapping windows; consecutive windows whose
|
| 94 |
+
tempo departs from the running segment by more than ``change_tol`` start a new segment.
|
| 95 |
+
"""
|
| 96 |
+
p, f, s = fit_constant_tempo(beat_act, t0_ms, t1_ms)
|
| 97 |
+
# local tempo track
|
| 98 |
+
bounds = [t0_ms]
|
| 99 |
+
step = window_s * 500.0
|
| 100 |
+
local = []
|
| 101 |
+
t = t0_ms
|
| 102 |
+
while t + window_s * 1000 <= t1_ms + step:
|
| 103 |
+
a, b = t, min(t + window_s * 1000, t1_ms)
|
| 104 |
+
if b - a >= 8000:
|
| 105 |
+
lp, lf, ls = fit_constant_tempo(beat_act, a, b, bpm_range=(60000 / p / 1.6, 60000 / p * 2.2))
|
| 106 |
+
# express local tempo at the global beat level
|
| 107 |
+
ratio = lp / p
|
| 108 |
+
for r in (0.5, 2.0, 1 / 3, 3.0, 2 / 3, 1.5):
|
| 109 |
+
if abs(ratio * r - 1) < abs(ratio - 1):
|
| 110 |
+
ratio, lp = ratio * r, lp * r
|
| 111 |
+
local.append((a, b, lp, ls))
|
| 112 |
+
t += step
|
| 113 |
+
segs = []
|
| 114 |
+
cur = None
|
| 115 |
+
for a, b, lp, ls in local:
|
| 116 |
+
if cur is None:
|
| 117 |
+
cur = [a, b, lp]
|
| 118 |
+
elif abs(lp / cur[2] - 1) > change_tol:
|
| 119 |
+
segs.append(cur)
|
| 120 |
+
cur = [(a + b) / 2 - window_s * 250, b, lp]
|
| 121 |
+
else:
|
| 122 |
+
cur[1] = b
|
| 123 |
+
if cur is not None:
|
| 124 |
+
segs.append(cur)
|
| 125 |
+
# refit each segment on its own span, searching only near its local tempo
|
| 126 |
+
sections = []
|
| 127 |
+
if len(segs) <= 1:
|
| 128 |
+
fits = [(t0_ms, t1_ms, p, f)]
|
| 129 |
+
else:
|
| 130 |
+
fits = []
|
| 131 |
+
for i, (a, b, lp) in enumerate(segs):
|
| 132 |
+
a = t0_ms if i == 0 else a
|
| 133 |
+
b = t1_ms if i == len(segs) - 1 else segs[i + 1][0]
|
| 134 |
+
if b - a < 4000:
|
| 135 |
+
continue
|
| 136 |
+
sp, sf, _ = fit_constant_tempo(beat_act, a, b, bpm_range=(60000 / lp * 0.95, 60000 / lp * 1.05), adjust_level=False)
|
| 137 |
+
fits.append((a, b, sp, sf))
|
| 138 |
+
for i, (a, b, sp, sf) in enumerate(fits):
|
| 139 |
+
first = a + sf
|
| 140 |
+
beats = first + np.arange(0, int((b - first) / sp) + 1) * sp
|
| 141 |
+
m, j = _choose_meter(down_act, beats)
|
| 142 |
+
start = first + j * sp
|
| 143 |
+
if i == 0: # extend the first section back to the song start on whole bars
|
| 144 |
+
start -= np.floor(start / (sp * m)) * sp * m
|
| 145 |
+
sections.append([start, sp, m])
|
| 146 |
+
out = []
|
| 147 |
+
sb = 0.0
|
| 148 |
+
for i, (t, bl, m) in enumerate(sections):
|
| 149 |
+
if i > 0:
|
| 150 |
+
pt, pbl, _ = sections[i - 1]
|
| 151 |
+
raw = sb + (t - pt) / pbl
|
| 152 |
+
sb = float(round(raw)) if abs(raw - round(raw)) < 1e-3 else float(np.ceil(raw))
|
| 153 |
+
out.append([t, bl, m, sb, 0.0])
|
| 154 |
+
return np.array(out, dtype=np.float64)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def beat_times(sections: np.ndarray, t0_ms: float, t1_ms: float) -> tuple[np.ndarray, np.ndarray]:
|
| 158 |
+
"""All beat and downbeat times of a section list within [t0, t1]."""
|
| 159 |
+
beats, downs = [], []
|
| 160 |
+
for i, (t, bl, m, _, _) in enumerate(sections[:, :5] if sections.shape[1] >= 5 else np.c_[sections, np.zeros(len(sections))]):
|
| 161 |
+
end = sections[i + 1, 0] if i + 1 < len(sections) else t1_ms
|
| 162 |
+
k0 = int(np.ceil((max(t0_ms, -1e9) - t) / bl)) if t < t0_ms else 0
|
| 163 |
+
k1 = int(np.floor((end - t) / bl - 1e-9))
|
| 164 |
+
for k in range(k0, k1 + 1):
|
| 165 |
+
tb = t + k * bl
|
| 166 |
+
if t0_ms <= tb <= t1_ms and tb < end:
|
| 167 |
+
beats.append(tb)
|
| 168 |
+
if k % int(m) == 0:
|
| 169 |
+
downs.append(tb)
|
| 170 |
+
return np.array(beats), np.array(downs)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def timing_metrics(pred_sections: np.ndarray, true_sections: np.ndarray, t0_ms: float, t1_ms: float) -> dict:
|
| 174 |
+
"""Compare a decoded timing map to the mapper's over the chart span."""
|
| 175 |
+
tb, td = beat_times(true_sections, t0_ms, t1_ms)
|
| 176 |
+
pb, pd = beat_times(pred_sections, t0_ms - 2000, t1_ms + 2000)
|
| 177 |
+
if len(tb) == 0 or len(pb) == 0:
|
| 178 |
+
return {}
|
| 179 |
+
idx = np.clip(np.searchsorted(pb, tb), 1, len(pb) - 1)
|
| 180 |
+
err = np.minimum(np.abs(pb[idx] - tb), np.abs(pb[idx - 1] - tb))
|
| 181 |
+
main_true = true_sections[np.argmax(np.diff(np.r_[true_sections[:, 0], t1_ms]))] if len(true_sections) else None
|
| 182 |
+
main_pred = pred_sections[np.argmax(np.diff(np.r_[pred_sections[:, 0], t1_ms]))]
|
| 183 |
+
ratio = main_pred[1] / main_true[1]
|
| 184 |
+
res = {
|
| 185 |
+
"beat_err_median_ms": float(np.median(err)),
|
| 186 |
+
"beat_within_5ms": float(np.mean(err <= 5)),
|
| 187 |
+
"beat_within_10ms": float(np.mean(err <= 10)),
|
| 188 |
+
"beat_within_20ms": float(np.mean(err <= 20)),
|
| 189 |
+
"bpm_rel_err": float(abs(ratio - 1)),
|
| 190 |
+
"bpm_level": "same" if abs(ratio - 1) < 0.01 else ("half" if abs(ratio - 2) < 0.02 else ("double" if abs(ratio - 0.5) < 0.01 else "other")),
|
| 191 |
+
"n_sections_true": int(len(true_sections)),
|
| 192 |
+
"n_sections_pred": int(len(pred_sections)),
|
| 193 |
+
}
|
| 194 |
+
if len(td) and len(pd):
|
| 195 |
+
idx = np.clip(np.searchsorted(pd, td), 1, len(pd) - 1)
|
| 196 |
+
derr = np.minimum(np.abs(pd[idx] - td), np.abs(pd[idx - 1] - td))
|
| 197 |
+
res["downbeat_within_20ms"] = float(np.mean(derr <= 20))
|
| 198 |
+
return res
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def tempo_class(sections: np.ndarray, t0_ms: float, t1_ms: float, tol: float = 0.002) -> str:
|
| 202 |
+
"""Classify a mapper timing map over [t0, t1]: 'constant', 'step' (a few sustained tempo
|
| 203 |
+
changes) or 'gradual' (accelerando/ritardando or rapid alternation: four or more tempo
|
| 204 |
+
changes within any 8 s, which only occurs when tempo is written beat by beat)."""
|
| 205 |
+
s = sections[(sections[:, 0] < t1_ms)]
|
| 206 |
+
if len(s) == 0:
|
| 207 |
+
return "constant"
|
| 208 |
+
keep = np.r_[True, np.abs(np.diff(np.log(s[:, 1]))) > tol]
|
| 209 |
+
ch = s[keep][1:, 0] # times where the tempo really changes
|
| 210 |
+
ch = ch[ch > t0_ms]
|
| 211 |
+
if len(ch) == 0:
|
| 212 |
+
return "constant"
|
| 213 |
+
if len(ch) >= 4 and np.min(ch[3:] - ch[:-3]) < 8000:
|
| 214 |
+
return "gradual"
|
| 215 |
+
return "step"
|
chartgen/train.py
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Train B0 with live, logged adjustments (README section 4, "訓練中的調整方式").
|
| 2 |
+
|
| 3 |
+
The run directory holds:
|
| 4 |
+
metrics.jsonl training / validation records
|
| 5 |
+
control.json written by the operator (agent); read every --control-every steps
|
| 6 |
+
interventions.jsonl every applied control change with step and reason
|
| 7 |
+
status.json latest summary
|
| 8 |
+
last.pt / best.pt checkpoints
|
| 9 |
+
|
| 10 |
+
control.json keys (all optional): lr, weights {note,length,timing,plan}, eval_now, gen_now,
|
| 11 |
+
save, stop, reason. Only validation data drive decisions; the test split is never loaded here.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import hashlib
|
| 18 |
+
import json
|
| 19 |
+
import math
|
| 20 |
+
import os
|
| 21 |
+
import time
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn.functional as F
|
| 27 |
+
|
| 28 |
+
from .dataset import N_TYPE, WindowSampler, collate, fixed_windows, load_songs
|
| 29 |
+
from .generate import evaluate_generation, generate
|
| 30 |
+
from .model import DEFAULT_WEIGHTS, B0, B0Config, b0_loss
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def song_split(key: str, val_frac: float = 0.1, test_frac: float = 0.1) -> str:
|
| 34 |
+
"""Deterministic split by song key (normalised artist|title), shared by all scripts."""
|
| 35 |
+
h = int(hashlib.sha1(f"split:{key}".encode()).hexdigest(), 16) % 10_000 / 10_000
|
| 36 |
+
return "test" if h < test_frac else ("val" if h < test_frac + val_frac else "train")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def split_songs(songs, val_frac, min_year=0):
|
| 40 |
+
keep = []
|
| 41 |
+
for s in songs:
|
| 42 |
+
charts = [c for c in s["charts"] if c.get("year", 9999) >= min_year]
|
| 43 |
+
if charts:
|
| 44 |
+
keep.append({**s, "charts": charts})
|
| 45 |
+
key = lambda s: s.get("song_key") or str(s["beatmapset_id"]) # noqa: E731
|
| 46 |
+
train = [s for s in keep if song_split(key(s), val_frac) == "train"]
|
| 47 |
+
val = [s for s in keep if song_split(key(s), val_frac) == "val"]
|
| 48 |
+
return train, val
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def type_weights(songs):
|
| 52 |
+
counts = np.ones(N_TYPE)
|
| 53 |
+
for s in songs:
|
| 54 |
+
for c in s["charts"]:
|
| 55 |
+
counts += np.bincount(c["type"], minlength=N_TYPE)
|
| 56 |
+
w = counts ** -0.5
|
| 57 |
+
return torch.tensor(w / w.mean(), dtype=torch.float32)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class Run:
|
| 61 |
+
def __init__(self, run_dir: Path):
|
| 62 |
+
self.dir = run_dir
|
| 63 |
+
self.dir.mkdir(parents=True, exist_ok=True)
|
| 64 |
+
self.metrics = open(run_dir / "metrics.jsonl", "a")
|
| 65 |
+
self.interventions = open(run_dir / "interventions.jsonl", "a")
|
| 66 |
+
self.control_path = run_dir / "control.json"
|
| 67 |
+
self._control_mtime = self.control_path.stat().st_mtime if self.control_path.exists() else 0.0
|
| 68 |
+
|
| 69 |
+
def log(self, rec):
|
| 70 |
+
self.metrics.write(json.dumps(rec) + "\n")
|
| 71 |
+
self.metrics.flush()
|
| 72 |
+
|
| 73 |
+
def status(self, rec):
|
| 74 |
+
tmp = self.dir / "status.json.tmp"
|
| 75 |
+
tmp.write_text(json.dumps(rec, indent=1))
|
| 76 |
+
os.replace(tmp, self.dir / "status.json")
|
| 77 |
+
|
| 78 |
+
def read_control(self):
|
| 79 |
+
if not self.control_path.exists():
|
| 80 |
+
return None
|
| 81 |
+
m = self.control_path.stat().st_mtime
|
| 82 |
+
if m == self._control_mtime:
|
| 83 |
+
return None
|
| 84 |
+
self._control_mtime = m
|
| 85 |
+
try:
|
| 86 |
+
return json.loads(self.control_path.read_text())
|
| 87 |
+
except json.JSONDecodeError:
|
| 88 |
+
return None
|
| 89 |
+
|
| 90 |
+
def intervene(self, step, changes, reason):
|
| 91 |
+
self.interventions.write(json.dumps({"step": step, "time": time.time(), "changes": changes, "reason": reason}) + "\n")
|
| 92 |
+
self.interventions.flush()
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@torch.no_grad()
|
| 96 |
+
def validate(model, val_windows, device, weights, tw, bs=32, amp=None):
|
| 97 |
+
model.eval()
|
| 98 |
+
sums, n = {}, 0
|
| 99 |
+
gap_correct = gap_total = type_correct = type_total = sv_correct = 0
|
| 100 |
+
beat_tp = beat_np = beat_nr = 0
|
| 101 |
+
kiai_tp = kiai_fp = kiai_fn = kiai_n = kiai_ok = 0
|
| 102 |
+
for i in range(0, len(val_windows), bs):
|
| 103 |
+
batch = {k: v.to(device) for k, v in collate(val_windows[i:i + bs]).items()}
|
| 104 |
+
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=amp is not None):
|
| 105 |
+
out = model(batch, plan_source="pred")
|
| 106 |
+
total, parts = b0_loss(out, batch, weights, tw)
|
| 107 |
+
for k, v in {"total": total, **parts}.items():
|
| 108 |
+
sums[k] = sums.get(k, 0.0) + float(v)
|
| 109 |
+
n += 1
|
| 110 |
+
gm = batch["tgt_ahead"] != -100
|
| 111 |
+
ok_ahead = out["ahead_logits"].argmax(-1) == batch["tgt_ahead"]
|
| 112 |
+
ok_phase = (out["phase_logits"].argmax(-1) == batch["tgt_phase"]) | (batch["tgt_phase"] == -100)
|
| 113 |
+
gap_correct += int((ok_ahead & ok_phase)[gm].sum())
|
| 114 |
+
gap_total += int(gm.sum())
|
| 115 |
+
tm = batch["ev_type"] != -100
|
| 116 |
+
type_correct += int((out["type_logits"].argmax(-1)[tm] == batch["ev_type"][tm]).sum())
|
| 117 |
+
type_total += int(tm.sum())
|
| 118 |
+
sv_correct += int((out["sv_logits"].argmax(-1)[tm] == batch["ev_sv"][tm]).sum())
|
| 119 |
+
# beat peaks within +/-2 frames (20 ms) of reference beats, on frames where timing is defined
|
| 120 |
+
act = torch.sigmoid(out["timing_logits"][..., 0].float())
|
| 121 |
+
peak = (act > 0.5) & (act >= F.max_pool1d(act[:, None], 5, 1, 2)[:, 0])
|
| 122 |
+
ref = batch["beat_tgt"] >= 0.5
|
| 123 |
+
bm = batch["beat_mask"] > 0
|
| 124 |
+
near_ref = F.max_pool1d(ref[:, None].float(), 5, 1, 2)[:, 0] > 0
|
| 125 |
+
near_peak = F.max_pool1d(peak[:, None].float(), 5, 1, 2)[:, 0] > 0
|
| 126 |
+
beat_tp += int((peak & near_ref & bm).sum())
|
| 127 |
+
beat_np += int((peak & bm).sum())
|
| 128 |
+
beat_nr += int((ref & bm).sum())
|
| 129 |
+
beat_rec_hit = int((ref & near_peak & bm).sum())
|
| 130 |
+
kp = torch.sigmoid(out["kiai_logits"].float()) > 0.5
|
| 131 |
+
kt = batch["kiai_tgt"] > 0.5
|
| 132 |
+
km = batch["kiai_mask"] > 0
|
| 133 |
+
kiai_tp += int((kp & kt & km).sum()); kiai_fp += int((kp & ~kt & km).sum()); kiai_fn += int((~kp & kt & km).sum())
|
| 134 |
+
kiai_ok += int(((kp == kt) & km).sum()); kiai_n += int(km.sum())
|
| 135 |
+
sums["_beat_rec_hit"] = sums.get("_beat_rec_hit", 0.0) + beat_rec_hit
|
| 136 |
+
model.train()
|
| 137 |
+
res = {f"val_{k}": v / n for k, v in sums.items()}
|
| 138 |
+
res["val_pos_acc"] = gap_correct / max(gap_total, 1)
|
| 139 |
+
res["val_type_acc"] = type_correct / max(type_total, 1)
|
| 140 |
+
res["val_sv_acc"] = sv_correct / max(type_total, 1)
|
| 141 |
+
bp, br = beat_tp / max(beat_np, 1), sums.pop("_beat_rec_hit", 0.0) / max(beat_nr, 1)
|
| 142 |
+
res.pop("val__beat_rec_hit", None)
|
| 143 |
+
res["val_beat_f1"] = 2 * bp * br / max(bp + br, 1e-9)
|
| 144 |
+
res["val_kiai_acc"] = kiai_ok / max(kiai_n, 1)
|
| 145 |
+
res["val_kiai_f1"] = 2 * kiai_tp / max(2 * kiai_tp + kiai_fp + kiai_fn, 1)
|
| 146 |
+
return res
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def main(argv=None):
|
| 150 |
+
p = argparse.ArgumentParser()
|
| 151 |
+
p.add_argument("--data", nargs="+", type=Path, required=True)
|
| 152 |
+
p.add_argument("--run-dir", type=Path, required=True)
|
| 153 |
+
p.add_argument("--val-frac", type=float, default=0.1)
|
| 154 |
+
p.add_argument("--batch", type=int, default=32)
|
| 155 |
+
p.add_argument("--lr", type=float, default=3e-4)
|
| 156 |
+
p.add_argument("--warmup", type=int, default=300)
|
| 157 |
+
p.add_argument("--max-steps", type=int, default=20000, help="compute cap; the operator usually stops earlier")
|
| 158 |
+
p.add_argument("--log-every", type=int, default=50)
|
| 159 |
+
p.add_argument("--control-every", type=int, default=50)
|
| 160 |
+
p.add_argument("--eval-every", type=int, default=500)
|
| 161 |
+
p.add_argument("--gen-every", type=int, default=2000)
|
| 162 |
+
p.add_argument("--val-windows", type=int, default=256)
|
| 163 |
+
p.add_argument("--gen-windows", type=int, default=64)
|
| 164 |
+
p.add_argument("--workers", type=int, default=4)
|
| 165 |
+
p.add_argument("--lr-range-test", type=int, default=0, help="steps of exponential LR sweep 1e-6 -> 1e-1, then exit")
|
| 166 |
+
p.add_argument("--resume", type=Path)
|
| 167 |
+
p.add_argument("--seed", type=int, default=0)
|
| 168 |
+
p.add_argument("--small", action="store_true", help="tiny model for CPU smoke tests")
|
| 169 |
+
p.add_argument("--replay", nargs="*", default=[],
|
| 170 |
+
help="replay a recorded schedule, e.g. 6450:lr=1e-4 4000:weights.plan=0.1 9150:stop (same changes at the same steps)")
|
| 171 |
+
p.add_argument("--init-model", type=Path, help="B0 checkpoint to fine-tune from (new modules, e.g. --gap-plan, start fresh)")
|
| 172 |
+
p.add_argument("--new-lr-mult", type=float, default=10.0,
|
| 173 |
+
help="learning-rate multiplier for modules that --init-model did not provide (zero-initialised, start slow)")
|
| 174 |
+
p.add_argument("--no-type-weights", action="store_true", help="plain cross-entropy for note types (no class weights)")
|
| 175 |
+
p.add_argument("--note-coord", choices=["true", "grid"], default="true",
|
| 176 |
+
help="note-head lookups in training from the note's real time (old) or its grid time (stage 4b)")
|
| 177 |
+
p.add_argument("--stretch-p", type=float, default=0.0, help="probability of a tempo-stretched training window")
|
| 178 |
+
p.add_argument("--plan-corrupt", type=float, default=0.0, help="probability that a given bar plan is corrupted like a prediction")
|
| 179 |
+
p.add_argument("--plan-drop", type=float, default=0.3, help="probability that no bar plan is given in training")
|
| 180 |
+
p.add_argument("--rep-hint", action="store_true", help="per-bar repetition hint from the audio")
|
| 181 |
+
p.add_argument("--bar-plan", action="store_true", help="decoder conditioned on a per-bar plan (oracle in training)")
|
| 182 |
+
p.add_argument("--gap-plan", action="store_true", help="planner predicts and decoder uses per-section note-gap distributions")
|
| 183 |
+
p.add_argument("--init-encoder", type=Path, help="Stage A checkpoint: load its (EMA target) music encoder into B0")
|
| 184 |
+
p.add_argument("--mmap", action="store_true", help="memory-map mel features (corpus larger than RAM)")
|
| 185 |
+
p.add_argument("--min-year", type=int, default=2014, help="drop charts ranked before this year")
|
| 186 |
+
a = p.parse_args(argv)
|
| 187 |
+
from . import dataset as _ds
|
| 188 |
+
_ds.NOTE_COORD = a.note_coord # read by make_example (forked loader workers inherit it)
|
| 189 |
+
|
| 190 |
+
torch.manual_seed(a.seed)
|
| 191 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 192 |
+
amp = torch.bfloat16 if device.type == "cuda" else None
|
| 193 |
+
run = Run(a.run_dir)
|
| 194 |
+
|
| 195 |
+
songs = load_songs(a.data, mmap=a.mmap)
|
| 196 |
+
train_songs, val_songs = split_songs(songs, a.val_frac, a.min_year)
|
| 197 |
+
(a.run_dir / "split.json").write_text(json.dumps({"train": sorted({s.get("song_key", "") for s in train_songs}),
|
| 198 |
+
"val": sorted({s.get("song_key", "") for s in val_songs})}))
|
| 199 |
+
val_windows = fixed_windows(val_songs, a.val_windows)
|
| 200 |
+
gen_windows = val_windows[: a.gen_windows]
|
| 201 |
+
tw = None if a.no_type_weights else type_weights(train_songs).to(device)
|
| 202 |
+
|
| 203 |
+
cfg = B0Config(d_model=64, enc_layers=1, dec_layers=1, n_heads=4, d_plan=32, plan_layers=1, branch_ch=16) if a.small else B0Config()
|
| 204 |
+
cfg.gap_plan = a.gap_plan
|
| 205 |
+
cfg.bar_plan = a.bar_plan
|
| 206 |
+
cfg.bar_plan_corrupt = a.plan_corrupt
|
| 207 |
+
cfg.bar_plan_drop = a.plan_drop
|
| 208 |
+
cfg.rep_hint = a.rep_hint
|
| 209 |
+
model = B0(cfg).to(device)
|
| 210 |
+
if a.init_model:
|
| 211 |
+
ck = torch.load(a.init_model, map_location=device, weights_only=False)
|
| 212 |
+
sd = dict(ck["model"])
|
| 213 |
+
w_old = sd.get("bar_plan_proj.weight")
|
| 214 |
+
if w_old is not None and hasattr(model, "bar_plan_proj") and w_old.shape != model.bar_plan_proj.weight.shape:
|
| 215 |
+
# plan grew from 16 features + "plan given" flag to BAR_F (17: + sustain) + flag: keep the learned columns,
|
| 216 |
+
# move the flag column, start the new feature at zero
|
| 217 |
+
w_new = torch.zeros_like(model.bar_plan_proj.weight)
|
| 218 |
+
n_old = w_old.shape[1] - 1
|
| 219 |
+
w_new[:, :n_old] = w_old[:, :n_old]
|
| 220 |
+
w_new[:, -1] = w_old[:, -1]
|
| 221 |
+
sd["bar_plan_proj.weight"] = w_new
|
| 222 |
+
print(f"bar_plan_proj expanded {tuple(w_old.shape)} -> {tuple(w_new.shape)}", flush=True)
|
| 223 |
+
missing, unexpected = model.load_state_dict(sd, strict=False)
|
| 224 |
+
assert not unexpected, unexpected
|
| 225 |
+
print("init model from", a.init_model, "new (untrained) tensors:", missing, flush=True)
|
| 226 |
+
if a.init_encoder:
|
| 227 |
+
ck = torch.load(a.init_encoder, map_location=device, weights_only=False)
|
| 228 |
+
sd = {k: v for k, v in ck["target_encoder"].items() if k != "mask_tok"}
|
| 229 |
+
missing, unexpected = model.load_state_dict(sd, strict=False)
|
| 230 |
+
assert not unexpected, unexpected
|
| 231 |
+
print("init encoder from", a.init_encoder, "loaded", len(sd), "tensors", flush=True)
|
| 232 |
+
n_params = sum(p.numel() for p in model.parameters())
|
| 233 |
+
new_names = set(missing) if a.init_model else set()
|
| 234 |
+
groups = [{"params": [p_ for n_, p_ in model.named_parameters() if n_ not in new_names], "mult": 1.0},
|
| 235 |
+
{"params": [p_ for n_, p_ in model.named_parameters() if n_ in new_names], "mult": a.new_lr_mult}]
|
| 236 |
+
opt = torch.optim.AdamW([g for g in groups if g["params"]], lr=a.lr, weight_decay=0.01)
|
| 237 |
+
|
| 238 |
+
state = {"lr": a.lr, "weights": dict(DEFAULT_WEIGHTS)}
|
| 239 |
+
step, best = 0, math.inf
|
| 240 |
+
if a.resume:
|
| 241 |
+
ck = torch.load(a.resume, map_location=device, weights_only=False)
|
| 242 |
+
model.load_state_dict(ck["model"])
|
| 243 |
+
opt.load_state_dict(ck["opt"])
|
| 244 |
+
step, best, state = ck["step"], ck["best"], ck["state"]
|
| 245 |
+
|
| 246 |
+
run.log({"event": "start", "step": step, "params": n_params, "device": str(device),
|
| 247 |
+
"gpu": torch.cuda.get_device_name() if device.type == "cuda" else None,
|
| 248 |
+
"train_songs": len(train_songs), "val_songs": len(val_songs),
|
| 249 |
+
"train_charts": sum(len(s["charts"]) for s in train_songs), "args": {k: str(v) for k, v in vars(a).items()}})
|
| 250 |
+
|
| 251 |
+
loader = torch.utils.data.DataLoader(
|
| 252 |
+
WindowSampler(train_songs, a.seed, stretch_p=a.stretch_p), batch_size=a.batch, collate_fn=collate,
|
| 253 |
+
num_workers=a.workers, pin_memory=device.type == "cuda", persistent_workers=a.workers > 0,
|
| 254 |
+
prefetch_factor=4 if a.workers > 0 else None)
|
| 255 |
+
it = iter(loader)
|
| 256 |
+
|
| 257 |
+
def save(name):
|
| 258 |
+
torch.save({"model": model.state_dict(), "opt": opt.state_dict(), "step": step, "best": best,
|
| 259 |
+
"state": state, "config": cfg.__dict__}, a.run_dir / name)
|
| 260 |
+
|
| 261 |
+
ema, t_last, wait_acc, comp_acc, n_since = {}, time.time(), 0.0, 0.0, 0
|
| 262 |
+
min_loss = math.inf
|
| 263 |
+
model.train()
|
| 264 |
+
while step < (a.lr_range_test or a.max_steps):
|
| 265 |
+
t0 = time.time()
|
| 266 |
+
batch = next(it)
|
| 267 |
+
batch = {k: v.to(device, non_blocking=True) for k, v in batch.items()}
|
| 268 |
+
t1 = time.time()
|
| 269 |
+
|
| 270 |
+
if a.lr_range_test:
|
| 271 |
+
lr = 1e-6 * (1e-1 / 1e-6) ** (step / a.lr_range_test)
|
| 272 |
+
else:
|
| 273 |
+
lr = state["lr"] * min(1.0, (step + 1) / a.warmup)
|
| 274 |
+
for g in opt.param_groups:
|
| 275 |
+
g["lr"] = lr * g.get("mult", 1.0)
|
| 276 |
+
|
| 277 |
+
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=amp is not None):
|
| 278 |
+
out = model(batch)
|
| 279 |
+
loss, parts = b0_loss(out, batch, state["weights"], tw)
|
| 280 |
+
opt.zero_grad(set_to_none=True)
|
| 281 |
+
loss.backward()
|
| 282 |
+
gnorm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0))
|
| 283 |
+
opt.step()
|
| 284 |
+
step += 1
|
| 285 |
+
if device.type == "cuda":
|
| 286 |
+
torch.cuda.synchronize()
|
| 287 |
+
t2 = time.time()
|
| 288 |
+
wait_acc += t1 - t0
|
| 289 |
+
comp_acc += t2 - t1
|
| 290 |
+
n_since += 1
|
| 291 |
+
|
| 292 |
+
lv = float(loss.detach())
|
| 293 |
+
if not math.isfinite(lv):
|
| 294 |
+
run.log({"event": "nonfinite_loss", "step": step, "lr": lr})
|
| 295 |
+
if a.lr_range_test:
|
| 296 |
+
break
|
| 297 |
+
continue
|
| 298 |
+
for k, v in {"loss": lv, **{k: float(v) for k, v in parts.items()}}.items():
|
| 299 |
+
ema[k] = v if k not in ema else 0.9 * ema[k] + 0.1 * v
|
| 300 |
+
|
| 301 |
+
if a.lr_range_test:
|
| 302 |
+
run.log({"event": "lr_range", "step": step, "lr": lr, "loss": lv, "loss_ema": ema["loss"]})
|
| 303 |
+
min_loss = min(min_loss, ema["loss"])
|
| 304 |
+
if step > 20 and ema["loss"] > 4 * min_loss:
|
| 305 |
+
break
|
| 306 |
+
continue
|
| 307 |
+
|
| 308 |
+
if step % a.log_every == 0:
|
| 309 |
+
dt = time.time() - t_last
|
| 310 |
+
rec = {"event": "train", "step": step, "lr": lr, "grad_norm": gnorm,
|
| 311 |
+
**{f"train_{k}": v for k, v in ema.items()},
|
| 312 |
+
"windows_per_s": n_since * a.batch / dt, "data_wait_frac": wait_acc / max(wait_acc + comp_acc, 1e-9)}
|
| 313 |
+
if device.type == "cuda":
|
| 314 |
+
rec["gpu_mem_gb"] = torch.cuda.max_memory_allocated() / 1e9
|
| 315 |
+
run.log(rec)
|
| 316 |
+
run.status({"step": step, "time": time.time(), **rec})
|
| 317 |
+
t_last, wait_acc, comp_acc, n_since = time.time(), 0.0, 0.0, 0
|
| 318 |
+
|
| 319 |
+
ctl = run.read_control() if step % a.control_every == 0 else None
|
| 320 |
+
for item in a.replay: # replayed interventions of a reference run (README: same rules for all variants)
|
| 321 |
+
at, what = item.split(":", 1)
|
| 322 |
+
if int(at) == step:
|
| 323 |
+
key, _, val = what.partition("=")
|
| 324 |
+
if what == "stop":
|
| 325 |
+
ctl = (ctl or {}) | {"stop": True}
|
| 326 |
+
elif key.startswith("weights."): # e.g. 4000:weights.plan=0.1
|
| 327 |
+
ctl = ctl or {}
|
| 328 |
+
ctl["weights"] = {**(ctl.get("weights") or {}), key.split(".", 1)[1]: float(val)}
|
| 329 |
+
else:
|
| 330 |
+
ctl = (ctl or {}) | {key: float(val)}
|
| 331 |
+
ctl["reason"] = f"replayed schedule: {item}"
|
| 332 |
+
force_eval = force_gen = False
|
| 333 |
+
if ctl:
|
| 334 |
+
changes = {}
|
| 335 |
+
if "lr" in ctl and ctl["lr"] != state["lr"]:
|
| 336 |
+
changes["lr"] = [state["lr"], ctl["lr"]]
|
| 337 |
+
state["lr"] = float(ctl["lr"])
|
| 338 |
+
for k, v in (ctl.get("weights") or {}).items():
|
| 339 |
+
if state["weights"].get(k) != v:
|
| 340 |
+
changes[f"weight.{k}"] = [state["weights"].get(k), v]
|
| 341 |
+
state["weights"][k] = float(v)
|
| 342 |
+
force_eval, force_gen = bool(ctl.get("eval_now")), bool(ctl.get("gen_now"))
|
| 343 |
+
if ctl.get("save"):
|
| 344 |
+
save(f"step{step}.pt")
|
| 345 |
+
changes["save"] = f"step{step}.pt"
|
| 346 |
+
if ctl.get("stop"):
|
| 347 |
+
changes["stop"] = True
|
| 348 |
+
if changes or force_eval or force_gen:
|
| 349 |
+
run.intervene(step, changes | ({"eval_now": True} if force_eval else {}) | ({"gen_now": True} if force_gen else {}),
|
| 350 |
+
ctl.get("reason", ""))
|
| 351 |
+
if ctl.get("stop"):
|
| 352 |
+
break
|
| 353 |
+
|
| 354 |
+
if step % a.eval_every == 0 or force_eval or force_gen:
|
| 355 |
+
v = validate(model, val_windows, device, state["weights"], tw, amp=amp)
|
| 356 |
+
rec = {"event": "val", "step": step, **v}
|
| 357 |
+
if step % a.gen_every == 0 or force_gen:
|
| 358 |
+
preds = generate(model, gen_windows, device)
|
| 359 |
+
model.train()
|
| 360 |
+
rec.update({f"gen_{k}": x for k, x in evaluate_generation(preds, gen_windows).items()})
|
| 361 |
+
run.log(rec)
|
| 362 |
+
save("last.pt")
|
| 363 |
+
# selection metric is independent of operator-set loss weights
|
| 364 |
+
sel = v["val_pos"] + v["val_note"] + v["val_beat"]
|
| 365 |
+
if sel < best:
|
| 366 |
+
best = sel
|
| 367 |
+
save("best.pt")
|
| 368 |
+
|
| 369 |
+
save("last.pt")
|
| 370 |
+
run.log({"event": "end", "step": step})
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
if __name__ == "__main__":
|
| 374 |
+
main()
|
chartgen/v11/__init__.py
ADDED
|
File without changes
|
chartgen/v11/gen_new.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Charts for new songs (audio only, no human chart) with the stage-2 system, for private play-testing.
|
| 2 |
+
|
| 3 |
+
uv run python -m chartgen.v11.gen_new timing --songs songs.json --out data/osz_play/v11_new
|
| 4 |
+
uv run python -m chartgen.v11.gen_new gen --songs songs.json --out data/osz_play/v11_new
|
| 5 |
+
|
| 6 |
+
songs.json: [{"id": "masyougetsu", "audio": "/path/a.mp3", "title": "...", "artist": "..."}, ...]
|
| 7 |
+
|
| 8 |
+
timing decodes the red lines from the audio (b9's beat / downbeat heads, chartgen.beattrack.decode_timing_auto) and
|
| 9 |
+
writes <out>/timing/<id>.json with the sections and checks: tempo list, beat-grid onset contrast. A file
|
| 10 |
+
edited by hand (e.g. a known BPM) is kept: gen reads it as is.
|
| 11 |
+
gen per song: R's map on the decoded timing (runs/r_full), the planner rows (B0 v1 + sp9), then two versions of
|
| 12 |
+
Oni and Inner Oni, as in the stage-2 runs:
|
| 13 |
+
R auto arm B of v11.s2_arms (R's positions and amounts; 1/8 amount drawn by tempo band; tau sharpening)
|
| 14 |
+
Base t09 stage-1 sample_t09 (sp9's plan, b9 sampled at T 0.9, no MBR, no argmax gate)
|
| 15 |
+
and writes one .osz per song (audio + the four .osu files).
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import io
|
| 22 |
+
import json
|
| 23 |
+
import pickle
|
| 24 |
+
import re
|
| 25 |
+
import zipfile
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
from types import SimpleNamespace
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
REPO = Path(__file__).resolve().parents[3]
|
| 33 |
+
RUNS = REPO / "data/hfruns/runs"
|
| 34 |
+
TIERS = (3, 4)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def load_audio(path):
|
| 38 |
+
from chartgen.features import decode_audio, log_mel
|
| 39 |
+
raw = Path(path).read_bytes()
|
| 40 |
+
return raw, np.asarray(log_mel(decode_audio(raw), device="cpu"), np.float32)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def bpm_list(sections):
|
| 44 |
+
s = np.asarray(sections, np.float64)
|
| 45 |
+
dur = np.diff(np.r_[s[:, 0], s[-1, 0] + 1e9])
|
| 46 |
+
return 60000.0 / s[:, 1], dur
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def flux(mel):
|
| 50 |
+
"""Spectral flux of the log-Mel (half-wave rectified, local mean removed), unit SD."""
|
| 51 |
+
d = np.diff(mel, axis=0, prepend=mel[:1])
|
| 52 |
+
f = np.maximum(d, 0).sum(1)
|
| 53 |
+
f = np.maximum(f - np.convolve(f, np.ones(50) / 50, "same"), 0)
|
| 54 |
+
return f / (f.std() + 1e-9)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def grid_check(sections, fl, t0, t1):
|
| 58 |
+
"""Strong spectral-flux peaks (top 7% local maxima) within 12 ms of a 1/4 position of the red lines, and the
|
| 59 |
+
share expected by chance (24 ms / quarter-beat length, time-weighted)."""
|
| 60 |
+
s = np.asarray(sections, np.float64)
|
| 61 |
+
pk = np.where((fl[1:-1] > fl[:-2]) & (fl[1:-1] >= fl[2:]) & (fl[1:-1] > np.percentile(fl, 93)))[0] + 1
|
| 62 |
+
pk = pk[(pk * 10 >= t0) & (pk * 10 <= t1)] * 10.0
|
| 63 |
+
j = np.clip(np.searchsorted(s[:, 0], pk, side="right") - 1, 0, len(s) - 1)
|
| 64 |
+
ph = ((pk - s[j, 0]) / s[j, 1] * 4) % 1.0
|
| 65 |
+
dist = np.minimum(ph, 1 - ph) * s[j, 1] / 4
|
| 66 |
+
return {"onsets_on_quarter_grid_12ms": round(float((dist < 12).mean()), 3),
|
| 67 |
+
"chance": round(float(np.mean(np.minimum(24.0 / (s[j, 1] / 4), 1.0))), 3), "n_peaks": int(len(pk))}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def manual_sections(spec, beat, down, t1):
|
| 71 |
+
"""Red lines from a hand-checked tempo list: spec = [{"bpm", "from_ms", "ref_ms"}] (ref_ms: one beat time of the
|
| 72 |
+
section from a spectral-flux fit). Per section, the offset is refined on b9's beat activation (+-20 ms, 1 ms;
|
| 73 |
+
the beat head learned the human red-line convention) and the bar phase is the one of 4 with the highest mean
|
| 74 |
+
downbeat activation; the section starts at its first downbeat at or after from_ms (the first section: the first
|
| 75 |
+
downbeat at or after 0 ms). start_beat as in chartgen.timing.decode_timing."""
|
| 76 |
+
at = lambda act, t: np.interp(np.asarray(t) / 10.0, np.arange(len(act)), act.astype(np.float64)) # noqa: E731
|
| 77 |
+
rows, info = [], []
|
| 78 |
+
for j, sp in enumerate(spec):
|
| 79 |
+
bl = 60000.0 / sp["bpm"]
|
| 80 |
+
lo = sp["from_ms"]
|
| 81 |
+
hi = spec[j + 1]["from_ms"] if j + 1 < len(spec) else t1
|
| 82 |
+
base = sp["ref_ms"] + np.ceil((lo - sp["ref_ms"]) / bl) * bl
|
| 83 |
+
grid = lambda o: np.arange(base + o, hi, bl) # noqa: E731
|
| 84 |
+
offs = np.arange(-20, 21, 1.0)
|
| 85 |
+
sc = [at(beat, grid(o)).mean() for o in offs]
|
| 86 |
+
o = offs[int(np.argmax(sc))]
|
| 87 |
+
b = grid(o)
|
| 88 |
+
ph = int(np.argmax([at(down, b[k::4]).mean() for k in range(4)]))
|
| 89 |
+
first = b[ph]
|
| 90 |
+
if j == 0:
|
| 91 |
+
first -= np.floor(first / (4 * bl)) * 4 * bl
|
| 92 |
+
rows.append([float(first), bl, 4.0])
|
| 93 |
+
info.append({"bpm": sp["bpm"], "shift_from_flux_ms": float(o), "bar_phase": ph, "start_ms": round(float(first), 1),
|
| 94 |
+
"beat_act_on_beats": round(float(max(sc)), 4)})
|
| 95 |
+
out, sb = [], 0.0
|
| 96 |
+
for i, (t, bl, m) in enumerate(rows):
|
| 97 |
+
if i:
|
| 98 |
+
pt, pbl, _ = rows[i - 1]
|
| 99 |
+
raw = sb + (t - pt) / pbl
|
| 100 |
+
sb = float(round(raw)) if abs(raw - round(raw)) < 1e-3 else float(np.ceil(raw))
|
| 101 |
+
out.append([t, bl, m, sb, 0.0])
|
| 102 |
+
return np.asarray(out, np.float64), info
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def timing(a):
|
| 106 |
+
from chartgen.beattrack import decode_timing_hybrid, grid_score
|
| 107 |
+
from chartgen.infer import frame_activations, load_model, music_span
|
| 108 |
+
from chartgen.timing import decode_timing
|
| 109 |
+
device = torch.device(a.device)
|
| 110 |
+
model = load_model(RUNS / "b9/best.pt", device)
|
| 111 |
+
songs = json.loads(Path(a.songs).read_text())
|
| 112 |
+
(a.out / "timing").mkdir(parents=True, exist_ok=True)
|
| 113 |
+
for s in songs:
|
| 114 |
+
f = a.out / "timing" / f"{s['id']}.json"
|
| 115 |
+
_, mel = load_audio(s["audio"])
|
| 116 |
+
beat, down, _ = frame_activations(model, mel, device)
|
| 117 |
+
t0, t1 = music_span(mel)
|
| 118 |
+
simple = decode_timing(beat, down, t0, t1)
|
| 119 |
+
hybrid = decode_timing_hybrid(beat, down, t0, t1)
|
| 120 |
+
g0, g1 = grid_score(beat, simple, t0, t1), grid_score(beat, hybrid, t0, t1)
|
| 121 |
+
ons = flux(mel)
|
| 122 |
+
rep = {}
|
| 123 |
+
for nm, sec in (("simple", simple), ("hybrid", hybrid)):
|
| 124 |
+
bpm, dur = bpm_list(sec)
|
| 125 |
+
main = bpm[np.argmax(dur)] if len(bpm) else 0
|
| 126 |
+
rep[nm] = {"grid_score": round(g0 if nm == "simple" else g1, 4), "sections": int(len(sec)),
|
| 127 |
+
"main_bpm": round(float(main), 2), "bpm_min": round(float(bpm.min()), 2),
|
| 128 |
+
"bpm_max": round(float(bpm.max()), 2), **grid_check(sec, ons, t0, t1)}
|
| 129 |
+
pick = "hybrid" if g1 > g0 * 1.05 else "simple"
|
| 130 |
+
print(f"{s['id']}: {len(mel) / 100:.0f} s, music {t0 / 1000:.1f}-{t1 / 1000:.1f} s, auto picks {pick}")
|
| 131 |
+
for nm in ("simple", "hybrid"):
|
| 132 |
+
print(f" {nm:7s} {rep[nm]}")
|
| 133 |
+
if "timing" in s:
|
| 134 |
+
sec, info = manual_sections(s["timing"], beat, down, t1)
|
| 135 |
+
pick = "manual"
|
| 136 |
+
bpm, dur = bpm_list(sec)
|
| 137 |
+
rep["manual"] = {"sections": info, **grid_check(sec, ons, t0, t1)}
|
| 138 |
+
print(f" manual {rep['manual']}")
|
| 139 |
+
else:
|
| 140 |
+
sec = hybrid if pick == "hybrid" else simple
|
| 141 |
+
f.write_text(json.dumps({"decoder": pick, "t0": t0, "t1": t1, "report": rep,
|
| 142 |
+
"sections": np.asarray(sec, np.float64).tolist()}, indent=1))
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def gen(a):
|
| 146 |
+
from chartgen import song_planner as sp
|
| 147 |
+
from chartgen.gen_mapset import CANDS, planner_rows
|
| 148 |
+
from chartgen.infer import TIER_NAMES, GeneratedChart, frame_activations, load_model, to_osu
|
| 149 |
+
from chartgen.v11 import s1_arms, s2_arms
|
| 150 |
+
from chartgen.v11.rmap import load_rmap, predict_group
|
| 151 |
+
from chartgen.v11.rmap_data import Group, beat_table
|
| 152 |
+
from chartgen.v11.rmap_eval import load_calib
|
| 153 |
+
from chartgen.v11.rmap_pseudo import Sampler
|
| 154 |
+
from chartgen.v11.song_signature import song_onsets
|
| 155 |
+
device = torch.device(a.device)
|
| 156 |
+
model = load_model(RUNS / "b9/best.pt", device)
|
| 157 |
+
enc = load_model(REPO / "data/runs/v1-full-1615/best.pt", device).eval()
|
| 158 |
+
ck = torch.load(RUNS / "sp9/best.pt", map_location=device)
|
| 159 |
+
planner = sp.SongPlanner(ck["d_in"]).to(device).eval()
|
| 160 |
+
planner.load_state_dict(ck["model"])
|
| 161 |
+
rmodel = load_rmap(RUNS / "r_full/best.pt", device)
|
| 162 |
+
S2 = RUNS / "v11_s2"
|
| 163 |
+
args = SimpleNamespace(seed=a.seed)
|
| 164 |
+
ctx = {"model": model, "planner": planner, "device": device, "args": args,
|
| 165 |
+
"cal": json.loads((RUNS / "sp9/thresholds.json").read_text())["calibration"],
|
| 166 |
+
"prior": pickle.load(open(RUNS / "sp9/chart_prior.pkl", "rb")),
|
| 167 |
+
"protos": pickle.load(open(RUNS / "sp9/protos.pkl", "rb")),
|
| 168 |
+
"cutoffs": json.loads((RUNS / "sp9/song_prop_cutoffs.json").read_text()),
|
| 169 |
+
"rest_band": (0.1, 0.6), "smp": Sampler(), "eighth": json.loads((S2 / "eighth_draw_table.json").read_text()),
|
| 170 |
+
"taus": json.loads((S2 / "taus.json").read_text())["tau"]}
|
| 171 |
+
calib_R = load_calib(S2 / "calib_R.json")
|
| 172 |
+
songs = json.loads(Path(a.songs).read_text())
|
| 173 |
+
groups = {}
|
| 174 |
+
for k, s in enumerate(songs):
|
| 175 |
+
if a.only and s["id"] not in a.only:
|
| 176 |
+
continue
|
| 177 |
+
tf = json.loads((a.out / "timing" / f"{s['id']}.json").read_text())
|
| 178 |
+
sections = np.asarray(tf["sections"], np.float64)
|
| 179 |
+
raw, mel = load_audio(s["audio"])
|
| 180 |
+
t0, t1 = float(tf["t0"]), float(tf["t1"])
|
| 181 |
+
sid = 990000000 + k
|
| 182 |
+
table = beat_table(sections, len(mel))
|
| 183 |
+
g = Group(sid, f"new|{s['id']}", "new", 3, table, sections, song_index=0) # era band 3 = 2022+
|
| 184 |
+
corpus = SimpleNamespace(groups=[g], songs=[{"mel": mel}], ons=[song_onsets(mel)])
|
| 185 |
+
lg = predict_group(rmodel, corpus, 0, device)
|
| 186 |
+
uid = s2_arms.group_uid(sid, sections)
|
| 187 |
+
ctx["maps"] = {"R": {"maps": {uid: lg}, "calib": calib_R}}
|
| 188 |
+
ctx["mel"], ctx["table"] = mel, table
|
| 189 |
+
feat, b_song = planner_rows(enc, mel, sections, device)
|
| 190 |
+
song = {"beatmapset_id": sid, "song_key": f"new|{s['id']}", "charts": [], "mel": mel}
|
| 191 |
+
charts = {}
|
| 192 |
+
out, _, _, _ = s2_arms.make_draw(ctx, song, sections, t0, t1, feat, b_song, 0, ["B"])
|
| 193 |
+
charts["R auto"] = out["B"]
|
| 194 |
+
if s.get("versions", ["R auto", "Base t09"]) == ["R auto"]:
|
| 195 |
+
base = None
|
| 196 |
+
else:
|
| 197 |
+
base = s1_arms.make_arms_draw(model, planner, mel, sections, song, t0, t1, ctx["cal"], device,
|
| 198 |
+
a.seed + sid, ctx["prior"], ctx["protos"], ctx["cutoffs"], feat, b_song,
|
| 199 |
+
(0.1, 0.6), ["sample_t09"])[0]
|
| 200 |
+
charts["Base t09"] = base["sample_t09"]
|
| 201 |
+
ext = Path(s["audio"]).suffix.lower()
|
| 202 |
+
aname = f"audio{ext}"
|
| 203 |
+
grp = groups.setdefault(s.get("osz", s["id"]), {"raw": raw, "aname": aname, "files": [], "song": s})
|
| 204 |
+
if True:
|
| 205 |
+
for label, cs in charts.items():
|
| 206 |
+
for t in TIERS:
|
| 207 |
+
c = cs[t]
|
| 208 |
+
gc = GeneratedChart(sections=sections, kiai=[tuple(x) for x in c["kiai"]], time=np.asarray(c["time"]),
|
| 209 |
+
type=np.asarray(c["type"]), length_beats=np.asarray(c["length_beats"]),
|
| 210 |
+
sv=np.asarray(c["sv"]), tier=t)
|
| 211 |
+
ver = f"{label} {TIER_NAMES[t]}{s.get('suffix', '')}"
|
| 212 |
+
osu = to_osu(gc, aname, s["title"], s["artist"]).replace(f"Version:{TIER_NAMES[t]}", f"Version:{ver}")
|
| 213 |
+
osu = osu.replace("Creator:chartgen", "Creator:chartgen v11s2")
|
| 214 |
+
grp["files"].append((f"{s['artist']} - {s['title']} (chartgen) [{ver}].osu".replace("/", "_"), osu))
|
| 215 |
+
print(f"{s['id']} {ver}: {len(c['time'])} notes, {int((np.asarray(c['type']) >= 4).sum())} rolls",
|
| 216 |
+
flush=True)
|
| 217 |
+
pickle.dump({"sections": sections, "charts": charts, "map": lg.astype(np.float16)},
|
| 218 |
+
open(a.out / "timing" / f"{s['id']}.charts.pkl", "wb"))
|
| 219 |
+
for gname, grp in groups.items():
|
| 220 |
+
s = grp["song"]
|
| 221 |
+
zbuf = io.BytesIO()
|
| 222 |
+
with zipfile.ZipFile(zbuf, "w", zipfile.ZIP_DEFLATED) as z:
|
| 223 |
+
z.writestr(grp["aname"], grp["raw"])
|
| 224 |
+
for n, txt in grp["files"]:
|
| 225 |
+
z.writestr(n, txt)
|
| 226 |
+
name = re.sub(r'[\\/:*?"<>|]', "_", f"{s['artist']} - {s['title']} (AI v11s2).osz")
|
| 227 |
+
(a.out / name).write_bytes(zbuf.getvalue())
|
| 228 |
+
print(f"{gname} -> {name} ({len(grp['files'])} difficulties)", flush=True)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def main(argv=None):
|
| 232 |
+
p = argparse.ArgumentParser()
|
| 233 |
+
p.add_argument("cmd", choices=["timing", "gen"])
|
| 234 |
+
p.add_argument("--songs", type=Path, required=True)
|
| 235 |
+
p.add_argument("--out", type=Path, required=True)
|
| 236 |
+
p.add_argument("--device", default="cpu")
|
| 237 |
+
p.add_argument("--seed", type=int, default=0)
|
| 238 |
+
p.add_argument("--only", nargs="*", default=[])
|
| 239 |
+
a = p.parse_args(argv)
|
| 240 |
+
a.out.mkdir(parents=True, exist_ok=True)
|
| 241 |
+
{"timing": timing, "gen": gen}[a.cmd](a)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
if __name__ == "__main__":
|
| 245 |
+
main()
|
chartgen/v11/patterns.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Beat-pattern tokenizer for v11 (reports/v11 重新設計:計畫.md, section 2; P0.5 in reports/v11 階段 0 預先登記:參考線.md).
|
| 2 |
+
|
| 3 |
+
Input: the hit notes of one chart as a grid, i.e. sorted unique 1/48-beat indices (chartgen.rhythm_eval2.grid_of).
|
| 4 |
+
The note at index g lies in beat g // 48 at position k = g % 48.
|
| 5 |
+
|
| 6 |
+
A beat's pattern is the set of its note positions among the 24 candidate positions: k/48 with k a multiple of 3 or of
|
| 7 |
+
4, which are all the 1/3, 1/4, 1/6, 1/8, 1/12 and 1/16 positions (POSITIONS). Positions only: colours, big notes,
|
| 8 |
+
rolls and balloons are separate streams. A pattern is stored as a 24-bit mask, bit i = POSITIONS[i].
|
| 9 |
+
|
| 10 |
+
Tokens: EMPTY (0) = no note on the 24 positions, OTHER (1) = a pattern outside the vocabulary, then the vocabulary
|
| 11 |
+
patterns (2, 3, ...), most common first. The vocabulary holds the patterns that occur in at least `min_count` beats of
|
| 12 |
+
the charts it is built on.
|
| 13 |
+
|
| 14 |
+
Notes on any other position (k neither a multiple of 3 nor of 4: 1/5, 1/7, 1/24, 1/48 and similar) are not part of a
|
| 15 |
+
pattern. encode() returns them in a separate list (`offgrid`), together with the masks of the OTHER beats (`other`),
|
| 16 |
+
so that decode(tokens, ..., offgrid, other) gives back the input exactly, and decode(tokens) alone gives back every
|
| 17 |
+
covered beat exactly.
|
| 18 |
+
|
| 19 |
+
A beat is covered when its token is not OTHER and it has no off-grid note (Encoded.covered()).
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
from collections import Counter
|
| 25 |
+
from dataclasses import dataclass, field
|
| 26 |
+
from fractions import Fraction
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
|
| 30 |
+
GRID = 48
|
| 31 |
+
POSITIONS = tuple(k for k in range(GRID) if k % 3 == 0 or k % 4 == 0)
|
| 32 |
+
N_POS = len(POSITIONS)
|
| 33 |
+
assert N_POS == 24
|
| 34 |
+
POS_BIT = np.full(GRID, -1, np.int64)
|
| 35 |
+
POS_BIT[list(POSITIONS)] = np.arange(N_POS)
|
| 36 |
+
_POS_ARR = np.asarray(POSITIONS, np.int64)
|
| 37 |
+
|
| 38 |
+
EMPTY = 0
|
| 39 |
+
OTHER = 1
|
| 40 |
+
N_SPECIAL = 2
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# ---------------------------------------------------------------- masks
|
| 44 |
+
|
| 45 |
+
def positions_to_mask(positions) -> int:
|
| 46 |
+
"""Set of positions k (each in POSITIONS) -> 24-bit mask."""
|
| 47 |
+
m = 0
|
| 48 |
+
for k in positions:
|
| 49 |
+
b = int(POS_BIT[int(k)])
|
| 50 |
+
if b < 0:
|
| 51 |
+
raise ValueError(f"position {k} is not one of the 24 candidate positions")
|
| 52 |
+
m |= 1 << b
|
| 53 |
+
return m
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def mask_to_positions(mask: int) -> tuple:
|
| 57 |
+
"""24-bit mask -> sorted tuple of positions k (1/48 of a beat)."""
|
| 58 |
+
return tuple(POSITIONS[i] for i in range(N_POS) if (int(mask) >> i) & 1)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def mask_str(mask: int) -> str:
|
| 62 |
+
"""Readable pattern: the positions as fractions of a beat, e.g. '0 1/4 1/2 3/4'; '-' for the empty pattern."""
|
| 63 |
+
pos = mask_to_positions(mask)
|
| 64 |
+
return " ".join(str(Fraction(k, GRID)) for k in pos) if pos else "-"
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def beat_masks(grid) -> tuple:
|
| 68 |
+
"""Split a grid into per-beat patterns.
|
| 69 |
+
|
| 70 |
+
Returns (beats, masks, offgrid): beats = sorted indices of the beats with at least one note on the 24 positions,
|
| 71 |
+
masks = their 24-bit masks (int64), offgrid = the notes (1/48 indices) on other positions."""
|
| 72 |
+
g = np.asarray(grid, np.int64)
|
| 73 |
+
if g.size == 0:
|
| 74 |
+
e = np.zeros(0, np.int64)
|
| 75 |
+
return e, e.copy(), e.copy()
|
| 76 |
+
beat = np.floor_divide(g, GRID)
|
| 77 |
+
bit = POS_BIT[np.mod(g, GRID)]
|
| 78 |
+
on = bit >= 0
|
| 79 |
+
offgrid = np.sort(g[~on])
|
| 80 |
+
b_on, bit_on = beat[on], bit[on]
|
| 81 |
+
if b_on.size == 0:
|
| 82 |
+
e = np.zeros(0, np.int64)
|
| 83 |
+
return e, e.copy(), offgrid
|
| 84 |
+
o = np.argsort(b_on, kind="stable")
|
| 85 |
+
b_on, val = b_on[o], np.left_shift(np.int64(1), bit_on[o])
|
| 86 |
+
beats, start = np.unique(b_on, return_index=True)
|
| 87 |
+
masks = np.bitwise_or.reduceat(val, start)
|
| 88 |
+
return beats, masks.astype(np.int64), offgrid
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def masks_to_grid(beats, masks) -> np.ndarray:
|
| 92 |
+
"""Inverse of the on-grid part of beat_masks: per-beat masks -> sorted 1/48 indices."""
|
| 93 |
+
beats, masks = np.asarray(beats, np.int64), np.asarray(masks, np.int64)
|
| 94 |
+
if beats.size == 0:
|
| 95 |
+
return np.zeros(0, np.int64)
|
| 96 |
+
bits = (masks[:, None] >> np.arange(N_POS)[None, :]) & 1
|
| 97 |
+
bi, pi = np.nonzero(bits)
|
| 98 |
+
return np.sort(beats[bi] * GRID + _POS_ARR[pi])
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# ---------------------------------------------------------------- vocabulary
|
| 102 |
+
|
| 103 |
+
@dataclass
|
| 104 |
+
class Vocab:
|
| 105 |
+
"""Token ids: EMPTY = 0, OTHER = 1, masks[i] has id i + 2 (masks ordered by count, then by mask value)."""
|
| 106 |
+
masks: np.ndarray # [V] int64, 24-bit pattern masks
|
| 107 |
+
counts: np.ndarray # [V] int64, number of beats with the pattern in the building charts
|
| 108 |
+
min_count: int = 3
|
| 109 |
+
_sorted: np.ndarray = field(init=False, repr=False)
|
| 110 |
+
_order: np.ndarray = field(init=False, repr=False)
|
| 111 |
+
|
| 112 |
+
def __post_init__(self):
|
| 113 |
+
self.masks = np.asarray(self.masks, np.int64)
|
| 114 |
+
self.counts = np.asarray(self.counts, np.int64)
|
| 115 |
+
if len(np.unique(self.masks)) != len(self.masks) or (self.masks <= 0).any():
|
| 116 |
+
raise ValueError("vocabulary masks must be distinct and non-empty")
|
| 117 |
+
self._order = np.argsort(self.masks, kind="stable")
|
| 118 |
+
self._sorted = self.masks[self._order]
|
| 119 |
+
|
| 120 |
+
def __len__(self) -> int:
|
| 121 |
+
"""Number of tokens, EMPTY and OTHER included."""
|
| 122 |
+
return len(self.masks) + N_SPECIAL
|
| 123 |
+
|
| 124 |
+
@property
|
| 125 |
+
def n_patterns(self) -> int:
|
| 126 |
+
return len(self.masks)
|
| 127 |
+
|
| 128 |
+
def ids(self, masks) -> np.ndarray:
|
| 129 |
+
"""Masks -> token ids (0 -> EMPTY, unknown non-empty -> OTHER)."""
|
| 130 |
+
m = np.asarray(masks, np.int64)
|
| 131 |
+
out = np.full(m.shape, OTHER, np.int64)
|
| 132 |
+
if self._sorted.size:
|
| 133 |
+
j = np.clip(np.searchsorted(self._sorted, m), 0, len(self._sorted) - 1)
|
| 134 |
+
hit = self._sorted[j] == m
|
| 135 |
+
out[hit] = self._order[j[hit]] + N_SPECIAL
|
| 136 |
+
out[m == 0] = EMPTY
|
| 137 |
+
return out
|
| 138 |
+
|
| 139 |
+
def mask(self, tokens) -> np.ndarray:
|
| 140 |
+
"""Token ids -> masks (EMPTY -> 0; OTHER -> -1, since its pattern is unknown)."""
|
| 141 |
+
t = np.asarray(tokens, np.int64)
|
| 142 |
+
if ((t < 0) | (t >= len(self))).any():
|
| 143 |
+
raise ValueError("token id out of range")
|
| 144 |
+
table = np.r_[np.int64(0), np.int64(-1), self.masks]
|
| 145 |
+
return table[t]
|
| 146 |
+
|
| 147 |
+
def to_dict(self) -> dict:
|
| 148 |
+
return {"min_count": int(self.min_count), "masks": self.masks.tolist(), "counts": self.counts.tolist()}
|
| 149 |
+
|
| 150 |
+
@classmethod
|
| 151 |
+
def from_dict(cls, d: dict) -> "Vocab":
|
| 152 |
+
return cls(np.asarray(d["masks"], np.int64), np.asarray(d["counts"], np.int64), int(d["min_count"]))
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def count_patterns(grids) -> Counter:
|
| 156 |
+
"""Number of beats per non-empty pattern (the on-grid part of every beat that has a note on the 24 positions)."""
|
| 157 |
+
out = Counter()
|
| 158 |
+
for g in grids:
|
| 159 |
+
_, masks, _ = beat_masks(g)
|
| 160 |
+
if masks.size:
|
| 161 |
+
u, c = np.unique(masks, return_counts=True)
|
| 162 |
+
out.update(dict(zip(u.tolist(), c.tolist())))
|
| 163 |
+
return out
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def vocab_from_counts(counts: Counter, min_count: int = 3) -> Vocab:
|
| 167 |
+
keep = sorted(((c, m) for m, c in counts.items() if c >= min_count and m != 0), key=lambda x: (-x[0], x[1]))
|
| 168 |
+
return Vocab(np.array([m for _, m in keep], np.int64), np.array([c for c, _ in keep], np.int64), min_count)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def build_vocab(grids, min_count: int = 3) -> Vocab:
|
| 172 |
+
"""Vocabulary of the patterns that occur in at least `min_count` beats of `grids` (iterable of 1/48 grids)."""
|
| 173 |
+
return vocab_from_counts(count_patterns(grids), min_count)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
# ---------------------------------------------------------------- encode / decode
|
| 177 |
+
|
| 178 |
+
@dataclass
|
| 179 |
+
class Encoded:
|
| 180 |
+
beat0: int # beat index of tokens[0]
|
| 181 |
+
tokens: np.ndarray # [n_beats] int64, one token per beat from beat0 to the last beat with a note
|
| 182 |
+
offgrid: np.ndarray # 1/48 indices of the notes off the 24 positions
|
| 183 |
+
other: dict # beat index -> mask, for the beats whose token is OTHER
|
| 184 |
+
|
| 185 |
+
def covered(self) -> np.ndarray:
|
| 186 |
+
"""[n_beats] bool: token is not OTHER and the beat has no off-grid note."""
|
| 187 |
+
ok = self.tokens != OTHER
|
| 188 |
+
if self.offgrid.size:
|
| 189 |
+
b = np.floor_divide(self.offgrid, GRID) - self.beat0
|
| 190 |
+
ok[b[(b >= 0) & (b < len(ok))]] = False
|
| 191 |
+
return ok
|
| 192 |
+
|
| 193 |
+
def has_note(self) -> np.ndarray:
|
| 194 |
+
"""[n_beats] bool: the beat has at least one note (on or off the 24 positions)."""
|
| 195 |
+
out = self.tokens != EMPTY
|
| 196 |
+
if self.offgrid.size:
|
| 197 |
+
b = np.floor_divide(self.offgrid, GRID) - self.beat0
|
| 198 |
+
out[b[(b >= 0) & (b < len(out))]] = True
|
| 199 |
+
return out
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def encode(grid, vocab: Vocab, beat0: int | None = None, n_beats: int | None = None) -> Encoded:
|
| 203 |
+
"""One token per beat. The span is beat0 .. beat0 + n_beats - 1 (default: first to last beat with a note); notes
|
| 204 |
+
outside a given span are not allowed."""
|
| 205 |
+
g = np.asarray(grid, np.int64)
|
| 206 |
+
if g.size and (np.diff(g) <= 0).any():
|
| 207 |
+
raise ValueError("grid must be sorted and unique")
|
| 208 |
+
beats, masks, offgrid = beat_masks(g)
|
| 209 |
+
all_beats = np.floor_divide(g, GRID)
|
| 210 |
+
if beat0 is None:
|
| 211 |
+
beat0 = int(all_beats.min()) if g.size else 0
|
| 212 |
+
if n_beats is None:
|
| 213 |
+
n_beats = int(all_beats.max()) - beat0 + 1 if g.size else 0
|
| 214 |
+
if g.size and (all_beats.min() < beat0 or all_beats.max() >= beat0 + n_beats):
|
| 215 |
+
raise ValueError("notes outside the requested beat span")
|
| 216 |
+
tokens = np.full(n_beats, EMPTY, np.int64)
|
| 217 |
+
ids = vocab.ids(masks)
|
| 218 |
+
tokens[beats - beat0] = ids
|
| 219 |
+
other = {int(b): int(m) for b, m, t in zip(beats.tolist(), masks.tolist(), ids.tolist()) if t == OTHER}
|
| 220 |
+
return Encoded(int(beat0), tokens, offgrid, other)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def decode(tokens, vocab: Vocab, beat0: int = 0, offgrid=None, other: dict | None = None) -> np.ndarray:
|
| 224 |
+
"""Tokens -> sorted 1/48 grid. OTHER beats are left empty unless their masks are given in `other`; off-grid notes
|
| 225 |
+
are added when given."""
|
| 226 |
+
t = np.asarray(tokens, np.int64)
|
| 227 |
+
m = vocab.mask(t)
|
| 228 |
+
if other:
|
| 229 |
+
for b, mk in other.items():
|
| 230 |
+
i = int(b) - beat0
|
| 231 |
+
if not (0 <= i < len(t)) or t[i] != OTHER:
|
| 232 |
+
raise ValueError(f"beat {b} of `other` is not an OTHER beat")
|
| 233 |
+
m[i] = mk
|
| 234 |
+
keep = m > 0
|
| 235 |
+
g = masks_to_grid(np.nonzero(keep)[0] + beat0, m[keep])
|
| 236 |
+
if offgrid is not None and len(offgrid):
|
| 237 |
+
g = np.union1d(g, np.asarray(offgrid, np.int64))
|
| 238 |
+
return g
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def decode_full(enc: Encoded, vocab: Vocab) -> np.ndarray:
|
| 242 |
+
"""Exact inverse of encode()."""
|
| 243 |
+
return decode(enc.tokens, vocab, enc.beat0, enc.offgrid, enc.other)
|
chartgen/v11/pmap.py
ADDED
|
@@ -0,0 +1,1130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""v11 stage 5d: the position model P (reports/v11 階段 5d 預先登記:位置模型自己寫定位置(小測試).md).
|
| 2 |
+
|
| 3 |
+
P is the position map R (chartgen.v11.rmap) continued from r_full's weights, with three additions, all initialised to
|
| 4 |
+
zero so that P starts as exactly R:
|
| 5 |
+
- inputs per beat: the target tier (embedding), the tier's own decided beats and the other tier's decided beats
|
| 6 |
+
(24-bit note mask -> linear, plus a state embedding: unknown / decided / decided as roll body / decided, outside the
|
| 7 |
+
vocabulary)
|
| 8 |
+
- output per beat: one token out of EMPTY, the 897 stage-0 patterns and HOLD (no hit, beat inside a roll / balloon
|
| 9 |
+
body); score s(v) = sum_{p in v} l_p + (W z) . e_v + b_v, with l the head's position logits of the target tier
|
| 10 |
+
(the stage-2 pseudo-chart factorisation) and z the beat state; patterns on invalid positions and OTHER at -inf
|
| 11 |
+
Training: masked prediction on W's per-beat data (writer_data caches) for Oni and Inner Oni charts of roles A and B,
|
| 12 |
+
tune for the checkpoint. Own tier: 10% fully masked, else ceil(cos(pi u / 2) L) random beats masked; Oni targets get the
|
| 13 |
+
same mapset's Inner Oni fully known in 90% of the samples. Cross-entropy on masked beats (not OTHER, not off-grid).
|
| 14 |
+
Generation: Inner Oni, then Oni given that Inner Oni; 16 steps; at step s the beats with the most confident
|
| 15 |
+
distribution (plus Gumbel noise of scale 1 - s/16) are decided by sampling their token at temperature 1, until
|
| 16 |
+
floor(N cos(pi s / 32)) beats remain open. Stage-5a 1/8 gate from R's readout (no amount shift); patterns with a
|
| 17 |
+
within-beat gap under the tier's floor - 1 ms are never drawn; s5a.enforce_min_gap afterwards.
|
| 18 |
+
|
| 19 |
+
python -m chartgen.v11.pmap train --data f*.pkl --cache-dir DIR --init r_full/best.pt --out runs/p_s0
|
| 20 |
+
python -m chartgen.v11.pmap gen --data f*.pkl --model runs/p_s0/best.pt --sets-file sets.txt \\
|
| 21 |
+
--maps-R maps_R_val_tune.npz --calib-R calib_R.json --s5a-params params.json --min-gap-json min_gap.json \\
|
| 22 |
+
--out runs/v11_s5d/gen/part0/mapsets_P.pkl
|
| 23 |
+
python -m chartgen.v11.pmap --selftest
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import argparse
|
| 29 |
+
import json
|
| 30 |
+
import math
|
| 31 |
+
import os
|
| 32 |
+
import pickle
|
| 33 |
+
import time
|
| 34 |
+
from functools import lru_cache
|
| 35 |
+
from pathlib import Path
|
| 36 |
+
|
| 37 |
+
import numpy as np
|
| 38 |
+
import torch
|
| 39 |
+
import torch.nn as nn
|
| 40 |
+
import torch.nn.functional as F
|
| 41 |
+
|
| 42 |
+
from chartgen.v11 import s5a
|
| 43 |
+
from chartgen.v11.patterns import EMPTY, GRID, OTHER
|
| 44 |
+
from chartgen.v11.rmap import CROP, STRIDE, Corpus, RMap, collate as r_collate, crop_arrays
|
| 45 |
+
from chartgen.v11.rmap_data import N_ERA, N_POS, N_TIERS, POS, Group, bits_to_bool
|
| 46 |
+
from chartgen.v11.rmap_eval import Maps, apply_calib, load_calib
|
| 47 |
+
from chartgen.v11.writer import WCorpus, chart_arrays
|
| 48 |
+
from chartgen.v11.writer_data import load_vocab
|
| 49 |
+
|
| 50 |
+
TARGET = (3, 4)
|
| 51 |
+
P_ALL_MASKED = 0.1
|
| 52 |
+
P_OTHER_KNOWN = 0.9
|
| 53 |
+
K_STEPS = 16
|
| 54 |
+
D_PAT = 64
|
| 55 |
+
ST_UNK, ST_KNOWN, ST_HOLD, ST_OTHER = 0, 1, 2, 3
|
| 56 |
+
NEW_MODULES = ("tier_emb", "own_lin", "own_state", "oth_lin", "oth_state", "pat_q", "pat_e", "pat_b")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@lru_cache(maxsize=1)
|
| 60 |
+
def tables():
|
| 61 |
+
"""Token tables: V (EMPTY, OTHER, patterns, HOLD), HOLD id, [V, 24] bits, within-beat min gap (1/48 beat, inf for
|
| 62 |
+
fewer than two notes), uses-the-1/8-family flag."""
|
| 63 |
+
vocab = load_vocab()
|
| 64 |
+
nv = len(vocab)
|
| 65 |
+
masks = np.r_[np.int64(0), np.int64(0), vocab.masks, np.int64(0)]
|
| 66 |
+
bits = ((masks[:, None] >> np.arange(N_POS)[None]) & 1).astype(bool)
|
| 67 |
+
mg = np.full(len(masks), np.inf)
|
| 68 |
+
for v in range(len(masks)):
|
| 69 |
+
p = POS[bits[v]]
|
| 70 |
+
if len(p) >= 2:
|
| 71 |
+
mg[v] = float(np.diff(np.sort(p)).min())
|
| 72 |
+
has8 = (bits & s5a.EIGHTH[None]).any(1)
|
| 73 |
+
return {"V": nv + 1, "HOLD": nv, "bits": bits, "mg48": mg, "has8": has8}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _zero(m):
|
| 77 |
+
for p in m.parameters():
|
| 78 |
+
nn.init.zeros_(p)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class PMap(RMap):
|
| 82 |
+
def __init__(self, V: int, d_pat: int = D_PAT, **rcfg):
|
| 83 |
+
super().__init__(**rcfg)
|
| 84 |
+
d = self.cfg["d"]
|
| 85 |
+
self.cfg.update({"V": V, "d_pat": d_pat})
|
| 86 |
+
self.tier_emb = nn.Embedding(N_TIERS, d)
|
| 87 |
+
self.own_lin = nn.Linear(N_POS, d, bias=False)
|
| 88 |
+
self.own_state = nn.Embedding(4, d)
|
| 89 |
+
self.oth_lin = nn.Linear(N_POS, d, bias=False)
|
| 90 |
+
self.oth_state = nn.Embedding(4, d)
|
| 91 |
+
self.pat_q = nn.Linear(d, d_pat)
|
| 92 |
+
self.pat_e = nn.Embedding(V, d_pat)
|
| 93 |
+
self.pat_b = nn.Embedding(V, 1)
|
| 94 |
+
for m in (self.tier_emb, self.own_lin, self.own_state, self.oth_lin, self.oth_state, self.pat_e, self.pat_b):
|
| 95 |
+
_zero(m)
|
| 96 |
+
self.register_buffer("vbits", torch.from_numpy(tables()["bits"].astype(np.float32)), persistent=False)
|
| 97 |
+
|
| 98 |
+
def music(self, b):
|
| 99 |
+
"""Per-position features h [B, L, 24, d_pos] and the beat input z0 [B, L, d] (music only)."""
|
| 100 |
+
feat = self.read(b)
|
| 101 |
+
B, L = feat.shape[:2]
|
| 102 |
+
parts = [feat, self.pos_eye.expand(B, L, N_POS, N_POS)]
|
| 103 |
+
if self.use_ms:
|
| 104 |
+
lbl = b["logbl"][..., None, None].expand(B, L, N_POS, 1)
|
| 105 |
+
parts += [b["hmax"], lbl, lbl + torch.log(self.gap_prev)[None, None, :, None],
|
| 106 |
+
lbl + torch.log(self.gap_next)[None, None, :, None]]
|
| 107 |
+
h = self.inp(torch.cat(parts, -1))
|
| 108 |
+
z0 = self.beat_in(h.flatten(-2)) + self.bib(b["bib"].clamp(max=15)) + self.era(b["era"])[:, None]
|
| 109 |
+
if self.use_ms:
|
| 110 |
+
z0 = z0 + self.tempo(b["logbl"][..., None])
|
| 111 |
+
return h, z0 + self.pe[:L][None]
|
| 112 |
+
|
| 113 |
+
copy = False
|
| 114 |
+
|
| 115 |
+
def encode(self, z0, x):
|
| 116 |
+
"""Beat states z [B, L, d] given the music input and the decided beats (x: tier, own_mask, own_state, oth_mask,
|
| 117 |
+
oth_state, beat)."""
|
| 118 |
+
z = (z0 + self.tier_emb(x["tier"])[:, None] + self.own_lin(x["own_mask"]) + self.own_state(x["own_state"])
|
| 119 |
+
+ self.oth_lin(x["oth_mask"]) + self.oth_state(x["oth_state"]))
|
| 120 |
+
return self.enc(z, src_key_padding_mask=~x["beat"])
|
| 121 |
+
|
| 122 |
+
def gen_scores(self, h, z, x):
|
| 123 |
+
"""(fp32 token scores [B, L, V] with invalid tokens at -inf, forbidden mask [B, L, V])."""
|
| 124 |
+
tier = x["tier"]
|
| 125 |
+
lg = self.head(h + self.back(z)[:, :, None]) # [B, L, 24, 5]
|
| 126 |
+
B, L = lg.shape[:2]
|
| 127 |
+
lt = torch.gather(lg, 3, tier.view(B, 1, 1, 1).expand(B, L, N_POS, 1))[..., 0]
|
| 128 |
+
q = self.pat_q(z)
|
| 129 |
+
with torch.autocast(h.device.type, enabled=False):
|
| 130 |
+
vb = self.vbits
|
| 131 |
+
s = (torch.einsum("blp,vp->blv", lt.float(), vb)
|
| 132 |
+
+ torch.einsum("bld,vd->blv", q.float(), self.pat_e.weight.float()) + self.pat_b.weight[:, 0].float())
|
| 133 |
+
forb = ((~x["valid"]).float() @ vb.T) > 0
|
| 134 |
+
forb[..., OTHER] = True
|
| 135 |
+
return s.masked_fill(forb, float("-inf")), forb
|
| 136 |
+
|
| 137 |
+
def scores(self, h, z0, beat, tier, own_mask, own_state, oth_mask, oth_state, valid):
|
| 138 |
+
"""fp32 token scores [B, L, V]; tokens on invalid positions and OTHER at -inf."""
|
| 139 |
+
x = {"beat": beat, "tier": tier, "own_mask": own_mask, "own_state": own_state, "oth_mask": oth_mask,
|
| 140 |
+
"oth_state": oth_state, "valid": valid}
|
| 141 |
+
return self.gen_scores(h, self.encode(z0, x), x)[0]
|
| 142 |
+
|
| 143 |
+
def token_logp(self, h, z0, x):
|
| 144 |
+
"""fp32 log-probabilities [B, L, V] of the tokens (invalid ones at -inf)."""
|
| 145 |
+
return torch.log_softmax(self.gen_scores(h, self.encode(z0, x), x)[0], -1)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
CW, KC = 16, 32 # copy head (stage 5e): candidates within 16 measures either way, same beat of the measure
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def candidates(meas, bib):
|
| 152 |
+
"""[L, KC] crop-relative candidate beats (-1 = none) and [L, KC] relative measure distance + CW: the beats with
|
| 153 |
+
the same beat-in-measure in the other measures within CW measures either way, nearest first."""
|
| 154 |
+
meas, bib = np.asarray(meas), np.asarray(bib)
|
| 155 |
+
L = len(meas)
|
| 156 |
+
cand = np.full((L, KC), -1, np.int64)
|
| 157 |
+
rel = np.zeros((L, KC), np.int64)
|
| 158 |
+
for bv in np.unique(bib):
|
| 159 |
+
idx = np.nonzero(bib == bv)[0]
|
| 160 |
+
ms = meas[idx]
|
| 161 |
+
for j, b in enumerate(idx):
|
| 162 |
+
d = ms - ms[j]
|
| 163 |
+
ok = (d != 0) & (np.abs(d) <= CW)
|
| 164 |
+
c, dd = idx[ok], d[ok]
|
| 165 |
+
o = np.argsort(np.abs(dd) * 2 + (dd > 0), kind="stable")[:KC]
|
| 166 |
+
cand[b, :len(o)] = c[o]
|
| 167 |
+
rel[b, :len(o)] = dd[o] + CW
|
| 168 |
+
return cand, rel
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class PMapCopy(PMap):
|
| 172 |
+
"""P with a copy head (stage 5e): every beat may take the token of a decided candidate beat (same beat of the
|
| 173 |
+
measure, within 16 measures either way). p = (1 - g) p_gen + g p_copy, with p_copy an attention over the decided
|
| 174 |
+
candidates (query and key from the beat states, plus a learned bias per relative measure distance) and g a gate
|
| 175 |
+
from the beat state (initial bias -3), zero when no candidate is decided."""
|
| 176 |
+
|
| 177 |
+
copy = True
|
| 178 |
+
|
| 179 |
+
def __init__(self, V: int, d_pat: int = D_PAT, d_c: int = 64, **rcfg):
|
| 180 |
+
rcfg.pop("copy", None)
|
| 181 |
+
super().__init__(V, d_pat, **rcfg)
|
| 182 |
+
self.cfg.update({"copy": True, "d_c": d_c})
|
| 183 |
+
d = self.cfg["d"]
|
| 184 |
+
self.cq = nn.Linear(d, d_c)
|
| 185 |
+
self.ck = nn.Linear(d, d_c)
|
| 186 |
+
self.c_gate = nn.Linear(d, 1)
|
| 187 |
+
nn.init.zeros_(self.c_gate.weight)
|
| 188 |
+
nn.init.constant_(self.c_gate.bias, -3.0)
|
| 189 |
+
self.c_rel = nn.Embedding(2 * CW + 1, 1)
|
| 190 |
+
nn.init.zeros_(self.c_rel.weight)
|
| 191 |
+
|
| 192 |
+
def token_logp(self, h, z0, x):
|
| 193 |
+
z = self.encode(z0, x)
|
| 194 |
+
s, forb = self.gen_scores(h, z, x)
|
| 195 |
+
with torch.autocast(h.device.type, enabled=False):
|
| 196 |
+
pg = s.new_zeros(s.shape)
|
| 197 |
+
zf = z.float()
|
| 198 |
+
q, k = self.cq(zf), self.ck(zf)
|
| 199 |
+
cand = x["cand"]
|
| 200 |
+
B, L, K = cand.shape
|
| 201 |
+
ci = cand.clamp(min=0)
|
| 202 |
+
kc = torch.gather(k, 1, ci.reshape(B, L * K, 1).expand(-1, -1, k.shape[-1])).view(B, L, K, -1)
|
| 203 |
+
att = (q[:, :, None] * kc).sum(-1) / math.sqrt(k.shape[-1]) + self.c_rel(x["rel"])[..., 0].float()
|
| 204 |
+
vk = (cand >= 0) & torch.gather(x["own_known"], 1, ci.reshape(B, L * K)).view(B, L, K)
|
| 205 |
+
has = vk.any(-1)
|
| 206 |
+
att = att.masked_fill(~vk, float("-inf")).masked_fill(~has[..., None], 0.0)
|
| 207 |
+
alpha = torch.softmax(att, -1) * has[..., None].float()
|
| 208 |
+
ctok = torch.gather(x["own_tok"], 1, ci.reshape(B, L * K)).view(B, L, K)
|
| 209 |
+
pc = torch.zeros_like(pg).scatter_add_(2, ctok, alpha).masked_fill(forb, 0.0)
|
| 210 |
+
pcs = pc.sum(-1, keepdim=True)
|
| 211 |
+
pc = pc / pcs.clamp_min(1e-12)
|
| 212 |
+
# mixture in log space, exact when the gate is off: log((1 - g) p_gen + g p_copy)
|
| 213 |
+
gl = self.c_gate(zf)[..., 0] + float(x.get("copy_beta", 0.0)) # stage 5f: repetition knob
|
| 214 |
+
use = has & (pcs[..., 0] > 1e-6)
|
| 215 |
+
log_g = torch.where(use, F.logsigmoid(gl), torch.full_like(gl, float("-inf")))
|
| 216 |
+
log_1g = torch.where(use, F.logsigmoid(-gl), torch.zeros_like(gl))
|
| 217 |
+
lg_gen = torch.log_softmax(s, -1).masked_fill(forb, 0.0)
|
| 218 |
+
out = torch.logaddexp(log_1g[..., None] + lg_gen, log_g[..., None] + torch.log(pc.clamp_min(1e-30)))
|
| 219 |
+
return out.masked_fill(forb, float("-inf"))
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def init_from_r(path, device, d_pat=D_PAT):
|
| 223 |
+
ck = torch.load(path, map_location=device, weights_only=False)
|
| 224 |
+
m = PMap(V=tables()["V"], d_pat=d_pat, **ck["cfg"]).to(device)
|
| 225 |
+
missing, unexpected = m.load_state_dict(ck["model"], strict=False)
|
| 226 |
+
assert not unexpected, unexpected
|
| 227 |
+
assert all(k.split(".")[0] in NEW_MODULES for k in missing), missing
|
| 228 |
+
return m
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
COPY_MODULES = ("cq", "ck", "c_gate", "c_rel")
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def load_pmap(path, device):
|
| 235 |
+
ck = torch.load(path, map_location=device, weights_only=False)
|
| 236 |
+
cfg = dict(ck["cfg"])
|
| 237 |
+
m = (PMapCopy if cfg.pop("copy", False) else PMap)(**cfg).to(device)
|
| 238 |
+
m.load_state_dict(ck["model"])
|
| 239 |
+
return m.eval()
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def init_copy_from_p(path, device):
|
| 243 |
+
"""PMapCopy with the weights of a trained P; the copy head is new."""
|
| 244 |
+
ck = torch.load(path, map_location=device, weights_only=False)
|
| 245 |
+
cfg = dict(ck["cfg"])
|
| 246 |
+
cfg.pop("copy", None)
|
| 247 |
+
m = PMapCopy(**cfg).to(device)
|
| 248 |
+
missing, unexpected = m.load_state_dict(ck["model"], strict=False)
|
| 249 |
+
assert not unexpected, unexpected
|
| 250 |
+
assert all(k.split(".")[0] in COPY_MODULES for k in missing), missing
|
| 251 |
+
return m
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
# ------------------------------------------------------------------------------------------------ training data
|
| 255 |
+
|
| 256 |
+
def tokens_of(c: WCorpus, gi, rec, r0, r1):
|
| 257 |
+
"""(token [L] with HOLD for roll-body beats without hits, state [L]: known / hold / other-or-off-grid)."""
|
| 258 |
+
T = tables()
|
| 259 |
+
a = chart_arrays(c, gi, rec, r0, r1)
|
| 260 |
+
tok = a["tok"].astype(np.int64).copy()
|
| 261 |
+
hold = a["in_body"] & (tok == EMPTY)
|
| 262 |
+
tok[hold] = T["HOLD"]
|
| 263 |
+
offgrid = (a["allowed"] == 0) & ~a["in_body"]
|
| 264 |
+
st = np.where(tok == T["HOLD"], ST_HOLD, np.where((tok == OTHER) | offgrid, ST_OTHER, ST_KNOWN))
|
| 265 |
+
return tok, st
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def charts_by_tier(G):
|
| 269 |
+
return {int(t): lst for t, lst in G["w"]["charts"].items()}
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def rand_mask(L, rng):
|
| 273 |
+
if rng.random() < P_ALL_MASKED:
|
| 274 |
+
return np.ones(L, bool)
|
| 275 |
+
n = max(1, math.ceil(math.cos(math.pi * rng.random() / 2) * L))
|
| 276 |
+
m = np.zeros(L, bool)
|
| 277 |
+
m[rng.choice(L, min(n, L), replace=False)] = True
|
| 278 |
+
return m
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def measure_mask(meas, rng):
|
| 282 |
+
"""Stage 5e: whole measures masked (10% everything, else a cos(pi u / 2) share of the measures, at least one)."""
|
| 283 |
+
L = len(meas)
|
| 284 |
+
if rng.random() < P_ALL_MASKED:
|
| 285 |
+
return np.ones(L, bool)
|
| 286 |
+
um = np.unique(meas)
|
| 287 |
+
n = max(1, math.ceil(math.cos(math.pi * rng.random() / 2) * len(um)))
|
| 288 |
+
return np.isin(meas, rng.choice(um, min(n, len(um)), replace=False))
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def make_p_crop(c: WCorpus, k: int, r0: int, rng, length: int = CROP, p_measure: float = 0.0):
|
| 292 |
+
gi, tier, _ = c.items[k]
|
| 293 |
+
G = c.groups[gi]
|
| 294 |
+
n = len(G["g"].table)
|
| 295 |
+
r1 = min(n, r0 + length)
|
| 296 |
+
L = r1 - r0
|
| 297 |
+
tok, st = tokens_of(c, gi, c.rec(k), r0, r1)
|
| 298 |
+
meas = np.asarray(G["meas"][r0:r1])
|
| 299 |
+
masked = measure_mask(meas, rng) if p_measure > 0 and rng.random() < p_measure else rand_mask(L, rng)
|
| 300 |
+
oth_tok, oth_st = np.zeros(L, np.int64), np.zeros(L, np.int64)
|
| 301 |
+
if tier == 3 and rng.random() < P_OTHER_KNOWN:
|
| 302 |
+
lst = charts_by_tier(G).get(4, [])
|
| 303 |
+
if lst:
|
| 304 |
+
oth_tok, oth_st = tokens_of(c, gi, lst[int(rng.integers(len(lst)))], r0, r1)
|
| 305 |
+
cand, rel = candidates(meas, G["g"].table.bib[r0:r1])
|
| 306 |
+
return {"rx": crop_arrays(c.r_view(gi), 0, 0, r0, r1, True), "tier": tier, "tok": tok, "state": st,
|
| 307 |
+
"masked": masked, "oth_tok": oth_tok, "oth_st": oth_st, "role": G["g"].role, "cand": cand, "rel": rel}
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def _pad(arrs, fill, dtype):
|
| 311 |
+
L = max(len(a) for a in arrs)
|
| 312 |
+
out = np.full((len(arrs), L), fill, dtype)
|
| 313 |
+
for i, a in enumerate(arrs):
|
| 314 |
+
out[i, :len(a)] = a
|
| 315 |
+
return out
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def collate_p(items):
|
| 319 |
+
T = tables()
|
| 320 |
+
b = r_collate([x["rx"] for x in items], True)
|
| 321 |
+
tok = _pad([x["tok"] for x in items], EMPTY, np.int64)
|
| 322 |
+
masked = _pad([x["masked"] for x in items], True, bool)
|
| 323 |
+
state = _pad([x["state"] for x in items], ST_OTHER, np.int64)
|
| 324 |
+
oth_tok = _pad([x["oth_tok"] for x in items], EMPTY, np.int64)
|
| 325 |
+
oth_st = _pad([x["oth_st"] for x in items], ST_UNK, np.int64)
|
| 326 |
+
own_tok = np.where(masked, EMPTY, tok)
|
| 327 |
+
b["tok"] = torch.from_numpy(tok)
|
| 328 |
+
b["own_mask"] = torch.from_numpy(T["bits"][own_tok].astype(np.float32))
|
| 329 |
+
b["own_state"] = torch.from_numpy(np.where(masked, ST_UNK, state))
|
| 330 |
+
b["oth_mask"] = torch.from_numpy(T["bits"][oth_tok].astype(np.float32))
|
| 331 |
+
b["oth_state"] = torch.from_numpy(oth_st)
|
| 332 |
+
b["tier"] = torch.tensor([x["tier"] for x in items])
|
| 333 |
+
b["lmask"] = torch.from_numpy(masked & (state != ST_OTHER)) & b["beat"]
|
| 334 |
+
b["own_tok"] = torch.from_numpy(own_tok)
|
| 335 |
+
b["own_known"] = torch.from_numpy(~masked & ((state == ST_KNOWN) | (state == ST_HOLD))) & b["beat"]
|
| 336 |
+
if all("cand" in x for x in items):
|
| 337 |
+
L = tok.shape[1]
|
| 338 |
+
cand = np.full((len(items), L, KC), -1, np.int64)
|
| 339 |
+
rel = np.zeros((len(items), L, KC), np.int64)
|
| 340 |
+
for i, x in enumerate(items):
|
| 341 |
+
cand[i, :len(x["cand"])] = x["cand"]
|
| 342 |
+
rel[i, :len(x["rel"])] = x["rel"]
|
| 343 |
+
b["cand"], b["rel"] = torch.from_numpy(cand), torch.from_numpy(rel)
|
| 344 |
+
return b
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def p_loss(model, b):
|
| 348 |
+
"""(mean cross-entropy over the counted beats, number of counted beats)."""
|
| 349 |
+
h, z0 = model.music(b)
|
| 350 |
+
lp = model.token_logp(h, z0, b)
|
| 351 |
+
ts = torch.gather(lp, 2, b["tok"][..., None])[..., 0]
|
| 352 |
+
lm = b["lmask"] & torch.isfinite(ts)
|
| 353 |
+
n = int(lm.sum())
|
| 354 |
+
return (-ts[lm].sum() / max(n, 1)), n
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
class PStream(torch.utils.data.IterableDataset):
|
| 358 |
+
"""Endless training batches (collated in the workers); charts drawn in proportion to their number of beats."""
|
| 359 |
+
|
| 360 |
+
def __init__(self, c: WCorpus, keys, batch, seed, p_measure=0.0):
|
| 361 |
+
self.c, self.keys, self.batch, self.seed, self.p_measure = c, np.asarray(keys), batch, seed, p_measure
|
| 362 |
+
w = np.array([len(c.groups[c.items[k][0]]["g"].table) for k in keys], np.float64)
|
| 363 |
+
self.p = w / w.sum()
|
| 364 |
+
|
| 365 |
+
def __iter__(self):
|
| 366 |
+
wi = torch.utils.data.get_worker_info()
|
| 367 |
+
rng = np.random.default_rng([self.seed, wi.id if wi else 0, int(time.time() * 1e3) % (2 ** 31)])
|
| 368 |
+
while True:
|
| 369 |
+
items = []
|
| 370 |
+
for k in rng.choice(self.keys, self.batch, p=self.p):
|
| 371 |
+
n = len(self.c.groups[self.c.items[k][0]]["g"].table)
|
| 372 |
+
items.append(make_p_crop(self.c, int(k), int(rng.integers(0, max(n - CROP, 0) + 1)), rng,
|
| 373 |
+
p_measure=self.p_measure))
|
| 374 |
+
yield collate_p(items)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def target_keys(c: WCorpus):
|
| 378 |
+
return [k for k, (_, t, _) in enumerate(c.items) if t in TARGET]
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def tune_specs(c: WCorpus, n, seed=7):
|
| 382 |
+
"""Fixed tune crops: (item, start, mask seed), rebuilt identically at every evaluation."""
|
| 383 |
+
rng = np.random.default_rng(seed)
|
| 384 |
+
keys = target_keys(c)
|
| 385 |
+
ks = rng.choice(keys, n, replace=len(keys) < n)
|
| 386 |
+
out = []
|
| 387 |
+
for i, k in enumerate(ks):
|
| 388 |
+
nb = len(c.groups[c.items[k][0]]["g"].table)
|
| 389 |
+
out.append((int(k), int(rng.integers(0, max(nb - CROP, 0) + 1)), seed * 100003 + i))
|
| 390 |
+
return out
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
@torch.no_grad()
|
| 394 |
+
def evaluate(model, c, specs, batch, device):
|
| 395 |
+
model.eval()
|
| 396 |
+
tot, cnt = 0.0, 0
|
| 397 |
+
for i in range(0, len(specs), batch):
|
| 398 |
+
items = [make_p_crop(c, k, r0, np.random.default_rng(sd)) for k, r0, sd in specs[i:i + batch]]
|
| 399 |
+
b = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in collate_p(items).items()}
|
| 400 |
+
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
|
| 401 |
+
l, n = p_loss(model, b)
|
| 402 |
+
tot += float(l) * n
|
| 403 |
+
cnt += n
|
| 404 |
+
model.train()
|
| 405 |
+
return tot / max(cnt, 1)
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
def train(a):
|
| 409 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 410 |
+
torch.manual_seed(a.seed)
|
| 411 |
+
out = Path(a.out)
|
| 412 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 413 |
+
logf = open(out / "metrics.jsonl", "a")
|
| 414 |
+
|
| 415 |
+
def log(rec):
|
| 416 |
+
rec["time"] = time.time()
|
| 417 |
+
logf.write(json.dumps(rec) + "\n")
|
| 418 |
+
logf.flush()
|
| 419 |
+
print(json.dumps(rec), flush=True)
|
| 420 |
+
|
| 421 |
+
tr = WCorpus(a.data, {"A", "B"}, a.cache_dir, log=lambda m: print(m, flush=True))
|
| 422 |
+
tu = WCorpus(a.data, {"tune"}, a.cache_dir, log=lambda m: print(m, flush=True))
|
| 423 |
+
if a.copy: # stage 5e: P2 = a trained P plus the copy head
|
| 424 |
+
model = init_copy_from_p(a.init, device)
|
| 425 |
+
newmods = COPY_MODULES
|
| 426 |
+
else:
|
| 427 |
+
model = init_from_r(a.init, device)
|
| 428 |
+
newmods = NEW_MODULES
|
| 429 |
+
new = [p for n, p in model.named_parameters() if n.split(".")[0] in newmods]
|
| 430 |
+
old = [p for n, p in model.named_parameters() if n.split(".")[0] not in newmods]
|
| 431 |
+
opt = torch.optim.AdamW([{"params": old, "lr": a.lr, "base": a.lr}, {"params": new, "lr": a.lr_new, "base": a.lr_new}],
|
| 432 |
+
weight_decay=0.01)
|
| 433 |
+
sched = lambda s: min(1.0, (s + 1) / a.warmup) * (0.5 * (1 + math.cos(math.pi * min(s, a.steps) / a.steps)) * 0.95 + 0.05) # noqa: E731
|
| 434 |
+
step, best = 0, math.inf
|
| 435 |
+
specs = tune_specs(tu, a.tune_crops)
|
| 436 |
+
if a.resume and (out / "last.pt").exists():
|
| 437 |
+
ck = torch.load(out / "last.pt", map_location=device, weights_only=False)
|
| 438 |
+
model.load_state_dict(ck["model"]); opt.load_state_dict(ck["opt"])
|
| 439 |
+
step, best = ck["step"], ck["best"]
|
| 440 |
+
print(f"resumed at step {step}, best {best:.5f}", flush=True)
|
| 441 |
+
keys = target_keys(tr)
|
| 442 |
+
log({"event": "start", "step": step, "params": sum(p.numel() for p in model.parameters()), "train_charts": len(keys),
|
| 443 |
+
"tune_charts": len(target_keys(tu)), "args": {k: str(v) for k, v in vars(a).items()}})
|
| 444 |
+
if step == 0:
|
| 445 |
+
log({"event": "eval", "step": 0, "tune_loss": evaluate(model, tu, specs, a.batch, device),
|
| 446 |
+
"note": "initial model (P from R: P = R; P2 from P: copy gate about 0.05)"})
|
| 447 |
+
dl = torch.utils.data.DataLoader(PStream(tr, keys, a.batch, a.seed + step, a.measure_mask), batch_size=None,
|
| 448 |
+
num_workers=a.workers,
|
| 449 |
+
prefetch_factor=4 if a.workers else None, persistent_workers=a.workers > 0)
|
| 450 |
+
it = iter(dl)
|
| 451 |
+
t_last, n_tok, ema = time.time(), 0, None
|
| 452 |
+
model.train()
|
| 453 |
+
while step < a.steps:
|
| 454 |
+
t_d = time.time()
|
| 455 |
+
b = next(it)
|
| 456 |
+
t_w = time.time() - t_d
|
| 457 |
+
b = {k: (v.to(device, non_blocking=True) if torch.is_tensor(v) else v) for k, v in b.items()}
|
| 458 |
+
for gp in opt.param_groups:
|
| 459 |
+
gp["lr"] = gp["base"] * sched(step)
|
| 460 |
+
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
|
| 461 |
+
loss, _ = p_loss(model, b)
|
| 462 |
+
opt.zero_grad(set_to_none=True)
|
| 463 |
+
loss.backward()
|
| 464 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 465 |
+
opt.step()
|
| 466 |
+
step += 1
|
| 467 |
+
n_tok += int(b["beat"].sum())
|
| 468 |
+
ema = loss.item() if ema is None else 0.98 * ema + 0.02 * loss.item()
|
| 469 |
+
if step % 50 == 0:
|
| 470 |
+
dt = time.time() - t_last
|
| 471 |
+
log({"event": "train", "step": step, "loss_ema": ema, "lr": a.lr * sched(step), "beats_per_s": n_tok / dt,
|
| 472 |
+
"data_wait_s": t_w})
|
| 473 |
+
t_last, n_tok = time.time(), 0
|
| 474 |
+
if step % a.eval_every == 0 or step == a.steps:
|
| 475 |
+
vl = evaluate(model, tu, specs, a.batch, device)
|
| 476 |
+
is_best = vl < best
|
| 477 |
+
best = min(best, vl)
|
| 478 |
+
ck = {"model": model.state_dict(), "opt": opt.state_dict(), "step": step, "best": best, "cfg": model.cfg}
|
| 479 |
+
torch.save(ck, out / "last.pt.tmp"); os.replace(out / "last.pt.tmp", out / "last.pt")
|
| 480 |
+
if is_best:
|
| 481 |
+
torch.save({"model": model.state_dict(), "cfg": model.cfg, "step": step, "tune_loss": vl}, out / "best.pt.tmp")
|
| 482 |
+
os.replace(out / "best.pt.tmp", out / "best.pt")
|
| 483 |
+
log({"event": "eval", "step": step, "tune_loss": vl, "best": best, "is_best": is_best})
|
| 484 |
+
if a.patience and not is_best and step - _last_best(out) >= a.patience:
|
| 485 |
+
log({"event": "early_stop", "step": step})
|
| 486 |
+
break
|
| 487 |
+
log({"event": "end", "step": step, "best": best})
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def _last_best(out: Path) -> int:
|
| 491 |
+
best_step = 0
|
| 492 |
+
for line in open(out / "metrics.jsonl"):
|
| 493 |
+
r = json.loads(line)
|
| 494 |
+
if r.get("event") == "eval" and r.get("is_best"):
|
| 495 |
+
best_step = r["step"]
|
| 496 |
+
return best_step
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
# ------------------------------------------------------------------------------------------------ generation
|
| 500 |
+
|
| 501 |
+
def windows(n):
|
| 502 |
+
starts = list(range(0, max(n - CROP, 0) + 1, STRIDE))
|
| 503 |
+
if starts[-1] + CROP < n:
|
| 504 |
+
starts.append(n - CROP)
|
| 505 |
+
edge = (CROP - STRIDE) // 2
|
| 506 |
+
out = []
|
| 507 |
+
for k, s in enumerate(starts):
|
| 508 |
+
e = min(n, s + CROP)
|
| 509 |
+
a = 0 if k == 0 else edge
|
| 510 |
+
bnd = e - s if e == n else (e - s) - edge
|
| 511 |
+
out.append((s, e, a, bnd))
|
| 512 |
+
return out
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
@torch.no_grad()
|
| 516 |
+
def music_windows(model, corpus, gi, device, meas=None):
|
| 517 |
+
"""Music part of every window of a group, computed once (era forced to the latest band); with meas (measure index
|
| 518 |
+
per beat), also the copy head's candidates of each window."""
|
| 519 |
+
out = []
|
| 520 |
+
bib = corpus.groups[gi].table.bib
|
| 521 |
+
for s, e, a, bnd in windows(len(corpus.groups[gi].table)):
|
| 522 |
+
item = crop_arrays(corpus, gi, 0, s, e, model.use_ms)
|
| 523 |
+
item["era"] = np.int64(N_ERA - 1)
|
| 524 |
+
bt = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in r_collate([item], model.use_ms).items()}
|
| 525 |
+
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
|
| 526 |
+
h, z0 = model.music(bt)
|
| 527 |
+
w = {"h": h, "z0": z0, "beat": bt["beat"], "valid": bt["valid"], "s": s, "e": e, "a": a, "bnd": bnd}
|
| 528 |
+
if meas is not None:
|
| 529 |
+
cand, rel = candidates(np.asarray(meas)[s:e], bib[s:e])
|
| 530 |
+
w["cand"], w["rel"] = torch.from_numpy(cand)[None].to(device), torch.from_numpy(rel)[None].to(device)
|
| 531 |
+
out.append(w)
|
| 532 |
+
return out
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def _state(tok, T):
|
| 536 |
+
"""Known-input arrays of a token array (-1 = undecided): (bits [.., 24] float32, state)."""
|
| 537 |
+
known = tok >= 0
|
| 538 |
+
t = np.where(known, tok, EMPTY)
|
| 539 |
+
st = np.where(~known, ST_UNK, np.where(t == T["HOLD"], ST_HOLD, ST_KNOWN))
|
| 540 |
+
return T["bits"][t].astype(np.float32), st
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
@torch.no_grad()
|
| 544 |
+
def logprobs(model, mw, tier, tok, oth, ban, device, beta=0.0):
|
| 545 |
+
"""[D, n, V] log-probabilities (numpy float32) for every beat, given decided tokens tok [D, n] (-1 = open) and the
|
| 546 |
+
other tier oth [D, n] (None = not given); banned tokens removed before normalising. beta: offset of the copy gate's
|
| 547 |
+
logit (stage 5f repetition knob; P2 only)."""
|
| 548 |
+
T = tables()
|
| 549 |
+
D, n = tok.shape
|
| 550 |
+
out = np.zeros((D, n, T["V"]), np.float32)
|
| 551 |
+
om, os_ = _state(tok, T)
|
| 552 |
+
if oth is None:
|
| 553 |
+
xm, xs = np.zeros_like(om), np.zeros_like(os_)
|
| 554 |
+
else:
|
| 555 |
+
xm, xs = _state(oth, T)
|
| 556 |
+
own_tok = np.where(tok >= 0, tok, EMPTY)
|
| 557 |
+
own_known = (tok >= 0) & (tok != OTHER)
|
| 558 |
+
for w in mw:
|
| 559 |
+
s, e, a, bnd = w["s"], w["e"], w["a"], w["bnd"]
|
| 560 |
+
L = e - s
|
| 561 |
+
tt = lambda x, dt: torch.from_numpy(np.ascontiguousarray(x[:, s:e])).to(device, dt) # noqa: E731
|
| 562 |
+
x = {"beat": w["beat"].expand(D, -1), "tier": torch.full((D,), tier, device=device, dtype=torch.long),
|
| 563 |
+
"own_mask": tt(om, torch.float32), "own_state": tt(os_, torch.long), "oth_mask": tt(xm, torch.float32),
|
| 564 |
+
"oth_state": tt(xs, torch.long), "valid": w["valid"].expand(D, -1, -1),
|
| 565 |
+
"own_tok": tt(own_tok, torch.long), "own_known": tt(own_known, torch.bool), "copy_beta": beta}
|
| 566 |
+
if "cand" in w:
|
| 567 |
+
x["cand"], x["rel"] = w["cand"].expand(D, -1, -1), w["rel"].expand(D, -1, -1)
|
| 568 |
+
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
|
| 569 |
+
lpx = model.token_logp(w["h"].expand(D, -1, -1, -1), w["z0"].expand(D, -1, -1), x)
|
| 570 |
+
lpx = lpx[:, :L].float()
|
| 571 |
+
bt = torch.from_numpy(ban[s:e]).to(device)
|
| 572 |
+
lpx = lpx.masked_fill(bt[None], float("-inf"))
|
| 573 |
+
lp = torch.log_softmax(lpx, -1).cpu().numpy()
|
| 574 |
+
out[:, s + a:s + bnd] = lp[:, a:bnd]
|
| 575 |
+
return out
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
@lru_cache(maxsize=1)
|
| 579 |
+
def family_counts():
|
| 580 |
+
"""[V, 3] positions of every token in: all positions (notes), the triplet family, the 1/8 family."""
|
| 581 |
+
from chartgen.v11.rmap_pseudo import FAMILY_POS
|
| 582 |
+
b = tables()["bits"].astype(np.float64)
|
| 583 |
+
return np.stack([b.sum(1), b[:, FAMILY_POS["triplet"]].sum(1), b[:, FAMILY_POS["eighth"]].sum(1)], 1)
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
def amount_offsets(lp, temp, device, iters=30, rounds=3):
|
| 587 |
+
"""Stage 5f variety knob: offsets d [3] (notes, triplet family, 1/8 family) such that softmax(lp / temp + C d),
|
| 588 |
+
summed over the rows of lp, has the same expected counts C as softmax(lp). Coordinate-wise bisection in [-8, 8]."""
|
| 589 |
+
if abs(temp - 1.0) < 1e-6 or not len(lp):
|
| 590 |
+
return np.zeros(3)
|
| 591 |
+
C = torch.as_tensor(family_counts(), dtype=torch.float32, device=device)
|
| 592 |
+
x = torch.as_tensor(lp, dtype=torch.float32, device=device)
|
| 593 |
+
|
| 594 |
+
def expect(logits):
|
| 595 |
+
return (torch.softmax(logits, -1) @ C).sum(0)
|
| 596 |
+
target = expect(x)
|
| 597 |
+
xs = x / temp
|
| 598 |
+
d = torch.zeros(3, device=device)
|
| 599 |
+
for _ in range(rounds):
|
| 600 |
+
for j in range(3):
|
| 601 |
+
if float(target[j]) <= 1e-6:
|
| 602 |
+
continue
|
| 603 |
+
lo, hi = -8.0, 8.0
|
| 604 |
+
for _ in range(iters):
|
| 605 |
+
mid = (lo + hi) / 2
|
| 606 |
+
dd = d.clone()
|
| 607 |
+
dd[j] = mid
|
| 608 |
+
if float(expect(xs + C @ dd)[j]) < float(target[j]):
|
| 609 |
+
lo = mid
|
| 610 |
+
else:
|
| 611 |
+
hi = mid
|
| 612 |
+
d[j] = (lo + hi) / 2
|
| 613 |
+
return d.cpu().numpy().astype(np.float64)
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def _sample(lp_rows, rng, temp, bias=None):
|
| 617 |
+
"""One token per row from log-probabilities at a temperature, plus an optional per-token bias (stage 5f amount
|
| 618 |
+
compensation); banned tokens stay at zero probability."""
|
| 619 |
+
x = lp_rows.astype(np.float64) / max(temp, 1e-3)
|
| 620 |
+
if bias is not None:
|
| 621 |
+
x = x + bias[None]
|
| 622 |
+
x = np.exp(x - x.max(1, keepdims=True))
|
| 623 |
+
cs = np.cumsum(x, 1)
|
| 624 |
+
u = rng.random(len(lp_rows))[:, None] * cs[:, -1:]
|
| 625 |
+
return np.minimum((cs < u).sum(1), cs.shape[1] - 1)
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
def decode_tier(model, mw, tier, n, active, ban, oth, rngs, device, steps=K_STEPS, temp=1.0, meas=None, beta=0.0,
|
| 629 |
+
keep_amounts=False):
|
| 630 |
+
"""Tokens [D, n] and the step each beat was decided at (0 = outside the span, forced EMPTY).
|
| 631 |
+
meas None: the stage-5d schedule (steps rounds, cosine, most confident beats first).
|
| 632 |
+
meas = measure index per beat (stage 5e): one measure per round, the undecided measure whose undecided beats have
|
| 633 |
+
the highest mean top log-probability (plus Gumbel noise of scale 1 - progress) first; only the windows holding the
|
| 634 |
+
decided beats are scored again.
|
| 635 |
+
beta: repetition knob (copy gate offset); keep_amounts: with temp != 1, sample from softmax(lp / temp + C d) with d
|
| 636 |
+
solved once on the first round so that the expected notes, triplet- and 1/8-family positions stay those of temp 1."""
|
| 637 |
+
D = len(rngs)
|
| 638 |
+
bias = [None] * D
|
| 639 |
+
tok = np.full((D, n), -1, np.int64)
|
| 640 |
+
step_of = np.zeros((D, n), np.int16)
|
| 641 |
+
tok[:, ~active] = EMPTY
|
| 642 |
+
N = int(active.sum())
|
| 643 |
+
if meas is None:
|
| 644 |
+
for s_ in range(1, steps + 1):
|
| 645 |
+
lp = logprobs(model, mw, tier, tok, oth, ban, device, beta)
|
| 646 |
+
if s_ == 1 and keep_amounts:
|
| 647 |
+
bias = [family_counts() @ amount_offsets(lp[k, active], temp, device) for k in range(D)]
|
| 648 |
+
remain = 0 if s_ == steps else int(math.floor(N * math.cos(math.pi / 2 * s_ / steps)))
|
| 649 |
+
for k in range(D):
|
| 650 |
+
unk = np.nonzero(tok[k] < 0)[0]
|
| 651 |
+
nfix = len(unk) - remain
|
| 652 |
+
if nfix <= 0:
|
| 653 |
+
continue
|
| 654 |
+
l = lp[k, unk]
|
| 655 |
+
key = l.max(1) + (1.0 - s_ / steps) * rngs[k].gumbel(size=len(unk))
|
| 656 |
+
pick = unk[np.argsort(-key, kind="stable")[:nfix]]
|
| 657 |
+
ch = _sample(lp[k, pick], rngs[k], temp, bias[k])
|
| 658 |
+
assert np.isfinite(lp[k, pick, ch]).all()
|
| 659 |
+
tok[k, pick] = ch
|
| 660 |
+
step_of[k, pick] = s_
|
| 661 |
+
assert (tok >= 0).all()
|
| 662 |
+
return tok, step_of
|
| 663 |
+
meas = np.asarray(meas)
|
| 664 |
+
n_meas = len(np.unique(meas[active]))
|
| 665 |
+
lp = logprobs(model, mw, tier, tok, oth, ban, device, beta)
|
| 666 |
+
if keep_amounts:
|
| 667 |
+
bias = [family_counts() @ amount_offsets(lp[k, active], temp, device) for k in range(D)]
|
| 668 |
+
s_ = 0
|
| 669 |
+
while (tok < 0).any():
|
| 670 |
+
s_ += 1
|
| 671 |
+
changed = np.zeros(n, bool)
|
| 672 |
+
for k in range(D):
|
| 673 |
+
unk = np.nonzero(tok[k] < 0)[0]
|
| 674 |
+
if not len(unk):
|
| 675 |
+
continue
|
| 676 |
+
mu = meas[unk]
|
| 677 |
+
um, inv = np.unique(mu, return_inverse=True)
|
| 678 |
+
score = np.bincount(inv, weights=lp[k, unk].max(1)) / np.bincount(inv)
|
| 679 |
+
key = score + max(0.0, 1.0 - s_ / max(n_meas, 1)) * rngs[k].gumbel(size=len(um))
|
| 680 |
+
m = um[int(np.argmax(key))]
|
| 681 |
+
pick = unk[mu == m]
|
| 682 |
+
ch = _sample(lp[k, pick], rngs[k], temp, bias[k])
|
| 683 |
+
assert np.isfinite(lp[k, pick, ch]).all()
|
| 684 |
+
tok[k, pick] = ch
|
| 685 |
+
step_of[k, pick] = min(s_, 32767)
|
| 686 |
+
changed[pick] = True
|
| 687 |
+
if (tok < 0).any():
|
| 688 |
+
sub = [w for w in mw if changed[w["s"]:w["e"]].any()]
|
| 689 |
+
lp_new = logprobs(model, sub, tier, tok, oth, ban, device, beta)
|
| 690 |
+
for w in sub:
|
| 691 |
+
lp[:, w["s"] + w["a"]:w["s"] + w["bnd"]] = lp_new[:, w["s"] + w["a"]:w["s"] + w["bnd"]]
|
| 692 |
+
return tok, step_of
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
def token_chart(tok_row, table, sections, tier, floor_ms):
|
| 696 |
+
"""Chart dict (all hits don, no big notes, rolls or kiai) of one token row, then the min-gap pass."""
|
| 697 |
+
T = tables()
|
| 698 |
+
bits = T["bits"][tok_row]
|
| 699 |
+
rows, cols = np.nonzero(bits)
|
| 700 |
+
tm = table.t0[rows] + table.bl[rows].astype(np.float64) * POS[cols] / GRID
|
| 701 |
+
o = np.argsort(tm, kind="stable")
|
| 702 |
+
n = len(tm)
|
| 703 |
+
c = {"tier": tier, "sections": np.asarray(sections, np.float64), "time": tm[o], "type": np.zeros(n, int),
|
| 704 |
+
"length_beats": np.zeros(n), "sv": np.ones(n), "kiai": []}
|
| 705 |
+
return s5a.enforce_min_gap(c, floor_ms)
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
def ban_table(table, active, tier, on, floor_ms):
|
| 709 |
+
"""[n, V] banned tokens: OTHER always; 1/8-family patterns when the gate is off; patterns with a within-beat gap
|
| 710 |
+
under floor - 1 ms; outside the span everything but EMPTY."""
|
| 711 |
+
T = tables()
|
| 712 |
+
n = len(table)
|
| 713 |
+
ban = np.zeros((n, T["V"]), bool)
|
| 714 |
+
ban[:, OTHER] = True
|
| 715 |
+
if not on:
|
| 716 |
+
ban[:, T["has8"]] = True
|
| 717 |
+
with np.errstate(invalid="ignore"):
|
| 718 |
+
ban |= (T["mg48"][None, :] * table.bl[:, None].astype(np.float64) / GRID) < (floor_ms - s5a.SEAM_SLACK_MS)
|
| 719 |
+
ban[~active] = True
|
| 720 |
+
ban[~active, EMPTY] = False
|
| 721 |
+
return ban
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
def group_uid(sid, sections):
|
| 725 |
+
return Group(int(sid), "", "", 0, None, np.asarray(sections, np.float64)).uid
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
def gen_song(model, corpus, gi, song, lg_cal, P5, floors, seed, draws, device, steps=K_STEPS, span=None,
|
| 729 |
+
decode="steps", temp=1.0, beta=0.0, keep_amounts=False, mw=None):
|
| 730 |
+
"""One set: {"draws": [{"charts": {t: chart}, "p": {t: info}}]}; Inner Oni first, then Oni given it.
|
| 731 |
+
span: (first ms, last ms) of the chart; default as s2_arms, from the song's human charts (first hit - 2 s, last hit).
|
| 732 |
+
New songs without charts pass the music span (gen_new.timing). decode: "steps" (stage 5d) or "measure" (stage 5e,
|
| 733 |
+
one measure per round); temp: sampling temperature of the tokens; beta, keep_amounts: the stage-5f knobs; mw: music
|
| 734 |
+
windows computed earlier for this group (the knob grid reuses them)."""
|
| 735 |
+
sid = int(song["beatmapset_id"])
|
| 736 |
+
g = corpus.groups[gi]
|
| 737 |
+
tb = g.table
|
| 738 |
+
n = len(tb)
|
| 739 |
+
if span is None:
|
| 740 |
+
t0s = min(float(c["time"][0]) for c in song["charts"] if len(c["time"])) - 2000.0
|
| 741 |
+
t1s = max(float(c["time"][-1]) for c in song["charts"] if len(c["time"]))
|
| 742 |
+
else:
|
| 743 |
+
t0s, t1s = float(span[0]), float(span[1])
|
| 744 |
+
active = (tb.t0 >= t0s) & (tb.t0 <= t1s)
|
| 745 |
+
from chartgen.dataset import measure_at
|
| 746 |
+
meas_all = measure_at(np.asarray(g.sections, np.float64), tb.beat.astype(np.float64))
|
| 747 |
+
if mw is None:
|
| 748 |
+
mw = music_windows(model, corpus, gi, device, meas_all if model.copy else None)
|
| 749 |
+
meas = meas_all if decode == "measure" else None
|
| 750 |
+
res = [{"charts": {}, "p": {}} for _ in range(draws)]
|
| 751 |
+
toks = {}
|
| 752 |
+
for t in (4, 3):
|
| 753 |
+
share = s5a.eighth_share(lg_cal[:, :, t])
|
| 754 |
+
on = P5.gate(t, share)
|
| 755 |
+
floor = float(floors[str(t)])
|
| 756 |
+
ban = ban_table(tb, active, t, on, floor)
|
| 757 |
+
rngs = [np.random.default_rng([seed, sid, k, t]) for k in range(draws)]
|
| 758 |
+
tok, step_of = decode_tier(model, mw, t, n, active, ban, toks.get(4) if t == 3 else None, rngs, device, steps,
|
| 759 |
+
temp=temp, meas=meas, beta=beta, keep_amounts=keep_amounts)
|
| 760 |
+
toks[t] = tok
|
| 761 |
+
for k in range(draws):
|
| 762 |
+
c, dropped = token_chart(tok[k], tb, g.sections, t, floor)
|
| 763 |
+
res[k]["charts"][t] = c
|
| 764 |
+
res[k]["p"][t] = {"tok": tok[k].astype(np.int16), "step": step_of[k], "eighth_share": share, "eighth_on": on,
|
| 765 |
+
"dropped": dropped, "decode": decode, "temp": temp, "beta": beta,
|
| 766 |
+
"keep_amounts": keep_amounts}
|
| 767 |
+
return res
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
def gen(a):
|
| 771 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 772 |
+
model = load_pmap(a.model, device)
|
| 773 |
+
P5 = s5a.Params(a.s5a_params)
|
| 774 |
+
floors = json.loads(Path(a.min_gap_json).read_text())
|
| 775 |
+
maps, calib = Maps(a.maps_R), load_calib(a.calib_R)
|
| 776 |
+
want = set(int(x) for x in Path(a.sets_file).read_text().split())
|
| 777 |
+
grid = [(float(b), float(t)) for b in a.betas.split(",") for t in a.temps.split(",")] if a.betas else None
|
| 778 |
+
out = Path(a.out)
|
| 779 |
+
if grid: # stage 5f: one pickle per (beta, temp) in the directory a.out
|
| 780 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 781 |
+
paths = {g: out / f"mapsets_b{g[0]:g}_t{g[1]:g}.pkl" for g in grid}
|
| 782 |
+
else:
|
| 783 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 784 |
+
paths = {None: out}
|
| 785 |
+
recs = {g: (pickle.load(open(f, "rb")) if f.exists() else {}) for g, f in paths.items()}
|
| 786 |
+
want -= set.intersection(*(set(r) for r in recs.values()))
|
| 787 |
+
print(f"sets to do {len(want)}; grid {grid}", flush=True)
|
| 788 |
+
corpus = Corpus(a.data, set(a.roles), log=lambda m: print(m, flush=True))
|
| 789 |
+
by_uid = {g.uid: gi for gi, g in enumerate(corpus.groups)}
|
| 790 |
+
|
| 791 |
+
def save():
|
| 792 |
+
for g, f in paths.items():
|
| 793 |
+
tmp = f.with_suffix(".tmp")
|
| 794 |
+
with open(tmp, "wb") as fh:
|
| 795 |
+
pickle.dump(recs[g], fh)
|
| 796 |
+
tmp.replace(f)
|
| 797 |
+
|
| 798 |
+
seen, t_start, n_new = set(), time.time(), 0
|
| 799 |
+
for si, song in enumerate(corpus.songs):
|
| 800 |
+
sid = int(song["beatmapset_id"])
|
| 801 |
+
if sid not in want or sid in seen:
|
| 802 |
+
continue
|
| 803 |
+
seen.add(sid)
|
| 804 |
+
ref = max(song["charts"], key=lambda c: len(c["time"]))
|
| 805 |
+
sections = np.asarray(ref["sections"], np.float64)
|
| 806 |
+
uid = group_uid(sid, sections)
|
| 807 |
+
gi = by_uid.get(uid)
|
| 808 |
+
if gi is None or uid not in maps:
|
| 809 |
+
print(f"{sid}: skipped (group {gi is not None}, map {uid in maps})", flush=True)
|
| 810 |
+
continue
|
| 811 |
+
t_set = time.time()
|
| 812 |
+
lg_cal = apply_calib(maps[uid], calib)
|
| 813 |
+
mw = None
|
| 814 |
+
if grid:
|
| 815 |
+
from chartgen.dataset import measure_at
|
| 816 |
+
g_ = corpus.groups[gi]
|
| 817 |
+
mw = music_windows(model, corpus, gi, device,
|
| 818 |
+
measure_at(np.asarray(g_.sections, np.float64), g_.table.beat.astype(np.float64)) if model.copy else None)
|
| 819 |
+
for g in paths:
|
| 820 |
+
beta, temp = g if g else (a.copy_beta, a.temp)
|
| 821 |
+
res = gen_song(model, corpus, gi, song, lg_cal, P5, floors, a.seed, a.draws, device, decode=a.decode,
|
| 822 |
+
temp=temp, beta=beta, keep_amounts=a.keep_amounts, mw=mw)
|
| 823 |
+
recs[g][sid] = {"song_key": song.get("song_key"), "sections": sections, "draws": res,
|
| 824 |
+
"beat0": int(corpus.groups[gi].table.beat[0])}
|
| 825 |
+
n_new += 1
|
| 826 |
+
notes = {t: len(c["time"]) for t, c in res[0]["charts"].items()}
|
| 827 |
+
print(f"{sid}: {time.time() - t_set:.1f} s (total {(time.time() - t_start) / 60:.1f} min, {n_new} sets) "
|
| 828 |
+
f"notes draw0 {notes}", flush=True)
|
| 829 |
+
if n_new % a.save_every == 0:
|
| 830 |
+
save()
|
| 831 |
+
save()
|
| 832 |
+
print("done", n_new, "new sets; missing", sorted(want - seen)[:20], flush=True)
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
# ------------------------------------------------------------------------------------------------ copy probe (stage 5e)
|
| 836 |
+
|
| 837 |
+
def repeat_targets(tok, st, meas, max_back=8):
|
| 838 |
+
"""[(rows of the target measure, rows of its source)] for human measures identical (token by token) to one of
|
| 839 |
+
the previous max_back measures; the source is the nearest such measure. Only measures with every beat known (not
|
| 840 |
+
OTHER / off-grid) and at least one note; targets whose source is itself a target are left out."""
|
| 841 |
+
T = tables()
|
| 842 |
+
rows = {}
|
| 843 |
+
for i, m in enumerate(meas):
|
| 844 |
+
rows.setdefault(int(m), []).append(i)
|
| 845 |
+
order = sorted(rows)
|
| 846 |
+
rhythm = {}
|
| 847 |
+
for m in order:
|
| 848 |
+
r = rows[m]
|
| 849 |
+
if all(st[i] != ST_OTHER for i in r) and any(tok[i] not in (EMPTY, T["HOLD"]) for i in r):
|
| 850 |
+
rhythm[m] = tuple(int(tok[i]) for i in r)
|
| 851 |
+
tgt = {}
|
| 852 |
+
for m in order:
|
| 853 |
+
if m not in rhythm:
|
| 854 |
+
continue
|
| 855 |
+
for mm in range(m - 1, m - max_back - 1, -1):
|
| 856 |
+
if rhythm.get(mm) == rhythm[m]:
|
| 857 |
+
tgt[m] = mm
|
| 858 |
+
break
|
| 859 |
+
return [(np.asarray(rows[m]), np.asarray(rows[s])) for m, s in tgt.items() if s not in tgt]
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
@torch.no_grad()
|
| 863 |
+
def probe(a):
|
| 864 |
+
"""Stage 5e, part A: for human repeated measures of the validation charts, the model's probability of the human
|
| 865 |
+
tokens of the target measure (= its source's) under three conditions of the own tier: D nothing decided, C
|
| 866 |
+
everything decided except the targets, Cs everything except the targets and their sources. Oni gets the same
|
| 867 |
+
mapset's Inner Oni (the generation condition), Inner Oni gets no other tier. Song-level means, bootstrap over sets."""
|
| 868 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 869 |
+
model = load_pmap(a.model, device)
|
| 870 |
+
T = tables()
|
| 871 |
+
want = set(int(x) for x in Path(a.sets_file).read_text().split())
|
| 872 |
+
c = WCorpus(a.data, {"val"}, a.cache_dir, log=lambda m: print(m, flush=True))
|
| 873 |
+
res = {3: {}, 4: {}}
|
| 874 |
+
t0 = time.time()
|
| 875 |
+
for k in target_keys(c):
|
| 876 |
+
gi, tier, _ = c.items[k]
|
| 877 |
+
G = c.groups[gi]
|
| 878 |
+
sid = int(G["g"].set_id)
|
| 879 |
+
if sid not in want:
|
| 880 |
+
continue
|
| 881 |
+
n = len(G["g"].table)
|
| 882 |
+
tok, st = tokens_of(c, gi, c.rec(k), 0, n)
|
| 883 |
+
oth_tok, oth_st = np.zeros(n, np.int64), np.zeros(n, np.int64)
|
| 884 |
+
if tier == 3:
|
| 885 |
+
lst = charts_by_tier(G).get(4, [])
|
| 886 |
+
if lst:
|
| 887 |
+
oth_tok, oth_st = tokens_of(c, gi, lst[0], 0, n)
|
| 888 |
+
targets = repeat_targets(tok, st, G["meas"])
|
| 889 |
+
out = res[tier].setdefault(sid, {"D": [], "C": [], "Cs": [], "beats": 0, "measures": 0})
|
| 890 |
+
for s, e, aa, bnd in windows(n):
|
| 891 |
+
tw = [(r, q) for r, q in targets if r.min() >= s + aa and r.max() < s + bnd and q.min() >= s and q.max() < e]
|
| 892 |
+
if not tw:
|
| 893 |
+
continue
|
| 894 |
+
tr = np.concatenate([r for r, _ in tw]) - s
|
| 895 |
+
sr = np.concatenate([q for _, q in tw]) - s
|
| 896 |
+
L = e - s
|
| 897 |
+
rx = crop_arrays(c.r_view(gi), 0, 0, s, e, True)
|
| 898 |
+
cand, rel = candidates(np.asarray(G["meas"][s:e]), G["g"].table.bib[s:e])
|
| 899 |
+
known = {"D": np.zeros(L, bool), "C": np.ones(L, bool), "Cs": np.ones(L, bool)}
|
| 900 |
+
known["C"][tr] = False
|
| 901 |
+
known["Cs"][tr] = False
|
| 902 |
+
known["Cs"][sr] = False
|
| 903 |
+
items = [{"rx": rx, "tier": tier, "tok": tok[s:e], "state": st[s:e], "masked": ~known[cd],
|
| 904 |
+
"oth_tok": oth_tok[s:e], "oth_st": oth_st[s:e], "role": "val", "cand": cand, "rel": rel}
|
| 905 |
+
for cd in ("D", "C", "Cs")]
|
| 906 |
+
b = {kk: (v.to(device) if torch.is_tensor(v) else v) for kk, v in collate_p(items).items()}
|
| 907 |
+
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
|
| 908 |
+
h, z0 = model.music(b)
|
| 909 |
+
lp = model.token_logp(h, z0, b).float()
|
| 910 |
+
g_ = torch.gather(lp, 2, b["tok"][..., None])[..., 0].cpu().numpy() # [3, L]
|
| 911 |
+
for r, _ in tw:
|
| 912 |
+
rr = r - s
|
| 913 |
+
vals = g_[:, rr].sum(1)
|
| 914 |
+
if not np.isfinite(vals).all():
|
| 915 |
+
continue
|
| 916 |
+
for j, cd in enumerate(("D", "C", "Cs")):
|
| 917 |
+
out[cd].append(float(vals[j]))
|
| 918 |
+
out["beats"] += len(rr)
|
| 919 |
+
out["measures"] += 1
|
| 920 |
+
rng = np.random.default_rng(0)
|
| 921 |
+
|
| 922 |
+
def boot(v):
|
| 923 |
+
v = np.asarray(v, float)
|
| 924 |
+
if len(v) < 5:
|
| 925 |
+
return [float(v.mean()) if len(v) else None, None, None, int(len(v))]
|
| 926 |
+
bs = v[rng.integers(0, len(v), (1000, len(v)))].mean(1)
|
| 927 |
+
return [float(v.mean()), float(np.percentile(bs, 2.5)), float(np.percentile(bs, 97.5)), int(len(v))]
|
| 928 |
+
summary = {}
|
| 929 |
+
for tier, d in res.items():
|
| 930 |
+
S = [x for x in d.values() if x["measures"] > 0]
|
| 931 |
+
blk = {"sets": len(S), "target measures": int(sum(x["measures"] for x in S)),
|
| 932 |
+
"beats": int(sum(x["beats"] for x in S))}
|
| 933 |
+
for cd in ("D", "C", "Cs"):
|
| 934 |
+
blk[f"copy probability {cd}"] = boot([np.mean(np.exp(x[cd])) for x in S])
|
| 935 |
+
blk[f"log-prob per measure {cd}"] = boot([np.mean(x[cd]) for x in S])
|
| 936 |
+
blk["copy probability C - Cs"] = boot([np.mean(np.exp(x["C"])) - np.mean(np.exp(x["Cs"])) for x in S])
|
| 937 |
+
blk["copy probability Cs - D"] = boot([np.mean(np.exp(x["Cs"])) - np.mean(np.exp(x["D"])) for x in S])
|
| 938 |
+
summary[{3: "Oni", 4: "Inner Oni"}[tier]] = blk
|
| 939 |
+
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
|
| 940 |
+
Path(a.out).write_text(json.dumps(summary, indent=1))
|
| 941 |
+
print(json.dumps(summary, indent=1), f"\n{time.time() - t0:.0f}s", flush=True)
|
| 942 |
+
|
| 943 |
+
|
| 944 |
+
# ------------------------------------------------------------------------------------------------ self-test
|
| 945 |
+
|
| 946 |
+
def selftest():
|
| 947 |
+
"""CPU checks on the pilot shard: (1) at initialisation P equals R's pseudo-chart factorisation; (2) the loss
|
| 948 |
+
falls when overfitting a fixed batch; (3) decoding gives valid, gate- and gap-respecting charts."""
|
| 949 |
+
torch.manual_seed(0)
|
| 950 |
+
dev = torch.device("cpu")
|
| 951 |
+
T = tables()
|
| 952 |
+
shard = ["data/pilot/features/taiko-00000.pkl"]
|
| 953 |
+
cache = "data/hfruns/runs/v11_s2/caches"
|
| 954 |
+
c = WCorpus(shard, {"A", "B"}, cache, log=lambda m: None)
|
| 955 |
+
model = init_from_r("data/hfruns/runs/r_full/best.pt", dev)
|
| 956 |
+
rng = np.random.default_rng(0)
|
| 957 |
+
keys = target_keys(c)
|
| 958 |
+
items = []
|
| 959 |
+
for k in rng.choice(keys, 4, replace=False):
|
| 960 |
+
n = len(c.groups[c.items[k][0]]["g"].table)
|
| 961 |
+
items.append(make_p_crop(c, int(k), int(rng.integers(0, max(n - 96, 0) + 1)), rng, length=96))
|
| 962 |
+
b = collate_p(items)
|
| 963 |
+
# (1) P = R at init: scores equal the sum of R's position logits over the pattern (finite entries)
|
| 964 |
+
model.eval()
|
| 965 |
+
with torch.no_grad():
|
| 966 |
+
lg_r, _ = RMap.forward(model, b)
|
| 967 |
+
h, z0 = model.music(b)
|
| 968 |
+
s = model.scores(h, z0, b["beat"], b["tier"], b["own_mask"], b["own_state"], b["oth_mask"], b["oth_state"], b["valid"])
|
| 969 |
+
lt = torch.gather(lg_r, 3, b["tier"].view(-1, 1, 1, 1).expand(*lg_r.shape[:3], 1))[..., 0]
|
| 970 |
+
ref = torch.einsum("blp,vp->blv", lt, model.vbits)
|
| 971 |
+
fin = torch.isfinite(s)
|
| 972 |
+
assert torch.allclose(s[fin], ref[fin], atol=1e-4), (s[fin] - ref[fin]).abs().max()
|
| 973 |
+
assert not fin[..., OTHER].any() and fin[..., EMPTY].all() and fin[..., T["HOLD"]].all()
|
| 974 |
+
print("P = R at init: ok;", "counted beats", int(b["lmask"].sum()), "HOLD targets",
|
| 975 |
+
int(((b["tok"] == T["HOLD"]) & b["lmask"]).sum()), "Oni with Inner Oni given",
|
| 976 |
+
int(((b["tier"] == 3)[:, None] & (b["oth_state"] > 0)).any(1).sum()))
|
| 977 |
+
# (2) overfit
|
| 978 |
+
model.train()
|
| 979 |
+
new = [p for nm, p in model.named_parameters() if nm.split(".")[0] in NEW_MODULES]
|
| 980 |
+
opt = torch.optim.AdamW([{"params": [p for nm, p in model.named_parameters() if nm.split(".")[0] not in NEW_MODULES],
|
| 981 |
+
"lr": 3e-4}, {"params": new, "lr": 3e-3}])
|
| 982 |
+
first = None
|
| 983 |
+
for st in range(25):
|
| 984 |
+
loss, n = p_loss(model, b)
|
| 985 |
+
opt.zero_grad(); loss.backward(); opt.step()
|
| 986 |
+
first = loss.item() if first is None else first
|
| 987 |
+
if st % 8 == 0:
|
| 988 |
+
print(st, round(loss.item(), 4), n)
|
| 989 |
+
assert loss.item() < first * 0.85, (first, loss.item())
|
| 990 |
+
print("overfit ok:", round(first, 3), "->", round(loss.item(), 3))
|
| 991 |
+
# (3) decoding on one group (short song part), gate off for Inner Oni to test the ban
|
| 992 |
+
model.eval()
|
| 993 |
+
rc = Corpus(shard, {"A", "B"}, log=lambda m: None)
|
| 994 |
+
gi = min(range(len(rc.groups)), key=lambda i: len(rc.groups[i].table))
|
| 995 |
+
g = rc.groups[gi]
|
| 996 |
+
song = rc.songs[g.song_index]
|
| 997 |
+
tb = g.table
|
| 998 |
+
n = len(tb)
|
| 999 |
+
active = np.ones(n, bool)
|
| 1000 |
+
mw = music_windows(model, rc, gi, dev)
|
| 1001 |
+
toks = {}
|
| 1002 |
+
for t, on in ((4, False), (3, True)):
|
| 1003 |
+
ban = ban_table(tb, active, t, on, 57.0 if t == 3 else 32.0)
|
| 1004 |
+
tok, step_of = decode_tier(model, mw, t, n, active, ban, toks.get(4) if t == 3 else None,
|
| 1005 |
+
[np.random.default_rng([0, k, t]) for k in range(2)], dev, steps=4)
|
| 1006 |
+
toks[t] = tok
|
| 1007 |
+
assert not ban[np.arange(n)[None].repeat(2, 0), tok].any()
|
| 1008 |
+
assert (step_of >= 1).all() and (step_of <= 4).all()
|
| 1009 |
+
if not on:
|
| 1010 |
+
assert not T["has8"][tok].any()
|
| 1011 |
+
ch, dropped = token_chart(tok[0], tb, g.sections, t, 57.0 if t == 3 else 32.0)
|
| 1012 |
+
gaps = np.diff(ch["time"])
|
| 1013 |
+
assert (gaps >= (57.0 if t == 3 else 32.0) - 1.0 - 1e-6).all()
|
| 1014 |
+
print(f"tier {t}: {n} beats, notes {len(ch['time'])}, dropped {dropped}, tokens HOLD "
|
| 1015 |
+
f"{int((tok == T['HOLD']).sum())}, steps {np.bincount(step_of[0], minlength=5)[1:].tolist()}")
|
| 1016 |
+
print("selftest ok", song["beatmapset_id"])
|
| 1017 |
+
|
| 1018 |
+
|
| 1019 |
+
def selftest_copy(p_ckpt="data/hfruns/runs/p_s0/best.pt"):
|
| 1020 |
+
"""CPU checks of the copy head on the pilot shard: (1) with no decided beat P2 equals P exactly; (2) candidates
|
| 1021 |
+
are same-beat beats of other measures within CW; (3) loss falls when overfitting with measure masking; (4) both
|
| 1022 |
+
decoding modes give valid tokens."""
|
| 1023 |
+
torch.manual_seed(0)
|
| 1024 |
+
dev = torch.device("cpu")
|
| 1025 |
+
shard = ["data/pilot/features/taiko-00000.pkl"]
|
| 1026 |
+
c = WCorpus(shard, {"A", "B"}, "data/hfruns/runs/v11_s2/caches", log=lambda m: None)
|
| 1027 |
+
p = load_pmap(p_ckpt, dev)
|
| 1028 |
+
p2 = init_copy_from_p(p_ckpt, dev).eval()
|
| 1029 |
+
rng = np.random.default_rng(0)
|
| 1030 |
+
keys = target_keys(c)
|
| 1031 |
+
items = []
|
| 1032 |
+
for k in rng.choice(keys, 4, replace=False):
|
| 1033 |
+
n = len(c.groups[c.items[k][0]]["g"].table)
|
| 1034 |
+
items.append(make_p_crop(c, int(k), int(rng.integers(0, max(n - 96, 0) + 1)), rng, length=96, p_measure=1.0))
|
| 1035 |
+
x0 = [dict(it, masked=np.ones(len(it["tok"]), bool)) for it in items]
|
| 1036 |
+
b0 = collate_p(x0)
|
| 1037 |
+
with torch.no_grad():
|
| 1038 |
+
h, z0 = p.music(b0)
|
| 1039 |
+
l1 = p.token_logp(h, z0, b0)
|
| 1040 |
+
l2 = p2.token_logp(*p2.music(b0), b0)
|
| 1041 |
+
fin = torch.isfinite(l1)
|
| 1042 |
+
assert torch.equal(fin, torch.isfinite(l2)) and torch.allclose(l1[fin], l2[fin], atol=1e-5)
|
| 1043 |
+
cand, rel = items[0]["cand"], items[0]["rel"]
|
| 1044 |
+
for i in range(len(cand)):
|
| 1045 |
+
for j, cc in enumerate(cand[i]):
|
| 1046 |
+
if cc < 0:
|
| 1047 |
+
continue
|
| 1048 |
+
assert abs(rel[i, j] - CW) <= CW and rel[i, j] != CW
|
| 1049 |
+
print("P2 = P with nothing decided: ok; candidates per beat (mean)", float((cand >= 0).sum(1).mean()))
|
| 1050 |
+
b = collate_p(items)
|
| 1051 |
+
p2.train()
|
| 1052 |
+
opt = torch.optim.AdamW(p2.parameters(), lr=1e-3)
|
| 1053 |
+
first = None
|
| 1054 |
+
for s in range(20):
|
| 1055 |
+
loss, n = p_loss(p2, b)
|
| 1056 |
+
assert torch.isfinite(loss)
|
| 1057 |
+
opt.zero_grad(); loss.backward(); opt.step()
|
| 1058 |
+
first = loss.item() if first is None else first
|
| 1059 |
+
assert loss.item() < first * 0.9, (first, loss.item())
|
| 1060 |
+
print("copy overfit ok:", round(first, 3), "->", round(loss.item(), 3), "gate bias", float(p2.c_gate.bias))
|
| 1061 |
+
p2.eval()
|
| 1062 |
+
rc = Corpus(shard, {"A", "B"}, log=lambda m: None)
|
| 1063 |
+
gi = min(range(len(rc.groups)), key=lambda i: len(rc.groups[i].table))
|
| 1064 |
+
g = rc.groups[gi]
|
| 1065 |
+
tb = g.table
|
| 1066 |
+
n = len(tb)
|
| 1067 |
+
from chartgen.dataset import measure_at
|
| 1068 |
+
meas = measure_at(np.asarray(g.sections, np.float64), tb.beat.astype(np.float64))
|
| 1069 |
+
mw = music_windows(p2, rc, gi, dev, meas)
|
| 1070 |
+
ban = ban_table(tb, np.ones(n, bool), 4, True, 32.0)
|
| 1071 |
+
for mode in ("steps", "measure"):
|
| 1072 |
+
tok, st = decode_tier(p2, mw, 4, n, np.ones(n, bool), ban, None, [np.random.default_rng([1, k]) for k in range(2)],
|
| 1073 |
+
dev, steps=4, temp=1.0, meas=meas if mode == "measure" else None)
|
| 1074 |
+
assert (tok >= 0).all() and not ban[np.arange(n)[None].repeat(2, 0), tok].any()
|
| 1075 |
+
print(f"decode {mode}: ok, rounds {int(st.max())}")
|
| 1076 |
+
print("selftest_copy ok")
|
| 1077 |
+
|
| 1078 |
+
|
| 1079 |
+
def main(argv=None):
|
| 1080 |
+
p = argparse.ArgumentParser()
|
| 1081 |
+
p.add_argument("cmd", nargs="?", choices=["train", "gen", "probe"])
|
| 1082 |
+
p.add_argument("--selftest", action="store_true")
|
| 1083 |
+
p.add_argument("--selftest-copy", action="store_true")
|
| 1084 |
+
p.add_argument("--data", nargs="*", default=[])
|
| 1085 |
+
p.add_argument("--cache-dir", default=None)
|
| 1086 |
+
p.add_argument("--init")
|
| 1087 |
+
p.add_argument("--model")
|
| 1088 |
+
p.add_argument("--out")
|
| 1089 |
+
p.add_argument("--seed", type=int, default=0)
|
| 1090 |
+
p.add_argument("--steps", type=int, default=8000)
|
| 1091 |
+
p.add_argument("--batch", type=int, default=16)
|
| 1092 |
+
p.add_argument("--lr", type=float, default=1e-4)
|
| 1093 |
+
p.add_argument("--lr-new", type=float, default=1e-3)
|
| 1094 |
+
p.add_argument("--warmup", type=int, default=300)
|
| 1095 |
+
p.add_argument("--eval-every", type=int, default=500)
|
| 1096 |
+
p.add_argument("--patience", type=int, default=2000)
|
| 1097 |
+
p.add_argument("--tune-crops", type=int, default=192)
|
| 1098 |
+
p.add_argument("--workers", type=int, default=6)
|
| 1099 |
+
p.add_argument("--resume", action="store_true")
|
| 1100 |
+
p.add_argument("--sets-file")
|
| 1101 |
+
p.add_argument("--maps-R")
|
| 1102 |
+
p.add_argument("--calib-R")
|
| 1103 |
+
p.add_argument("--s5a-params")
|
| 1104 |
+
p.add_argument("--min-gap-json")
|
| 1105 |
+
p.add_argument("--draws", type=int, default=2)
|
| 1106 |
+
p.add_argument("--save-every", type=int, default=10)
|
| 1107 |
+
p.add_argument("--decode", choices=["steps", "measure"], default="steps")
|
| 1108 |
+
p.add_argument("--copy-beta", type=float, default=0.0)
|
| 1109 |
+
p.add_argument("--betas", default="")
|
| 1110 |
+
p.add_argument("--temps", default="1")
|
| 1111 |
+
p.add_argument("--keep-amounts", action="store_true")
|
| 1112 |
+
p.add_argument("--roles", nargs="+", default=["val"])
|
| 1113 |
+
p.add_argument("--copy", action="store_true")
|
| 1114 |
+
p.add_argument("--measure-mask", type=float, default=0.0)
|
| 1115 |
+
p.add_argument("--temp", type=float, default=1.0)
|
| 1116 |
+
a = p.parse_args(argv)
|
| 1117 |
+
if a.selftest:
|
| 1118 |
+
selftest()
|
| 1119 |
+
elif a.selftest_copy:
|
| 1120 |
+
selftest_copy()
|
| 1121 |
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""v11 stage 2: the position map R (reports/v11 階段 2 預先登記:位置圖 R.md, section 2).
|
| 2 |
+
|
| 3 |
+
Inputs per candidate position (24 per beat): log-Mel (128) and 6 onset/loudness columns (song_signature.song_onsets)
|
| 4 |
+
read at the position's exact time by linear interpolation at t + d*10 ms, d = -3..3 (7 frames); with ms inputs also
|
| 5 |
+
the max of the 6 columns over the position's own window (halfway to the neighbouring positions, at least +-1 frame),
|
| 6 |
+
log beat length and the log ms gaps to the previous / next candidate position. Per beat: beat-in-measure, era band and
|
| 7 |
+
(with ms) log beat length. A position embedding (MLP) -> the 24 embeddings of a beat concatenated -> beat token ->
|
| 8 |
+
bidirectional Transformer over the beats of a crop (sinusoidal positions; training crops of 512 beats; inference
|
| 9 |
+
crops of 512 with stride 384, keeping the middle) -> each position's embedding + its beat's state -> 5 tier logits.
|
| 10 |
+
BCE per tier, no class weights; loss only where the tier has a chart and the loss mask is set.
|
| 11 |
+
|
| 12 |
+
The no-ms model drops the window max, beat length and gaps, and reads its 7 frames at d*10/a ms with a drawn from
|
| 13 |
+
U(0.87, 1.15) (p = 0.5 per crop, i.e. a +-15% time stretch around fixed beat positions) during training.
|
| 14 |
+
|
| 15 |
+
Random init, no B0/b9/sp9 weights. Training: AdamW, bf16, warmup + cosine, early stopping on the tuning set's loss;
|
| 16 |
+
last.pt every eval for --resume.
|
| 17 |
+
|
| 18 |
+
python -m chartgen.v11.rmap train --data f*.pkl --roles A B --out runs/r_full [--no-ms] [--steps N]
|
| 19 |
+
python -m chartgen.v11.rmap export --data f*.pkl --model runs/r_full/best.pt --roles val tune --out maps_val.npz
|
| 20 |
+
python -m chartgen.v11.rmap --selftest
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import argparse
|
| 26 |
+
import json
|
| 27 |
+
import math
|
| 28 |
+
import os
|
| 29 |
+
import pickle
|
| 30 |
+
import time
|
| 31 |
+
from pathlib import Path
|
| 32 |
+
|
| 33 |
+
import numpy as np
|
| 34 |
+
import torch
|
| 35 |
+
import torch.nn as nn
|
| 36 |
+
import torch.nn.functional as F
|
| 37 |
+
|
| 38 |
+
from chartgen.dataset import load_songs
|
| 39 |
+
from chartgen.v11.patterns import GRID
|
| 40 |
+
from chartgen.v11.rmap_data import (N_ERA, N_POS, N_TIERS, POS, Group, bits_to_bool, song_groups)
|
| 41 |
+
from chartgen.v11.song_signature import song_onsets
|
| 42 |
+
|
| 43 |
+
N_MEL, N_ONS = 128, 6
|
| 44 |
+
D_OFF = np.arange(-3, 4)
|
| 45 |
+
CROP = 512
|
| 46 |
+
STRIDE = 384
|
| 47 |
+
PAD_F = 8
|
| 48 |
+
GAP_PREV = np.diff(np.r_[POS[-1] - GRID, POS]).astype(np.float32) # in 1/48 beat
|
| 49 |
+
GAP_NEXT = np.diff(np.r_[POS, POS[0] + GRID]).astype(np.float32)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# ------------------------------------------------------------------------------------------------ data
|
| 53 |
+
|
| 54 |
+
def cache_path(shard) -> Path:
|
| 55 |
+
return Path(shard).with_suffix(".r.pkl")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def prep_shard(shard) -> Path:
|
| 59 |
+
"""Write <shard>.r.pkl: per non-test song its charts (no mel), mel offset/length in the <shard>.mel.npy sidecar,
|
| 60 |
+
onset columns (float16) and groups (all roles). The sidecar is written by load_songs(mmap=True)."""
|
| 61 |
+
out = cache_path(shard)
|
| 62 |
+
if out.exists():
|
| 63 |
+
return out
|
| 64 |
+
songs = load_songs([shard], mmap=True)
|
| 65 |
+
recs, o = [], 0
|
| 66 |
+
for s in songs:
|
| 67 |
+
n = len(s["mel"])
|
| 68 |
+
gs = song_groups(s)
|
| 69 |
+
if gs:
|
| 70 |
+
recs.append({"beatmapset_id": s["beatmapset_id"], "song_key": s.get("song_key"), "charts": s["charts"],
|
| 71 |
+
"mel_off": o, "mel_len": n,
|
| 72 |
+
"ons": song_onsets(np.asarray(s["mel"], np.float32)).astype(np.float16), "groups": gs})
|
| 73 |
+
o += n
|
| 74 |
+
tmp = out.with_suffix(f".{os.getpid()}.tmp")
|
| 75 |
+
with open(tmp, "wb") as f:
|
| 76 |
+
pickle.dump(recs, f, protocol=pickle.HIGHEST_PROTOCOL)
|
| 77 |
+
os.replace(tmp, out)
|
| 78 |
+
return out
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class Corpus:
|
| 82 |
+
"""Song records (mel memmaps), their onset columns and the groups of the requested roles (from the per-shard
|
| 83 |
+
caches of prep_shard, built on first use)."""
|
| 84 |
+
|
| 85 |
+
def __init__(self, paths, roles, tiers=range(N_TIERS), log=print):
|
| 86 |
+
t0 = time.time()
|
| 87 |
+
self.songs, self.ons, self.groups = [], [], []
|
| 88 |
+
for p in sorted(x for x in paths if not str(x).endswith(".r.pkl")):
|
| 89 |
+
cp = cache_path(p)
|
| 90 |
+
recs = pickle.load(open(cp if cp.exists() and not Path(p).exists() else prep_shard(p), "rb"))
|
| 91 |
+
npy = Path(p).with_suffix(".mel.npy")
|
| 92 |
+
mm = np.load(npy, mmap_mode="r") if npy.exists() else None # evaluation only: no mel needed
|
| 93 |
+
for r in recs:
|
| 94 |
+
gs = [g for g in r["groups"] if g.role in roles and any(t in g.charts for t in tiers)]
|
| 95 |
+
if not gs:
|
| 96 |
+
continue
|
| 97 |
+
song = {"beatmapset_id": r["beatmapset_id"], "song_key": r["song_key"], "charts": r["charts"],
|
| 98 |
+
"mel": (mm[r["mel_off"]:r["mel_off"] + r["mel_len"]] if mm is not None
|
| 99 |
+
else np.zeros((r["mel_len"], 0), np.float16))}
|
| 100 |
+
self.songs.append(song)
|
| 101 |
+
self.ons.append(r["ons"])
|
| 102 |
+
for g in gs:
|
| 103 |
+
g.song_index = len(self.songs) - 1
|
| 104 |
+
g.charts = {t: v for t, v in g.charts.items() if t in tiers}
|
| 105 |
+
self.groups.append(g)
|
| 106 |
+
log(f"{Path(p).name}: {len(self.songs)} songs, {len(self.groups)} groups ({time.time() - t0:.0f} s)")
|
| 107 |
+
|
| 108 |
+
def examples(self):
|
| 109 |
+
"""[(group index, example index, n beats)]"""
|
| 110 |
+
return [(gi, i, len(g.table)) for gi, g in enumerate(self.groups) for i in range(g.n_examples())]
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def crop_arrays(corpus: Corpus, gi: int, ei: int, r0: int, r1: int, use_ms: bool, stretch: float = 1.0):
|
| 114 |
+
"""Numpy arrays of one crop (beat rows r0..r1 of group gi, example ei)."""
|
| 115 |
+
g: Group = corpus.groups[gi]
|
| 116 |
+
tb = g.table
|
| 117 |
+
mel = corpus.songs[g.song_index]["mel"]
|
| 118 |
+
ons = corpus.ons[g.song_index]
|
| 119 |
+
T = len(mel)
|
| 120 |
+
pt = tb.t0[r0:r1, None] + tb.bl[r0:r1, None].astype(np.float64) * POS[None] / GRID # [L, 24] ms
|
| 121 |
+
f0 = int(math.floor(pt.min() / 10.0)) - PAD_F
|
| 122 |
+
f1 = int(math.ceil(pt.max() / 10.0)) + PAD_F + 1
|
| 123 |
+
a, b = max(f0, 0), min(f1, T)
|
| 124 |
+
W = f1 - f0
|
| 125 |
+
m = np.full((W, N_MEL), float(np.min(mel[a:b])) if b > a else 0.0, np.float16)
|
| 126 |
+
o = np.zeros((W, N_ONS), np.float16)
|
| 127 |
+
if b > a:
|
| 128 |
+
m[a - f0:b - f0] = mel[a:b]
|
| 129 |
+
o[a - f0:b - f0] = ons[a:b]
|
| 130 |
+
tpos = (pt / 10.0 - f0).astype(np.float32)
|
| 131 |
+
out = {"mel": m, "ons": o, "tpos": tpos, "bib": tb.bib[r0:r1].astype(np.int64),
|
| 132 |
+
"era": np.int64(g.era), "valid": bits_to_bool(tb.valid[r0:r1]), "stretch": np.float32(stretch)}
|
| 133 |
+
tgt, los, has = g.example(ei)
|
| 134 |
+
out["tgt"] = np.stack([bits_to_bool(tgt[r0:r1, t]) for t in range(N_TIERS)], -1)
|
| 135 |
+
out["loss"] = np.stack([bits_to_bool(los[r0:r1, t]) for t in range(N_TIERS)], -1) & has[None, None, :]
|
| 136 |
+
if use_ms:
|
| 137 |
+
bl = tb.bl[r0:r1].astype(np.float32)
|
| 138 |
+
out["logbl"] = np.log(bl)
|
| 139 |
+
hl = bl[:, None] * GAP_PREV[None] / GRID / 2 / 10.0
|
| 140 |
+
hr = bl[:, None] * GAP_NEXT[None] / GRID / 2 / 10.0
|
| 141 |
+
c = np.round(tpos).astype(np.int64)
|
| 142 |
+
lo = np.clip(np.minimum(c - 1, np.ceil(tpos - hl - 1e-6).astype(np.int64)), 0, W - 1)
|
| 143 |
+
hi = np.clip(np.maximum(c + 1, np.floor(tpos + hr + 1e-6).astype(np.int64)), 0, W - 1)
|
| 144 |
+
mx = np.full(lo.shape + (N_ONS,), -np.inf, np.float32)
|
| 145 |
+
of = o.astype(np.float32)
|
| 146 |
+
for d in range(int((hi - lo).max()) + 1):
|
| 147 |
+
gidx = lo + d
|
| 148 |
+
ok = gidx <= hi
|
| 149 |
+
mx[ok] = np.maximum(mx[ok], of[gidx[ok]])
|
| 150 |
+
out["hmax"] = mx
|
| 151 |
+
return out
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def collate(items, use_ms: bool):
|
| 155 |
+
B = len(items)
|
| 156 |
+
L = max(len(x["bib"]) for x in items)
|
| 157 |
+
W = max(len(x["mel"]) for x in items)
|
| 158 |
+
batch = {
|
| 159 |
+
"mel": torch.zeros(B, W, N_MEL, dtype=torch.float16), "ons": torch.zeros(B, W, N_ONS, dtype=torch.float16),
|
| 160 |
+
"tpos": torch.zeros(B, L, N_POS), "bib": torch.zeros(B, L, dtype=torch.long),
|
| 161 |
+
"era": torch.tensor([int(x["era"]) for x in items]), "stretch": torch.tensor([float(x["stretch"]) for x in items]),
|
| 162 |
+
"beat": torch.zeros(B, L, dtype=torch.bool), "valid": torch.zeros(B, L, N_POS, dtype=torch.bool),
|
| 163 |
+
"tgt": torch.zeros(B, L, N_POS, N_TIERS, dtype=torch.bool), "loss": torch.zeros(B, L, N_POS, N_TIERS, dtype=torch.bool),
|
| 164 |
+
"wlen": torch.tensor([len(x["mel"]) for x in items]),
|
| 165 |
+
}
|
| 166 |
+
if use_ms:
|
| 167 |
+
batch["logbl"] = torch.zeros(B, L)
|
| 168 |
+
batch["hmax"] = torch.zeros(B, L, N_POS, N_ONS)
|
| 169 |
+
for i, x in enumerate(items):
|
| 170 |
+
n, w = len(x["bib"]), len(x["mel"])
|
| 171 |
+
batch["mel"][i, :w] = torch.from_numpy(x["mel"])
|
| 172 |
+
batch["ons"][i, :w] = torch.from_numpy(x["ons"])
|
| 173 |
+
batch["tpos"][i, :n] = torch.from_numpy(x["tpos"])
|
| 174 |
+
batch["bib"][i, :n] = torch.from_numpy(x["bib"])
|
| 175 |
+
batch["beat"][i, :n] = True
|
| 176 |
+
batch["valid"][i, :n] = torch.from_numpy(x["valid"])
|
| 177 |
+
batch["tgt"][i, :n] = torch.from_numpy(x["tgt"])
|
| 178 |
+
batch["loss"][i, :n] = torch.from_numpy(x["loss"] & x["valid"][..., None])
|
| 179 |
+
if use_ms:
|
| 180 |
+
batch["logbl"][i, :n] = torch.from_numpy(x["logbl"])
|
| 181 |
+
batch["hmax"][i, :n] = torch.from_numpy(np.nan_to_num(x["hmax"], neginf=0.0))
|
| 182 |
+
return batch
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
class CropStream(torch.utils.data.IterableDataset):
|
| 186 |
+
"""Endless random training crops; examples drawn in proportion to their number of beats."""
|
| 187 |
+
|
| 188 |
+
def __init__(self, corpus: Corpus, use_ms: bool, batch: int, seed: int, stretch_p: float = 0.0):
|
| 189 |
+
self.c, self.use_ms, self.batch, self.seed, self.stretch_p = corpus, use_ms, batch, seed, stretch_p
|
| 190 |
+
ex = corpus.examples()
|
| 191 |
+
self.ex = ex
|
| 192 |
+
w = np.array([n for _, _, n in ex], np.float64)
|
| 193 |
+
self.p = w / w.sum()
|
| 194 |
+
|
| 195 |
+
def __iter__(self):
|
| 196 |
+
wi = torch.utils.data.get_worker_info()
|
| 197 |
+
rng = np.random.default_rng([self.seed, wi.id if wi else 0, int(time.time() * 1e3) % (2 ** 31)])
|
| 198 |
+
while True:
|
| 199 |
+
items = []
|
| 200 |
+
for j in rng.choice(len(self.ex), self.batch, p=self.p):
|
| 201 |
+
gi, ei, n = self.ex[j]
|
| 202 |
+
r0 = int(rng.integers(0, max(n - CROP, 0) + 1))
|
| 203 |
+
a = float(rng.uniform(0.87, 1.15)) if rng.random() < self.stretch_p else 1.0
|
| 204 |
+
items.append(crop_arrays(self.c, gi, ei, r0, min(n, r0 + CROP), self.use_ms, a))
|
| 205 |
+
yield collate(items, self.use_ms)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
# ------------------------------------------------------------------------------------------------ model
|
| 209 |
+
|
| 210 |
+
class RMap(nn.Module):
|
| 211 |
+
def __init__(self, use_ms: bool = True, d_pos: int = 96, d: int = 256, layers: int = 6, heads: int = 8,
|
| 212 |
+
drop: float = 0.1):
|
| 213 |
+
super().__init__()
|
| 214 |
+
self.use_ms = use_ms
|
| 215 |
+
self.cfg = {"use_ms": use_ms, "d_pos": d_pos, "d": d, "layers": layers, "heads": heads, "drop": drop}
|
| 216 |
+
fin = len(D_OFF) * (N_MEL + N_ONS) + N_POS + ((N_ONS + 3) if use_ms else 0)
|
| 217 |
+
self.inp = nn.Sequential(nn.LayerNorm(fin), nn.Linear(fin, d_pos), nn.GELU(), nn.Linear(d_pos, d_pos))
|
| 218 |
+
self.beat_in = nn.Linear(N_POS * d_pos, d)
|
| 219 |
+
self.bib = nn.Embedding(16, d)
|
| 220 |
+
self.era = nn.Embedding(N_ERA, d)
|
| 221 |
+
self.tempo = nn.Linear(1, d) if use_ms else None
|
| 222 |
+
layer = nn.TransformerEncoderLayer(d, heads, 4 * d, drop, batch_first=True, norm_first=True, activation="gelu")
|
| 223 |
+
self.enc = nn.TransformerEncoder(layer, layers, enable_nested_tensor=False)
|
| 224 |
+
self.back = nn.Linear(d, d_pos)
|
| 225 |
+
self.head = nn.Sequential(nn.LayerNorm(d_pos), nn.Linear(d_pos, d_pos), nn.GELU(), nn.Linear(d_pos, N_TIERS))
|
| 226 |
+
pe = torch.zeros(4096, d)
|
| 227 |
+
pos = torch.arange(4096).float()[:, None]
|
| 228 |
+
div = torch.exp(torch.arange(0, d, 2).float() * (-math.log(10000.0) / d))
|
| 229 |
+
pe[:, 0::2], pe[:, 1::2] = torch.sin(pos * div), torch.cos(pos * div)
|
| 230 |
+
self.register_buffer("pe", pe, persistent=False)
|
| 231 |
+
self.register_buffer("pos_eye", torch.eye(N_POS), persistent=False)
|
| 232 |
+
gp, gn = torch.tensor(GAP_PREV / GRID), torch.tensor(GAP_NEXT / GRID)
|
| 233 |
+
self.register_buffer("gap_prev", gp, persistent=False)
|
| 234 |
+
self.register_buffer("gap_next", gn, persistent=False)
|
| 235 |
+
|
| 236 |
+
def read(self, b):
|
| 237 |
+
"""[B, L, 24, 7 * 134] interpolated features."""
|
| 238 |
+
x = torch.cat([b["mel"], b["ons"]], -1).float() # [B, W, 134]
|
| 239 |
+
B, W, _ = x.shape
|
| 240 |
+
step = torch.ones(B, device=x.device) if self.use_ms else 1.0 / b["stretch"]
|
| 241 |
+
off = torch.as_tensor(D_OFF, device=x.device, dtype=torch.float32)
|
| 242 |
+
t = b["tpos"][..., None] + off * step[:, None, None, None] # [B, L, 24, 7]
|
| 243 |
+
t = t.clamp(0, W - 1.001)
|
| 244 |
+
i0 = t.floor().long()
|
| 245 |
+
w = (t - i0).unsqueeze(-1)
|
| 246 |
+
bi = torch.arange(B, device=x.device)[:, None]
|
| 247 |
+
flat0, flat1 = i0.reshape(B, -1), (i0 + 1).reshape(B, -1)
|
| 248 |
+
v = x[bi, flat0] * (1 - w.reshape(B, -1, 1)) + x[bi, flat1] * w.reshape(B, -1, 1)
|
| 249 |
+
return v.reshape(*i0.shape, x.shape[-1]).flatten(-2)
|
| 250 |
+
|
| 251 |
+
def forward(self, b):
|
| 252 |
+
feat = self.read(b)
|
| 253 |
+
B, L = feat.shape[:2]
|
| 254 |
+
parts = [feat, self.pos_eye.expand(B, L, N_POS, N_POS)]
|
| 255 |
+
if self.use_ms:
|
| 256 |
+
lbl = b["logbl"][..., None, None].expand(B, L, N_POS, 1)
|
| 257 |
+
parts += [b["hmax"], lbl, lbl + torch.log(self.gap_prev)[None, None, :, None],
|
| 258 |
+
lbl + torch.log(self.gap_next)[None, None, :, None]]
|
| 259 |
+
h = self.inp(torch.cat(parts, -1)) # [B, L, 24, d_pos]
|
| 260 |
+
z = self.beat_in(h.flatten(-2)) + self.bib(b["bib"].clamp(max=15)) + self.era(b["era"])[:, None]
|
| 261 |
+
if self.use_ms:
|
| 262 |
+
z = z + self.tempo(b["logbl"][..., None])
|
| 263 |
+
z = z + self.pe[:L][None]
|
| 264 |
+
z = self.enc(z, src_key_padding_mask=~b["beat"])
|
| 265 |
+
out = self.head(h + self.back(z)[:, :, None]) # [B, L, 24, 5]
|
| 266 |
+
return out, z
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def masked_bce(logits, b):
|
| 270 |
+
m = b["loss"]
|
| 271 |
+
y = b["tgt"].float()
|
| 272 |
+
l = F.binary_cross_entropy_with_logits(logits.float(), y, reduction="none")
|
| 273 |
+
return (l * m).sum() / m.sum().clamp(min=1)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
# ------------------------------------------------------------------------------------------------ inference
|
| 277 |
+
|
| 278 |
+
@torch.no_grad()
|
| 279 |
+
def predict_group(model: RMap, corpus: Corpus, gi: int, device, ei: int = 0, hidden: bool = False):
|
| 280 |
+
"""[n_beats, 24, 5] logits (float32) of a whole group, crops of CROP beats with stride STRIDE (middle kept);
|
| 281 |
+
with hidden=True also the beat states [n_beats, d] of the Transformer."""
|
| 282 |
+
g = corpus.groups[gi]
|
| 283 |
+
n = len(g.table)
|
| 284 |
+
out = np.zeros((n, N_POS, N_TIERS), np.float32)
|
| 285 |
+
hz = np.zeros((n, model.cfg["d"]), np.float32) if hidden else None
|
| 286 |
+
starts = list(range(0, max(n - CROP, 0) + 1, STRIDE))
|
| 287 |
+
if starts[-1] + CROP < n:
|
| 288 |
+
starts.append(n - CROP)
|
| 289 |
+
edge = (CROP - STRIDE) // 2
|
| 290 |
+
for k, s in enumerate(starts):
|
| 291 |
+
e = min(n, s + CROP)
|
| 292 |
+
items = [crop_arrays(corpus, gi, ei, s, e, model.use_ms)]
|
| 293 |
+
bt = {kk: (v.to(device) if torch.is_tensor(v) else v) for kk, v in collate(items, model.use_ms).items()}
|
| 294 |
+
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
|
| 295 |
+
lg, z = model(bt)
|
| 296 |
+
lg = lg[0].float().cpu().numpy()
|
| 297 |
+
a = 0 if k == 0 else edge
|
| 298 |
+
bnd = e - s if e == n else (e - s) - edge
|
| 299 |
+
out[s + a:s + bnd] = lg[a:bnd]
|
| 300 |
+
if hidden:
|
| 301 |
+
hz[s + a:s + bnd] = z[0].float().cpu().numpy()[a:bnd]
|
| 302 |
+
return (out, hz) if hidden else out
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
# ------------------------------------------------------------------------------------------------ training
|
| 306 |
+
|
| 307 |
+
def tune_batches(corpus: Corpus, use_ms: bool, n: int, batch: int, seed: int = 0):
|
| 308 |
+
rng = np.random.default_rng(seed)
|
| 309 |
+
ex = corpus.examples()
|
| 310 |
+
w = np.array([x[2] for x in ex], np.float64)
|
| 311 |
+
picks = rng.choice(len(ex), n, p=w / w.sum())
|
| 312 |
+
items = []
|
| 313 |
+
for j in picks:
|
| 314 |
+
gi, ei, nb = ex[j]
|
| 315 |
+
r0 = int(rng.integers(0, max(nb - CROP, 0) + 1))
|
| 316 |
+
items.append((gi, ei, r0, min(nb, r0 + CROP)))
|
| 317 |
+
return [items[i:i + batch] for i in range(0, len(items), batch)]
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def train(a):
|
| 321 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 322 |
+
out = Path(a.out)
|
| 323 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 324 |
+
logf = open(out / "metrics.jsonl", "a")
|
| 325 |
+
|
| 326 |
+
def log(rec):
|
| 327 |
+
rec["time"] = time.time()
|
| 328 |
+
logf.write(json.dumps(rec) + "\n")
|
| 329 |
+
logf.flush()
|
| 330 |
+
print(json.dumps(rec), flush=True)
|
| 331 |
+
|
| 332 |
+
use_ms = not a.no_ms
|
| 333 |
+
tr = Corpus(a.data, set(a.roles), log=lambda m: print(m, flush=True))
|
| 334 |
+
tu = Corpus(a.data, {"tune"}, log=lambda m: print(m, flush=True)) if a.tune_crops > 0 else None
|
| 335 |
+
model = RMap(use_ms=use_ms, d_pos=a.d_pos, d=a.d, layers=a.layers, heads=a.heads).to(device)
|
| 336 |
+
n_par = sum(p.numel() for p in model.parameters())
|
| 337 |
+
opt = torch.optim.AdamW(model.parameters(), lr=a.lr, weight_decay=0.01)
|
| 338 |
+
sched = lambda s: min(1.0, (s + 1) / a.warmup) * (0.5 * (1 + math.cos(math.pi * min(s, a.steps) / a.steps)) * 0.95 + 0.05) # noqa: E731
|
| 339 |
+
step, best = 0, math.inf
|
| 340 |
+
if a.resume and (out / "last.pt").exists():
|
| 341 |
+
ck = torch.load(out / "last.pt", map_location=device)
|
| 342 |
+
model.load_state_dict(ck["model"]); opt.load_state_dict(ck["opt"])
|
| 343 |
+
step, best = ck["step"], ck["best"]
|
| 344 |
+
print(f"resumed at step {step}, best {best:.5f}", flush=True)
|
| 345 |
+
log({"event": "start", "step": step, "params": n_par, "train_groups": len(tr.groups), "roles": a.roles,
|
| 346 |
+
"use_ms": use_ms, "args": vars(a)})
|
| 347 |
+
stream = CropStream(tr, use_ms, a.batch, a.seed + step, stretch_p=0.5 if a.no_ms else 0.0)
|
| 348 |
+
dl = torch.utils.data.DataLoader(stream, batch_size=None, num_workers=a.workers, prefetch_factor=4 if a.workers else None,
|
| 349 |
+
persistent_workers=a.workers > 0)
|
| 350 |
+
tune = tune_batches(tu, use_ms, a.tune_crops, a.batch) if tu else []
|
| 351 |
+
it = iter(dl)
|
| 352 |
+
t_last, n_tok, ema = time.time(), 0, None
|
| 353 |
+
model.train()
|
| 354 |
+
while step < a.steps:
|
| 355 |
+
t_d = time.time()
|
| 356 |
+
b = next(it)
|
| 357 |
+
t_w = time.time() - t_d
|
| 358 |
+
b = {k: (v.to(device, non_blocking=True) if torch.is_tensor(v) else v) for k, v in b.items()}
|
| 359 |
+
for gp in opt.param_groups:
|
| 360 |
+
gp["lr"] = a.lr * sched(step)
|
| 361 |
+
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
|
| 362 |
+
lg, _ = model(b)
|
| 363 |
+
loss = masked_bce(lg, b)
|
| 364 |
+
opt.zero_grad(set_to_none=True)
|
| 365 |
+
loss.backward()
|
| 366 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 367 |
+
opt.step()
|
| 368 |
+
step += 1
|
| 369 |
+
n_tok += int(b["beat"].sum())
|
| 370 |
+
ema = loss.item() if ema is None else 0.98 * ema + 0.02 * loss.item()
|
| 371 |
+
if step % 50 == 0:
|
| 372 |
+
dt = time.time() - t_last
|
| 373 |
+
log({"event": "train", "step": step, "loss_ema": ema, "lr": a.lr * sched(step), "beats_per_s": n_tok / dt,
|
| 374 |
+
"data_wait_s": t_w})
|
| 375 |
+
t_last, n_tok = time.time(), 0
|
| 376 |
+
if step % a.eval_every == 0 or step == a.steps:
|
| 377 |
+
vl = evaluate(model, tu, tune, use_ms, device) if tune else float("nan")
|
| 378 |
+
is_best = vl < best
|
| 379 |
+
best = min(best, vl)
|
| 380 |
+
ck = {"model": model.state_dict(), "opt": opt.state_dict(), "step": step, "best": best, "cfg": model.cfg}
|
| 381 |
+
torch.save(ck, out / "last.pt.tmp"); os.replace(out / "last.pt.tmp", out / "last.pt")
|
| 382 |
+
if is_best:
|
| 383 |
+
torch.save({"model": model.state_dict(), "cfg": model.cfg, "step": step, "tune_loss": vl}, out / "best.pt.tmp")
|
| 384 |
+
os.replace(out / "best.pt.tmp", out / "best.pt")
|
| 385 |
+
log({"event": "eval", "step": step, "tune_loss": vl, "best": best, "is_best": is_best})
|
| 386 |
+
model.train()
|
| 387 |
+
if a.patience and is_best is False and step - _last_best(out) >= a.patience:
|
| 388 |
+
log({"event": "early_stop", "step": step})
|
| 389 |
+
break
|
| 390 |
+
log({"event": "end", "step": step, "best": best})
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def _last_best(out: Path) -> int:
|
| 394 |
+
best_step = 0
|
| 395 |
+
for line in open(out / "metrics.jsonl"):
|
| 396 |
+
r = json.loads(line)
|
| 397 |
+
if r.get("event") == "eval" and r.get("is_best"):
|
| 398 |
+
best_step = r["step"]
|
| 399 |
+
return best_step
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
@torch.no_grad()
|
| 403 |
+
def evaluate(model, corpus, batches, use_ms, device):
|
| 404 |
+
model.eval()
|
| 405 |
+
tot, cnt = 0.0, 0.0
|
| 406 |
+
for bl in batches:
|
| 407 |
+
items = [crop_arrays(corpus, gi, ei, r0, r1, use_ms) for gi, ei, r0, r1 in bl]
|
| 408 |
+
b = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in collate(items, use_ms).items()}
|
| 409 |
+
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
|
| 410 |
+
lg, _ = model(b)
|
| 411 |
+
m = b["loss"]
|
| 412 |
+
l = F.binary_cross_entropy_with_logits(lg.float(), b["tgt"].float(), reduction="none")
|
| 413 |
+
tot += float((l * m).sum())
|
| 414 |
+
cnt += float(m.sum())
|
| 415 |
+
return tot / max(cnt, 1.0)
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def load_rmap(path, device):
|
| 419 |
+
ck = torch.load(path, map_location=device)
|
| 420 |
+
m = RMap(**ck["cfg"]).to(device)
|
| 421 |
+
m.load_state_dict(ck["model"])
|
| 422 |
+
return m.eval()
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def export(a):
|
| 426 |
+
"""Logits of every group of the given roles: one npz with per-group arrays (float16, key = group uid) and an index.
|
| 427 |
+
With --hidden, also beat states and log beat length of every 4th beat (manipulation check of the no-ms model)."""
|
| 428 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 429 |
+
model = load_rmap(a.model, device)
|
| 430 |
+
c = Corpus(a.data, set(a.roles), log=lambda m: print(m, flush=True))
|
| 431 |
+
arrs, index, H, Y, K = {}, [], [], [], []
|
| 432 |
+
t0 = time.time()
|
| 433 |
+
for gi, g in enumerate(c.groups):
|
| 434 |
+
if a.hidden:
|
| 435 |
+
lg, hz = predict_group(model, c, gi, device, hidden=True)
|
| 436 |
+
H.append(hz[::4].astype(np.float16)); Y.append(np.log(g.table.bl[::4])); K += [g.key] * len(hz[::4])
|
| 437 |
+
else:
|
| 438 |
+
lg = predict_group(model, c, gi, device)
|
| 439 |
+
arrs[g.uid] = lg.astype(np.float16)
|
| 440 |
+
index.append({"uid": g.uid, "set": g.set_id, "key": g.key, "role": g.role, "era": g.era,
|
| 441 |
+
"beat0": int(g.table.beat[0]), "n": len(g.table)})
|
| 442 |
+
if gi % 200 == 0:
|
| 443 |
+
print(f"{gi}/{len(c.groups)} groups ({time.time() - t0:.0f} s)", flush=True)
|
| 444 |
+
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
|
| 445 |
+
np.savez_compressed(a.out, index=json.dumps(index), **arrs)
|
| 446 |
+
if a.hidden:
|
| 447 |
+
np.savez_compressed(str(a.out).replace(".npz", "_hidden.npz"), h=np.concatenate(H), logbl=np.concatenate(Y),
|
| 448 |
+
key=np.array(K))
|
| 449 |
+
print("wrote", a.out, len(index), "groups")
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
# ------------------------------------------------------------------------------------------------ self-test
|
| 453 |
+
|
| 454 |
+
def selftest(shard="data/pilot/features/taiko-00000.pkl"):
|
| 455 |
+
torch.manual_seed(0)
|
| 456 |
+
for use_ms in (True, False):
|
| 457 |
+
c = Corpus([shard], {"A", "B"}, log=lambda m: None)
|
| 458 |
+
st = CropStream(c, use_ms, 2, 0, stretch_p=0.0 if use_ms else 0.5)
|
| 459 |
+
b = next(iter(st))
|
| 460 |
+
m = RMap(use_ms=use_ms, d_pos=32, d=64, layers=2, heads=4)
|
| 461 |
+
lg, z = m(b)
|
| 462 |
+
assert lg.shape == (*b["tpos"].shape, N_TIERS), lg.shape
|
| 463 |
+
loss = masked_bce(lg, b)
|
| 464 |
+
loss.backward()
|
| 465 |
+
print(f"use_ms={use_ms}: batch beats {int(b['beat'].sum())}, positives {int((b['tgt'] & b['loss']).sum())}, "
|
| 466 |
+
f"loss {loss.item():.4f}, params {sum(p.numel() for p in m.parameters())}")
|
| 467 |
+
# interpolation check: a position read at an integer frame equals that frame
|
| 468 |
+
x = torch.cat([b["mel"], b["ons"]], -1).float()
|
| 469 |
+
tp = b["tpos"][0, 0, 0].item()
|
| 470 |
+
bb = {k: v.clone() if torch.is_tensor(v) else v for k, v in b.items()}
|
| 471 |
+
bb["tpos"][0, 0, 0] = float(round(tp))
|
| 472 |
+
feat = m.read(bb)
|
| 473 |
+
assert torch.allclose(feat[0, 0, 0].reshape(7, -1)[3], x[0, round(tp)], atol=1e-3)
|
| 474 |
+
lg2 = predict_group(m.eval(), c, 0, torch.device("cpu"))
|
| 475 |
+
assert lg2.shape == (len(c.groups[0].table), N_POS, N_TIERS)
|
| 476 |
+
print("selftest ok")
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def main(argv=None):
|
| 480 |
+
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 481 |
+
ap.add_argument("cmd", nargs="?", choices=["train", "export", "prep"])
|
| 482 |
+
ap.add_argument("--selftest", action="store_true")
|
| 483 |
+
ap.add_argument("--data", nargs="+")
|
| 484 |
+
ap.add_argument("--roles", nargs="+", default=["A", "B"])
|
| 485 |
+
ap.add_argument("--out")
|
| 486 |
+
ap.add_argument("--model")
|
| 487 |
+
ap.add_argument("--no-ms", action="store_true")
|
| 488 |
+
ap.add_argument("--steps", type=int, default=20000)
|
| 489 |
+
ap.add_argument("--batch", type=int, default=16)
|
| 490 |
+
ap.add_argument("--lr", type=float, default=3e-4)
|
| 491 |
+
ap.add_argument("--warmup", type=int, default=500)
|
| 492 |
+
ap.add_argument("--d-pos", type=int, default=96)
|
| 493 |
+
ap.add_argument("--d", type=int, default=256)
|
| 494 |
+
ap.add_argument("--layers", type=int, default=6)
|
| 495 |
+
ap.add_argument("--heads", type=int, default=8)
|
| 496 |
+
ap.add_argument("--workers", type=int, default=6)
|
| 497 |
+
ap.add_argument("--eval-every", type=int, default=500)
|
| 498 |
+
ap.add_argument("--tune-crops", type=int, default=256)
|
| 499 |
+
ap.add_argument("--patience", type=int, default=3000)
|
| 500 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 501 |
+
ap.add_argument("--resume", action="store_true")
|
| 502 |
+
ap.add_argument("--hidden", action="store_true")
|
| 503 |
+
a = ap.parse_args(argv)
|
| 504 |
+
if a.selftest:
|
| 505 |
+
selftest()
|
| 506 |
+
elif a.cmd == "train":
|
| 507 |
+
train(a)
|
| 508 |
+
elif a.cmd == "export":
|
| 509 |
+
export(a)
|
| 510 |
+
elif a.cmd == "prep":
|
| 511 |
+
for p in sorted(a.data):
|
| 512 |
+
t0 = time.time()
|
| 513 |
+
prep_shard(p)
|
| 514 |
+
print(f"{Path(p).name}: cache ready ({time.time() - t0:.0f} s)", flush=True)
|
| 515 |
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""v11 stage 2: data for the position map R (reports/v11 階段 2 預先登記:位置圖 R.md, sections 1-2).
|
| 2 |
+
|
| 3 |
+
One *group* is one song record (beatmapset + audio) and one timing (charts of a mapset share their red lines in all but
|
| 4 |
+
10 of 5,268 multi-chart mapsets; charts with other red lines form their own group). A group holds
|
| 5 |
+
|
| 6 |
+
beat table every global beat b of the timing that has a candidate position inside the audio: its start time (ms),
|
| 7 |
+
beat length (ms), section, beat-in-measure, and a 24-bit mask of valid positions (time inside the audio
|
| 8 |
+
and before the next red line minus 1 ms; positions of a beat cut by a red line after it are invalid)
|
| 9 |
+
per tier a list of charts, each as two 24-bit masks per beat: target (hit notes, types 0-3, on the 24 positions;
|
| 10 |
+
chart['beat'] * 48 rounded, which equals the time-derived grid exactly) and loss (valid, not strictly
|
| 11 |
+
inside a roll / balloon body, and the beat has no hit note off the 24 positions)
|
| 12 |
+
|
| 13 |
+
Roles (by song key = song_key or str(beatmapset_id)): test songs are never loaded; val; train songs are split into the
|
| 14 |
+
tuning set (sha1('tune:' + key) % 10 == 0) and halves A / B (sha1('fold:' + key) % 2). Era band of a group = the latest
|
| 15 |
+
chart year in it: <= 2013, 2014-2016, 2017-2021, 2022+.
|
| 16 |
+
|
| 17 |
+
python -m chartgen.v11.rmap_data --selftest
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import hashlib
|
| 24 |
+
import math
|
| 25 |
+
from dataclasses import dataclass, field
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
from chartgen.dataset import measure_at, measure_span, roll_end_beats
|
| 30 |
+
from chartgen.train import song_split
|
| 31 |
+
from chartgen.v11.patterns import GRID, N_POS, POS_BIT, POSITIONS
|
| 32 |
+
|
| 33 |
+
POS = np.asarray(POSITIONS, np.int64) # [24] positions in 1/48 beat
|
| 34 |
+
N_TIERS = 5
|
| 35 |
+
ERA_EDGES = (2014, 2017, 2022)
|
| 36 |
+
N_ERA = len(ERA_EDGES) + 1
|
| 37 |
+
MAX_BIB = 15 # beat-in-measure index is clipped here
|
| 38 |
+
ALL24 = np.uint32((1 << N_POS) - 1)
|
| 39 |
+
# position classes (dataset.subdiv_class order): 0 beat, 1 1/2, 2 1/3, 3 1/4, 4 1/6, 5 1/8, 6 1/12, 7 1/16
|
| 40 |
+
POS_CLASS = np.array([[1, 2, 3, 4, 6, 8, 12, 16].index(GRID // math.gcd(int(k), GRID)) if k else 0 for k in POS])
|
| 41 |
+
FAMILIES = {"beat": (0,), "1/2": (1,), "1/4": (3,), "triplet": (2, 4, 6), "eighth": (5, 7)}
|
| 42 |
+
FAMILY_OF_CLASS = {c: f for f, cs in FAMILIES.items() for c in cs}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def song_key(song: dict) -> str:
|
| 46 |
+
return song.get("song_key") or str(song["beatmapset_id"])
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _h(salt: str, key: str) -> int:
|
| 50 |
+
return int(hashlib.sha1(f"{salt}:{key}".encode()).hexdigest(), 16)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def role(key: str) -> str | None:
|
| 54 |
+
"""'val', 'tune', 'A', 'B', or None for test songs."""
|
| 55 |
+
sp = song_split(key)
|
| 56 |
+
if sp == "test":
|
| 57 |
+
return None
|
| 58 |
+
if sp == "val":
|
| 59 |
+
return "val"
|
| 60 |
+
if _h("tune", key) % 10 == 0:
|
| 61 |
+
return "tune"
|
| 62 |
+
return "A" if _h("fold", key) % 2 == 0 else "B"
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def era_band(year) -> int:
|
| 66 |
+
return int(np.searchsorted(ERA_EDGES, int(year or 0), side="right"))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def bits_to_bool(m: np.ndarray) -> np.ndarray:
|
| 70 |
+
"""[n] uint32 masks -> [n, 24] bool."""
|
| 71 |
+
return ((np.asarray(m, np.uint32)[:, None] >> np.arange(N_POS, dtype=np.uint32)[None]) & 1).astype(bool)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def bool_to_bits(b: np.ndarray) -> np.ndarray:
|
| 75 |
+
return (np.asarray(b, np.uint32) << np.arange(N_POS, dtype=np.uint32)[None]).sum(1).astype(np.uint32)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# ------------------------------------------------------------------------------------------------ beat table
|
| 79 |
+
|
| 80 |
+
@dataclass
|
| 81 |
+
class BeatTable:
|
| 82 |
+
beat: np.ndarray # [n] int64 global beat numbers (sorted, unique)
|
| 83 |
+
t0: np.ndarray # [n] float64 ms of the beat start
|
| 84 |
+
bl: np.ndarray # [n] float32 beat length (ms)
|
| 85 |
+
sec: np.ndarray # [n] int16 section index
|
| 86 |
+
bib: np.ndarray # [n] uint8 beat index inside its measure (clipped at MAX_BIB)
|
| 87 |
+
valid: np.ndarray # [n] uint32 24-bit mask of valid positions
|
| 88 |
+
|
| 89 |
+
def __len__(self):
|
| 90 |
+
return len(self.beat)
|
| 91 |
+
|
| 92 |
+
def pos_ms(self) -> np.ndarray:
|
| 93 |
+
"""[n, 24] ms of every candidate position."""
|
| 94 |
+
return self.t0[:, None] + self.bl[:, None].astype(np.float64) * POS[None] / GRID
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def beat_table(sections, n_frames: int) -> BeatTable:
|
| 98 |
+
s = np.asarray(sections, np.float64)
|
| 99 |
+
end = n_frames * 10.0
|
| 100 |
+
B, T0, BL, SEC, NXT = [], [], [], [], []
|
| 101 |
+
for j in range(len(s)):
|
| 102 |
+
t0, bl, sb = s[j, 0], s[j, 1], s[j, 3]
|
| 103 |
+
if not bl > 0:
|
| 104 |
+
continue
|
| 105 |
+
nxt_t = s[j + 1, 0] if j + 1 < len(s) else math.inf
|
| 106 |
+
lo = math.floor(sb + (0.0 - t0) / bl) if j == 0 else int(round(sb))
|
| 107 |
+
lo = max(lo, int(round(sb))) if t0 < 0 and j == 0 else lo
|
| 108 |
+
hi = int(round(s[j + 1, 3])) if j + 1 < len(s) else math.ceil(sb + (end - t0) / bl)
|
| 109 |
+
if hi <= lo:
|
| 110 |
+
continue
|
| 111 |
+
b = np.arange(lo, hi, dtype=np.int64)
|
| 112 |
+
tb = t0 + (b - sb) * bl
|
| 113 |
+
keep = (tb < min(end, nxt_t)) & (tb + bl > 0)
|
| 114 |
+
B.append(b[keep]); T0.append(tb[keep]); BL.append(np.full(keep.sum(), bl)); SEC.append(np.full(keep.sum(), j))
|
| 115 |
+
NXT.append(np.full(keep.sum(), nxt_t))
|
| 116 |
+
if not B:
|
| 117 |
+
z = np.zeros(0)
|
| 118 |
+
return BeatTable(z.astype(np.int64), z, z.astype(np.float32), z.astype(np.int16), z.astype(np.uint8),
|
| 119 |
+
z.astype(np.uint32))
|
| 120 |
+
b, t0, bl, sec, nxt = (np.concatenate(x) for x in (B, T0, BL, SEC, NXT))
|
| 121 |
+
o = np.argsort(b, kind="stable")
|
| 122 |
+
b, t0, bl, sec, nxt = b[o], t0[o], bl[o], sec[o], nxt[o]
|
| 123 |
+
keep = np.r_[True, np.diff(b) > 0] # duplicate beat numbers cannot occur by construction; be safe
|
| 124 |
+
b, t0, bl, sec, nxt = b[keep], t0[keep], bl[keep], sec[keep], nxt[keep]
|
| 125 |
+
pt = t0[:, None] + bl[:, None] * POS[None] / GRID
|
| 126 |
+
ok = (pt >= 0) & (pt < end) & (pt < nxt[:, None] - 1.0)
|
| 127 |
+
m = measure_at(s, b.astype(np.float64))
|
| 128 |
+
start, _ = measure_span(s, m)
|
| 129 |
+
bib = np.clip(np.round(b - start), 0, MAX_BIB).astype(np.uint8)
|
| 130 |
+
return BeatTable(b, t0, bl.astype(np.float32), sec.astype(np.int16), bib, bool_to_bits(ok))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
# ------------------------------------------------------------------------------------------------ chart targets
|
| 134 |
+
|
| 135 |
+
def chart_masks(chart: dict, table: BeatTable) -> tuple[np.ndarray, np.ndarray]:
|
| 136 |
+
"""(target, loss) 24-bit masks per beat of the table for one chart on the table's timing."""
|
| 137 |
+
n = len(table)
|
| 138 |
+
tgt = np.zeros(n, np.uint32)
|
| 139 |
+
loss = table.valid.copy()
|
| 140 |
+
if n == 0:
|
| 141 |
+
return tgt, loss
|
| 142 |
+
beat = np.asarray(chart["beat"], np.float64)
|
| 143 |
+
typ = np.asarray(chart["type"])
|
| 144 |
+
hit = typ <= 3
|
| 145 |
+
g = np.round(beat[hit] * GRID).astype(np.int64)
|
| 146 |
+
bb, kk = np.floor_divide(g, GRID), np.mod(g, GRID)
|
| 147 |
+
row = np.searchsorted(table.beat, bb)
|
| 148 |
+
ok = (row < n) & (table.beat[np.minimum(row, n - 1)] == bb)
|
| 149 |
+
bit = POS_BIT[kk]
|
| 150 |
+
on = ok & (bit >= 0)
|
| 151 |
+
np.bitwise_or.at(tgt, row[on], (np.uint32(1) << bit[on].astype(np.uint32)).astype(np.uint32))
|
| 152 |
+
off = ok & (bit < 0)
|
| 153 |
+
loss[row[off]] = 0
|
| 154 |
+
roll = typ >= 4
|
| 155 |
+
if roll.any():
|
| 156 |
+
sb = beat[roll]
|
| 157 |
+
eb = roll_end_beats(np.asarray(chart["sections"], np.float64), sb,
|
| 158 |
+
np.asarray(chart["length_beats"], np.float64)[roll])
|
| 159 |
+
for a, e in zip(sb, eb):
|
| 160 |
+
if e - a <= 1e-6:
|
| 161 |
+
continue
|
| 162 |
+
r0 = np.searchsorted(table.beat, math.floor(a))
|
| 163 |
+
r1 = np.searchsorted(table.beat, math.ceil(e), side="right")
|
| 164 |
+
if r1 <= r0:
|
| 165 |
+
continue
|
| 166 |
+
pv = table.beat[r0:r1, None] + POS[None] / GRID
|
| 167 |
+
inside = (pv > a + 1e-6) & (pv < e - 1e-6)
|
| 168 |
+
loss[r0:r1] &= ~bool_to_bits(inside)
|
| 169 |
+
tgt &= table.valid
|
| 170 |
+
return tgt, loss
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
# ------------------------------------------------------------------------------------------------ groups
|
| 174 |
+
|
| 175 |
+
@dataclass
|
| 176 |
+
class Group:
|
| 177 |
+
set_id: int
|
| 178 |
+
key: str
|
| 179 |
+
role: str
|
| 180 |
+
era: int
|
| 181 |
+
table: BeatTable
|
| 182 |
+
sections: np.ndarray
|
| 183 |
+
charts: dict = field(default_factory=dict) # tier -> list of (beatmap_id, year, target, loss)
|
| 184 |
+
song_index: int = -1 # index of the song record in the loaded list
|
| 185 |
+
|
| 186 |
+
@property
|
| 187 |
+
def uid(self) -> str:
|
| 188 |
+
"""Stable id of the group: set id and a hash of its red lines."""
|
| 189 |
+
h = hashlib.sha1(np.round(np.asarray(self.sections, np.float64)[:, :4], 3).tobytes()).hexdigest()[:8]
|
| 190 |
+
return f"s{self.set_id}_{h}"
|
| 191 |
+
|
| 192 |
+
def n_examples(self) -> int:
|
| 193 |
+
return max((len(v) for v in self.charts.values()), default=0)
|
| 194 |
+
|
| 195 |
+
def example(self, i: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 196 |
+
"""(target [n, 5] uint32, loss [n, 5] uint32, tier present [5] bool): chart i % k of every tier."""
|
| 197 |
+
n = len(self.table)
|
| 198 |
+
tgt = np.zeros((n, N_TIERS), np.uint32)
|
| 199 |
+
los = np.zeros((n, N_TIERS), np.uint32)
|
| 200 |
+
has = np.zeros(N_TIERS, bool)
|
| 201 |
+
for t, lst in self.charts.items():
|
| 202 |
+
_, _, a, b = lst[i % len(lst)]
|
| 203 |
+
tgt[:, t], los[:, t], has[t] = a, b, True
|
| 204 |
+
return tgt, los, has
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def song_groups(song: dict, song_index: int = -1, tiers=range(N_TIERS)) -> list[Group]:
|
| 208 |
+
key = song_key(song)
|
| 209 |
+
r = role(key)
|
| 210 |
+
if r is None:
|
| 211 |
+
return []
|
| 212 |
+
n_frames = len(song["mel"])
|
| 213 |
+
by_timing: dict[bytes, list] = {}
|
| 214 |
+
for c in song["charts"]:
|
| 215 |
+
if int(c["tier"]) not in tiers or len(c["time"]) == 0:
|
| 216 |
+
continue
|
| 217 |
+
s = np.asarray(c["sections"], np.float64)
|
| 218 |
+
by_timing.setdefault(np.round(s[:, :4], 3).tobytes(), []).append(c)
|
| 219 |
+
out = []
|
| 220 |
+
for cs in by_timing.values():
|
| 221 |
+
s = np.asarray(cs[0]["sections"], np.float64)
|
| 222 |
+
table = beat_table(s, n_frames)
|
| 223 |
+
if len(table) < 8:
|
| 224 |
+
continue
|
| 225 |
+
g = Group(int(song["beatmapset_id"]), key, r, era_band(max(int(c.get("year") or 0) for c in cs)), table, s,
|
| 226 |
+
song_index=song_index)
|
| 227 |
+
for c in sorted(cs, key=lambda c: int(c["beatmap_id"])):
|
| 228 |
+
tgt, los = chart_masks(c, table)
|
| 229 |
+
g.charts.setdefault(int(c["tier"]), []).append((int(c["beatmap_id"]), int(c.get("year") or 0), tgt, los))
|
| 230 |
+
out.append(g)
|
| 231 |
+
return out
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
# ------------------------------------------------------------------------------------------------ self-test
|
| 235 |
+
|
| 236 |
+
def selftest(shard: str | None = None):
|
| 237 |
+
from chartgen.dataset import load_songs
|
| 238 |
+
from chartgen.rhythm_eval2 import grid_of
|
| 239 |
+
path = shard or "data/pilot/features/taiko-00000.pkl"
|
| 240 |
+
songs = load_songs([path], mmap=True)
|
| 241 |
+
n_g = n_ch = 0
|
| 242 |
+
n_hit = n_cov = n_valid_miss = 0
|
| 243 |
+
roles = {}
|
| 244 |
+
for i, s in enumerate(songs):
|
| 245 |
+
for g in song_groups(s, i):
|
| 246 |
+
roles[g.role] = roles.get(g.role, 0) + 1
|
| 247 |
+
n_g += 1
|
| 248 |
+
for t, lst in g.charts.items():
|
| 249 |
+
for bid, _, tgt, los in lst:
|
| 250 |
+
n_ch += 1
|
| 251 |
+
c = next(c for c in s["charts"] if int(c["beatmap_id"]) == bid)
|
| 252 |
+
grid = grid_of(c, c["sections"])
|
| 253 |
+
ok = np.isin(np.mod(grid, GRID), POS)
|
| 254 |
+
n_hit += len(grid)
|
| 255 |
+
rec = []
|
| 256 |
+
tb = bits_to_bool(tgt)
|
| 257 |
+
rows, cols = np.nonzero(tb)
|
| 258 |
+
rec = np.sort(g.table.beat[rows] * GRID + POS[cols])
|
| 259 |
+
# every on-grid hit inside a valid position is a target, and nothing else
|
| 260 |
+
want = np.sort(grid[ok])
|
| 261 |
+
inside = np.isin(want, rec)
|
| 262 |
+
n_cov += inside.sum()
|
| 263 |
+
n_valid_miss += (~inside).sum()
|
| 264 |
+
assert np.isin(rec, want).all(), (bid, "target not in chart")
|
| 265 |
+
assert (tgt & ~g.table.valid).sum() == 0
|
| 266 |
+
print(f"songs {len(songs)}, groups {n_g} {roles}, charts {n_ch}; hit notes {n_hit}, as targets {n_cov}, "
|
| 267 |
+
f"not targets (off-grid or outside valid positions) {n_hit - n_cov}")
|
| 268 |
+
# cut-beat test: a red line at 2.5 beats of a 500 ms section
|
| 269 |
+
sec = np.array([[0.0, 500.0, 4, 0, 0], [1250.0, 400.0, 4, 3, 0]])
|
| 270 |
+
tb = beat_table(sec, 600)
|
| 271 |
+
v = bits_to_bool(tb.valid)
|
| 272 |
+
assert list(tb.beat[:5]) == [0, 1, 2, 3, 4], tb.beat[:5]
|
| 273 |
+
k_ok = POS[v[2]]
|
| 274 |
+
assert k_ok.max() < 24 and k_ok.min() == 0, k_ok # beat 2 valid only before 2.5 (1250 ms)
|
| 275 |
+
assert v[3].all() and np.isclose(tb.t0[3], 1250.0)
|
| 276 |
+
print("cut-beat test ok; positions valid in beat 2:", k_ok.tolist())
|
| 277 |
+
print("selftest ok")
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def main(argv=None):
|
| 281 |
+
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 282 |
+
ap.add_argument("--selftest", action="store_true")
|
| 283 |
+
ap.add_argument("--shard")
|
| 284 |
+
a = ap.parse_args(argv)
|
| 285 |
+
if a.selftest:
|
| 286 |
+
selftest(a.shard)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
if __name__ == "__main__":
|
| 290 |
+
main()
|
chartgen/v11/rmap_eval.py
ADDED
|
@@ -0,0 +1,735 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""v11 stage 2 evaluation of the position map R (reports/v11 階段 2 預先登記:位置圖 R.md, sections 2-6).
|
| 2 |
+
|
| 3 |
+
Maps are npz files of rmap.export / rmap_base (per group uid: logits [n_beats, 24, 5] float16). Targets and loss masks
|
| 4 |
+
come from the shard caches (rmap.prep_shard) through rmap.Corpus. Only Oni (3) and Inner Oni (4) are judged.
|
| 5 |
+
|
| 6 |
+
calib temperature T and offset b per (tier, family), fitted on the tuning set: logit' = logit / T + b; offset
|
| 7 |
+
fixed at 0 for families with positives in fewer than 100 tuning songs
|
| 8 |
+
position S2.1 (log-loss of calibrated R vs the calibrated simple baseline, paired song bootstrap) and S2.2 (count
|
| 9 |
+
ratio and calibration slope) on val, judged cells = (tier, family) with positives in >= 100 val songs;
|
| 10 |
+
AUC and the 2022+ subset reported
|
| 11 |
+
|
| 12 |
+
Bootstrap: songs (song key) resampled 1000x with seed 0 from one rng per population; weights shared by all maps.
|
| 13 |
+
|
| 14 |
+
python -m chartgen.v11.rmap_eval calib --data f*.pkl --maps tune_R.npz --out calib_R.json
|
| 15 |
+
python -m chartgen.v11.rmap_eval position --data f*.pkl --maps val_R.npz --calib calib_R.json \
|
| 16 |
+
--simple val_simple.npz --simple-calib calib_simple.json --prior val_prior.npz --out position.json
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import argparse
|
| 22 |
+
import json
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
import torch
|
| 27 |
+
|
| 28 |
+
from chartgen.v11.rmap import Corpus
|
| 29 |
+
from chartgen.v11.rmap_data import POS_CLASS, bits_to_bool
|
| 30 |
+
|
| 31 |
+
TIERS = (3, 4)
|
| 32 |
+
TNAME = {3: "Oni", 4: "Inner Oni"}
|
| 33 |
+
FAMS = ("beat", "1/2", "1/4", "triplet", "eighth")
|
| 34 |
+
FAM_CLASSES = {"beat": (0,), "1/2": (1,), "1/4": (3,), "triplet": (2, 4, 6), "eighth": (5, 7)}
|
| 35 |
+
FAM_POS = {f: np.isin(POS_CLASS, c) for f, c in FAM_CLASSES.items()}
|
| 36 |
+
N_BOOT, SEED = 1000, 0
|
| 37 |
+
MIN_SONGS = 100
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class Maps:
|
| 41 |
+
def __init__(self, path):
|
| 42 |
+
self.z = np.load(path)
|
| 43 |
+
self.index = {r["uid"]: r for r in json.loads(str(self.z["index"]))}
|
| 44 |
+
|
| 45 |
+
def __contains__(self, uid):
|
| 46 |
+
return uid in self.index
|
| 47 |
+
|
| 48 |
+
def __getitem__(self, uid) -> np.ndarray:
|
| 49 |
+
return self.z[uid].astype(np.float32)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def apply_calib(lg: np.ndarray, calib: dict | None) -> np.ndarray:
|
| 53 |
+
"""Calibrated logits of tiers 3-4 (other tiers untouched)."""
|
| 54 |
+
if not calib:
|
| 55 |
+
return lg
|
| 56 |
+
out = lg.copy()
|
| 57 |
+
for t in TIERS:
|
| 58 |
+
for f in FAMS:
|
| 59 |
+
T, b = calib[str(t)][f]
|
| 60 |
+
out[:, FAM_POS[f], t] = lg[:, FAM_POS[f], t] / T + b
|
| 61 |
+
return out
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def rows(corpus: Corpus, maps_list, calibs, tier: int, fam: str, roles=None, era=None):
|
| 65 |
+
"""Positions of one (tier, family): y, logits of each map [m, N], song keys, era of the group."""
|
| 66 |
+
Y, Z, K, E = [], [[] for _ in maps_list], [], []
|
| 67 |
+
sel_pos = FAM_POS[fam]
|
| 68 |
+
for g in corpus.groups:
|
| 69 |
+
if tier not in g.charts or (roles and g.role not in roles) or (era is not None and g.era != era):
|
| 70 |
+
continue
|
| 71 |
+
if not all(g.uid in m for m in maps_list):
|
| 72 |
+
continue
|
| 73 |
+
lgs = [apply_calib(m[g.uid], c)[:, sel_pos, tier] for m, c in zip(maps_list, calibs)]
|
| 74 |
+
for _, _, tgt, los in g.charts[tier]:
|
| 75 |
+
L = bits_to_bool(los)[:, sel_pos]
|
| 76 |
+
T = bits_to_bool(tgt)[:, sel_pos]
|
| 77 |
+
Y.append(T[L])
|
| 78 |
+
for i, lg in enumerate(lgs):
|
| 79 |
+
Z[i].append(lg[L])
|
| 80 |
+
K += [g.key] * int(L.sum())
|
| 81 |
+
E += [g.era] * int(L.sum())
|
| 82 |
+
if not Y:
|
| 83 |
+
return None
|
| 84 |
+
return (np.concatenate(Y).astype(np.float32), [np.concatenate(z) for z in Z], np.array(K), np.array(E))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def fit_tb(z, y, temp_only: bool):
|
| 88 |
+
zt, yt = torch.tensor(z, dtype=torch.float64), torch.tensor(y, dtype=torch.float64)
|
| 89 |
+
logT = torch.zeros(1, dtype=torch.float64, requires_grad=True)
|
| 90 |
+
b = torch.zeros(1, dtype=torch.float64, requires_grad=not temp_only)
|
| 91 |
+
params = [logT] + ([] if temp_only else [b])
|
| 92 |
+
opt = torch.optim.LBFGS(params, lr=1.0, max_iter=100, line_search_fn="strong_wolfe")
|
| 93 |
+
|
| 94 |
+
def closure():
|
| 95 |
+
opt.zero_grad()
|
| 96 |
+
loss = torch.nn.functional.binary_cross_entropy_with_logits(zt / torch.exp(logT) + b, yt)
|
| 97 |
+
loss.backward()
|
| 98 |
+
return loss
|
| 99 |
+
opt.step(closure)
|
| 100 |
+
return float(torch.exp(logT)), float(b)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def calib(a):
|
| 104 |
+
c = Corpus(a.data, {"tune"}, tiers=TIERS, log=lambda m: None)
|
| 105 |
+
m = Maps(a.maps)
|
| 106 |
+
out, info = {}, {}
|
| 107 |
+
for t in TIERS:
|
| 108 |
+
out[str(t)] = {}
|
| 109 |
+
for f in FAMS:
|
| 110 |
+
r = rows(c, [m], [None], t, f)
|
| 111 |
+
y, (z,), keys, _ = r
|
| 112 |
+
n_pos_songs = len(np.unique(keys[y > 0]))
|
| 113 |
+
T, b = fit_tb(z, y, temp_only=n_pos_songs < MIN_SONGS)
|
| 114 |
+
out[str(t)][f] = [T, b]
|
| 115 |
+
info[f"{t}|{f}"] = {"positions": int(len(y)), "positives": int(y.sum()), "songs_with_positives": int(n_pos_songs),
|
| 116 |
+
"temperature": T, "offset": b, "offset_fitted": n_pos_songs >= MIN_SONGS}
|
| 117 |
+
print(t, f, info[f"{t}|{f}"], flush=True)
|
| 118 |
+
Path(a.out).write_text(json.dumps({"calib": out, "info": info}, indent=1))
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def load_calib(path):
|
| 122 |
+
return json.loads(Path(path).read_text())["calib"] if path else None
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# ------------------------------------------------------------------------------------------------ statistics
|
| 126 |
+
|
| 127 |
+
def song_weights(keys_unique, seed=SEED):
|
| 128 |
+
rng = np.random.default_rng(seed)
|
| 129 |
+
n = len(keys_unique)
|
| 130 |
+
return rng.multinomial(n, np.full(n, 1.0 / n), size=N_BOOT).astype(np.float64)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def per_song(keys, *vals):
|
| 134 |
+
u, inv = np.unique(keys, return_inverse=True)
|
| 135 |
+
return u, [np.bincount(inv, weights=v, minlength=len(u)) for v in vals]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def ci(boot):
|
| 139 |
+
b = np.asarray(boot, float)
|
| 140 |
+
b = b[np.isfinite(b)]
|
| 141 |
+
return [float(np.percentile(b, 2.5)), float(np.percentile(b, 97.5))] if len(b) > 10 else [None, None]
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def auc(y, s):
|
| 145 |
+
y = np.asarray(y, bool)
|
| 146 |
+
n1, n0 = int(y.sum()), int((~y).sum())
|
| 147 |
+
if n1 == 0 or n0 == 0:
|
| 148 |
+
return float("nan")
|
| 149 |
+
o = np.argsort(s, kind="mergesort")
|
| 150 |
+
ss = s[o]
|
| 151 |
+
r = np.empty(len(s), np.float64)
|
| 152 |
+
# average ranks over ties
|
| 153 |
+
_, first, cnt = np.unique(ss, return_index=True, return_counts=True)
|
| 154 |
+
avg = first + (cnt - 1) / 2.0 + 1
|
| 155 |
+
r[o] = np.repeat(avg, cnt)
|
| 156 |
+
return float((r[y].sum() - n1 * (n1 + 1) / 2) / (n1 * n0))
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def logloss_terms(z, y):
|
| 160 |
+
return np.logaddexp(0, z) - y * z
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def calib_slope(z, y):
|
| 164 |
+
zt, yt = torch.tensor(z, dtype=torch.float64), torch.tensor(y, dtype=torch.float64)
|
| 165 |
+
w = torch.tensor([1.0, 0.0], dtype=torch.float64, requires_grad=True)
|
| 166 |
+
opt = torch.optim.LBFGS([w], lr=1.0, max_iter=100, line_search_fn="strong_wolfe")
|
| 167 |
+
|
| 168 |
+
def closure():
|
| 169 |
+
opt.zero_grad()
|
| 170 |
+
loss = torch.nn.functional.binary_cross_entropy_with_logits(w[0] * zt + w[1], yt)
|
| 171 |
+
loss.backward()
|
| 172 |
+
return loss
|
| 173 |
+
opt.step(closure)
|
| 174 |
+
return float(w[0])
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def position(a):
|
| 178 |
+
c = Corpus(a.data, {"val"}, tiers=TIERS, log=lambda m: None)
|
| 179 |
+
R, S, P = Maps(a.maps), Maps(a.simple), Maps(a.prior)
|
| 180 |
+
cR, cS = load_calib(a.calib), load_calib(a.simple_calib)
|
| 181 |
+
res = {"pre_registration": "reports/v11 階段 2 預先登記:位置圖 R.md", "n_boot": N_BOOT, "seed": SEED, "cells": {}}
|
| 182 |
+
for t in TIERS:
|
| 183 |
+
for f in FAMS:
|
| 184 |
+
for subset, era in (("all", None), ("2022+", 3)):
|
| 185 |
+
r = rows(c, [R, S, P], [cR, cS, None], t, f, era=era)
|
| 186 |
+
if r is None:
|
| 187 |
+
continue
|
| 188 |
+
y, (zR, zS, zP), keys, _ = r
|
| 189 |
+
u, (n, ys, pR, lR, lS, lP) = per_song(keys, np.ones_like(y), y, 1 / (1 + np.exp(-zR)),
|
| 190 |
+
logloss_terms(zR, y), logloss_terms(zS, y), logloss_terms(zP, y))
|
| 191 |
+
W = song_weights(u)
|
| 192 |
+
n_pos_songs = int((ys > 0).sum())
|
| 193 |
+
d = (lR.sum() - lS.sum()) / n.sum()
|
| 194 |
+
dB = (W @ lR - W @ lS) / (W @ n)
|
| 195 |
+
ratio = pR.sum() / max(ys.sum(), 1e-9)
|
| 196 |
+
ratioB = (W @ pR) / np.maximum(W @ ys, 1e-9)
|
| 197 |
+
slope = calib_slope(zR, y)
|
| 198 |
+
blk = {"songs": int(len(u)), "songs_with_positives": n_pos_songs, "positions": int(len(y)),
|
| 199 |
+
"positives": int(y.sum()), "judged": subset == "all" and n_pos_songs >= MIN_SONGS,
|
| 200 |
+
"logloss": {"R": float(lR.sum() / n.sum()), "simple": float(lS.sum() / n.sum()),
|
| 201 |
+
"prior": float(lP.sum() / n.sum())},
|
| 202 |
+
"R_minus_simple": [float(d), *ci(dB)],
|
| 203 |
+
"auc": {"R": auc(y, zR), "simple": auc(y, zS), "prior": auc(y, zP)},
|
| 204 |
+
"count_ratio": [float(ratio), *ci(ratioB)], "calibration_slope": slope}
|
| 205 |
+
if blk["judged"]:
|
| 206 |
+
lo, hi = blk["R_minus_simple"][1:]
|
| 207 |
+
blk["S2.1"] = bool(d < 0 and hi is not None and hi < 0)
|
| 208 |
+
rl, rh = blk["count_ratio"][1:]
|
| 209 |
+
blk["S2.2"] = bool(0.8 <= ratio <= 1.25 and rl is not None and rl <= 1 <= rh and 0.8 <= slope <= 1.2)
|
| 210 |
+
res["cells"][f"{TNAME[t]}|{f}|{subset}"] = blk
|
| 211 |
+
print(TNAME[t], f, subset, {k: blk[k] for k in ("songs_with_positives", "R_minus_simple", "count_ratio",
|
| 212 |
+
"calibration_slope")}, blk.get("S2.1"), blk.get("S2.2"), flush=True)
|
| 213 |
+
judged = [v for v in res["cells"].values() if v["judged"]]
|
| 214 |
+
res["S2.1"] = bool(judged) and all(v["S2.1"] for v in judged)
|
| 215 |
+
res["S2.2"] = bool(judged) and all(v["S2.2"] for v in judged)
|
| 216 |
+
Path(a.out).write_text(json.dumps(res, indent=1))
|
| 217 |
+
print("S2.1", res["S2.1"], "S2.2", res["S2.2"])
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
# ------------------------------------------------------------------------------------------------ bars (S2.3)
|
| 221 |
+
|
| 222 |
+
BAR_LABELS = {"1/6": np.isin(POS_CLASS, [4]), "triplet": np.isin(POS_CLASS, [2, 4, 6]), "eighth": np.isin(POS_CLASS, [5, 7])}
|
| 223 |
+
JUDGED_BAR = ("1/6", "triplet")
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def complete_bars(g, n_frames):
|
| 227 |
+
"""Bars helper of the group (rows 0..383 from the measure at 0 ms) and a mask of complete bars: length equal to
|
| 228 |
+
the meter and every beat of the bar in the table with all positions valid."""
|
| 229 |
+
from chartgen.dataset import measure_span
|
| 230 |
+
from chartgen.v11.rmap_pseudo import Bars
|
| 231 |
+
bars = Bars.for_song(g.sections, g.table.beat, n_frames)
|
| 232 |
+
s = np.asarray(g.sections, np.float64)
|
| 233 |
+
st, en = measure_span(s, np.arange(bars.n) + bars.b0)
|
| 234 |
+
j = np.clip(np.searchsorted(s[:, 3], st + 1e-9, side="right") - 1, 0, len(s) - 1)
|
| 235 |
+
meter = np.where(s[j, 2] > 0, s[j, 2], 4)
|
| 236 |
+
ok = np.isclose(en - st, meter)
|
| 237 |
+
full_valid = bits_to_bool(g.table.valid).all(1)
|
| 238 |
+
cnt = np.bincount(bars.row[bars.ok], minlength=bars.n)
|
| 239 |
+
good = np.bincount(bars.row[bars.ok], weights=full_valid[bars.ok].astype(float), minlength=bars.n)
|
| 240 |
+
ok &= (cnt == meter) & (good == cnt)
|
| 241 |
+
return bars, ok
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def bar_scores(lg_tier: np.ndarray, valid: np.ndarray, bars, sel: np.ndarray) -> np.ndarray:
|
| 245 |
+
"""1 - prod(1 - p) over the bar's positions of a class set; returned as log-odds-free score in [0, 1]."""
|
| 246 |
+
p = 1 / (1 + np.exp(-lg_tier))
|
| 247 |
+
l1 = np.where(valid & sel[None], np.log1p(-np.clip(p, 0, 1 - 1e-7)), 0.0).sum(1)
|
| 248 |
+
tot = np.zeros(bars.n)
|
| 249 |
+
np.add.at(tot, bars.row[bars.ok], l1[bars.ok])
|
| 250 |
+
return 1 - np.exp(tot)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def song_mean_stat(keys, vals):
|
| 254 |
+
"""Per-chart values -> per song mean -> (song keys, values)."""
|
| 255 |
+
u, inv = np.unique(keys, return_inverse=True)
|
| 256 |
+
s = np.bincount(inv, weights=vals, minlength=len(u))
|
| 257 |
+
n = np.bincount(inv, minlength=len(u))
|
| 258 |
+
return u, s / n
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def paired_song_diff(u, a, b, W):
|
| 262 |
+
est = float(a.mean() - b.mean())
|
| 263 |
+
boot = (W @ a - W @ b) / W.sum(1)
|
| 264 |
+
return [est, *ci(boot)]
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def bars_eval(a):
|
| 268 |
+
import pickle
|
| 269 |
+
c = Corpus(a.data, {"val"}, tiers=TIERS, log=lambda m: None)
|
| 270 |
+
R, S = Maps(a.maps), Maps(a.simple)
|
| 271 |
+
cR, cS = load_calib(a.calib), load_calib(a.simple_calib)
|
| 272 |
+
sp9 = pickle.load(open(a.sp9, "rb")) # {(uid, tier): (b0, o [n, 17])}
|
| 273 |
+
res = {"cells": {}}
|
| 274 |
+
for t in TIERS:
|
| 275 |
+
per = {lab: {"keys": [], "R": [], "simple": [], "sp9": []} for lab in BAR_LABELS}
|
| 276 |
+
for g in c.groups:
|
| 277 |
+
if t not in g.charts or g.uid not in R or g.uid not in S or (g.uid, t) not in sp9:
|
| 278 |
+
continue
|
| 279 |
+
n_frames = len(c.songs[g.song_index]["mel"])
|
| 280 |
+
bars, ok = complete_bars(g, n_frames)
|
| 281 |
+
valid = bits_to_bool(g.table.valid)
|
| 282 |
+
lR = apply_calib(R[g.uid], cR)[:, :, t]
|
| 283 |
+
lS = apply_calib(S[g.uid], cS)[:, :, t]
|
| 284 |
+
b0, o = sp9[(g.uid, t)]
|
| 285 |
+
assert b0 == bars.b0, (g.uid, b0, bars.b0)
|
| 286 |
+
sig = 1 / (1 + np.exp(-o[:, :6]))
|
| 287 |
+
gl = o[:, 6:16]
|
| 288 |
+
gap = np.exp(gl - gl.max(1, keepdims=True))
|
| 289 |
+
gap /= gap.sum(1, keepdims=True)
|
| 290 |
+
sp = {"1/6": gap[:, 1], "triplet": sig[:, 4], "eighth": sig[:, 5]}
|
| 291 |
+
for _, _, tgt, _ in g.charts[t]:
|
| 292 |
+
T = bits_to_bool(tgt)
|
| 293 |
+
for lab, sel in BAR_LABELS.items():
|
| 294 |
+
has = np.zeros(bars.n, bool)
|
| 295 |
+
np.logical_or.at(has, bars.row[bars.ok], (T & sel[None]).any(1)[bars.ok])
|
| 296 |
+
nb = min(bars.n, len(sp[lab]))
|
| 297 |
+
m = ok[:nb]
|
| 298 |
+
y = has[:nb][m]
|
| 299 |
+
if y.all() or not y.any():
|
| 300 |
+
continue
|
| 301 |
+
per[lab]["keys"].append(g.key)
|
| 302 |
+
per[lab]["R"].append(auc(y, bar_scores(lR, valid, bars, sel)[:nb][m]))
|
| 303 |
+
per[lab]["simple"].append(auc(y, bar_scores(lS, valid, bars, sel)[:nb][m]))
|
| 304 |
+
per[lab]["sp9"].append(auc(y, sp[lab][:nb][m]))
|
| 305 |
+
for lab, d in per.items():
|
| 306 |
+
if not d["keys"]:
|
| 307 |
+
continue
|
| 308 |
+
keys = np.array(d["keys"])
|
| 309 |
+
u, vR = song_mean_stat(keys, np.array(d["R"]))
|
| 310 |
+
_, vS = song_mean_stat(keys, np.array(d["simple"]))
|
| 311 |
+
_, vP = song_mean_stat(keys, np.array(d["sp9"]))
|
| 312 |
+
W = song_weights(u)
|
| 313 |
+
best = "sp9" if vP.mean() >= vS.mean() else "simple"
|
| 314 |
+
diff = paired_song_diff(u, vR, vP if best == "sp9" else vS, W)
|
| 315 |
+
blk = {"charts": len(keys), "songs": len(u), "auc": {"R": float(vR.mean()), "simple": float(vS.mean()),
|
| 316 |
+
"sp9": float(vP.mean())},
|
| 317 |
+
"stronger_comparator": best, "R_minus_stronger": diff,
|
| 318 |
+
"R_minus_sp9": paired_song_diff(u, vR, vP, W), "R_minus_simple": paired_song_diff(u, vR, vS, W)}
|
| 319 |
+
if lab in JUDGED_BAR:
|
| 320 |
+
blk["holds"] = bool(diff[1] is not None and diff[1] > 0)
|
| 321 |
+
res["cells"][f"{TNAME[t]}|{lab}"] = blk
|
| 322 |
+
print(TNAME[t], lab, blk, flush=True)
|
| 323 |
+
res["S2.3"] = all(res["cells"].get(f"{TNAME[t]}|{lab}", {}).get("holds", False) for t in TIERS for lab in JUDGED_BAR)
|
| 324 |
+
Path(a.out).write_text(json.dumps(res, indent=1))
|
| 325 |
+
print("S2.3", res["S2.3"])
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
# ------------------------------------------------------------------------------------------------ slow-song 1/8 (S2.4)
|
| 329 |
+
|
| 330 |
+
EIGHTH_POS = POS_CLASS == 5
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def slow8_eval(a):
|
| 334 |
+
"""Val (full model maps) + train cross-fit (A model on B songs, B model on A songs)."""
|
| 335 |
+
from chartgen.rhythm_eval import main_bpm
|
| 336 |
+
c = Corpus(a.data, {"val", "A", "B"}, tiers=TIERS, log=lambda m: None)
|
| 337 |
+
Rv, Rtr = Maps(a.maps), [Maps(p) for p in a.maps_train]
|
| 338 |
+
Sv, Str = Maps(a.simple), [Maps(p) for p in a.simple_train]
|
| 339 |
+
Pv, Ptr = Maps(a.prior), [Maps(p) for p in a.prior_train]
|
| 340 |
+
|
| 341 |
+
def pick(uid, val_map, tr_maps):
|
| 342 |
+
if uid in val_map:
|
| 343 |
+
return val_map[uid]
|
| 344 |
+
for m in tr_maps:
|
| 345 |
+
if uid in m:
|
| 346 |
+
return m[uid]
|
| 347 |
+
return None
|
| 348 |
+
|
| 349 |
+
res = {"cells": {}}
|
| 350 |
+
for t in TIERS:
|
| 351 |
+
keys, vals = [], {"R": [], "simple": [], "prior": []}
|
| 352 |
+
for g in c.groups:
|
| 353 |
+
if t not in g.charts or main_bpm(g.sections) >= 110:
|
| 354 |
+
continue
|
| 355 |
+
lgs = {"R": pick(g.uid, Rv, Rtr), "simple": pick(g.uid, Sv, Str), "prior": pick(g.uid, Pv, Ptr)}
|
| 356 |
+
if any(v is None for v in lgs.values()):
|
| 357 |
+
continue
|
| 358 |
+
n_frames = len(c.songs[g.song_index]["mel"])
|
| 359 |
+
from chartgen.v11.rmap_pseudo import Bars
|
| 360 |
+
bars = Bars.for_song(g.sections, g.table.beat, n_frames)
|
| 361 |
+
valid = bits_to_bool(g.table.valid)
|
| 362 |
+
for _, _, tgt, _ in g.charts[t]:
|
| 363 |
+
T = bits_to_bool(tgt)
|
| 364 |
+
hit8 = np.zeros(bars.n, bool)
|
| 365 |
+
np.logical_or.at(hit8, bars.row[bars.ok], (T & EIGHTH_POS[None]).any(1)[bars.ok])
|
| 366 |
+
per_bar = {k: [] for k in vals}
|
| 367 |
+
for bi in np.where(hit8)[0]:
|
| 368 |
+
rows_b = np.where(bars.ok & (bars.row == bi))[0]
|
| 369 |
+
cand = valid[rows_b][:, EIGHTH_POS]
|
| 370 |
+
y = T[rows_b][:, EIGHTH_POS][cand]
|
| 371 |
+
if y.sum() < 1 or y.sum() > len(y) - 1:
|
| 372 |
+
continue
|
| 373 |
+
for k, lg in lgs.items():
|
| 374 |
+
per_bar[k].append(auc(y, lg[rows_b][:, EIGHTH_POS, t][cand]))
|
| 375 |
+
if per_bar["R"]:
|
| 376 |
+
keys.append(g.key)
|
| 377 |
+
for k in vals:
|
| 378 |
+
vals[k].append(float(np.mean(per_bar[k])))
|
| 379 |
+
if not keys:
|
| 380 |
+
continue
|
| 381 |
+
keys = np.array(keys)
|
| 382 |
+
u, vR = song_mean_stat(keys, np.array(vals["R"]))
|
| 383 |
+
_, vS = song_mean_stat(keys, np.array(vals["simple"]))
|
| 384 |
+
_, vP = song_mean_stat(keys, np.array(vals["prior"]))
|
| 385 |
+
W = song_weights(u)
|
| 386 |
+
best = "simple" if vS.mean() >= vP.mean() else "prior"
|
| 387 |
+
diff = paired_song_diff(u, vR, vS if best == "simple" else vP, W)
|
| 388 |
+
blk = {"charts": len(keys), "songs": len(u), "auc": {"R": float(vR.mean()), "simple": float(vS.mean()),
|
| 389 |
+
"prior": float(vP.mean())},
|
| 390 |
+
"stronger_comparator": best, "R_minus_stronger": diff, "holds": bool(diff[1] is not None and diff[1] > 0)}
|
| 391 |
+
res["cells"][TNAME[t]] = blk
|
| 392 |
+
print(TNAME[t], blk, flush=True)
|
| 393 |
+
res["S2.4"] = all(res["cells"].get(TNAME[t], {}).get("holds", False) for t in TIERS)
|
| 394 |
+
Path(a.out).write_text(json.dumps(res, indent=1))
|
| 395 |
+
print("S2.4", res["S2.4"])
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
# ------------------------------------------------------------------------------------------------ pseudo-chart readouts
|
| 399 |
+
|
| 400 |
+
def human_settings(song, chart):
|
| 401 |
+
from chartgen.latent_stats import chart_settings
|
| 402 |
+
from chartgen.song_planner import chart_rows
|
| 403 |
+
_, H, _ = chart_rows(np.zeros(((len(song["mel"]) + 1) // 2, 1), np.float32), chart)
|
| 404 |
+
return chart_settings(H)
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def chart_of(song, bid):
|
| 408 |
+
return next(ch for ch in song["charts"] if int(ch["beatmap_id"]) == int(bid))
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def pseudo_draws(sampler, lg_tier, valid, bid, k=16):
|
| 412 |
+
from chartgen.v11.rmap_pseudo import pseudo_seed
|
| 413 |
+
S0 = sampler.scores(lg_tier, valid)
|
| 414 |
+
G = np.stack([sampler.gumbel(np.random.default_rng(pseudo_seed(bid, i)), 1, len(lg_tier))[0] for i in range(k)])
|
| 415 |
+
return sampler.draw(S0, G) # [k, n] masks
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def song_level(a):
|
| 419 |
+
"""S2.5: triplet amount of R's pseudo-charts, line fitted on the tuning set, R2 on the ceiling's val charts."""
|
| 420 |
+
from chartgen.v11.rmap_pseudo import Bars, Sampler, fast_settings
|
| 421 |
+
smp = Sampler()
|
| 422 |
+
out = {}
|
| 423 |
+
for role, mp in (("tune", a.maps_tune), ("val", a.maps)):
|
| 424 |
+
c = Corpus(a.data, {role}, tiers=TIERS, log=lambda m: None)
|
| 425 |
+
M, cal = Maps(mp), load_calib(a.calib)
|
| 426 |
+
recs = []
|
| 427 |
+
for g in c.groups:
|
| 428 |
+
if g.uid not in M:
|
| 429 |
+
continue
|
| 430 |
+
song = c.songs[g.song_index]
|
| 431 |
+
bars = Bars.for_song(g.sections, g.table.beat, len(song["mel"]))
|
| 432 |
+
lg = apply_calib(M[g.uid], cal)
|
| 433 |
+
valid = bits_to_bool(g.table.valid)
|
| 434 |
+
for t in TIERS:
|
| 435 |
+
for bid, _, _, _ in g.charts.get(t, []):
|
| 436 |
+
hs = human_settings(song, chart_of(song, bid))
|
| 437 |
+
if hs is None:
|
| 438 |
+
continue
|
| 439 |
+
fs = fast_settings(pseudo_draws(smp, lg[:, :, t], valid, bid), bars)
|
| 440 |
+
recs.append({"set": g.set_id, "bid": bid, "tier": t, "key": g.key, "y": float(hs[2]),
|
| 441 |
+
"r": float(np.nanmean(fs["triplet"]))})
|
| 442 |
+
out[role] = recs
|
| 443 |
+
print(role, len(recs), "charts", flush=True)
|
| 444 |
+
ceil = np.load(a.ceilings)
|
| 445 |
+
res = {"cells": {}}
|
| 446 |
+
for t in TIERS:
|
| 447 |
+
tu = [r for r in out["tune"] if r["tier"] == t and np.isfinite(r["r"])]
|
| 448 |
+
A = np.polyfit([r["r"] for r in tu], [r["y"] for r in tu], 1)
|
| 449 |
+
va = {(r["set"], r["bid"]): r for r in out["val"] if r["tier"] == t and np.isfinite(r["r"])}
|
| 450 |
+
sets, bids = ceil[f"sig|{t}|set"], ceil[f"sig|{t}|bid"]
|
| 451 |
+
y, pc = ceil[f"pos12|triplet|{t}|y"], ceil[f"pos12|triplet|{t}|pred"]
|
| 452 |
+
songs = ceil[f"sig|{t}|song"]
|
| 453 |
+
keep = np.array([(int(s_), int(b_)) in va for s_, b_ in zip(sets, bids)])
|
| 454 |
+
pr = np.array([np.polyval(A, va[(int(s_), int(b_))]["r"]) for s_, b_, k in zip(sets, bids, keep) if k])
|
| 455 |
+
yy, pcc, ss = y[keep], pc[keep], songs[keep]
|
| 456 |
+
|
| 457 |
+
def r2(yv, pv):
|
| 458 |
+
return 1 - ((yv - pv) ** 2).sum() / ((yv - yv.mean()) ** 2).sum()
|
| 459 |
+
u, inv = np.unique(ss, return_inverse=True)
|
| 460 |
+
W = song_weights(u)
|
| 461 |
+
Wi = W[:, inv]
|
| 462 |
+
|
| 463 |
+
def wr2(pv):
|
| 464 |
+
m = (Wi @ yy) / Wi.sum(1)
|
| 465 |
+
return 1 - (Wi * (yy[None] - pv[None]) ** 2).sum(1) / (Wi * (yy[None] - m[:, None]) ** 2).sum(1)
|
| 466 |
+
est_R, est_C = r2(yy, pr), r2(yy, pcc)
|
| 467 |
+
blk = {"charts": int(keep.sum()), "ceiling_charts": int(len(keep)), "line": A.tolist(),
|
| 468 |
+
"r2_R": float(est_R), "r2_pos12": float(est_C), "diff": [float(est_R - est_C), *ci(wr2(pr) - wr2(pcc))],
|
| 469 |
+
"corr2_R": float(np.corrcoef(yy, pr)[0, 1] ** 2), "corr2_pos12": float(np.corrcoef(yy, pcc)[0, 1] ** 2),
|
| 470 |
+
"holds": bool(est_R >= est_C + 0.02)}
|
| 471 |
+
res["cells"][TNAME[t]] = blk
|
| 472 |
+
print(TNAME[t], blk, flush=True)
|
| 473 |
+
res["S2.5"] = all(res["cells"][TNAME[t]]["holds"] for t in TIERS)
|
| 474 |
+
res["per_chart"] = out
|
| 475 |
+
Path(a.out).write_text(json.dumps(res, indent=1))
|
| 476 |
+
print("S2.5", res["S2.5"])
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
# ------------------------------------------------------------------------------------------------ tempo slope (S2.6)
|
| 480 |
+
|
| 481 |
+
def pseudo_log_median_gap(masks, g):
|
| 482 |
+
"""mean over draws of log median gap (ms) between consecutive distinct hit times of the pseudo-charts."""
|
| 483 |
+
from chartgen.v11.rmap_data import POS as P24
|
| 484 |
+
out = []
|
| 485 |
+
for m in masks:
|
| 486 |
+
bits = (np.asarray(m, np.int64)[:, None] >> np.arange(24)) & 1
|
| 487 |
+
r, k = np.nonzero(bits)
|
| 488 |
+
t = np.unique(g.table.t0[r] + g.table.bl[r].astype(np.float64) * P24[k] / 48.0)
|
| 489 |
+
if len(t) >= 16:
|
| 490 |
+
out.append(np.log(np.median(np.diff(t))))
|
| 491 |
+
return float(np.mean(out)) if out else np.nan
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def main_charts_val(tiers=TIERS):
|
| 495 |
+
"""{(song key, tier): beatmap id} of the main human mapset per val song (as stage 0: build_human_collection)."""
|
| 496 |
+
from chartgen import disteval as de
|
| 497 |
+
E, cat = de.load_charts_all(), de.load_catalog()
|
| 498 |
+
col = de.build_human_collection(E, modern_only=False, catalog=cat, split="val")
|
| 499 |
+
out = {}
|
| 500 |
+
for key, v in col.items():
|
| 501 |
+
ms = v["human"][0]
|
| 502 |
+
for t in tiers:
|
| 503 |
+
if t in ms:
|
| 504 |
+
out[(key, t)] = int(ms[t]["beatmap_id"])
|
| 505 |
+
return out
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def slope_with_ci(x, y, keys):
|
| 509 |
+
u, inv = np.unique(keys, return_inverse=True)
|
| 510 |
+
W = np.vstack([np.ones(len(u)), song_weights(u)])[:, inv]
|
| 511 |
+
S = W.sum(1)
|
| 512 |
+
mx, my = W @ x / S, W @ y / S
|
| 513 |
+
dx, dy = x[None] - mx[:, None], y[None] - my[:, None]
|
| 514 |
+
sl = (W * dx * dy).sum(1) / (W * dx * dx).sum(1)
|
| 515 |
+
return sl
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
def tempo(a):
|
| 519 |
+
from chartgen.rhythm_eval import main_bpm
|
| 520 |
+
from chartgen.v11.rmap_pseudo import Sampler
|
| 521 |
+
smp = Sampler()
|
| 522 |
+
c = Corpus(a.data, {"val"}, tiers=TIERS, log=lambda m: None)
|
| 523 |
+
mains = main_charts_val()
|
| 524 |
+
models = {"R": (Maps(a.maps), load_calib(a.calib)), "noms": (Maps(a.noms), load_calib(a.noms_calib)),
|
| 525 |
+
"simple": (Maps(a.simple), load_calib(a.simple_calib)), "prior": (Maps(a.prior), None)}
|
| 526 |
+
res = {"cells": {}}
|
| 527 |
+
for t in TIERS:
|
| 528 |
+
X, Y, K, Z = [], [], [], {k: [] for k in models}
|
| 529 |
+
for g in c.groups:
|
| 530 |
+
if t not in g.charts or not all(g.uid in m for m, _ in models.values()):
|
| 531 |
+
continue
|
| 532 |
+
song = c.songs[g.song_index]
|
| 533 |
+
for bid, _, _, _ in g.charts[t]:
|
| 534 |
+
if mains.get((g.key, t)) != bid:
|
| 535 |
+
continue
|
| 536 |
+
ch = chart_of(song, bid)
|
| 537 |
+
ht = np.unique(np.sort(np.asarray(ch["time"], np.float64)[np.asarray(ch["type"]) <= 3]))
|
| 538 |
+
if len(ht) < 16:
|
| 539 |
+
continue
|
| 540 |
+
vals = {}
|
| 541 |
+
valid = bits_to_bool(g.table.valid)
|
| 542 |
+
for k, (M, cal) in models.items():
|
| 543 |
+
vals[k] = pseudo_log_median_gap(pseudo_draws(smp, apply_calib(M[g.uid], cal)[:, :, t], valid, bid), g)
|
| 544 |
+
if not all(np.isfinite(v) for v in vals.values()):
|
| 545 |
+
continue
|
| 546 |
+
X.append(np.log(main_bpm(ch["sections"]))); Y.append(np.log(np.median(np.diff(ht)))); K.append(g.key)
|
| 547 |
+
for k in models:
|
| 548 |
+
Z[k].append(vals[k])
|
| 549 |
+
X, Y, K = np.array(X), np.array(Y), np.array(K)
|
| 550 |
+
hs = slope_with_ci(X, Y, K)
|
| 551 |
+
blk = {"songs": int(len(np.unique(K))), "human": [float(hs[0]), *ci(hs[1:])]}
|
| 552 |
+
for k in models:
|
| 553 |
+
ms_ = slope_with_ci(X, np.array(Z[k]), K)
|
| 554 |
+
blk[k] = [float(ms_[0]), *ci(ms_[1:])]
|
| 555 |
+
blk[f"{k}_minus_human"] = [float(ms_[0] - hs[0]), *ci(ms_[1:] - hs[1:])]
|
| 556 |
+
lo, hi = blk["human"][1:]
|
| 557 |
+
blk["full_inside_human_ci"] = bool(lo is not None and lo <= blk["R"][0] <= hi)
|
| 558 |
+
blk["noms_extra_distance"] = abs(blk["noms"][0] - blk["human"][0]) - abs(blk["R"][0] - blk["human"][0])
|
| 559 |
+
res["cells"][TNAME[t]] = blk
|
| 560 |
+
print(TNAME[t], blk, flush=True)
|
| 561 |
+
if a.hidden:
|
| 562 |
+
z = np.load(a.hidden)
|
| 563 |
+
H, yb, kk = z["h"].astype(np.float32), z["logbl"].astype(np.float64), z["key"]
|
| 564 |
+
fold = np.array([int(__import__("hashlib").sha1(f"probe:{k}".encode()).hexdigest(), 16) % 5 for k in kk])
|
| 565 |
+
pred = np.zeros_like(yb)
|
| 566 |
+
for f in range(5):
|
| 567 |
+
tr, te = fold != f, fold == f
|
| 568 |
+
mu, sd = H[tr].mean(0), H[tr].std(0) + 1e-6
|
| 569 |
+
A = (H[tr] - mu) / sd
|
| 570 |
+
w = np.linalg.solve(A.T @ A + 1.0 * len(A) / 100 * np.eye(A.shape[1]), A.T @ (yb[tr] - yb[tr].mean()))
|
| 571 |
+
pred[te] = ((H[te] - mu) / sd) @ w + yb[tr].mean()
|
| 572 |
+
r2 = 1 - ((yb - pred) ** 2).sum() / ((yb - yb.mean()) ** 2).sum()
|
| 573 |
+
res["manipulation_check_r2"] = float(r2)
|
| 574 |
+
res["manipulation_check_tempo_removed"] = bool(r2 < 0.8)
|
| 575 |
+
print("manipulation check R2", r2)
|
| 576 |
+
res["S2.6_first"] = all(res["cells"][TNAME[t]]["full_inside_human_ci"] for t in TIERS)
|
| 577 |
+
second = res["cells"]["Oni"]["noms_extra_distance"] >= 0.10
|
| 578 |
+
res["S2.6_second"] = (None if not res.get("manipulation_check_tempo_removed", True) else bool(second))
|
| 579 |
+
Path(a.out).write_text(json.dumps(res, indent=1))
|
| 580 |
+
print("S2.6 first", res["S2.6_first"], "second", res["S2.6_second"])
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
# ------------------------------------------------------------------------------------------------ fidelity (pre-run check 3)
|
| 584 |
+
|
| 585 |
+
def fidelity(a):
|
| 586 |
+
from chartgen.dataset import subdiv_class
|
| 587 |
+
from chartgen.gapstats import gap_bins
|
| 588 |
+
from chartgen.v11.rmap_data import POS as P24
|
| 589 |
+
from chartgen.v11.rmap_pseudo import Bars, Sampler, fast_settings
|
| 590 |
+
smp = Sampler()
|
| 591 |
+
c = Corpus(a.data, {"tune"}, tiers=TIERS, log=lambda m: None)
|
| 592 |
+
M, cal = Maps(a.maps), load_calib(a.calib)
|
| 593 |
+
from chartgen.v11.rmap_pseudo import apply_tau
|
| 594 |
+
taus = json.loads(Path(a.taus).read_text())["tau"]["R"] if a.taus else {}
|
| 595 |
+
|
| 596 |
+
def stats_of_grid(gr, bl_of):
|
| 597 |
+
gr = np.unique(gr)
|
| 598 |
+
if len(gr) < 16:
|
| 599 |
+
return None
|
| 600 |
+
blk = gr // (48 * 16)
|
| 601 |
+
fine = subdiv_class(gr) >= 5
|
| 602 |
+
u = np.unique(blk)
|
| 603 |
+
a_ = float(np.isin(u, np.unique(blk[fine])).mean())
|
| 604 |
+
gb = gap_bins(np.diff(gr) / 48.0)
|
| 605 |
+
c_ = float((gb == 8).mean())
|
| 606 |
+
return a_, c_
|
| 607 |
+
|
| 608 |
+
rec = {t: {"pseudo": [], "human": []} for t in TIERS}
|
| 609 |
+
for g in c.groups:
|
| 610 |
+
if g.uid not in M:
|
| 611 |
+
continue
|
| 612 |
+
song = c.songs[g.song_index]
|
| 613 |
+
bars = Bars.for_song(g.sections, g.table.beat, len(song["mel"]))
|
| 614 |
+
lg = apply_calib(M[g.uid], cal)
|
| 615 |
+
valid = bits_to_bool(g.table.valid)
|
| 616 |
+
for t in TIERS:
|
| 617 |
+
for bid, _, tgt, _ in g.charts.get(t, []):
|
| 618 |
+
ch = chart_of(song, bid)
|
| 619 |
+
hs = human_settings(song, ch)
|
| 620 |
+
hit = np.asarray(ch["type"]) <= 3
|
| 621 |
+
hg = np.round(np.asarray(ch["beat"])[hit] * 48).astype(np.int64)
|
| 622 |
+
hst = stats_of_grid(hg, None)
|
| 623 |
+
m = pseudo_draws(smp, apply_tau(lg[:, :, t], taus.get(str(t))), valid, bid, k=1)
|
| 624 |
+
bits = (np.asarray(m[0], np.int64)[:, None] >> np.arange(24)) & 1
|
| 625 |
+
r, k = np.nonzero(bits)
|
| 626 |
+
pg = g.table.beat[r] * 48 + P24[k]
|
| 627 |
+
pst = stats_of_grid(pg, None)
|
| 628 |
+
fs = fast_settings(m, bars)
|
| 629 |
+
if hs is None or hst is None or pst is None or not np.isfinite(fs["triplet"][0]):
|
| 630 |
+
continue
|
| 631 |
+
ht = np.unique(np.asarray(ch["time"], np.float64)[hit])
|
| 632 |
+
pt = np.unique(g.table.t0[r] + g.table.bl[r].astype(np.float64) * P24[k] / 48.0)
|
| 633 |
+
rec[t]["human"].append([hst[0], hs[2], hs[3], hst[1], np.log(np.median(np.diff(ht)))])
|
| 634 |
+
rec[t]["pseudo"].append([pst[0], fs["triplet"][0], fs["eighth"][0], pst[1], np.log(np.median(np.diff(pt)))])
|
| 635 |
+
names = ["blocks_with_1/8_or_finer", "triplet_setting", "eighth_setting", "gap_other_share", "log_median_gap_ms"]
|
| 636 |
+
res = {}
|
| 637 |
+
for t in TIERS:
|
| 638 |
+
H, P = np.array(rec[t]["human"]), np.array(rec[t]["pseudo"])
|
| 639 |
+
blk = {"charts": len(H)}
|
| 640 |
+
for i, nm in enumerate(names):
|
| 641 |
+
blk[nm] = {"human": float(H[:, i].mean()), "pseudo": float(P[:, i].mean()),
|
| 642 |
+
"ratio": float(P[:, i].mean() / H[:, i].mean()) if i < 4 else None,
|
| 643 |
+
"diff": float(P[:, i].mean() - H[:, i].mean())}
|
| 644 |
+
blk["flag"] = any(blk[nm]["ratio"] > 1.5 for nm in names[:3])
|
| 645 |
+
res[TNAME[t]] = blk
|
| 646 |
+
print(TNAME[t], blk, flush=True)
|
| 647 |
+
res["flag_any"] = any(res[TNAME[t]]["flag"] for t in TIERS)
|
| 648 |
+
Path(a.out).write_text(json.dumps(res, indent=1))
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
# ------------------------------------------------------------------------------------------------ sampling temperature
|
| 652 |
+
|
| 653 |
+
def taufit(a):
|
| 654 |
+
"""Addendum of 2026-11-20: per map, tier and family, the temperature tau (logits / tau before the end-to-end
|
| 655 |
+
conversion samples) that makes the share of 16-beat blocks holding a note of the family equal to the human share,
|
| 656 |
+
on the tuning set (one pseudo-chart per chart, seed pseudo_seed(beatmap id, 0)); triplet family first, then the
|
| 657 |
+
1/8 family with the triplet tau fixed; bisection on log tau in [log 0.05, log 2], 20 steps."""
|
| 658 |
+
from chartgen.v11.rmap_pseudo import FAMILY_POS, Sampler, apply_tau, block_share, pseudo_seed
|
| 659 |
+
smp = Sampler()
|
| 660 |
+
c = Corpus(a.data, {"tune"}, tiers=TIERS, log=lambda m: None)
|
| 661 |
+
specs = {"R": (a.maps, a.calib), "prior": (a.prior, None), "simple": (a.simple, a.simple_calib)}
|
| 662 |
+
out, info = {}, {}
|
| 663 |
+
for name, (mp, cp) in specs.items():
|
| 664 |
+
M, cal = Maps(mp), load_calib(cp)
|
| 665 |
+
out[name] = {}
|
| 666 |
+
for t in TIERS:
|
| 667 |
+
items = []
|
| 668 |
+
for g in c.groups:
|
| 669 |
+
if t not in g.charts or g.uid not in M:
|
| 670 |
+
continue
|
| 671 |
+
lg = apply_calib(M[g.uid], cal)[:, :, t]
|
| 672 |
+
valid = bits_to_bool(g.table.valid)
|
| 673 |
+
for bid, _, tgt, _ in g.charts[t]:
|
| 674 |
+
G = smp.gumbel(np.random.default_rng(pseudo_seed(bid, 0)), 1, len(lg))[0]
|
| 675 |
+
items.append((lg, valid, G, g.table.beat, tgt))
|
| 676 |
+
human = {f: float(np.nanmean([block_share(it[4].astype(np.int64), it[3], FAMILY_POS[f]) for it in items]))
|
| 677 |
+
for f in ("triplet", "eighth")}
|
| 678 |
+
|
| 679 |
+
def share(tau, fam):
|
| 680 |
+
v = [block_share(smp.masks[np.argmax(smp.scores(apply_tau(lg, tau), valid) + G, -1)], beats,
|
| 681 |
+
FAMILY_POS[fam]) for lg, valid, G, beats, _ in items]
|
| 682 |
+
return float(np.nanmean(v))
|
| 683 |
+
tau = {"triplet": 1.0, "eighth": 1.0}
|
| 684 |
+
rec = {}
|
| 685 |
+
for fam in ("triplet", "eighth"):
|
| 686 |
+
lo, hi = np.log(0.05), np.log(2.0)
|
| 687 |
+
s_hi = share({**tau, fam: float(np.exp(hi))}, fam)
|
| 688 |
+
s_lo = share({**tau, fam: float(np.exp(lo))}, fam)
|
| 689 |
+
if human[fam] >= s_hi:
|
| 690 |
+
tau[fam] = float(np.exp(hi))
|
| 691 |
+
elif human[fam] <= s_lo:
|
| 692 |
+
tau[fam] = float(np.exp(lo))
|
| 693 |
+
else:
|
| 694 |
+
for _ in range(20):
|
| 695 |
+
mid = 0.5 * (lo + hi)
|
| 696 |
+
if share({**tau, fam: float(np.exp(mid))}, fam) < human[fam]:
|
| 697 |
+
lo = mid
|
| 698 |
+
else:
|
| 699 |
+
hi = mid
|
| 700 |
+
tau[fam] = float(np.exp(0.5 * (lo + hi)))
|
| 701 |
+
rec[fam] = {"human_block_share": human[fam], "pseudo_block_share_tau1": share({**tau, fam: 1.0}, fam),
|
| 702 |
+
"tau": tau[fam], "pseudo_block_share_fitted": share(tau, fam)}
|
| 703 |
+
out[name][str(t)] = tau
|
| 704 |
+
info[f"{name}|{t}"] = {"charts": len(items), **rec}
|
| 705 |
+
print(name, t, info[f"{name}|{t}"], flush=True)
|
| 706 |
+
Path(a.out).write_text(json.dumps({"tau": out, "info": info}, indent=1))
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
def main(argv=None):
|
| 710 |
+
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 711 |
+
ap.add_argument("cmd", choices=["calib", "position", "bars", "slow8", "song", "tempo", "fidelity", "taufit"])
|
| 712 |
+
ap.add_argument("--data", nargs="+", required=True)
|
| 713 |
+
ap.add_argument("--maps", required=True)
|
| 714 |
+
ap.add_argument("--calib")
|
| 715 |
+
ap.add_argument("--simple")
|
| 716 |
+
ap.add_argument("--simple-calib")
|
| 717 |
+
ap.add_argument("--prior")
|
| 718 |
+
ap.add_argument("--sp9")
|
| 719 |
+
ap.add_argument("--maps-train", nargs="*", default=[])
|
| 720 |
+
ap.add_argument("--simple-train", nargs="*", default=[])
|
| 721 |
+
ap.add_argument("--prior-train", nargs="*", default=[])
|
| 722 |
+
ap.add_argument("--maps-tune")
|
| 723 |
+
ap.add_argument("--ceilings")
|
| 724 |
+
ap.add_argument("--noms")
|
| 725 |
+
ap.add_argument("--noms-calib")
|
| 726 |
+
ap.add_argument("--hidden")
|
| 727 |
+
ap.add_argument("--taus")
|
| 728 |
+
ap.add_argument("--out", required=True)
|
| 729 |
+
a = ap.parse_args(argv)
|
| 730 |
+
{"calib": calib, "position": position, "bars": bars_eval, "slow8": slow8_eval, "song": song_level,
|
| 731 |
+
"tempo": tempo, "fidelity": fidelity, "taufit": taufit}[a.cmd](a)
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
if __name__ == "__main__":
|
| 735 |
+
main()
|
chartgen/v11/rmap_pseudo.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""v11 stage 2: pseudo-charts from a position map (reports/v11 階段 2 預先登記:位置圖 R.md, section 1).
|
| 2 |
+
|
| 3 |
+
A pseudo-chart holds hit notes only. Each beat draws one pattern from the stage-0 vocabulary (897 patterns, pooled over
|
| 4 |
+
tiers, reports/figs/v11_s0_vocab.json) plus the empty beat, with weight prod_{k in pattern} p_k * prod_{k not in
|
| 5 |
+
pattern} (1 - p_k), normalised. In log space that is const + sum of the logits of the pattern's positions, so the
|
| 6 |
+
scores of all patterns are logits @ M^T (M = [patterns, 24] 0/1). Patterns outside the vocabulary are never drawn.
|
| 7 |
+
Draws use the Gumbel-max trick; with fixed Gumbel noise the draw is a monotone function of a logit shift, which makes
|
| 8 |
+
the song-wide shift (bisection on delta, 30 steps in [-8, 8]) stable.
|
| 9 |
+
|
| 10 |
+
Song-level settings of a pseudo-chart (latent_stats.chart_settings on dataset.bar_plan) are computed here in a
|
| 11 |
+
vectorised form from per-beat masks (fast_settings); the self-test checks them against bar_plan + chart_settings.
|
| 12 |
+
|
| 13 |
+
python -m chartgen.v11.rmap_pseudo --selftest
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import json
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
from chartgen.dataset import measure_at, measure_span
|
| 25 |
+
from chartgen.v11.patterns import GRID, N_POS, POSITIONS
|
| 26 |
+
from chartgen.v11.rmap_data import POS, POS_CLASS
|
| 27 |
+
|
| 28 |
+
REPO = Path(__file__).resolve().parents[3]
|
| 29 |
+
VOCAB_JSON = REPO / "reports/figs/v11_s0_vocab.json"
|
| 30 |
+
TRIP_POS = np.isin(POS_CLASS, [2, 4, 6]) # bar_plan column 4: 1/3, 1/6, 1/12
|
| 31 |
+
FINE_POS = POS_CLASS >= 5 # bar_plan column 5: 1/8, 1/12, 1/16 (and finer)
|
| 32 |
+
FAMILY_POS = {"triplet": np.isin(POS_CLASS, [2, 4, 6]), "eighth": np.isin(POS_CLASS, [5, 7]),
|
| 33 |
+
"all": np.ones(N_POS, bool)}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def load_vocab_masks(path=VOCAB_JSON) -> np.ndarray:
|
| 37 |
+
d = json.loads(Path(path).read_text())["vocab_pooled"]
|
| 38 |
+
return np.asarray(d["masks"], np.int64)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
_POP8 = np.array([bin(i).count("1") for i in range(256)], np.int64)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def popcount(m: np.ndarray, sel: np.ndarray | None = None) -> np.ndarray:
|
| 45 |
+
"""Number of set bits of 24-bit masks (restricted to the positions in sel)."""
|
| 46 |
+
m = np.asarray(m, np.int64)
|
| 47 |
+
if sel is not None:
|
| 48 |
+
m = m & int((np.asarray(sel, np.int64) << np.arange(N_POS)).sum())
|
| 49 |
+
return _POP8[m & 255] + _POP8[(m >> 8) & 255] + _POP8[(m >> 16) & 255]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class Sampler:
|
| 53 |
+
def __init__(self, masks=None):
|
| 54 |
+
masks = load_vocab_masks() if masks is None else np.asarray(masks, np.int64)
|
| 55 |
+
self.masks = np.r_[0, masks].astype(np.int64) # index 0 = empty beat
|
| 56 |
+
self.M = ((self.masks[:, None] >> np.arange(N_POS)) & 1).astype(np.float32) # [V+1, 24]
|
| 57 |
+
|
| 58 |
+
def scores(self, logits: np.ndarray, valid: np.ndarray) -> np.ndarray:
|
| 59 |
+
lg = np.where(valid, np.clip(logits, -30, 30), -1e4).astype(np.float32) # invalid positions: never drawn
|
| 60 |
+
return lg @ self.M.T # [n, V+1]
|
| 61 |
+
|
| 62 |
+
def family_count(self, fam: np.ndarray) -> np.ndarray:
|
| 63 |
+
return self.M @ fam.astype(np.float32) # [V+1]
|
| 64 |
+
|
| 65 |
+
def gumbel(self, rng, k: int, n: int) -> np.ndarray:
|
| 66 |
+
return rng.gumbel(size=(k, n, len(self.masks))).astype(np.float32)
|
| 67 |
+
|
| 68 |
+
def draw(self, S: np.ndarray, G: np.ndarray) -> np.ndarray:
|
| 69 |
+
"""[k, n] beat masks (int64)."""
|
| 70 |
+
return self.masks[np.argmax(S[None] + G, -1)]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def masks_to_grid(beats: np.ndarray, masks: np.ndarray) -> np.ndarray:
|
| 74 |
+
bits = (np.asarray(masks, np.int64)[:, None] >> np.arange(N_POS)) & 1
|
| 75 |
+
bi, pi = np.nonzero(bits)
|
| 76 |
+
return np.sort(np.asarray(beats, np.int64)[bi] * GRID + POS[pi])
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class Bars:
|
| 80 |
+
"""Measures of a timing as bar_plan sees them: rows b0 .. b0 + n - 1 (b0 = measure at 0 ms, n <= 384, as in
|
| 81 |
+
song_planner.chart_rows), the measure row of every beat of a beat table, and the measure lengths in beats."""
|
| 82 |
+
|
| 83 |
+
def __init__(self, sections, beats: np.ndarray, b0: int, n: int):
|
| 84 |
+
s = np.asarray(sections, np.float64)
|
| 85 |
+
self.b0, self.n = int(b0), int(n)
|
| 86 |
+
self.row = measure_at(s, np.asarray(beats, np.float64)) - self.b0
|
| 87 |
+
st, en = measure_span(s, np.arange(self.n) + self.b0)
|
| 88 |
+
self.mlen = np.maximum(en - st, 1e-6)
|
| 89 |
+
self.ok = (self.row >= 0) & (self.row < self.n)
|
| 90 |
+
|
| 91 |
+
@classmethod
|
| 92 |
+
def for_song(cls, sections, beats, n_frames: int):
|
| 93 |
+
from chartgen.dataset import _beats_at
|
| 94 |
+
from chartgen.song_planner import MAX_SONG_BARS
|
| 95 |
+
t = np.arange((n_frames + 1) // 2) * 20.0
|
| 96 |
+
bars = measure_at(np.asarray(sections, np.float64), _beats_at(np.asarray(sections, np.float64), t))
|
| 97 |
+
b0 = int(bars.min())
|
| 98 |
+
return cls(sections, beats, b0, min(int(bars.max()) - b0 + 1, MAX_SONG_BARS))
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def fast_settings(masks: np.ndarray, bars: Bars) -> dict:
|
| 102 |
+
"""masks [k, n_beats] -> per draw: triplet (chart_settings[2]), eighth ([3]), density ([5]) and n_play; NaN where
|
| 103 |
+
chart_settings would return None (fewer than 8 played measures)."""
|
| 104 |
+
masks = np.atleast_2d(masks)
|
| 105 |
+
k = len(masks)
|
| 106 |
+
nh = popcount(masks)
|
| 107 |
+
nt = popcount(masks, TRIP_POS)
|
| 108 |
+
nf = popcount(masks, FINE_POS)
|
| 109 |
+
idx = (np.arange(k)[:, None] * bars.n + bars.row[bars.ok][None]).ravel()
|
| 110 |
+
H, T, Fn = (np.bincount(idx, weights=src[:, bars.ok].ravel().astype(np.float64), minlength=k * bars.n)
|
| 111 |
+
.reshape(k, bars.n) for src in (nh, nt, nf))
|
| 112 |
+
play = H > 0
|
| 113 |
+
n_play = play.sum(1)
|
| 114 |
+
with np.errstate(invalid="ignore", divide="ignore"):
|
| 115 |
+
trip = np.where(play, (T / np.maximum(H, 1)) > 0.3, False).sum(1) / n_play
|
| 116 |
+
eig = np.where(play, (Fn / np.maximum(H, 1)) > 0.25, False).sum(1) / n_play
|
| 117 |
+
dens = np.where(play, np.log1p(H / bars.mlen[None]), 0.0).sum(1) / n_play
|
| 118 |
+
bad = n_play < 8
|
| 119 |
+
# stage 5a: note-level share of the 1/8 family (classes 1/8 and 1/16) among all notes of the draw
|
| 120 |
+
n8 = popcount(masks, FAMILY_POS["eighth"])[:, bars.ok].sum(1)
|
| 121 |
+
with np.errstate(invalid="ignore", divide="ignore"):
|
| 122 |
+
e8 = n8 / np.maximum(H.sum(1), 1)
|
| 123 |
+
return {"triplet": np.where(bad, np.nan, trip), "eighth": np.where(bad, np.nan, eig),
|
| 124 |
+
"density": np.where(bad, np.nan, dens), "n_play": n_play, "eighth_share": np.where(bad, np.nan, e8)}
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def shift_to_target(sampler: Sampler, S0: np.ndarray, G: np.ndarray, fam: np.ndarray, bars: Bars, which: str,
|
| 128 |
+
target: float, lo: float = -8.0, hi: float = 8.0, steps: int = 30):
|
| 129 |
+
"""delta such that the mean over the k draws of `which` equals target (S = S0 + delta * family count).
|
| 130 |
+
The draws of the bisection run in torch (on the GPU when there is one); same arithmetic as Sampler.draw."""
|
| 131 |
+
import torch
|
| 132 |
+
dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 133 |
+
c = sampler.family_count(fam)
|
| 134 |
+
base = torch.as_tensor(S0[None] + G, device=dev) # [k, n, V+1] float32, identical to draw()
|
| 135 |
+
ct = torch.as_tensor(c, device=dev)
|
| 136 |
+
|
| 137 |
+
def f(d):
|
| 138 |
+
idx = torch.argmax(base + np.float32(d) * ct, -1).cpu().numpy()
|
| 139 |
+
v = fast_settings(sampler.masks[idx], bars)[which]
|
| 140 |
+
return float(np.mean(np.nan_to_num(v, nan=0.0))) # too few played measures counts as 0
|
| 141 |
+
|
| 142 |
+
flo, fhi = f(lo), f(hi)
|
| 143 |
+
if not (flo <= target <= fhi):
|
| 144 |
+
return (lo if target < flo else hi), (flo if target < flo else fhi)
|
| 145 |
+
for _ in range(steps):
|
| 146 |
+
mid = 0.5 * (lo + hi)
|
| 147 |
+
if f(mid) < target:
|
| 148 |
+
lo = mid
|
| 149 |
+
else:
|
| 150 |
+
hi = mid
|
| 151 |
+
d = 0.5 * (lo + hi)
|
| 152 |
+
return d, f(d)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def apply_tau(lg: np.ndarray, tau: dict | None) -> np.ndarray:
|
| 156 |
+
"""Sampling temperature of the end-to-end conversion (pre-registration addendum of 2026-11-20): the logits of the
|
| 157 |
+
triplet family (1/3, 1/6, 1/12) and of the 1/8 family (1/8, 1/16) divided by their tau. lg: [n, 24] one tier."""
|
| 158 |
+
if not tau:
|
| 159 |
+
return lg
|
| 160 |
+
out = np.array(lg, np.float32, copy=True)
|
| 161 |
+
for fam in ("triplet", "eighth"):
|
| 162 |
+
out[:, FAMILY_POS[fam]] /= float(tau[fam])
|
| 163 |
+
return out
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def block_share(masks: np.ndarray, beats: np.ndarray, sel: np.ndarray) -> float:
|
| 167 |
+
"""Share of 16-beat blocks (global beat // 16) with a note that hold a note on the selected positions."""
|
| 168 |
+
has = popcount(masks) > 0
|
| 169 |
+
if not has.any():
|
| 170 |
+
return float("nan")
|
| 171 |
+
blk = np.asarray(beats, np.int64)[has] // 16
|
| 172 |
+
fam = (popcount(masks, sel) > 0)[has]
|
| 173 |
+
u = np.unique(blk)
|
| 174 |
+
return float(np.isin(u, np.unique(blk[fam])).mean())
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def pseudo_seed(beatmap_id: int, i: int) -> int:
|
| 178 |
+
import hashlib
|
| 179 |
+
return int(hashlib.sha1(f"pseudo:{beatmap_id}:{i}".encode()).hexdigest()[:8], 16)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
# ------------------------------------------------------------------------------------------------ self-test
|
| 183 |
+
|
| 184 |
+
def selftest():
|
| 185 |
+
from chartgen.dataset import bar_plan, load_songs
|
| 186 |
+
from chartgen.latent_stats import chart_settings
|
| 187 |
+
from chartgen.v11.patterns import beat_masks
|
| 188 |
+
from chartgen.v11.rmap_data import song_groups
|
| 189 |
+
smp = Sampler()
|
| 190 |
+
print("vocabulary patterns:", len(smp.masks) - 1)
|
| 191 |
+
songs = load_songs(["data/pilot/features/taiko-00000.pkl"], mmap=True)
|
| 192 |
+
n_chk = 0
|
| 193 |
+
for s in songs[:60]:
|
| 194 |
+
for g in song_groups(s):
|
| 195 |
+
bars = Bars.for_song(g.sections, g.table.beat, len(s["mel"]))
|
| 196 |
+
for t, lst in g.charts.items():
|
| 197 |
+
bid = lst[0][0]
|
| 198 |
+
c = next(c for c in s["charts"] if int(c["beatmap_id"]) == bid)
|
| 199 |
+
hit = np.asarray(c["type"]) <= 3
|
| 200 |
+
gr = np.unique(np.round(np.asarray(c["beat"])[hit] * GRID).astype(np.int64))
|
| 201 |
+
if np.isin(np.mod(gr, GRID), POS, invert=True).any():
|
| 202 |
+
continue
|
| 203 |
+
ref = chart_settings(bar_plan(gr, np.zeros(len(gr), np.int64), bars.b0, g.sections, None, bars.n))
|
| 204 |
+
bt, ms, _ = beat_masks(gr)
|
| 205 |
+
full = np.zeros(len(g.table), np.int64)
|
| 206 |
+
row = np.searchsorted(g.table.beat, bt)
|
| 207 |
+
okr = (row < len(g.table)) & (g.table.beat[np.minimum(row, len(g.table) - 1)] == bt)
|
| 208 |
+
full[row[okr]] = ms[okr]
|
| 209 |
+
fs = fast_settings(full[None], bars)
|
| 210 |
+
if ref is None:
|
| 211 |
+
assert np.isnan(fs["triplet"][0])
|
| 212 |
+
continue
|
| 213 |
+
for nm, j in (("triplet", 2), ("eighth", 3), ("density", 5)):
|
| 214 |
+
assert abs(fs[nm][0] - ref[j]) < 1e-5, (bid, nm, fs[nm][0], ref[j])
|
| 215 |
+
n_chk += 1
|
| 216 |
+
print("fast_settings == bar_plan + chart_settings on", n_chk, "hit-only charts")
|
| 217 |
+
# sampling: probabilities near 0/1 reproduce a pattern; shift moves the triplet amount monotonically
|
| 218 |
+
g = song_groups(songs[1])[0]
|
| 219 |
+
bars = Bars.for_song(g.sections, g.table.beat, len(songs[1]["mel"]))
|
| 220 |
+
rng = np.random.default_rng(0)
|
| 221 |
+
n = len(g.table)
|
| 222 |
+
logits = rng.normal(-3, 1.5, (n, N_POS)).astype(np.float32)
|
| 223 |
+
valid = np.ones((n, N_POS), bool)
|
| 224 |
+
S0 = smp.scores(logits, valid)
|
| 225 |
+
G = smp.gumbel(rng, 16, n)
|
| 226 |
+
vals = [np.nanmean(fast_settings(smp.draw(S0 + d * smp.family_count(FAMILY_POS["triplet"])[None], G), bars)["triplet"])
|
| 227 |
+
for d in (-4, 0, 4)]
|
| 228 |
+
assert vals[0] <= vals[1] <= vals[2], vals
|
| 229 |
+
d, got = shift_to_target(smp, S0, G, FAMILY_POS["triplet"], bars, "triplet", 0.2)
|
| 230 |
+
assert abs(got - 0.2) < 0.03, (d, got)
|
| 231 |
+
print(f"triplet at delta -4/0/4: {[round(v, 3) for v in vals]}; shift to 0.2 -> delta {d:.3f}, value {got:.3f}")
|
| 232 |
+
print("selftest ok")
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def main(argv=None):
|
| 236 |
+
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 237 |
+
ap.add_argument("--selftest", action="store_true")
|
| 238 |
+
a = ap.parse_args(argv)
|
| 239 |
+
if a.selftest:
|
| 240 |
+
selftest()
|
| 241 |
+
|
| 242 |
+
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""v11 stage 1: controls on the v10c generator (b9), generated as paired arms from the same plan draws.
|
| 2 |
+
|
| 3 |
+
Each draw of a set uses one setting draw of the v10c prior (chart_prior + song cutoffs + count_then_place + tier
|
| 4 |
+
coordination, as gen_mapset.make_draw). From it every arm writes Oni and Inner Oni:
|
| 5 |
+
|
| 6 |
+
argmax_mbr b9's section class by argmax (plan_source pred), v10c bar plan, N=4 candidates, MBR (= v10c)
|
| 7 |
+
argmax_t09 the same run's T=0.9 candidate (no MBR)
|
| 8 |
+
sample_mbr section class sampled from b9's section head (plan_source sample), v10c bar plan, N=4, MBR
|
| 9 |
+
sample_t09 the same run's T=0.9 candidate
|
| 10 |
+
class_human the human chart's section class (oracle_r), v10c bar plan, one T=0.9 sample
|
| 11 |
+
amount_human sampled section class; bar plan from count_then_place with the human chart's song-level amounts
|
| 12 |
+
(chart_settings[:6] of the human bar plan) instead of the prior draw; one T=0.9 sample
|
| 13 |
+
plan_human the human chart's whole plan: section class, density and gaps (plan_source oracle) and the human bar
|
| 14 |
+
plan and rest mask; one T=0.9 sample
|
| 15 |
+
|
| 16 |
+
The human chart of a tier is the reference set's own chart, chosen as disteval._entry_mapset does (>= MIN_NOTES
|
| 17 |
+
notes; smallest sha1 of the beatmap id). Arms that need it skip a tier the set does not have. Only the plan fields
|
| 18 |
+
are copied from the human example into the generation examples (built from a timing-only chart), so no other
|
| 19 |
+
information from the human chart (repetition hints, events) reaches the generator.
|
| 20 |
+
|
| 21 |
+
Output: one gen_mapset-format pickle per arm, <out>/mapsets_S1_<arm>.pkl ({set: {song_key, sections, draws: [{charts:
|
| 22 |
+
{tier: chart}, settings, b}]}}), saved every --save-every sets and resumable.
|
| 23 |
+
|
| 24 |
+
python -m chartgen.v11.s1_arms --data f*.pkl --model b9.pt --encoder best_v1.pt --planner sp9.pt \\
|
| 25 |
+
--thresholds thresholds.json --prior chart_prior.pkl --protos protos.pkl --song-cutoffs cutoffs.json \\
|
| 26 |
+
--sets-file sets.txt --draws 2 --out runs/v11_s1
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
from __future__ import annotations
|
| 30 |
+
|
| 31 |
+
import argparse
|
| 32 |
+
import dataclasses
|
| 33 |
+
import json
|
| 34 |
+
import pickle
|
| 35 |
+
import time
|
| 36 |
+
from pathlib import Path
|
| 37 |
+
|
| 38 |
+
import numpy as np
|
| 39 |
+
import torch
|
| 40 |
+
|
| 41 |
+
from chartgen import song_planner as sp
|
| 42 |
+
from chartgen.dataset import WINDOW, load_songs, make_example
|
| 43 |
+
from chartgen.disteval import MIN_NOTES, _sha
|
| 44 |
+
from chartgen.gen_mapset import (CANDS, mbr_pick, masks, planner_out, planner_rows, song_property_amounts,
|
| 45 |
+
window_plan)
|
| 46 |
+
from chartgen.generate import generate
|
| 47 |
+
from chartgen.infer import _dummy_chart, decode_kiai, frame_activations, load_model
|
| 48 |
+
from chartgen.latent_stats import chart_settings
|
| 49 |
+
from chartgen.plan_decide import count_then_place
|
| 50 |
+
from chartgen.train import song_split
|
| 51 |
+
|
| 52 |
+
TIERS = (3, 4)
|
| 53 |
+
ARMS = ("argmax_mbr", "argmax_t09", "sample_mbr", "sample_t09", "class_human", "amount_human", "plan_human")
|
| 54 |
+
T09 = 2 # index of the first T=0.9 candidate in CANDS
|
| 55 |
+
SEQS_PER_CALL = 96 # sequences per generate call (v10c: 24 windows x 4 candidates)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def human_of(song: dict, tier: int):
|
| 59 |
+
cs = [c for c in song["charts"] if int(c["tier"]) == tier and len(c["time"]) >= MIN_NOTES]
|
| 60 |
+
return min(cs, key=lambda c: _sha(c["beatmap_id"])) if cs else None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def human_settings(mel, chart):
|
| 64 |
+
_, H, _ = sp.chart_rows(np.zeros(((len(mel) + 1) // 2, 1), np.float32), chart)
|
| 65 |
+
return chart_settings(H)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def run_windows(model, mel, sections, tier, t0, t1, device, seed, plan_source, cands, plan_pair=None, human=None,
|
| 69 |
+
copy=(), min_gap_ms=None, phase_ok=None, seam_slack_ms=5.0):
|
| 70 |
+
"""Generate one tier over all windows. plan_pair = (b_song, song plan) gives the bar plan and rest mask; with
|
| 71 |
+
plan_pair None the human example's own bar plan is used. copy: plan fields taken from the human example.
|
| 72 |
+
min_gap_ms (stage 4b): shortest allowed gap between events, enforced on grid times while decoding inside a window
|
| 73 |
+
and, at the joins between windows, by dropping a hit note more than 5 ms closer than this to the previous kept hit
|
| 74 |
+
note (the 5 ms leave room for the predicted timing residual).
|
| 75 |
+
phase_ok (stage 5a): bool mask over the 48 positions of a beat; events only on open positions (generate.phase_ok).
|
| 76 |
+
seam_slack_ms (stage 5a fix): the slack of the min-gap pass over the merged windows (5 ms up to stage 4; the
|
| 77 |
+
stage-5a arms use 1 ms, see s5a.enforce_min_gap).
|
| 78 |
+
Returns {candidate name or 'mbr': (time, type, length, sv) arrays}."""
|
| 79 |
+
dummy = _dummy_chart(sections, tier)
|
| 80 |
+
song = {"mel": mel}
|
| 81 |
+
starts = list(range(int(max(t0, 0) // 10), int(t1 // 10), WINDOW))
|
| 82 |
+
names = [c[0] for c in cands] + (["mbr"] if len(cands) > 1 else [])
|
| 83 |
+
acc = {n: ([], [], [], []) for n in names}
|
| 84 |
+
per_call = max(1, SEQS_PER_CALL // len(cands))
|
| 85 |
+
for gi in range(0, len(starts), per_call):
|
| 86 |
+
exs, bplans, allowed, conts, temps, scales, meta = [], [], [], [], [], [], []
|
| 87 |
+
for st in starts[gi:gi + per_call]:
|
| 88 |
+
ex = make_example(song, dummy, st)
|
| 89 |
+
hx = make_example(song, human, st) if human is not None else None
|
| 90 |
+
if copy:
|
| 91 |
+
ex = dataclasses.replace(ex, **{k: getattr(hx, k) for k in copy})
|
| 92 |
+
if plan_pair is not None:
|
| 93 |
+
w, cov, bar0 = window_plan(plan_pair[1], plan_pair[0], sections, st)
|
| 94 |
+
else: # the human bar plan, aligned to the window's first measure
|
| 95 |
+
w, cov = hx.bar_plan, np.ones(len(hx.bar_plan), bool)
|
| 96 |
+
bar0 = int(window_plan(np.zeros((1, w.shape[1]), np.float32), 0, sections, st)[2])
|
| 97 |
+
al, cont = masks(ex, sections, w, cov, bar0)
|
| 98 |
+
for _, temp, sc in cands:
|
| 99 |
+
exs.append(ex); bplans.append(w); allowed.append(al); conts.append(cont); temps.append(temp); scales.append(sc)
|
| 100 |
+
meta.append(ex)
|
| 101 |
+
torch.manual_seed(seed + gi)
|
| 102 |
+
preds = generate(model, exs, device, temperature=temps, rho_scale=scales, plan_source=plan_source,
|
| 103 |
+
bar_plan=np.stack(bplans), allowed=allowed, continue_until=conts,
|
| 104 |
+
min_gap_ms=min_gap_ms if min_gap_ms else None,
|
| 105 |
+
phase_ok=None if phase_ok is None else [phase_ok] * len(exs))
|
| 106 |
+
for k, ex in enumerate(meta):
|
| 107 |
+
group = preds[k * len(cands):(k + 1) * len(cands)]
|
| 108 |
+
picks = {c[0]: group[i] for i, c in enumerate(cands)}
|
| 109 |
+
if len(cands) > 1:
|
| 110 |
+
picks["mbr"] = group[mbr_pick(group)]
|
| 111 |
+
for n, p in picks.items():
|
| 112 |
+
t = p["time"] + ex.start_ms
|
| 113 |
+
keep = (t < ex.start_ms + WINDOW * 10.0) & (t <= t1 + 2000)
|
| 114 |
+
for lst, v in zip(acc[n], (t, p["type"], p["length"], p["sv"])):
|
| 115 |
+
lst.append(v[keep])
|
| 116 |
+
out = {}
|
| 117 |
+
for n, (ts, ty, ln, sv) in acc.items():
|
| 118 |
+
tm = np.concatenate(ts) if ts else np.zeros(0)
|
| 119 |
+
order = np.argsort(tm, kind="stable")
|
| 120 |
+
tm = tm[order]
|
| 121 |
+
keep = np.r_[True, np.diff(tm) > 1.0] if len(tm) else np.zeros(0, bool)
|
| 122 |
+
if min_gap_ms and len(tm):
|
| 123 |
+
tys = np.concatenate(ty)[order]
|
| 124 |
+
last = -np.inf
|
| 125 |
+
for i in np.where(keep)[0]:
|
| 126 |
+
if tys[i] > 3:
|
| 127 |
+
continue
|
| 128 |
+
if tm[i] - last < min_gap_ms - seam_slack_ms: # slack for the timing residual inside a window
|
| 129 |
+
keep[i] = False
|
| 130 |
+
else:
|
| 131 |
+
last = tm[i]
|
| 132 |
+
out[n] = (tm[keep],) + tuple(np.concatenate(x)[order][keep] if x else np.zeros(0) for x in (ty, ln, sv))
|
| 133 |
+
return out
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def as_chart(arrs, sections, tier, kiai_p, t0, t1):
|
| 137 |
+
tm, ty, ln, sv = arrs
|
| 138 |
+
first, last = (tm[0], tm[-1]) if len(tm) else (t0, t1)
|
| 139 |
+
return {"tier": tier, "sections": sections, "time": tm, "type": ty.astype(int), "length_beats": ln, "sv": sv,
|
| 140 |
+
"kiai": decode_kiai(kiai_p, sections, first, last)}
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def make_arms_draw(model, planner, mel, sections, song, t0, t1, cal, device, seed, prior, protos, cutoffs, feat, b_song,
|
| 144 |
+
rest_band, arms):
|
| 145 |
+
"""One draw: {arm: {tier: chart}} and the settings used, all arms sharing the prior draw and the seeds."""
|
| 146 |
+
rng = np.random.default_rng(seed)
|
| 147 |
+
draw, bvec = prior.sample_set({t: feat for t in TIERS}, rng)
|
| 148 |
+
rng_h = np.random.default_rng(seed)
|
| 149 |
+
draw_h, _ = prior.sample_set({t: feat for t in TIERS}, rng_h) # same draw, separate rng for the human-amount arm
|
| 150 |
+
plans, plans_h, settings = {}, {}, {}
|
| 151 |
+
guide = guide_h = None
|
| 152 |
+
for t in sorted(TIERS, reverse=True): # v10c coordination: hardest tier first
|
| 153 |
+
o_t = planner_out(planner, feat, t, device)
|
| 154 |
+
d = np.array(draw[t], float)
|
| 155 |
+
d[2], d[3] = song_property_amounts(o_t, t, cutoffs, None, rng)
|
| 156 |
+
plan_t, _ = count_then_place(o_t, d, t, protos, cal["th_sustain"], sure_rest=0.05, rest_band=rest_band, guide=guide)
|
| 157 |
+
guide, plans[t] = plan_t, (b_song, plan_t)
|
| 158 |
+
settings[t] = d
|
| 159 |
+
hum = human_of(song, t)
|
| 160 |
+
if "amount_human" in arms and hum is not None:
|
| 161 |
+
hs = human_settings(mel, hum)
|
| 162 |
+
dh = np.array(draw_h[t], float)
|
| 163 |
+
if hs is not None:
|
| 164 |
+
dh[:6] = hs[:6]
|
| 165 |
+
ph, _ = count_then_place(o_t, dh, t, protos, cal["th_sustain"], sure_rest=0.05, rest_band=rest_band,
|
| 166 |
+
guide=guide_h)
|
| 167 |
+
guide_h, plans_h[t] = ph, (b_song, ph)
|
| 168 |
+
settings[f"{t}_human"] = dh
|
| 169 |
+
out = {a: {} for a in arms}
|
| 170 |
+
for t in TIERS:
|
| 171 |
+
_, _, kiai_p = frame_activations(model, mel, device, sections, t)
|
| 172 |
+
s_t = seed + 1000 * t
|
| 173 |
+
hum = human_of(song, t)
|
| 174 |
+
if {"argmax_mbr", "argmax_t09"} & set(arms):
|
| 175 |
+
r = run_windows(model, mel, sections, t, t0, t1, device, s_t, "pred", CANDS, plans[t])
|
| 176 |
+
out.get("argmax_mbr", {})[t] = as_chart(r["mbr"], sections, t, kiai_p, t0, t1)
|
| 177 |
+
out.get("argmax_t09", {})[t] = as_chart(r[CANDS[T09][0]], sections, t, kiai_p, t0, t1)
|
| 178 |
+
if {"sample_mbr", "sample_t09"} & set(arms):
|
| 179 |
+
r = run_windows(model, mel, sections, t, t0, t1, device, s_t, "sample", CANDS, plans[t])
|
| 180 |
+
out.get("sample_mbr", {})[t] = as_chart(r["mbr"], sections, t, kiai_p, t0, t1)
|
| 181 |
+
out.get("sample_t09", {})[t] = as_chart(r[CANDS[T09][0]], sections, t, kiai_p, t0, t1)
|
| 182 |
+
one = (CANDS[T09],)
|
| 183 |
+
if hum is None:
|
| 184 |
+
continue
|
| 185 |
+
if "class_human" in arms:
|
| 186 |
+
r = run_windows(model, mel, sections, t, t0, t1, device, s_t, "oracle_r", one, plans[t], hum, ("plan_r",))
|
| 187 |
+
out["class_human"][t] = as_chart(r[one[0][0]], sections, t, kiai_p, t0, t1)
|
| 188 |
+
if "amount_human" in arms and t in plans_h:
|
| 189 |
+
r = run_windows(model, mel, sections, t, t0, t1, device, s_t, "sample", one, plans_h[t])
|
| 190 |
+
out["amount_human"][t] = as_chart(r[one[0][0]], sections, t, kiai_p, t0, t1)
|
| 191 |
+
if "plan_human" in arms:
|
| 192 |
+
r = run_windows(model, mel, sections, t, t0, t1, device, s_t, "oracle", one, None, hum,
|
| 193 |
+
("plan_rho", "plan_r", "plan_gap"))
|
| 194 |
+
out["plan_human"][t] = as_chart(r[one[0][0]], sections, t, kiai_p, t0, t1)
|
| 195 |
+
return out, settings, bvec
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def main(argv=None):
|
| 199 |
+
p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 200 |
+
p.add_argument("--data", nargs="+", type=Path, required=True)
|
| 201 |
+
p.add_argument("--model", type=Path, required=True, help="b9")
|
| 202 |
+
p.add_argument("--encoder", type=Path, required=True, help="B0 v1, for the planner's music memory")
|
| 203 |
+
p.add_argument("--planner", type=Path, required=True, help="sp9")
|
| 204 |
+
p.add_argument("--thresholds", type=Path, required=True)
|
| 205 |
+
p.add_argument("--prior", type=Path, required=True)
|
| 206 |
+
p.add_argument("--protos", type=Path, required=True)
|
| 207 |
+
p.add_argument("--song-cutoffs", type=Path, required=True)
|
| 208 |
+
p.add_argument("--rest-band", type=float, nargs=2, default=(0.1, 0.6))
|
| 209 |
+
p.add_argument("--sets-file", type=Path, required=True)
|
| 210 |
+
p.add_argument("--arms", nargs="+", default=list(ARMS), choices=ARMS)
|
| 211 |
+
p.add_argument("--draws", type=int, default=2)
|
| 212 |
+
p.add_argument("--seed", type=int, default=0)
|
| 213 |
+
p.add_argument("--max-sets", type=int, default=0, help="stop after this many new sets (timing test)")
|
| 214 |
+
p.add_argument("--save-every", type=int, default=5)
|
| 215 |
+
p.add_argument("--out", type=Path, required=True)
|
| 216 |
+
a = p.parse_args(argv)
|
| 217 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 218 |
+
model = load_model(a.model, device)
|
| 219 |
+
enc = load_model(a.encoder, device).eval()
|
| 220 |
+
cal = json.loads(a.thresholds.read_text())["calibration"]
|
| 221 |
+
ck = torch.load(a.planner, map_location=device)
|
| 222 |
+
planner = sp.SongPlanner(ck["d_in"]).to(device).eval()
|
| 223 |
+
planner.load_state_dict(ck["model"])
|
| 224 |
+
prior = pickle.load(open(a.prior, "rb"))
|
| 225 |
+
protos = pickle.load(open(a.protos, "rb"))
|
| 226 |
+
cutoffs = json.loads(a.song_cutoffs.read_text())
|
| 227 |
+
a.out.mkdir(parents=True, exist_ok=True)
|
| 228 |
+
pk = {arm: a.out / f"mapsets_S1_{arm}.pkl" for arm in a.arms}
|
| 229 |
+
rec = {arm: (pickle.load(open(f, "rb")) if f.exists() else {}) for arm, f in pk.items()}
|
| 230 |
+
done = set.intersection(*(set(r) for r in rec.values())) if rec else set()
|
| 231 |
+
want = set(int(x) for x in a.sets_file.read_text().split()) - done
|
| 232 |
+
print(f"sets to do {len(want)} (done {len(done)}), arms {a.arms}", flush=True)
|
| 233 |
+
|
| 234 |
+
def save():
|
| 235 |
+
for arm, f in pk.items():
|
| 236 |
+
tmp = f.with_suffix(".tmp")
|
| 237 |
+
pickle.dump(rec[arm], open(tmp, "wb"))
|
| 238 |
+
tmp.replace(f)
|
| 239 |
+
|
| 240 |
+
n_new, t_start = 0, time.time()
|
| 241 |
+
for f in a.data:
|
| 242 |
+
if not want or (a.max_sets and n_new >= a.max_sets):
|
| 243 |
+
break
|
| 244 |
+
for s in [s for s in load_songs([f], mmap=True) if s["beatmapset_id"] in want]:
|
| 245 |
+
if song_split(s.get("song_key") or str(s["beatmapset_id"])) == "test":
|
| 246 |
+
raise ValueError(f"set {s['beatmapset_id']} is in the test split")
|
| 247 |
+
sid = int(s["beatmapset_id"])
|
| 248 |
+
mel = np.asarray(s["mel"], np.float32)
|
| 249 |
+
ref = max(s["charts"], key=lambda c: len(c["time"]))
|
| 250 |
+
sections = np.asarray(ref["sections"], np.float64)
|
| 251 |
+
t0 = min(float(c["time"][0]) for c in s["charts"]) - 2000.0
|
| 252 |
+
t1 = max(float(c["time"][-1]) for c in s["charts"])
|
| 253 |
+
feat, b_song = planner_rows(enc, mel, sections, device)
|
| 254 |
+
entries = {arm: {"song_key": s.get("song_key"), "sections": sections, "draws": []} for arm in a.arms}
|
| 255 |
+
t_set = time.time()
|
| 256 |
+
for k in range(a.draws):
|
| 257 |
+
charts, settings, bvec = make_arms_draw(model, planner, mel, sections, s, t0, t1, cal, device,
|
| 258 |
+
a.seed + sid + 7919 * k, prior, protos, cutoffs, feat, b_song,
|
| 259 |
+
tuple(a.rest_band), a.arms)
|
| 260 |
+
for arm in a.arms:
|
| 261 |
+
entries[arm]["draws"].append({"charts": charts[arm], "settings": settings, "b": bvec})
|
| 262 |
+
for arm in a.arms:
|
| 263 |
+
rec[arm][sid] = entries[arm]
|
| 264 |
+
n_new += 1
|
| 265 |
+
want.discard(sid)
|
| 266 |
+
notes = {arm: {t: len(c["time"]) for t, c in entries[arm]["draws"][0]["charts"].items()} for arm in a.arms}
|
| 267 |
+
print(f"{sid}: {time.time() - t_set:.1f} s (total {(time.time() - t_start) / 60:.1f} min, {n_new} sets) "
|
| 268 |
+
f"notes draw0 {notes}", flush=True)
|
| 269 |
+
if n_new % a.save_every == 0:
|
| 270 |
+
save()
|
| 271 |
+
if a.max_sets and n_new >= a.max_sets:
|
| 272 |
+
break
|
| 273 |
+
save()
|
| 274 |
+
print("done", n_new, "new sets", flush=True)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
if __name__ == "__main__":
|
| 278 |
+
main()
|
chartgen/v11/s2_arms.py
ADDED
|
@@ -0,0 +1,512 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""v11 stage 2 end-to-end arms (reports/v11 階段 2 預先登記:位置圖 R.md, section 4.6).
|
| 2 |
+
|
| 3 |
+
Every arm starts from the stage-1 draw of the set (same prior draw, song cutoffs, count_then_place and hardest-tier-
|
| 4 |
+
first coordination, same seeds as v11.s1_arms), generates with b9, one T=0.9 candidate, no MBR, no argmax:
|
| 5 |
+
|
| 6 |
+
A bar plan: columns 0, 2, 3, 16 (rests, big notes, roll starts, roll cover) from count_then_place with the
|
| 7 |
+
human chart's song-level amounts (as amount_human); columns 1, 4, 5, 6-15 and the section fields
|
| 8 |
+
(plan_rho, plan_r, plan_gap) from one pseudo-chart of R, shifted in turn to the human density
|
| 9 |
+
(chart_settings[5], all positions), triplet amount ([2], 1/3-1/6-1/12 positions) and 1/8 amount ([3],
|
| 10 |
+
1/8-1/16 positions)
|
| 11 |
+
A_prior A with the prior map
|
| 12 |
+
B columns 0, 2, 3, 16 as sample_t09; pseudo-chart of R with no density / triplet shift and the 1/8 amount
|
| 13 |
+
shifted to a value drawn from the 2022+ train charts of the same tier and tempo band
|
| 14 |
+
B_prior B with the prior map
|
| 15 |
+
B_simple B with the simple-baseline map
|
| 16 |
+
C the human chart's bar plan and rest mask, b9's own sampled section plan
|
| 17 |
+
G8 stage 5a: B, but the 1/8 family follows R's song-level readout (v11.s5a): readout below the tier's theta ->
|
| 18 |
+
the 1/8-family positions are never drawn in the pseudo-chart and are closed in b9's decoding; at or above
|
| 19 |
+
theta -> the 1/8-family logits are shifted so that the pseudo-chart's 1/8-family note share equals the
|
| 20 |
+
amount given by the stage-5a rule. No tempo-band draw
|
| 21 |
+
G8T G8, and the triplet-family logits are shifted so that the pseudo-chart's triplet setting equals the value
|
| 22 |
+
predicted from R's triplet readout (line fitted on the tuning songs)
|
| 23 |
+
|
| 24 |
+
Pseudo-chart rules (addendum of 2026-11-20 first: the triplet- and 1/8-family logits of each map divided by that
|
| 25 |
+
map's tuning-set temperature tau, --taus): notes only in measures with play = 1 in the base plan (positions elsewhere are never drawn); a
|
| 26 |
+
shift is a song-wide logit offset found by bisection on 16 draws with fixed noise; a target of 0 is not shifted, but
|
| 27 |
+
measures above the threshold (triplet 0.3, 1/8 0.25) are redrawn up to 50 times; a played measure without notes is
|
| 28 |
+
redrawn up to 100 times, then one position is drawn in proportion to p. Seeds: final draw default_rng([seed, set, k,
|
| 29 |
+
tier, 1]), bisection noise [.., 2], 1/8 target [.., 8].
|
| 30 |
+
|
| 31 |
+
Output: <out>/mapsets_S2_<arm>.pkl in the gen_mapset format, each draw also holding the decided plan, the pseudo-chart
|
| 32 |
+
grid and the shift targets per tier.
|
| 33 |
+
|
| 34 |
+
python -m chartgen.v11.s2_arms --data f*.pkl --model b9.pt --encoder best_v1.pt --planner sp9.pt \\
|
| 35 |
+
--thresholds thresholds.json --prior chart_prior.pkl --protos protos.pkl --song-cutoffs cutoffs.json \\
|
| 36 |
+
--maps-R val_R.npz --calib-R calib_R.json --maps-prior val_prior.npz --maps-simple val_simple.npz \\
|
| 37 |
+
--calib-simple calib_simple.json --eighth-table eighth_draw_table.json --sets-file sets.txt --out runs/v11_s2
|
| 38 |
+
python -m chartgen.v11.s2_arms --selftest
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
from __future__ import annotations
|
| 42 |
+
|
| 43 |
+
import argparse
|
| 44 |
+
import json
|
| 45 |
+
import pickle
|
| 46 |
+
import time
|
| 47 |
+
from pathlib import Path
|
| 48 |
+
|
| 49 |
+
import numpy as np
|
| 50 |
+
import torch
|
| 51 |
+
|
| 52 |
+
from chartgen import song_planner as sp
|
| 53 |
+
from chartgen.dataset import bar_plan, beat_ms, load_songs, make_example
|
| 54 |
+
from chartgen.gen_mapset import CANDS, planner_out, planner_rows, song_property_amounts
|
| 55 |
+
from chartgen.infer import frame_activations, load_model
|
| 56 |
+
from chartgen.plan_decide import count_then_place
|
| 57 |
+
from chartgen.rhythm_eval import main_bpm
|
| 58 |
+
from chartgen.rhythm_eval2 import TEMPO
|
| 59 |
+
from chartgen.train import song_split
|
| 60 |
+
from chartgen.v11.rmap_data import Group, bits_to_bool, beat_table
|
| 61 |
+
from chartgen.v11.rmap_eval import Maps, apply_calib, load_calib
|
| 62 |
+
from chartgen.v11.rmap_pseudo import FAMILY_POS, FINE_POS, TRIP_POS, Bars, Sampler, apply_tau, masks_to_grid, popcount, \
|
| 63 |
+
shift_to_target
|
| 64 |
+
from chartgen.v11.s1_arms import T09, as_chart, human_of, human_settings, run_windows
|
| 65 |
+
|
| 66 |
+
TIERS = (3, 4)
|
| 67 |
+
ARMS = ("A", "A_prior", "B", "B_prior", "B_simple", "C", "Bc", "G8", "G8T")
|
| 68 |
+
MAP_OF = {"A": "R", "A_prior": "prior", "B": "R", "B_prior": "prior", "B_simple": "simple", "Bc": "R", "G8": "R",
|
| 69 |
+
"G8T": "R"}
|
| 70 |
+
S5A_ARMS = ("G8", "G8T")
|
| 71 |
+
KEEP_COLS = [0, 2, 3, 16]
|
| 72 |
+
HIT_COLS = [1, 2, 4, 5] + list(range(6, 16))
|
| 73 |
+
ONE = (CANDS[T09],)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def group_uid(sid: int, sections) -> str:
|
| 77 |
+
return Group(int(sid), "", "", 0, None, np.asarray(sections, np.float64)).uid
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# ------------------------------------------------------------------------------------------------ pseudo-chart
|
| 81 |
+
|
| 82 |
+
def bar_counts(masks, bars, sel=None):
|
| 83 |
+
c = popcount(masks, sel)
|
| 84 |
+
out = np.zeros(bars.n)
|
| 85 |
+
np.add.at(out, bars.row[bars.ok], c[bars.ok])
|
| 86 |
+
return out
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def make_pseudo(smp: Sampler, lg: np.ndarray, table, bars: Bars, play: np.ndarray, targets: list, seed_parts,
|
| 90 |
+
ban: np.ndarray | None = None):
|
| 91 |
+
"""One pseudo-chart (per-beat masks) and the shifts used. targets: [(family, setting, value or None)].
|
| 92 |
+
ban (stage 5a): bool mask over the 24 positions that are never drawn."""
|
| 93 |
+
n = len(table)
|
| 94 |
+
valid = bits_to_bool(table.valid).copy()
|
| 95 |
+
if ban is not None:
|
| 96 |
+
valid[:, np.asarray(ban, bool)] = False
|
| 97 |
+
inplan = bars.ok
|
| 98 |
+
rest_beat = np.zeros(n, bool)
|
| 99 |
+
rest_beat[inplan] = play[bars.row[inplan]] < 0.5
|
| 100 |
+
valid[rest_beat] = False
|
| 101 |
+
S = smp.scores(lg, valid)
|
| 102 |
+
G16 = smp.gumbel(np.random.default_rng([*seed_parts, 2]), 16, n)
|
| 103 |
+
shifts, zero_rule = {}, {}
|
| 104 |
+
for fam, which, target in targets:
|
| 105 |
+
if target is None:
|
| 106 |
+
continue
|
| 107 |
+
if isinstance(target, tuple): # stage 5a: ("scale", c) = c x the mean of the 16 draws before the shift
|
| 108 |
+
from chartgen.v11.rmap_pseudo import fast_settings
|
| 109 |
+
base16 = fast_settings(smp.draw(S, G16), bars)[which]
|
| 110 |
+
base16 = float(np.mean(np.nan_to_num(base16, nan=0.0)))
|
| 111 |
+
target = min(1.0, float(target[1]) * base16)
|
| 112 |
+
if target <= 0:
|
| 113 |
+
zero_rule[fam] = 0.3 if fam == "triplet" else 0.25
|
| 114 |
+
continue
|
| 115 |
+
d, got = shift_to_target(smp, S, G16, FAMILY_POS[fam], bars, which, float(target))
|
| 116 |
+
S = S + d * smp.family_count(FAMILY_POS[fam])[None]
|
| 117 |
+
shifts[fam] = {"target": float(target), "delta": float(d), "mean_16": float(got)}
|
| 118 |
+
rng = np.random.default_rng([*seed_parts, 1])
|
| 119 |
+
m = smp.draw(S, smp.gumbel(rng, 1, n))[0]
|
| 120 |
+
|
| 121 |
+
def redraw(beats_idx):
|
| 122 |
+
m[beats_idx] = smp.draw(S[beats_idx], smp.gumbel(rng, 1, len(beats_idx)))[0]
|
| 123 |
+
|
| 124 |
+
for fam, thr in zero_rule.items():
|
| 125 |
+
sel = TRIP_POS if fam == "triplet" else FINE_POS
|
| 126 |
+
for _ in range(50):
|
| 127 |
+
h, f = bar_counts(m, bars), bar_counts(m, bars, sel)
|
| 128 |
+
bad = np.where((h > 0) & (f / np.maximum(h, 1) > thr))[0]
|
| 129 |
+
if not len(bad):
|
| 130 |
+
break
|
| 131 |
+
redraw(np.where(inplan & np.isin(bars.row, bad))[0])
|
| 132 |
+
n_forced = 0
|
| 133 |
+
play_rows = np.where(play > 0.5)[0]
|
| 134 |
+
for _ in range(100):
|
| 135 |
+
h = bar_counts(m, bars)
|
| 136 |
+
empty = play_rows[h[play_rows] == 0]
|
| 137 |
+
cand = [b for b in empty if valid[inplan & (bars.row == b)].any()]
|
| 138 |
+
if not cand:
|
| 139 |
+
break
|
| 140 |
+
redraw(np.where(inplan & np.isin(bars.row, cand))[0])
|
| 141 |
+
h = bar_counts(m, bars)
|
| 142 |
+
for b in play_rows[h[play_rows] == 0]:
|
| 143 |
+
rows_b = np.where(inplan & (bars.row == b))[0]
|
| 144 |
+
v = valid[rows_b]
|
| 145 |
+
if not v.any():
|
| 146 |
+
continue
|
| 147 |
+
p = 1 / (1 + np.exp(-np.clip(lg[rows_b], -30, 30))) * v
|
| 148 |
+
flat = p.reshape(-1) / p.sum()
|
| 149 |
+
j = rng.choice(len(flat), p=flat)
|
| 150 |
+
m[rows_b[j // 24]] |= np.int64(1) << (j % 24)
|
| 151 |
+
n_forced += 1
|
| 152 |
+
return m, {"shifts": shifts, "zero_rule": sorted(zero_rule), "forced_notes": n_forced}
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def pseudo_chart(grid, sections, tier):
|
| 156 |
+
b = grid / 48.0
|
| 157 |
+
n = len(grid)
|
| 158 |
+
return {"tier": tier, "sections": sections, "time": beat_ms(np.asarray(sections, np.float64), b), "beat": b,
|
| 159 |
+
"type": np.zeros(n, np.int8), "length_beats": np.zeros(n, np.float32), "delta_ms": np.zeros(n, np.float32),
|
| 160 |
+
"sv": np.ones(n, np.float32), "kiai": np.zeros((0, 2))}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def merged_plan(grid, b_song, sections, base_plan):
|
| 164 |
+
H = bar_plan(grid, np.zeros(len(grid), np.int64), b_song, np.asarray(sections, np.float64), None, len(base_plan))
|
| 165 |
+
out = H.copy()
|
| 166 |
+
out[:, KEEP_COLS] = base_plan[:, KEEP_COLS]
|
| 167 |
+
off = out[:, 0] < 0.5
|
| 168 |
+
out[np.ix_(off, HIT_COLS)] = 0.0
|
| 169 |
+
return out
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
# ------------------------------------------------------------------------------------------------ draw
|
| 173 |
+
|
| 174 |
+
def eighth_target(table, tier, sections, parts):
|
| 175 |
+
bpm = main_bpm(sections)
|
| 176 |
+
band = next(i for i, (lo, hi) in enumerate(TEMPO) if lo <= bpm < hi)
|
| 177 |
+
d = table[str(tier)][str(band)]
|
| 178 |
+
pool = d["modern"] if sum(len(v) for v in d["modern"].values()) >= 30 else d["all"]
|
| 179 |
+
rng = np.random.default_rng(parts)
|
| 180 |
+
songs = sorted(pool)
|
| 181 |
+
vals = pool[songs[int(rng.integers(len(songs)))]]
|
| 182 |
+
return float(vals[int(rng.integers(len(vals)))])
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def replace_rests(plan: np.ndarray, score: np.ndarray) -> np.ndarray:
|
| 186 |
+
"""Stage 4d-3: keep the plan's number of inside rests but move them to the highest-scoring rows. Rows with a roll
|
| 187 |
+
start or roll cover stay as they are; a row that becomes a rest loses its big-note share, a row that stops being a
|
| 188 |
+
rest is played with no big notes (the pseudo-chart then fills it)."""
|
| 189 |
+
plan = np.array(plan, np.float32, copy=True)
|
| 190 |
+
n = min(len(plan), len(score))
|
| 191 |
+
roll = (plan[:n, 3] > 0.5) | (plan[:n, 16] > 0)
|
| 192 |
+
act = (plan[:n, 0] > 0.5) | roll
|
| 193 |
+
idx = np.where(act)[0]
|
| 194 |
+
if len(idx) < 2:
|
| 195 |
+
return plan
|
| 196 |
+
inside = np.zeros(n, bool)
|
| 197 |
+
inside[idx.min():idx.max() + 1] = True
|
| 198 |
+
k = int((inside & ~act).sum())
|
| 199 |
+
strict = inside.copy()
|
| 200 |
+
strict[[idx.min(), idx.max()]] = False # the first and last active rows keep the song's span
|
| 201 |
+
cand = np.where(strict & ~roll)[0]
|
| 202 |
+
new_rest = np.zeros(n, bool)
|
| 203 |
+
if k > 0 and len(cand):
|
| 204 |
+
new_rest[cand[np.argsort(-score[cand], kind="stable")[:k]]] = True
|
| 205 |
+
flip_off = strict & ~roll & new_rest & (plan[:n, 0] > 0.5)
|
| 206 |
+
flip_on = strict & ~roll & ~new_rest & (plan[:n, 0] < 0.5)
|
| 207 |
+
plan[:n][flip_off, 0] = 0.0
|
| 208 |
+
plan[:n][flip_off, 2] = 0.0
|
| 209 |
+
plan[:n][flip_on, 0] = 1.0
|
| 210 |
+
return plan
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def make_draw(ctx, song, sections, t0, t1, feat, b_song, k, arms):
|
| 214 |
+
model, planner, cal, device = ctx["model"], ctx["planner"], ctx["cal"], ctx["device"]
|
| 215 |
+
prior, protos, cutoffs, a = ctx["prior"], ctx["protos"], ctx["cutoffs"], ctx["args"]
|
| 216 |
+
sid = int(song["beatmapset_id"])
|
| 217 |
+
mel = ctx["mel"]
|
| 218 |
+
seed = a.seed + sid + 7919 * k
|
| 219 |
+
rng = np.random.default_rng(seed)
|
| 220 |
+
draw, bvec = prior.sample_set({t: feat for t in TIERS}, rng)
|
| 221 |
+
rng_h = np.random.default_rng(seed)
|
| 222 |
+
draw_h, _ = prior.sample_set({t: feat for t in TIERS}, rng_h)
|
| 223 |
+
plans, plans_h, settings, hset = {}, {}, {}, {}
|
| 224 |
+
guide = guide_h = None
|
| 225 |
+
for t in sorted(TIERS, reverse=True): # identical to v11.s1_arms.make_arms_draw
|
| 226 |
+
o_t = planner_out(planner, feat, t, device)
|
| 227 |
+
d = np.array(draw[t], float)
|
| 228 |
+
d[2], d[3] = song_property_amounts(o_t, t, cutoffs, None, rng)
|
| 229 |
+
plan_t, _ = count_then_place(o_t, d, t, protos, cal["th_sustain"], sure_rest=0.05, rest_band=ctx["rest_band"],
|
| 230 |
+
guide=guide)
|
| 231 |
+
rs = ctx["rest_scores"].get(sid, {})
|
| 232 |
+
if t in rs and rs.get("b_song") == int(b_song) and rs.get("rows") == len(plan_t):
|
| 233 |
+
plan_t = replace_rests(plan_t, rs[t]) # stage 4d-3: model rest placement
|
| 234 |
+
guide, plans[t] = plan_t, plan_t
|
| 235 |
+
settings[t] = d
|
| 236 |
+
hum = human_of(song, t)
|
| 237 |
+
if hum is not None:
|
| 238 |
+
hs = human_settings(mel, hum)
|
| 239 |
+
if hs is not None:
|
| 240 |
+
dh = np.array(draw_h[t], float)
|
| 241 |
+
dh[:6] = hs[:6]
|
| 242 |
+
ph, _ = count_then_place(o_t, dh, t, protos, cal["th_sustain"], sure_rest=0.05,
|
| 243 |
+
rest_band=ctx["rest_band"], guide=guide_h)
|
| 244 |
+
guide_h, plans_h[t] = ph, ph
|
| 245 |
+
hset[t] = hs
|
| 246 |
+
uid = group_uid(sid, sections)
|
| 247 |
+
table = ctx["table"]
|
| 248 |
+
bars = Bars(sections, table.beat, b_song, len(feat))
|
| 249 |
+
out = {arm: {} for arm in arms}
|
| 250 |
+
extra = {arm: {} for arm in arms}
|
| 251 |
+
pre_c = {}
|
| 252 |
+
if "Bc" in arms and uid in ctx["maps"]["R"]["maps"]:
|
| 253 |
+
# stage 4c: both tiers' pseudo-charts first (Inner Oni, then Oni as a subset), coupled noise, no tau
|
| 254 |
+
from chartgen.v11.s4c_sampler import make_pseudo_coupled, measure_units
|
| 255 |
+
lg_all = apply_calib(ctx["maps"]["R"]["maps"][uid], ctx["maps"]["R"]["calib"])
|
| 256 |
+
p4 = 1 / (1 + np.exp(-np.clip(lg_all[:, :, 4], -30, 30)))
|
| 257 |
+
unit, by_row = measure_units(p4, bars, plans[4][:, 0], a.coupled_s0)
|
| 258 |
+
for t in (4, 3):
|
| 259 |
+
tg = [("eighth", "eighth", eighth_target(ctx["eighth"], t, sections, [a.seed, sid, k, t, 8]))]
|
| 260 |
+
pre_c[t] = make_pseudo_coupled(ctx["smp"], lg_all[:, :, t], table, bars, plans[t][:, 0], tg,
|
| 261 |
+
[a.seed, sid, k, 4], unit, by_row, a.coupled_lam,
|
| 262 |
+
upper=pre_c[4][0] if t == 3 else None, conc=a.coupled_conc)
|
| 263 |
+
pre_c[t][1]["targets"] = tg
|
| 264 |
+
for t in TIERS:
|
| 265 |
+
_, _, kiai_p = frame_activations(model, mel, device, sections, t)
|
| 266 |
+
ctx["kiai_p"][t] = kiai_p.astype(np.float16) # stage 4b: kept for recalibrating the kiai threshold
|
| 267 |
+
s_t = seed + 1000 * t
|
| 268 |
+
hum = human_of(song, t)
|
| 269 |
+
for arm in arms:
|
| 270 |
+
if arm == "C":
|
| 271 |
+
if hum is None:
|
| 272 |
+
continue
|
| 273 |
+
r = run_windows(model, mel, sections, t, t0, t1, device, s_t, "sample", ONE, None, hum)
|
| 274 |
+
out[arm][t] = as_chart(r[ONE[0][0]], sections, t, kiai_p, t0, t1)
|
| 275 |
+
continue
|
| 276 |
+
is_a = arm.startswith("A")
|
| 277 |
+
if is_a and t not in plans_h:
|
| 278 |
+
continue
|
| 279 |
+
src = ctx["maps"][MAP_OF[arm]]
|
| 280 |
+
if uid not in src["maps"]:
|
| 281 |
+
continue
|
| 282 |
+
lg = apply_tau(apply_calib(src["maps"][uid], src["calib"])[:, :, t],
|
| 283 |
+
ctx["taus"].get(MAP_OF[arm], {}).get(str(t)))
|
| 284 |
+
base = plans_h[t] if is_a else plans[t]
|
| 285 |
+
if is_a:
|
| 286 |
+
hs = hset[t]
|
| 287 |
+
targets = [("all", "density", hs[5]), ("triplet", "triplet", hs[2]), ("eighth", "eighth", hs[3])]
|
| 288 |
+
else:
|
| 289 |
+
targets = [("eighth", "eighth", eighth_target(ctx["eighth"], t, sections, [a.seed, sid, k, t, 8]))]
|
| 290 |
+
phase_ok, gate = None, None
|
| 291 |
+
if arm in S5A_ARMS:
|
| 292 |
+
from chartgen.v11 import s5a
|
| 293 |
+
P = ctx["s5a"]
|
| 294 |
+
lg_cal = apply_calib(src["maps"][uid], src["calib"])[:, :, t]
|
| 295 |
+
share = s5a.eighth_share(lg_cal)
|
| 296 |
+
on = P.gate(t, share)
|
| 297 |
+
targets, ban = [], None
|
| 298 |
+
gate = {"share": share, "on": on}
|
| 299 |
+
if arm == "G8T":
|
| 300 |
+
ro = (s5a.triplet_readout(ctx["smp"], lg_cal, bits_to_bool(table.valid), bars, [a.seed, sid, t, 5])
|
| 301 |
+
if P.needs_readout else None)
|
| 302 |
+
targets.append(("triplet", "triplet", P.triplet_target(t, ro, float((base[:, 0] > 0.5).sum()))))
|
| 303 |
+
gate["triplet_readout"] = ro
|
| 304 |
+
if on:
|
| 305 |
+
amt = P.eighth_amount(t, share, np.random.default_rng([a.seed, sid, k, t, 8]))
|
| 306 |
+
targets.append(("eighth", "eighth_share", amt))
|
| 307 |
+
else:
|
| 308 |
+
ban, phase_ok = s5a.EIGHTH, s5a.PHASE_NO_EIGHTH
|
| 309 |
+
m, info = make_pseudo(ctx["smp"], lg, table, bars, base[:, 0], targets, [a.seed, sid, k, t], ban=ban)
|
| 310 |
+
elif arm == "Bc":
|
| 311 |
+
m, info = pre_c[t]
|
| 312 |
+
targets = info["targets"]
|
| 313 |
+
else:
|
| 314 |
+
m, info = make_pseudo(ctx["smp"], lg, table, bars, base[:, 0], targets, [a.seed, sid, k, t])
|
| 315 |
+
grid = masks_to_grid(table.beat, m)
|
| 316 |
+
plan = merged_plan(grid, b_song, sections, base)
|
| 317 |
+
pc = pseudo_chart(grid, sections, t)
|
| 318 |
+
r = run_windows(model, mel, sections, t, t0, t1, device, s_t, "oracle", ONE, (b_song, plan), pc,
|
| 319 |
+
("plan_rho", "plan_r", "plan_gap"), min_gap_ms=ctx["min_gap"].get(str(t)),
|
| 320 |
+
phase_ok=phase_ok, **({"seam_slack_ms": 1.0} if arm in S5A_ARMS else {}))
|
| 321 |
+
out[arm][t] = as_chart(r[ONE[0][0]], sections, t, kiai_p, t0, t1)
|
| 322 |
+
extra[arm][t] = {"plan": (int(b_song), plan.astype(np.float16)), "pseudo": grid.astype(np.int32),
|
| 323 |
+
"targets": targets, **info}
|
| 324 |
+
if gate is not None:
|
| 325 |
+
if not gate["on"]: # stage 5a fix after the first run: the ban also holds on the chart's own red lines
|
| 326 |
+
out[arm][t], gate["dropped"] = s5a.drop_eighth_family(out[arm][t])
|
| 327 |
+
extra[arm][t]["gate"] = gate
|
| 328 |
+
return out, extra, settings, bvec
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
# ------------------------------------------------------------------------------------------------ self-test
|
| 332 |
+
|
| 333 |
+
def selftest(shard="data/pilot/features/taiko-00000.pkl"):
|
| 334 |
+
"""Pre-run check 2: the degenerate map (1 on a human chart's hit positions, 0 elsewhere) reproduces the chart's
|
| 335 |
+
bar plan columns 1, 4, 5, 6-15, its hit-only plan_rho and plan_r; the merged plan keeps the base columns 0, 2, 3,
|
| 336 |
+
16; positions after a red line inside a cut beat never get notes."""
|
| 337 |
+
from chartgen.song_planner import chart_rows
|
| 338 |
+
from chartgen.v11.patterns import GRID, POSITIONS
|
| 339 |
+
from chartgen.v11.rmap_data import POS
|
| 340 |
+
smp = Sampler()
|
| 341 |
+
vocab = set(smp.masks.tolist())
|
| 342 |
+
songs = load_songs([shard], mmap=True)
|
| 343 |
+
n_ok = n_cut = 0
|
| 344 |
+
for s in songs:
|
| 345 |
+
if song_split(s.get("song_key") or str(s["beatmapset_id"])) == "test":
|
| 346 |
+
continue
|
| 347 |
+
for ch in s["charts"]:
|
| 348 |
+
if int(ch["tier"]) not in TIERS:
|
| 349 |
+
continue
|
| 350 |
+
sec = np.asarray(ch["sections"], np.float64)
|
| 351 |
+
hit = np.asarray(ch["type"]) <= 3
|
| 352 |
+
g = np.unique(np.round(np.asarray(ch["beat"])[hit] * GRID).astype(np.int64))
|
| 353 |
+
if not np.isin(g % GRID, POSITIONS).all():
|
| 354 |
+
continue
|
| 355 |
+
table = beat_table(sec, len(s["mel"]))
|
| 356 |
+
if not np.isin(g // GRID, table.beat).all():
|
| 357 |
+
continue
|
| 358 |
+
bits = np.zeros((len(table), 24), bool)
|
| 359 |
+
row = np.searchsorted(table.beat, g // GRID)
|
| 360 |
+
bits[row, np.searchsorted(POS, g % GRID)] = True
|
| 361 |
+
masks = (bits.astype(np.int64) << np.arange(24)).sum(1)
|
| 362 |
+
if not set(masks[masks > 0].tolist()) <= vocab:
|
| 363 |
+
continue
|
| 364 |
+
if (bits & ~bits_to_bool(table.valid)).any():
|
| 365 |
+
continue
|
| 366 |
+
_, Hfull, b0 = chart_rows(np.zeros(((len(s["mel"]) + 1) // 2, 1), np.float32), ch)
|
| 367 |
+
bars = Bars(sec, table.beat, b0, len(Hfull))
|
| 368 |
+
lg = np.where(bits, 30.0, -30.0).astype(np.float32)
|
| 369 |
+
m, _ = make_pseudo(smp, lg, table, bars, Hfull[:, 0], [], [0, int(s["beatmapset_id"]), 0, int(ch["tier"])])
|
| 370 |
+
grid = masks_to_grid(table.beat, m)
|
| 371 |
+
assert np.array_equal(grid, g), (ch["beatmap_id"], len(grid), len(g))
|
| 372 |
+
plan = merged_plan(grid, b0, sec, Hfull)
|
| 373 |
+
ref = bar_plan(g, np.zeros(len(g), np.int64), b0, sec, None, len(Hfull))
|
| 374 |
+
cols = [1, 4, 5] + list(range(6, 16))
|
| 375 |
+
assert np.allclose(plan[:, cols], ref[:, cols], atol=1e-6), ch["beatmap_id"]
|
| 376 |
+
assert np.allclose(plan[:, KEEP_COLS], Hfull[:, KEEP_COLS])
|
| 377 |
+
hc = {**ch, "time": np.asarray(ch["time"])[hit], "beat": np.asarray(ch["beat"])[hit],
|
| 378 |
+
"type": np.zeros(hit.sum(), np.int8), "length_beats": np.zeros(hit.sum(), np.float32),
|
| 379 |
+
"delta_ms": np.zeros(hit.sum(), np.float32), "sv": np.ones(hit.sum(), np.float32)}
|
| 380 |
+
pc = pseudo_chart(grid, sec, int(ch["tier"]))
|
| 381 |
+
for st in (0, 2000):
|
| 382 |
+
if st * 10 > np.asarray(ch["time"])[-1]:
|
| 383 |
+
continue
|
| 384 |
+
e1, e2 = make_example({"mel": s["mel"]}, hc, st), make_example({"mel": s["mel"]}, pc, st)
|
| 385 |
+
assert np.allclose(e1.plan_rho, e2.plan_rho) and np.array_equal(e1.plan_r, e2.plan_r), ch["beatmap_id"]
|
| 386 |
+
n_ok += 1
|
| 387 |
+
# reverse test: every position set to 1; positions invalid in the table must stay empty
|
| 388 |
+
inv = ~bits_to_bool(table.valid)
|
| 389 |
+
if inv.any():
|
| 390 |
+
m2, _ = make_pseudo(smp, np.full((len(table), 24), 30.0, np.float32), table, bars,
|
| 391 |
+
np.ones(len(Hfull)), [], [0, 0, 0, 0])
|
| 392 |
+
got = bits_to_bool(m2.astype(np.uint32))
|
| 393 |
+
assert not (got & inv).any()
|
| 394 |
+
n_cut += 1
|
| 395 |
+
print(f"degenerate-map test passed on {n_ok} charts; red-line cut test on {n_cut} charts")
|
| 396 |
+
assert n_ok > 20
|
| 397 |
+
print("selftest ok")
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
# ------------------------------------------------------------------------------------------------ main
|
| 401 |
+
|
| 402 |
+
def main(argv=None):
|
| 403 |
+
p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 404 |
+
p.add_argument("--selftest", action="store_true")
|
| 405 |
+
p.add_argument("--data", nargs="+", type=Path)
|
| 406 |
+
p.add_argument("--model", type=Path)
|
| 407 |
+
p.add_argument("--encoder", type=Path)
|
| 408 |
+
p.add_argument("--planner", type=Path)
|
| 409 |
+
p.add_argument("--thresholds", type=Path)
|
| 410 |
+
p.add_argument("--prior", type=Path)
|
| 411 |
+
p.add_argument("--protos", type=Path)
|
| 412 |
+
p.add_argument("--song-cutoffs", type=Path)
|
| 413 |
+
p.add_argument("--maps-R", type=Path)
|
| 414 |
+
p.add_argument("--calib-R", type=Path)
|
| 415 |
+
p.add_argument("--maps-prior", type=Path)
|
| 416 |
+
p.add_argument("--maps-simple", type=Path)
|
| 417 |
+
p.add_argument("--calib-simple", type=Path)
|
| 418 |
+
p.add_argument("--eighth-table", type=Path)
|
| 419 |
+
p.add_argument("--taus", type=Path, help="sampling temperatures (addendum of 2026-11-20), rmap_eval taufit")
|
| 420 |
+
p.add_argument("--rest-band", type=float, nargs=2, default=(0.1, 0.6))
|
| 421 |
+
p.add_argument("--sets-file", type=Path)
|
| 422 |
+
p.add_argument("--arms", nargs="+", default=list(ARMS), choices=ARMS)
|
| 423 |
+
p.add_argument("--draws", type=int, default=2)
|
| 424 |
+
p.add_argument("--seed", type=int, default=0)
|
| 425 |
+
p.add_argument("--max-sets", type=int, default=0)
|
| 426 |
+
p.add_argument("--save-every", type=int, default=5)
|
| 427 |
+
p.add_argument("--min-gap-json", type=Path, help="stage 4b: {tier: shortest allowed gap in ms} enforced in decoding")
|
| 428 |
+
p.add_argument("--keep-kiai-p", action="store_true", help="stage 4b: store b9's kiai probabilities per tier")
|
| 429 |
+
p.add_argument("--rest-scores", type=Path, help="stage 4d-3: {set: {tier: row scores}} for model rest placement")
|
| 430 |
+
p.add_argument("--coupled-lam", type=float, default=0.5, help="stage 4c arm Bc: in-measure noise sharing")
|
| 431 |
+
p.add_argument("--coupled-s0", type=float, default=0.8, help="stage 4c arm Bc: similarity to join a unit")
|
| 432 |
+
p.add_argument("--coupled-conc", type=float, default=1.0, help="stage 4c arm Bc: measure-level fine concentration")
|
| 433 |
+
p.add_argument("--s5a-params", type=Path, help="stage 5a arms G8 / G8T: params.json of reports/figs/v11_s5a_tune.py")
|
| 434 |
+
p.add_argument("--out", type=Path)
|
| 435 |
+
a = p.parse_args(argv)
|
| 436 |
+
if a.selftest:
|
| 437 |
+
selftest()
|
| 438 |
+
return
|
| 439 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 440 |
+
ck = torch.load(a.planner, map_location=device)
|
| 441 |
+
planner = sp.SongPlanner(ck["d_in"]).to(device).eval()
|
| 442 |
+
planner.load_state_dict(ck["model"])
|
| 443 |
+
ctx = {"model": load_model(a.model, device), "planner": planner, "device": device, "args": a,
|
| 444 |
+
"cal": json.loads(a.thresholds.read_text())["calibration"], "prior": pickle.load(open(a.prior, "rb")),
|
| 445 |
+
"protos": pickle.load(open(a.protos, "rb")), "cutoffs": json.loads(a.song_cutoffs.read_text()),
|
| 446 |
+
"rest_band": tuple(a.rest_band), "smp": Sampler(), "eighth": json.loads(a.eighth_table.read_text()),
|
| 447 |
+
"taus": json.loads(a.taus.read_text())["tau"] if a.taus else {},
|
| 448 |
+
"min_gap": json.loads(a.min_gap_json.read_text()) if a.min_gap_json else {}, "kiai_p": {},
|
| 449 |
+
"rest_scores": pickle.load(open(a.rest_scores, "rb")) if a.rest_scores else {},
|
| 450 |
+
"maps": {"R": {"maps": Maps(a.maps_R), "calib": load_calib(a.calib_R)},
|
| 451 |
+
"prior": {"maps": Maps(a.maps_prior), "calib": None},
|
| 452 |
+
"simple": {"maps": Maps(a.maps_simple), "calib": load_calib(a.calib_simple)}}}
|
| 453 |
+
if any(arm in S5A_ARMS for arm in a.arms):
|
| 454 |
+
from chartgen.v11.s5a import Params
|
| 455 |
+
ctx["s5a"] = Params(a.s5a_params)
|
| 456 |
+
enc = load_model(a.encoder, device).eval()
|
| 457 |
+
a.out.mkdir(parents=True, exist_ok=True)
|
| 458 |
+
pk = {arm: a.out / f"mapsets_S2_{arm}.pkl" for arm in a.arms}
|
| 459 |
+
rec = {arm: (pickle.load(open(f, "rb")) if f.exists() else {}) for arm, f in pk.items()}
|
| 460 |
+
done = set.intersection(*(set(r) for r in rec.values())) if rec else set()
|
| 461 |
+
want = set(int(x) for x in a.sets_file.read_text().split()) - done
|
| 462 |
+
print(f"sets to do {len(want)} (done {len(done)}), arms {a.arms}", flush=True)
|
| 463 |
+
|
| 464 |
+
def save():
|
| 465 |
+
for arm, f in pk.items():
|
| 466 |
+
tmp = f.with_suffix(".tmp")
|
| 467 |
+
with open(tmp, "wb") as fh:
|
| 468 |
+
pickle.dump(rec[arm], fh)
|
| 469 |
+
tmp.replace(f)
|
| 470 |
+
|
| 471 |
+
n_new, t_start = 0, time.time()
|
| 472 |
+
for f in a.data:
|
| 473 |
+
if not want or (a.max_sets and n_new >= a.max_sets):
|
| 474 |
+
break
|
| 475 |
+
for s in [s for s in load_songs([f], mmap=True) if s["beatmapset_id"] in want]:
|
| 476 |
+
if song_split(s.get("song_key") or str(s["beatmapset_id"])) == "test":
|
| 477 |
+
raise ValueError(f"set {s['beatmapset_id']} is in the test split")
|
| 478 |
+
sid = int(s["beatmapset_id"])
|
| 479 |
+
mel = np.asarray(s["mel"], np.float32)
|
| 480 |
+
ref = max(s["charts"], key=lambda c: len(c["time"]))
|
| 481 |
+
sections = np.asarray(ref["sections"], np.float64)
|
| 482 |
+
t0 = min(float(c["time"][0]) for c in s["charts"]) - 2000.0
|
| 483 |
+
t1 = max(float(c["time"][-1]) for c in s["charts"])
|
| 484 |
+
feat, b_song = planner_rows(enc, mel, sections, device)
|
| 485 |
+
ctx["mel"], ctx["table"] = mel, beat_table(sections, len(mel))
|
| 486 |
+
entries = {arm: {"song_key": s.get("song_key"), "sections": sections, "draws": []} for arm in a.arms}
|
| 487 |
+
t_set = time.time()
|
| 488 |
+
for k in range(a.draws):
|
| 489 |
+
charts, extra, settings, bvec = make_draw(ctx, s, sections, t0, t1, feat, b_song, k, a.arms)
|
| 490 |
+
for arm in a.arms:
|
| 491 |
+
entries[arm]["draws"].append({"charts": charts[arm], "settings": settings, "b": bvec,
|
| 492 |
+
"s2": extra[arm]})
|
| 493 |
+
if a.keep_kiai_p:
|
| 494 |
+
for arm in a.arms:
|
| 495 |
+
entries[arm]["kiai_p"] = dict(ctx["kiai_p"])
|
| 496 |
+
for arm in a.arms:
|
| 497 |
+
rec[arm][sid] = entries[arm]
|
| 498 |
+
n_new += 1
|
| 499 |
+
want.discard(sid)
|
| 500 |
+
notes = {arm: {t: len(c["time"]) for t, c in entries[arm]["draws"][0]["charts"].items()} for arm in a.arms}
|
| 501 |
+
print(f"{sid}: {time.time() - t_set:.1f} s (total {(time.time() - t_start) / 60:.1f} min, {n_new} sets) "
|
| 502 |
+
f"notes draw0 {notes}", flush=True)
|
| 503 |
+
if n_new % a.save_every == 0:
|
| 504 |
+
save()
|
| 505 |
+
if a.max_sets and n_new >= a.max_sets:
|
| 506 |
+
break
|
| 507 |
+
save()
|
| 508 |
+
print("done", n_new, "new sets", flush=True)
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
if __name__ == "__main__":
|
| 512 |
+
main()
|
chartgen/v11/s2_osz.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Play-test .osz files for stage 2: the charts already generated by the end-to-end runs, no new generation.
|
| 2 |
+
|
| 3 |
+
For each of the 12 play-test songs (validation, 2022+), one .osz holds Oni and Inner Oni from draw 0 of:
|
| 4 |
+
Base t09 stage 1 sample_t09: b9 without MBR or the argmax gate (the fair baseline, D1)
|
| 5 |
+
R auto arm B: R's positions and R's own amounts
|
| 6 |
+
Prior no-audio arm B_prior: same pipeline, position map from the prior (no audio)
|
| 7 |
+
R + human amt arm A: R's positions with the human song amounts
|
| 8 |
+
Human plan stage 1 plan_human: b9 given the human bar plan (upper reference)
|
| 9 |
+
plus the human Oni / Inner Oni .osu files and the audio, copied from data/osz_play/v10c/.
|
| 10 |
+
|
| 11 |
+
uv run python -m chartgen.v11.s2_osz [--blind]
|
| 12 |
+
|
| 13 |
+
--blind also writes a copy where the five AI versions are named X1..X5 in a per-song random order, with the key in
|
| 14 |
+
key.json beside it (do not open the key before playing).
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import io
|
| 21 |
+
import json
|
| 22 |
+
import pickle
|
| 23 |
+
import re
|
| 24 |
+
import zipfile
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
from ..infer import TIER_NAMES, GeneratedChart, to_osu
|
| 30 |
+
|
| 31 |
+
PLAY = [2324765, 1855684, 2591578, 1293072, 1814276, 1534286, 1732205, 2175073, 2490016, 1354083, 2317728, 1889017]
|
| 32 |
+
ARMS = [ # (label, pickle)
|
| 33 |
+
("Base t09", "data/hfruns/runs/v11_s1/mapsets_S1_sample_t09.pkl"),
|
| 34 |
+
("R auto", "data/hfruns/runs/v11_s2/mapsets_S2_B.pkl"),
|
| 35 |
+
("Prior no-audio", "data/hfruns/runs/v11_s2/mapsets_S2_B_prior.pkl"),
|
| 36 |
+
("R + human amt", "data/hfruns/runs/v11_s2/mapsets_S2_A.pkl"),
|
| 37 |
+
("Human plan", "data/hfruns/runs/v11_s1/mapsets_S1_plan_human.pkl"),
|
| 38 |
+
]
|
| 39 |
+
TIERS = (3, 4)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def source_osz(src: Path, sid: int) -> Path:
|
| 43 |
+
hits = sorted(src.glob(f"{sid} *.osz"))
|
| 44 |
+
if not hits:
|
| 45 |
+
raise FileNotFoundError(f"no .osz for {sid} in {src}")
|
| 46 |
+
return hits[0]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def parse_meta(osu: str) -> dict:
|
| 50 |
+
out = {}
|
| 51 |
+
for k in ("Title", "Artist", "AudioFilename", "Version"):
|
| 52 |
+
m = re.search(rf"^{k}:\s*(.*)$", osu, re.M)
|
| 53 |
+
out[k] = m.group(1).strip() if m else ""
|
| 54 |
+
return out
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def osu_text(c: dict, sections, audio: str, title: str, artist: str, version: str) -> str:
|
| 58 |
+
g = GeneratedChart(sections=np.asarray(sections, np.float64), kiai=[tuple(x) for x in c["kiai"]],
|
| 59 |
+
time=np.asarray(c["time"], float), type=np.asarray(c["type"]),
|
| 60 |
+
length_beats=np.asarray(c["length_beats"], float), sv=np.asarray(c["sv"], float), tier=int(c["tier"]))
|
| 61 |
+
osu = to_osu(g, audio, title, artist)
|
| 62 |
+
osu = osu.replace(f"Version:{TIER_NAMES[g.tier]}", f"Version:{version}")
|
| 63 |
+
return osu.replace("Creator:chartgen", "Creator:chartgen v11s2")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def main(argv=None):
|
| 67 |
+
p = argparse.ArgumentParser()
|
| 68 |
+
p.add_argument("--src", type=Path, default=Path("data/osz_play/v10c"))
|
| 69 |
+
p.add_argument("--out", type=Path, default=Path("data/osz_play/v11_s2"))
|
| 70 |
+
p.add_argument("--blind", action="store_true")
|
| 71 |
+
p.add_argument("--seed", type=int, default=20261120)
|
| 72 |
+
a = p.parse_args(argv)
|
| 73 |
+
recs = {}
|
| 74 |
+
for label, path in ARMS:
|
| 75 |
+
d = pickle.load(open(path, "rb"))
|
| 76 |
+
recs[label] = {sid: d[sid] for sid in PLAY}
|
| 77 |
+
del d
|
| 78 |
+
a.out.mkdir(parents=True, exist_ok=True)
|
| 79 |
+
blind_dir = a.out / "blind"
|
| 80 |
+
if a.blind:
|
| 81 |
+
blind_dir.mkdir(exist_ok=True)
|
| 82 |
+
rng = np.random.default_rng(a.seed)
|
| 83 |
+
key, summary = {}, []
|
| 84 |
+
for sid in PLAY:
|
| 85 |
+
src = source_osz(a.src, sid)
|
| 86 |
+
with zipfile.ZipFile(src) as z:
|
| 87 |
+
names = z.namelist()
|
| 88 |
+
osus = {n: z.read(n).decode("utf-8") for n in names if n.endswith(".osu")}
|
| 89 |
+
human = {n: t for n, t in osus.items() if parse_meta(t)["Version"].startswith(("Human Oni", "Human Inner Oni"))}
|
| 90 |
+
meta = parse_meta(next(iter(osus.values())))
|
| 91 |
+
audio_name = meta["AudioFilename"]
|
| 92 |
+
audio = z.read(audio_name)
|
| 93 |
+
title, artist = meta["Title"], meta["Artist"]
|
| 94 |
+
order = list(rng.permutation(len(ARMS)))
|
| 95 |
+
key[str(sid)] = {f"X{i + 1}": ARMS[j][0] for i, j in enumerate(order)}
|
| 96 |
+
for blind in ([False, True] if a.blind else [False]):
|
| 97 |
+
zbuf = io.BytesIO()
|
| 98 |
+
with zipfile.ZipFile(zbuf, "w", zipfile.ZIP_DEFLATED) as z:
|
| 99 |
+
z.writestr(audio_name, audio)
|
| 100 |
+
for i, j in enumerate(order if blind else range(len(ARMS))):
|
| 101 |
+
label = ARMS[j][0]
|
| 102 |
+
rec = recs[label][sid]
|
| 103 |
+
charts = rec["draws"][0]["charts"]
|
| 104 |
+
for t in [t for t in TIERS if t in charts]: # A and plan_human need a human chart of the tier
|
| 105 |
+
name = f"X{i + 1}" if blind else label
|
| 106 |
+
version = f"{name} {TIER_NAMES[t]}"
|
| 107 |
+
osu = osu_text(charts[t], rec["sections"], audio_name, title, artist, version)
|
| 108 |
+
z.writestr(f"{artist} - {title} (chartgen) [{version}].osu".replace("/", "_"), osu)
|
| 109 |
+
if not blind:
|
| 110 |
+
summary.append((sid, label, TIER_NAMES[t], len(charts[t]["time"])))
|
| 111 |
+
for n, t in human.items():
|
| 112 |
+
z.writestr(n, t)
|
| 113 |
+
tag = "AI v11s2 blind" if blind else "AI v11s2 + human"
|
| 114 |
+
fname = f"{sid} {artist} - {title} ({tag}).osz".replace("/", "_")
|
| 115 |
+
((blind_dir if blind else a.out) / fname).write_bytes(zbuf.getvalue())
|
| 116 |
+
print(f"{sid} {artist} - {title}: human {len(human)} files", flush=True)
|
| 117 |
+
if a.blind:
|
| 118 |
+
(a.out / "key.json").write_text(json.dumps(key, indent=1, ensure_ascii=False))
|
| 119 |
+
(a.out / "note_counts.tsv").write_text("set\tversion\ttier\tnotes\n" + "".join(f"{s}\t{l}\t{t}\t{n}\n" for s, l, t, n in summary))
|
| 120 |
+
print("done", len(PLAY), flush=True)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
if __name__ == "__main__":
|
| 124 |
+
main()
|
chartgen/v11/s4c_sampler.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stage 4c: pseudo-charts with shared decisions (reports/v11 階段 4c 預先登記:共用決定.md).
|
| 2 |
+
|
| 3 |
+
The stage-2 pseudo-chart draws every beat's pattern independently: pattern = argmax over the 897-pattern vocabulary of
|
| 4 |
+
(R score + Gumbel noise), fresh noise per beat. Each beat's marginal is then right, but nothing ties decisions together,
|
| 5 |
+
so fine notes scatter, repeated music gets different rhythms and Oni does not nest in Inner Oni (handbook 2.7). Here the
|
| 6 |
+
scores are unchanged and only the noise is shared, so every beat keeps its marginal distribution while decisions that
|
| 7 |
+
humans make together are drawn together:
|
| 8 |
+
|
| 9 |
+
units a played measure joins the unit of its most similar earlier played measure (same beat count, within the
|
| 10 |
+
previous `window` played measures) when the cosine similarity of R's centred probabilities is >= s0;
|
| 11 |
+
a unit's measures share their noise rows, so where R's scores agree they get the same patterns
|
| 12 |
+
in-measure beat k of a unit uses the unit's shared row with probability lam (decided once per unit and k), else its
|
| 13 |
+
own row; similar beats of a measure then get the same pattern (regular rhythm, unbroken streams)
|
| 14 |
+
tiers Inner Oni is drawn first; Oni uses the same units and noise rows, and may only choose patterns that are
|
| 15 |
+
subsets of Inner Oni's pattern on the same beat (top-down reduction, D8)
|
| 16 |
+
amounts calibrated R logits without the stage-2 sharpening tau; the 1/8 amount is shifted to its drawn target as
|
| 17 |
+
in stage 2; every shift is found on the noise of the final draw (see make_pseudo_coupled)
|
| 18 |
+
|
| 19 |
+
The similarity uses R's own probabilities, not the onset descriptor the evaluation uses (handbook 5).
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
|
| 26 |
+
from chartgen.v11.rmap_data import POS, bits_to_bool
|
| 27 |
+
from chartgen.v11.rmap_pseudo import FAMILY_POS, FINE_POS, TRIP_POS, Sampler, popcount, shift_to_target
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def bar_counts(masks, bars, sel=None):
|
| 31 |
+
"""Positions per measure row (as v11.s2_arms.bar_counts)."""
|
| 32 |
+
c = popcount(masks, sel)
|
| 33 |
+
out = np.zeros(bars.n)
|
| 34 |
+
np.add.at(out, bars.row[bars.ok], c[bars.ok])
|
| 35 |
+
return out
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def measure_units(p: np.ndarray, bars, play: np.ndarray, s0: float, window: int = 8):
|
| 39 |
+
"""Unit id per measure row (-1 for rows without beats). p: [n beats, 24] probabilities of the unit-defining tier."""
|
| 40 |
+
rows = np.where(bars.ok)[0]
|
| 41 |
+
by_row = {}
|
| 42 |
+
for b in rows:
|
| 43 |
+
by_row.setdefault(int(bars.row[b]), []).append(b)
|
| 44 |
+
mu = p[rows].mean(0) if len(rows) else np.zeros(p.shape[1])
|
| 45 |
+
desc = {r: (p[bs] - mu).ravel() for r, bs in by_row.items()}
|
| 46 |
+
unit = -np.ones(bars.n, np.int64)
|
| 47 |
+
played = []
|
| 48 |
+
for r in sorted(by_row):
|
| 49 |
+
unit[r] = r
|
| 50 |
+
if play[r] < 0.5:
|
| 51 |
+
continue
|
| 52 |
+
best, best_s = None, -1.0
|
| 53 |
+
for i in played[-window:]:
|
| 54 |
+
if len(by_row[i]) != len(by_row[r]):
|
| 55 |
+
continue
|
| 56 |
+
a, b = desc[i], desc[r]
|
| 57 |
+
s = float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-9))
|
| 58 |
+
if s > best_s:
|
| 59 |
+
best, best_s = i, s
|
| 60 |
+
if best is not None and best_s >= s0:
|
| 61 |
+
unit[r] = unit[best]
|
| 62 |
+
played.append(r)
|
| 63 |
+
return unit, by_row
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def coupled_noise(smp: Sampler, n_beats: int, bars, unit, by_row, lam: float, seed_parts, k: int = 1):
|
| 67 |
+
"""[k, n_beats, V+1] Gumbel noise: beats of linked measures share rows; within a unit, beat j uses the unit's
|
| 68 |
+
shared row with probability lam (decided once per unit and beat position)."""
|
| 69 |
+
V = len(smp.masks)
|
| 70 |
+
G = np.empty((k, n_beats, V), np.float32)
|
| 71 |
+
cache = {}
|
| 72 |
+
for d in range(k):
|
| 73 |
+
rng_free = np.random.default_rng([*seed_parts, 31, d])
|
| 74 |
+
G[d] = rng_free.gumbel(size=(n_beats, V)) # rows outside any measure stay independent
|
| 75 |
+
for r, bs in by_row.items():
|
| 76 |
+
u = int(unit[r])
|
| 77 |
+
bs = sorted(bs)
|
| 78 |
+
for j, b in enumerate(bs):
|
| 79 |
+
key = (u, j)
|
| 80 |
+
if key not in cache:
|
| 81 |
+
rng_u = np.random.default_rng([*seed_parts, 37, u, j])
|
| 82 |
+
share = rng_u.random() < lam
|
| 83 |
+
cache[key] = ("shared" if share else "own", rng_u)
|
| 84 |
+
mode, _ = cache[key]
|
| 85 |
+
src = (u, -1) if mode == "shared" else (u, j)
|
| 86 |
+
for d in range(k):
|
| 87 |
+
kk = (src, d)
|
| 88 |
+
if kk not in cache:
|
| 89 |
+
cache[kk] = np.random.default_rng([*seed_parts, 41, u, src[1] + 1, d]).gumbel(size=V).astype(np.float32)
|
| 90 |
+
G[d, b] = cache[kk]
|
| 91 |
+
return G
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def subset_mask(smp: Sampler, upper: np.ndarray) -> np.ndarray:
|
| 95 |
+
"""[n beats, V+1] additive score mask: 0 where the pattern is a subset of `upper` on that beat, else -1e4."""
|
| 96 |
+
ok = (smp.masks[None, :] & ~np.asarray(upper, np.int64)[:, None]) == 0
|
| 97 |
+
return np.where(ok, 0.0, -1e4).astype(np.float32)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
OFF_Q = (POS % 12) != 0 # off the 1/4-beat grid: 1/3, 1/6, 1/8, 1/12, 1/16
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def fine_measures(lg: np.ndarray, valid: np.ndarray, bars, play, unit, conc: float, seed_parts):
|
| 104 |
+
"""Measure-level fine decision (stage 4c, `conc` < 1): measure r uses fine positions with probability
|
| 105 |
+
conc * P_R(any fine position in r); the uniform is drawn per unit (linked measures and both tiers share it). Returns
|
| 106 |
+
(z [n rows] bool, delta from independent positions; make_pseudo_coupled re-finds the shift with the sampler)."""
|
| 107 |
+
p = 1 / (1 + np.exp(-np.clip(lg, -30, 30))) * valid
|
| 108 |
+
pf = np.where(OFF_Q[None], p, 0.0)
|
| 109 |
+
rows = bars.row[bars.ok]
|
| 110 |
+
none = np.ones(bars.n)
|
| 111 |
+
np.multiply.at(none, rows, np.prod(1 - pf[bars.ok], 1))
|
| 112 |
+
q = np.clip(conc * (1 - none), 0, 1) * (play > 0.5)
|
| 113 |
+
u = np.array([np.random.default_rng([*seed_parts, 43, int(unit[r]) if unit[r] >= 0 else 10 ** 6 + r]).random()
|
| 114 |
+
for r in range(bars.n)])
|
| 115 |
+
z = u < q
|
| 116 |
+
total = pf[bars.ok].sum()
|
| 117 |
+
sel = np.zeros(len(lg), bool)
|
| 118 |
+
sel[np.where(bars.ok)[0]] = z[rows]
|
| 119 |
+
if total <= 0 or not sel.any():
|
| 120 |
+
return z, 0.0
|
| 121 |
+
lgf = np.clip(lg[sel][:, OFF_Q], -30, 30)
|
| 122 |
+
vf = valid[sel][:, OFF_Q]
|
| 123 |
+
lo, hi = -5.0, 15.0
|
| 124 |
+
for _ in range(40):
|
| 125 |
+
mid = 0.5 * (lo + hi)
|
| 126 |
+
e = (1 / (1 + np.exp(-(lgf + mid))) * vf).sum()
|
| 127 |
+
lo, hi = (mid, hi) if e < total else (lo, mid)
|
| 128 |
+
return z, 0.5 * (lo + hi)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def make_pseudo_coupled(smp: Sampler, lg: np.ndarray, table, bars, play: np.ndarray, targets: list, seed_parts,
|
| 132 |
+
unit, by_row, lam: float, upper: np.ndarray | None = None, conc: float = 1.0,
|
| 133 |
+
eighth_first: bool = False):
|
| 134 |
+
"""One pseudo-chart (per-beat masks) with coupled noise; `upper` (Inner Oni's masks) restricts Oni to subsets;
|
| 135 |
+
conc < 1 adds the measure-level fine decision (fine_measures; for Oni the measures where Inner Oni has fine
|
| 136 |
+
positions). Same rest handling, zero rule and empty-measure repair as rmap_pseudo / s2_arms.make_pseudo."""
|
| 137 |
+
n = len(table)
|
| 138 |
+
valid = bits_to_bool(table.valid).copy()
|
| 139 |
+
inplan = bars.ok
|
| 140 |
+
rest_beat = np.zeros(n, bool)
|
| 141 |
+
rest_beat[inplan] = play[bars.row[inplan]] < 0.5
|
| 142 |
+
valid[rest_beat] = False
|
| 143 |
+
sub = subset_mask(smp, upper) if upper is not None else 0.0
|
| 144 |
+
# the noise of the final draw; shifts are calibrated on it, because Oni shares Inner Oni's noise and, under the
|
| 145 |
+
# subset rule, follows Inner Oni's choices: independent calibration draws would miss that and overshoot
|
| 146 |
+
G = coupled_noise(smp, n, bars, unit, by_row, lam, [*seed_parts, 1], k=1)
|
| 147 |
+
if conc < 1.0:
|
| 148 |
+
# measure-level fine decision; the shift of the chosen measures' fine patterns is found with the sampler itself
|
| 149 |
+
# (8 coupled draws) so that the mean number of fine positions equals that of the same sampler without it
|
| 150 |
+
if upper is None:
|
| 151 |
+
z, _ = fine_measures(lg, valid, bars, play, unit, conc, seed_parts)
|
| 152 |
+
else:
|
| 153 |
+
# Oni: its fine measures are Inner Oni's (the subset rule already concentrates them); no second thinning
|
| 154 |
+
fu = np.zeros(bars.n)
|
| 155 |
+
np.add.at(fu, bars.row[inplan], popcount(np.asarray(upper, np.int64)[inplan], OFF_Q))
|
| 156 |
+
z = fu > 0
|
| 157 |
+
on = np.zeros(n, bool)
|
| 158 |
+
on[np.where(inplan)[0]] = z[bars.row[inplan]]
|
| 159 |
+
fam = smp.family_count(OFF_Q) # fine positions per pattern [V+1]
|
| 160 |
+
G8 = coupled_noise(smp, n, bars, unit, by_row, lam, [*seed_parts, 5], k=8)
|
| 161 |
+
# target: the tier's own amount without the subset rule (R's amount for this tier), so concentrating Inner Oni's
|
| 162 |
+
# fine notes does not shrink Oni's; the subset rule then only decides where they can go
|
| 163 |
+
S_full = smp.scores(lg, valid)
|
| 164 |
+
if eighth_first:
|
| 165 |
+
# stage 4c variant: the drawn 1/8 amount is set before concentrating, as part of the fine amount, so the
|
| 166 |
+
# 1/8 notes are concentrated with the triplets instead of being added afterwards into the few chosen
|
| 167 |
+
# measures (which overshot notes per fine measure on the validation pseudo-charts)
|
| 168 |
+
e_shift = 0.0
|
| 169 |
+
for fam_name, which, tgt in targets:
|
| 170 |
+
if fam_name == "eighth" and tgt is not None and tgt > 0:
|
| 171 |
+
e_shift, _ = shift_to_target(smp, S_full, G, FAMILY_POS["eighth"], bars, which, float(tgt))
|
| 172 |
+
ce = smp.family_count(FAMILY_POS["eighth"])
|
| 173 |
+
lg = np.array(lg, np.float32, copy=True)
|
| 174 |
+
lg[:, FAMILY_POS["eighth"]] += e_shift
|
| 175 |
+
S_full = smp.scores(lg, valid)
|
| 176 |
+
targets = [x for x in targets if not (x[0] == "eighth" and x[2] is not None and x[2] > 0)]
|
| 177 |
+
del ce
|
| 178 |
+
target = float(fam[np.argmax(S_full[None] + G8, -1)].sum(-1).mean())
|
| 179 |
+
valid[np.ix_(inplan & ~on, OFF_Q)] = False
|
| 180 |
+
S0 = smp.scores(lg, valid) + sub
|
| 181 |
+
add = (on[:, None] * fam[None, :]).astype(np.float32)
|
| 182 |
+
lo, hi = -5.0, 15.0
|
| 183 |
+
for _ in range(20):
|
| 184 |
+
mid = 0.5 * (lo + hi)
|
| 185 |
+
c = float(fam[np.argmax(S0[None] + G + np.float32(mid) * add[None], -1)].sum(-1).mean())
|
| 186 |
+
lo, hi = (mid, hi) if c < target else (lo, mid)
|
| 187 |
+
S = S0 + np.float32(0.5 * (lo + hi)) * add
|
| 188 |
+
else:
|
| 189 |
+
S = smp.scores(lg, valid) + sub
|
| 190 |
+
shifts, zero_rule = {}, {}
|
| 191 |
+
for fam, which, target in targets:
|
| 192 |
+
if target is None:
|
| 193 |
+
continue
|
| 194 |
+
if target <= 0:
|
| 195 |
+
zero_rule[fam] = 0.3 if fam == "triplet" else 0.25
|
| 196 |
+
continue
|
| 197 |
+
d, got = shift_to_target(smp, S, G, FAMILY_POS[fam], bars, which, float(target))
|
| 198 |
+
S = S + d * smp.family_count(FAMILY_POS[fam])[None]
|
| 199 |
+
shifts[fam] = {"target": float(target), "delta": float(d), "got": float(got)}
|
| 200 |
+
m = smp.draw(S, G)[0]
|
| 201 |
+
rng = np.random.default_rng([*seed_parts, 3])
|
| 202 |
+
|
| 203 |
+
def redraw(beats_idx):
|
| 204 |
+
m[beats_idx] = smp.draw(S[beats_idx], smp.gumbel(rng, 1, len(beats_idx)))[0]
|
| 205 |
+
|
| 206 |
+
for fam, thr in zero_rule.items():
|
| 207 |
+
sel = TRIP_POS if fam == "triplet" else FINE_POS
|
| 208 |
+
for _ in range(50):
|
| 209 |
+
h, f = bar_counts(m, bars), bar_counts(m, bars, sel)
|
| 210 |
+
bad = np.where((h > 0) & (f / np.maximum(h, 1) > thr))[0]
|
| 211 |
+
if not len(bad):
|
| 212 |
+
break
|
| 213 |
+
redraw(np.where(inplan & np.isin(bars.row, bad))[0])
|
| 214 |
+
n_forced = 0
|
| 215 |
+
play_rows = np.where(play > 0.5)[0]
|
| 216 |
+
for _ in range(100):
|
| 217 |
+
h = bar_counts(m, bars)
|
| 218 |
+
empty = play_rows[h[play_rows] == 0]
|
| 219 |
+
cand = [b for b in empty if valid[inplan & (bars.row == b)].any()]
|
| 220 |
+
if not cand:
|
| 221 |
+
break
|
| 222 |
+
redraw(np.where(inplan & np.isin(bars.row, cand))[0])
|
| 223 |
+
h = bar_counts(m, bars)
|
| 224 |
+
for b in play_rows[h[play_rows] == 0]:
|
| 225 |
+
rows_b = np.where(inplan & (bars.row == b))[0]
|
| 226 |
+
v = valid[rows_b]
|
| 227 |
+
if upper is not None:
|
| 228 |
+
v = v & ((np.asarray(upper, np.int64)[rows_b, None] >> np.arange(24)) & 1).astype(bool)
|
| 229 |
+
if not v.any():
|
| 230 |
+
continue
|
| 231 |
+
p = 1 / (1 + np.exp(-np.clip(lg[rows_b], -30, 30))) * v
|
| 232 |
+
flat = p.reshape(-1) / p.sum()
|
| 233 |
+
j = rng.choice(len(flat), p=flat)
|
| 234 |
+
m[rows_b[j // 24]] |= np.int64(1) << (j % 24)
|
| 235 |
+
n_forced += 1
|
| 236 |
+
return m, {"shifts": shifts, "zero_rule": sorted(zero_rule), "forced_notes": n_forced}
|
chartgen/v11/s5a.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""v11 stage 5a: song-level decisions taken from R's own readout (reports/v11 階段 5a 預先登記:整首決定照 R 的讀數.md).
|
| 2 |
+
|
| 3 |
+
eighth_share R's song-level 1/8 readout of one tier: expected notes on the 1/8-family positions (classes 1/8 and
|
| 4 |
+
1/16) / expected notes on all 24 positions, under the calibrated probabilities, over every beat of
|
| 5 |
+
the map (as reports/figs/v11_s5_eighth_use.py)
|
| 6 |
+
triplet_readout mean triplet setting (share of played measures whose triplet share is > 0.3) of 16 pseudo-charts
|
| 7 |
+
drawn from the calibrated map with no tau and no rest plan (as rmap_eval.song_level, stage 2 S2.5)
|
| 8 |
+
Params per tier: theta (1/8 gate), the 1/8 amount of gated-on songs (a pool of human note shares to draw
|
| 9 |
+
from, or a line on the readout), the triplet line (human triplet setting on the readout);
|
| 10 |
+
all fitted on the tuning songs by reports/figs/v11_s5a_tune.py
|
| 11 |
+
|
| 12 |
+
The same functions are used by the tuning script and by chartgen.v11.s2_arms (arms G8 and G8T).
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
from chartgen.v11.rmap_pseudo import FAMILY_POS, Bars, Sampler, fast_settings
|
| 23 |
+
|
| 24 |
+
EIGHTH = FAMILY_POS["eighth"]
|
| 25 |
+
PHASE_NO_EIGHTH = (np.arange(48) % 4 == 0) # the 1/12-beat positions: beat, 1/2, 1/3, 1/4, 1/6, 1/12
|
| 26 |
+
READOUT_DRAWS = 16
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def eighth_share(lg_tier: np.ndarray) -> float:
|
| 30 |
+
p = 1 / (1 + np.exp(-np.asarray(lg_tier, np.float64)))
|
| 31 |
+
return float(p[:, EIGHTH].sum() / max(p.sum(), 1e-9))
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def triplet_readout(smp: Sampler, lg_tier: np.ndarray, valid: np.ndarray, bars: Bars, seed_parts) -> float:
|
| 35 |
+
S0 = smp.scores(lg_tier, valid)
|
| 36 |
+
G = smp.gumbel(np.random.default_rng(list(seed_parts)), READOUT_DRAWS, len(lg_tier))
|
| 37 |
+
v = fast_settings(smp.draw(S0, G), bars)["triplet"]
|
| 38 |
+
return float(np.nanmean(v)) if np.isfinite(v).any() else float("nan")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def drop_eighth_family(chart: dict) -> tuple[dict, int]:
|
| 42 |
+
"""A gated-off chart without the hit notes that land on the 1/8 family (classes 1/8, 1/16, finer) when their times
|
| 43 |
+
are read on the chart's own red lines, as the evaluation reads them (rhythm_eval2.grid_of). The decoder's position
|
| 44 |
+
mask works on the window's grid table; next to a red line that table and the red lines disagree (verification
|
| 45 |
+
report 3.2), and in sections with beats of a few ms the predicted timing residual moves a note by a grid step.
|
| 46 |
+
Returns (chart, number of notes removed). Rolls and balloons are kept."""
|
| 47 |
+
from chartgen.dataset import GRID, subdiv_class
|
| 48 |
+
from chartgen.rhythm_eval2 import beats_tol
|
| 49 |
+
t = np.asarray(chart["time"], np.float64)
|
| 50 |
+
ty = np.asarray(chart["type"])
|
| 51 |
+
if len(t) == 0:
|
| 52 |
+
return chart, 0
|
| 53 |
+
g = np.round(beats_tol(chart["sections"], t) * GRID).astype(np.int64)
|
| 54 |
+
bad = (ty <= 3) & (subdiv_class(g) >= 5) & (subdiv_class(g) != 6)
|
| 55 |
+
if not bad.any():
|
| 56 |
+
return chart, 0
|
| 57 |
+
out = dict(chart)
|
| 58 |
+
for k in ("time", "type", "length_beats", "sv"):
|
| 59 |
+
out[k] = np.asarray(chart[k])[~bad]
|
| 60 |
+
return out, int(bad.sum())
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
SEAM_SLACK_MS = 1.0 # stage-5a arms: hit notes closer than (the tier's floor - 1 ms) to the previous kept hit are dropped
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def enforce_min_gap(chart: dict, floor_ms: float, slack_ms: float = SEAM_SLACK_MS) -> tuple[dict, int]:
|
| 67 |
+
"""The min-gap pass of s1_arms.run_windows over a finished chart: in time order, a hit note closer than
|
| 68 |
+
floor - slack to the previous kept hit note is dropped (rolls and balloons are kept and do not reset the clock).
|
| 69 |
+
Applied to a chart that already went through the pass with a larger slack, it is not always what a new generation
|
| 70 |
+
with this slack gives: in a chain of three close notes the old pass may have dropped a note that the new pass
|
| 71 |
+
would keep after dropping its neighbour, and that note is no longer in the stored chart. Stored charts filtered
|
| 72 |
+
this way are a preview; the registered result comes from a new generation. Returns (chart, notes removed)."""
|
| 73 |
+
t = np.asarray(chart["time"], np.float64)
|
| 74 |
+
ty = np.asarray(chart["type"])
|
| 75 |
+
keep = np.ones(len(t), bool)
|
| 76 |
+
last = -np.inf
|
| 77 |
+
for i in np.argsort(t, kind="stable"):
|
| 78 |
+
if ty[i] > 3:
|
| 79 |
+
continue
|
| 80 |
+
if t[i] - last < floor_ms - slack_ms:
|
| 81 |
+
keep[i] = False
|
| 82 |
+
else:
|
| 83 |
+
last = t[i]
|
| 84 |
+
if keep.all():
|
| 85 |
+
return chart, 0
|
| 86 |
+
out = dict(chart)
|
| 87 |
+
for k in ("time", "type", "length_beats", "sv"):
|
| 88 |
+
out[k] = np.asarray(chart[k])[keep]
|
| 89 |
+
return out, int((~keep).sum())
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class Params:
|
| 93 |
+
def __init__(self, path):
|
| 94 |
+
d = json.loads(Path(path).read_text())
|
| 95 |
+
self.d = d
|
| 96 |
+
self.theta = {int(t): float(v) for t, v in d["theta"].items()}
|
| 97 |
+
self.rule = d["eighth_rule"]
|
| 98 |
+
self.pool = {int(t): np.asarray(v, float) for t, v in d.get("eighth_pool", {}).items()}
|
| 99 |
+
self.line8 = {int(t): v for t, v in d.get("eighth_line", {}).items()}
|
| 100 |
+
self.line3 = {int(t): v for t, v in d["triplet_line"].items()}
|
| 101 |
+
# second tuning round (reports/figs/v11_s5a_tune2.py): the rule actually used for the triplet target
|
| 102 |
+
self.trip_rule = d.get("triplet_rule")
|
| 103 |
+
self.trip_scale = {int(t): float(v) for t, v in d.get("triplet_scale", {}).items()}
|
| 104 |
+
self.trip_origin = {int(t): v for t, v in d.get("triplet_origin", {}).items()}
|
| 105 |
+
|
| 106 |
+
def gate(self, tier: int, share: float) -> bool:
|
| 107 |
+
return bool(share >= self.theta[tier])
|
| 108 |
+
|
| 109 |
+
def eighth_amount(self, tier: int, share: float, rng) -> float:
|
| 110 |
+
"""Target 1/8-family note share of a gated-on chart."""
|
| 111 |
+
if self.rule == "line":
|
| 112 |
+
b, a, lo, hi = self.line8[tier]
|
| 113 |
+
return float(np.clip(a + b * share, lo, hi))
|
| 114 |
+
pool = self.pool[tier]
|
| 115 |
+
return float(pool[int(rng.integers(len(pool)))])
|
| 116 |
+
|
| 117 |
+
@property
|
| 118 |
+
def needs_readout(self) -> bool:
|
| 119 |
+
return self.trip_rule in ("V1", "V2")
|
| 120 |
+
|
| 121 |
+
def triplet_target(self, tier: int, readout: float | None, n_play: float):
|
| 122 |
+
"""Target of the pseudo-chart's triplet setting (share of played measures with a triplet share > 0.3).
|
| 123 |
+
V3: ("scale", c) = c x the sampler's own unshifted amount (resolved inside make_pseudo).
|
| 124 |
+
V1 / V2: slope x readout through the origin, 0 when that is fewer than the cut-off number of played measures;
|
| 125 |
+
None (no triplet handling) when the readout is undefined."""
|
| 126 |
+
if self.trip_rule == "V3":
|
| 127 |
+
return ("scale", self.trip_scale[tier])
|
| 128 |
+
if readout is None or not np.isfinite(readout):
|
| 129 |
+
return None
|
| 130 |
+
b0, cut = self.trip_origin[tier]
|
| 131 |
+
v = float(b0) * float(readout)
|
| 132 |
+
return 0.0 if v * n_play < float(cut) else min(v, 1.0)
|
chartgen/v11/s5d_osz.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Play-test .osz files for stage 5d: the position model P with b9fix writing colours and big notes on P's positions,
|
| 2 |
+
next to the 5c system, and the human charts for the validation songs. Private play-testing only.
|
| 3 |
+
|
| 4 |
+
val the 12 play-test songs of stages 2-3 (validation, 2022+). P = the stage-5d generation (v11_s5d/gen, draw 0);
|
| 5 |
+
5c = the stage-5a G8 charts (v11_s5a/gen2, draw 0) with one shared kiai per set (stage 5c). Audio and the human
|
| 6 |
+
.osu files from data/osz_play/v10c
|
| 7 |
+
new the songs of data/osz_play/v11_new/songs.json (audio only, red lines decoded by gen_new.timing). P and 5c are
|
| 8 |
+
generated here on CPU: 5c = arm G8 of s2_arms with b9fix and the gap floor; P = pmap.gen_song on the music span
|
| 9 |
+
|
| 10 |
+
Colouring P: b9fix decodes each 20 s window (halved while a window holds more than 360 of P's notes) with every P hit
|
| 11 |
+
note required and no other position allowed, so it only chooses the note type (don / ka / big don / big ka; roll and
|
| 12 |
+
balloon types switched off), the SV class and the timing residual. Its bar plan is the plan of P's own notes with the
|
| 13 |
+
big-note column of the 5c draw's base plan (sp9). Rolls: one drumroll per run of P's HOLD beats, from the run's first
|
| 14 |
+
beat to a quarter beat before the next beat. Kiai (both systems): b9fix's kiai probabilities decoded once per set at
|
| 15 |
+
0.35 over the earliest to latest hit (stage 5c).
|
| 16 |
+
|
| 17 |
+
uv run python -m chartgen.v11.s5d_osz val
|
| 18 |
+
uv run python -m chartgen.v11.s5d_osz new
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import argparse
|
| 24 |
+
import dataclasses
|
| 25 |
+
import io
|
| 26 |
+
import json
|
| 27 |
+
import pickle
|
| 28 |
+
import re
|
| 29 |
+
import zipfile
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
from types import SimpleNamespace
|
| 32 |
+
|
| 33 |
+
import numpy as np
|
| 34 |
+
import torch
|
| 35 |
+
|
| 36 |
+
REPO = Path(__file__).resolve().parents[3]
|
| 37 |
+
RUNS = REPO / "data/hfruns/runs"
|
| 38 |
+
TIERS = (3, 4)
|
| 39 |
+
KIAI_THR = 0.35
|
| 40 |
+
FLOORS = {3: 57.0, 4: 32.0}
|
| 41 |
+
NAMES = {3: "Oni", 4: "Inner Oni"}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def mel_of(raw: bytes):
|
| 45 |
+
from chartgen.features import decode_audio, log_mel
|
| 46 |
+
return np.asarray(log_mel(decode_audio(raw), device="cpu"), np.float32)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def hits(c):
|
| 50 |
+
return np.sort(np.asarray(c["time"], float)[np.asarray(c["type"]) <= 3])
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def shared_kiai(kiai_p, sections, charts):
|
| 54 |
+
from chartgen.infer import decode_kiai
|
| 55 |
+
tt = [hits(c) for c in charts.values()]
|
| 56 |
+
tt = [x for x in tt if len(x) >= 2]
|
| 57 |
+
return decode_kiai(np.asarray(kiai_p, np.float32), np.asarray(sections, np.float64), min(x[0] for x in tt),
|
| 58 |
+
max(x[-1] for x in tt), thr=KIAI_THR)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def p_plan(times, sections, base_pair):
|
| 62 |
+
"""Bar plan of P's notes on the base plan's measures, with the base's big-note column."""
|
| 63 |
+
from chartgen.dataset import GRID, bar_plan
|
| 64 |
+
from chartgen.rhythm_eval2 import beats_tol
|
| 65 |
+
b_song, base = base_pair
|
| 66 |
+
g = np.round(beats_tol(sections, times) * GRID).astype(np.int64)
|
| 67 |
+
H = bar_plan(g, np.zeros(len(g), np.int64), b_song, np.asarray(sections, np.float64), None, len(base))
|
| 68 |
+
H[:, 2] = base[:, 2]
|
| 69 |
+
return b_song, H.astype(np.float32)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@torch.no_grad()
|
| 73 |
+
def colour_forced(b9, mel, sections, tier, times, plan_pair, t0, t1, device, seed):
|
| 74 |
+
"""(time, type, length, sv) of b9fix decoding with exactly P's hit positions."""
|
| 75 |
+
from chartgen.dataset import GRID, WINDOW, make_example
|
| 76 |
+
from chartgen.gen_mapset import window_plan
|
| 77 |
+
from chartgen.generate import generate
|
| 78 |
+
from chartgen.infer import _dummy_chart
|
| 79 |
+
from chartgen.rhythm_eval2 import beats_tol
|
| 80 |
+
from chartgen.v11.s2_arms import pseudo_chart
|
| 81 |
+
sections = np.asarray(sections, np.float64)
|
| 82 |
+
times = np.sort(np.asarray(times, float))
|
| 83 |
+
g_all = np.round(beats_tol(sections, times) * GRID).astype(np.int64)
|
| 84 |
+
pc = pseudo_chart(g_all, sections, tier)
|
| 85 |
+
dummy = _dummy_chart(sections, tier)
|
| 86 |
+
song = {"mel": mel}
|
| 87 |
+
tb = np.zeros(7, np.float32)
|
| 88 |
+
tb[4:] = -1e9
|
| 89 |
+
out = []
|
| 90 |
+
|
| 91 |
+
def run(st, nf):
|
| 92 |
+
lo, hi = st * 10.0, (st + nf) * 10.0
|
| 93 |
+
ex = make_example(song, dummy, st)
|
| 94 |
+
sel = (times >= lo) & (times < hi)
|
| 95 |
+
off = g_all[sel] - ex.start_grid
|
| 96 |
+
off = np.unique(off[(off >= 0) & (off < len(ex.grid_time) - 1)])
|
| 97 |
+
if not len(off):
|
| 98 |
+
return
|
| 99 |
+
if len(off) > 360 and nf >= 250:
|
| 100 |
+
run(st, nf // 2)
|
| 101 |
+
run(st + nf // 2, nf - nf // 2)
|
| 102 |
+
return
|
| 103 |
+
hx = make_example(song, pc, st)
|
| 104 |
+
ex = dataclasses.replace(ex, plan_rho=hx.plan_rho, plan_r=hx.plan_r, plan_gap=hx.plan_gap)
|
| 105 |
+
w, _, _ = window_plan(plan_pair[1], plan_pair[0], sections, st)
|
| 106 |
+
al = np.zeros(len(ex.grid_time) + 1, bool)
|
| 107 |
+
al[off] = True
|
| 108 |
+
torch.manual_seed(seed + st)
|
| 109 |
+
p = generate(b9, [ex], device, temperature=[0.9], rho_scale=[1.0], plan_source="oracle", bar_plan=w[None],
|
| 110 |
+
allowed=[al], required=[off], continue_until=[int(off[-1])], type_bias=tb)[0]
|
| 111 |
+
t = p["time"] + ex.start_ms
|
| 112 |
+
keep = (t >= lo - 30.0) & (t < hi + 30.0)
|
| 113 |
+
out.append((t[keep], p["type"][keep], p["length"][keep], p["sv"][keep]))
|
| 114 |
+
|
| 115 |
+
for st in range(int(max(t0, 0) // 10), int(t1 // 10) + 1, WINDOW):
|
| 116 |
+
run(st, WINDOW)
|
| 117 |
+
tm = np.concatenate([o[0] for o in out]) if out else np.zeros(0)
|
| 118 |
+
order = np.argsort(tm, kind="stable")
|
| 119 |
+
res = tuple(np.concatenate([o[i] for o in out])[order] if out else np.zeros(0) for i in range(4))
|
| 120 |
+
return res
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def hold_rolls(tok, table, hold_id):
|
| 124 |
+
"""(time, length in beats) of one drumroll per run of HOLD beats."""
|
| 125 |
+
h = np.asarray(tok) == hold_id
|
| 126 |
+
if not h.any():
|
| 127 |
+
return np.zeros(0), np.zeros(0)
|
| 128 |
+
e = np.flatnonzero(np.diff(np.r_[0, h.astype(int), 0]))
|
| 129 |
+
a, b = e[::2], e[1::2]
|
| 130 |
+
return table.t0[a].astype(float), np.maximum((b - a) - 0.25, 0.25).astype(float)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def p_full(b9, mel, sections, tier, pchart, tok, table, plan_pair, t0, t1, device, seed):
|
| 134 |
+
"""P's chart with b9fix colours and HOLD rolls; returns (chart, report)."""
|
| 135 |
+
from chartgen.v11.pmap import tables
|
| 136 |
+
ph = hits(pchart)
|
| 137 |
+
tm, ty, ln, sv = colour_forced(b9, mel, sections, tier, ph, plan_pair, t0, t1, device, seed)
|
| 138 |
+
rt, rl = hold_rolls(tok, table, tables()["HOLD"])
|
| 139 |
+
t = np.r_[tm, rt]
|
| 140 |
+
o = np.argsort(t, kind="stable")
|
| 141 |
+
ch = {"tier": tier, "sections": np.asarray(sections, np.float64), "time": t[o],
|
| 142 |
+
"type": np.r_[np.asarray(ty, int), np.full(len(rt), 4)][o],
|
| 143 |
+
"length_beats": np.r_[np.zeros(len(tm)), rl][o], "sv": np.r_[np.asarray(sv, float), np.ones(len(rt))][o]}
|
| 144 |
+
hit_t = np.sort(tm[np.asarray(ty) <= 3])
|
| 145 |
+
matched = int(sum(np.min(np.abs(hit_t - x)) <= 30.0 for x in ph)) if len(hit_t) else 0
|
| 146 |
+
rep = {"P notes": int(len(ph)), "coloured notes": int(len(tm)), "P notes matched within 30 ms": matched,
|
| 147 |
+
"ka share": float(np.isin(ty, (1, 3)).mean()) if len(ty) else 0.0,
|
| 148 |
+
"big share": float(np.isin(ty, (2, 3)).mean()) if len(ty) else 0.0, "rolls": int(len(rt))}
|
| 149 |
+
return ch, rep
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def osu_text(c, sections, audio, title, artist, version):
|
| 153 |
+
from chartgen.infer import TIER_NAMES, GeneratedChart, to_osu
|
| 154 |
+
g = GeneratedChart(sections=np.asarray(sections, np.float64), kiai=[tuple(x) for x in c["kiai"]],
|
| 155 |
+
time=np.asarray(c["time"], float), type=np.asarray(c["type"]),
|
| 156 |
+
length_beats=np.asarray(c["length_beats"], float), sv=np.asarray(c["sv"], float), tier=int(c["tier"]))
|
| 157 |
+
osu = to_osu(g, audio, title, artist).replace(f"Version:{TIER_NAMES[g.tier]}", f"Version:{version}")
|
| 158 |
+
return osu.replace("Creator:chartgen", "Creator:chartgen v11s5d")
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def write_osz(path, audio_name, audio, files):
|
| 162 |
+
zbuf = io.BytesIO()
|
| 163 |
+
with zipfile.ZipFile(zbuf, "w", zipfile.ZIP_DEFLATED) as z:
|
| 164 |
+
z.writestr(audio_name, audio)
|
| 165 |
+
for n, t in files:
|
| 166 |
+
z.writestr(n, t)
|
| 167 |
+
path.write_bytes(zbuf.getvalue())
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def alignment_lag(mel, times):
|
| 171 |
+
"""Lag (ms, -60..60) at which the spectral flux at the note times is highest: a check that the local audio decode
|
| 172 |
+
matches the timing the notes were written on (0 or close = aligned)."""
|
| 173 |
+
from chartgen.v11.gen_new import flux
|
| 174 |
+
fl = flux(mel)
|
| 175 |
+
lags = np.arange(-60, 61, 5)
|
| 176 |
+
sc = [np.interp((times + l) / 10.0, np.arange(len(fl)), fl).mean() for l in lags]
|
| 177 |
+
return int(lags[int(np.argmax(sc))])
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def mel_len_from_caches(sid):
|
| 181 |
+
for cp in sorted((RUNS / "v11_s2/caches").glob("*.r.pkl")):
|
| 182 |
+
for r in pickle.load(open(cp, "rb")):
|
| 183 |
+
if int(r["beatmapset_id"]) == sid:
|
| 184 |
+
return int(r["mel_len"])
|
| 185 |
+
return None
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def val(a):
|
| 189 |
+
from chartgen import rhythm_eval2 as re2
|
| 190 |
+
from chartgen.infer import load_model
|
| 191 |
+
from chartgen.v11.rmap_data import beat_table
|
| 192 |
+
from chartgen.v11.s2_osz import PLAY, parse_meta, source_osz
|
| 193 |
+
device = torch.device("cpu")
|
| 194 |
+
b9 = load_model(RUNS / "b9fix/best.pt", device)
|
| 195 |
+
P = re2.load_system(tuple(str(p.relative_to(RUNS)) for p in sorted(RUNS.glob("v11_s5d/gen/part*/mapsets_P.pkl"))))
|
| 196 |
+
C = re2.load_system(tuple(str(p.relative_to(RUNS)) for p in sorted(RUNS.glob("v11_s5a/gen2/part*/mapsets_S2_G8.pkl"))))
|
| 197 |
+
a.out.mkdir(parents=True, exist_ok=True)
|
| 198 |
+
report = {}
|
| 199 |
+
for sid in PLAY:
|
| 200 |
+
src = source_osz(Path("data/osz_play/v10c"), sid)
|
| 201 |
+
with zipfile.ZipFile(src) as z:
|
| 202 |
+
osus = {n: z.read(n).decode("utf-8") for n in z.namelist() if n.endswith(".osu")}
|
| 203 |
+
human = {n: t for n, t in osus.items() if parse_meta(t)["Version"].startswith(("Human Oni", "Human Inner Oni"))}
|
| 204 |
+
meta = parse_meta(next(iter(osus.values())))
|
| 205 |
+
audio_name = meta["AudioFilename"]
|
| 206 |
+
audio = z.read(audio_name)
|
| 207 |
+
title, artist = meta["Title"], meta["Artist"]
|
| 208 |
+
mel = mel_of(audio)
|
| 209 |
+
pe, ce = P[sid], C[sid]
|
| 210 |
+
sections = np.asarray(pe["sections"], np.float64)
|
| 211 |
+
n4 = len(pe["draws"][0]["p"][4]["tok"])
|
| 212 |
+
table = beat_table(sections, len(mel))
|
| 213 |
+
if len(table) != n4 or int(table.beat[0]) != pe["beat0"]:
|
| 214 |
+
table = beat_table(sections, mel_len_from_caches(sid))
|
| 215 |
+
assert len(table) == n4 and int(table.beat[0]) == pe["beat0"], (sid, len(table), n4)
|
| 216 |
+
kiai_p = ce["kiai_p"][4]
|
| 217 |
+
cdraw = ce["draws"][0]
|
| 218 |
+
pcharts, rep = {}, {"alignment lag ms (P notes on local audio)": alignment_lag(mel, hits(pe["draws"][0]["charts"][4]))}
|
| 219 |
+
t0 = min(float(hits(c)[0]) for c in pe["draws"][0]["charts"].values()) - 1000.0
|
| 220 |
+
t1 = max(float(hits(c)[-1]) for c in pe["draws"][0]["charts"].values())
|
| 221 |
+
for t in TIERS:
|
| 222 |
+
base = cdraw["s2"][t]["plan"]
|
| 223 |
+
pc = pe["draws"][0]["charts"][t]
|
| 224 |
+
plan = p_plan(hits(pc), sections, (int(base[0]), np.asarray(base[1], np.float32)))
|
| 225 |
+
pcharts[t], rep[NAMES[t]] = p_full(b9, mel, sections, t, pc, pe["draws"][0]["p"][t]["tok"], table, plan, t0,
|
| 226 |
+
t1, device, a.seed + sid + 1000 * t)
|
| 227 |
+
kp = shared_kiai(kiai_p, sections, pcharts)
|
| 228 |
+
for t in TIERS:
|
| 229 |
+
pcharts[t]["kiai"] = kp
|
| 230 |
+
ccharts = {t: dict(cdraw["charts"][t]) for t in TIERS}
|
| 231 |
+
kc = shared_kiai(kiai_p, sections, ccharts)
|
| 232 |
+
for t in TIERS:
|
| 233 |
+
ccharts[t]["kiai"] = kc
|
| 234 |
+
files = []
|
| 235 |
+
for label, cs in (("P", pcharts), ("5c", ccharts)):
|
| 236 |
+
for t in TIERS:
|
| 237 |
+
v = f"{label} {NAMES[t]}"
|
| 238 |
+
files.append((f"{artist} - {title} (chartgen) [{v}].osu".replace("/", "_"),
|
| 239 |
+
osu_text(cs[t], sections, audio_name, title, artist, v)))
|
| 240 |
+
files += list(human.items())
|
| 241 |
+
name = f"{sid} {artist} - {title} (AI v11s5d + human).osz".replace("/", "_")
|
| 242 |
+
write_osz(a.out / re.sub(r'[\\:*?"<>|]', "_", name), audio_name, audio, files)
|
| 243 |
+
rep["notes"] = {f"{l} {NAMES[t]}": int((np.asarray(cs[t]["type"]) <= 3).sum()) for l, cs in (("P", pcharts), ("5c", ccharts)) for t in TIERS}
|
| 244 |
+
report[str(sid)] = rep
|
| 245 |
+
print(sid, title, json.dumps(rep, ensure_ascii=False), flush=True)
|
| 246 |
+
(a.out / "report.json").write_text(json.dumps(report, indent=1, ensure_ascii=False))
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def new(a):
|
| 250 |
+
from chartgen import song_planner as sp
|
| 251 |
+
from chartgen.gen_mapset import planner_rows
|
| 252 |
+
from chartgen.infer import frame_activations, load_model
|
| 253 |
+
from chartgen.v11 import pmap, s2_arms, s5a
|
| 254 |
+
from chartgen.v11.rmap import load_rmap, predict_group
|
| 255 |
+
from chartgen.v11.rmap_data import Group, beat_table
|
| 256 |
+
from chartgen.v11.rmap_eval import apply_calib, load_calib
|
| 257 |
+
from chartgen.v11.rmap_pseudo import Sampler
|
| 258 |
+
from chartgen.v11.song_signature import song_onsets
|
| 259 |
+
device = torch.device("cpu")
|
| 260 |
+
b9 = load_model(RUNS / "b9fix/best.pt", device)
|
| 261 |
+
enc = load_model(REPO / "data/runs/v1-full-1615/best.pt", device).eval()
|
| 262 |
+
ck = torch.load(RUNS / "sp9/best.pt", map_location=device)
|
| 263 |
+
planner = sp.SongPlanner(ck["d_in"]).to(device).eval()
|
| 264 |
+
planner.load_state_dict(ck["model"])
|
| 265 |
+
rmodel = load_rmap(RUNS / "r_full/best.pt", device)
|
| 266 |
+
pm = pmap.load_pmap(RUNS / "p_s0/best.pt", device)
|
| 267 |
+
S2 = RUNS / "v11_s2"
|
| 268 |
+
P5 = s5a.Params(RUNS / "v11_s5a/params.json")
|
| 269 |
+
calib_R = load_calib(S2 / "calib_R.json")
|
| 270 |
+
ctx = {"model": b9, "planner": planner, "device": device, "args": SimpleNamespace(seed=a.seed),
|
| 271 |
+
"cal": json.loads((RUNS / "sp9/thresholds.json").read_text())["calibration"],
|
| 272 |
+
"prior": pickle.load(open(RUNS / "sp9/chart_prior.pkl", "rb")),
|
| 273 |
+
"protos": pickle.load(open(RUNS / "sp9/protos.pkl", "rb")),
|
| 274 |
+
"cutoffs": json.loads((RUNS / "sp9/song_prop_cutoffs.json").read_text()),
|
| 275 |
+
"rest_band": (0.1, 0.6), "smp": Sampler(), "eighth": json.loads((S2 / "eighth_draw_table.json").read_text()),
|
| 276 |
+
"taus": json.loads((S2 / "taus.json").read_text())["tau"], "s5a": P5,
|
| 277 |
+
"min_gap": {str(k): v for k, v in FLOORS.items()}, "kiai_p": {}, "rest_scores": {}}
|
| 278 |
+
songs = json.loads(Path(a.songs).read_text())
|
| 279 |
+
a.out.mkdir(parents=True, exist_ok=True)
|
| 280 |
+
groups, report = {}, {}
|
| 281 |
+
for k, s in enumerate(songs):
|
| 282 |
+
if a.only and s["id"] not in a.only:
|
| 283 |
+
continue
|
| 284 |
+
tf = json.loads((a.timing / f"{s['id']}.json").read_text())
|
| 285 |
+
sections = np.asarray(tf["sections"], np.float64)
|
| 286 |
+
raw = Path(s["audio"]).read_bytes()
|
| 287 |
+
mel = mel_of(raw)
|
| 288 |
+
t0, t1 = float(tf["t0"]), float(tf["t1"])
|
| 289 |
+
sid = 990000000 + k
|
| 290 |
+
table = beat_table(sections, len(mel))
|
| 291 |
+
g = Group(sid, f"new|{s['id']}", "new", 3, table, sections, song_index=0)
|
| 292 |
+
corpus = SimpleNamespace(groups=[g], songs=[{"mel": mel}], ons=[song_onsets(mel)])
|
| 293 |
+
lg = predict_group(rmodel, corpus, 0, device)
|
| 294 |
+
uid = s2_arms.group_uid(sid, sections)
|
| 295 |
+
ctx["maps"] = {"R": {"maps": {uid: lg}, "calib": calib_R}}
|
| 296 |
+
ctx["mel"], ctx["table"] = mel, table
|
| 297 |
+
feat, b_song = planner_rows(enc, mel, sections, device)
|
| 298 |
+
song = {"beatmapset_id": sid, "song_key": f"new|{s['id']}", "charts": [], "mel": mel}
|
| 299 |
+
out, extra, _, _ = s2_arms.make_draw(ctx, song, sections, t0, t1, feat, b_song, 0, ["G8"])
|
| 300 |
+
ccharts = {t: dict(out["G8"][t]) for t in TIERS}
|
| 301 |
+
kiai_p = ctx["kiai_p"][4]
|
| 302 |
+
kc = shared_kiai(kiai_p, sections, ccharts)
|
| 303 |
+
for t in TIERS:
|
| 304 |
+
ccharts[t]["kiai"] = kc
|
| 305 |
+
res = pmap.gen_song(pm, corpus, 0, song, apply_calib(lg, calib_R), P5, {str(k2): v for k2, v in FLOORS.items()},
|
| 306 |
+
a.seed, 1, device, span=(t0 - 2000.0, t1))
|
| 307 |
+
pcharts, rep = {}, {}
|
| 308 |
+
for t in TIERS:
|
| 309 |
+
pc = res[0]["charts"][t]
|
| 310 |
+
plan = p_plan(hits(pc), sections, extra["G8"][t]["plan"])
|
| 311 |
+
pcharts[t], rep[NAMES[t]] = p_full(b9, mel, sections, t, pc, res[0]["p"][t]["tok"], table, plan,
|
| 312 |
+
t0 - 2000.0, t1, device, a.seed + sid + 1000 * t)
|
| 313 |
+
rep[NAMES[t]]["1/8 gate on"] = bool(res[0]["p"][t]["eighth_on"])
|
| 314 |
+
kp = shared_kiai(kiai_p, sections, pcharts)
|
| 315 |
+
for t in TIERS:
|
| 316 |
+
pcharts[t]["kiai"] = kp
|
| 317 |
+
aname = f"audio{Path(s['audio']).suffix.lower()}"
|
| 318 |
+
grp = groups.setdefault(s.get("osz", s["id"]), {"raw": raw, "aname": aname, "files": [], "song": s})
|
| 319 |
+
for label, cs in (("P", pcharts), ("5c", ccharts)):
|
| 320 |
+
for t in TIERS:
|
| 321 |
+
v = f"{label} {NAMES[t]}{s.get('suffix', '')}"
|
| 322 |
+
grp["files"].append((f"{s['artist']} - {s['title']} (chartgen) [{v}].osu".replace("/", "_"),
|
| 323 |
+
osu_text(cs[t], sections, aname, s["title"], s["artist"], v)))
|
| 324 |
+
rep["notes"] = {f"{l} {NAMES[t]}": int((np.asarray(cs[t]["type"]) <= 3).sum()) for l, cs in (("P", pcharts), ("5c", ccharts)) for t in TIERS}
|
| 325 |
+
report[s["id"]] = rep
|
| 326 |
+
pickle.dump({"sections": sections, "P": pcharts, "5c": ccharts}, open(a.out / f"{s['id']}.charts.pkl", "wb"))
|
| 327 |
+
print(s["id"], json.dumps(rep, ensure_ascii=False), flush=True)
|
| 328 |
+
for gname, grp in groups.items():
|
| 329 |
+
s = grp["song"]
|
| 330 |
+
name = re.sub(r'[\\/:*?"<>|]', "_", f"{s['artist']} - {s['title']} (AI v11s5d).osz")
|
| 331 |
+
write_osz(a.out / name, grp["aname"], grp["raw"], grp["files"])
|
| 332 |
+
print(gname, "->", name, len(grp["files"]), "difficulties", flush=True)
|
| 333 |
+
(a.out / "report.json").write_text(json.dumps(report, indent=1, ensure_ascii=False))
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def main(argv=None):
|
| 337 |
+
p = argparse.ArgumentParser()
|
| 338 |
+
p.add_argument("cmd", choices=["val", "new"])
|
| 339 |
+
p.add_argument("--out", type=Path, default=None)
|
| 340 |
+
p.add_argument("--songs", type=Path, default=Path("data/osz_play/v11_new/songs.json"))
|
| 341 |
+
p.add_argument("--timing", type=Path, default=Path("data/osz_play/v11_new/timing"))
|
| 342 |
+
p.add_argument("--seed", type=int, default=0)
|
| 343 |
+
p.add_argument("--only", nargs="*", default=[])
|
| 344 |
+
a = p.parse_args(argv)
|
| 345 |
+
a.out = a.out or Path("data/osz_play/v11_s5d" if a.cmd == "val" else "data/osz_play/v11_s5d_new")
|
| 346 |
+
{"val": val, "new": new}[a.cmd](a)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
if __name__ == "__main__":
|
| 350 |
+
main()
|
chartgen/v11/song_signature.py
ADDED
|
@@ -0,0 +1,745 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""v11 stage 0, P0.1 (reports/v11 階段 0 預先登記:參考線.md): does a song-level audio signature that reads all 24
|
| 2 |
+
candidate positions per beat (the P0.5 position set, which includes the odd 1/8 positions) predict the song-level 1/8
|
| 3 |
+
amount better than the current signature with 12 positions per beat?
|
| 4 |
+
|
| 5 |
+
Song signature, from the song's log-Mel (100 fps) and the timing sections of one chart (the reference chart):
|
| 6 |
+
|
| 7 |
+
columns onset strength of the 5 bands of song_planner.onset_bands (positive spectral flux, z-scored per song) and
|
| 8 |
+
loudness (z-scored mean log-Mel): the 6 columns the planner rows use (song_planner --beat-sync --loudness);
|
| 9 |
+
beats every whole beat of the timing whose span lies inside the audio and inside one timing section;
|
| 10 |
+
pos12 positions k/12 beat (k = 0..11), each read as the max over +-1 frame around it (the planner's reading,
|
| 11 |
+
song_planner.beat_sync, there at 48 slots per measure = 12 per beat in 4/4);
|
| 12 |
+
pos24 positions k/48 beat with k a multiple of 3 or 4 (24 positions: every 1/3, 1/4, 1/6, 1/8, 1/12 and 1/16
|
| 13 |
+
position; same set as v11.patterns.POSITIONS), each read as the max over its own time window: from halfway
|
| 14 |
+
to the previous position to halfway to the next one, and at least +-1 frame;
|
| 15 |
+
signature the mean over beats of these values ([positions x 6]), plus log main BPM (rhythm_eval.main_bpm).
|
| 16 |
+
|
| 17 |
+
Both signatures use the same code; only the positions and the window rule differ. Unlike beat_sync, values are not
|
| 18 |
+
floored at -1 (beat_sync starts its max from -1).
|
| 19 |
+
|
| 20 |
+
Probe, per tier (Oni 3, Inner Oni 4), on the planner rows (runs/ps9/rows.pkl, train and val songs; song_split is
|
| 21 |
+
checked again so no test song can enter): ridge regression from the signature to the chart's 1/8 setting
|
| 22 |
+
(latent_stats.chart_settings index 3; the P0.1 target) and triplet setting (index 2; reported only). Out-of-fold
|
| 23 |
+
predictions over 4 folds grouped by song (sha1 'fold:<song>' % 4, as latent_stats and the earlier probes); the ridge
|
| 24 |
+
strength is chosen inside each training part by a 3-fold split grouped by song. Reported: R2, correlation and slope
|
| 25 |
+
(of the prediction on the human value) of the out-of-fold predictions, each with a song bootstrap 95% CI (1000x,
|
| 26 |
+
seed 0), and the paired difference pos24 - pos12 on the same resamples; the same per tempo band (rhythm_eval2.TEMPO,
|
| 27 |
+
from the same resamples); and a log-BPM-only line for reference.
|
| 28 |
+
|
| 29 |
+
P0.1 prediction: R2(pos24) - R2(pos12) >= 0.08 for the 1/8 setting at both Oni and Inner Oni.
|
| 30 |
+
|
| 31 |
+
python -m chartgen.v11.song_signature --rows runs/ps9/rows.pkl --data data/features/taiko-*.pkl \\
|
| 32 |
+
--out runs/v11_s0/sig_probe.json --save-rows runs/v11_s0/sig_rows.npz
|
| 33 |
+
python -m chartgen.v11.song_signature --from-rows runs/v11_s0/sig_rows.npz --out sig_probe.json # analysis only
|
| 34 |
+
python -m chartgen.v11.song_signature --selftest [--tmp DIR] # synthetic data
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
from __future__ import annotations
|
| 38 |
+
|
| 39 |
+
import argparse
|
| 40 |
+
import hashlib
|
| 41 |
+
import json
|
| 42 |
+
import math
|
| 43 |
+
import pickle
|
| 44 |
+
import sys
|
| 45 |
+
import tempfile
|
| 46 |
+
import time
|
| 47 |
+
from collections import Counter
|
| 48 |
+
from pathlib import Path
|
| 49 |
+
|
| 50 |
+
import numpy as np
|
| 51 |
+
|
| 52 |
+
from chartgen.dataset import GRID, _beats_at, load_songs
|
| 53 |
+
from chartgen.latent_stats import chart_settings
|
| 54 |
+
from chartgen.rhythm_eval import main_bpm
|
| 55 |
+
from chartgen.rhythm_eval2 import TEMPO
|
| 56 |
+
from chartgen.song_planner import BANDS, onset_bands
|
| 57 |
+
from chartgen.train import song_split
|
| 58 |
+
|
| 59 |
+
POS12 = np.arange(0, GRID, 4) # k/12 beat, in 1/48 beat
|
| 60 |
+
POS24 = np.array([k for k in range(GRID) if k % 3 == 0 or k % 4 == 0]) # P0.5 set, 24 positions
|
| 61 |
+
COLS = tuple(f"band{a}-{b}" for a, b in BANDS) + ("loudness",)
|
| 62 |
+
TARGETS = {"eighth": 3, "triplet": 2} # chart_settings index
|
| 63 |
+
TIER_NAMES = {3: "Oni", 4: "Inner Oni"}
|
| 64 |
+
FEATURE_SETS = ("pos12", "pos24", "pos24n", "bpm_only") # pos24n: pos24 read at +-1 frame (window control)
|
| 65 |
+
LAMS = (0.1, 1.0, 10.0, 100.0, 1000.0, 10000.0) # penalty = lam * n_train / 100
|
| 66 |
+
P01_MARGIN = 0.08
|
| 67 |
+
MIN_BEATS = 8
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# ------------------------------------------------------------------------------------------------ signature
|
| 71 |
+
|
| 72 |
+
def song_onsets(mel) -> np.ndarray:
|
| 73 |
+
"""[frames, 6]: band onsets and loudness of a song, as the planner rows build them."""
|
| 74 |
+
ons = onset_bands(mel)
|
| 75 |
+
lm = np.asarray(mel, np.float32).mean(1)
|
| 76 |
+
return np.concatenate([ons, ((lm - lm.mean()) / (lm.std() + 1e-6))[:, None]], 1).astype(np.float32)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _section_of_beat(s: np.ndarray, beats: np.ndarray) -> np.ndarray:
|
| 80 |
+
return np.clip(np.searchsorted(s[:, 3], beats + 1e-9, side="right") - 1, 0, len(s) - 1)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def whole_beats(sections, n_frames: int) -> np.ndarray:
|
| 84 |
+
"""Global beat numbers b (floats with integer values) whose span [b, b + 1) lies inside the audio and inside one
|
| 85 |
+
timing section (a beat cut short by the next red line is left out)."""
|
| 86 |
+
s = np.asarray(sections, np.float64)
|
| 87 |
+
end_ms = n_frames * 10.0
|
| 88 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 89 |
+
lo, hi = (float(x) for x in _beats_at(s, np.array([0.0, end_ms])))
|
| 90 |
+
if not (math.isfinite(lo) and math.isfinite(hi)):
|
| 91 |
+
return np.zeros(0)
|
| 92 |
+
b = np.arange(math.ceil(lo - 1e-6), math.floor(hi + 1e-6), dtype=np.float64)
|
| 93 |
+
if len(b) == 0:
|
| 94 |
+
return b
|
| 95 |
+
j = _section_of_beat(s, b)
|
| 96 |
+
bl = s[j, 1]
|
| 97 |
+
t0 = s[j, 0] + (b - s[j, 3]) * bl
|
| 98 |
+
t1 = t0 + bl
|
| 99 |
+
nxt = np.where(j + 1 < len(s), s[np.minimum(j + 1, len(s) - 1), 0], np.inf)
|
| 100 |
+
keep = (bl > 0) & (t0 >= 0) & (t1 <= end_ms) & (t1 <= nxt + 1.0)
|
| 101 |
+
return b[keep]
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def position_windows(sections, beats: np.ndarray, pos48: np.ndarray, own_window: bool):
|
| 105 |
+
"""Frames read for each (beat, position): (centre f, first lo, last hi), each [n_beats, n_positions].
|
| 106 |
+
own_window=False: f +- 1 frame. own_window=True: the frames whose time lies between halfway to the previous
|
| 107 |
+
position and halfway to the next one (positions wrap around the beat), and at least f +- 1."""
|
| 108 |
+
s = np.asarray(sections, np.float64)
|
| 109 |
+
pos48 = np.asarray(pos48, np.float64)
|
| 110 |
+
j = _section_of_beat(s, beats)
|
| 111 |
+
bl = s[j, 1][:, None]
|
| 112 |
+
t = (s[j, 0] + (beats - s[j, 3]) * s[j, 1])[:, None] + bl * pos48[None] / GRID
|
| 113 |
+
f = np.round(t / 10.0).astype(np.int64)
|
| 114 |
+
if not own_window:
|
| 115 |
+
return f, f - 1, f + 1
|
| 116 |
+
prev = np.diff(np.r_[pos48[-1] - GRID, pos48])
|
| 117 |
+
nxt = np.diff(np.r_[pos48, pos48[0] + GRID])
|
| 118 |
+
hl = bl * prev[None] / GRID / 2
|
| 119 |
+
hr = bl * nxt[None] / GRID / 2
|
| 120 |
+
lo = np.minimum(f - 1, np.ceil((t - hl) / 10.0 - 1e-9).astype(np.int64))
|
| 121 |
+
hi = np.maximum(f + 1, np.floor((t + hr) / 10.0 + 1e-9).astype(np.int64))
|
| 122 |
+
return f, lo, hi
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def read_max(onsets: np.ndarray, lo: np.ndarray, hi: np.ndarray) -> np.ndarray:
|
| 126 |
+
"""[*lo.shape, columns]: max of onsets over frames lo..hi (inclusive, frames outside the audio skipped; NaN when
|
| 127 |
+
no frame of the window is inside the audio)."""
|
| 128 |
+
T = len(onsets)
|
| 129 |
+
out = np.full(lo.shape + (onsets.shape[1],), -np.inf, np.float32)
|
| 130 |
+
width = int((hi - lo).max()) if lo.size else 0
|
| 131 |
+
for d in range(width + 1):
|
| 132 |
+
g = lo + d
|
| 133 |
+
ok = (g <= hi) & (g >= 0) & (g < T)
|
| 134 |
+
if ok.any():
|
| 135 |
+
out[ok] = np.maximum(out[ok], onsets[g[ok]])
|
| 136 |
+
out[~np.isfinite(out)] = np.nan
|
| 137 |
+
return out
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def signature(onsets: np.ndarray, sections, pos48: np.ndarray, own_window: bool, beats: np.ndarray | None = None):
|
| 141 |
+
"""[len(pos48) * columns] mean over beats (position-major), and the mean window width in frames."""
|
| 142 |
+
if beats is None:
|
| 143 |
+
beats = whole_beats(sections, len(onsets))
|
| 144 |
+
_, lo, hi = position_windows(sections, beats, pos48, own_window)
|
| 145 |
+
v = read_max(onsets, lo, hi)
|
| 146 |
+
return np.nanmean(v, 0).reshape(-1), float((hi - lo + 1).mean())
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def chart_signatures(onsets: np.ndarray, sections) -> dict | str:
|
| 150 |
+
"""Both signatures of one chart's timing over a song's onsets, or the reason they cannot be made: 'too_few_beats'
|
| 151 |
+
(< MIN_BEATS whole beats inside the audio) or 'bad_timing' (main BPM not a positive number, or a non-finite
|
| 152 |
+
signature)."""
|
| 153 |
+
beats = whole_beats(sections, len(onsets))
|
| 154 |
+
if len(beats) < MIN_BEATS:
|
| 155 |
+
return "too_few_beats"
|
| 156 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 157 |
+
bpm = float(main_bpm(sections))
|
| 158 |
+
if not (math.isfinite(bpm) and bpm > 0):
|
| 159 |
+
return "bad_timing"
|
| 160 |
+
sig12, w12 = signature(onsets, sections, POS12, False, beats)
|
| 161 |
+
sig24, w24 = signature(onsets, sections, POS24, True, beats)
|
| 162 |
+
sig24n, _ = signature(onsets, sections, POS24, False, beats)
|
| 163 |
+
if not (np.isfinite(sig12).all() and np.isfinite(sig24).all() and np.isfinite(sig24n).all()):
|
| 164 |
+
return "bad_timing"
|
| 165 |
+
s = np.asarray(sections, np.float64)
|
| 166 |
+
odd_bpm = 60000.0 / s[_section_of_beat(s, beats), 1]
|
| 167 |
+
return {"sig12": sig12.astype(np.float32), "sig24": sig24.astype(np.float32), "sig24n": sig24n.astype(np.float32),
|
| 168 |
+
"lbpm": math.log(bpm),
|
| 169 |
+
"n_beats": int(len(beats)), "win12": w12, "win24": w24,
|
| 170 |
+
"odd_tempo_share": float(((odd_bpm < 40) | (odd_bpm > 400)).mean())}
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
# ------------------------------------------------------------------------------------------------ data
|
| 174 |
+
|
| 175 |
+
def song_of(meta) -> str:
|
| 176 |
+
return meta[3] or str(meta[0])
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def collect(rows_path: Path, shard_paths: list[Path], tiers=(3, 4), splits=("train", "val"), rows=None):
|
| 180 |
+
"""Records (one per chart of the given tiers in the planner rows) with targets and both signatures, and counts."""
|
| 181 |
+
t0 = time.time()
|
| 182 |
+
R = rows if rows is not None else pickle.load(open(rows_path, "rb"))
|
| 183 |
+
cnt = Counter()
|
| 184 |
+
need: dict[int, dict[int, dict]] = {}
|
| 185 |
+
for split in splits:
|
| 186 |
+
for x in R.get(split, []):
|
| 187 |
+
tier = int(x[2])
|
| 188 |
+
if tier not in tiers:
|
| 189 |
+
continue
|
| 190 |
+
meta = x[3]
|
| 191 |
+
song = song_of(meta)
|
| 192 |
+
cnt["rows"] += 1
|
| 193 |
+
if song_split(song) == "test":
|
| 194 |
+
cnt["skipped_test_split"] += 1
|
| 195 |
+
continue
|
| 196 |
+
if meta[1] is None:
|
| 197 |
+
cnt["skipped_no_beatmap_id"] += 1
|
| 198 |
+
continue
|
| 199 |
+
c = chart_settings(x[1])
|
| 200 |
+
if c is None:
|
| 201 |
+
cnt["skipped_no_settings"] += 1
|
| 202 |
+
continue
|
| 203 |
+
d = need.setdefault(int(meta[0]), {})
|
| 204 |
+
if int(meta[1]) in d:
|
| 205 |
+
cnt["skipped_duplicate_row"] += 1
|
| 206 |
+
continue
|
| 207 |
+
d[int(meta[1])] = {"split": split, "tier": tier, "song": song, "set": int(meta[0]), "bid": int(meta[1]),
|
| 208 |
+
"in_ps9": True,
|
| 209 |
+
**{k: float(c[i]) for k, i in TARGETS.items()}}
|
| 210 |
+
del R
|
| 211 |
+
print(f"rows: {dict(cnt)}; {sum(len(v) for v in need.values())} charts in {len(need)} sets to read "
|
| 212 |
+
f"({time.time() - t0:.0f} s)", flush=True)
|
| 213 |
+
for p in shard_paths:
|
| 214 |
+
n_here = 0
|
| 215 |
+
for s in load_songs([Path(p)], mmap=False):
|
| 216 |
+
want = need.get(int(s["beatmapset_id"]))
|
| 217 |
+
if not want:
|
| 218 |
+
continue
|
| 219 |
+
ons = None
|
| 220 |
+
for ch in s["charts"]:
|
| 221 |
+
r = want.get(int(ch["beatmap_id"])) if ch.get("beatmap_id") is not None else None
|
| 222 |
+
if r is None or "sig12" in r:
|
| 223 |
+
continue
|
| 224 |
+
if ons is None:
|
| 225 |
+
ons = song_onsets(s["mel"])
|
| 226 |
+
sig = chart_signatures(ons, ch["sections"])
|
| 227 |
+
if isinstance(sig, str):
|
| 228 |
+
r["skip"] = sig
|
| 229 |
+
continue
|
| 230 |
+
r.update(sig)
|
| 231 |
+
n_here += 1
|
| 232 |
+
print(f"{Path(p).name}: {n_here} charts, {time.time() - t0:.0f} s", flush=True)
|
| 233 |
+
recs = [r for v in need.values() for r in v.values() if "sig12" in r]
|
| 234 |
+
allr = [r for v in need.values() for r in v.values()]
|
| 235 |
+
for why in ("too_few_beats", "bad_timing"):
|
| 236 |
+
cnt[f"skipped_{why}"] = sum(1 for r in allr if r.get("skip") == why)
|
| 237 |
+
cnt["missing_in_shards"] = sum(1 for r in allr if "sig12" not in r and "skip" not in r)
|
| 238 |
+
cnt["used"] = len(recs)
|
| 239 |
+
return recs, dict(cnt)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def ps9_keys(path: Path) -> set:
|
| 243 |
+
"""(beatmapset_id, beatmap_id) of the Oni and Inner Oni charts in the planner rows: from rows.pkl, or from a .json
|
| 244 |
+
list written by --write-ps9-keys."""
|
| 245 |
+
if path.suffix == ".json":
|
| 246 |
+
return {tuple(k) for k in json.loads(path.read_text())}
|
| 247 |
+
R = pickle.load(open(path, "rb"))
|
| 248 |
+
return {(int(x[3][0]), int(x[3][1])) for sp in ("train", "val") for x in R.get(sp, [])
|
| 249 |
+
if int(x[2]) in (3, 4) and x[3][1] is not None}
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def collect_all(shard_paths: list[Path], tiers=(3, 4), splits=("train", "val"), ps9: set | None = None):
|
| 253 |
+
"""Records for every chart of the given tiers in the shards (train and val songs; >= 16 notes, the planner rows'
|
| 254 |
+
rule), with targets computed from the chart itself (chart_rows + chart_settings, as the planner rows do), and
|
| 255 |
+
counts. in_ps9 marks the charts that are also in the planner rows."""
|
| 256 |
+
from chartgen.song_planner import chart_rows
|
| 257 |
+
t0 = time.time()
|
| 258 |
+
cnt, recs, seen = Counter(), [], set()
|
| 259 |
+
for p in shard_paths:
|
| 260 |
+
n_here = 0
|
| 261 |
+
for s in load_songs([Path(p)], mmap=False):
|
| 262 |
+
song = s.get("song_key") or str(s["beatmapset_id"])
|
| 263 |
+
sp = song_split(song)
|
| 264 |
+
if sp == "test":
|
| 265 |
+
cnt["skipped_test_split_songs"] += 1
|
| 266 |
+
continue
|
| 267 |
+
if sp not in splits:
|
| 268 |
+
continue
|
| 269 |
+
ons = None
|
| 270 |
+
for ch in s["charts"]:
|
| 271 |
+
tier = int(ch["tier"])
|
| 272 |
+
if tier not in tiers:
|
| 273 |
+
continue
|
| 274 |
+
cnt["charts"] += 1
|
| 275 |
+
if len(ch["time"]) < 16:
|
| 276 |
+
cnt["skipped_lt16_notes"] += 1
|
| 277 |
+
continue
|
| 278 |
+
if ch.get("beatmap_id") is None:
|
| 279 |
+
cnt["skipped_no_beatmap_id"] += 1
|
| 280 |
+
continue
|
| 281 |
+
key = (int(s["beatmapset_id"]), int(ch["beatmap_id"]))
|
| 282 |
+
if key in seen:
|
| 283 |
+
cnt["skipped_duplicate"] += 1
|
| 284 |
+
continue
|
| 285 |
+
seen.add(key)
|
| 286 |
+
_, H, _ = chart_rows(np.zeros(((len(s["mel"]) + 1) // 2, 1), np.float32), ch)
|
| 287 |
+
c = chart_settings(H)
|
| 288 |
+
if c is None:
|
| 289 |
+
cnt["skipped_no_settings"] += 1
|
| 290 |
+
continue
|
| 291 |
+
if ons is None:
|
| 292 |
+
ons = song_onsets(s["mel"])
|
| 293 |
+
sig = chart_signatures(ons, ch["sections"])
|
| 294 |
+
if isinstance(sig, str):
|
| 295 |
+
cnt[f"skipped_{sig}"] += 1
|
| 296 |
+
continue
|
| 297 |
+
recs.append({"split": sp, "tier": tier, "song": song, "set": key[0], "bid": key[1],
|
| 298 |
+
"in_ps9": bool(ps9 is not None and key in ps9),
|
| 299 |
+
**{k: float(c[i]) for k, i in TARGETS.items()}, **sig})
|
| 300 |
+
n_here += 1
|
| 301 |
+
print(f"{Path(p).name}: {n_here} charts, {time.time() - t0:.0f} s", flush=True)
|
| 302 |
+
cnt["used"] = len(recs)
|
| 303 |
+
cnt["used_in_ps9"] = sum(r["in_ps9"] for r in recs)
|
| 304 |
+
return recs, dict(cnt)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
REC_KEYS = ("split", "song", "set", "bid", "tier", "in_ps9", "lbpm", "n_beats", "win12", "win24", "odd_tempo_share",
|
| 308 |
+
*TARGETS)
|
| 309 |
+
SIG_KEYS = ("sig12", "sig24", "sig24n")
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def save_recs(recs: list[dict], path: Path):
|
| 313 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 314 |
+
np.savez_compressed(
|
| 315 |
+
path, **{k: np.array([r[k] for r in recs]) for k in REC_KEYS},
|
| 316 |
+
**{k: np.stack([r[k] for r in recs]) for k in SIG_KEYS}, pos12=POS12, pos24=POS24, cols=np.array(COLS))
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def load_recs(paths) -> list[dict]:
|
| 320 |
+
"""Signatures saved with --save-rows, from one or more .npz files (one chart kept per (set, beatmap id))."""
|
| 321 |
+
out, seen = [], set()
|
| 322 |
+
for path in ([paths] if isinstance(paths, (str, Path)) else paths):
|
| 323 |
+
z = np.load(path, allow_pickle=False)
|
| 324 |
+
for i in range(len(z["tier"])):
|
| 325 |
+
r = {k: z[k][i].item() for k in REC_KEYS}
|
| 326 |
+
if (r["set"], r["bid"]) in seen:
|
| 327 |
+
continue
|
| 328 |
+
seen.add((r["set"], r["bid"]))
|
| 329 |
+
for k in SIG_KEYS:
|
| 330 |
+
r[k] = z[k][i]
|
| 331 |
+
out.append(r)
|
| 332 |
+
return out
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
# ------------------------------------------------------------------------------------------------ probe
|
| 336 |
+
|
| 337 |
+
def _hfold(song: str, salt: str, k: int) -> int:
|
| 338 |
+
return int(hashlib.sha1(f"{salt}:{song}".encode()).hexdigest(), 16) % k
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def _ridge(Xtr, ytr, Xte, lam):
|
| 342 |
+
mu, sd = Xtr.mean(0), Xtr.std(0) + 1e-6
|
| 343 |
+
A, B = (Xtr - mu) / sd, (Xte - mu) / sd
|
| 344 |
+
y0 = ytr.mean()
|
| 345 |
+
W = np.linalg.solve(A.T @ A + lam * len(A) / 100 * np.eye(A.shape[1]), A.T @ (ytr - y0))
|
| 346 |
+
return B @ W + y0
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def _r2(y, p):
|
| 350 |
+
sst = ((y - y.mean()) ** 2).sum()
|
| 351 |
+
return 1 - ((y - p) ** 2).sum() / sst if sst > 0 else float("nan")
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def ridge_oof(X, y, songs, lams=LAMS):
|
| 355 |
+
"""Out-of-fold predictions over 4 folds grouped by song; ridge strength chosen per outer fold by a 3-fold inner
|
| 356 |
+
split (grouped by song) of its training part. Returns (predictions, chosen strength per fold)."""
|
| 357 |
+
outer = np.array([_hfold(s, "fold", 4) for s in songs])
|
| 358 |
+
inner = np.array([_hfold(s, "inner", 3) for s in songs])
|
| 359 |
+
p = np.full(len(y), np.nan)
|
| 360 |
+
chosen = []
|
| 361 |
+
for k in range(4):
|
| 362 |
+
tr, te = outer != k, outer == k
|
| 363 |
+
if not te.any():
|
| 364 |
+
continue
|
| 365 |
+
Xi, yi, fi = X[tr], y[tr], inner[tr]
|
| 366 |
+
best = None
|
| 367 |
+
for lam in lams:
|
| 368 |
+
q = np.full(len(yi), yi.mean())
|
| 369 |
+
for j in range(3):
|
| 370 |
+
a, b = fi != j, fi == j
|
| 371 |
+
if a.any() and b.any():
|
| 372 |
+
q[b] = _ridge(Xi[a], yi[a], Xi[b], lam)
|
| 373 |
+
r2 = _r2(yi, q)
|
| 374 |
+
if best is None or r2 > best[0]:
|
| 375 |
+
best = (r2, lam)
|
| 376 |
+
chosen.append(best[1])
|
| 377 |
+
p[te] = _ridge(Xi, yi, X[te], best[1])
|
| 378 |
+
return p, chosen
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def metrics(y, p) -> np.ndarray:
|
| 382 |
+
"""[R2, correlation, slope of p on y]."""
|
| 383 |
+
if len(y) < 3:
|
| 384 |
+
return np.full(3, np.nan)
|
| 385 |
+
yc, pc = y - y.mean(), p - p.mean()
|
| 386 |
+
sst, spp = (yc ** 2).sum(), (pc ** 2).sum()
|
| 387 |
+
if sst <= 0:
|
| 388 |
+
return np.full(3, np.nan)
|
| 389 |
+
sxy = (yc * pc).sum()
|
| 390 |
+
return np.array([1 - ((y - p) ** 2).sum() / sst, sxy / math.sqrt(sst * spp) if spp > 0 else np.nan, sxy / sst])
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
METRICS = ("r2", "corr", "slope")
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def _ci(est, boot):
|
| 397 |
+
boot = np.asarray(boot, float)
|
| 398 |
+
ok = np.isfinite(boot)
|
| 399 |
+
lo, hi = (np.percentile(boot[ok], [2.5, 97.5]) if ok.sum() >= 10 else (np.nan, np.nan))
|
| 400 |
+
return [round(float(est), 4), round(float(lo), 4), round(float(hi), 4)]
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def summarize(y, P: dict, songs, mask, reps):
|
| 404 |
+
"""Metrics of each feature set and of pos24 - pos12 on the rows in mask, with CIs over the song resamples."""
|
| 405 |
+
idx = np.where(mask)[0]
|
| 406 |
+
res = {"n_charts": int(len(idx)), "n_songs": int(len(set(songs[idx]))),
|
| 407 |
+
"y_mean": round(float(y[idx].mean()), 4) if len(idx) else None,
|
| 408 |
+
"y_sd": round(float(y[idx].std()), 4) if len(idx) else None}
|
| 409 |
+
if len(idx) < 10:
|
| 410 |
+
return res
|
| 411 |
+
est = {fs: metrics(y[idx], P[fs][idx]) for fs in P}
|
| 412 |
+
boot = {fs: [] for fs in P}
|
| 413 |
+
for rep in reps:
|
| 414 |
+
r = rep[mask[rep]]
|
| 415 |
+
for fs in P:
|
| 416 |
+
boot[fs].append(metrics(y[r], P[fs][r]))
|
| 417 |
+
boot = {fs: np.array(v) for fs, v in boot.items()}
|
| 418 |
+
for fs in P:
|
| 419 |
+
res[fs] = {m: _ci(est[fs][i], boot[fs][:, i]) for i, m in enumerate(METRICS)}
|
| 420 |
+
for a in ("pos24", "pos24n"):
|
| 421 |
+
d_est, d_boot = est[a] - est["pos12"], boot[a] - boot["pos12"]
|
| 422 |
+
res[f"{a}_minus_pos12"] = {m: _ci(d_est[i], d_boot[:, i]) for i, m in enumerate(METRICS)}
|
| 423 |
+
return res
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def design(recs, fs) -> np.ndarray:
|
| 427 |
+
lb = np.array([[r["lbpm"]] for r in recs], np.float64)
|
| 428 |
+
if fs == "bpm_only":
|
| 429 |
+
return lb
|
| 430 |
+
return np.concatenate([np.stack([r["sig" + fs[3:]] for r in recs]).astype(np.float64), lb], 1)
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def probe(recs, tiers=(3, 4), n_boot=1000, seed=0, lams=LAMS) -> dict:
|
| 434 |
+
out = {}
|
| 435 |
+
for t in tiers:
|
| 436 |
+
R = [r for r in recs if r["tier"] == t]
|
| 437 |
+
name = TIER_NAMES.get(t, f"tier{t}")
|
| 438 |
+
if len(R) < 20:
|
| 439 |
+
out[name] = {"n_charts": len(R), "note": "too few charts"}
|
| 440 |
+
continue
|
| 441 |
+
songs = np.array([r["song"] for r in R])
|
| 442 |
+
bpm = np.exp(np.array([r["lbpm"] for r in R]))
|
| 443 |
+
uniq, inv = np.unique(songs, return_inverse=True)
|
| 444 |
+
members = [np.where(inv == i)[0] for i in range(len(uniq))]
|
| 445 |
+
rng = np.random.default_rng(seed)
|
| 446 |
+
reps = [np.concatenate([members[i] for i in rng.integers(len(uniq), size=len(uniq))]) for _ in range(n_boot)]
|
| 447 |
+
X = {fs: design(R, fs) for fs in FEATURE_SETS}
|
| 448 |
+
Xbad = {fs: int((~np.isfinite(X[fs])).any(1).sum()) for fs in FEATURE_SETS}
|
| 449 |
+
if any(Xbad.values()):
|
| 450 |
+
raise ValueError(f"non-finite signatures in {Xbad} charts of tier {t}")
|
| 451 |
+
block = {"n_charts": len(R), "n_songs": int(len(uniq)), "n_sets": int(len({r['set'] for r in R}))}
|
| 452 |
+
for tgt in TARGETS:
|
| 453 |
+
y = np.array([r[tgt] for r in R])
|
| 454 |
+
P, lam = {}, {}
|
| 455 |
+
for fs in FEATURE_SETS:
|
| 456 |
+
P[fs], lam[fs] = ridge_oof(X[fs], y, songs, lams)
|
| 457 |
+
res = {"overall": summarize(y, P, songs, np.ones(len(y), bool), reps), "by_tempo": {}, "ridge_strength": lam}
|
| 458 |
+
for lo, hi in TEMPO:
|
| 459 |
+
res["by_tempo"][f"{lo}-{hi} BPM"] = summarize(y, P, songs, (bpm >= lo) & (bpm < hi), reps)
|
| 460 |
+
block[tgt] = res
|
| 461 |
+
out[name] = block
|
| 462 |
+
return out
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def p01_verdict(res: dict) -> dict:
|
| 466 |
+
v = {}
|
| 467 |
+
for name in ("Oni", "Inner Oni"):
|
| 468 |
+
d = (((res.get(name) or {}).get("eighth") or {}).get("overall") or {}).get("pos24_minus_pos12")
|
| 469 |
+
v[name] = {"delta_r2": d["r2"] if d else None}
|
| 470 |
+
ds = [v[n]["delta_r2"] for n in ("Oni", "Inner Oni")]
|
| 471 |
+
if all(d is not None for d in ds):
|
| 472 |
+
v["held_point_estimate"] = all(d[0] >= P01_MARGIN for d in ds)
|
| 473 |
+
v["ci_lower_ge_margin_both"] = all(d[1] >= P01_MARGIN for d in ds)
|
| 474 |
+
v["ci_lower_gt_0_both"] = all(d[1] > 0 for d in ds)
|
| 475 |
+
v["rule"] = (f"pre-registration: R2 of the 1/8 setting rises by at least {P01_MARGIN} at both Oni and Inner Oni "
|
| 476 |
+
"(a point threshold; it names no CI rule, so both readings are given)")
|
| 477 |
+
return v
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
def config() -> dict:
|
| 481 |
+
return {"prereg": "reports/v11 階段 0 預先登記:參考線.md, P0.1",
|
| 482 |
+
"pos12_1_48": POS12.tolist(), "pos24_1_48": POS24.tolist(), "columns": list(COLS),
|
| 483 |
+
"read_pos12": "max over round(t/10) +- 1 frame", "read_pos24": "max over own window (halfway to neighbours), >= +-1 frame",
|
| 484 |
+
"read_pos24n": "pos24 positions read like pos12 (+- 1 frame); report-only window control",
|
| 485 |
+
"decision": "point estimate of the 1/8 R2 difference (pos24 - pos12) >= 0.08 at Oni and at Inner Oni (addendum)",
|
| 486 |
+
"features": "mean over whole beats inside the audio, plus log main BPM",
|
| 487 |
+
"targets": {k: f"chart_settings index {i}" for k, i in TARGETS.items()},
|
| 488 |
+
"folds": "4, grouped by song, sha1('fold:'+song) % 4; ridge strength by 3-fold inner split (sha1('inner:'+song) % 3)",
|
| 489 |
+
"ridge_strengths": list(LAMS), "slope": "of out-of-fold prediction on human value",
|
| 490 |
+
"bootstrap": "songs, 1000x, seed 0, percentile 95% CI; tempo bands subset the same resamples",
|
| 491 |
+
"tempo_bands": [list(b) for b in TEMPO]}
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def report(res: dict):
|
| 495 |
+
for name, block in res.items():
|
| 496 |
+
if not isinstance(block, dict) or "eighth" not in block:
|
| 497 |
+
continue
|
| 498 |
+
for tgt in TARGETS:
|
| 499 |
+
print(f"\n== {tgt} setting, {name} (charts {block['n_charts']}, songs {block['n_songs']})")
|
| 500 |
+
rows = [("overall", block[tgt]["overall"])] + list(block[tgt]["by_tempo"].items())
|
| 501 |
+
for lab, s in rows:
|
| 502 |
+
print(f" [{lab}] n={s['n_charts']} songs={s['n_songs']}")
|
| 503 |
+
for fs in (*FEATURE_SETS, "pos24_minus_pos12", "pos24n_minus_pos12"):
|
| 504 |
+
if fs in s:
|
| 505 |
+
print(f" {fs:18s} " + " ".join(f"{m} {v[0]:+.3f} [{v[1]:+.3f},{v[2]:+.3f}]" for m, v in s[fs].items()))
|
| 506 |
+
print(f" ridge strength per fold: {block[tgt]['ridge_strength']}")
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def run_probe(recs, counts, out: Path, n_boot: int, seed: int, tiers):
|
| 510 |
+
res = probe(recs, tiers=tiers, n_boot=n_boot, seed=seed)
|
| 511 |
+
doc = {"config": {**config(), "n_boot": n_boot, "seed": seed}, "counts": counts,
|
| 512 |
+
"diagnostics": {"mean_window_frames_pos12": float(np.mean([r["win12"] for r in recs])),
|
| 513 |
+
"mean_window_frames_pos24": float(np.mean([r["win24"] for r in recs])),
|
| 514 |
+
"charts_with_beats_outside_40_400_bpm": int(sum(r["odd_tempo_share"] > 0 for r in recs))},
|
| 515 |
+
"results": res, "p0_1": p01_verdict(res)}
|
| 516 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 517 |
+
out.write_text(json.dumps(doc, indent=1, ensure_ascii=False))
|
| 518 |
+
report(res)
|
| 519 |
+
print("\nP0.1:", json.dumps(doc["p0_1"], ensure_ascii=False), flush=True)
|
| 520 |
+
return doc
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
# ------------------------------------------------------------------------------------------------ self-test
|
| 524 |
+
|
| 525 |
+
def _click_mel(rng, n_frames, times_ms, n_mels=128):
|
| 526 |
+
"""Noise plus a one-frame broadband click at each time (one frame, so a click never reaches a neighbour's window
|
| 527 |
+
through its decay)."""
|
| 528 |
+
mel = -8.0 + 0.3 * rng.standard_normal((n_frames, n_mels))
|
| 529 |
+
for t in times_ms:
|
| 530 |
+
f = int(round(t / 10.0))
|
| 531 |
+
if 0 <= f < n_frames:
|
| 532 |
+
mel[f] += 4.0
|
| 533 |
+
return mel.astype(np.float16)
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
def _synth_song(rng, i, key, bpm, q8, q3, dur_s=40.0):
|
| 537 |
+
"""One synthetic song (one mapset; Oni and Inner Oni with the same notes). Every beat has a note. Per measure,
|
| 538 |
+
with probability q8 every beat also has notes at the odd 1/8 positions 6/48 and 30/48; otherwise the audio has
|
| 539 |
+
clicks at 2/48 and 26/48 with no notes there (so the number of clicks, which sets the per-song z-scoring, does not
|
| 540 |
+
reveal q8; at <= 105 BPM neither pair is within +-1 frame of a 1/12 position). Independently, with probability q3
|
| 541 |
+
every beat has notes at 1/3 and 2/3. The audio has a click at every note."""
|
| 542 |
+
offset = 300.0 + 200.0 * rng.random()
|
| 543 |
+
bl = 60000.0 / bpm
|
| 544 |
+
sections = np.array([[offset, bl, 4, 0, 0]], np.float64)
|
| 545 |
+
n_meas = int((dur_s * 1000 - offset) / bl) // 4 - 1
|
| 546 |
+
e8, e3 = rng.random(n_meas) < q8, rng.random(n_meas) < q3
|
| 547 |
+
g, clicks = [], []
|
| 548 |
+
for m in range(n_meas):
|
| 549 |
+
for b in range(4):
|
| 550 |
+
base = (4 * m + b) * GRID
|
| 551 |
+
notes = [0] + ([6, 30] if e8[m] else []) + ([16, 32] if e3[m] else [])
|
| 552 |
+
g += [base + k for k in notes]
|
| 553 |
+
clicks += [base + k for k in notes] + ([] if e8[m] else [base + 2, base + 26])
|
| 554 |
+
g = np.sort(np.array(g, np.int64))
|
| 555 |
+
beat = g / GRID
|
| 556 |
+
times = offset + beat * bl
|
| 557 |
+
n_frames = int(dur_s * 100)
|
| 558 |
+
charts = [{"beatmap_id": 10 * i + t, "tier": t, "year": 2020, "sections": sections, "time": times, "beat": beat,
|
| 559 |
+
"type": np.zeros(len(g), np.int64), "length_beats": np.zeros(len(g))} for t in (3, 4)]
|
| 560 |
+
mel = _click_mel(rng, n_frames, offset + np.array(clicks) / GRID * bl)
|
| 561 |
+
return {"beatmapset_id": 1000 + i, "song_key": key, "mel": mel, "charts": charts}
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
def selftest(tmp: Path | None = None):
|
| 565 |
+
from chartgen.song_planner import chart_rows
|
| 566 |
+
rng = np.random.default_rng(0)
|
| 567 |
+
|
| 568 |
+
# 1. position sets
|
| 569 |
+
assert len(POS24) == 24 and len(POS12) == 12 and set(POS12) <= set(POS24)
|
| 570 |
+
assert {6, 18, 30, 42} <= set(POS24) and not ({6, 18, 30, 42} & set(POS12))
|
| 571 |
+
try:
|
| 572 |
+
from chartgen.v11.patterns import POSITIONS
|
| 573 |
+
except Exception as e: # noqa: BLE001 - the vocabulary module is optional here
|
| 574 |
+
POSITIONS = None
|
| 575 |
+
print(f"note: v11.patterns not importable ({type(e).__name__}), POS24 checked on its own")
|
| 576 |
+
if POSITIONS is not None:
|
| 577 |
+
assert tuple(POS24.tolist()) == tuple(POSITIONS), "POS24 differs from v11.patterns.POSITIONS"
|
| 578 |
+
print("ok: POS24 == v11.patterns.POSITIONS")
|
| 579 |
+
# a timing with a zero beat length is skipped, not fatal
|
| 580 |
+
for bad in ([[0.0, 0.0, 4, 0, 0]], [[0.0, -500.0, 4, 0, 0]], [[0.0, 500.0, 4, 0, 0], [9000.0, 0.0, 4, 18, 0]]):
|
| 581 |
+
r = chart_signatures(np.zeros((3000, len(COLS)), np.float32), np.array(bad))
|
| 582 |
+
assert isinstance(r, str), (bad, r)
|
| 583 |
+
|
| 584 |
+
# 2. windows: at least +-1 frame, the 12-position reading is exactly +-1, own windows stay near their halfway points
|
| 585 |
+
bl = 60000.0 / 70
|
| 586 |
+
sec = np.array([[500.0, bl, 4, 0, 0]])
|
| 587 |
+
beats = whole_beats(sec, 6000)
|
| 588 |
+
f, lo, hi = position_windows(sec, beats, POS24, True)
|
| 589 |
+
assert (lo <= f - 1).all() and (hi >= f + 1).all()
|
| 590 |
+
t = 500.0 + (beats[:, None] + POS24[None] / GRID) * bl
|
| 591 |
+
gap = bl * np.diff(np.r_[POS24, POS24[0] + GRID]) / GRID
|
| 592 |
+
assert ((hi * 10.0 - t) <= np.maximum(gap[None] / 2, 15.0) + 1e-6).all()
|
| 593 |
+
f12, lo12, hi12 = position_windows(sec, beats, POS12, False)
|
| 594 |
+
assert (lo12 == f12 - 1).all() and (hi12 == f12 + 1).all()
|
| 595 |
+
print(f"ok: windows (70 BPM: pos24 mean width {(hi - lo + 1).mean():.2f} frames, pos12 3)")
|
| 596 |
+
|
| 597 |
+
# 3. whole beats with a tempo change whose red line cuts a beat short
|
| 598 |
+
t2 = 500.0 + 20.6 * bl # 20.6 beats into section 1 -> next start beat 21
|
| 599 |
+
sec2 = np.array([[500.0, bl, 4, 0, 0], [t2, 400.0, 4, 21, 0]])
|
| 600 |
+
b2 = whole_beats(sec2, 6000)
|
| 601 |
+
assert 20.0 not in b2 and 19.0 in b2 and 21.0 in b2, "beat cut short by the red line must be left out"
|
| 602 |
+
assert len(b2) == 20 + int((60000 - t2) // 400), len(b2)
|
| 603 |
+
print(f"ok: whole beats across a tempo change ({len(b2)} beats)")
|
| 604 |
+
|
| 605 |
+
# 4. clicks at the odd 1/8 position: pos24 sees them at both tempos, pos12 does not at the slow one
|
| 606 |
+
times = []
|
| 607 |
+
for b in b2:
|
| 608 |
+
j = _section_of_beat(sec2, np.array([b]))[0]
|
| 609 |
+
t0 = sec2[j, 0] + (b - sec2[j, 3]) * sec2[j, 1]
|
| 610 |
+
times += [t0, t0 + sec2[j, 1] * 6 / GRID]
|
| 611 |
+
ons = song_onsets(_click_mel(rng, 6000, times))
|
| 612 |
+
full = len(BANDS) - 1 # full-band column
|
| 613 |
+
slow = b2[b2 < 20]
|
| 614 |
+
s24, _ = signature(ons, sec2, POS24, True, slow)
|
| 615 |
+
s12, _ = signature(ons, sec2, POS12, False, slow)
|
| 616 |
+
s24, s12 = s24.reshape(len(POS24), -1)[:, full], s12.reshape(len(POS12), -1)[:, full]
|
| 617 |
+
i6 = int(np.where(POS24 == 6)[0][0])
|
| 618 |
+
assert s24[i6] > 2.0 and s24[0] > 2.0, (s24[i6], s24[0])
|
| 619 |
+
assert s12[1] < 0.5 and s12[2] < 0.5, s12[:3] # k = 4/48 and 8/48, around the click at 6/48
|
| 620 |
+
fast = b2[b2 >= 21]
|
| 621 |
+
f24, _ = signature(ons, sec2, POS24, True, fast)
|
| 622 |
+
assert f24.reshape(len(POS24), -1)[i6, full] > 2.0
|
| 623 |
+
print(f"ok: odd 1/8 clicks at 70 BPM: pos24[6/48] {s24[i6]:.2f}, pos12[4/48, 8/48] {s12[1]:.2f} {s12[2]:.2f}")
|
| 624 |
+
|
| 625 |
+
# 5. end to end on synthetic shards and planner rows: the 1/8 amount is visible only to pos24 (slow songs), the
|
| 626 |
+
# triplet amount to both; one test-split song must be dropped
|
| 627 |
+
tmpdir = tempfile.TemporaryDirectory(dir=tmp)
|
| 628 |
+
root = Path(tmpdir.name)
|
| 629 |
+
songs, rows = [], {"train": [], "val": []}
|
| 630 |
+
i, n_test = 0, 0
|
| 631 |
+
while len(songs) < 100 + n_test:
|
| 632 |
+
key = f"synthetic|song{i}"
|
| 633 |
+
sp = song_split(key)
|
| 634 |
+
if sp == "test" and n_test >= 1:
|
| 635 |
+
i += 1
|
| 636 |
+
continue
|
| 637 |
+
n_test += sp == "test"
|
| 638 |
+
s = _synth_song(rng, i, key, rng.uniform(60, 100), rng.uniform(0, 1), rng.uniform(0, 1))
|
| 639 |
+
songs.append(s)
|
| 640 |
+
for c in s["charts"]:
|
| 641 |
+
_, H, b0 = chart_rows(np.zeros(((len(s["mel"]) + 1) // 2, 1), np.float32), c)
|
| 642 |
+
rows["train" if sp == "test" else sp].append(
|
| 643 |
+
(np.zeros((len(H), 1), np.float16), H, c["tier"], (s["beatmapset_id"], c["beatmap_id"], b0, key)))
|
| 644 |
+
i += 1
|
| 645 |
+
shards = [root / "taiko-00000.pkl", root / "taiko-00001.pkl"]
|
| 646 |
+
for k, p in enumerate(shards):
|
| 647 |
+
pickle.dump(songs[k::2], open(p, "wb"))
|
| 648 |
+
pickle.dump(rows, open(root / "rows.pkl", "wb"))
|
| 649 |
+
out = root / "sig_probe.json"
|
| 650 |
+
main(["--rows", str(root / "rows.pkl"), "--data", *map(str, shards), "--out", str(out),
|
| 651 |
+
"--save-rows", str(root / "sig_rows.npz"), "--n-boot", "200"])
|
| 652 |
+
doc = json.loads(out.read_text())
|
| 653 |
+
c = doc["counts"]
|
| 654 |
+
assert c["skipped_test_split"] == 2 and c["missing_in_shards"] == 0 and c["used"] == 200, c
|
| 655 |
+
for name in ("Oni", "Inner Oni"):
|
| 656 |
+
e = doc["results"][name]["eighth"]["overall"]
|
| 657 |
+
tr = doc["results"][name]["triplet"]["overall"]
|
| 658 |
+
assert e["pos24"]["r2"][0] > 0.5 and e["pos12"]["r2"][0] < 0.25, (name, e["pos24"]["r2"], e["pos12"]["r2"])
|
| 659 |
+
assert e["pos24_minus_pos12"]["r2"][1] > 0.25, e["pos24_minus_pos12"]
|
| 660 |
+
assert tr["pos12"]["r2"][0] > 0.5 and tr["pos24"]["r2"][0] > 0.5, (tr["pos12"]["r2"], tr["pos24"]["r2"])
|
| 661 |
+
assert doc["p0_1"]["held_point_estimate"] is True
|
| 662 |
+
# analysis from the saved signatures gives the same numbers
|
| 663 |
+
out2 = root / "sig_probe2.json"
|
| 664 |
+
main(["--from-rows", str(root / "sig_rows.npz"), "--out", str(out2), "--n-boot", "200"])
|
| 665 |
+
assert json.loads(out2.read_text())["results"] == doc["results"]
|
| 666 |
+
# all-charts mode: targets from the charts themselves; every synthetic chart is in the rows, so the same results
|
| 667 |
+
keys = root / "ps9_keys.json"
|
| 668 |
+
main(["--rows", str(root / "rows.pkl"), "--write-ps9-keys", str(keys)])
|
| 669 |
+
out3 = root / "sig_probe3.json"
|
| 670 |
+
main(["--all-charts", "--ps9", str(keys), "--data", *map(str, shards), "--out", str(out3),
|
| 671 |
+
"--save-rows", str(root / "sig_all.npz"), "--n-boot", "200"])
|
| 672 |
+
doc3 = json.loads(out3.read_text())
|
| 673 |
+
assert doc3["counts"]["used"] == 200 and doc3["counts"]["used_in_ps9"] == 200, doc3["counts"]
|
| 674 |
+
assert doc3["results"] == doc["results"], "all-charts mode differs from the planner-rows mode"
|
| 675 |
+
# split saving: two part files, analysed together, give the same results
|
| 676 |
+
for k, sh in enumerate(shards):
|
| 677 |
+
main(["--all-charts", "--ps9", str(keys), "--data", str(sh), "--save-rows", str(root / f"part{k}.npz"),
|
| 678 |
+
"--no-probe"])
|
| 679 |
+
out4 = root / "sig_probe4.json"
|
| 680 |
+
main(["--from-rows", str(root / "part0.npz"), str(root / "part1.npz"), "--out", str(out4), "--n-boot", "200",
|
| 681 |
+
"--only-ps9"])
|
| 682 |
+
assert json.loads(out4.read_text())["results"] == doc["results"], "per-shard parts differ"
|
| 683 |
+
print("ok: all-charts mode and per-shard parts reproduce the planner-rows results")
|
| 684 |
+
tmpdir.cleanup()
|
| 685 |
+
print("\nSELFTEST PASSED", flush=True)
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
# ------------------------------------------------------------------------------------------------ main
|
| 689 |
+
|
| 690 |
+
def main(argv=None):
|
| 691 |
+
p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 692 |
+
p.add_argument("--rows", type=Path, help="planner rows (runs/ps9/rows.pkl)")
|
| 693 |
+
p.add_argument("--data", nargs="+", type=Path, help="feature shards (taiko-*.pkl with log-Mel)")
|
| 694 |
+
p.add_argument("--from-rows", nargs="+", type=Path, help="analysis only, from signatures saved with --save-rows")
|
| 695 |
+
p.add_argument("--all-charts", action="store_true",
|
| 696 |
+
help="every Oni/Inner Oni chart in --data (targets from the chart itself), not only the planner rows")
|
| 697 |
+
p.add_argument("--ps9", type=Path, help="with --all-charts: rows.pkl or a key .json, to flag charts in the rows")
|
| 698 |
+
p.add_argument("--write-ps9-keys", type=Path, help="write the (set, beatmap id) keys of --rows to this .json and exit")
|
| 699 |
+
p.add_argument("--only-ps9", action="store_true", help="analyse only the charts that are in the planner rows")
|
| 700 |
+
p.add_argument("--counts", type=Path, help="with --from-rows: a .json of collection counts to record")
|
| 701 |
+
p.add_argument("--no-probe", action="store_true", help="collect and save signatures only")
|
| 702 |
+
p.add_argument("--out", type=Path, help="result JSON")
|
| 703 |
+
p.add_argument("--save-rows", type=Path, help="also save the per-chart signatures and targets (.npz)")
|
| 704 |
+
p.add_argument("--tiers", type=int, nargs="+", default=[3, 4])
|
| 705 |
+
p.add_argument("--n-boot", type=int, default=1000)
|
| 706 |
+
p.add_argument("--seed", type=int, default=0)
|
| 707 |
+
p.add_argument("--selftest", action="store_true", help="run the synthetic self-test and exit")
|
| 708 |
+
p.add_argument("--tmp", type=Path, help="directory for the self-test's temporary files")
|
| 709 |
+
a = p.parse_args(argv)
|
| 710 |
+
if a.selftest:
|
| 711 |
+
selftest(a.tmp)
|
| 712 |
+
return
|
| 713 |
+
if a.write_ps9_keys:
|
| 714 |
+
a.write_ps9_keys.write_text(json.dumps(sorted(ps9_keys(a.rows))))
|
| 715 |
+
return
|
| 716 |
+
if a.out is None and not a.no_probe:
|
| 717 |
+
p.error("--out is required")
|
| 718 |
+
if a.from_rows:
|
| 719 |
+
recs = load_recs(a.from_rows)
|
| 720 |
+
if any(song_split(r["song"]) == "test" for r in recs):
|
| 721 |
+
raise ValueError("saved signatures contain a test-split song")
|
| 722 |
+
counts = {"used": len(recs), "source": [str(x) for x in a.from_rows]}
|
| 723 |
+
if a.counts:
|
| 724 |
+
counts["collection"] = json.loads(a.counts.read_text())
|
| 725 |
+
elif a.all_charts:
|
| 726 |
+
if not a.data:
|
| 727 |
+
p.error("--data is required")
|
| 728 |
+
recs, counts = collect_all(sorted(a.data), tiers=tuple(a.tiers), ps9=ps9_keys(a.ps9) if a.ps9 else None)
|
| 729 |
+
else:
|
| 730 |
+
if a.rows is None or not a.data:
|
| 731 |
+
p.error("--rows and --data are required (or --from-rows / --all-charts)")
|
| 732 |
+
recs, counts = collect(a.rows, sorted(a.data), tiers=tuple(a.tiers))
|
| 733 |
+
if a.save_rows and not a.from_rows and recs:
|
| 734 |
+
save_recs(recs, a.save_rows)
|
| 735 |
+
if a.no_probe:
|
| 736 |
+
print(json.dumps(counts), flush=True)
|
| 737 |
+
return
|
| 738 |
+
if a.only_ps9:
|
| 739 |
+
recs = [r for r in recs if r["in_ps9"]]
|
| 740 |
+
counts = {**counts, "analysed": "only charts in the planner rows (ps9)", "used_after_filter": len(recs)}
|
| 741 |
+
run_probe(recs, counts, a.out, a.n_boot, a.seed, tuple(a.tiers))
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
if __name__ == "__main__":
|
| 745 |
+
sys.exit(main())
|
chartgen/v11/writer.py
ADDED
|
@@ -0,0 +1,1002 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""v11 stage 3: the pattern writer W with the chart encoder E_c (reports/v11 階段 3 預先登記:節奏型寫手 W.md).
|
| 2 |
+
|
| 3 |
+
Per beat, W picks one pattern token (EMPTY or one of the 897 vocabulary patterns) with score
|
| 4 |
+
s_t(v) = gamma_tier * sum_{p in v} l_{t,p} + d_t(v)
|
| 5 |
+
where l are R's calibrated logits of the tier (the direct music term) and d_t the design network's output. Before the
|
| 6 |
+
pattern, an object head decides whether a roll / balloon starts in the beat (kind, position, length in 1/4 beats);
|
| 7 |
+
after it, a colour head gives each note don / ka / big don / big ka. Music enters W only through the frozen R:
|
| 8 |
+
logits (music term), beat states z (object head, repetition hint, JEPA predictor) and position features u (colour head).
|
| 9 |
+
A "music off" mode (flag input; gamma term, hint, z and u removed) is trained on 15% of the samples, so W-nomusic is a
|
| 10 |
+
trained mode of the same model.
|
| 11 |
+
|
| 12 |
+
E_c: bidirectional Transformer over the beats of known chart content (own chart's known beats; another tier of the same
|
| 13 |
+
song aligned beat by beat); it reads no audio. For a reference chart (another song) the same E_c is pooled by 4
|
| 14 |
+
learned queries into style vectors, which the design network reads by cross-attention. Auxiliary losses on E_c: JEPA
|
| 15 |
+
(EMA target encoder on the full own chart, predictor from c_t and R's z_t, 1 - cosine on the unknown beats) and SADL
|
| 16 |
+
(arXiv:2611.21596: supply loss on H = E_c outputs at known beats, VIC demand regulariser on a BN projector), fp32.
|
| 17 |
+
|
| 18 |
+
Training data: chartgen.v11.writer_data caches (<shard>.w.pkl) next to the stage-2 R caches (<shard>.r.pkl) and the
|
| 19 |
+
mel sidecars (<shard>.mel.npy). R per fold: songs of role A read r_B, B read r_A, tune read r_A (never a model that
|
| 20 |
+
trained on the song).
|
| 21 |
+
|
| 22 |
+
python -m chartgen.v11.writer train --data f*.pkl --r-a r_A.pt --r-b r_B.pt --calib-a calib_A.json \\
|
| 23 |
+
--calib-b calib_B.json --out runs/w_s0 [--seed 0] [--no-jepa]
|
| 24 |
+
python -m chartgen.v11.writer --selftest
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
|
| 29 |
+
import argparse
|
| 30 |
+
import copy
|
| 31 |
+
import json
|
| 32 |
+
import math
|
| 33 |
+
import os
|
| 34 |
+
import pickle
|
| 35 |
+
import time
|
| 36 |
+
from pathlib import Path
|
| 37 |
+
from types import SimpleNamespace
|
| 38 |
+
|
| 39 |
+
import numpy as np
|
| 40 |
+
import torch
|
| 41 |
+
import torch.nn as nn
|
| 42 |
+
import torch.nn.functional as F
|
| 43 |
+
|
| 44 |
+
from chartgen.dataset import measure_at
|
| 45 |
+
from chartgen.v11.patterns import GRID, OTHER
|
| 46 |
+
from chartgen.v11.rmap import CROP, N_POS, collate as r_collate, crop_arrays, load_rmap
|
| 47 |
+
from chartgen.v11.rmap_data import POS, era_band
|
| 48 |
+
from chartgen.v11.rmap_eval import apply_calib, load_calib
|
| 49 |
+
from chartgen.v11.writer_data import SETTINGS, load_vocab, w_cache_path
|
| 50 |
+
|
| 51 |
+
MARGIN = 64 # beats of R context on each side of a crop
|
| 52 |
+
N_STYLE = 4
|
| 53 |
+
N_KIND = 3
|
| 54 |
+
N_LEN = 32
|
| 55 |
+
LEN_LO, LEN_HI = 0.25, 32.0 # object length bins in beats (log spaced)
|
| 56 |
+
HINT_MEAS, HINT_MAXB = 16, 64
|
| 57 |
+
N_COL = 4
|
| 58 |
+
UNK = None # set from the vocabulary size (token id V = UNK, V + 1 = NONE / BOS)
|
| 59 |
+
|
| 60 |
+
P_KNOWN = (("none", 0.4), ("prefix", 0.2), ("prefix_suffix", 0.2), ("scatter", 0.1), ("other_tier", 0.1))
|
| 61 |
+
P_REF = (("none", 0.6), ("same_mapper", 0.3), ("random", 0.1))
|
| 62 |
+
P_SPEC = (0.7, 0.5, 0.5, 0.5, 0.5)
|
| 63 |
+
P_HINT_OFF, P_MUSIC_OFF = 0.15, 0.15
|
| 64 |
+
TIER_WEIGHT = (1.0, 1.0, 1.0, 2.0, 2.0)
|
| 65 |
+
AUTOCAST_CPU = os.environ.get("W_AUTOCAST_CPU") == "1" # selftest: catch bf16 dtype issues on CPU
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def len_bin(len_beats: float) -> int:
|
| 69 |
+
x = (math.log(max(len_beats, LEN_LO)) - math.log(LEN_LO)) / (math.log(LEN_HI) - math.log(LEN_LO))
|
| 70 |
+
return int(min(max(round(x * (N_LEN - 1)), 0), N_LEN - 1))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def bin_len(b: int) -> float:
|
| 74 |
+
return float(math.exp(math.log(LEN_LO) + b / (N_LEN - 1) * (math.log(LEN_HI) - math.log(LEN_LO))))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def unpack_colours(col: np.ndarray, tok_mask: np.ndarray) -> np.ndarray:
|
| 78 |
+
"""[n] uint64 packed colours + [n] 24-bit note masks -> [n, 24] int8 colour (-1 = no note)."""
|
| 79 |
+
c = col.astype(np.uint64)
|
| 80 |
+
sh = (np.arange(N_POS, dtype=np.uint64) * np.uint64(2))
|
| 81 |
+
val = ((c[:, None] >> sh[None]) & np.uint64(3)).astype(np.int8)
|
| 82 |
+
has = ((tok_mask.astype(np.int64)[:, None] >> np.arange(N_POS)[None]) & 1).astype(bool)
|
| 83 |
+
return np.where(has, val, np.int8(-1))
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# ------------------------------------------------------------------------------------------------ corpus
|
| 87 |
+
|
| 88 |
+
class WCorpus:
|
| 89 |
+
"""Song records (mel memmap, onset columns), R groups (beat tables) and W chart records, for the given roles."""
|
| 90 |
+
|
| 91 |
+
def __init__(self, paths, roles, cache_dir=None, log=print):
|
| 92 |
+
self.vocab = load_vocab()
|
| 93 |
+
self.vmask = np.r_[np.int64(0), np.int64(0), self.vocab.masks] # token -> 24-bit mask
|
| 94 |
+
self.songs, self.groups, self.items = [], [], []
|
| 95 |
+
t0 = time.time()
|
| 96 |
+
for p in sorted(Path(x) for x in paths if str(x).endswith(".pkl") and ".r." not in str(x) and ".w." not in str(x)):
|
| 97 |
+
rc = (Path(cache_dir) / f"{p.stem}.r.pkl") if cache_dir else p.with_suffix(".r.pkl")
|
| 98 |
+
wc = w_cache_path(rc)
|
| 99 |
+
recs = pickle.load(open(rc, "rb"))
|
| 100 |
+
wrecs = pickle.load(open(wc, "rb"))
|
| 101 |
+
npy = p.with_suffix(".mel.npy")
|
| 102 |
+
mm = np.load(npy, mmap_mode="r") if npy.exists() else None
|
| 103 |
+
assert len(recs) == len(wrecs)
|
| 104 |
+
for r, w in zip(recs, wrecs):
|
| 105 |
+
assert int(r["beatmapset_id"]) == w["set"]
|
| 106 |
+
keep = [(g, wg) for g, wg in zip(r["groups"], w["groups"]) if g.role in roles]
|
| 107 |
+
if not keep:
|
| 108 |
+
continue
|
| 109 |
+
si = len(self.songs)
|
| 110 |
+
self.songs.append({"set": w["set"], "key": w["key"], "ons": r["ons"],
|
| 111 |
+
"mel": (mm[r["mel_off"]:r["mel_off"] + r["mel_len"]] if mm is not None
|
| 112 |
+
else np.zeros((r["mel_len"], 128), np.float16))})
|
| 113 |
+
for g, wg in keep:
|
| 114 |
+
assert g.uid == wg["uid"]
|
| 115 |
+
g.song_index = si
|
| 116 |
+
gi = len(self.groups)
|
| 117 |
+
meas = measure_at(np.asarray(g.sections, np.float64), g.table.beat.astype(np.float64))
|
| 118 |
+
self.groups.append({"g": g, "w": wg, "song": si, "meas": meas,
|
| 119 |
+
"logbl": np.log(g.table.bl.astype(np.float32))})
|
| 120 |
+
for t, lst in wg["charts"].items():
|
| 121 |
+
for ci, rec in enumerate(lst):
|
| 122 |
+
n_tr = int(((rec["allowed"] != 0) & (rec["tok"] != OTHER)).sum())
|
| 123 |
+
if n_tr >= 16:
|
| 124 |
+
self.items.append((gi, int(t), ci))
|
| 125 |
+
log(f"{p.name}: {len(self.songs)} songs, {len(self.groups)} groups, {len(self.items)} charts "
|
| 126 |
+
f"({time.time() - t0:.0f} s)")
|
| 127 |
+
self.by_mapper = {}
|
| 128 |
+
for k, (gi, t, ci) in enumerate(self.items):
|
| 129 |
+
self.by_mapper.setdefault(self.rec(k)["mapper"], []).append(k)
|
| 130 |
+
|
| 131 |
+
def rec(self, k):
|
| 132 |
+
gi, t, ci = self.items[k]
|
| 133 |
+
return self.groups[gi]["w"]["charts"][t][ci]
|
| 134 |
+
|
| 135 |
+
def role(self, gi):
|
| 136 |
+
return self.groups[gi]["g"].role
|
| 137 |
+
|
| 138 |
+
def key(self, gi):
|
| 139 |
+
return self.songs[self.groups[gi]["song"]]["key"]
|
| 140 |
+
|
| 141 |
+
def r_view(self, gi):
|
| 142 |
+
"""Adapter for rmap.crop_arrays: groups=[g], songs=[{mel}], ons=[ons]."""
|
| 143 |
+
G = self.groups[gi]
|
| 144 |
+
g = copy.copy(G["g"])
|
| 145 |
+
g.song_index = 0
|
| 146 |
+
s = self.songs[G["song"]]
|
| 147 |
+
return SimpleNamespace(groups=[g], songs=[{"mel": s["mel"]}], ons=[s["ons"]])
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
# ------------------------------------------------------------------------------------------------ crops
|
| 151 |
+
|
| 152 |
+
def chart_arrays(c: WCorpus, gi, rec, r0, r1):
|
| 153 |
+
"""Token-level arrays of rows r0..r1 of one chart record."""
|
| 154 |
+
tok = rec["tok"][r0:r1].astype(np.int64)
|
| 155 |
+
allowed = rec["allowed"][r0:r1].astype(np.int64)
|
| 156 |
+
tmask = c.vmask[tok]
|
| 157 |
+
col = unpack_colours(rec["col"][r0:r1], tmask)
|
| 158 |
+
n = r1 - r0
|
| 159 |
+
obj = np.full((n, 3), -1, np.int64) # kind, pos, len bin at the start beat
|
| 160 |
+
in_body = np.zeros(n, bool)
|
| 161 |
+
tb = c.groups[gi]["g"].table
|
| 162 |
+
for row, pos, kind, lms in rec["objs"]:
|
| 163 |
+
bl = float(tb.bl[row])
|
| 164 |
+
if r0 <= row < r1 and obj[row - r0, 0] < 0:
|
| 165 |
+
obj[row - r0] = (kind, pos, len_bin(lms / bl))
|
| 166 |
+
t_start = tb.t0[row] + bl * POS[pos] / GRID
|
| 167 |
+
t_end = t_start + lms
|
| 168 |
+
lo, hi = max(row + 1, r0), r1
|
| 169 |
+
if hi > lo:
|
| 170 |
+
cover = (tb.t0[lo:hi] >= t_start) & (tb.t0[lo:hi] < t_end - 1e-6)
|
| 171 |
+
in_body[lo - r0:hi - r0] |= cover
|
| 172 |
+
return {"tok": tok, "allowed": allowed, "col": col, "obj": obj, "in_body": in_body}
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def known_mask(mode, n_chart_rows, r0, r1, rng):
|
| 176 |
+
"""Known rows of the crop for a context mode, decided on the whole chart's row range."""
|
| 177 |
+
k = np.zeros(r1 - r0, bool)
|
| 178 |
+
N = n_chart_rows
|
| 179 |
+
if mode == "prefix":
|
| 180 |
+
cut = int(N * rng.uniform(0.05, 0.6))
|
| 181 |
+
k = np.arange(r0, r1) < cut
|
| 182 |
+
elif mode == "prefix_suffix":
|
| 183 |
+
a, b = sorted(rng.uniform(0.05, 0.95, 2))
|
| 184 |
+
k = (np.arange(r0, r1) < int(N * a)) | (np.arange(r0, r1) >= int(N * b))
|
| 185 |
+
elif mode == "scatter":
|
| 186 |
+
for _ in range(int(rng.integers(2, 6))):
|
| 187 |
+
s = int(rng.integers(0, N))
|
| 188 |
+
k |= (np.arange(r0, r1) >= s) & (np.arange(r0, r1) < s + int(rng.integers(8, 64)))
|
| 189 |
+
return k
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def hint_candidates(meas, bib, ra, r0, r1):
|
| 193 |
+
"""[L, HINT_MEAS] rows (relative to ra) of earlier beats with the same beat-in-measure in the previous 16
|
| 194 |
+
measures and at most 64 beats back; -1 = none."""
|
| 195 |
+
L = r1 - r0
|
| 196 |
+
out = np.full((L, HINT_MEAS), -1, np.int64)
|
| 197 |
+
for i, t in enumerate(range(r0, r1)):
|
| 198 |
+
lo = max(ra, t - HINT_MAXB)
|
| 199 |
+
cand = np.nonzero((bib[lo:t] == bib[t]) & (meas[lo:t] >= meas[t] - HINT_MEAS) & (meas[lo:t] < meas[t]))[0] + lo
|
| 200 |
+
cand = cand[-HINT_MEAS:]
|
| 201 |
+
out[i, :len(cand)] = cand - ra
|
| 202 |
+
return out
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def make_crop(c: WCorpus, k: int, r0: int, rng, train: bool = True, mode=None, ref_mode=None, spec=None,
|
| 206 |
+
hint_off=None, music_off=None):
|
| 207 |
+
gi, tier, ci = c.items[k]
|
| 208 |
+
G = c.groups[gi]
|
| 209 |
+
g = G["g"]
|
| 210 |
+
rec = c.rec(k)
|
| 211 |
+
n = len(g.table)
|
| 212 |
+
r1 = min(n, r0 + CROP)
|
| 213 |
+
ra, rb = max(0, r0 - MARGIN), min(n, r1 + MARGIN)
|
| 214 |
+
rv = c.r_view(gi)
|
| 215 |
+
rx = crop_arrays(rv, 0, 0, ra, rb, True)
|
| 216 |
+
cur = chart_arrays(c, gi, rec, r0, r1)
|
| 217 |
+
win = chart_arrays(c, gi, rec, ra, r1) # tokens of the hint window (teacher forcing)
|
| 218 |
+
mode = mode or (rng.choice([m for m, _ in P_KNOWN], p=[p for _, p in P_KNOWN]) if train else "none")
|
| 219 |
+
known = np.zeros(r1 - r0, bool)
|
| 220 |
+
other = None
|
| 221 |
+
if mode == "other_tier":
|
| 222 |
+
alts = [(t2, j) for t2, lst in G["w"]["charts"].items() for j in range(len(lst)) if t2 != tier]
|
| 223 |
+
if alts:
|
| 224 |
+
t2, j = alts[int(rng.integers(len(alts)))]
|
| 225 |
+
other = chart_arrays(c, gi, G["w"]["charts"][t2][j], r0, r1)
|
| 226 |
+
other["tier"] = t2
|
| 227 |
+
else:
|
| 228 |
+
mode = "none"
|
| 229 |
+
elif mode != "none":
|
| 230 |
+
known = known_mask(mode, n, r0, r1, rng)
|
| 231 |
+
ref_mode = ref_mode or (rng.choice([m for m, _ in P_REF], p=[p for _, p in P_REF]) if train else "none")
|
| 232 |
+
ref = None
|
| 233 |
+
if ref_mode != "none":
|
| 234 |
+
key = c.key(gi)
|
| 235 |
+
pool = c.by_mapper.get(rec["mapper"], []) if ref_mode == "same_mapper" else None
|
| 236 |
+
for _ in range(20):
|
| 237 |
+
kk = int(pool[int(rng.integers(len(pool)))]) if pool else int(rng.integers(len(c.items)))
|
| 238 |
+
gi2 = c.items[kk][0]
|
| 239 |
+
if c.key(gi2) != key and c.role(gi2) in ("A", "B"):
|
| 240 |
+
ref = kk
|
| 241 |
+
break
|
| 242 |
+
ref_arr = None
|
| 243 |
+
if ref is not None:
|
| 244 |
+
gi2 = c.items[ref][0]
|
| 245 |
+
rec2 = c.rec(ref)
|
| 246 |
+
n2 = len(c.groups[gi2]["g"].table)
|
| 247 |
+
nz = np.nonzero(rec2["tok"] > 0)[0]
|
| 248 |
+
s2 = int(max(0, min(nz[int(rng.integers(len(nz)))] - CROP // 4 if len(nz) else 0, n2 - CROP)))
|
| 249 |
+
e2 = min(n2, s2 + CROP)
|
| 250 |
+
ref_arr = chart_arrays(c, gi2, rec2, s2, e2)
|
| 251 |
+
ref_arr["bib"] = c.groups[gi2]["g"].table.bib[s2:e2].astype(np.int64)
|
| 252 |
+
ref_arr["logbl"] = c.groups[gi2]["logbl"][s2:e2]
|
| 253 |
+
ref_arr["tier"] = c.items[ref][1]
|
| 254 |
+
st = rec["settings"].astype(np.float32)
|
| 255 |
+
spec = spec if spec is not None else (rng.random(5) < np.array(P_SPEC) if train else np.zeros(5, bool))
|
| 256 |
+
hint_off = bool(rng.random() < P_HINT_OFF) if hint_off is None and train else bool(hint_off)
|
| 257 |
+
music_off = bool(rng.random() < P_MUSIC_OFF) if music_off is None and train else bool(music_off)
|
| 258 |
+
year = int(rec["year"])
|
| 259 |
+
bib = g.table.bib.astype(np.int64)
|
| 260 |
+
return {
|
| 261 |
+
"r": rx, "off": r0 - ra, "L": r1 - r0, "tier": tier, "era": era_band(year),
|
| 262 |
+
"role": g.role, "tok": cur["tok"], "allowed": cur["allowed"], "col": cur["col"], "obj": cur["obj"],
|
| 263 |
+
"in_body": cur["in_body"], "tok_win": win["tok"], "col_win": win["col"], "obj_win": win["obj"],
|
| 264 |
+
"prev_tok": (rec["tok"][r0 - 1] if r0 > 0 else -1), "prev_col": (win["col"][r0 - ra - 1] if r0 > ra else None),
|
| 265 |
+
"known": known, "other": other, "ref": ref_arr,
|
| 266 |
+
"bib": bib[r0:r1], "logbl": G["logbl"][r0:r1],
|
| 267 |
+
"hint": hint_candidates(G["meas"], bib, ra, r0, r1),
|
| 268 |
+
"settings": st, "spec": spec, "hint_off": hint_off, "music_off": music_off,
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
# ------------------------------------------------------------------------------------------------ batching
|
| 273 |
+
|
| 274 |
+
def _pad(arrs, fill, dtype):
|
| 275 |
+
L = max(len(a) for a in arrs)
|
| 276 |
+
out = np.full((len(arrs), L) + arrs[0].shape[1:], fill, dtype)
|
| 277 |
+
for i, a in enumerate(arrs):
|
| 278 |
+
out[i, :len(a)] = a
|
| 279 |
+
return torch.from_numpy(out)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def collate_w(items, V):
|
| 283 |
+
"""W batch (R inputs collated separately per fold by the caller)."""
|
| 284 |
+
B = len(items)
|
| 285 |
+
BOS, NONE = V + 1, V + 1
|
| 286 |
+
b = {}
|
| 287 |
+
b["tok"] = _pad([x["tok"] for x in items], 0, np.int64)
|
| 288 |
+
L = b["tok"].shape[1]
|
| 289 |
+
b["mask"] = _pad([np.ones(x["L"], bool) for x in items], False, bool)
|
| 290 |
+
b["allowed"] = _pad([x["allowed"] for x in items], 0, np.int64)
|
| 291 |
+
b["col"] = _pad([x["col"] for x in items], -1, np.int8).long()
|
| 292 |
+
b["obj"] = _pad([x["obj"] for x in items], -1, np.int64)
|
| 293 |
+
b["in_body"] = _pad([x["in_body"] for x in items], False, bool)
|
| 294 |
+
# previous-beat inputs: token, colours, object kind (shifted by one)
|
| 295 |
+
prev_tok, prev_col, prev_obj = [], [], []
|
| 296 |
+
for x in items:
|
| 297 |
+
p0 = x["prev_tok"] if x["prev_tok"] >= 0 else BOS
|
| 298 |
+
prev_tok.append(np.r_[p0, x["tok"][:-1]])
|
| 299 |
+
pc = x["prev_col"] if x["prev_col"] is not None else np.full(N_POS, -1, np.int8)
|
| 300 |
+
prev_col.append(np.r_[pc[None], x["col"][:-1]])
|
| 301 |
+
prev_obj.append(np.r_[-1, x["obj"][:-1, 0]])
|
| 302 |
+
b["prev_tok"] = _pad(prev_tok, 0, np.int64)
|
| 303 |
+
b["prev_col"] = _pad(prev_col, -1, np.int8).long()
|
| 304 |
+
b["prev_obj"] = _pad(prev_obj, -1, np.int64)
|
| 305 |
+
b["bib"] = _pad([x["bib"] for x in items], 0, np.int64).clamp(max=15)
|
| 306 |
+
b["logbl"] = _pad([x["logbl"].astype(np.float32) for x in items], 0.0, np.float32)
|
| 307 |
+
b["tier"] = torch.tensor([x["tier"] for x in items])
|
| 308 |
+
b["era"] = torch.tensor([x["era"] for x in items])
|
| 309 |
+
b["off"] = torch.tensor([x["off"] for x in items])
|
| 310 |
+
b["settings"] = torch.from_numpy(np.stack([x["settings"] for x in items]))
|
| 311 |
+
b["spec"] = torch.from_numpy(np.stack([x["spec"] for x in items]))
|
| 312 |
+
b["hint_off"] = torch.tensor([x["hint_off"] for x in items])
|
| 313 |
+
b["music_off"] = torch.tensor([x["music_off"] for x in items])
|
| 314 |
+
b["hint"] = _pad([x["hint"] for x in items], -1, np.int64)
|
| 315 |
+
b["tok_win"] = _pad([x["tok_win"] for x in items], 0, np.int64)
|
| 316 |
+
b["col_win"] = _pad([x["col_win"] for x in items], -1, np.int8).long()
|
| 317 |
+
# E_c input: own known beats and the aligned other tier
|
| 318 |
+
kt, kc, ko, ot, oc, oo, otier, known = [], [], [], [], [], [], [], []
|
| 319 |
+
for x in items:
|
| 320 |
+
k = x["known"]
|
| 321 |
+
known.append(k)
|
| 322 |
+
kt.append(np.where(k, x["tok"], V)) # V = UNK
|
| 323 |
+
kc.append(np.where(k[:, None], x["col"], -1))
|
| 324 |
+
ko.append(np.where(k, x["obj"][:, 0], -1))
|
| 325 |
+
o = x["other"]
|
| 326 |
+
if o is not None:
|
| 327 |
+
ot.append(o["tok"]); oc.append(o["col"]); oo.append(o["obj"][:, 0]); otier.append(o["tier"])
|
| 328 |
+
else:
|
| 329 |
+
ot.append(np.full(x["L"], NONE)); oc.append(np.full((x["L"], N_POS), -1, np.int8))
|
| 330 |
+
oo.append(np.full(x["L"], -1)); otier.append(5)
|
| 331 |
+
b["known"] = _pad(known, False, bool)
|
| 332 |
+
b["k_tok"] = _pad(kt, V, np.int64)
|
| 333 |
+
b["k_col"] = _pad(kc, -1, np.int8).long()
|
| 334 |
+
b["k_obj"] = _pad(ko, -1, np.int64)
|
| 335 |
+
b["o_tok"] = _pad(ot, NONE, np.int64)
|
| 336 |
+
b["o_col"] = _pad(oc, -1, np.int8).long()
|
| 337 |
+
b["o_obj"] = _pad(oo, -1, np.int64)
|
| 338 |
+
b["o_tier"] = torch.tensor(otier)
|
| 339 |
+
# reference charts
|
| 340 |
+
has_ref = [x["ref"] is not None for x in items]
|
| 341 |
+
b["has_ref"] = torch.tensor(has_ref)
|
| 342 |
+
if any(has_ref):
|
| 343 |
+
refs = [x["ref"] for x in items if x["ref"] is not None]
|
| 344 |
+
b["r_tok"] = _pad([r["tok"] for r in refs], 0, np.int64)
|
| 345 |
+
b["r_col"] = _pad([r["col"] for r in refs], -1, np.int8).long()
|
| 346 |
+
b["r_obj"] = _pad([r["obj"][:, 0] for r in refs], -1, np.int64)
|
| 347 |
+
b["r_bib"] = _pad([r["bib"] for r in refs], 0, np.int64).clamp(max=15)
|
| 348 |
+
b["r_logbl"] = _pad([r["logbl"].astype(np.float32) for r in refs], 0.0, np.float32)
|
| 349 |
+
b["r_mask"] = _pad([np.ones(len(r["tok"]), bool) for r in refs], False, bool)
|
| 350 |
+
b["r_tier"] = torch.tensor([r["tier"] for r in refs])
|
| 351 |
+
b["role"] = [x["role"] for x in items]
|
| 352 |
+
b["L"] = L
|
| 353 |
+
return b
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
# ------------------------------------------------------------------------------------------------ R features
|
| 357 |
+
|
| 358 |
+
def r_forward(model, batch):
|
| 359 |
+
"""R logits [B, L, 24, 5], beat states z [B, L, d] and position features u [B, L, 24, d_pos] (no grad)."""
|
| 360 |
+
feat = model.read(batch)
|
| 361 |
+
B, L = feat.shape[:2]
|
| 362 |
+
parts = [feat, model.pos_eye.expand(B, L, N_POS, N_POS)]
|
| 363 |
+
if model.use_ms:
|
| 364 |
+
lbl = batch["logbl"][..., None, None].expand(B, L, N_POS, 1)
|
| 365 |
+
parts += [batch["hmax"], lbl, lbl + torch.log(model.gap_prev)[None, None, :, None],
|
| 366 |
+
lbl + torch.log(model.gap_next)[None, None, :, None]]
|
| 367 |
+
h = model.inp(torch.cat(parts, -1))
|
| 368 |
+
z = model.beat_in(h.flatten(-2)) + model.bib(batch["bib"].clamp(max=15)) + model.era(batch["era"])[:, None]
|
| 369 |
+
if model.use_ms:
|
| 370 |
+
z = z + model.tempo(batch["logbl"][..., None])
|
| 371 |
+
z = z + model.pe[:L][None]
|
| 372 |
+
z = model.enc(z, src_key_padding_mask=~batch["beat"])
|
| 373 |
+
u = h + model.back(z)[:, :, None]
|
| 374 |
+
return model.head(u), z, u
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
class RFolds:
|
| 378 |
+
"""Frozen R models per fold with their calibrations. fold_of(role) -> 'A' (r_A) or 'B' (r_B)."""
|
| 379 |
+
|
| 380 |
+
def __init__(self, paths: dict, calibs: dict, device):
|
| 381 |
+
self.m = {f: load_rmap(p, device).eval() for f, p in paths.items()}
|
| 382 |
+
for m in self.m.values():
|
| 383 |
+
for q in m.parameters():
|
| 384 |
+
q.requires_grad_(False)
|
| 385 |
+
self.cal = {f: load_calib(c) for f, c in calibs.items()}
|
| 386 |
+
self.device = device
|
| 387 |
+
|
| 388 |
+
@staticmethod
|
| 389 |
+
def fold_of(role: str) -> str:
|
| 390 |
+
return {"A": "B", "B": "A", "tune": "A"}[role] # never the model that trained on the song
|
| 391 |
+
|
| 392 |
+
@torch.no_grad()
|
| 393 |
+
def run(self, rx_list, folds):
|
| 394 |
+
"""rx_list: rmap.crop_arrays dicts; folds: model key per item. Returns lists of (logits, z, u) per item."""
|
| 395 |
+
out = [None] * len(rx_list)
|
| 396 |
+
for f in sorted(set(folds)):
|
| 397 |
+
idx = [i for i, ff in enumerate(folds) if ff == f]
|
| 398 |
+
bt = r_collate([rx_list[i] for i in idx], True)
|
| 399 |
+
bt = {k: (v.to(self.device) if torch.is_tensor(v) else v) for k, v in bt.items()}
|
| 400 |
+
with torch.autocast(self.device.type, dtype=torch.bfloat16, enabled=self.device.type == "cuda"):
|
| 401 |
+
lg, z, u = r_forward(self.m[f], bt)
|
| 402 |
+
lg = lg.float().cpu().numpy()
|
| 403 |
+
for j, i in enumerate(idx):
|
| 404 |
+
n = len(rx_list[i]["bib"])
|
| 405 |
+
out[i] = (apply_calib(lg[j, :n], self.cal[f]), z[j, :n].float(), u[j, :n].float())
|
| 406 |
+
return out
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
# ------------------------------------------------------------------------------------------------ model
|
| 410 |
+
|
| 411 |
+
def rope(x, pos):
|
| 412 |
+
"""Rotary position embedding on the last dim of x [B, H, L, dh] with positions pos [B, L]."""
|
| 413 |
+
dh = x.shape[-1]
|
| 414 |
+
inv = 1.0 / (10000 ** (torch.arange(0, dh, 2, device=x.device, dtype=torch.float32) / dh))
|
| 415 |
+
ang = pos[:, None, :, None].float() * inv[None, None, None]
|
| 416 |
+
cos, sin = ang.cos().to(x.dtype), ang.sin().to(x.dtype)
|
| 417 |
+
x1, x2 = x[..., 0::2], x[..., 1::2]
|
| 418 |
+
return torch.stack([x1 * cos - x2 * sin, x1 * sin + x2 * cos], -1).flatten(-2)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
class DecLayer(nn.Module):
|
| 422 |
+
def __init__(self, d, h, drop):
|
| 423 |
+
super().__init__()
|
| 424 |
+
self.h, self.dh = h, d // h
|
| 425 |
+
self.ln1, self.qkv, self.o1 = nn.LayerNorm(d), nn.Linear(d, 3 * d), nn.Linear(d, d)
|
| 426 |
+
self.ln2, self.q2, self.kv2, self.o2 = nn.LayerNorm(d), nn.Linear(d, d), nn.Linear(d, 2 * d), nn.Linear(d, d)
|
| 427 |
+
self.ln3 = nn.LayerNorm(d)
|
| 428 |
+
self.ff = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d))
|
| 429 |
+
self.drop = nn.Dropout(drop)
|
| 430 |
+
|
| 431 |
+
def _split(self, x):
|
| 432 |
+
B, L, _ = x.shape
|
| 433 |
+
return x.view(B, L, self.h, self.dh).transpose(1, 2)
|
| 434 |
+
|
| 435 |
+
def forward(self, x, pos, style, cache=None, window=CROP):
|
| 436 |
+
B, L, d = x.shape
|
| 437 |
+
q, k, v = self.qkv(self.ln1(x)).chunk(3, -1)
|
| 438 |
+
q, k, v = self._split(q), self._split(k), self._split(v)
|
| 439 |
+
q, k = rope(q, pos), rope(k, pos)
|
| 440 |
+
if cache is None:
|
| 441 |
+
a = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=0.1 if self.training else 0.0)
|
| 442 |
+
else:
|
| 443 |
+
if "k" in cache:
|
| 444 |
+
k = torch.cat([cache["k"], k], 2)[:, :, -window:]
|
| 445 |
+
v = torch.cat([cache["v"], v], 2)[:, :, -window:]
|
| 446 |
+
cache["k"], cache["v"] = k, v
|
| 447 |
+
a = F.scaled_dot_product_attention(q, k, v)
|
| 448 |
+
x = x + self.drop(self.o1(a.transpose(1, 2).reshape(B, L, d)))
|
| 449 |
+
q2 = self._split(self.q2(self.ln2(x)))
|
| 450 |
+
k2, v2 = self.kv2(style).chunk(2, -1)
|
| 451 |
+
a2 = F.scaled_dot_product_attention(q2, self._split(k2), self._split(v2))
|
| 452 |
+
x = x + self.drop(self.o2(a2.transpose(1, 2).reshape(B, L, d)))
|
| 453 |
+
return x + self.drop(self.ff(self.ln3(x)))
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
class ColourSum(nn.Module):
|
| 457 |
+
"""Sum of (position, colour) embeddings of a beat's notes: [.., 24] int (-1 none) -> [.., d]."""
|
| 458 |
+
|
| 459 |
+
def __init__(self, d):
|
| 460 |
+
super().__init__()
|
| 461 |
+
self.e = nn.Embedding(N_POS * N_COL + 1, d, padding_idx=N_POS * N_COL)
|
| 462 |
+
|
| 463 |
+
def forward(self, col):
|
| 464 |
+
idx = torch.where(col >= 0, torch.arange(N_POS, device=col.device) * N_COL + col.clamp(min=0),
|
| 465 |
+
torch.full_like(col, N_POS * N_COL))
|
| 466 |
+
return self.e(idx).sum(-2)
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
class ChartEncoder(nn.Module):
|
| 470 |
+
"""E_c: bidirectional Transformer over beats of known chart content (no audio)."""
|
| 471 |
+
|
| 472 |
+
def __init__(self, V, d=256, layers=4, heads=8, drop=0.1):
|
| 473 |
+
super().__init__()
|
| 474 |
+
self.tok = nn.Embedding(V + 2, d) # V = UNK, V + 1 = NONE
|
| 475 |
+
self.otok = nn.Embedding(V + 2, d)
|
| 476 |
+
self.col, self.ocol = ColourSum(d), ColourSum(d)
|
| 477 |
+
self.obj = nn.Embedding(N_KIND + 1, d)
|
| 478 |
+
self.oobj = nn.Embedding(N_KIND + 1, d)
|
| 479 |
+
self.otier = nn.Embedding(6, d)
|
| 480 |
+
self.bib = nn.Embedding(16, d)
|
| 481 |
+
self.tempo = nn.Linear(1, d)
|
| 482 |
+
layer = nn.TransformerEncoderLayer(d, heads, 4 * d, drop, batch_first=True, norm_first=True, activation="gelu")
|
| 483 |
+
self.enc = nn.TransformerEncoder(layer, layers, enable_nested_tensor=False)
|
| 484 |
+
self.norm = nn.LayerNorm(d)
|
| 485 |
+
pe = torch.zeros(4096, d)
|
| 486 |
+
p = torch.arange(4096).float()[:, None]
|
| 487 |
+
div = torch.exp(torch.arange(0, d, 2).float() * (-math.log(10000.0) / d))
|
| 488 |
+
pe[:, 0::2], pe[:, 1::2] = torch.sin(p * div), torch.cos(p * div)
|
| 489 |
+
self.register_buffer("pe", pe, persistent=False)
|
| 490 |
+
|
| 491 |
+
def forward(self, tok, col, obj, otok, ocol, oobj, otier, bib, logbl, mask):
|
| 492 |
+
L = tok.shape[1]
|
| 493 |
+
x = (self.tok(tok) + self.col(col) + self.obj(obj + 1) + self.otok(otok) + self.ocol(ocol) + self.oobj(oobj + 1)
|
| 494 |
+
+ self.otier(otier)[:, None] + self.bib(bib) + self.tempo(logbl[..., None]) + self.pe[:L][None])
|
| 495 |
+
return self.norm(self.enc(x, src_key_padding_mask=~mask))
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
class Writer(nn.Module):
|
| 499 |
+
def __init__(self, V, d=256, dec_layers=6, enc_layers=4, heads=8, drop=0.1, d_z=256, d_u=96, jepa=True):
|
| 500 |
+
super().__init__()
|
| 501 |
+
self.V, self.d = V, d
|
| 502 |
+
self.cfg = {"V": V, "d": d, "dec_layers": dec_layers, "enc_layers": enc_layers, "heads": heads, "drop": drop,
|
| 503 |
+
"d_z": d_z, "d_u": d_u, "jepa": jepa}
|
| 504 |
+
self.enc = ChartEncoder(V, d, enc_layers, heads, drop)
|
| 505 |
+
self.pool_q = nn.Parameter(torch.randn(N_STYLE, d) * 0.02)
|
| 506 |
+
self.pool = nn.MultiheadAttention(d, heads, batch_first=True)
|
| 507 |
+
self.null_style = nn.Parameter(torch.randn(N_STYLE, d) * 0.02)
|
| 508 |
+
self.r_tier = nn.Embedding(5, d)
|
| 509 |
+
# decoder inputs
|
| 510 |
+
self.tok_in = nn.Embedding(V + 2, d) # V + 1 = BOS
|
| 511 |
+
self.col_in = ColourSum(d)
|
| 512 |
+
self.obj_in = nn.Embedding(N_KIND + 1, d)
|
| 513 |
+
self.body_in = nn.Embedding(2, d)
|
| 514 |
+
self.bib = nn.Embedding(16, d)
|
| 515 |
+
self.tempo = nn.Linear(1, d)
|
| 516 |
+
self.tier = nn.Embedding(5, d)
|
| 517 |
+
self.era = nn.Embedding(4, d)
|
| 518 |
+
self.set_in = nn.Linear(2 * len(SETTINGS), d)
|
| 519 |
+
self.ctx_in = nn.Linear(d, d)
|
| 520 |
+
self.hint_tok = nn.Embedding(V + 2, d)
|
| 521 |
+
self.hint_col = ColourSum(d)
|
| 522 |
+
self.hint_sim = nn.Linear(1, d)
|
| 523 |
+
self.music_flag = nn.Embedding(2, d)
|
| 524 |
+
self.layers = nn.ModuleList([DecLayer(d, heads, drop) for _ in range(dec_layers)])
|
| 525 |
+
self.norm = nn.LayerNorm(d)
|
| 526 |
+
self.out = nn.Linear(d, V) # design logits over tokens 0..V-1 (EMPTY, OTHER, patterns)
|
| 527 |
+
self.gamma = nn.Parameter(torch.ones(5))
|
| 528 |
+
# heads
|
| 529 |
+
self.z_proj = nn.Linear(d_z, d)
|
| 530 |
+
self.obj_start = nn.Sequential(nn.Linear(d, d), nn.GELU(), nn.Linear(d, 1))
|
| 531 |
+
self.obj_kind = nn.Linear(d, N_KIND)
|
| 532 |
+
self.obj_pos = nn.Linear(d, N_POS)
|
| 533 |
+
self.obj_len = nn.Linear(d, N_LEN)
|
| 534 |
+
self.c_pos = nn.Embedding(N_POS, d)
|
| 535 |
+
self.c_prev = nn.Embedding(N_COL + 1, d)
|
| 536 |
+
self.u_proj = nn.Linear(d_u, d)
|
| 537 |
+
self.col_head = nn.Sequential(nn.Linear(d, d), nn.GELU(), nn.Linear(d, N_COL))
|
| 538 |
+
# JEPA / SADL
|
| 539 |
+
if jepa:
|
| 540 |
+
self.pred = nn.Sequential(nn.Linear(2 * d, 2 * d), nn.GELU(), nn.Linear(2 * d, d))
|
| 541 |
+
self.pred_z = nn.Linear(d_z, d)
|
| 542 |
+
self.proj = nn.Sequential(nn.Linear(d, 1024), nn.BatchNorm1d(1024), nn.ReLU(), nn.Linear(1024, d),
|
| 543 |
+
nn.BatchNorm1d(d))
|
| 544 |
+
|
| 545 |
+
# ---- pieces
|
| 546 |
+
def style(self, b):
|
| 547 |
+
"""[B, N_STYLE, d] style vectors (learned null style without a reference)."""
|
| 548 |
+
B = b["tier"].shape[0]
|
| 549 |
+
st = self.null_style[None].expand(B, -1, -1).clone()
|
| 550 |
+
if b["has_ref"].any():
|
| 551 |
+
V = self.V
|
| 552 |
+
r = self.enc(b["r_tok"], b["r_col"], b["r_obj"], torch.full_like(b["r_tok"], V + 1),
|
| 553 |
+
torch.full_like(b["r_col"], -1), torch.full_like(b["r_obj"], -1),
|
| 554 |
+
torch.full_like(b["r_tier"], 5), b["r_bib"], b["r_logbl"], b["r_mask"])
|
| 555 |
+
r = r + self.r_tier(b["r_tier"])[:, None]
|
| 556 |
+
q = self.pool_q[None].expand(r.shape[0], -1, -1)
|
| 557 |
+
pooled, _ = self.pool(q, r, r, key_padding_mask=~b["r_mask"])
|
| 558 |
+
st = st.to(pooled.dtype)
|
| 559 |
+
st[b["has_ref"]] = pooled
|
| 560 |
+
return st
|
| 561 |
+
|
| 562 |
+
def context(self, b, tok=None, col=None, obj=None, known=None):
|
| 563 |
+
tok = b["k_tok"] if tok is None else tok
|
| 564 |
+
return self.enc(tok, b["k_col"] if col is None else col, b["k_obj"] if obj is None else obj, b["o_tok"],
|
| 565 |
+
b["o_col"], b["o_obj"], b["o_tier"], b["bib"], b["logbl"], b["mask"])
|
| 566 |
+
|
| 567 |
+
def hint(self, b, z_win):
|
| 568 |
+
"""Repetition hint per beat: token / colours of the most music-similar candidate beat, and its similarity."""
|
| 569 |
+
B, L, K = b["hint"].shape
|
| 570 |
+
Lw = z_win.shape[1]
|
| 571 |
+
zz = F.pad(z_win, (0, 0, 0, 3))
|
| 572 |
+
w = (zz[:, 0:Lw] + zz[:, 1:Lw + 1] + zz[:, 2:Lw + 2] + zz[:, 3:Lw + 3]) / 4
|
| 573 |
+
w = F.normalize(w, dim=-1)
|
| 574 |
+
cur = b["off"][:, None] + torch.arange(L, device=w.device)[None] # rows of the crop in the window
|
| 575 |
+
wc = torch.gather(w, 1, cur.clamp(max=Lw - 1)[..., None].expand(-1, -1, w.shape[-1]))
|
| 576 |
+
cand = b["hint"].clamp(min=0)
|
| 577 |
+
wk = torch.gather(w, 1, cand.reshape(B, -1)[..., None].expand(-1, -1, w.shape[-1])).view(B, L, K, -1)
|
| 578 |
+
sim = (wk * wc[:, :, None]).sum(-1).masked_fill(b["hint"] < 0, -2.0)
|
| 579 |
+
best, j = sim.max(-1)
|
| 580 |
+
row = torch.gather(cand, 2, j[..., None])[..., 0]
|
| 581 |
+
ok = (best > -1.5) & ~b["hint_off"][:, None]
|
| 582 |
+
htok = torch.gather(b["tok_win"], 1, row).masked_fill(~ok, self.V + 1)
|
| 583 |
+
hcol = torch.gather(b["col_win"], 1, row[..., None].expand(-1, -1, N_POS)).masked_fill(~ok[..., None], -1)
|
| 584 |
+
return self.hint_tok(htok) + self.hint_col(hcol) + self.hint_sim(torch.where(ok, best, 0.0)[..., None].float())
|
| 585 |
+
|
| 586 |
+
def dec_input(self, b, ctx, hint):
|
| 587 |
+
spec = b["spec"].float()
|
| 588 |
+
sv = torch.cat([torch.log1p(b["settings"].float()) * spec, spec], -1)
|
| 589 |
+
return (self.tok_in(b["prev_tok"]) + self.col_in(b["prev_col"]) + self.obj_in(b["prev_obj"] + 1)
|
| 590 |
+
+ self.body_in(b["in_body"].long()) + self.bib(b["bib"]) + self.tempo(b["logbl"][..., None])
|
| 591 |
+
+ self.tier(b["tier"])[:, None] + self.era(b["era"])[:, None] + self.set_in(sv)[:, None]
|
| 592 |
+
+ self.ctx_in(ctx) + hint + self.music_flag(b["music_off"].long())[:, None])
|
| 593 |
+
|
| 594 |
+
def decode(self, x, style, pos=None, caches=None):
|
| 595 |
+
if pos is None:
|
| 596 |
+
pos = torch.arange(x.shape[1], device=x.device)[None].expand(x.shape[0], -1)
|
| 597 |
+
for i, layer in enumerate(self.layers):
|
| 598 |
+
x = layer(x, pos, style, None if caches is None else caches[i])
|
| 599 |
+
return self.norm(x)
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
# ------------------------------------------------------------------------------------------------ losses
|
| 603 |
+
|
| 604 |
+
def pattern_scores(model, h, lg, tier, allowed, music_off, vmask_bits, lam=1.0):
|
| 605 |
+
"""fp32 scores [B, L, V] = gamma * music + design, invalid patterns at -inf (EMPTY always valid)."""
|
| 606 |
+
d = model.out(h).float()
|
| 607 |
+
with torch.autocast(h.device.type, enabled=False): # music term and scores in fp32
|
| 608 |
+
M = vmask_bits.float() # [V, 24] (EMPTY, OTHER rows 0)
|
| 609 |
+
m = torch.einsum("blp,vp->blv", lg.float(), M)
|
| 610 |
+
g = (model.gamma[tier].float() * lam)[:, None, None]
|
| 611 |
+
s = d + g * m * (~music_off).float()[:, None, None]
|
| 612 |
+
forb = ((~bits_to_bool_t(allowed)).float() @ M.T) > 0 # pattern uses a forbidden position
|
| 613 |
+
forb[..., 1] = True # OTHER is never generated
|
| 614 |
+
forb[..., 0] = False
|
| 615 |
+
return s.masked_fill(forb, float("-inf"))
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
def bits_to_bool_t(x):
|
| 619 |
+
return ((x[..., None] >> torch.arange(N_POS, device=x.device)) & 1).bool()
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
def vic(Z):
|
| 623 |
+
std = torch.sqrt(Z.var(0) + 1e-4)
|
| 624 |
+
var = F.relu(1 - std).mean()
|
| 625 |
+
Zc = Z - Z.mean(0)
|
| 626 |
+
C = (Zc.T @ Zc) / max(len(Z) - 1, 1)
|
| 627 |
+
off = C - torch.diag(torch.diag(C))
|
| 628 |
+
return var + 0.04 * (off ** 2).sum() / Z.shape[1]
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def _cov(U):
|
| 632 |
+
Uc = U - U.mean(0)
|
| 633 |
+
return Uc.T @ Uc / max(len(U) - 1, 1)
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
def f_exc(U, g=9.0):
|
| 637 |
+
N, d = U.shape
|
| 638 |
+
e = (U ** 2).mean().clamp_min(1e-6)
|
| 639 |
+
m = min(d, N - 1)
|
| 640 |
+
return torch.logdet(torch.eye(d, device=U.device) + g * _cov(U) / e) / (m * math.log1p(g * d / m))
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
def f_tr(H, Z, g=9.0, rho=1e-3):
|
| 644 |
+
N, dH = H.shape
|
| 645 |
+
dZ = Z.shape[1]
|
| 646 |
+
CH, CZ = _cov(H), _cov(Z)
|
| 647 |
+
Hc, Zc = H - H.mean(0), Z - Z.mean(0)
|
| 648 |
+
X = Hc.T @ Zc / max(N - 1, 1)
|
| 649 |
+
tH = (torch.trace(CH) / dH).clamp_min(1e-6)
|
| 650 |
+
tZ = (torch.trace(CZ) / dZ).clamp_min(1e-6)
|
| 651 |
+
LH = torch.linalg.cholesky(CH + rho * tH * torch.eye(dH, device=H.device))
|
| 652 |
+
LZ = torch.linalg.cholesky(CZ + rho * tZ * torch.eye(dZ, device=H.device))
|
| 653 |
+
K = torch.linalg.solve_triangular(LH, X, upper=False)
|
| 654 |
+
K = torch.linalg.solve_triangular(LZ, K.T, upper=False).T
|
| 655 |
+
m = min(dH, dZ, N - 1)
|
| 656 |
+
G = K @ K.T if dH <= dZ else K.T @ K
|
| 657 |
+
return torch.logdet(torch.eye(G.shape[0], device=H.device) + g * G) / (m * math.log1p(g))
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
def sadl(H, Z, lam_d=0.1, lam_s=0.01, eps=1e-6):
|
| 661 |
+
"""D(Z) (VIC) and the one-sided supply loss S (arXiv:2611.21596, eqs. 6-10), fp32."""
|
| 662 |
+
H, Z = H.float(), Z.float()
|
| 663 |
+
D = vic(Z)
|
| 664 |
+
with torch.no_grad():
|
| 665 |
+
D0 = vic(torch.zeros_like(Z) + 1e-8 * torch.randn_like(Z))
|
| 666 |
+
q = torch.exp(0.5 * (torch.log(torch.clamp(1 - D / D0, 0, 1) + eps) + torch.log(f_exc(Z) + eps)))
|
| 667 |
+
k = torch.minimum(f_exc(H), f_tr(H, Z.detach()))
|
| 668 |
+
S = F.relu(torch.log(q + eps) - torch.log(k + eps)) ** 2
|
| 669 |
+
return lam_d * D + lam_s * S, {"D": D.item(), "S": S.item(), "q": q.item(), "k": k.item()}
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
@torch.no_grad()
|
| 673 |
+
@torch.autocast("cuda", enabled=False)
|
| 674 |
+
def collapse_stats(H):
|
| 675 |
+
H = H.float()
|
| 676 |
+
e = (H ** 2).mean().clamp_min(1e-12)
|
| 677 |
+
C = _cov(H)
|
| 678 |
+
f = torch.trace(C) / (H.shape[1] * e)
|
| 679 |
+
ev = torch.linalg.eigvalsh(C).clamp(min=0)
|
| 680 |
+
p = ev / ev.sum().clamp_min(1e-12)
|
| 681 |
+
erank = torch.exp(-(p * torch.log(p.clamp_min(1e-12))).sum())
|
| 682 |
+
return {"f_H": f.item(), "erank": erank.item()}
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
def forward_losses(model, ema_enc, b, rout, vmask_bits, device, w_col=0.5, w_obj=0.5, w_jepa=0.2, jepa=True):
|
| 686 |
+
"""All training losses for one batch. rout: per item (calibrated logits [Lr,24,5] numpy, z [Lr,dz], u [Lr,24,du])."""
|
| 687 |
+
B, L = b["tok"].shape
|
| 688 |
+
tier = b["tier"]
|
| 689 |
+
# R features aligned to the crop, and the window z for the hint
|
| 690 |
+
Lw = max(r[1].shape[0] for r in rout)
|
| 691 |
+
lg = torch.zeros(B, L, N_POS, device=device)
|
| 692 |
+
z = torch.zeros(B, L, rout[0][1].shape[-1], device=device)
|
| 693 |
+
u = torch.zeros(B, L, N_POS, rout[0][2].shape[-1], device=device)
|
| 694 |
+
zw = torch.zeros(B, Lw, rout[0][1].shape[-1], device=device)
|
| 695 |
+
for i, (l_np, zi, ui) in enumerate(rout):
|
| 696 |
+
o, n = int(b["off"][i]), int(b["mask"][i].sum())
|
| 697 |
+
lg[i, :n] = torch.from_numpy(l_np[o:o + n, :, int(tier[i])]).to(device)
|
| 698 |
+
z[i, :n], u[i, :n] = zi[o:o + n].to(device), ui[o:o + n].to(device)
|
| 699 |
+
zw[i, :zi.shape[0]] = zi.to(device)
|
| 700 |
+
moff = b["music_off"]
|
| 701 |
+
z = z * (~moff).float()[:, None, None]
|
| 702 |
+
u = u * (~moff).float()[:, None, None, None]
|
| 703 |
+
zw = zw * (~moff).float()[:, None, None]
|
| 704 |
+
b = dict(b)
|
| 705 |
+
b["hint_off"] = b["hint_off"] | moff
|
| 706 |
+
style = model.style(b)
|
| 707 |
+
ctx = model.context(b)
|
| 708 |
+
x = model.dec_input(b, ctx, model.hint(b, zw))
|
| 709 |
+
h = model.decode(x, style)
|
| 710 |
+
s = pattern_scores(model, h, lg, tier, b["allowed"], moff, vmask_bits)
|
| 711 |
+
tgt = b["tok"]
|
| 712 |
+
tmask = b["mask"] & ~b["known"] & (b["allowed"] != 0) & (tgt != OTHER)
|
| 713 |
+
tmask &= ~torch.isinf(torch.gather(s, 2, tgt[..., None])[..., 0]) # target on an invalid position
|
| 714 |
+
logp = torch.log_softmax(s, -1)
|
| 715 |
+
nll = -torch.gather(logp, 2, tgt[..., None])[..., 0]
|
| 716 |
+
tw = torch.tensor(TIER_WEIGHT, device=device)[tier][:, None].expand(-1, L)
|
| 717 |
+
l_pat = (nll * tw)[tmask].sum() / tw[tmask].sum().clamp_min(1)
|
| 718 |
+
# colours: notes of trained beats, previous colour in the beat by teacher forcing
|
| 719 |
+
col = b["col"]
|
| 720 |
+
has = (col >= 0) & tmask[..., None]
|
| 721 |
+
prev = torch.full_like(col, N_COL)
|
| 722 |
+
last = torch.full(col.shape[:2], N_COL, dtype=torch.long, device=device)
|
| 723 |
+
for p in range(N_POS):
|
| 724 |
+
prev[:, :, p] = last
|
| 725 |
+
last = torch.where(col[:, :, p] >= 0, col[:, :, p], last)
|
| 726 |
+
hc = (h[:, :, None] + model.c_pos.weight[None, None] + model.u_proj(u) + model.c_prev(prev))
|
| 727 |
+
cl = model.col_head(hc[has]).float()
|
| 728 |
+
l_col = F.cross_entropy(cl, col[has]) if has.any() else torch.zeros((), device=device)
|
| 729 |
+
# objects
|
| 730 |
+
omask = b["mask"] & ~b["known"] & ~b["in_body"]
|
| 731 |
+
ho = h + model.z_proj(z)
|
| 732 |
+
start = (b["obj"][..., 0] >= 0)
|
| 733 |
+
l_start = F.binary_cross_entropy_with_logits(model.obj_start(ho)[..., 0].float()[omask], start[omask].float())
|
| 734 |
+
sm = start & omask
|
| 735 |
+
if sm.any():
|
| 736 |
+
l_kind = F.cross_entropy(model.obj_kind(ho[sm]).float(), b["obj"][..., 0][sm])
|
| 737 |
+
l_pos = F.cross_entropy(model.obj_pos(ho[sm]).float(), b["obj"][..., 1][sm])
|
| 738 |
+
l_len = F.cross_entropy(model.obj_len(ho[sm]).float(), b["obj"][..., 2][sm])
|
| 739 |
+
l_obj = l_start + (l_kind + l_pos + l_len) / 3
|
| 740 |
+
else:
|
| 741 |
+
l_obj = l_start
|
| 742 |
+
loss = l_pat + w_col * l_col + w_obj * l_obj
|
| 743 |
+
stats = {"pat": l_pat.item(), "col": l_col.item(), "obj": l_obj.item()}
|
| 744 |
+
# E_c auxiliary losses on samples with known content
|
| 745 |
+
has_ctx = (b["known"].any(1) | (b["o_tier"] < 5))
|
| 746 |
+
if jepa and has_ctx.any():
|
| 747 |
+
with torch.no_grad():
|
| 748 |
+
tgt_rep = ema_enc(b["tok"], b["col"], b["obj"][..., 0], torch.full_like(b["tok"], model.V + 1),
|
| 749 |
+
torch.full_like(b["col"], -1), torch.full_like(b["obj"][..., 0], -1),
|
| 750 |
+
torch.full_like(b["o_tier"], 5), b["bib"], b["logbl"], b["mask"])
|
| 751 |
+
unk = b["mask"] & ~b["known"] & has_ctx[:, None]
|
| 752 |
+
if unk.any():
|
| 753 |
+
pr = model.pred(torch.cat([ctx, model.pred_z(z)], -1))
|
| 754 |
+
l_j = (1 - F.cosine_similarity(pr[unk].float(), tgt_rep[unk].float(), dim=-1)).mean()
|
| 755 |
+
loss = loss + w_jepa * l_j
|
| 756 |
+
stats["jepa"] = l_j.item()
|
| 757 |
+
kn = b["mask"] & (b["known"] | ((b["o_tok"] != model.V + 1) & (b["o_tok"] != 0)))
|
| 758 |
+
Hk = ctx[kn]
|
| 759 |
+
if len(Hk) > 64:
|
| 760 |
+
if len(Hk) > 2000:
|
| 761 |
+
Hk = Hk[torch.randperm(len(Hk), device=device)[:2000]]
|
| 762 |
+
with torch.autocast(device.type, enabled=False):
|
| 763 |
+
Zk = model.proj(Hk.float())
|
| 764 |
+
l_s, st = sadl(Hk.float(), Zk)
|
| 765 |
+
loss = loss + l_s
|
| 766 |
+
stats.update({f"sadl_{k}": v for k, v in st.items()})
|
| 767 |
+
stats.update(collapse_stats(Hk))
|
| 768 |
+
return loss, stats
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
# ------------------------------------------------------------------------------------------------ training
|
| 772 |
+
|
| 773 |
+
class Stream(torch.utils.data.IterableDataset):
|
| 774 |
+
def __init__(self, c: WCorpus, batch, seed):
|
| 775 |
+
self.c, self.batch, self.seed = c, batch, seed
|
| 776 |
+
w = np.array([TIER_WEIGHT[t] * len(c.groups[gi]["g"].table) for gi, t, _ in c.items], np.float64)
|
| 777 |
+
self.p = w / w.sum()
|
| 778 |
+
|
| 779 |
+
def __iter__(self):
|
| 780 |
+
wi = torch.utils.data.get_worker_info()
|
| 781 |
+
rng = np.random.default_rng([self.seed, wi.id if wi else 0, int(time.time() * 1e3) % (2 ** 31)])
|
| 782 |
+
while True:
|
| 783 |
+
items = []
|
| 784 |
+
for k in rng.choice(len(self.c.items), self.batch, p=self.p):
|
| 785 |
+
n = len(self.c.groups[self.c.items[k][0]]["g"].table)
|
| 786 |
+
r0 = int(rng.integers(0, max(n - CROP, 0) + 1))
|
| 787 |
+
items.append(make_crop(self.c, int(k), r0, rng))
|
| 788 |
+
yield items
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
def fixed_tune(c: WCorpus, n, batch, seed=7):
|
| 792 |
+
"""Fixed tune batches: the random condition scheme with a fixed seed (comparable across steps)."""
|
| 793 |
+
rng = np.random.default_rng(seed)
|
| 794 |
+
out = []
|
| 795 |
+
ks = rng.choice(len(c.items), n, replace=len(c.items) < n)
|
| 796 |
+
for i in range(0, n, batch):
|
| 797 |
+
items = []
|
| 798 |
+
for k in ks[i:i + batch]:
|
| 799 |
+
nb = len(c.groups[c.items[k][0]]["g"].table)
|
| 800 |
+
items.append(make_crop(c, int(k), int(rng.integers(0, max(nb - CROP, 0) + 1)), rng))
|
| 801 |
+
out.append(items)
|
| 802 |
+
return out
|
| 803 |
+
|
| 804 |
+
|
| 805 |
+
def run_batch(model, ema_enc, items, rf: RFolds, vmask_bits, device, jepa):
|
| 806 |
+
b = collate_w(items, model.V)
|
| 807 |
+
folds = [rf.fold_of(x["role"]) for x in items]
|
| 808 |
+
rout = rf.run([x["r"] for x in items], folds)
|
| 809 |
+
bt = {k: (v.to(device, non_blocking=True) if torch.is_tensor(v) else v) for k, v in b.items()}
|
| 810 |
+
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda" or AUTOCAST_CPU):
|
| 811 |
+
return forward_losses(model, ema_enc, bt, rout, vmask_bits, device, jepa=jepa)
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
@torch.no_grad()
|
| 815 |
+
def evaluate(model, ema_enc, tune, rf, vmask_bits, device, jepa):
|
| 816 |
+
model.eval()
|
| 817 |
+
tot = {}
|
| 818 |
+
for items in tune:
|
| 819 |
+
_, st = run_batch(model, ema_enc, items, rf, vmask_bits, device, jepa)
|
| 820 |
+
for k, v in st.items():
|
| 821 |
+
tot.setdefault(k, []).append(v)
|
| 822 |
+
model.train()
|
| 823 |
+
return {k: float(np.mean(v)) for k, v in tot.items()}
|
| 824 |
+
|
| 825 |
+
|
| 826 |
+
def vocab_bits(vocab, device):
|
| 827 |
+
m = np.r_[np.int64(0), np.int64(0), vocab.masks]
|
| 828 |
+
return torch.from_numpy(((m[:, None] >> np.arange(N_POS)[None]) & 1).astype(np.float32)).to(device)
|
| 829 |
+
|
| 830 |
+
|
| 831 |
+
def train(a):
|
| 832 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 833 |
+
torch.manual_seed(a.seed)
|
| 834 |
+
out = Path(a.out)
|
| 835 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 836 |
+
logf = open(out / "metrics.jsonl", "a")
|
| 837 |
+
|
| 838 |
+
def log(rec):
|
| 839 |
+
rec["time"] = time.time()
|
| 840 |
+
logf.write(json.dumps(rec) + "\n")
|
| 841 |
+
logf.flush()
|
| 842 |
+
print(json.dumps(rec), flush=True)
|
| 843 |
+
|
| 844 |
+
tr = WCorpus(a.data, {"A", "B"}, a.cache_dir, log=lambda m: print(m, flush=True))
|
| 845 |
+
tu = WCorpus(a.data, {"tune"}, a.cache_dir, log=lambda m: print(m, flush=True))
|
| 846 |
+
rf = RFolds({"A": a.r_a, "B": a.r_b}, {"A": a.calib_a, "B": a.calib_b}, device)
|
| 847 |
+
V = len(tr.vocab)
|
| 848 |
+
jepa = not a.no_jepa
|
| 849 |
+
model = Writer(V, jepa=True).to(device)
|
| 850 |
+
ema_enc = copy.deepcopy(model.enc).eval()
|
| 851 |
+
for q in ema_enc.parameters():
|
| 852 |
+
q.requires_grad_(False)
|
| 853 |
+
vb = vocab_bits(tr.vocab, device)
|
| 854 |
+
decay = [p for n, p in model.named_parameters() if p.ndim >= 2]
|
| 855 |
+
no_decay = [p for n, p in model.named_parameters() if p.ndim < 2]
|
| 856 |
+
opt = torch.optim.AdamW([{"params": decay, "weight_decay": 0.01}, {"params": no_decay, "weight_decay": 0.0}],
|
| 857 |
+
lr=a.lr)
|
| 858 |
+
sched = lambda s: min(1.0, (s + 1) / a.warmup) * (0.5 * (1 + math.cos(math.pi * min(s, a.steps) / a.steps)) * 0.95 + 0.05) # noqa: E731
|
| 859 |
+
step, best = 0, math.inf
|
| 860 |
+
if a.resume and (out / "last.pt").exists():
|
| 861 |
+
ck = torch.load(out / "last.pt", map_location=device, weights_only=False)
|
| 862 |
+
model.load_state_dict(ck["model"]); opt.load_state_dict(ck["opt"]); ema_enc.load_state_dict(ck["ema"])
|
| 863 |
+
step, best = ck["step"], ck["best"]
|
| 864 |
+
torch.set_rng_state(ck["rng"].cpu()) # map_location moves the saved ByteTensor to the GPU
|
| 865 |
+
print(f"resumed at step {step}, best {best:.5f}", flush=True)
|
| 866 |
+
log({"event": "start", "step": step, "params": sum(p.numel() for p in model.parameters()),
|
| 867 |
+
"train_charts": len(tr.items), "tune_charts": len(tu.items), "args": {k: str(v) for k, v in vars(a).items()}})
|
| 868 |
+
tune = fixed_tune(tu, a.tune_crops, a.batch)
|
| 869 |
+
dl = torch.utils.data.DataLoader(Stream(tr, a.batch, a.seed + step), batch_size=None, num_workers=a.workers,
|
| 870 |
+
prefetch_factor=4 if a.workers else None, persistent_workers=a.workers > 0,
|
| 871 |
+
collate_fn=lambda x: x)
|
| 872 |
+
it = iter(dl)
|
| 873 |
+
t_last, n_tok, ema_l = time.time(), 0, None
|
| 874 |
+
model.train()
|
| 875 |
+
while step < a.steps:
|
| 876 |
+
t_d = time.time()
|
| 877 |
+
items = next(it)
|
| 878 |
+
t_w = time.time() - t_d
|
| 879 |
+
for gp in opt.param_groups:
|
| 880 |
+
gp["lr"] = a.lr * sched(step)
|
| 881 |
+
loss, st = run_batch(model, ema_enc, items, rf, vb, device, jepa)
|
| 882 |
+
opt.zero_grad(set_to_none=True)
|
| 883 |
+
loss.backward()
|
| 884 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 885 |
+
opt.step()
|
| 886 |
+
with torch.no_grad():
|
| 887 |
+
for pe, pm in zip(ema_enc.parameters(), model.enc.parameters()):
|
| 888 |
+
pe.mul_(0.996).add_(pm.detach(), alpha=0.004)
|
| 889 |
+
step += 1
|
| 890 |
+
n_tok += sum(x["L"] for x in items)
|
| 891 |
+
ema_l = st["pat"] if ema_l is None else 0.98 * ema_l + 0.02 * st["pat"]
|
| 892 |
+
if step % 50 == 0:
|
| 893 |
+
dt = time.time() - t_last
|
| 894 |
+
log({"event": "train", "step": step, "pat_ema": ema_l, **st, "lr": a.lr * sched(step),
|
| 895 |
+
"gamma": model.gamma.detach().cpu().tolist(), "beats_per_s": n_tok / dt, "data_wait_s": t_w})
|
| 896 |
+
t_last, n_tok = time.time(), 0
|
| 897 |
+
if step % a.eval_every == 0 or step == a.steps:
|
| 898 |
+
ev = evaluate(model, ema_enc, tune, rf, vb, device, jepa)
|
| 899 |
+
vl = ev["pat"]
|
| 900 |
+
is_best = vl < best
|
| 901 |
+
best = min(best, vl)
|
| 902 |
+
ck = {"model": model.state_dict(), "opt": opt.state_dict(), "ema": ema_enc.state_dict(), "step": step,
|
| 903 |
+
"best": best, "cfg": model.cfg, "rng": torch.get_rng_state()}
|
| 904 |
+
torch.save(ck, out / "last.pt.tmp"); os.replace(out / "last.pt.tmp", out / "last.pt")
|
| 905 |
+
if is_best:
|
| 906 |
+
torch.save({"model": model.state_dict(), "cfg": model.cfg, "step": step, "tune": ev},
|
| 907 |
+
out / "best.pt.tmp")
|
| 908 |
+
os.replace(out / "best.pt.tmp", out / "best.pt")
|
| 909 |
+
log({"event": "eval", "step": step, "tune": ev, "best": best, "is_best": is_best})
|
| 910 |
+
model.train()
|
| 911 |
+
if a.patience and not is_best and step - _last_best(out) >= a.patience:
|
| 912 |
+
log({"event": "early_stop", "step": step})
|
| 913 |
+
break
|
| 914 |
+
log({"event": "end", "step": step, "best": best})
|
| 915 |
+
|
| 916 |
+
|
| 917 |
+
def _last_best(out: Path) -> int:
|
| 918 |
+
best_step = 0
|
| 919 |
+
for line in open(out / "metrics.jsonl"):
|
| 920 |
+
r = json.loads(line)
|
| 921 |
+
if r.get("event") == "eval" and r.get("is_best"):
|
| 922 |
+
best_step = r["step"]
|
| 923 |
+
return best_step
|
| 924 |
+
|
| 925 |
+
|
| 926 |
+
def load_writer(path, device):
|
| 927 |
+
ck = torch.load(path, map_location=device, weights_only=False)
|
| 928 |
+
m = Writer(**ck["cfg"]).to(device)
|
| 929 |
+
m.load_state_dict(ck["model"])
|
| 930 |
+
return m.eval()
|
| 931 |
+
|
| 932 |
+
|
| 933 |
+
# ------------------------------------------------------------------------------------------------ self-test
|
| 934 |
+
|
| 935 |
+
def selftest(steps=60):
|
| 936 |
+
"""CPU smoke test on the pilot shard: crops build, one fold-split R forward, losses finite and decreasing on a
|
| 937 |
+
fixed batch (overfit), role / reference leakage asserts."""
|
| 938 |
+
torch.manual_seed(0)
|
| 939 |
+
shard = ["data/pilot/features/taiko-00000.pkl"]
|
| 940 |
+
cache = "data/hfruns/runs/v11_s2/caches"
|
| 941 |
+
c = WCorpus(shard, {"A", "B"}, cache)
|
| 942 |
+
rf = RFolds({"A": "data/hfruns/runs/r_A/best.pt", "B": "data/hfruns/runs/r_B/best.pt"},
|
| 943 |
+
{"A": "data/hfruns/runs/v11_s2/calib_A.json", "B": "data/hfruns/runs/v11_s2/calib_B.json"},
|
| 944 |
+
torch.device("cpu"))
|
| 945 |
+
V = len(c.vocab)
|
| 946 |
+
rng = np.random.default_rng(0)
|
| 947 |
+
items = []
|
| 948 |
+
for k in rng.choice(len(c.items), 6, replace=False):
|
| 949 |
+
n = len(c.groups[c.items[k][0]]["g"].table)
|
| 950 |
+
r0 = int(rng.integers(0, max(n - 128, 0) + 1))
|
| 951 |
+
x = make_crop(c, int(k), r0, rng)
|
| 952 |
+
x_small = x
|
| 953 |
+
items.append(x_small)
|
| 954 |
+
for x in items:
|
| 955 |
+
if x["ref"] is not None:
|
| 956 |
+
pass
|
| 957 |
+
assert rf.fold_of(x["role"]) != x["role"]
|
| 958 |
+
model = Writer(V, d=64, dec_layers=2, enc_layers=1, heads=4, d_z=256, d_u=96)
|
| 959 |
+
ema_enc = copy.deepcopy(model.enc)
|
| 960 |
+
vb = vocab_bits(c.vocab, torch.device("cpu"))
|
| 961 |
+
opt = torch.optim.AdamW(model.parameters(), lr=2e-3)
|
| 962 |
+
first = None
|
| 963 |
+
for s in range(steps):
|
| 964 |
+
loss, st = run_batch(model, ema_enc, items, rf, vb, torch.device("cpu"), True)
|
| 965 |
+
assert torch.isfinite(loss), st
|
| 966 |
+
opt.zero_grad(); loss.backward(); opt.step()
|
| 967 |
+
if first is None:
|
| 968 |
+
first = st["pat"]
|
| 969 |
+
if s % 10 == 0 or s == steps - 1:
|
| 970 |
+
print(s, {k: round(v, 4) for k, v in st.items()})
|
| 971 |
+
assert st["pat"] < first * 0.85, (first, st["pat"])
|
| 972 |
+
print("selftest ok: pattern loss", round(first, 3), "->", round(st["pat"], 3))
|
| 973 |
+
|
| 974 |
+
|
| 975 |
+
def main(argv=None):
|
| 976 |
+
p = argparse.ArgumentParser()
|
| 977 |
+
p.add_argument("cmd", nargs="?", choices=["train"])
|
| 978 |
+
p.add_argument("--selftest", action="store_true")
|
| 979 |
+
p.add_argument("--data", nargs="*", default=[])
|
| 980 |
+
p.add_argument("--cache-dir", default=None)
|
| 981 |
+
p.add_argument("--r-a"), p.add_argument("--r-b"), p.add_argument("--calib-a"), p.add_argument("--calib-b")
|
| 982 |
+
p.add_argument("--out")
|
| 983 |
+
p.add_argument("--seed", type=int, default=0)
|
| 984 |
+
p.add_argument("--no-jepa", action="store_true")
|
| 985 |
+
p.add_argument("--steps", type=int, default=30000)
|
| 986 |
+
p.add_argument("--batch", type=int, default=24)
|
| 987 |
+
p.add_argument("--lr", type=float, default=3e-4)
|
| 988 |
+
p.add_argument("--warmup", type=int, default=1000)
|
| 989 |
+
p.add_argument("--eval-every", type=int, default=500)
|
| 990 |
+
p.add_argument("--patience", type=int, default=4000)
|
| 991 |
+
p.add_argument("--tune-crops", type=int, default=192)
|
| 992 |
+
p.add_argument("--workers", type=int, default=6)
|
| 993 |
+
p.add_argument("--resume", action="store_true")
|
| 994 |
+
a = p.parse_args(argv)
|
| 995 |
+
if a.selftest:
|
| 996 |
+
selftest()
|
| 997 |
+
elif a.cmd == "train":
|
| 998 |
+
train(a)
|
| 999 |
+
|
| 1000 |
+
|
| 1001 |
+
if __name__ == "__main__":
|
| 1002 |
+
main()
|
chartgen/v11/writer_data.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""v11 stage 3: per-beat training data of the pattern writer W (reports/v11 階段 3 預先登記:節奏型寫手 W.md, section 1).
|
| 2 |
+
|
| 3 |
+
Built from the stage-2 R caches (<shard>.r.pkl: song records with raw charts and timing groups), so the beat tables
|
| 4 |
+
and roles are exactly R's. One record per chart, on its group's beat table (n beats):
|
| 5 |
+
tok [n] int16 pattern token (patterns.Vocab ids: EMPTY 0, OTHER 1, patterns 2..)
|
| 6 |
+
allowed [n] uint32 24-bit mask of the positions a note may take: valid (inside the audio, before a red line) and
|
| 7 |
+
not strictly inside a roll / balloon body; 0 for a beat with a note off the 24 positions
|
| 8 |
+
col [n] uint64 colour of each hit note, 2 bits per position (0 don, 1 ka, 2 big don, 3 big ka)
|
| 9 |
+
objs [k, 4] int32 roll / balloon objects: (beat row, position index 0-23, kind 0 roll / 1 big roll /
|
| 10 |
+
2 balloon, length in ms)
|
| 11 |
+
settings [5] float32 nps, big, triplet, eighth, rolls per minute (definitions in the registration)
|
| 12 |
+
mapper catalog mapper_user_id (-1 if unknown); year; beatmap id
|
| 13 |
+
A beat is trained on when allowed != 0 and tok != OTHER (train_mask()).
|
| 14 |
+
|
| 15 |
+
python -m chartgen.v11.writer_data prep --caches data/hfruns/runs/v11_s2/caches/*.r.pkl
|
| 16 |
+
python -m chartgen.v11.writer_data --selftest
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import argparse
|
| 22 |
+
import json
|
| 23 |
+
import os
|
| 24 |
+
import pickle
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
from chartgen.dataset import beat_ms, roll_end_beats
|
| 30 |
+
from chartgen.v11.patterns import GRID, OTHER, POS_BIT, POSITIONS, Vocab
|
| 31 |
+
from chartgen.v11.rmap_data import FAMILY_OF_CLASS, N_POS, POS, POS_CLASS, chart_masks
|
| 32 |
+
|
| 33 |
+
REPO = Path(__file__).resolve().parents[2]
|
| 34 |
+
VOCAB_JSON = REPO / "reports/figs/v11_s0_vocab.json"
|
| 35 |
+
CATALOG = REPO / "data/catalog/taiko_beatmaps.parquet"
|
| 36 |
+
SETTINGS = ("nps", "big", "triplet", "eighth", "rolls_per_min")
|
| 37 |
+
FAM_OF_POS = np.array([FAMILY_OF_CLASS[c] for c in POS_CLASS])
|
| 38 |
+
TRIPLET_POS = FAM_OF_POS == "triplet"
|
| 39 |
+
EIGHTH_POS = FAM_OF_POS == "eighth"
|
| 40 |
+
_POS_ARR = np.asarray(POSITIONS)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def load_vocab() -> Vocab:
|
| 44 |
+
d = json.loads(VOCAB_JSON.read_text())
|
| 45 |
+
return Vocab.from_dict(d["vocab_pooled"])
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def load_mappers() -> dict:
|
| 49 |
+
import pyarrow.parquet as pq
|
| 50 |
+
t = pq.read_table(CATALOG, columns=["beatmap_id", "mapper_user_id"]).to_pydict()
|
| 51 |
+
return {int(b): (int(m) if m is not None else -1) for b, m in zip(t["beatmap_id"], t["mapper_user_id"])}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def nearest_pos(k: int) -> int:
|
| 55 |
+
"""Index (0-23) of the candidate position nearest to 1/48 index k (k in 0..47)."""
|
| 56 |
+
return int(np.argmin(np.abs(_POS_ARR - k)))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def chart_settings_w(chart: dict) -> np.ndarray:
|
| 60 |
+
ty = np.asarray(chart["type"])
|
| 61 |
+
t = np.asarray(chart["time"], np.float64)
|
| 62 |
+
beat = np.asarray(chart["beat"], np.float64)
|
| 63 |
+
hit = ty <= 3
|
| 64 |
+
n = int(hit.sum())
|
| 65 |
+
out = np.zeros(5, np.float32)
|
| 66 |
+
if n < 2:
|
| 67 |
+
return out
|
| 68 |
+
span = max((t[hit].max() - t[hit].min()) / 1000.0, 1.0)
|
| 69 |
+
out[0] = n / span
|
| 70 |
+
out[1] = float((ty[hit] >= 2).mean())
|
| 71 |
+
k = np.mod(np.round(beat[hit] * GRID).astype(np.int64), GRID)
|
| 72 |
+
bit = POS_BIT[k]
|
| 73 |
+
on = bit >= 0
|
| 74 |
+
out[2] = float(TRIPLET_POS[bit[on]].sum() / n)
|
| 75 |
+
out[3] = float(EIGHTH_POS[bit[on]].sum() / n)
|
| 76 |
+
span_all = max((t.max() - t.min()) / 60000.0, 1.0 / 60)
|
| 77 |
+
out[4] = float((ty >= 4).sum() / span_all)
|
| 78 |
+
return out
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def chart_w(chart: dict, table, vocab: Vocab) -> dict:
|
| 82 |
+
tgt, loss = chart_masks(chart, table)
|
| 83 |
+
n = len(table)
|
| 84 |
+
tok = vocab.ids(tgt.astype(np.int64)).astype(np.int16)
|
| 85 |
+
col = np.zeros(n, np.uint64)
|
| 86 |
+
beat = np.asarray(chart["beat"], np.float64)
|
| 87 |
+
ty = np.asarray(chart["type"])
|
| 88 |
+
hit = ty <= 3
|
| 89 |
+
g = np.round(beat[hit] * GRID).astype(np.int64)
|
| 90 |
+
bb, kk = np.floor_divide(g, GRID), np.mod(g, GRID)
|
| 91 |
+
row = np.searchsorted(table.beat, bb)
|
| 92 |
+
ok = (row < n) & (table.beat[np.minimum(row, n - 1)] == bb) & (POS_BIT[kk] >= 0)
|
| 93 |
+
for r, b, c in zip(row[ok], POS_BIT[kk[ok]], ty[hit][ok]):
|
| 94 |
+
col[r] |= np.uint64(int(c) & 3) << np.uint64(2 * int(b))
|
| 95 |
+
objs = []
|
| 96 |
+
roll = ty >= 4
|
| 97 |
+
if roll.any():
|
| 98 |
+
sec = np.asarray(chart["sections"], np.float64)
|
| 99 |
+
sb = beat[roll]
|
| 100 |
+
eb = roll_end_beats(sec, sb, np.asarray(chart["length_beats"], np.float64)[roll])
|
| 101 |
+
ms0, ms1 = beat_ms(sec, sb), beat_ms(sec, eb)
|
| 102 |
+
for a, kind, l0, l1 in zip(sb, ty[roll], ms0, ms1):
|
| 103 |
+
b0 = int(np.floor(a + 1e-9))
|
| 104 |
+
r = int(np.searchsorted(table.beat, b0))
|
| 105 |
+
if r >= n or table.beat[r] != b0:
|
| 106 |
+
continue
|
| 107 |
+
k = int(round((a - b0) * GRID)) % GRID
|
| 108 |
+
objs.append((r, nearest_pos(k), int(kind) - 4, int(round(max(l1 - l0, 0.0)))))
|
| 109 |
+
return {"tok": tok, "allowed": loss.astype(np.uint32), "col": col,
|
| 110 |
+
"objs": np.asarray(objs, np.int32).reshape(-1, 4), "settings": chart_settings_w(chart)}
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def train_mask(rec: dict) -> np.ndarray:
|
| 114 |
+
return (rec["allowed"] != 0) & (rec["tok"] != OTHER)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def w_cache_path(rcache) -> Path:
|
| 118 |
+
return Path(str(rcache).replace(".r.pkl", ".w.pkl"))
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def prep_w(rcache, vocab: Vocab | None = None, mappers: dict | None = None) -> Path:
|
| 122 |
+
"""<shard>.w.pkl: [{set, key, groups: [{uid, role, era, charts: {tier: [record]}}]}] from <shard>.r.pkl."""
|
| 123 |
+
out = w_cache_path(rcache)
|
| 124 |
+
if out.exists():
|
| 125 |
+
return out
|
| 126 |
+
vocab = vocab or load_vocab()
|
| 127 |
+
mappers = mappers if mappers is not None else load_mappers()
|
| 128 |
+
recs = pickle.load(open(rcache, "rb"))
|
| 129 |
+
songs = []
|
| 130 |
+
for r in recs:
|
| 131 |
+
by_bid = {int(c["beatmap_id"]): c for c in r["charts"]}
|
| 132 |
+
gs = []
|
| 133 |
+
for g in r["groups"]:
|
| 134 |
+
charts = {}
|
| 135 |
+
for t, lst in g.charts.items():
|
| 136 |
+
for bid, year, _, _ in lst:
|
| 137 |
+
c = by_bid[int(bid)]
|
| 138 |
+
w = chart_w(c, g.table, vocab)
|
| 139 |
+
w.update(bid=int(bid), year=int(year), mapper=mappers.get(int(bid), -1))
|
| 140 |
+
charts.setdefault(int(t), []).append(w)
|
| 141 |
+
gs.append({"uid": g.uid, "role": g.role, "era": g.era, "n": len(g.table), "charts": charts})
|
| 142 |
+
songs.append({"set": int(r["beatmapset_id"]), "key": r["song_key"] or str(r["beatmapset_id"]), "groups": gs})
|
| 143 |
+
tmp = out.with_suffix(f".{os.getpid()}.tmp")
|
| 144 |
+
with open(tmp, "wb") as f:
|
| 145 |
+
pickle.dump(songs, f, protocol=pickle.HIGHEST_PROTOCOL)
|
| 146 |
+
os.replace(tmp, out)
|
| 147 |
+
return out
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
# ------------------------------------------------------------------------------------------------ decoding
|
| 151 |
+
|
| 152 |
+
def decode_chart(tok, col, objs, table, sections, vocab: Vocab, tier: int) -> dict:
|
| 153 |
+
"""W records (or generated arrays) -> chart dict (time ms, type, length_beats, sv, kiai empty) on the table."""
|
| 154 |
+
masks = vocab.mask(np.where(np.asarray(tok) == OTHER, 0, tok)).astype(np.int64)
|
| 155 |
+
times, types, lens = [], [], []
|
| 156 |
+
pt = table.pos_ms() # [n, 24]
|
| 157 |
+
for r in np.nonzero(masks > 0)[0]:
|
| 158 |
+
m = int(masks[r])
|
| 159 |
+
for i in range(N_POS):
|
| 160 |
+
if m >> i & 1:
|
| 161 |
+
times.append(pt[r, i])
|
| 162 |
+
types.append(int((int(col[r]) >> (2 * i)) & 3))
|
| 163 |
+
lens.append(0.0)
|
| 164 |
+
sec = np.asarray(sections, np.float64)
|
| 165 |
+
for r, i, kind, lms in np.asarray(objs).reshape(-1, 4):
|
| 166 |
+
t0 = pt[r, i]
|
| 167 |
+
b0 = table.beat[r] + POS[i] / GRID
|
| 168 |
+
# length in beats of the section where the object starts
|
| 169 |
+
j = max(int(np.searchsorted(sec[:, 0], t0, side="right")) - 1, 0)
|
| 170 |
+
times.append(t0)
|
| 171 |
+
types.append(int(kind) + 4)
|
| 172 |
+
lens.append(float(lms) / sec[j, 1])
|
| 173 |
+
_ = b0
|
| 174 |
+
o = np.argsort(times, kind="stable")
|
| 175 |
+
return {"tier": tier, "sections": sec, "time": np.asarray(times)[o], "type": np.asarray(types, int)[o],
|
| 176 |
+
"length_beats": np.asarray(lens)[o], "sv": np.ones(len(o)), "kiai": []}
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# ------------------------------------------------------------------------------------------------ self-test
|
| 180 |
+
|
| 181 |
+
def selftest(rcache="data/hfruns/runs/v11_s2/caches/taiko-00000.r.pkl", max_charts=400):
|
| 182 |
+
"""Round trip: chart -> W records -> chart reproduces every hit note (time within 1 ms, same type) on the beats
|
| 183 |
+
that are trained on, and every roll / balloon start, kind and length (within 1 ms)."""
|
| 184 |
+
from chartgen.rhythm_eval2 import grid_of
|
| 185 |
+
vocab = load_vocab()
|
| 186 |
+
recs = pickle.load(open(rcache, "rb"))
|
| 187 |
+
n_ch = n_note = n_obj = bad = 0
|
| 188 |
+
devs = []
|
| 189 |
+
for r in recs:
|
| 190 |
+
by_bid = {int(c["beatmap_id"]): c for c in r["charts"]}
|
| 191 |
+
for g in r["groups"]:
|
| 192 |
+
for t, lst in g.charts.items():
|
| 193 |
+
for bid, _, _, _ in lst:
|
| 194 |
+
c = by_bid[int(bid)]
|
| 195 |
+
w = chart_w(c, g.table, vocab)
|
| 196 |
+
dec = decode_chart(w["tok"], w["col"], w["objs"], g.table, g.sections, vocab, t)
|
| 197 |
+
tm = train_mask(w)
|
| 198 |
+
# human hit notes on trained beats
|
| 199 |
+
ty = np.asarray(c["type"])
|
| 200 |
+
hit = ty <= 3
|
| 201 |
+
gh = np.round(np.asarray(c["beat"], np.float64)[hit] * GRID).astype(np.int64)
|
| 202 |
+
rows = np.searchsorted(g.table.beat, np.floor_divide(gh, GRID))
|
| 203 |
+
okr = (rows < len(g.table)) & (g.table.beat[np.minimum(rows, len(g.table) - 1)] == np.floor_divide(gh, GRID))
|
| 204 |
+
sel = okr.copy()
|
| 205 |
+
sel[okr] = tm[rows[okr]]
|
| 206 |
+
raw = np.asarray(c["time"], np.float64)[hit][sel]
|
| 207 |
+
ht = beat_ms(np.asarray(c["sections"], np.float64), gh[sel] / GRID) # grid time of each note
|
| 208 |
+
devs.append(np.abs(raw - ht))
|
| 209 |
+
hty = ty[hit][sel]
|
| 210 |
+
dh = dec["type"] <= 3
|
| 211 |
+
dt, dty = dec["time"][dh], dec["type"][dh]
|
| 212 |
+
drow = np.searchsorted(g.table.t0, dt, side="right") - 1
|
| 213 |
+
dsel = tm[np.clip(drow, 0, len(tm) - 1)]
|
| 214 |
+
dt, dty = dt[dsel], dty[dsel]
|
| 215 |
+
if len(ht) != len(dt) or (len(ht) and (np.abs(np.sort(ht) - np.sort(dt)).max() > 1.0)):
|
| 216 |
+
bad += 1
|
| 217 |
+
if bad <= 3:
|
| 218 |
+
print("hit mismatch", bid, t, len(ht), len(dt))
|
| 219 |
+
elif len(ht) and (hty[np.argsort(ht)] != dty[np.argsort(dt)]).any():
|
| 220 |
+
bad += 1
|
| 221 |
+
if bad <= 3:
|
| 222 |
+
print("type mismatch", bid, t)
|
| 223 |
+
ro = ty >= 4
|
| 224 |
+
if ro.sum() != (dec["type"] >= 4).sum():
|
| 225 |
+
bad += 1
|
| 226 |
+
if bad <= 3:
|
| 227 |
+
print("object count mismatch", bid, t, ro.sum(), (dec["type"] >= 4).sum())
|
| 228 |
+
n_ch += 1
|
| 229 |
+
n_note += len(ht)
|
| 230 |
+
n_obj += int(ro.sum())
|
| 231 |
+
if n_ch >= max_charts:
|
| 232 |
+
break
|
| 233 |
+
d = np.concatenate(devs) if devs else np.zeros(1)
|
| 234 |
+
print(f"selftest: {n_ch} charts, {n_note} notes on trained beats, {n_obj} objects, {bad} mismatches; "
|
| 235 |
+
f"raw time vs grid time: median {np.median(d):.2f} ms, 99th pct {np.percentile(d, 99):.2f} ms")
|
| 236 |
+
assert bad == 0
|
| 237 |
+
return True
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def main(argv=None):
|
| 241 |
+
p = argparse.ArgumentParser()
|
| 242 |
+
p.add_argument("cmd", nargs="?", choices=["prep"])
|
| 243 |
+
p.add_argument("--caches", nargs="*", default=[])
|
| 244 |
+
p.add_argument("--workers", type=int, default=4)
|
| 245 |
+
p.add_argument("--selftest", action="store_true")
|
| 246 |
+
a = p.parse_args(argv)
|
| 247 |
+
if a.selftest:
|
| 248 |
+
selftest()
|
| 249 |
+
return
|
| 250 |
+
if a.cmd == "prep":
|
| 251 |
+
from multiprocessing import Pool
|
| 252 |
+
with Pool(a.workers) as pool:
|
| 253 |
+
for out in pool.imap_unordered(prep_w, a.caches):
|
| 254 |
+
print("wrote", out, flush=True)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
if __name__ == "__main__":
|
| 258 |
+
main()
|
packages.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
ffmpeg
|
pipeline.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Infer a paired Model P chartset and export it for osu!taiko and TJA."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
from dataclasses import replace
|
| 6 |
+
from functools import lru_cache
|
| 7 |
+
import hashlib
|
| 8 |
+
import json
|
| 9 |
+
import math
|
| 10 |
+
import os
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
import subprocess
|
| 13 |
+
from types import SimpleNamespace
|
| 14 |
+
import zipfile
|
| 15 |
+
|
| 16 |
+
from huggingface_hub import hf_hub_download
|
| 17 |
+
import numpy as np
|
| 18 |
+
from safetensors.torch import load_file
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from chartgen.beattrack import decode_timing_auto
|
| 22 |
+
from chartgen.dataset import GRID, MAX_AHEAD, WINDOW, bar_plan, make_example, measure_at
|
| 23 |
+
from chartgen.features import SAMPLE_RATE, decode_audio, log_mel
|
| 24 |
+
from chartgen.gen_mapset import window_plan
|
| 25 |
+
from chartgen.generate import generate
|
| 26 |
+
from chartgen.infer import GeneratedChart, _dummy_chart, frame_activations, music_span, to_osu
|
| 27 |
+
from chartgen.model import B0, B0Config
|
| 28 |
+
from chartgen.rhythm_eval2 import beats_tol
|
| 29 |
+
from chartgen.v11 import pmap
|
| 30 |
+
from chartgen.v11.rmap import RMap, predict_group
|
| 31 |
+
from chartgen.v11.rmap_data import Group, beat_table
|
| 32 |
+
from chartgen.v11.rmap_eval import apply_calib, load_calib
|
| 33 |
+
from chartgen.v11.s2_arms import pseudo_chart
|
| 34 |
+
from chartgen.v11.s5d_osz import hold_rolls, shared_kiai
|
| 35 |
+
from chartgen.v11.song_signature import song_onsets
|
| 36 |
+
from tja_export import to_tja
|
| 37 |
+
|
| 38 |
+
ROOT = Path(__file__).resolve().parent
|
| 39 |
+
MODEL_REPO = "JacobLinCool/internal-model-p"
|
| 40 |
+
MODEL_REVISION = "f7752e9a48baa7adf7bd43ba63eaadbc522219b9"
|
| 41 |
+
DEVICE = torch.device("cpu")
|
| 42 |
+
FLOORS = {"3": 57.0, "4": 32.0}
|
| 43 |
+
TIERS = {3: "Oni", 4: "Inner Oni"}
|
| 44 |
+
SYNTH_SONG_ID = 990000000
|
| 45 |
+
AUDIO_NAME = "audio.mp3"
|
| 46 |
+
MAX_SECONDS = 180
|
| 47 |
+
MIN_SECONDS = 8
|
| 48 |
+
COLOUR_WINDOW_NOTES = 360
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class AudioInputError(ValueError):
|
| 52 |
+
"""Input that the public demo cannot decode or use."""
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class EighthGate:
|
| 56 |
+
def __init__(self, path):
|
| 57 |
+
self.theta = json.loads(path.read_text(encoding="utf-8"))
|
| 58 |
+
|
| 59 |
+
def gate(self, tier, share):
|
| 60 |
+
return share >= self.theta[str(tier)]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@lru_cache(maxsize=1)
|
| 64 |
+
def load_models():
|
| 65 |
+
local = os.environ.get("MODEL_P_DIR")
|
| 66 |
+
|
| 67 |
+
def asset(name):
|
| 68 |
+
if local:
|
| 69 |
+
return Path(local) / name
|
| 70 |
+
return Path(hf_hub_download(MODEL_REPO, name, revision=MODEL_REVISION))
|
| 71 |
+
|
| 72 |
+
manifest = json.loads(asset("config.json").read_text(encoding="utf-8"))
|
| 73 |
+
models = {
|
| 74 |
+
"p": pmap.PMap(**manifest["p"]["config"]),
|
| 75 |
+
"r": RMap(**manifest["r"]["config"]),
|
| 76 |
+
"b9fix": B0(B0Config(**manifest["b9fix"]["config"])),
|
| 77 |
+
}
|
| 78 |
+
for name, model in models.items():
|
| 79 |
+
entry = manifest[name]
|
| 80 |
+
path = asset(entry["filename"])
|
| 81 |
+
with path.open("rb") as file:
|
| 82 |
+
digest = hashlib.file_digest(file, "sha256").hexdigest()
|
| 83 |
+
if digest != entry["sha256"]:
|
| 84 |
+
raise RuntimeError(f"Checkpoint hash mismatch for {name}.")
|
| 85 |
+
model.load_state_dict(load_file(path), strict=True)
|
| 86 |
+
model.eval()
|
| 87 |
+
return models
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def transcode(input_path, output_path):
|
| 91 |
+
# Share one exported, decoder-compatible audio file between both formats.
|
| 92 |
+
result = subprocess.run(
|
| 93 |
+
["ffmpeg", "-nostdin", "-v", "error", "-y", "-i", os.fspath(input_path),
|
| 94 |
+
"-map", "0:a:0", "-t", str(MAX_SECONDS + 1), "-c:a", "libmp3lame", "-q:a", "2",
|
| 95 |
+
"-ac", "2", "-ar", "44100", os.fspath(output_path)],
|
| 96 |
+
capture_output=True, timeout=45, check=False,
|
| 97 |
+
)
|
| 98 |
+
if result.returncode:
|
| 99 |
+
raise AudioInputError("Upload a readable file with an audio track.")
|
| 100 |
+
samples = decode_audio(os.fspath(output_path))
|
| 101 |
+
if not MIN_SECONDS * SAMPLE_RATE <= len(samples) <= MAX_SECONDS * SAMPLE_RATE:
|
| 102 |
+
raise AudioInputError(f"Audio must be {MIN_SECONDS} to {MAX_SECONDS} seconds long.")
|
| 103 |
+
if not np.isfinite(samples).all() or np.sqrt(np.mean(samples ** 2)) < 1e-4:
|
| 104 |
+
raise AudioInputError("The uploaded audio is silent.")
|
| 105 |
+
return samples
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def make_sections(b9, mel, bpm, downbeat_ms):
|
| 109 |
+
start_ms, end_ms = music_span(mel)
|
| 110 |
+
if end_ms - start_ms < 2500:
|
| 111 |
+
raise AudioInputError("The file needs at least 2.5 seconds of active audio.")
|
| 112 |
+
if bpm is None:
|
| 113 |
+
beat, downbeat, _ = frame_activations(b9, mel, DEVICE)
|
| 114 |
+
sections = decode_timing_auto(beat, downbeat, start_ms, end_ms)
|
| 115 |
+
else:
|
| 116 |
+
if not math.isfinite(bpm) or not 60 <= bpm <= 320:
|
| 117 |
+
raise AudioInputError("Set BPM between 60 and 320.")
|
| 118 |
+
if not math.isfinite(downbeat_ms) or not 0 <= downbeat_ms < len(mel) * 10:
|
| 119 |
+
raise AudioInputError("The first downbeat must fall inside the audio.")
|
| 120 |
+
sections = np.array([[downbeat_ms, 60000 / bpm, 4, 0, 0]], dtype=np.float64)
|
| 121 |
+
|
| 122 |
+
# Extend the first timing section by whole measures to cover any pickup.
|
| 123 |
+
sections = np.asarray(sections, dtype=np.float64).copy()
|
| 124 |
+
bar_ms = sections[0, 1] * sections[0, 2]
|
| 125 |
+
lead_bars = max(0, math.ceil(sections[0, 0] / bar_ms))
|
| 126 |
+
sections[0, 0] -= lead_bars * bar_ms
|
| 127 |
+
sections[0, 3] -= lead_bars * sections[0, 2]
|
| 128 |
+
return sections, max(0.0, start_ms - 2000.0), end_ms
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
@torch.inference_mode()
|
| 132 |
+
def colour_notes(b9, mel, sections, tier, times, seed):
|
| 133 |
+
"""Run the original forced-position note decoder and retain P's timing lattice."""
|
| 134 |
+
grid = np.rint(beats_tol(sections, times) * GRID).astype(np.int64)
|
| 135 |
+
if np.any(np.diff(grid) <= 0):
|
| 136 |
+
raise RuntimeError("Model P emitted non-increasing grid positions.")
|
| 137 |
+
song = {"mel": mel}
|
| 138 |
+
template = _dummy_chart(sections, tier)
|
| 139 |
+
target = pseudo_chart(grid, sections, tier)
|
| 140 |
+
bars = measure_at(sections, grid / GRID)
|
| 141 |
+
first_bar = int(bars[0])
|
| 142 |
+
plan = bar_plan(grid, np.zeros(len(grid), np.int64), first_bar, sections, None, int(bars[-1]) - first_bar + 1)
|
| 143 |
+
type_bias = np.zeros(7, np.float32)
|
| 144 |
+
type_bias[4:] = -1e9
|
| 145 |
+
colours, speeds = [], []
|
| 146 |
+
breaks = set((np.flatnonzero(np.diff(grid // GRID) > MAX_AHEAD) + 1).tolist())
|
| 147 |
+
start = 0
|
| 148 |
+
while start < len(grid):
|
| 149 |
+
frame = max(0, int(times[start] // 10))
|
| 150 |
+
ex = make_example(song, template, frame)
|
| 151 |
+
stop = min(start + COLOUR_WINDOW_NOTES, np.searchsorted(times, (frame + WINDOW) * 10))
|
| 152 |
+
for boundary in range(start + 1, stop):
|
| 153 |
+
if boundary in breaks:
|
| 154 |
+
stop = boundary
|
| 155 |
+
break
|
| 156 |
+
stop = min(stop, np.searchsorted(grid, ex.start_grid + len(ex.grid_time) - 1))
|
| 157 |
+
offsets = grid[start:stop] - ex.start_grid
|
| 158 |
+
if not len(offsets) or offsets[0] <= 0:
|
| 159 |
+
raise RuntimeError("A Model P note fell outside its colour decoder window.")
|
| 160 |
+
hint = make_example(song, target, frame)
|
| 161 |
+
ex = replace(ex, plan_rho=hint.plan_rho, plan_r=hint.plan_r, plan_gap=hint.plan_gap)
|
| 162 |
+
window, _, _ = window_plan(plan, first_bar, sections, frame)
|
| 163 |
+
allowed = np.zeros(len(ex.grid_time) + 1, bool)
|
| 164 |
+
allowed[offsets] = True
|
| 165 |
+
torch.manual_seed(seed + frame)
|
| 166 |
+
pred = generate(
|
| 167 |
+
b9, [ex], DEVICE, temperature=0.9, plan_source="oracle", bar_plan=window[None],
|
| 168 |
+
allowed=[allowed], required=[offsets], continue_until=[int(offsets[-1])], type_bias=type_bias,
|
| 169 |
+
)[0]
|
| 170 |
+
if not np.array_equal(pred["grid_offset"], offsets) or np.any(pred["type"] > 3):
|
| 171 |
+
raise RuntimeError("The colour decoder changed Model P's hit positions.")
|
| 172 |
+
colours.append(pred["type"])
|
| 173 |
+
speeds.append(pred["sv"])
|
| 174 |
+
start = stop
|
| 175 |
+
return np.concatenate(colours), np.concatenate(speeds)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
@torch.inference_mode()
|
| 179 |
+
def infer(samples, seed=0, bpm=None, downbeat_ms=0.0):
|
| 180 |
+
models = load_models()
|
| 181 |
+
mel = log_mel(samples).astype(np.float32)
|
| 182 |
+
b9 = models["b9fix"]
|
| 183 |
+
sections, start, end = make_sections(b9, mel, bpm, downbeat_ms)
|
| 184 |
+
table = beat_table(sections, len(mel))
|
| 185 |
+
group = Group(SYNTH_SONG_ID, "upload", "new", 3, table, sections, song_index=0)
|
| 186 |
+
song = {"mel": mel, "beatmapset_id": SYNTH_SONG_ID}
|
| 187 |
+
corpus = SimpleNamespace(groups=[group], songs=[song], ons=[song_onsets(mel)])
|
| 188 |
+
lg = predict_group(models["r"], corpus, 0, DEVICE)
|
| 189 |
+
calib = load_calib(ROOT / "assets/r-calibration.json")
|
| 190 |
+
gate = EighthGate(ROOT / "assets/eighth-gate.json")
|
| 191 |
+
result = pmap.gen_song(
|
| 192 |
+
models["p"], corpus, 0, song, apply_calib(lg, calib), gate, FLOORS,
|
| 193 |
+
seed, 1, DEVICE, span=(start, end),
|
| 194 |
+
)[0]
|
| 195 |
+
_, _, kiai_prob = frame_activations(b9, mel, DEVICE, sections, 4)
|
| 196 |
+
candidates = [c for c in result["charts"].values() if len(c["time"]) >= 2]
|
| 197 |
+
if not candidates or any(not len(c["time"]) for c in result["charts"].values()):
|
| 198 |
+
raise AudioInputError("The model found too few notes. Try a more rhythmic track or set its BPM and downbeat.")
|
| 199 |
+
kiai = shared_kiai(kiai_prob, sections, result["charts"])
|
| 200 |
+
charts = {}
|
| 201 |
+
for tier, chart in result["charts"].items():
|
| 202 |
+
hits = chart["time"]
|
| 203 |
+
types, sv = colour_notes(b9, mel, sections, tier, hits, seed + 1000 * tier)
|
| 204 |
+
rolls, lengths = hold_rolls(result["p"][tier]["tok"], table, pmap.tables()["HOLD"])
|
| 205 |
+
roll_section = np.searchsorted(sections[:, 0], rolls, side="right") - 1
|
| 206 |
+
next_hit = np.searchsorted(hits, rolls, side="right")
|
| 207 |
+
hit_end = np.r_[hits, len(samples) * 1000 / SAMPLE_RATE][next_hit]
|
| 208 |
+
beat_ms = sections[roll_section, 1]
|
| 209 |
+
lengths = np.minimum(lengths, (hit_end - rolls) / beat_ms - 0.25)
|
| 210 |
+
valid = (lengths >= 0.25) & (rolls < len(samples) * 1000 / SAMPLE_RATE)
|
| 211 |
+
times = np.concatenate([hits, rolls[valid]])
|
| 212 |
+
order = np.argsort(times, kind="stable")
|
| 213 |
+
charts[tier] = GeneratedChart(
|
| 214 |
+
sections=sections, kiai=kiai, time=times[order],
|
| 215 |
+
type=np.r_[types, np.full(int(valid.sum()), 4)][order],
|
| 216 |
+
length_beats=np.r_[np.zeros(len(hits)), lengths[valid]][order],
|
| 217 |
+
sv=np.r_[sv, np.ones(int(valid.sum()))][order], tier=tier,
|
| 218 |
+
)
|
| 219 |
+
return charts
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def clean_field(value):
|
| 223 |
+
return " ".join(str(value).splitlines()).replace("//", "/").strip()[:120]
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def generate_package(input_path, output, *, title, artist="", seed=0, bpm=None, downbeat_ms=0.0):
|
| 227 |
+
if isinstance(seed, bool) or seed != int(seed) or not 0 <= seed < 2 ** 31:
|
| 228 |
+
raise AudioInputError("Seed must be an integer from 0 to 2147483647.")
|
| 229 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 230 |
+
audio = output / AUDIO_NAME
|
| 231 |
+
samples = transcode(input_path, audio)
|
| 232 |
+
charts = infer(samples, int(seed), bpm, downbeat_ms)
|
| 233 |
+
title = clean_field(title) or "Generated taiko chart"
|
| 234 |
+
artist = clean_field(artist)
|
| 235 |
+
osz = output / "Model P.osz"
|
| 236 |
+
with zipfile.ZipFile(osz, "w", zipfile.ZIP_DEFLATED) as package:
|
| 237 |
+
package.write(audio, AUDIO_NAME)
|
| 238 |
+
for tier, chart in charts.items():
|
| 239 |
+
package.writestr(f"{TIERS[tier]}.osu", to_osu(chart, AUDIO_NAME, title, artist))
|
| 240 |
+
tja = output / "Model P TJA.zip"
|
| 241 |
+
with zipfile.ZipFile(tja, "w", zipfile.ZIP_DEFLATED) as package:
|
| 242 |
+
package.write(audio, AUDIO_NAME)
|
| 243 |
+
package.writestr("Model P.tja", to_tja(charts, AUDIO_NAME, title, artist))
|
| 244 |
+
audio.unlink()
|
| 245 |
+
return osz, tja, {TIERS[tier]: int((chart.type <= 3).sum()) for tier, chart in sorted(charts.items())}
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def main():
|
| 249 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 250 |
+
parser.add_argument("audio", type=Path)
|
| 251 |
+
parser.add_argument("--output", type=Path, default=Path("export"))
|
| 252 |
+
parser.add_argument("--title")
|
| 253 |
+
parser.add_argument("--artist", default="")
|
| 254 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 255 |
+
parser.add_argument("--bpm", type=float)
|
| 256 |
+
parser.add_argument("--downbeat-ms", type=float, default=0)
|
| 257 |
+
args = parser.parse_args()
|
| 258 |
+
torch.set_num_threads(min(4, os.cpu_count() or 1))
|
| 259 |
+
*paths, counts = generate_package(
|
| 260 |
+
args.audio, args.output, title=args.title or args.audio.stem, artist=args.artist,
|
| 261 |
+
seed=args.seed, bpm=args.bpm, downbeat_ms=args.downbeat_ms,
|
| 262 |
+
)
|
| 263 |
+
for path in paths:
|
| 264 |
+
print(path)
|
| 265 |
+
print(json.dumps(counts))
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
if __name__ == "__main__":
|
| 269 |
+
main()
|
reports/figs/v11_s0_vocab.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"vocab_pooled":{"min_count":3,"masks":[1,4097,266241,266305,4096,4161,262145,65793,65537,262209,4160,266240,266304,266513,64,1118209,65,4369,1118481,262208,256,1118273,266313,266817,65536,299073,262144,1052673,257,1052929,266825,36873,4353,2363457,69889,2363393,2396225,65809,1118465,299009,1048577,2363465,4169,4105,2396745,36865,1118208,65792,69905,9,1048833,299081,1114369,262657,32769,2396161,1114113,266249,299585,299593,4352,273,2363977,2396233,1052945,2359297,4673,17,1052928,69633,4681,36929,1052672,2396737,1118272,279617,1048832,2363969,36864,69649,32768,1048576,266816,2097152,512,2049,4113,2363456,4,8193,299072,2359361,2097153,266753,2101249,73,266497,1118281,16,1114385,32832,8192,1114112,1024,2101761,8,4112,4460817,20485,5,528385,513,266308,1052737,1052688,2048,69697,2363665,4609,262217,33,1118217,1118793,32833,262401,1118464,262153,295489,2359296,20481,2396160,4104,32,299008,2396433,585,65552,4672,2101248,69632,4101,262417,16384,2363392,4225,1048592,67585,2101313,1118276,1025,299281,4460609,4164,524289,262721,266257,3,528513,2396224,2101256,2097160,266245,2,1118225,128,17473,267585,1049601,4460545,65553,131073,2359305,279616,12291,65601,2097664,577,16385,266256,348225,9217,8388608,69888,262160,1118785,2363905,2359369,10241,576,262152,1052689,85,328965,1114368,20545,2363401,4198401,270881,1048641,65600,348245,2445377,16400,131072,135169,33793,1314885,8448,2097216,33025,4456449,65797,36928,262161,4194304,4194305,266248,1052736,1114129,5592405,266307,266761,4260097,8388609,4100,65545,2097168,2101521,2392065,1118545,2363649,4099,2099200,2359360,4129,8449,299584,524417,2097665,2396757,8392704,12289,557057,20480,32776,266309,294913,299017,2130440,4368,33865,66576,282625,1114177,2134081,68,1052745,17472,32841,262400,266496,270338,327681,1082369,21,520,1088,4608,16897,33281,76033,266325,1118480,2101257,5461,262148,2396417,129,299093,1052944,1053249,1118485,1119489,4456721,2101312,5247233,5591041,69648,86081,279625,299529,1053257,1331265,1380625,2363913,4260880,4460608,4224,8194,12288,12353,16448,32897,262656,559169,2134089,2359809,2396232,2396245,65540,131200,264193,266433,294912,327937,1134849,1310721,1331521,2376777,2392064,2396169,2396736,5246977,272,4168,16388,37377,69909,266243,299265,328961,524288,790593,1052676,1386753,2097425,2099201,2130433,2928641,545,4181,135168,266369,267605,1118549,2376705,2445313,584,4098,33288,131104,131585,263169,266837,282629,348161,348233,528449,1331273,2129921,2232321,2232449,2359873,2393089,4456465,5541953,5541961,9216,69904,262729,266242,279620,557056,798915,1048849,1119505,2445909,4460617,4473924,8421505,4355,65808,67584,279552,559170,1048640,1065217,1315141,2097169,2101264,2404939,34,4165,5121,36937,86273,262689,262720,263172,266512,278529,299605,524320,528512,1048584,1118212,1118213,1118224,1310789,1315137,1380609,2097185,2097217,2134017,4198465,4456513,5509705,8390656,8200,20801,32800,37449,66049,66817,67841,70209,131586,264200,267593,274499,348745,524353,524802,528384,559105,790529,798721,1069057,1114176,1114384,1118293,1118788,1311041,1331205,2376772,2392577,4194320,4457537,4461121,5509121,5509185,5510465,5542465,4232,5441,16449,20753,37137,37461,65541,65796,262212,262664,266312,274497,528641,798785,1048705,1314817,1315089,2129920,2359881,2363477,2363968,4198400,4210752,4461129,5242881,8654913,136,261,514,4107,4117,8257,9281,16416,20805,69696,70208,131074,262273,266561,282689,665730,790595,1057281,1061121,1118468,1134865,1310725,2097408,2101505,2359872,2376769,2392321,2394113,4473920,4493385,5509193,5509205,5510473,8388736,8392769,321,2064,4128,16644,37441,65544,70913,131584,262147,262176,262272,266273,299013,299075,299076,299077,307275,332097,559168,1048580,1049089,1053013,1090051,1118216,1118469,1331525,2097280,2097672,2101265,2101321,2134088,2134593,2232448,2363460,2363464,2392585,2396673,2445897,2920513,4194816,4456448,5246976,5312785,11451115,105,260,1345,2065,2112,8196,8256,12352,17409,17476,17481,37001,65801,66121,66561,69893,86017,131136,262177,262229,262274,262465,262665,263233,266272,266277,266824,279553,295433,295497,332873,348259,348737,524296,524809,561289,665617,1048593,1056769,1064961,1124609,1376513,2097409,2101377,2101825,2105408,2105409,2131969,2166785,2359569,2363713,2364745,2392641,2396165,2396265,2396681,2445385,2523137,2887873,4198404,4456512,4458497,4472833,5542473,5574929,8389120,8392705,8392706,8396801,1092,1281,4680,8737,16640,32770,34880,37385,87381,135304,262149,262658,266244,282945,524416,524800,528416,557089,559104,786433,798913,1048848,1114128,1314881,1316169,1331201,2097161,2101281,2130505,2162688,2364737,2392129,2396168,2396228,2397505,2445585,3062475,4194368,4195328,4259840,4473921,5247249,5542161,8388610,8388617,9180489,521,1028,1029,1032,1040,2052,2080,2113,2176,4617,4811,5120,10240,17480,32784,33280,33289,33345,33353,37384,37440,65813,66056,66577,69641,73729,133121,135296,262213,263168,263236,266315,266321,266376,266955,267584,270849,271361,282693,327685,332033,332049,524352,524418,524545,524801,532481,557065,559177,1052680,1052801,1053953,1054017,1085441,1114121,1118274,1311045,1331269,2097225,2097281,2099209,2101250,2101280,2101520,2130465,2131017,2162752,2232833,2359304,2361345,2363426,2363459,2376704,2380101,2396229,2396480,2397513,2445889,2536009,4194308,4194369,4196352,4210689,4259841,4260881,4460549,4472832,4472896,4493585,5242880,5247041,5509697,5541889,5591625,8388642,8392712,8396832,8421377,8423681,8454272,8454400,8454401,8655104,8912897,8982801,9054225,11309641,72,265,1041,1056,2304,4421,4616,5376,5449,10497,16452,16641,20737,32772,33041,34881,34882,36936,37376,41217,65665,65795,66821,69705,87360,131137,131617,135233,262660,264208,266258,266320,266565,266785,266820,267337,274433,274435,279568,282897,295425,299329,299521,299531,299588,300353,300373,307713,331841,332363,348757,349504,524544,524808,528657,528897,532610,557184,561665,660033,790801,1049604,1050625,1050626,1065216,1065220,1116161,1118337,1118784,1119233,1130768,1134869,1380353,1396993,2097184,2099217,2099266,2101333,2105344,2113537,2129984,2134016,2134080,2162689,2164737,2232593,2263045,2359817,2363397,2363408,2363976,2367745,2368073,2396873,2527233,2887681,2888265,2901313,2920529,4456521,4457476,4460612,4460801,4473857,4521985,5247232,5505025,5509377,5538313,5574913,5574993,5591125,8390657,8406018,8688201,9453825,10911809],"counts":[2478411,1959693,685871,559222,546145,415071,125370,55995,49126,48675,40246,39247,19558,15731,14267,13257,12043,11885,11789,9634,9097,8980,6432,5689,5660,4750,4667,4573,4291,4158,4018,3906,3217,3158,2879,2727,2439,2289,1978,1757,1736,1670,1620,1602,1579,1532,1511,1508,1419,1408,1158,1061,1050,1033,917,892,888,882,823,779,654,610,608,592,542,528,526,525,512,501,490,425,422,417,397,395,394,385,380,368,345,345,336,329,328,314,311,301,297,290,289,285,284,281,278,268,267,264,260,246,234,221,221,214,210,207,206,202,194,190,190,187,185,168,158,156,154,151,148,145,140,140,139,138,138,134,131,130,128,126,124,123,121,120,118,114,113,110,110,109,107,106,105,103,101,100,99,99,98,97,94,94,91,89,87,86,84,84,79,77,75,74,72,72,70,68,67,67,67,64,64,64,63,62,62,61,60,60,60,60,59,58,54,54,54,54,52,51,50,50,49,48,48,48,47,46,45,44,44,42,42,42,41,41,41,40,40,39,39,38,38,37,36,36,36,36,35,35,35,35,34,34,34,34,33,33,33,33,33,32,32,31,31,30,29,29,29,29,29,29,29,28,28,27,27,27,27,27,27,26,26,26,26,26,26,25,25,24,24,24,24,24,24,24,23,23,23,23,23,23,23,23,23,23,22,22,22,21,21,21,21,21,21,21,20,20,20,19,19,19,19,19,19,19,19,19,19,18,18,18,18,18,18,18,18,18,18,18,18,17,17,17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,15,15,15,15,15,15,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3]}}
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 2 |
+
torch==2.14.1+cpu; platform_system == "Linux"
|
| 3 |
+
torch==2.14.1; platform_system != "Linux"
|
| 4 |
+
numpy==2.5.3
|
| 5 |
+
safetensors==0.8.0
|
| 6 |
+
huggingface_hub==2.2.0
|
| 7 |
+
gradio==6.30.0
|
tja_export.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Write TJA on Model P's 48-slot beat lattice, including tempo changes."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
from functools import reduce
|
| 6 |
+
import math
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
from chartgen.dataset import GRID
|
| 11 |
+
|
| 12 |
+
COURSES = {3: "Oni", 4: "Edit"}
|
| 13 |
+
NOTE_CODES = {0: "1", 1: "2", 2: "3", 3: "4", 4: "5"}
|
| 14 |
+
SLOT_EPSILON = 1e-5
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def section_slots(sections, index, latest_ms):
|
| 18 |
+
start_ms, beat_ms, meter = sections[index, :3]
|
| 19 |
+
if index + 1 < len(sections):
|
| 20 |
+
end_ms = sections[index + 1, 0]
|
| 21 |
+
return max(1, math.ceil((end_ms - start_ms) * GRID / beat_ms - SLOT_EPSILON))
|
| 22 |
+
measure_slots = int(meter) * GRID
|
| 23 |
+
return max(1, math.ceil((latest_ms - start_ms + 0.1) * GRID / beat_ms / measure_slots)) * measure_slots
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def position(sections, time_ms, latest_ms):
|
| 27 |
+
index = int(np.clip(np.searchsorted(sections[:, 0], time_ms + 1e-3, side="right") - 1, 0, len(sections) - 1))
|
| 28 |
+
start_ms, beat_ms = sections[index, :2]
|
| 29 |
+
n_slots = section_slots(sections, index, latest_ms)
|
| 30 |
+
slot = int(np.clip(round((time_ms - start_ms) * GRID / beat_ms), 0, n_slots - 1))
|
| 31 |
+
return index, slot
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def measures(sections, notes, commands, latest_ms):
|
| 35 |
+
lines = []
|
| 36 |
+
previous_bpm = 60000 / sections[0, 1]
|
| 37 |
+
previous_measure = (4, 4)
|
| 38 |
+
lateness_ms = 0.0
|
| 39 |
+
current_scroll = 1.0
|
| 40 |
+
for index, (start_ms, beat_ms, meter, _, omit) in enumerate(sections):
|
| 41 |
+
if index and abs(lateness_ms) > 1e-6:
|
| 42 |
+
lines.append(f"#DELAY {-lateness_ms / 1000:.9f}")
|
| 43 |
+
bpm = 60000 / beat_ms
|
| 44 |
+
if abs(bpm - previous_bpm) > 1e-9:
|
| 45 |
+
lines.append(f"#BPMCHANGE {bpm:.9f}")
|
| 46 |
+
previous_bpm = bpm
|
| 47 |
+
n_slots = section_slots(sections, index, latest_ms)
|
| 48 |
+
regular = int(meter) * GRID
|
| 49 |
+
if omit:
|
| 50 |
+
lines.append("#BARLINEOFF")
|
| 51 |
+
for first in range(0, n_slots, regular):
|
| 52 |
+
stop = min(first + regular, n_slots)
|
| 53 |
+
count = stop - first
|
| 54 |
+
measure = (int(meter), 4)
|
| 55 |
+
if count != regular:
|
| 56 |
+
gcd = math.gcd(count, GRID * 4)
|
| 57 |
+
measure = count // gcd, GRID * 4 // gcd
|
| 58 |
+
if measure != previous_measure:
|
| 59 |
+
lines.append(f"#MEASURE {measure[0]}/{measure[1]}")
|
| 60 |
+
previous_measure = measure
|
| 61 |
+
occupied = (k for k in set(notes[index]) | set(commands[index]) if first <= k < stop)
|
| 62 |
+
step = reduce(math.gcd, (k - first for k in occupied), count)
|
| 63 |
+
row = ""
|
| 64 |
+
for k in range(first, stop, step):
|
| 65 |
+
event = notes[index].get(k)
|
| 66 |
+
controls = list(commands[index].get(k, []))
|
| 67 |
+
if event and abs(event[1] - current_scroll) > 1e-5:
|
| 68 |
+
current_scroll = event[1]
|
| 69 |
+
controls.append(f"#SCROLL {current_scroll:.6f}")
|
| 70 |
+
if controls:
|
| 71 |
+
if row:
|
| 72 |
+
lines.append(row)
|
| 73 |
+
row = ""
|
| 74 |
+
lines.extend(controls)
|
| 75 |
+
row += event[0] if event else "0"
|
| 76 |
+
lines.append(row + ",")
|
| 77 |
+
if omit:
|
| 78 |
+
lines.append("#BARLINEON")
|
| 79 |
+
if index + 1 < len(sections):
|
| 80 |
+
lateness_ms = start_ms + n_slots * beat_ms / GRID - sections[index + 1, 0]
|
| 81 |
+
return lines
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def write_course(chart):
|
| 85 |
+
sections = chart.sections
|
| 86 |
+
# Track a chart's last possible roll end when sizing its final measure.
|
| 87 |
+
active_sections = np.searchsorted(sections[:, 0], chart.time + 1e-3, side="right") - 1
|
| 88 |
+
tails = chart.time + chart.length_beats * sections[active_sections, 1]
|
| 89 |
+
latest_ms = max(float(tails.max()), max((b for _, b in chart.kiai), default=0.0))
|
| 90 |
+
notes = defaultdict(dict)
|
| 91 |
+
controls = defaultdict(lambda: defaultdict(list))
|
| 92 |
+
for start, stop in chart.kiai:
|
| 93 |
+
a, x = position(sections, start, latest_ms)
|
| 94 |
+
b, y = position(sections, stop, latest_ms)
|
| 95 |
+
if (a, x) < (b, y):
|
| 96 |
+
controls[a][x].append("#GOGOSTART")
|
| 97 |
+
controls[b][y].append("#GOGOEND")
|
| 98 |
+
for t, ty, sv in zip(chart.time, chart.type, chart.sv):
|
| 99 |
+
section, slot = position(sections, t, latest_ms)
|
| 100 |
+
if slot in notes[section]:
|
| 101 |
+
raise RuntimeError("Two generated notes occupy the same TJA slot.")
|
| 102 |
+
notes[section][slot] = (NOTE_CODES[int(ty)], float(sv))
|
| 103 |
+
for i in np.flatnonzero(chart.type == 4):
|
| 104 |
+
start = position(sections, chart.time[i], latest_ms)
|
| 105 |
+
end = position(sections, tails[i], latest_ms)
|
| 106 |
+
section, slot = end
|
| 107 |
+
if start < end and slot not in notes[section]:
|
| 108 |
+
notes[section][slot] = ("8", 1.0)
|
| 109 |
+
else:
|
| 110 |
+
# A roll rounded to the same slot as its end cannot be encoded.
|
| 111 |
+
del notes[start[0]][start[1]]
|
| 112 |
+
return measures(sections, notes, controls, latest_ms)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def to_tja(charts, audio_name, title, artist):
|
| 116 |
+
sections = charts[3].sections
|
| 117 |
+
lines = [
|
| 118 |
+
f"TITLE:{title}", f"ARTIST:{artist}", f"WAVE:{audio_name}",
|
| 119 |
+
f"BPM:{60000 / sections[0, 1]:.9f}", f"OFFSET:{-sections[0, 0] / 1000:.9f}", "",
|
| 120 |
+
]
|
| 121 |
+
for tier in sorted(charts):
|
| 122 |
+
lines.extend([f"COURSE:{COURSES[tier]}", "LEVEL:10", "#START", *write_course(charts[tier]), "#END", ""])
|
| 123 |
+
return "\n".join(lines)
|