goldhub commited on
Commit
826fa00
·
verified ·
1 Parent(s): e77664f

Night 10.11.2026: Mothersuperior/YuE2-hum-to-song, unchanged (CC BY-NC 4.0), at the Studio's own path; its lines in MANIFEST.tsv, SHA256SUMS, THIRD_PARTY_NOTICES.md and the card

Browse files
MANIFEST.tsv CHANGED
@@ -321,6 +321,18 @@ checkpoints/YuE2-Vae/licenses/stable-audio-tools-MIT.txt 1069 a1fac33b7bcd791b74
321
  checkpoints/YuE2-Vae/model.safetensors 530512720 807ce9d5149fa27c5ad3e6582058469852e908f6c5acc8c8aa338e7ab7751346 41ec0766770852a708e52947a0b465408d8ceac50a8fdcf340f9b39e86a45bd6 m-a-p/YuE2-Vae@152733a1 CC BY-NC 4.0
322
  checkpoints/YuE2-Vae/modeling_vae.py 25265 b6578ff461e6be9fd079ca5ddf12893940f3b3338ff3435fceae89c466486f5a - m-a-p/YuE2-Vae@152733a1 CC BY-NC 4.0
323
  checkpoints/YuE2-Vae/weights_manifest.json 178 017d64a4d288217a43fcac3866a0e1d55f796fa891d4dfb6de0bd170ab750026 - m-a-p/YuE2-Vae@152733a1 CC BY-NC 4.0
 
 
 
 
 
 
 
 
 
 
 
 
324
  checkpoints/comfy/checkpoints/yue2_3b_bf16.safetensors 7799983228 33765adbf9813c9a50318218760b2fd819a319862460a04884607581961c6fee 6e4bd30a36d02c7d60820061e80a770a006227ade06308970863098268e392c9 Comfy-Org/YuE2 (m-a-p/YuE2-3B packed whole for ComfyUI) CC BY-NC 4.0
325
  checkpoints/comfy/checkpoints/yue2_3b_int8_convrot.safetensors 3960938800 96fe199377309001ed8cd26a944baeee8cc31a20ba7c36d1d3c0a7e1f4149db6 f0960163c99b8bc27bf7f35985a9c914353e1e3dd842f03c2d88dc1f6faeaf15 Comfy-Org/YuE2 (m-a-p/YuE2-3B packed whole for ComfyUI, int8) CC BY-NC 4.0
326
  checkpoints/yue2-mothersuperior-realaudio-tokenizer-v4/README.md 12028 05d63d2479f5a65956505b0dedfa3cc39f473f73bcd7d1dc55dd4a12a74c8ee2 - Mothersuperior/yue2-mothersuperior-realaudio-tokenizer-v4 (its card) CC BY-NC 4.0
 
321
  checkpoints/YuE2-Vae/model.safetensors 530512720 807ce9d5149fa27c5ad3e6582058469852e908f6c5acc8c8aa338e7ab7751346 41ec0766770852a708e52947a0b465408d8ceac50a8fdcf340f9b39e86a45bd6 m-a-p/YuE2-Vae@152733a1 CC BY-NC 4.0
322
  checkpoints/YuE2-Vae/modeling_vae.py 25265 b6578ff461e6be9fd079ca5ddf12893940f3b3338ff3435fceae89c466486f5a - m-a-p/YuE2-Vae@152733a1 CC BY-NC 4.0
323
  checkpoints/YuE2-Vae/weights_manifest.json 178 017d64a4d288217a43fcac3866a0e1d55f796fa891d4dfb6de0bd170ab750026 - m-a-p/YuE2-Vae@152733a1 CC BY-NC 4.0
324
+ checkpoints/YuE2-hum-to-song/README.md 9808 38f387740590f9f833fd302d18d8cebb0cccb52cf6a81705da59e4bffc624b58 - Mothersuperior/YuE2-hum-to-song@cd323af5 CC BY-NC 4.0
325
+ checkpoints/YuE2-hum-to-song/hum_adapter_v1.pt 282191689 8f1e60dbd8910750e03adf4a4f7a8b0aba0866aa4a686338a32e7b3cedfd74d9 - Mothersuperior/YuE2-hum-to-song@cd323af5 CC BY-NC 4.0
326
+ checkpoints/YuE2-hum-to-song/hum_adapter_v1.safetensors 282152712 d8bc53e3d386e617c40a2e9563cef20d1e48faaab2240a4051d68c21373c585c 20377ccc26e3af6a78c1f6eaf7b67099a2ccf88f947d3ed79e548030d119568b Mothersuperior/YuE2-hum-to-song@cd323af5 CC BY-NC 4.0
327
+ checkpoints/YuE2-hum-to-song/hum_adapter_v1_combined.safetensors 421613360 eeaf490b7045bb1215b3255f826dca551da8eb99d3d8e90311ce095e43b20b12 f7dc9ece3ef16abf52d897180a6dd92137df742cf56a41479c4935b0618be12c Mothersuperior/YuE2-hum-to-song@cd323af5 CC BY-NC 4.0
328
+ checkpoints/YuE2-hum-to-song/humsong_yue2_adapter_v1_comfy.safetensors 322511768 215c957c1d33e411cf791891862ad837e3ea0e747717dd1e988de17f7adf79a2 4967d676c0611ff71326c0582411075c96fb635ed07fdc015523a81c51955699 Mothersuperior/YuE2-hum-to-song@cd323af5 CC BY-NC 4.0
329
+ checkpoints/YuE2-hum-to-song/minted_regularizer_pack_v2.pt 296098847 587631eec5946f9f87d4b422abcda7e35dee43299efb7b7d2fcba4cd8752c475 - Mothersuperior/YuE2-hum-to-song@cd323af5 CC BY-NC 4.0
330
+ checkpoints/YuE2-hum-to-song/scripts/ckpt_io.py 1642 44d48fc08aa7c4a2e0f3120adbe4a05c5f6e1ec54442153bd8a7bc00a24a0e9a - Mothersuperior/YuE2-hum-to-song@cd323af5 CC BY-NC 4.0
331
+ checkpoints/YuE2-hum-to-song/scripts/hum_continue.py 3387 38827397349f5b1cb1505cebf81bcd48f935643e0b6bf7a71cdbd3b76353a3fe - Mothersuperior/YuE2-hum-to-song@cd323af5 CC BY-NC 4.0
332
+ checkpoints/YuE2-hum-to-song/scripts/hum_prep.py 8222 db5bf87d22bcbd233b7a62d13beb4b7293eb345c602c3644af5494fd0d1bd0b9 - Mothersuperior/YuE2-hum-to-song@cd323af5 CC BY-NC 4.0
333
+ checkpoints/YuE2-hum-to-song/scripts/infer_hum.py 5858 0e962e034f2516442f5f7b623d94ff375c51a5382da935c6355c81f4f8e84114 - Mothersuperior/YuE2-hum-to-song@cd323af5 CC BY-NC 4.0
334
+ checkpoints/YuE2-hum-to-song/scripts/to_comfy_lora.py 5204 b970443e2c7596f179ad8df932022b72166ada666edd49090f1737ca76631350 - Mothersuperior/YuE2-hum-to-song@cd323af5 CC BY-NC 4.0
335
+ checkpoints/YuE2-hum-to-song/scripts/train_hum.py 11173 de9bc30fe9cfe685f9a5e6477de475af51422461d0ffd651597dff5a484fedec - Mothersuperior/YuE2-hum-to-song@cd323af5 CC BY-NC 4.0
336
  checkpoints/comfy/checkpoints/yue2_3b_bf16.safetensors 7799983228 33765adbf9813c9a50318218760b2fd819a319862460a04884607581961c6fee 6e4bd30a36d02c7d60820061e80a770a006227ade06308970863098268e392c9 Comfy-Org/YuE2 (m-a-p/YuE2-3B packed whole for ComfyUI) CC BY-NC 4.0
337
  checkpoints/comfy/checkpoints/yue2_3b_int8_convrot.safetensors 3960938800 96fe199377309001ed8cd26a944baeee8cc31a20ba7c36d1d3c0a7e1f4149db6 f0960163c99b8bc27bf7f35985a9c914353e1e3dd842f03c2d88dc1f6faeaf15 Comfy-Org/YuE2 (m-a-p/YuE2-3B packed whole for ComfyUI, int8) CC BY-NC 4.0
338
  checkpoints/yue2-mothersuperior-realaudio-tokenizer-v4/README.md 12028 05d63d2479f5a65956505b0dedfa3cc39f473f73bcd7d1dc55dd4a12a74c8ee2 - Mothersuperior/yue2-mothersuperior-realaudio-tokenizer-v4 (its card) CC BY-NC 4.0
README.md CHANGED
@@ -72,6 +72,7 @@ hf download goldhub/Ruach_Studio_Models_v2 --local-dir . --include "checkpoints/
72
  | `checkpoints/MERT-v2-30s/` | 2.53 GB | MERT-v2 for 30-second clips, the listener's ear beside MERT-v2-FullSong, its `LICENSE` and notices beside it | [m-a-p/MERT-v2-30s](https://huggingface.co/m-a-p/MERT-v2-30s) | CC BY-NC 4.0 |
73
  | `checkpoints/SheetSage2/` | 0.23 GB | the transcriber as m-a-p publishes it (safetensors and its code), the source of `models/SheetSage2-*.gguf` | [m-a-p/SheetSage2](https://huggingface.co/m-a-p/SheetSage2) | CC BY-NC 4.0 |
74
  | `checkpoints/yue2-mothersuperior-realaudio-tokenizer-v4/` (the rest) | 2.70 GB | the realaudio tokenizer's other heads and NAR adapters (v4, v5, v8, v9; fp32, bf16, ComfyUI), beside the head the LoRA Trainer reads | [Mothersuperior/yue2-mothersuperior-realaudio-tokenizer-v4](https://huggingface.co/Mothersuperior/yue2-mothersuperior-realaudio-tokenizer-v4) | CC BY-NC 4.0 |
 
75
 
76
  **The fine-tunes and the Artist's adapters are here because their authors let them be shared.** On Civitai each of these allows sharing and selling the model itself and its merges; they are credited all the same. Many others the Artist paints with allow running and renting but not sharing the file (Outpaint, Turbo 4 steps, High Resolution, More Real, Cinematic Photography, Flux Pro Style, the FinalCut fine-tune of 2.1 and more): they stay with their authors on Civitai; taken from there into `artwork/loras/` or `artwork/Qwen-Image-2.1/checkpoints/`, the Artist offers them.
77
 
 
72
  | `checkpoints/MERT-v2-30s/` | 2.53 GB | MERT-v2 for 30-second clips, the listener's ear beside MERT-v2-FullSong, its `LICENSE` and notices beside it | [m-a-p/MERT-v2-30s](https://huggingface.co/m-a-p/MERT-v2-30s) | CC BY-NC 4.0 |
73
  | `checkpoints/SheetSage2/` | 0.23 GB | the transcriber as m-a-p publishes it (safetensors and its code), the source of `models/SheetSage2-*.gguf` | [m-a-p/SheetSage2](https://huggingface.co/m-a-p/SheetSage2) | CC BY-NC 4.0 |
74
  | `checkpoints/yue2-mothersuperior-realaudio-tokenizer-v4/` (the rest) | 2.70 GB | the realaudio tokenizer's other heads and NAR adapters (v4, v5, v8, v9; fp32, bf16, ComfyUI), beside the head the LoRA Trainer reads | [Mothersuperior/yue2-mothersuperior-realaudio-tokenizer-v4](https://huggingface.co/Mothersuperior/yue2-mothersuperior-realaudio-tokenizer-v4) | CC BY-NC 4.0 |
75
+ | `checkpoints/YuE2-hum-to-song/` | 1.60 GB | a hummed melody into a song: the prosody adapter and its regularizer pack, its card and scripts | [Mothersuperior/YuE2-hum-to-song](https://huggingface.co/Mothersuperior/YuE2-hum-to-song) | CC BY-NC 4.0 |
76
 
77
  **The fine-tunes and the Artist's adapters are here because their authors let them be shared.** On Civitai each of these allows sharing and selling the model itself and its merges; they are credited all the same. Many others the Artist paints with allow running and renting but not sharing the file (Outpaint, Turbo 4 steps, High Resolution, More Real, Cinematic Photography, Flux Pro Style, the FinalCut fine-tune of 2.1 and more): they stay with their authors on Civitai; taken from there into `artwork/loras/` or `artwork/Qwen-Image-2.1/checkpoints/`, the Artist offers them.
78
 
SHA256SUMS CHANGED
@@ -317,6 +317,18 @@ a1fac33b7bcd791b74fb33aeb439f825e7277e239fc119fb7d2ab6f084a0c101 checkpoints/Yu
317
  807ce9d5149fa27c5ad3e6582058469852e908f6c5acc8c8aa338e7ab7751346 checkpoints/YuE2-Vae/model.safetensors
318
  b6578ff461e6be9fd079ca5ddf12893940f3b3338ff3435fceae89c466486f5a checkpoints/YuE2-Vae/modeling_vae.py
319
  017d64a4d288217a43fcac3866a0e1d55f796fa891d4dfb6de0bd170ab750026 checkpoints/YuE2-Vae/weights_manifest.json
 
 
 
 
 
 
 
 
 
 
 
 
320
  33765adbf9813c9a50318218760b2fd819a319862460a04884607581961c6fee checkpoints/comfy/checkpoints/yue2_3b_bf16.safetensors
321
  96fe199377309001ed8cd26a944baeee8cc31a20ba7c36d1d3c0a7e1f4149db6 checkpoints/comfy/checkpoints/yue2_3b_int8_convrot.safetensors
322
  05d63d2479f5a65956505b0dedfa3cc39f473f73bcd7d1dc55dd4a12a74c8ee2 checkpoints/yue2-mothersuperior-realaudio-tokenizer-v4/README.md
 
317
  807ce9d5149fa27c5ad3e6582058469852e908f6c5acc8c8aa338e7ab7751346 checkpoints/YuE2-Vae/model.safetensors
318
  b6578ff461e6be9fd079ca5ddf12893940f3b3338ff3435fceae89c466486f5a checkpoints/YuE2-Vae/modeling_vae.py
319
  017d64a4d288217a43fcac3866a0e1d55f796fa891d4dfb6de0bd170ab750026 checkpoints/YuE2-Vae/weights_manifest.json
320
+ 38f387740590f9f833fd302d18d8cebb0cccb52cf6a81705da59e4bffc624b58 checkpoints/YuE2-hum-to-song/README.md
321
+ 8f1e60dbd8910750e03adf4a4f7a8b0aba0866aa4a686338a32e7b3cedfd74d9 checkpoints/YuE2-hum-to-song/hum_adapter_v1.pt
322
+ d8bc53e3d386e617c40a2e9563cef20d1e48faaab2240a4051d68c21373c585c checkpoints/YuE2-hum-to-song/hum_adapter_v1.safetensors
323
+ eeaf490b7045bb1215b3255f826dca551da8eb99d3d8e90311ce095e43b20b12 checkpoints/YuE2-hum-to-song/hum_adapter_v1_combined.safetensors
324
+ 215c957c1d33e411cf791891862ad837e3ea0e747717dd1e988de17f7adf79a2 checkpoints/YuE2-hum-to-song/humsong_yue2_adapter_v1_comfy.safetensors
325
+ 587631eec5946f9f87d4b422abcda7e35dee43299efb7b7d2fcba4cd8752c475 checkpoints/YuE2-hum-to-song/minted_regularizer_pack_v2.pt
326
+ 44d48fc08aa7c4a2e0f3120adbe4a05c5f6e1ec54442153bd8a7bc00a24a0e9a checkpoints/YuE2-hum-to-song/scripts/ckpt_io.py
327
+ 38827397349f5b1cb1505cebf81bcd48f935643e0b6bf7a71cdbd3b76353a3fe checkpoints/YuE2-hum-to-song/scripts/hum_continue.py
328
+ db5bf87d22bcbd233b7a62d13beb4b7293eb345c602c3644af5494fd0d1bd0b9 checkpoints/YuE2-hum-to-song/scripts/hum_prep.py
329
+ 0e962e034f2516442f5f7b623d94ff375c51a5382da935c6355c81f4f8e84114 checkpoints/YuE2-hum-to-song/scripts/infer_hum.py
330
+ b970443e2c7596f179ad8df932022b72166ada666edd49090f1737ca76631350 checkpoints/YuE2-hum-to-song/scripts/to_comfy_lora.py
331
+ de9bc30fe9cfe685f9a5e6477de475af51422461d0ffd651597dff5a484fedec checkpoints/YuE2-hum-to-song/scripts/train_hum.py
332
  33765adbf9813c9a50318218760b2fd819a319862460a04884607581961c6fee checkpoints/comfy/checkpoints/yue2_3b_bf16.safetensors
333
  96fe199377309001ed8cd26a944baeee8cc31a20ba7c36d1d3c0a7e1f4149db6 checkpoints/comfy/checkpoints/yue2_3b_int8_convrot.safetensors
334
  05d63d2479f5a65956505b0dedfa3cc39f473f73bcd7d1dc55dd4a12a74c8ee2 checkpoints/yue2-mothersuperior-realaudio-tokenizer-v4/README.md
THIRD_PARTY_NOTICES.md CHANGED
@@ -241,6 +241,18 @@ Licence: CC BY-NC 4.0
241
 
242
  - `models/YuE2-Vae-legacy-F32.gguf`
243
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  ## Mothersuperior/YuE2-instrumental-cot-full-loras (the Kit's library: Instrumental)
245
 
246
  Licence: CC BY-NC 4.0
 
241
 
242
  - `models/YuE2-Vae-legacy-F32.gguf`
243
 
244
+ ## Mothersuperior/YuE2-hum-to-song
245
+
246
+ Licence: CC BY-NC 4.0
247
+
248
+ - `checkpoints/YuE2-hum-to-song/README.md`
249
+ - `checkpoints/YuE2-hum-to-song/hum_adapter_v1.pt`
250
+ - `checkpoints/YuE2-hum-to-song/hum_adapter_v1.safetensors`
251
+ - `checkpoints/YuE2-hum-to-song/hum_adapter_v1_combined.safetensors`
252
+ - `checkpoints/YuE2-hum-to-song/humsong_yue2_adapter_v1_comfy.safetensors`
253
+ - `checkpoints/YuE2-hum-to-song/minted_regularizer_pack_v2.pt`
254
+ - `checkpoints/YuE2-hum-to-song/scripts/…`
255
+
256
  ## Mothersuperior/YuE2-instrumental-cot-full-loras (the Kit's library: Instrumental)
257
 
258
  Licence: CC BY-NC 4.0
checkpoints/YuE2-hum-to-song/README.md ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-nc-4.0
3
+ base_model:
4
+ - m-a-p/YuE2-3B
5
+ tags:
6
+ - audio
7
+ - music
8
+ - yue2
9
+ - lora
10
+ - hum-to-song
11
+ ---
12
+ # Hum-to-Song on YuE2: how it works
13
+
14
+ Hum a melody for 10 to 30 seconds, add a style line and lyrics, get a finished song that keeps your melody, builds a structure around it, and continues long after your hum stops. This document describes the two mechanisms behind it, how they were trained, and how to run them with the scripts here or inside ComfyUI.
15
+
16
+ ## The problem, and why it splits in two
17
+
18
+ YuE2 generates a song in two stages. The **AR planner** first writes a symbolic **ABC score** (its chain-of-thought, `cot="melody"` or `"full"`), then writes 25 Hz **semantic tokens** conditioned on that score. The **NAR decoder** then turns tokens into VAE latents by flow matching, and the VAE decodes 48 kHz audio.
19
+
20
+ That split decides where a hum has to enter. Melody is *decided* by the planner, not by the decoder: once the semantic tokens exist, the decoder can shape timing, articulation and timbre, but it cannot change which notes are sung. So a hum module needs two parts:
21
+
22
+ 1. **Score continuation** puts the hum's melody into the planner, where the melody is chosen. This is the part that makes the song *be about* your melody. It needs no training.
23
+ 2. **A prosody adapter** puts the hum's actual pitch contour and timing into the decoder, so the sung line follows how you hummed it, not just what you hummed. This is the trained part.
24
+
25
+ ```mermaid
26
+ flowchart LR
27
+ H[hum audio] --> T[melody transcriber -> ABC]
28
+ T --> P["open score prefix<br/>[ABC_START] + hum ABC (no end token)"]
29
+ S[style + lyrics] --> P
30
+ P --> AR1[AR: continue the score]
31
+ AR1 --> AR2[AR: semantic tokens from the full score]
32
+ H --> C[pitch tracker -> sine carrier -> VAE encode]
33
+ AR2 --> NAR[NAR decoder + prosody adapter]
34
+ C -->|added at layers 0,7,14,21| NAR
35
+ NAR --> VAE[VAE decode] --> A[song]
36
+ ```
37
+
38
+ ## Stage 1: score continuation (no training)
39
+
40
+ **Transcribe the hum.** A melody transcriber (SheetSage2, melody-only mode) turns the hum into ABC in YuE2's own two-voice score format: a `Vocal` melody line and an `Ins` line, key, meter, tempo. A 20 s hum becomes roughly 200 to 250 score tokens. Trailing bars that are only rests are stripped, so the score does not end where the hum ended.
41
+
42
+ **Leave the score open.** YuE2's prompt for a provided score is `[EOD] text(instructions, style, lyrics) [ABC_START] score [ABC_END] [MUSIC_START]`. We build the same prompt but stop after the hum's score tokens, with **no `ABC_END`**. The planner is then simply asked to keep writing. Because it was pretrained to write complete scores after `[ABC_START]`, it treats the hum's bars as the opening of a song and writes the rest: new sections, transitions, an ending, all in the same key, meter and range. On our tests the hummed phrase recurred verbatim two to four times later in the continued score, typically as the hook.
43
+
44
+ **Then the normal path.** The full score (hum bars plus continuation) is closed with `[ABC_END] [MUSIC_START]`, the planner writes semantic tokens for the whole song, and the decoder renders them. Song length comes from the score the planner wrote, so 20 s of hum yields a 2 to 3 minute song with an ending.
45
+
46
+ Three melody modes fall out of this: *continue from hum* (the above), *hum only* (close the score right after the hum, so the song is exactly your melody), and *ignore hum* (let the planner write its own score; the adapter below can still shape phrasing).
47
+
48
+ ## Stage 2: the prosody adapter (trained)
49
+
50
+ ### The conditioning signal
51
+ The decoder is not shown the hum itself. It is shown a deliberately reduced version that carries melody and timing and nothing else:
52
+
53
+ - pitch is tracked with pYIN over 65 to 1000 Hz (hop 512 at 48 kHz), gaps forward-filled, interpolated to the sample grid;
54
+ - a **sine wave** is synthesized at that pitch;
55
+ - its amplitude follows the rectified hum, low-passed with a 4th-order 30 Hz and a 2nd-order 80 Hz Butterworth filter, which smears syllables away;
56
+ - the carrier is encoded by YuE2's own VAE into 25 Hz latents, `[T, 64]`.
57
+
58
+ Because the decoder only ever sees sine tones, it cannot depend on the singer's timbre or words. That is what lets a training set built from real vocal stems generalize to a person humming into a laptop microphone.
59
+
60
+ ### Where it enters the decoder
61
+ Four zero-initialized `Linear(64 → 2048)` projections take the (edge-padded) carrier latents and **add** them to the decoder's hidden state: one at the input (alongside `vae2llm(x_t)`, the time embedding and positional embedding) and one each before layers 7, 14 and 21 of the 28 layers. Frames with no hum carry zeros, which the projections map to a learned bias, so "no hum here" is an explicit state rather than an absence.
62
+
63
+ Trainable parameters: the four projections, a rank-64 LoRA on the decoder's attention and MLP projections (`nar_self_attn.{q,k,v,o}_proj`, `nar_mlp.{gate,up,down}_proj`), and the two full `vae2llm` / `llm2vae` layers. The adapter was trained on top of our real-audio decoder LoRA (folded into the base first); the *combined* release merges both into one rank-96 LoRA so it applies to the stock model in one step.
64
+
65
+ ### Training pairs
66
+ Pairs are self-supervised from ordinary songs with separated vocals: the **condition** is the sine carrier of the vocal stem, the **target** is the full mix's VAE latents, and the semantic tokens in context are the mix's own tokens from our audio-to-token head (the same kind of tokens the planner produces at inference). 3,163 training pairs, 188 held out. Loss is the standard flow-matching objective on 30 s windows: `MSE(v_pred, noise − x1)` with `x_t = t·noise + (1 − t)·x1`, the whole song's tokens in the AR cache.
67
+
68
+ ### The partial-hum rule
69
+ Real use is "hum a bit, get a whole song", so half of the training draws see only part of the carrier: for eligible songs the hum is kept only from **2 s before the vocal onset** for a random **12 to 28 s** and zeroed everywhere else. Onset is detected from the pitch tracker's voiced flag combined with energy (sustained 0.4 s). Training windows are biased 60/40 toward the hum's edges so the model often sees the handoff from "follow the hum" to "continue on your own". Vocal onset was found for 3,304 of the 3,351 clips; median onset 7 s, so trimming the dead air mattered.
70
+
71
+ 10% of draws zero the whole carrier, which enables **classifier-free guidance on the hum channel** at inference: `v = v_no_hum + g · (v_hum − v_no_hum)`, exposed as *hum influence*.
72
+
73
+ ### Numbers
74
+ 12,000 steps, held-out clips:
75
+
76
+ | | step 0 | step 12,000 |
77
+ |---|---|---|
78
+ | with hum | 0.960 | **0.906** |
79
+ | no hum (carrier zeroed) | 0.960 | 0.913 |
80
+ | partial hum (fixed 20 s from onset) | 0.901 | 0.871 |
81
+
82
+ The with-hum advantage appears late (crossover near step 5,000) and stays modest. That is expected: the semantic tokens in context already fix the melody, so the carrier can only add timing and pitch nuance. This is exactly why melody had to go into the planner (stage 1) and why the adapter is the finishing layer, not the melody carrier.
83
+
84
+ ## Inference outside ComfyUI
85
+ ```
86
+ # stage 1: hum -> ABC (melody-only transcription), then open-score continuation + song
87
+ python scripts/hum_continue.py hum_score.abc style.txt lyrics.txt out_tag <seed> [nar_lora]
88
+ # stage 2: render the same song's tokens through the prosody adapter with the hum's carrier
89
+ VOICE_CFG=1.0 HUM_OFFSET_S=0 python scripts/infer_hum.py hum_adapter_v1.pt hum.wav out_tag_score.abc out_tag_tokens.npy style.txt lyrics.txt out.flac <seed>
90
+ ```
91
+ `hum_continue.py` builds the open prefix with `token_prefixes(request, tok) + hum_abc_ids`, calls the pipeline's ABC generator on it, then runs the stock semantic and decoder path. `infer_hum.py` folds the adapter into the decoder, places the carrier latents at `HUM_OFFSET_S`, and integrates the flow ODE with hum-channel guidance. `hum_prep.py` and `train_hum.py` reproduce the dataset and training.
92
+
93
+ ## Inference in ComfyUI
94
+ The ComfyUI-HumSong node pack (`ComfyUI-HumSong/`) implements both stages natively with four nodes and no stock nodes: **HumSong Loader** (checkpoint, hum adapter, melody transcriber), **Hum Input** (file or in-node microphone recording), **Hum to Song** (style, lyrics, seed, length cap, hum influence, melody mode), **HumSong Output** (FLAC, player, score view with the hummed bars highlighted). Internally the loader applies the adapter's decoder LoRA through ComfyUI's own LoRA machinery (`humsong_yue2_adapter_v1_comfy.safetensors`, fused-projection layout) and keeps the four injection projections; the song node wraps the decoder's forward to add the carrier at the four depths and to apply hum-channel guidance, and uses ComfyUI's built-in SheetSage2 for transcription.
95
+
96
+ ## Weights
97
+ | file | use |
98
+ |---|---|
99
+ | `hum_adapter_v1.safetensors` | adapter as trained; fold `nar_lora_joint_v4` into the base first |
100
+ | `hum_adapter_v1_combined.safetensors` | self-contained against stock YuE2-3B (rank-96 LoRA + projections) |
101
+ | `humsong_yue2_adapter_v1_comfy.safetensors` | ComfyUI layout for the node pack |
102
+ | `hum_adapter_v1.pt` | training checkpoint |
103
+ | `minted_regularizer_pack_v2.pt` | regularizer for training planner LoRAs (FS_Audio Suite trainer): 12,247 YuE2 self-generated songs as semantic tokens + style + lyrics + ABC score text, no audio. Coin-flipped against your artist so the LoRA keeps the base model's range. |
104
+
105
+ ## Limits worth knowing
106
+ The transcriber needs something voice-like; it does not transcribe pure sine tones, so a real hum works and a synthesized tone does not. The hum sets the melody and the opening, not the total length; the planner decides where the song ends. The adapter's effect is subtle by design and best judged in the first hummed section. Weights derive from YuE2-3B (CC BY-NC 4.0): non-commercial use only.
checkpoints/YuE2-hum-to-song/hum_adapter_v1.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f1e60dbd8910750e03adf4a4f7a8b0aba0866aa4a686338a32e7b3cedfd74d9
3
+ size 282191689
checkpoints/YuE2-hum-to-song/hum_adapter_v1.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d8bc53e3d386e617c40a2e9563cef20d1e48faaab2240a4051d68c21373c585c
3
+ size 282152712
checkpoints/YuE2-hum-to-song/hum_adapter_v1_combined.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eeaf490b7045bb1215b3255f826dca551da8eb99d3d8e90311ce095e43b20b12
3
+ size 421613360
checkpoints/YuE2-hum-to-song/humsong_yue2_adapter_v1_comfy.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:215c957c1d33e411cf791891862ad837e3ea0e747717dd1e988de17f7adf79a2
3
+ size 322511768
checkpoints/YuE2-hum-to-song/minted_regularizer_pack_v2.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:587631eec5946f9f87d4b422abcda7e35dee43299efb7b7d2fcba4cd8752c475
3
+ size 296098847
checkpoints/YuE2-hum-to-song/scripts/ckpt_io.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load our checkpoints from either the original .pt files or the .safetensors releases, returning the same dict layout the scripts expect.
2
+ head : {"model": state_dict, "cfg": {...}}
3
+ NAR LoRA: {"lora": [A0,B0,...] (layer-major: nar_self_attn q,k,v,o then nar_mlp gate,up,down), "io": {"vae2llm": sd, "llm2vae": sd}, "rank": int}
4
+ AR LoRA : {"lora": [A0,B0,...] (layer-major: self_attn q,k,v,o then mlp gate,up,down), "rank": int}"""
5
+ import torch
6
+ def _mods(prefix): return [(f"{prefix}self_attn",n) for n in ("q_proj","k_proj","v_proj","o_proj")]+[(f"{prefix}mlp",n) for n in ("gate_proj","up_proj","down_proj")]
7
+ def load_ckpt(path, map_location="cpu"):
8
+ if not str(path).endswith(".safetensors"): return torch.load(path, map_location=map_location, weights_only=False)
9
+ from safetensors.torch import load_file; from safetensors import safe_open
10
+ t=load_file(path, device=str(map_location))
11
+ with safe_open(path, "pt") as f: meta=f.metadata() or {}
12
+ if any(k.endswith(".lora_A") for k in t):
13
+ prefix="nar_" if any(".nar_self_attn." in k for k in t) else ""
14
+ layers=sorted({int(k.split(".")[1]) for k in t if k.startswith("layers.")}); lora=[]
15
+ for L in layers:
16
+ for blk,proj in _mods(prefix): lora+=[t[f"layers.{L}.{blk}.{proj}.lora_A"], t[f"layers.{L}.{blk}.{proj}.lora_B"]]
17
+ out={"lora":lora, "rank":int(meta.get("rank", lora[0].shape[0]))}
18
+ if prefix: out["io"]={m:{k.split(".",1)[1]:v for k,v in t.items() if k.startswith(m+".")} for m in ("vae2llm","llm2vae")}
19
+ return out
20
+ return {"model":t, "cfg":{"instnorm": meta.get("input","").find("instnorm=true")>=0}}
checkpoints/YuE2-hum-to-song/scripts/hum_continue.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hum -> full song by SCORE CONTINUATION (YuE2-native): the hum's melody ABC is placed in the prompt as the OPEN beginning of the score
2
+ (no ABC_END), the AR continues the score to a full song, then writes the music; stock NAR path with the joint_v3 NAR LoRA.
3
+ usage: hum_continue.py <abc_file> <style_file> <lyrics_file> <out_tag> <seed> [nar_lora|none] env: OUT_DIR, KEEP_HEADER=1"""
4
+ import os, sys, json, re, numpy as np, torch, torch.nn as nn
5
+ os.environ.setdefault("HF_HOME","/workspace/hf")
6
+ from yue2 import YuE2Pipeline
7
+ from yue2.protocol import SongRequest, token_prefixes, resolve_sampling, ABC_START, ABC_END
8
+ from yue2.pipeline import SymbolicPlan
9
+ ABC_F,STYLE_F,LYR_F,TAG,SEED=sys.argv[1:6]; NAR_CK=sys.argv[6] if len(sys.argv)>6 else "/workspace/tok/full/joint_v3/lora_best.pt"; OUT=os.environ.get("OUT_DIR","/workspace/hum/hum_cont"); os.makedirs(OUT,exist_ok=True); dev="cuda"
10
+ pipe=YuE2Pipeline.from_pretrained("m-a-p/YuE2-3B", vae="m-a-p/YuE2-Vae"); model=pipe._load_model(); bb=model.model; tok=pipe.tokenizer
11
+ if NAR_CK!="none":
12
+ nar=torch.load(NAR_CK,map_location=dev); it=iter(nar["lora"])
13
+ with torch.no_grad():
14
+ for layer in bb.layers:
15
+ for mod,names in ((layer.nar_self_attn,("q_proj","k_proj","v_proj","o_proj")),(layer.nar_mlp,("gate_proj","up_proj","down_proj"))):
16
+ for n in names: A=next(it).to(dev).float(); B=next(it).to(dev).float(); lin=getattr(mod,n); lin.weight.add_((B@A).to(lin.weight.dtype))
17
+ model.vae2llm.load_state_dict({k:v.to(torch.bfloat16) for k,v in nar["io"]["vae2llm"].items()}); model.llm2vae.load_state_dict({k:v.to(torch.bfloat16) for k,v in nar["io"]["llm2vae"].items()})
18
+ print("NAR LoRA merged", flush=True)
19
+ style=open(STYLE_F).read().strip(); lyrics=open(LYR_F).read().strip()
20
+ abc=open(ABC_F).read().strip()
21
+ # drop trailing bars that are only rests at the end of the hum (the hum stopped; the song should not), keep an open final line
22
+ lines=abc.split("\n")
23
+ while lines and re.fullmatch(r"(V: (Vocal|Ins))|(Z\d*\|)|", lines[-1].strip()): lines.pop()
24
+ abc_open="\n".join(lines)+"\n"
25
+ req=SongRequest(style=style,lyrics=lyrics,cot="melody",seed=int(SEED),id=TAG)
26
+ partial=tok.encode(abc_open); prefix=token_prefixes(req,tok)+partial # ends INSIDE the score: no ABC_END -> the AR keeps writing it
27
+ print(f"open score prefix: {len(partial)} ABC tokens from the hum ({abc_open.count(chr(10))} lines)", flush=True)
28
+ sampling=resolve_sampling(None,pipe.generation_config.abc)
29
+ ids,timing,trunc=pipe._generate(prefix,sampling,int(SEED),"abc")
30
+ full=partial+list(ids); plan=SymbolicPlan(req,tok.decode(full),full,token_prefixes(req,tok,full),timing,trunc)
31
+ open(f"{OUT}/{TAG}_score.abc","w").write(plan.abc); print(f"score continued: +{len(ids)} tokens -> {len(full)} total, {plan.abc.count(chr(10))} lines", flush=True)
32
+ sem=pipe.generate_semantic(plan); lat=pipe.synthesize(sem); audio=pipe.decode(lat)
33
+ import soundfile as sf; sf.write(f"{OUT}/{TAG}.flac", audio, 48000, subtype="PCM_24"); np.save(f"{OUT}/{TAG}_tokens.npy",np.asarray(sem.tokens,dtype=np.int32))
34
+ json.dump({"style":style,"lyrics":lyrics,"seed":int(SEED),"cot":"melody+continuation","hum_abc":ABC_F,"hum_abc_tokens":len(partial),"continued_tokens":len(ids),"nar":NAR_CK,"audio_seconds":len(audio)/48000},open(f"{OUT}/{TAG}.json","w"),indent=1)
35
+ print(f"GEN DONE {TAG} {len(audio)/48000:.1f}s tokens {len(sem.tokens)}", flush=True)
checkpoints/YuE2-hum-to-song/scripts/hum_prep.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hum-to-song data prep (self-contained). For each manifest row {id, vocal, mix, style, lyrics, held}:
2
+ hum = VAE latents [T,64] of the prosody carrier built from the VOCAL stem (pYIN pitch -> sine, amplitude = low-passed |vocal|; no words, no timbre)
3
+ mix = VAE latents [T,64] of the full MIX (training target)
4
+ tokmix = semantic tokens of the MIX from the audio->token head (what the AR generates at inference)
5
+ prefix = YuE2 cot=off prompt ids (instructions + style + lyrics)
6
+ onset_s / sing_s = vocal onset (pYIN voiced & energy, sustained 0.4 s) and seconds of singing after it (partial-hum rule)
7
+ -> OUT/<id>.npz + OUT/<id>.json. One GPU process; a spawned CPU pool runs pYIN.
8
+ usage: hum_prep.py manifest.jsonl OUT_DIR env: HEAD (tokenizer head .pt/.safetensors), NWORKERS, SHARD, NSHARD, NUMBA_CACHE_DIR"""
9
+ import os, sys, json, subprocess, time, socket, numpy as np
10
+ os.environ.setdefault("HF_HOME", os.environ.get("HF_HOME", os.path.expanduser("~/.cache/huggingface"))); os.environ.setdefault("OMP_NUM_THREADS","2")
11
+ os.environ.setdefault("NUMBA_CACHE_DIR", f"/tmp/numba_cache_{socket.gethostname()[:8]}") # a numba cache shared across machines with different CPUs segfaults
12
+ SR=48000; HOP=512
13
+ def load_audio(path, sr_out, mono):
14
+ r=subprocess.run(["ffmpeg","-v","error","-i",path,"-f","f32le","-ac","1" if mono else "2","-ar",str(sr_out),"-"],capture_output=True); a=np.frombuffer(r.stdout,dtype=np.float32)
15
+ return a if mono else a.reshape(-1,2)
16
+ def prosody_sine(y, sr=SR):
17
+ """-> sine carrier, voiced fraction, vocal onset (s, -1 if none), seconds of singing after onset"""
18
+ import librosa; from scipy.signal import butter, sosfiltfilt
19
+ f0,voiced,_=librosa.pyin(y,fmin=65,fmax=1000,sr=sr,hop_length=HOP,frame_length=4*HOP); f0=f0.copy(); idx=np.where(~np.isnan(f0))[0]
20
+ if len(idx)==0: return None,0.0,-1.0,0.0
21
+ f0[:idx[0]]=f0[idx[0]]
22
+ for i in range(1,len(f0)):
23
+ if np.isnan(f0[i]): f0[i]=f0[i-1]
24
+ t=np.arange(len(y))/sr; f=np.interp(t,np.arange(len(f0))*HOP/sr,f0)
25
+ env=np.abs(y); env=sosfiltfilt(butter(4,30,btype="low",fs=sr,output="sos"),env); env=sosfiltfilt(butter(2,80,btype="low",fs=sr,output="sos"),env); env=np.clip(env,0,None)
26
+ r=env*np.sin(2*np.pi*np.cumsum(f)/sr); r=(r/(np.abs(r).max()+1e-9)*0.9).astype(np.float32)
27
+ fr=y[:len(y)//HOP*HOP].reshape(-1,HOP); db=20*np.log10(np.sqrt((fr**2).mean(1))+1e-9); act=(db>db.max()-30)&voiced[:len(db)].astype(bool)
28
+ k=int(0.4*sr/HOP); run=np.convolve(act.astype(int),np.ones(k,int),"valid")>=k; idx=np.where(run)[0]
29
+ onset=float(idx[0]*HOP/sr) if len(idx) else -1.0; sing=float(act[idx[0]:].sum()*HOP/sr) if len(idx) else 0.0
30
+ return r,float(np.nanmean(voiced)),onset,sing
31
+ def work(row):
32
+ try:
33
+ v=load_audio(row["vocal"],SR,True); r,vr,onset,sing=prosody_sine(v)
34
+ if r is None: return row,None,None,None,(0.0,-1.0,0.0)
35
+ return row,np.stack([r,r],1),load_audio(row["mix"],SR,False),load_audio(row["mix"],24000,True),(vr,onset,sing)
36
+ except Exception as e: print("ERR",row.get("id"),type(e).__name__,str(e)[:80],flush=True); return row,None,None,None,(0.0,-1.0,0.0)
37
+ if __name__=="__main__":
38
+ import torch, torch.nn as nn, multiprocessing as mp, glob
39
+ from transformers import AutoModel, AutoFeatureExtractor
40
+ from yue2.modeling_vae import YuE2VAE
41
+ from yue2.protocol import SongRequest, token_prefixes
42
+ from yue2.tokenization_yue2 import YuE2TextTokenizer
43
+ sys.path.insert(0,os.path.dirname(os.path.abspath(__file__))); from ckpt_io import load_ckpt
44
+ MAN,OUT=sys.argv[1:3]; os.makedirs(OUT,exist_ok=True); dev="cuda"; NW=int(os.environ.get("NWORKERS","24")); SH=int(os.environ.get("SHARD","0")); NSH=int(os.environ.get("NSHARD","1"))
45
+ HEAD=os.environ.get("HEAD","tokenizer_head_joint_v4.safetensors")
46
+ snap=lambda n: glob.glob(f"{os.environ['HF_HOME']}/hub/models--m-a-p--{n}/snapshots/*")[0]; tok=YuE2TextTokenizer(snap("YuE2-3B")+"/qwen.tiktoken")
47
+ vae=YuE2VAE.from_pretrained(snap("YuE2-Vae"),decoder_only=False,device=dev,local_files_only=True)
48
+ proc=AutoFeatureExtractor.from_pretrained("m-a-p/MERT-v2-FullSong",trust_remote_code=True); mert=AutoModel.from_pretrained("m-a-p/MERT-v2-FullSong",trust_remote_code=True).to(dev).eval()
49
+ VOCAB=32768; WIN=512; D=512; L=8; H=8
50
+ class Tok(nn.Module):
51
+ def __init__(s, din):
52
+ super().__init__(); s.inp=nn.Linear(din,D); s.pos=nn.Parameter(torch.zeros(1,WIN,D))
53
+ layer=nn.TransformerEncoderLayer(D,H,4*D,dropout=0.1,batch_first=True,norm_first=True,activation="gelu"); s.enc=nn.TransformerEncoder(layer,L); s.norm=nn.LayerNorm(D); s.head=nn.Linear(D,VOCAB)
54
+ def forward(s,x): return s.head(s.norm(s.enc(s.inp(x)+s.pos[:,:x.shape[1]])))
55
+ head=Tok(1024).to(dev).eval(); head.load_state_dict(load_ckpt(HEAD,dev)["model"])
56
+ def latents(st48):
57
+ out=[]; CH=SR*30
58
+ with torch.inference_mode():
59
+ for s in range(0,len(st48),CH):
60
+ seg=st48[s:s+CH]
61
+ if len(seg)<1920: break
62
+ out.append(vae.encode(torch.tensor(np.ascontiguousarray(seg.T[None])))[0].T.float().cpu())
63
+ return torch.cat(out,0).numpy()
64
+ def mert_l20(m24):
65
+ CH=24000*30; chunks=[m24[s:s+CH] for s in range(0,len(m24),CH)]; chunks=[c for c in chunks if len(c)>=24000]; full=[c for c in chunks if len(c)==CH]; tail=[c for c in chunks if len(c)<CH]; feats=[]
66
+ with torch.inference_mode(), torch.autocast("cuda",dtype=torch.bfloat16):
67
+ for group in ([full] if full else [])+[[c] for c in tail]:
68
+ inp={k:v.to(dev) for k,v in proc(group,sampling_rate=24000,return_tensors="pt").items()}; feats.append(mert(**inp,output_hidden_states=True).hidden_states[20].reshape(-1,1024))
69
+ Hh=torch.cat(feats,0).float(); T25=int(round(len(m24)/24000*25)); return torch.nn.functional.interpolate(Hh.T[None],size=T25,mode="linear",align_corners=False)[0].T.cpu().numpy()
70
+ @torch.no_grad()
71
+ def predict(x):
72
+ x=(x-x.mean(0))/(x.std(0)+1e-5); T=len(x); out=np.zeros(T,dtype=np.int64); starts=list(range(0,max(1,T-WIN+1),WIN//2))
73
+ if starts[-1]+WIN<T: starts.append(max(0,T-WIN))
74
+ for s0 in starts:
75
+ xw=x[s0:s0+WIN]; n=len(xw)
76
+ if n<WIN: xw=np.pad(xw,((0,WIN-n),(0,0)))
77
+ with torch.autocast("cuda",dtype=torch.bfloat16): pred=head(torch.tensor(xw[None],dtype=torch.float32,device=dev))[0,:n].float().argmax(-1).cpu().numpy()
78
+ lo=s0+(0 if s0==0 else WIN//4); hi=s0+n-(0 if s0+n>=T else WIN//4); out[lo:hi]=pred[lo-s0:hi-s0]
79
+ return out
80
+ rows=[json.loads(l) for l in open(MAN) if l.strip()]; rows=[r for r in rows if not os.path.exists(f"{OUT}/{r['id']}.npz")][SH::NSH]
81
+ prosody_sine(np.sin(np.linspace(0,2*np.pi*220*3,SR*3)).astype(np.float32)) # prewarm the numba cache before the pool
82
+ print(f"hum prep: shard {SH}/{NSH} {len(rows)} clips, {NW} pYIN workers",flush=True); done=skip=0; t0=time.time(); B=2*NW
83
+ def results(): # bounded in-flight raw audio (the GPU is slower than the pool)
84
+ for b in range(0,len(rows),B): yield from pool.imap_unordered(work,rows[b:b+B],chunksize=1)
85
+ with mp.get_context("spawn").Pool(NW) as pool:
86
+ for row,st,m48,m24,(vr,onset,sing) in results():
87
+ if st is None: skip+=1; continue
88
+ zm=latents(m48); n=len(zm); zh=latents(st)[:n]; tm=predict(mert_l20(m24))[:n]
89
+ if len(zh)<n: zh=np.pad(zh,((0,n-len(zh)),(0,0)))
90
+ if len(tm)<n: tm=np.pad(tm,(0,n-len(tm)),mode="edge")
91
+ pre=token_prefixes(SongRequest(style=row["style"],lyrics=row["lyrics"],cot="off",seed=1,id="h"),tok)
92
+ np.savez(f"{OUT}/{row['id']}.npz.tmp.npz",hum=zh.astype(np.float16),mix=zm.astype(np.float32),tokmix=tm.astype(np.int32),prefix=np.asarray(pre,dtype=np.int64),voiced=np.float32(vr),onset_s=np.float32(onset),sing_s=np.float32(sing)); os.replace(f"{OUT}/{row['id']}.npz.tmp.npz",f"{OUT}/{row['id']}.npz")
93
+ json.dump({"id":row["id"],"held":bool(row.get("held",False))},open(f"{OUT}/{row['id']}.json","w")); done+=1
94
+ if done%50==0: print(f"{done}/{len(rows)} skipped {skip} {(time.time()-t0)/done:.1f}s/clip",flush=True)
95
+ print(f"HUM PREP DONE {done} skipped {skip}",flush=True)
checkpoints/YuE2-hum-to-song/scripts/infer_hum.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage 2 of hum->song: render continuation tokens through the HUM-conditioned NAR adapter (sine-carrier latents of the hum, placed at HUM_OFFSET_S).
2
+ usage: infer_hum.py <adapter.pt> <hum.wav|none> <score.abc> <tokens.npy> <style.txt> <lyrics.txt> <out.flac> [seed] env: VOICE_CFG (1.0), HUM_OFFSET_S (0), STEPS (32)"""
3
+ import os, sys, glob, json, math, numpy as np, torch, torch.nn as nn, torch.nn.functional as F, soundfile as sf
4
+ os.environ.setdefault("HF_HOME","/workspace/hf"); sys.path.insert(0,"/workspace/hum")
5
+ from yue2.modeling_yue2 import YuE2ForCausalLM
6
+ from yue2.modeling_vae import YuE2VAE
7
+ from yue2.protocol import CODEC_OFFSET, MUSIC_END, SongRequest, token_prefixes
8
+ from yue2.tokenization_yue2 import YuE2TextTokenizer
9
+ from yue2.nar import attention as nar_attention
10
+ from hum_prep import prosody_sine, load_audio
11
+ ADAPTER,HUM,SCORE,TOKS,STYLE_F,LYR_F,OUTF=sys.argv[1:8]; SEED=int(sys.argv[8]) if len(sys.argv)>8 else 7; GUID=float(os.environ.get("VOICE_CFG","1.0")); OFF=float(os.environ.get("HUM_OFFSET_S","0")); STEPS=int(os.environ.get("STEPS","32")); dev="cuda"
12
+ snap=lambda n: glob.glob(f"/workspace/hf/hub/models--m-a-p--{n}/snapshots/*")[0]; tok=YuE2TextTokenizer(snap("YuE2-3B")+"/qwen.tiktoken")
13
+ vae=YuE2VAE.from_pretrained(snap("YuE2-Vae"),decoder_only=False,device=dev,local_files_only=True)
14
+ style=open(STYLE_F).read().strip(); lyrics=open(LYR_F).read().strip(); score=open(SCORE).read().strip()
15
+ tv=np.load(TOKS).astype(np.int64); T=len(tv)
16
+ prefix=token_prefixes(SongRequest(style=style,lyrics=lyrics,cot="melody",seed=1,id="h",abc=score),tok) # same layout the continuation used
17
+ cond=torch.zeros(T,64,device=dev)
18
+ if HUM!="none":
19
+ y=load_audio(HUM,48000,True); r,vr,onset,sing=prosody_sine(y); st=np.stack([r,r],1)
20
+ with torch.inference_mode(): zh=torch.cat([vae.encode(torch.tensor(np.ascontiguousarray(st[s:s+48000*30].T[None])))[0].T.float() for s in range(0,len(st),48000*30) if len(st[s:s+48000*30])>=1920],0)
21
+ o=int(OFF*25); L=min(len(zh),T-o); cond[o:o+L]=zh[:L].to(dev); print(f"hum: {len(y)/48000:.1f}s voiced {vr:.2f} -> {L} latent frames placed at {OFF:.1f}s of a {T/25:.1f}s song",flush=True)
22
+ model=YuE2ForCausalLM.from_pretrained(snap("YuE2-3B"),local_files_only=True,torch_dtype=torch.bfloat16,low_cpu_mem_usage=True).eval().to(dev); bb=model.model
23
+ ck=torch.load(ADAPTER,map_location=dev); INJ=ck.get("inject",[0])
24
+ def fold(lora_list):
25
+ it=iter(lora_list)
26
+ with torch.no_grad():
27
+ for layer in bb.layers:
28
+ for mod,names in ((layer.nar_self_attn,("q_proj","k_proj","v_proj","o_proj")),(layer.nar_mlp,("gate_proj","up_proj","down_proj"))):
29
+ for nm in names: A=next(it).to(dev).float(); B=next(it).to(dev).float(); lin=getattr(mod,nm); lin.weight.add_((B@A).to(lin.weight.dtype))
30
+ if ck.get("folded_init"): fold(torch.load(ck["folded_init"],map_location=dev)["lora"])
31
+ fold(ck["lora"])
32
+ with torch.no_grad(): model.vae2llm.load_state_dict({k:v.to(torch.bfloat16) for k,v in ck["io"]["vae2llm"].items()}); model.llm2vae.load_state_dict({k:v.to(torch.bfloat16) for k,v in ck["io"]["llm2vae"].items()})
33
+ stem_proj=nn.ModuleList([nn.Linear(64,model.config.hidden_size) for _ in INJ]).to(dev); stem_proj.load_state_dict(ck["stem_proj"]); stem_proj.to(torch.bfloat16)
34
+ def ar_layer(layer,x,cos_,sin_):
35
+ q,k,v=layer.self_attn.project_qkv(layer.input_layernorm(x),cos_,sin_); h=nar_attention(q[0],k[0],v[0],causal=True)
36
+ x=x+layer.self_attn.o_proj(h.flatten(1)[None]); return x+layer.mlp(layer.post_attention_layernorm(x)),k[0],v[0]
37
+ def nar_layer(layer,h,ak,av,ncos,nsin):
38
+ q,k,v=layer.nar_self_attn.project_qkv(layer.nar_input_layernorm(h),ncos,nsin); a=nar_attention(q[0],torch.cat((ak,k[0])),torch.cat((av,v[0])))
39
+ h=h+layer.nar_self_attn.o_proj(a.flatten(1)[None]); return h+layer.nar_mlp(layer.nar_pre_mlp_layernorm(h))
40
+ @torch.inference_mode()
41
+ def solve(codec, voc, steps):
42
+ ar=torch.tensor([prefix+[int(c)+CODEC_OFFSET for c in codec]+[MUSIC_END]],device=dev); Lq=ar.shape[1]; cos_,sin_=bb.rotary_emb(torch.arange(Lq,device=dev)[None]); x=bb.embed_tokens(ar); cache=[]
43
+ for layer in bb.layers: x,k,v=ar_layer(layer,x,cos_,sin_); cache.append((k,v))
44
+ Tn=len(codec); N=Tn+2; ncos,nsin=bb.rotary_emb(torch.arange(Lq,Lq+N,device=dev)[None]); pe=model.latent_pos_embed(torch.arange(N,device=dev).clamp(max=model.config.max_latent_frames-1))[None]
45
+ vp=F.pad(voc,(0,0,1,1))[None].to(torch.bfloat16); zp=torch.zeros_like(vp)
46
+ stem_h={k:stem_proj[j](vp) for j,k in enumerate(INJ)}; zero_h={k:stem_proj[j](zp) for j,k in enumerate(INJ)}
47
+ def vel(state,t,sh_):
48
+ tc=min(max(t,1e-4),1-1e-4); sh=model._shift_t_value(float(np.clip(np.log(tc/(1-tc)),-20,20)),dev,torch.bfloat16)
49
+ h=model.vae2llm(F.pad(state,(0,0,1,1))[None].to(torch.bfloat16))+sh_[0]+model.time_embedder(sh.expand(N))[None]+pe
50
+ for li,(layer,(ak,av)) in enumerate(zip(bb.layers,cache)):
51
+ if li in sh_ and li>0: h=h+sh_[li]
52
+ h=nar_layer(layer,h,ak,av,ncos,nsin)
53
+ return model.llm2vae(bb.norm(h))[0,1:-1].float()
54
+ def velocity(state,t):
55
+ v=vel(state,t,stem_h)
56
+ return v if GUID==1.0 else vel(state,t,zero_h)+GUID*(v-vel(state,t,zero_h))
57
+ g=torch.Generator(device="cpu").manual_seed(SEED); state=torch.randn(Tn,64,generator=g).to(dev); dt=1.0/steps
58
+ for i in range(steps):
59
+ t=1.0-i*dt; v1=velocity(state,t); mid=state-v1*(dt/2); state=state-velocity(mid,t-dt/2)*dt
60
+ return state
61
+ z=solve(tv,cond,STEPS).cpu(); del model; torch.cuda.empty_cache()
62
+ with torch.inference_mode(): audio=vae.decode_tiled(z.T[None].contiguous(),core_frames=750,halo_frames=16,output_device="cpu")[0].float().clamp(-1,1).T.numpy()
63
+ audio=np.nan_to_num(audio).astype(np.float32); sf.write(OUTF,audio,48000,subtype="PCM_24"); print(f"HUM INFER DONE {OUTF} {len(audio)/48000:.1f}s cfg {GUID} finite {bool(torch.isfinite(z).all())}",flush=True)
checkpoints/YuE2-hum-to-song/scripts/to_comfy_lora.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Convert our YuE2 LoRAs to ComfyUI's native YuE2 LoRA layout.
2
+ ComfyUI's repackaged checkpoint (Comfy-Org/YuE2) renames the NAR branch nar_self_attn/nar_mlp -> self_attn/mlp and FUSES projections:
3
+ self_attn.qkv_proj = [q(2048) ; k(1024) ; v(1024)] rows, mlp.gate_up_proj = [gate(6144) ; up(6144)] rows.
4
+ Our separate rank-r LoRAs become one block-diagonal LoRA per fused matrix (rank 3r / 2r) whose up@down equals the stacked separate deltas exactly.
5
+ Key bases: NAR -> diffusion_model.model.layers.{i}..., AR -> text_encoders.model.layers.{i}... (what comfy/lora.py's key maps accept).
6
+ Suffixes: .lora_up.weight / .lora_down.weight (no .alpha => scale 1.0, matching our W += B@A). vae2llm/llm2vae full weights -> .diff / .diff_b vs the m-a-p base.
7
+ usage: to_comfy_lora.py <ar|nar> <in.pt|.safetensors> <out.safetensors>"""
8
+ import sys, os, glob, json, torch
9
+ from safetensors.torch import save_file, load_file
10
+ from safetensors import safe_open
11
+ sys.path.insert(0,"/workspace/kit_export/tokrepo_v4/scripts"); from ckpt_io import load_ckpt
12
+ BRANCH, SRC, DST = sys.argv[1:4]
13
+ ck=load_ckpt(SRC,"cpu"); lora=[t.float() for t in ck["lora"]]; R=int(ck["rank"])
14
+ prefix="diffusion_model.model.layers" if BRANCH=="nar" else "text_encoders.model.layers"
15
+ mods=[("self_attn","q_proj"),("self_attn","k_proj"),("self_attn","v_proj"),("self_attn","o_proj"),("mlp","gate_proj"),("mlp","up_proj"),("mlp","down_proj")]
16
+ assert len(lora)==28*len(mods)*2, len(lora)
17
+ def blockdiag_up(Bs):
18
+ rows=sum(b.shape[0] for b in Bs); cols=sum(b.shape[1] for b in Bs); up=torch.zeros(rows,cols); r=c=0
19
+ for b in Bs: up[r:r+b.shape[0], c:c+b.shape[1]]=b; r+=b.shape[0]; c+=b.shape[1]
20
+ return up
21
+ out={}; i=0; checks=[]
22
+ for L in range(28):
23
+ P={}
24
+ for blk,proj in mods: P[proj]=(lora[i],lora[i+1]); i+=2 # A [r,in], B [out,r]
25
+ # fused qkv: down = [Aq;Ak;Av], up = blockdiag(Bq,Bk,Bv)
26
+ Aq,Bq=P["q_proj"]; Ak,Bk=P["k_proj"]; Av,Bv=P["v_proj"]
27
+ down=torch.cat([Aq,Ak,Av],0); up=blockdiag_up([Bq,Bk,Bv])
28
+ out[f"{prefix}.{L}.self_attn.qkv_proj.lora_down.weight"]=down.contiguous(); out[f"{prefix}.{L}.self_attn.qkv_proj.lora_up.weight"]=up.contiguous()
29
+ checks.append((up@down, torch.cat([Bq@Aq,Bk@Ak,Bv@Av],0)))
30
+ Ao,Bo=P["o_proj"]; out[f"{prefix}.{L}.self_attn.o_proj.lora_down.weight"]=Ao.contiguous(); out[f"{prefix}.{L}.self_attn.o_proj.lora_up.weight"]=Bo.contiguous()
31
+ Ag,Bg=P["gate_proj"]; Au,Bu=P["up_proj"]
32
+ down=torch.cat([Ag,Au],0); up=blockdiag_up([Bg,Bu])
33
+ out[f"{prefix}.{L}.mlp.gate_up_proj.lora_down.weight"]=down.contiguous(); out[f"{prefix}.{L}.mlp.gate_up_proj.lora_up.weight"]=up.contiguous()
34
+ checks.append((up@down, torch.cat([Bg@Ag,Bu@Au],0)))
35
+ Ad,Bd=P["down_proj"]; out[f"{prefix}.{L}.mlp.down_proj.lora_down.weight"]=Ad.contiguous(); out[f"{prefix}.{L}.mlp.down_proj.lora_up.weight"]=Bd.contiguous()
36
+ maxerr=max((a-b).abs().max().item() for a,b in checks); print(f"fused-vs-separate delta max abs err {maxerr:.2e} over {len(checks)} fused matrices")
37
+ assert maxerr==0.0
38
+ if BRANCH=="nar": # full vae2llm/llm2vae replacements -> weight/bias diffs against the m-a-p base
39
+ snap=glob.glob("/workspace/hf/hub/models--m-a-p--YuE2-3B/snapshots/*")[0]; base={}
40
+ for f in glob.glob(f"{snap}/*.safetensors"):
41
+ with safe_open(f,"pt") as sf:
42
+ for k in sf.keys():
43
+ if k in ("model.vae2llm.weight","model.vae2llm.bias","model.llm2vae.weight","model.llm2vae.bias","vae2llm.weight","vae2llm.bias","llm2vae.weight","llm2vae.bias"): base[k.replace("model.","",1) if k.startswith("model.") else k]=sf.get_tensor(k).float()
44
+ assert len(base)==4, list(base)
45
+ for m in ("vae2llm","llm2vae"):
46
+ out[f"diffusion_model.{m}.diff"]=(ck["io"][m]["weight"].float()-base[f"{m}.weight"]).contiguous(); out[f"diffusion_model.{m}.diff_b"]=(ck["io"][m]["bias"].float()-base[f"{m}.bias"]).contiguous()
47
+ print(f"{m}: weight diff max {out[f'diffusion_model.{m}.diff'].abs().max():.4f} bias diff max {out[f'diffusion_model.{m}.diff_b'].abs().max():.4f}")
48
+ # verify every base key exists in Comfy-Org/YuE2's checkpoint (header only, no download)
49
+ from huggingface_hub import parse_safetensors_file_metadata
50
+ ck_keys=set(parse_safetensors_file_metadata("Comfy-Org/YuE2","checkpoints/yue2_3b_bf16.safetensors").tensors.keys())
51
+ missing=[]
52
+ for k in out:
53
+ base_k=k.rsplit(".",2)[0] if k.endswith((".lora_up.weight",".lora_down.weight")) else k.rsplit(".",1)[0]
54
+ full=("model."+base_k if base_k.startswith("diffusion_model.") else base_k)+".weight"
55
+ if full not in ck_keys: missing.append(full)
56
+ print("all target weights present in Comfy-Org/YuE2 checkpoint:", not missing, missing[:3])
57
+ meta={"format":"pt","yue2_lora_branch":BRANCH,"base_model":"Comfy-Org/YuE2 yue2_3b (m-a-p/YuE2-3B repackaged)","lora_rank_separate":str(R),"scale":"1.0 (no alpha)","layout":"qkv_proj and gate_up_proj are block-diagonal fusions of separate q/k/v and gate/up LoRAs (rank 3r / 2r); up@down == stacked deltas exactly","source":os.path.basename(SRC)}
58
+ save_file({k:v.to(torch.bfloat16) if BRANCH!="nar" or not k.endswith(("diff","diff_b")) else v for k,v in out.items()}, DST, metadata=meta)
59
+ print(f"wrote {DST}: {len(out)} tensors, {os.path.getsize(DST)/2**20:.1f} MB")
checkpoints/YuE2-hum-to-song/scripts/train_hum.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hum->song (prosody-conditioned decoder): prosody-conditioned NAR.
2
+ Condition = VAE latents of a pYIN sine carrier of the vocal (melody + timing, no words/timbre), added to the NAR hidden at layers INJECT via zero-init Linear(64->2048).
3
+ Target = MIX latents (the model writes new vocals over the melody). Tokens = mix-derived (what the AR generates at inference).
4
+ partial-hum rule: with prob PARTIAL_P (eligible clips), keep only PMIN-PMAX s of hum starting LEAD s before the vocal onset, zero elsewhere,
5
+ so a 10-20 s hum at inference still yields a full song. Trainable: NAR LoRA (init joint_v3) + vae2llm/llm2vae + stem_proj.
6
+ usage: train_hum.py <name> <steps> [hum_dropout=0.1]
7
+ env: PREP (hum_prep output dir) INIT_LORA PARTIAL_P PMIN PMAX WIN RANK INJECT LR_STEM OUT_ROOT"""
8
+ import os, sys, glob, json, math, time, random, numpy as np, torch, torch.nn as nn, torch.nn.functional as F
9
+ from torch.utils.checkpoint import checkpoint
10
+ os.environ.setdefault("HF_HOME","/workspace/hf"); torch.backends.cuda.matmul.allow_tf32=True
11
+ from yue2.modeling_yue2 import YuE2ForCausalLM
12
+ from yue2.protocol import CODEC_OFFSET, MUSIC_END
13
+ from yue2.nar import attention as nar_attention
14
+ NAME=sys.argv[1]; STEPS=int(sys.argv[2]); SDROP=float(sys.argv[3]) if len(sys.argv)>3 else 0.1; OUT=os.environ.get("OUT_ROOT","runs")+f"/{NAME}"; os.makedirs(OUT,exist_ok=True); dev="cuda"
15
+ PREP=os.environ.get("PREP","/workspace/hum/prep"); TARGET="mix"; TOKSRC="mix"
16
+ PARTIAL_P=float(os.environ.get("PARTIAL_P","0.5")); PMIN=float(os.environ.get("PMIN","12")); PMAX=float(os.environ.get("PMAX","28")); LEAD=2.0
17
+ INIT_LORA=os.environ.get("INIT_LORA","nar_lora_joint_v4.pt") # the real-audio NAR LoRA; its delta is folded into the base before training (rank differs); WIN=int(os.environ.get('WIN','768')); RANK=int(os.environ.get('RANK','64')); INJ=[int(x) for x in os.environ.get('INJECT','0,7,14,21').split(',')]; LR_LORA=5e-5; LR_IO=2e-5; LR_STEM=float(os.environ.get("LR_STEM","1e-3")); ACC=2
18
+ snap=glob.glob("/workspace/hf/hub/models--m-a-p--YuE2-3B/snapshots/*")[0]
19
+ model=YuE2ForCausalLM.from_pretrained(snap,local_files_only=True,torch_dtype=torch.bfloat16,low_cpu_mem_usage=True).eval().to(dev); model.requires_grad_(False); bb=model.model
20
+ class LoRALinear(nn.Module):
21
+ def __init__(s, base, r):
22
+ super().__init__(); s.base=base; s.A=nn.Parameter(torch.randn(r,base.in_features,device=base.weight.device)*(1/math.sqrt(base.in_features))); s.B=nn.Parameter(torch.zeros(base.out_features,r,device=base.weight.device))
23
+ def forward(s,x): return s.base(x)+((x.float()@s.A.T)@s.B.T).to(x.dtype)
24
+ lora=[]
25
+ for layer in bb.layers:
26
+ for mod,names in ((layer.nar_self_attn,("q_proj","k_proj","v_proj","o_proj")),(layer.nar_mlp,("gate_proj","up_proj","down_proj"))):
27
+ for n in names: l=LoRALinear(getattr(mod,n),RANK); setattr(mod,n,l); lora+=[l.A,l.B]
28
+ model.vae2llm.float(); model.llm2vae.float(); io=list(model.vae2llm.parameters())+list(model.llm2vae.parameters())
29
+ sys.path.insert(0,os.path.dirname(os.path.abspath(__file__))); from ckpt_io import load_ckpt; ck=load_ckpt(INIT_LORA,dev)
30
+ with torch.no_grad():
31
+ if ck.get('rank',32)==RANK:
32
+ for p,v in zip(lora,ck['lora']): p.copy_(v.to(dev))
33
+ else: # rank differs from joint_v3: fold the joint_v3 delta into the base weights so the new LoRA starts from the adapted decoder
34
+ it=iter(ck['lora'])
35
+ for layer in bb.layers:
36
+ for mod,names in ((layer.nar_self_attn,('q_proj','k_proj','v_proj','o_proj')),(layer.nar_mlp,('gate_proj','up_proj','down_proj'))):
37
+ for n in names: A=next(it).to(dev).float(); B=next(it).to(dev).float(); getattr(mod,n).base.weight.add_((B@A).to(getattr(mod,n).base.weight.dtype))
38
+ print('joint_v3 NAR delta folded into base; fresh rank',RANK,'LoRA',flush=True)
39
+ model.vae2llm.load_state_dict({k:v.float() for k,v in ck["io"]["vae2llm"].items()}); model.llm2vae.load_state_dict({k:v.float() for k,v in ck["io"]["llm2vae"].items()})
40
+ stem_proj=nn.ModuleList([nn.Linear(64,model.config.hidden_size) for _ in INJ]).to(dev)
41
+ for m_ in stem_proj: nn.init.zeros_(m_.weight); nn.init.zeros_(m_.bias)
42
+ for p in lora+io: p.requires_grad_(True)
43
+ opt=torch.optim.AdamW([{"params":lora,"lr":LR_LORA},{"params":io,"lr":LR_IO},{"params":stem_proj.parameters(),"lr":LR_STEM}],weight_decay=0.0,betas=(0.9,0.95)); base_lrs=[g["lr"] for g in opt.param_groups]
44
+ items=[]
45
+ for f in sorted(glob.glob(f"{PREP}/*.npz")): # hum_prep.py output: hum, mix, tokmix, prefix, onset_s, sing_s (+ <id>.json with held flag)
46
+ if not os.path.exists(f[:-4]+".json"): continue
47
+ m=json.load(open(f[:-4]+".json")); h=np.load(f)
48
+ n=min(len(h["mix"]),len(h["hum"]),len(h["tokmix"]))
49
+ items.append(dict(id=m["id"],held=m["held"],mix=h["mix"][:n],voc=h["hum"][:n].astype(np.float32),tok=h["tokmix"][:n].astype(np.int64),prefix=[int(v) for v in h["prefix"]],onset=float(h["onset_s"]),sing=float(h["sing_s"])))
50
+ train=[x for x in items if not x["held"]]; val=[x for x in items if x["held"]]
51
+ elig=lambda x: x["onset"]>=0 and x["sing"]>=PMIN
52
+ print(f"{NAME}: train {len(train)} val {len(val)} clips | target {TARGET} | cond hum (sine latents) | tokens {TOKSRC} | hum dropout {SDROP} | stem lr {LR_STEM}",flush=True)
53
+ print(f"{NAME}: partial-hum eligible {sum(map(elig,train))}/{len(train)} train clips (p={PARTIAL_P}, {PMIN:.0f}-{PMAX:.0f}s from onset-{LEAD:.0f}s)",flush=True)
54
+ def ar_layer(layer,x,cos_,sin_):
55
+ q,k,v=layer.self_attn.project_qkv(layer.input_layernorm(x),cos_,sin_); h=nar_attention(q[0],k[0],v[0],causal=True)
56
+ x=x+layer.self_attn.o_proj(h.flatten(1)[None]); return x+layer.mlp(layer.post_attention_layernorm(x)),k[0],v[0]
57
+ def nar_layer(layer,h,ak,av,ncos,nsin):
58
+ q,k,v=layer.nar_self_attn.project_qkv(layer.nar_input_layernorm(h),ncos,nsin); a=nar_attention(q[0],torch.cat((ak,k[0])),torch.cat((av,v[0])))
59
+ h=h+layer.nar_self_attn.o_proj(a.flatten(1)[None]); return h+layer.nar_mlp(layer.nar_pre_mlp_layernorm(h))
60
+ def flow_loss(prefix,codec,x1,voc,t,noise,grad=True):
61
+ with torch.no_grad():
62
+ ar=torch.tensor([prefix+[int(c)+CODEC_OFFSET for c in codec]+[MUSIC_END]],device=dev); Lq=ar.shape[1]; cos_,sin_=bb.rotary_emb(torch.arange(Lq,device=dev)[None]); x=bb.embed_tokens(ar); cache=[]
63
+ for layer in bb.layers: x,k,v=ar_layer(layer,x,cos_,sin_); cache.append((k,v))
64
+ T=len(codec); xt=t*noise+(1-t)*x1; target=noise-x1; N=T+2; ncos,nsin=bb.rotary_emb(torch.arange(Lq,Lq+N,device=dev)[None])
65
+ pe=model.latent_pos_embed(torch.arange(N,device=dev).clamp(max=model.config.max_latent_frames-1))[None]; sh=model._shift_t_value(float(np.clip(np.log(t/(1-t)),-20,20)),dev,torch.bfloat16)
66
+ vp=F.pad(voc,(0,0,1,1))[None].float(); sh_all={k:stem_proj[i](vp).to(torch.bfloat16) for i,k in enumerate(INJ)}
67
+ h=(model.vae2llm(F.pad(xt,(0,0,1,1))[None].float())).to(torch.bfloat16)+sh_all[0]+model.time_embedder(sh.expand(N))[None]+pe
68
+ for li,(layer,(ak,av)) in enumerate(zip(bb.layers,cache)):
69
+ if li in sh_all and li>0: h=h+sh_all[li]
70
+ h=checkpoint(nar_layer,layer,h,ak,av,ncos,nsin,use_reentrant=False) if grad else nar_layer(layer,h,ak,av,ncos,nsin)
71
+ return F.mse_loss(model.llm2vae(bb.norm(h)[0,1:-1].float()),target)
72
+ def window(it,s=None):
73
+ n=len(it["mix"]); s=random.randint(0,max(0,n-WIN)) if s is None else s; return it["tok"][s:s+WIN],torch.tensor(it["mix"][s:s+WIN],device=dev),torch.tensor(it["voc"][s:s+WIN],device=dev)
74
+ def partial_cond(it, L=None):
75
+ """partial-hum rule: keep only PMIN-PMAX s of hum starting LEAD s before the vocal onset; zero elsewhere. -> (cond [n,64], start_frame, len_frames)"""
76
+ n=len(it["mix"]); L=random.uniform(PMIN,PMAX) if L is None else L; L=min(L,it["sing"]+LEAD); sf=int(max(0.0,it["onset"]-LEAD)*25); Lf=max(1,min(int(L*25),n-sf))
77
+ cond=np.zeros_like(it["voc"]); cond[sf:sf+Lf]=it["voc"][sf:sf+Lf]; return cond,sf,Lf
78
+ def window_partial(it):
79
+ cond,sf,Lf=partial_cond(it); n=len(it["mix"])
80
+ if random.random()<0.6: lo=max(0,sf+Lf-WIN); hi=max(lo,min(sf,max(0,n-WIN))); s=random.randint(lo,hi) # window overlaps the hum (sees its start/end and the handoff)
81
+ else: s=random.randint(0,max(0,n-WIN)) # anywhere: mostly hum-free continuation
82
+ return it["tok"][s:s+WIN],torch.tensor(it["mix"][s:s+WIN],device=dev),torch.tensor(cond[s:s+WIN],device=dev)
83
+ @torch.no_grad()
84
+ def evaluate():
85
+ tot=tot0=totp=0; g=torch.Generator(device="cpu").manual_seed(123); k=kp=0
86
+ for it in val[:6]:
87
+ n=len(it["mix"]); c,z,v=window(it,max(0,(n-WIN)//2)); noise=torch.randn(len(c),64,generator=g).to(dev)
88
+ for t in (0.2,0.5,0.8):
89
+ tot+=flow_loss(it["prefix"],c,z,v,t,noise,grad=False).item(); tot0+=flow_loss(it["prefix"],c,z,torch.zeros_like(v),t,noise,grad=False).item(); k+=1
90
+ if elig(it): # partial: fixed 20 s hum from onset-2 s, window anchored at the hum start (covers hum + continuation)
91
+ cond,sf,Lf=partial_cond(it,20.0); s0=min(sf,max(0,n-WIN)); cp=it["tok"][s0:s0+WIN]; zp=torch.tensor(it["mix"][s0:s0+WIN],device=dev); vp=torch.tensor(cond[s0:s0+WIN],device=dev); noisep=torch.randn(len(cp),64,generator=g).to(dev)
92
+ for t in (0.2,0.5,0.8): totp+=flow_loss(it["prefix"],cp,zp,vp,t,noisep,grad=False).item(); kp+=1
93
+ return tot/k, tot0/k, (totp/kp if kp else float("nan"))
94
+ def save(path): torch.save({"lora":[p.detach().cpu() for p in lora],"io":{"vae2llm":model.vae2llm.state_dict(),"llm2vae":model.llm2vae.state_dict()},"stem_proj":stem_proj.state_dict(),"inject":INJ,"rank":RANK,"folded_init":INIT_LORA,
95
+ "condition":"hum_sine_latents","tokens":TOKSRC,"partial_p":PARTIAL_P,"partial_range_s":[PMIN,PMAX],"lead_s":LEAD},path)
96
+ e,e0,ep=evaluate(); msg=f"EVAL step 0 with_hum {e:.4f} no_hum {e0:.4f} partial_hum {ep:.4f}"; print(msg,flush=True); log=open(f"{OUT}/train.log","a"); log.write(msg+"\n"); log.flush(); best=e; t0=time.time(); npart=0
97
+ for st in range(1,STEPS+1):
98
+ mult=min(1,st/50)*(0.2+0.8*0.5*(1+math.cos(math.pi*st/STEPS)))
99
+ for g_,b in zip(opt.param_groups,base_lrs): g_["lr"]=b*mult
100
+ for _ in range(ACC):
101
+ it=random.choice(train); part=elig(it) and random.random()<PARTIAL_P; npart+=part
102
+ c,z,v=window_partial(it) if part else window(it); t=float(np.clip(np.random.beta(2,2),0.02,0.98)); noise=torch.randn(len(c),64,device=dev)
103
+ if random.random()<SDROP: v=torch.zeros_like(v)
104
+ loss=flow_loss(it["prefix"],c,z,v,t,noise)/ACC; loss.backward()
105
+ torch.nn.utils.clip_grad_norm_(lora+io+list(stem_proj.parameters()),1.0); opt.step(); opt.zero_grad(set_to_none=True)
106
+ if st<=3 or st%25==0: print(f"step {st} loss {loss.item()*ACC:.4f} partial_frac {npart/(st*ACC):.2f} {time.time()-t0:.0f}s mem {torch.cuda.max_memory_allocated()/2**30:.1f}G",flush=True)
107
+ if st%100==0 or st==STEPS:
108
+ e,e0,ep=evaluate(); msg=f"EVAL step {st} with_hum {e:.4f} no_hum {e0:.4f} partial_hum {ep:.4f} {time.time()-t0:.0f}s"; print(msg,flush=True); log.write(msg+"\n"); log.flush()
109
+ if e<best: best=e; save(f"{OUT}/best.pt")
110
+ save(f"{OUT}/last.pt")
111
+ if st%500==0: save(f"{OUT}/step-{st}.pt")
112
+ print(f"RESULT {NAME}: best with_hum {best:.4f}",flush=True)