InsiderX-Pro commited on
Commit
9979f26
·
verified ·
1 Parent(s): 70fca58

Release OmniVoice Burmese checkpoint-200 with inference guide

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* 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
 
 
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
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
COMPLETE.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "adapter_backend": "local_experiment_peft",
3
+ "base_model": "k2-fsa/OmniVoice",
4
+ "base_model_sha256": "730839316de585f4c8298ec0e1712efc10fb19c6fa4e36eb741cb8d51ebcf6aa",
5
+ "checkpoint_kind": "model-only",
6
+ "experiment_id": "P2_TESTSET_FT_OMNI_COMMON400_W050_E1",
7
+ "format_version": 1,
8
+ "inference_ready_with_referenced_base": true,
9
+ "metrics": {
10
+ "anchor_kl": 0.0,
11
+ "anchor_tokens": 0,
12
+ "non_target_kl": 0.0,
13
+ "non_target_tokens": 0,
14
+ "recovery_used": false,
15
+ "recovery_visible_tokens": 0,
16
+ "replay": 0.0,
17
+ "replay_tokens": 0,
18
+ "target_ce": 6.36165189743042,
19
+ "target_objective": {
20
+ "anchor_kl_weight": 0.0,
21
+ "checkpoint_kl_chunks": true,
22
+ "codebook_weights": [
23
+ 8.0,
24
+ 8.0,
25
+ 6.0,
26
+ 6.0,
27
+ 4.0,
28
+ 4.0,
29
+ 2.0,
30
+ 2.0
31
+ ],
32
+ "kl_chunk_tokens": 256,
33
+ "non_target_kl_weight": 0.0,
34
+ "prompt_guard_tokens": 0,
35
+ "recovery_probability": 0.0,
36
+ "recovery_visible_ratio_max": 0.5,
37
+ "recovery_visible_ratio_min": 0.25,
38
+ "replay_weight": 1.0,
39
+ "student_eval_mode": true,
40
+ "target_ce_weight": 0.5,
41
+ "temperature": 2.0
42
+ },
43
+ "target_tokens": 2832,
44
+ "teacher_batches": 0,
45
+ "total": 3.18082594871521
46
+ },
47
+ "model_only": true,
48
+ "optimizer_saved": false,
49
+ "run_id": "untracked",
50
+ "run_steps": 200,
51
+ "scheduler_total_steps": 200,
52
+ "step": 200
53
+ }
README.md ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - my
4
+ pipeline_tag: text-to-speech
5
+ base_model: k2-fsa/OmniVoice
6
+ tags:
7
+ - omnivoice
8
+ - lora
9
+ - voice-cloning
10
+ - low-resource-tts
11
+ ---
12
+
13
+ # S2R-Adaptation-TTS · OmniVoice Burmese
14
+
15
+ [Project page](https://insiderx-pro.github.io/S2R-Adaptation-TTS/) ·
16
+ [Paper PDF](https://insiderx-pro.github.io/S2R-Adaptation-TTS/assets/paper.pdf) ·
17
+ [GitHub](https://github.com/InsiderX-Pro/S2R-Adaptation-TTS)
18
+
19
+ Native routed LoRA weights from **`omni_common400/checkpoint-200`**.
20
+ The tensor file is copied unchanged from the requested checkpoint.
21
+
22
+ ## What this checkpoint contains
23
+
24
+ | Property | Value |
25
+ |---|---|
26
+ | Base | `k2-fsa/OmniVoice` |
27
+ | Language | Burmese |
28
+ | Format | Native routed LoRA; not a standard Hugging Face PEFT adapter |
29
+ | LoRA | Rank 8, alpha 16, dropout 0.05; 28 transformer layers |
30
+ | Routing | `text_prediction`, including an audio-head delta |
31
+ | Continuation | One epoch on Common400: 400 rows / 150 unique target recordings |
32
+ | Updates | 200 steps; seed 7; learning rate 2e-7; accumulation 2 |
33
+ | Objective | Uniform target CE weight 0.5 |
34
+ | Training reference | First up to 3 seconds of the target recording |
35
+
36
+ **Evaluation scope:** this checkpoint has been trained on Common400. Scores on
37
+ Common400 are in-sample and must not be presented as held-out performance.
38
+ It is separate from the paper's cubic S→R main-result checkpoints; the paper's
39
+ 6.85% CER and 4.51 MOS are not asserted for this artifact.
40
+
41
+ ## Download and run
42
+
43
+ Use Python 3.12 with a compatible PyTorch installation. Install the upstream
44
+ OmniVoice 0.1.5 inference package and Hugging Face client:
45
+
46
+ ```bash
47
+ pip install omnivoice==0.1.5 huggingface_hub soundfile accelerate
48
+ hf download InsiderX-Pro/S2R-Adaptation-TTS --local-dir s2r-omnivoice
49
+ cd s2r-omnivoice
50
+ python inference.py \
51
+ --text "သင် မင်္ဂလာပါ။" \
52
+ --ref-audio /path/to/reference.wav \
53
+ --ref-text "The exact transcript of your reference recording." \
54
+ --output output.wav
55
+ ```
56
+
57
+ Replace the text and reference inputs with your own. The reference transcript
58
+ must match the supplied recording. Use `--device cpu` if CUDA is unavailable.
59
+ Use `--base-dir /path/to/OmniVoice` to reuse a local base-model directory.
60
+
61
+ The loader downloads the base at revision
62
+ `c5fdb5ccb189668d56333f77ba2629f4cd7535f4` and verifies its weight SHA-256:
63
+ `730839316de585f4c8298ec0e1712efc10fb19c6fa4e36eb741cb8d51ebcf6aa`.
64
+ It restores the native adapter and installs per-forward text/prediction routing.
65
+ Loading only `adapter_model.safetensors` with a generic PEFT loader is insufficient.
66
+ The base and its audio codec are separate downloads; they are not duplicated here.
67
+
68
+ ## Files and provenance
69
+
70
+ - `adapter_model.safetensors`: original adapter tensors.
71
+ - `peft_config.json`: native adapter specification, with a portable base identifier.
72
+ - `tokenizer.json`, `tokenizer_config.json`, `chat_template.jinja`: checkpoint tokenizer assets.
73
+ - `inference.py`, `native_adapter/`: loading and routing helpers from the project.
74
+ - `training_recipe.json`: relevant continuation settings without server-specific paths.
75
+ - `COMPLETE.json`, `snapshot.json`: completion metadata with a portable base identifier.
76
+ - `source_checksums.json`: original checkpoint file sizes and SHA-256 digests.
77
+
78
+ No training recordings, evaluation audio, transcripts, credentials or optimizer
79
+ state are included. Original run configurations contain stale inherited experiment
80
+ labels and local paths; the curated training recipe records this continuation.
81
+ Base-model licenses apply separately. No additional blanket license is declared
82
+ for the project-specific adapter or helpers in this upload.
83
+
84
+ ## Citation
85
+
86
+ ```bibtex
87
+ @unpublished{lu2026reliable,
88
+ title = {From Reliable Text to Real Voices: Trust-Aware Progressive Adaptation for Low-Resource TTS},
89
+ author = {Lu, Jiayi and Geng, Yizhong and Yang, Jinghan and Jiang, Tianhan and An, Boxun and Gao, Yingming and Li, Ya},
90
+ year = {2026},
91
+ note = {Manuscript}
92
+ }
93
+ ```
94
+
95
+ The arXiv entry is pending. Use the project page for the current manuscript and
96
+ the paper's experimental results.
adapter_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1084cea52a8e9f5cb4fc9e4ef85c3be43e10181a9305d37cd63ad59282fbf81b
3
+ size 53816712
chat_template.jinja ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {{- messages[0].content + '\n\n' }}
5
+ {%- endif %}
6
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
7
+ {%- for tool in tools %}
8
+ {{- "\n" }}
9
+ {{- tool | tojson }}
10
+ {%- endfor %}
11
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
12
+ {%- else %}
13
+ {%- if messages[0].role == 'system' %}
14
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
15
+ {%- endif %}
16
+ {%- endif %}
17
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
18
+ {%- for message in messages[::-1] %}
19
+ {%- set index = (messages|length - 1) - loop.index0 %}
20
+ {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
21
+ {%- set ns.multi_step_tool = false %}
22
+ {%- set ns.last_query_index = index %}
23
+ {%- endif %}
24
+ {%- endfor %}
25
+ {%- for message in messages %}
26
+ {%- if message.content is string %}
27
+ {%- set content = message.content %}
28
+ {%- else %}
29
+ {%- set content = '' %}
30
+ {%- endif %}
31
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
32
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
33
+ {%- elif message.role == "assistant" %}
34
+ {%- set reasoning_content = '' %}
35
+ {%- if message.reasoning_content is string %}
36
+ {%- set reasoning_content = message.reasoning_content %}
37
+ {%- else %}
38
+ {%- if '</think>' in content %}
39
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
40
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
41
+ {%- endif %}
42
+ {%- endif %}
43
+ {%- if loop.index0 > ns.last_query_index %}
44
+ {%- if loop.last or (not loop.last and reasoning_content) %}
45
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
46
+ {%- else %}
47
+ {{- '<|im_start|>' + message.role + '\n' + content }}
48
+ {%- endif %}
49
+ {%- else %}
50
+ {{- '<|im_start|>' + message.role + '\n' + content }}
51
+ {%- endif %}
52
+ {%- if message.tool_calls %}
53
+ {%- for tool_call in message.tool_calls %}
54
+ {%- if (loop.first and content) or (not loop.first) %}
55
+ {{- '\n' }}
56
+ {%- endif %}
57
+ {%- if tool_call.function %}
58
+ {%- set tool_call = tool_call.function %}
59
+ {%- endif %}
60
+ {{- '<tool_call>\n{"name": "' }}
61
+ {{- tool_call.name }}
62
+ {{- '", "arguments": ' }}
63
+ {%- if tool_call.arguments is string %}
64
+ {{- tool_call.arguments }}
65
+ {%- else %}
66
+ {{- tool_call.arguments | tojson }}
67
+ {%- endif %}
68
+ {{- '}\n</tool_call>' }}
69
+ {%- endfor %}
70
+ {%- endif %}
71
+ {{- '<|im_end|>\n' }}
72
+ {%- elif message.role == "tool" %}
73
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
74
+ {{- '<|im_start|>user' }}
75
+ {%- endif %}
76
+ {{- '\n<tool_response>\n' }}
77
+ {{- content }}
78
+ {{- '\n</tool_response>' }}
79
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
80
+ {{- '<|im_end|>\n' }}
81
+ {%- endif %}
82
+ {%- endif %}
83
+ {%- endfor %}
84
+ {%- if add_generation_prompt %}
85
+ {{- '<|im_start|>assistant\n' }}
86
+ {%- if enable_thinking is defined and enable_thinking is false %}
87
+ {{- '<think>\n\n</think>\n\n' }}
88
+ {%- endif %}
89
+ {%- endif %}
inference.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load the native routed OmniVoice adapter and synthesize with a reference."""
2
+ from pathlib import Path
3
+ from types import MethodType
4
+ import argparse
5
+ import hashlib
6
+ import torch
7
+ from native_adapter import load_adapter_checkpoint, inference_routing_mask, set_routing_mask
8
+
9
+ BASE_REPO = 'k2-fsa/OmniVoice'
10
+ BASE_REVISION = 'c5fdb5ccb189668d56333f77ba2629f4cd7535f4'
11
+ BASE_SHA256 = '730839316de585f4c8298ec0e1712efc10fb19c6fa4e36eb741cb8d51ebcf6aa'
12
+
13
+ def install_routing(model):
14
+ routing = model._local_peft_spec.routing
15
+ original_forward = model.forward
16
+ def routed_forward(this, *args, **kwargs):
17
+ ids = kwargs.get('input_ids', args[0] if args else None)
18
+ mask = kwargs.get('audio_mask', args[1] if len(args) > 1 else None)
19
+ if not isinstance(ids, torch.Tensor) or not isinstance(mask, torch.Tensor):
20
+ raise TypeError('Routed inference requires input_ids and audio_mask tensors')
21
+ route = inference_routing_mask(routing=routing, input_ids=ids,
22
+ audio_mask=mask, audio_mask_id=this.config.audio_mask_id,
23
+ attention_mask=kwargs.get('attention_mask'))
24
+ set_routing_mask(this, route)
25
+ return original_forward(*args, **kwargs)
26
+ model.forward = MethodType(routed_forward, model)
27
+ return model
28
+
29
+ def load_model(adapter_dir=None, base_dir=None, device='cuda', dtype=None):
30
+ from huggingface_hub import snapshot_download
31
+ from omnivoice.models.omnivoice import OmniVoice
32
+ adapter_dir = Path(adapter_dir or Path(__file__).parent)
33
+ base_dir = Path(base_dir or snapshot_download(BASE_REPO, revision=BASE_REVISION))
34
+ weights = base_dir/'model.safetensors'
35
+ with weights.open('rb') as stream:
36
+ digest = hashlib.file_digest(stream, 'sha256').hexdigest()
37
+ if digest != BASE_SHA256:
38
+ raise ValueError('Base weights do not match the checkpoint training base')
39
+ dtype = dtype or (torch.float16 if str(device).startswith('cuda') else torch.float32)
40
+ model = OmniVoice.from_pretrained(str(base_dir), device_map=device,
41
+ dtype=dtype, attn_implementation='sdpa')
42
+ load_adapter_checkpoint(model, adapter_dir, trainable=False)
43
+ return install_routing(model).eval()
44
+
45
+ def main():
46
+ import soundfile as sf
47
+ parser=argparse.ArgumentParser(description=__doc__)
48
+ parser.add_argument('--text', required=True)
49
+ parser.add_argument('--ref-audio', required=True)
50
+ parser.add_argument('--ref-text', required=True)
51
+ parser.add_argument('--output', default='output.wav')
52
+ parser.add_argument('--base-dir')
53
+ parser.add_argument('--device', default='cuda')
54
+ args=parser.parse_args()
55
+ torch.manual_seed(42)
56
+ model=load_model(base_dir=args.base_dir,device=args.device)
57
+ with torch.inference_mode():
58
+ audio=model.generate(text=args.text, language='Burmese',
59
+ ref_audio=args.ref_audio, ref_text=args.ref_text)[0]
60
+ sf.write(args.output,audio,model.sampling_rate)
61
+
62
+ if __name__=='__main__':
63
+ main()
native_adapter/__init__.py ADDED
@@ -0,0 +1,883 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dependency-free vanilla LoRA and LoRA-Null adapters for OmniVoice.
2
+
3
+ The module names are intentionally checked against the local OmniVoice/Qwen3
4
+ checkout. A changed upstream architecture fails closed instead of silently
5
+ training the wrong parameters.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import math
12
+ from dataclasses import asdict, dataclass
13
+ from pathlib import Path
14
+ from typing import Any, Iterable
15
+
16
+ import torch
17
+ from safetensors.torch import load_file, save_file
18
+ from torch import nn
19
+ from torch.nn import functional as F
20
+
21
+ from .loranull.basis_cache import load_basis_cache
22
+ from .loranull.math import factor_projected_weight, projected_factor_relative_error
23
+
24
+
25
+ ADAPTER_FILE = "adapter_model.safetensors"
26
+ PEFT_CONFIG_FILE = "peft_config.json"
27
+ AUDIT_FILE = "trainable_audit.json"
28
+ COMPLETE_FILE = "COMPLETE.json"
29
+ TARGET_PROJECTIONS = ("q_proj", "k_proj", "v_proj", "o_proj")
30
+ MLP_PROJECTIONS = ("gate_proj", "up_proj", "down_proj")
31
+ ROOT_PROJECTIONS = (
32
+ "audio_heads", "audio_embeddings_delta", "audio_heads_delta", "text_embeddings"
33
+ )
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class PeftSpec:
38
+ experiment_id: str
39
+ strategy: str
40
+ base_model: str
41
+ rank: int | None = None
42
+ alpha: float | None = None
43
+ dropout: float = 0.0
44
+ target_modules: tuple[str, ...] = TARGET_PROJECTIONS
45
+ layer_indices: tuple[int, ...] = tuple(range(28))
46
+ adapter_layers: int | None = None
47
+ bottleneck: int | None = None
48
+ routing: str = "none"
49
+ initialization: str = "vanilla"
50
+ null_basis_path: str | None = None
51
+ null_basis_sha256: str | None = None
52
+ base_model_sha256: str | None = None
53
+ null_init_scale: float = 1.0
54
+ freeze_a: bool = False
55
+ hard_project_a: bool = False
56
+
57
+ def validate(self) -> None:
58
+ if self.strategy == "lora":
59
+ if not self.experiment_id.lower().startswith("p2"):
60
+ raise ValueError("phase-2 LoRA experiment IDs must start with P2")
61
+ if self.rank is None or self.rank <= 0 or self.alpha is None or self.alpha <= 0:
62
+ raise ValueError("LoRA rank and alpha must be positive")
63
+ if not 0 <= self.dropout < 1:
64
+ raise ValueError("LoRA dropout must be in [0, 1)")
65
+ if not self.target_modules or not set(self.target_modules).issubset(
66
+ set(TARGET_PROJECTIONS) | set(MLP_PROJECTIONS) | set(ROOT_PROJECTIONS)
67
+ ):
68
+ raise ValueError(f"unsupported LoRA targets: {self.target_modules}")
69
+ if not self.layer_indices or len(set(self.layer_indices)) != len(self.layer_indices):
70
+ raise ValueError("layer_indices must be non-empty and unique")
71
+ if min(self.layer_indices) < 0 or max(self.layer_indices) >= 28:
72
+ raise ValueError("layer_indices must be within [0, 27]")
73
+ if self.routing not in {
74
+ "none", "prediction", "text_only", "text_prediction", "target_region"
75
+ }:
76
+ raise ValueError(f"unsupported LoRA routing mode: {self.routing}")
77
+ if self.initialization not in {"vanilla", "lora_null"}:
78
+ raise ValueError(f"unsupported LoRA initialization: {self.initialization}")
79
+ if self.initialization == "lora_null":
80
+ if not self.null_basis_path:
81
+ raise ValueError("LoRA-Null requires null_basis_path")
82
+ if not self.null_basis_sha256 or len(self.null_basis_sha256) != 64:
83
+ raise ValueError("LoRA-Null requires a 64-character basis SHA-256")
84
+ if not self.base_model_sha256 or len(self.base_model_sha256) != 64:
85
+ raise ValueError("LoRA-Null requires the base model SHA-256")
86
+ if self.null_init_scale < 0:
87
+ raise ValueError("null_init_scale must be non-negative")
88
+ if "text_embeddings" in self.target_modules:
89
+ raise ValueError("LoRA-Null currently supports Linear targets, not embeddings")
90
+ if self.freeze_a and self.hard_project_a:
91
+ raise ValueError("freeze_a and hard_project_a are mutually exclusive")
92
+ elif self.freeze_a or self.hard_project_a:
93
+ raise ValueError(
94
+ "freeze_a and hard_project_a are only defined for lora_null initialization"
95
+ )
96
+ elif self.strategy == "residual_adapter":
97
+ if self.experiment_id.lower() != "e5":
98
+ raise ValueError("Residual adapters are reserved for experiment E5")
99
+ if (self.adapter_layers, self.bottleneck) != (4, 64):
100
+ raise ValueError("E5 requires the final 4 blocks and bottleneck=64")
101
+ else:
102
+ raise ValueError(f"Unsupported PEFT strategy: {self.strategy}")
103
+
104
+ @classmethod
105
+ def from_dict(cls, value: dict[str, Any]) -> "PeftSpec":
106
+ value = dict(value)
107
+ if "target_modules" in value:
108
+ value["target_modules"] = tuple(value["target_modules"])
109
+ if "layer_indices" in value:
110
+ value["layer_indices"] = tuple(int(item) for item in value["layer_indices"])
111
+ spec = cls(**value)
112
+ spec.validate()
113
+ return spec
114
+
115
+ def to_dict(self) -> dict[str, Any]:
116
+ value = asdict(self)
117
+ value["target_modules"] = list(self.target_modules)
118
+ value["layer_indices"] = list(self.layer_indices)
119
+ return value
120
+
121
+
122
+ class LoRALinear(nn.Module):
123
+ """Frozen Linear plus a trainable low-rank delta."""
124
+
125
+ def __init__(
126
+ self,
127
+ base_layer: nn.Linear,
128
+ rank: int,
129
+ alpha: float,
130
+ dropout: float,
131
+ routing: str = "none",
132
+ ):
133
+ super().__init__()
134
+ if rank <= 0:
135
+ raise ValueError("LoRA rank must be positive")
136
+ self.base_layer = base_layer
137
+ self.rank = rank
138
+ self.alpha = float(alpha)
139
+ self.scaling = self.alpha / rank
140
+ self.dropout = nn.Dropout(dropout)
141
+ self.routing = routing
142
+ self.route_mask: torch.Tensor | None = None
143
+ factory = {"device": base_layer.weight.device, "dtype": base_layer.weight.dtype}
144
+ self.lora_A = nn.Linear(base_layer.in_features, rank, bias=False, **factory)
145
+ self.lora_B = nn.Linear(rank, base_layer.out_features, bias=False, **factory)
146
+ nn.init.kaiming_uniform_(self.lora_A.weight, a=math.sqrt(5))
147
+ nn.init.zeros_(self.lora_B.weight)
148
+ for parameter in self.base_layer.parameters():
149
+ parameter.requires_grad = False
150
+
151
+ @property
152
+ def in_features(self) -> int:
153
+ return self.base_layer.in_features
154
+
155
+ @property
156
+ def out_features(self) -> int:
157
+ return self.base_layer.out_features
158
+
159
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
160
+ base = self.base_layer(inputs)
161
+ if self.scaling == 0.0:
162
+ return base
163
+ delta = self.lora_B(self.lora_A(self.dropout(inputs))) * self.scaling
164
+ if self.routing != "none":
165
+ if self.route_mask is None:
166
+ raise RuntimeError(f"LoRA route mask is unset for routing={self.routing}")
167
+ expected = inputs.shape[:-1]
168
+ if tuple(self.route_mask.shape) != tuple(expected):
169
+ raise ValueError(
170
+ f"LoRA route mask shape {tuple(self.route_mask.shape)} != {tuple(expected)}"
171
+ )
172
+ delta = delta * self.route_mask.to(device=delta.device, dtype=delta.dtype).unsqueeze(-1)
173
+ return base + delta
174
+
175
+
176
+ class LoRANullLinear(LoRALinear):
177
+ """Centered LoRA-Null branch that leaves the frozen base weight untouched.
178
+
179
+ The forward delta is ``s * (B_t A_t - B_0 A_0) x``. Both terms receive the
180
+ same dropout realization, so initialization is a numerical no-op. This is
181
+ equivalent to the paper's residual-base construction without mutating the
182
+ base checkpoint.
183
+ """
184
+
185
+ def __init__(
186
+ self,
187
+ base_layer: nn.Linear,
188
+ rank: int,
189
+ alpha: float,
190
+ dropout: float,
191
+ null_basis: torch.Tensor,
192
+ *,
193
+ init_scale: float = 1.0,
194
+ freeze_a: bool = False,
195
+ routing: str = "none",
196
+ ) -> None:
197
+ super().__init__(base_layer, rank, alpha, dropout, routing=routing)
198
+ b_weight, a_weight = factor_projected_weight(
199
+ base_layer.weight,
200
+ null_basis,
201
+ scaling=self.scaling,
202
+ init_scale=init_scale,
203
+ )
204
+ factory_dtype = base_layer.weight.dtype
205
+ factory_device = base_layer.weight.device
206
+ with torch.no_grad():
207
+ self.lora_A.weight.copy_(a_weight.to(device=factory_device, dtype=factory_dtype))
208
+ self.lora_B.weight.copy_(b_weight.to(device=factory_device, dtype=factory_dtype))
209
+ self.register_buffer("anchor_A", self.lora_A.weight.detach().clone(), persistent=True)
210
+ self.register_buffer("anchor_B", self.lora_B.weight.detach().clone(), persistent=True)
211
+ self.register_buffer(
212
+ "projection_basis",
213
+ null_basis.detach().to(device=factory_device, dtype=torch.float32).clone(),
214
+ persistent=False,
215
+ )
216
+ self.init_scale = float(init_scale)
217
+ self.freeze_a = bool(freeze_a)
218
+ self.lora_A.weight.requires_grad = not self.freeze_a
219
+ self.initialization_relative_error = projected_factor_relative_error(
220
+ base_layer.weight,
221
+ null_basis,
222
+ self.anchor_B,
223
+ self.anchor_A,
224
+ scaling=self.scaling,
225
+ init_scale=self.init_scale,
226
+ )
227
+ if self.initialization_relative_error > 5e-4:
228
+ raise RuntimeError(
229
+ "LoRA-Null projected-weight factorization failed: "
230
+ f"relative_error={self.initialization_relative_error:.3e}"
231
+ )
232
+
233
+ @torch.no_grad()
234
+ def project_lora_a_(self) -> dict[str, float]:
235
+ """Project trainable A rows back into the calibrated input subspace."""
236
+ current = self.lora_A.weight.detach().float()
237
+ basis = self.projection_basis.to(device=current.device, dtype=torch.float32)
238
+ projected = (current @ basis) @ basis.mT
239
+ total = float(current.square().sum().item())
240
+ outside = float((current - projected).square().sum().item())
241
+ self.lora_A.weight.copy_(projected.to(dtype=self.lora_A.weight.dtype))
242
+ after = self.lora_A.weight.detach().float()
243
+ after_projected = (after @ basis) @ basis.mT
244
+ outside_after = float((after - after_projected).square().sum().item())
245
+ return {
246
+ "total_energy_before": total,
247
+ "outside_energy_before": outside,
248
+ "outside_energy_after": outside_after,
249
+ }
250
+
251
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
252
+ base = self.base_layer(inputs)
253
+ if self.scaling == 0.0:
254
+ return base
255
+ adapted_inputs = self.dropout(inputs)
256
+ current = self.lora_B(self.lora_A(adapted_inputs))
257
+ anchor = F.linear(F.linear(adapted_inputs, self.anchor_A), self.anchor_B)
258
+ delta = (current - anchor) * self.scaling
259
+ if self.routing != "none":
260
+ if self.route_mask is None:
261
+ raise RuntimeError(f"LoRA route mask is unset for routing={self.routing}")
262
+ expected = inputs.shape[:-1]
263
+ if tuple(self.route_mask.shape) != tuple(expected):
264
+ raise ValueError(
265
+ f"LoRA route mask shape {tuple(self.route_mask.shape)} != {tuple(expected)}"
266
+ )
267
+ delta = delta * self.route_mask.to(device=delta.device, dtype=delta.dtype).unsqueeze(-1)
268
+ return base + delta
269
+
270
+ def merged_weight(self) -> torch.Tensor:
271
+ """Return ``W0 + s * (BtAt - B0A0)`` without changing the module."""
272
+
273
+ current = self.lora_B.weight @ self.lora_A.weight
274
+ anchor = self.anchor_B @ self.anchor_A
275
+ return self.base_layer.weight + self.scaling * (current - anchor)
276
+
277
+
278
+ class LoRAEmbedding(nn.Module):
279
+ """Frozen token embedding plus a routed low-rank delta."""
280
+
281
+ def __init__(
282
+ self,
283
+ base_layer: nn.Embedding,
284
+ rank: int,
285
+ alpha: float,
286
+ dropout: float,
287
+ routing: str,
288
+ ):
289
+ super().__init__()
290
+ if rank <= 0:
291
+ raise ValueError("LoRA rank must be positive")
292
+ self.base_layer = base_layer
293
+ self.rank = rank
294
+ self.alpha = float(alpha)
295
+ self.scaling = self.alpha / rank
296
+ self.dropout = nn.Dropout(dropout)
297
+ self.routing = routing
298
+ self.route_mask: torch.Tensor | None = None
299
+ factory = {"device": base_layer.weight.device, "dtype": base_layer.weight.dtype}
300
+ self.lora_A = nn.Embedding(base_layer.num_embeddings, rank, **factory)
301
+ self.lora_B = nn.Linear(rank, base_layer.embedding_dim, bias=False, **factory)
302
+ nn.init.normal_(self.lora_A.weight, mean=0.0, std=0.02)
303
+ nn.init.zeros_(self.lora_B.weight)
304
+ for parameter in self.base_layer.parameters():
305
+ parameter.requires_grad = False
306
+
307
+ @property
308
+ def num_embeddings(self) -> int:
309
+ return self.base_layer.num_embeddings
310
+
311
+ @property
312
+ def embedding_dim(self) -> int:
313
+ return self.base_layer.embedding_dim
314
+
315
+ @property
316
+ def weight(self) -> torch.Tensor:
317
+ return self.base_layer.weight
318
+
319
+ def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
320
+ base = self.base_layer(input_ids)
321
+ delta = self.lora_B(self.dropout(self.lora_A(input_ids))) * self.scaling
322
+ if self.route_mask is None:
323
+ raise RuntimeError(f"embedding route mask is unset for routing={self.routing}")
324
+ if tuple(self.route_mask.shape) != tuple(input_ids.shape):
325
+ raise ValueError("text embedding route mask does not match input tokens")
326
+ route = self.route_mask.to(device=delta.device, dtype=delta.dtype).unsqueeze(-1)
327
+ return base + delta * route
328
+
329
+
330
+ class RoutedEmbeddingDelta(nn.Module):
331
+ """Frozen audio embedding plus a zero-initialized target-region delta."""
332
+
333
+ def __init__(self, base_layer: nn.Embedding, routing: str):
334
+ super().__init__()
335
+ self.base_layer = base_layer
336
+ self.routing = routing
337
+ self.route_mask: torch.Tensor | None = None
338
+ self.scaling = 1.0
339
+ factory = {"device": base_layer.weight.device, "dtype": base_layer.weight.dtype}
340
+ self.delta = nn.Embedding(
341
+ base_layer.num_embeddings,
342
+ base_layer.embedding_dim,
343
+ **factory,
344
+ )
345
+ nn.init.zeros_(self.delta.weight)
346
+ for parameter in self.base_layer.parameters():
347
+ parameter.requires_grad = False
348
+
349
+ def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
350
+ base = self.base_layer(input_ids)
351
+ delta = self.delta(input_ids) * self.scaling
352
+ if self.route_mask is None:
353
+ raise RuntimeError(f"embedding delta route mask is unset for routing={self.routing}")
354
+ if input_ids.ndim != 3 or tuple(self.route_mask.shape) != (
355
+ input_ids.shape[0], input_ids.shape[2]
356
+ ):
357
+ raise ValueError("embedding delta expects ids [B, C, S] and route [B, S]")
358
+ route = self.route_mask.to(device=delta.device, dtype=delta.dtype)[:, None, :, None]
359
+ return base + delta * route
360
+
361
+
362
+ class RoutedLinearDelta(nn.Module):
363
+ """Frozen output projection plus a zero-initialized full-rank delta."""
364
+
365
+ def __init__(self, base_layer: nn.Linear, routing: str):
366
+ super().__init__()
367
+ self.base_layer = base_layer
368
+ self.routing = routing
369
+ self.route_mask: torch.Tensor | None = None
370
+ self.scaling = 1.0
371
+ factory = {"device": base_layer.weight.device, "dtype": base_layer.weight.dtype}
372
+ self.delta = nn.Linear(
373
+ base_layer.in_features,
374
+ base_layer.out_features,
375
+ bias=False,
376
+ **factory,
377
+ )
378
+ nn.init.zeros_(self.delta.weight)
379
+ for parameter in self.base_layer.parameters():
380
+ parameter.requires_grad = False
381
+
382
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
383
+ base = self.base_layer(inputs)
384
+ delta = self.delta(inputs) * self.scaling
385
+ if self.route_mask is None:
386
+ raise RuntimeError(f"output delta route mask is unset for routing={self.routing}")
387
+ if tuple(self.route_mask.shape) != tuple(inputs.shape[:-1]):
388
+ raise ValueError("output delta route mask does not match input tokens")
389
+ route = self.route_mask.to(device=delta.device, dtype=delta.dtype).unsqueeze(-1)
390
+ return base + delta * route
391
+
392
+
393
+ class ResidualAdapter(nn.Module):
394
+ """Bottleneck residual branch, initialized as an exact no-op."""
395
+
396
+ def __init__(self, hidden_size: int, bottleneck: int, reference: torch.Tensor):
397
+ super().__init__()
398
+ factory = {"device": reference.device, "dtype": reference.dtype}
399
+ self.down = nn.Linear(hidden_size, bottleneck, bias=True, **factory)
400
+ self.activation = nn.GELU()
401
+ self.up = nn.Linear(bottleneck, hidden_size, bias=True, **factory)
402
+ nn.init.normal_(self.down.weight, mean=0.0, std=0.02)
403
+ nn.init.zeros_(self.down.bias)
404
+ nn.init.zeros_(self.up.weight)
405
+ nn.init.zeros_(self.up.bias)
406
+
407
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
408
+ return self.up(self.activation(self.down(hidden_states)))
409
+
410
+
411
+ def _adapter_output_hook(module: nn.Module, _inputs: tuple[Any, ...], output: Any) -> Any:
412
+ adapter = module.peft_adapter
413
+ if isinstance(output, torch.Tensor):
414
+ return output + adapter(output)
415
+ if isinstance(output, tuple) and output and isinstance(output[0], torch.Tensor):
416
+ return (output[0] + adapter(output[0]), *output[1:])
417
+ raise TypeError(f"Unsupported Qwen block output type: {type(output)!r}")
418
+
419
+
420
+ def _qwen_layers(model: nn.Module) -> nn.ModuleList:
421
+ llm = getattr(model, "llm", None)
422
+ layers = getattr(llm, "layers", None)
423
+ if not isinstance(layers, nn.ModuleList):
424
+ raise TypeError("Expected OmniVoice.llm.layers to be torch.nn.ModuleList")
425
+ if len(layers) != 28:
426
+ raise ValueError(f"Expected 28 Qwen3 blocks, found {len(layers)}")
427
+ return layers
428
+
429
+
430
+ def _freeze_all(model: nn.Module) -> None:
431
+ for parameter in model.parameters():
432
+ parameter.requires_grad = False
433
+
434
+
435
+ def _wrap_linear(
436
+ projection: nn.Linear,
437
+ module_name: str,
438
+ spec: PeftSpec,
439
+ bases: dict[str, torch.Tensor] | None,
440
+ ) -> LoRALinear:
441
+ if spec.initialization == "vanilla":
442
+ return LoRALinear(
443
+ projection,
444
+ spec.rank,
445
+ spec.alpha,
446
+ spec.dropout,
447
+ routing=spec.routing,
448
+ )
449
+ if bases is None or module_name not in bases:
450
+ raise KeyError(f"null-basis cache lacks target module {module_name!r}")
451
+ basis = bases[module_name]
452
+ if tuple(basis.shape) != (projection.in_features, spec.rank):
453
+ raise ValueError(
454
+ f"basis {module_name} has shape {tuple(basis.shape)}, expected "
455
+ f"({projection.in_features}, {spec.rank})"
456
+ )
457
+ return LoRANullLinear(
458
+ projection,
459
+ spec.rank,
460
+ spec.alpha,
461
+ spec.dropout,
462
+ basis,
463
+ init_scale=spec.null_init_scale,
464
+ freeze_a=spec.freeze_a,
465
+ routing=spec.routing,
466
+ )
467
+
468
+
469
+ def _inject_lora(
470
+ model: nn.Module,
471
+ spec: PeftSpec,
472
+ bases: dict[str, torch.Tensor] | None = None,
473
+ ) -> list[str]:
474
+ replaced: list[str] = []
475
+ layers = _qwen_layers(model)
476
+ block_targets = tuple(
477
+ name for name in spec.target_modules if name not in ROOT_PROJECTIONS
478
+ )
479
+ for layer_index in spec.layer_indices:
480
+ block = layers[layer_index]
481
+ attention = getattr(block, "self_attn", None)
482
+ mlp = getattr(block, "mlp", None)
483
+ if attention is None or mlp is None:
484
+ raise TypeError(f"Qwen block {layer_index} lacks self_attn or mlp")
485
+ for projection_name in block_targets:
486
+ owner = attention if projection_name in TARGET_PROJECTIONS else mlp
487
+ owner_name = "self_attn" if projection_name in TARGET_PROJECTIONS else "mlp"
488
+ projection = getattr(owner, projection_name, None)
489
+ if not isinstance(projection, nn.Linear):
490
+ raise TypeError(
491
+ f"llm.layers.{layer_index}.{owner_name}.{projection_name} "
492
+ f"must be nn.Linear, found {type(projection)!r}"
493
+ )
494
+ module_name = f"llm.layers.{layer_index}.{owner_name}.{projection_name}"
495
+ wrapped = _wrap_linear(projection, module_name, spec, bases)
496
+ setattr(owner, projection_name, wrapped)
497
+ replaced.append(module_name)
498
+ if "audio_heads" in spec.target_modules:
499
+ projection = getattr(model, "audio_heads", None)
500
+ if not isinstance(projection, nn.Linear):
501
+ raise TypeError(
502
+ f"audio_heads must be nn.Linear, found {type(projection)!r}"
503
+ )
504
+ model.audio_heads = _wrap_linear(projection, "audio_heads", spec, bases)
505
+ replaced.append("audio_heads")
506
+ if "text_embeddings" in spec.target_modules:
507
+ embedding = model.get_input_embeddings()
508
+ if not isinstance(embedding, nn.Embedding):
509
+ raise TypeError(
510
+ f"text input embeddings must be nn.Embedding, found {type(embedding)!r}"
511
+ )
512
+ model.set_input_embeddings(
513
+ LoRAEmbedding(
514
+ embedding,
515
+ spec.rank,
516
+ spec.alpha,
517
+ spec.dropout,
518
+ routing=spec.routing,
519
+ )
520
+ )
521
+ replaced.append("text_embeddings")
522
+ if "audio_embeddings_delta" in spec.target_modules:
523
+ embedding = getattr(model, "audio_embeddings", None)
524
+ if not isinstance(embedding, nn.Embedding):
525
+ raise TypeError(f"audio_embeddings must be nn.Embedding, found {type(embedding)!r}")
526
+ model.audio_embeddings = RoutedEmbeddingDelta(embedding, routing=spec.routing)
527
+ replaced.append("audio_embeddings_delta")
528
+ if "audio_heads_delta" in spec.target_modules:
529
+ if "audio_heads" in spec.target_modules:
530
+ raise ValueError("audio_heads and audio_heads_delta are mutually exclusive")
531
+ projection = getattr(model, "audio_heads", None)
532
+ if not isinstance(projection, nn.Linear):
533
+ raise TypeError(f"audio_heads must be nn.Linear, found {type(projection)!r}")
534
+ model.audio_heads = RoutedLinearDelta(projection, routing=spec.routing)
535
+ replaced.append("audio_heads_delta")
536
+ return replaced
537
+
538
+
539
+ def set_routing_mask(model: nn.Module, route_mask: torch.Tensor | None) -> int:
540
+ """Set one [batch, sequence] token mask on every routed LoRA projection."""
541
+ routed = 0
542
+ routed_types = (LoRALinear, LoRAEmbedding, RoutedEmbeddingDelta, RoutedLinearDelta)
543
+ for module in model.modules():
544
+ if isinstance(module, routed_types) and module.routing != "none":
545
+ module.route_mask = route_mask
546
+ routed += 1
547
+ if routed and route_mask is None:
548
+ raise ValueError("routed LoRA requires a non-null route mask")
549
+ return routed
550
+
551
+
552
+ def inference_routing_mask(
553
+ *,
554
+ routing: str,
555
+ input_ids: torch.Tensor,
556
+ audio_mask: torch.Tensor,
557
+ audio_mask_id: int,
558
+ attention_mask: torch.Tensor | None = None,
559
+ ) -> torch.Tensor | None:
560
+ """Build the exact generation-time route for conditional/unconditional rows."""
561
+ if routing == "none":
562
+ return None
563
+ if routing == "prediction":
564
+ return (input_ids == audio_mask_id).any(dim=1) & audio_mask.bool()
565
+ if routing == "text_only":
566
+ return ~audio_mask.bool()
567
+ if routing == "text_prediction":
568
+ prediction = (input_ids == audio_mask_id).any(dim=1) & audio_mask.bool()
569
+ return (~audio_mask.bool()) | prediction
570
+ if routing != "target_region":
571
+ raise ValueError(f"unsupported LoRA routing mode: {routing}")
572
+
573
+ batch_size, sequence_length = audio_mask.shape
574
+ if batch_size % 2:
575
+ raise ValueError("target-region inference expects paired conditional/unconditional rows")
576
+ half = batch_size // 2
577
+ target_lengths = audio_mask[half:].sum(dim=1).to(dtype=torch.long)
578
+ if attention_mask is None:
579
+ conditional_lengths = torch.full_like(target_lengths, sequence_length)
580
+ elif attention_mask.ndim == 4:
581
+ conditional_lengths = attention_mask[:half, 0, 0].sum(dim=-1).to(dtype=torch.long)
582
+ elif attention_mask.ndim == 2:
583
+ conditional_lengths = attention_mask[:half].sum(dim=-1).to(dtype=torch.long)
584
+ else:
585
+ raise ValueError(f"unsupported attention mask rank: {attention_mask.ndim}")
586
+
587
+ route = torch.zeros_like(audio_mask, dtype=torch.bool)
588
+ for index, (conditional_length, target_length) in enumerate(
589
+ zip(conditional_lengths.tolist(), target_lengths.tolist())
590
+ ):
591
+ if target_length <= 0 or target_length > conditional_length:
592
+ raise ValueError(
593
+ f"invalid target length {target_length} for conditional length {conditional_length}"
594
+ )
595
+ route[index, conditional_length - target_length : conditional_length] = True
596
+ route[half + index, :target_length] = True
597
+ return route
598
+
599
+
600
+ def _inject_residual_adapters(model: nn.Module, spec: PeftSpec) -> list[str]:
601
+ layers = _qwen_layers(model)
602
+ first_layer = len(layers) - spec.adapter_layers
603
+ injected: list[str] = []
604
+ for layer_index in range(first_layer, len(layers)):
605
+ block = layers[layer_index]
606
+ if hasattr(block, "peft_adapter"):
607
+ raise RuntimeError(f"Qwen block {layer_index} already has peft_adapter")
608
+ reference = next(block.parameters())
609
+ hidden_size = model.config.llm_config.hidden_size
610
+ block.add_module(
611
+ "peft_adapter",
612
+ ResidualAdapter(hidden_size, spec.bottleneck, reference),
613
+ )
614
+ block._peft_adapter_hook_handle = block.register_forward_hook(
615
+ _adapter_output_hook
616
+ )
617
+ injected.append(f"llm.layers.{layer_index}.peft_adapter")
618
+ return injected
619
+
620
+
621
+ def inject_peft(model: nn.Module, spec: PeftSpec) -> dict[str, Any]:
622
+ """Freeze the complete base model and inject exactly one E4/E5 strategy."""
623
+ spec.validate()
624
+ if hasattr(model, "_local_peft_spec"):
625
+ raise RuntimeError("PEFT has already been injected into this model")
626
+ _freeze_all(model)
627
+ if spec.strategy == "lora":
628
+ bases = None
629
+ basis_metadata = None
630
+ if spec.initialization == "lora_null":
631
+ bases, basis_metadata = load_basis_cache(
632
+ spec.null_basis_path,
633
+ expected_sha256=spec.null_basis_sha256,
634
+ )
635
+ observed_base = basis_metadata.get("base_model_sha256")
636
+ if observed_base != spec.base_model_sha256:
637
+ raise RuntimeError(
638
+ "null-basis base model mismatch: "
639
+ f"cache={observed_base!r}, adapter={spec.base_model_sha256!r}"
640
+ )
641
+ observed_rank = basis_metadata.get("rank")
642
+ if observed_rank is not None and int(observed_rank) != spec.rank:
643
+ raise RuntimeError(
644
+ f"null-basis rank {observed_rank} != adapter rank {spec.rank}"
645
+ )
646
+ modules = _inject_lora(model, spec, bases=bases)
647
+ if basis_metadata is not None:
648
+ model._null_basis_metadata = basis_metadata
649
+ else:
650
+ modules = _inject_residual_adapters(model, spec)
651
+ model._local_peft_spec = spec
652
+ report = audit_trainable_parameters(model, spec)
653
+ report["injected_modules"] = modules
654
+ return report
655
+
656
+
657
+ @torch.no_grad()
658
+ def project_lora_null_a(model: nn.Module) -> dict[str, float | int]:
659
+ """Apply the exact post-step A projection to every LoRA-Null module."""
660
+ modules = [module for module in model.modules() if isinstance(module, LoRANullLinear)]
661
+ if not modules:
662
+ raise RuntimeError("hard_project_a requested but no LoRA-Null modules were found")
663
+ total = 0.0
664
+ outside_before = 0.0
665
+ outside_after = 0.0
666
+ for module in modules:
667
+ result = module.project_lora_a_()
668
+ total += result["total_energy_before"]
669
+ outside_before += result["outside_energy_before"]
670
+ outside_after += result["outside_energy_after"]
671
+ return {
672
+ "modules": len(modules),
673
+ "outside_energy_fraction_before": outside_before / max(total, 1e-30),
674
+ "outside_norm_fraction_before": math.sqrt(outside_before / max(total, 1e-30)),
675
+ "outside_energy_fraction_after": outside_after / max(total, 1e-30),
676
+ }
677
+
678
+
679
+ def _is_adapter_parameter(name: str, strategy: str) -> bool:
680
+ if strategy == "lora":
681
+ return (
682
+ ".lora_A.weight" in name
683
+ or ".lora_B.weight" in name
684
+ or name.endswith(".delta.weight")
685
+ )
686
+ return ".peft_adapter.down." in name or ".peft_adapter.up." in name
687
+
688
+
689
+ def _is_adapter_state(name: str, strategy: str) -> bool:
690
+ return _is_adapter_parameter(name, strategy) or (
691
+ strategy == "lora" and (name.endswith(".anchor_A") or name.endswith(".anchor_B"))
692
+ )
693
+
694
+
695
+ def adapter_state_dict(model: nn.Module, spec: PeftSpec) -> dict[str, torch.Tensor]:
696
+ return {
697
+ name: value.detach().cpu().contiguous()
698
+ for name, value in model.state_dict().items()
699
+ if _is_adapter_state(name, spec.strategy)
700
+ }
701
+
702
+
703
+ def audit_trainable_parameters(model: nn.Module, spec: PeftSpec) -> dict[str, Any]:
704
+ trainable = [(name, p) for name, p in model.named_parameters() if p.requires_grad]
705
+ unexpected = [name for name, _ in trainable if not _is_adapter_parameter(name, spec.strategy)]
706
+ if unexpected:
707
+ raise AssertionError(f"Unexpected trainable base parameters: {unexpected}")
708
+ frozen_guards = {}
709
+ embeddings = getattr(model, "audio_embeddings", None)
710
+ if embeddings is None:
711
+ raise AssertionError("OmniVoice is missing audio_embeddings")
712
+ embedding_base = (
713
+ embeddings.base_layer if isinstance(embeddings, RoutedEmbeddingDelta) else embeddings
714
+ )
715
+ frozen_guards["audio_embeddings"] = all(
716
+ not parameter.requires_grad for parameter in embedding_base.parameters()
717
+ )
718
+ if not frozen_guards["audio_embeddings"]:
719
+ raise AssertionError("audio_embeddings must remain frozen")
720
+ audio_heads = getattr(model, "audio_heads", None)
721
+ if audio_heads is None:
722
+ raise AssertionError("OmniVoice is missing audio_heads")
723
+ head_base = (
724
+ audio_heads.base_layer
725
+ if isinstance(audio_heads, (LoRALinear, RoutedLinearDelta))
726
+ else audio_heads
727
+ )
728
+ frozen_guards["audio_heads_base"] = all(
729
+ not parameter.requires_grad for parameter in head_base.parameters()
730
+ )
731
+ if not frozen_guards["audio_heads_base"]:
732
+ raise AssertionError("the base audio_heads parameters must remain frozen")
733
+
734
+ text_embeddings = model.get_input_embeddings()
735
+ text_embedding_base = (
736
+ text_embeddings.base_layer
737
+ if isinstance(text_embeddings, LoRAEmbedding)
738
+ else text_embeddings
739
+ )
740
+ frozen_guards["text_embeddings_base"] = all(
741
+ not parameter.requires_grad for parameter in text_embedding_base.parameters()
742
+ )
743
+ if not frozen_guards["text_embeddings_base"]:
744
+ raise AssertionError("the base text embeddings must remain frozen")
745
+
746
+ if spec.strategy == "lora":
747
+ lora_modules = [
748
+ module for module in model.modules()
749
+ if isinstance(module, (LoRALinear, LoRAEmbedding))
750
+ ]
751
+ delta_modules = [
752
+ module
753
+ for module in model.modules()
754
+ if isinstance(module, (RoutedEmbeddingDelta, RoutedLinearDelta))
755
+ ]
756
+ block_target_count = sum(
757
+ name not in ROOT_PROJECTIONS for name in spec.target_modules
758
+ )
759
+ root_target_count = sum(
760
+ name in ROOT_PROJECTIONS for name in spec.target_modules
761
+ )
762
+ expected_modules = len(spec.layer_indices) * block_target_count + root_target_count
763
+ if len(lora_modules) + len(delta_modules) != expected_modules:
764
+ raise AssertionError(
765
+ f"Expected {expected_modules} adapter modules, "
766
+ f"found {len(lora_modules) + len(delta_modules)}"
767
+ )
768
+ expected_tensors = sum(
769
+ int(module.lora_A.weight.requires_grad) + int(module.lora_B.weight.requires_grad)
770
+ for module in lora_modules
771
+ ) + len(delta_modules)
772
+ expected_parameters = sum(
773
+ (module.lora_A.weight.numel() if module.lora_A.weight.requires_grad else 0)
774
+ + (module.lora_B.weight.numel() if module.lora_B.weight.requires_grad else 0)
775
+ for module in lora_modules
776
+ ) + sum(module.delta.weight.numel() for module in delta_modules)
777
+ else:
778
+ injected_modules = [module for module in model.modules() if isinstance(module, ResidualAdapter)]
779
+ if len(injected_modules) != 4:
780
+ raise AssertionError(f"Expected 4 residual adapters, found {len(injected_modules)}")
781
+ expected_tensors = len(injected_modules) * 4
782
+ expected_parameters = sum(
783
+ sum(parameter.numel() for parameter in module.parameters())
784
+ for module in injected_modules
785
+ )
786
+ count = sum(parameter.numel() for _, parameter in trainable)
787
+ if len(trainable) != expected_tensors or count != expected_parameters:
788
+ raise AssertionError(
789
+ f"Trainable contract mismatch: tensors={len(trainable)}/{expected_tensors}, "
790
+ f"parameters={count}/{expected_parameters}"
791
+ )
792
+ total = sum(parameter.numel() for parameter in model.parameters())
793
+ return {
794
+ "experiment_id": spec.experiment_id,
795
+ "strategy": spec.strategy,
796
+ "trainable_tensors": len(trainable),
797
+ "trainable_parameters": count,
798
+ "total_parameters_after_injection": total,
799
+ "trainable_percent": 100.0 * count / total,
800
+ "frozen_guards": frozen_guards,
801
+ "trainable_names": [name for name, _ in trainable],
802
+ }
803
+
804
+
805
+ def trainable_parameters(model: nn.Module) -> Iterable[nn.Parameter]:
806
+ parameters = [parameter for parameter in model.parameters() if parameter.requires_grad]
807
+ if not parameters:
808
+ raise RuntimeError("No trainable PEFT parameters found")
809
+ return parameters
810
+
811
+
812
+ def save_adapter_checkpoint(
813
+ model: nn.Module,
814
+ checkpoint_dir: str | Path,
815
+ spec: PeftSpec,
816
+ audit: dict[str, Any] | None = None,
817
+ metadata: dict[str, Any] | None = None,
818
+ ) -> None:
819
+ checkpoint_dir = Path(checkpoint_dir)
820
+ checkpoint_dir.mkdir(parents=True, exist_ok=True)
821
+ state = adapter_state_dict(model, spec)
822
+ expected = audit_trainable_parameters(model, spec)
823
+ if not set(expected["trainable_names"]).issubset(state):
824
+ raise AssertionError("Adapter state is missing trainable parameters")
825
+ save_file(state, checkpoint_dir / ADAPTER_FILE)
826
+ (checkpoint_dir / PEFT_CONFIG_FILE).write_text(
827
+ json.dumps(spec.to_dict(), indent=2) + "\n", encoding="utf-8"
828
+ )
829
+ (checkpoint_dir / AUDIT_FILE).write_text(
830
+ json.dumps(audit or expected, indent=2) + "\n", encoding="utf-8"
831
+ )
832
+ if metadata is not None:
833
+ (checkpoint_dir / "model_metadata.json").write_text(
834
+ json.dumps(metadata, indent=2) + "\n", encoding="utf-8"
835
+ )
836
+
837
+
838
+ def read_peft_spec(checkpoint_dir: str | Path) -> PeftSpec:
839
+ path = Path(checkpoint_dir) / PEFT_CONFIG_FILE
840
+ return PeftSpec.from_dict(json.loads(path.read_text(encoding="utf-8")))
841
+
842
+
843
+ def load_adapter_checkpoint(
844
+ model: nn.Module,
845
+ checkpoint_dir: str | Path,
846
+ *,
847
+ inject_if_needed: bool = True,
848
+ trainable: bool = False,
849
+ ) -> dict[str, Any]:
850
+ """Restore adapter weights into a clean or already-injected base model."""
851
+ checkpoint_dir = Path(checkpoint_dir)
852
+ spec = read_peft_spec(checkpoint_dir)
853
+ current_spec = getattr(model, "_local_peft_spec", None)
854
+ if current_spec is None:
855
+ if not inject_if_needed:
856
+ raise RuntimeError("Model has no injected adapter")
857
+ inject_peft(model, spec)
858
+ elif current_spec != spec:
859
+ raise ValueError(f"Injected spec {current_spec} differs from checkpoint {spec}")
860
+ state = load_file(checkpoint_dir / ADAPTER_FILE, device="cpu")
861
+ expected_names = set(adapter_state_dict(model, spec))
862
+ if set(state) != expected_names:
863
+ missing = sorted(expected_names - set(state))
864
+ extra = sorted(set(state) - expected_names)
865
+ raise RuntimeError(f"Adapter key mismatch; missing={missing}, extra={extra}")
866
+ state_targets = model.state_dict(keep_vars=True)
867
+ originally_trainable = {
868
+ name for name, parameter in model.named_parameters() if parameter.requires_grad
869
+ }
870
+ with torch.no_grad():
871
+ for name, value in state.items():
872
+ target = state_targets[name]
873
+ target.copy_(value.to(device=target.device, dtype=target.dtype))
874
+ for name, parameter in model.named_parameters():
875
+ parameter.requires_grad = trainable and name in originally_trainable
876
+ audit = audit_trainable_parameters(model, spec) if trainable else {
877
+ "experiment_id": spec.experiment_id,
878
+ "strategy": spec.strategy,
879
+ "loaded_tensors": len(state),
880
+ "loaded_parameters": sum(value.numel() for value in state.values()),
881
+ "all_parameters_frozen": all(not p.requires_grad for p in model.parameters()),
882
+ }
883
+ return audit
native_adapter/loranull/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Numerical helpers used by the recovered adapter."""
native_adapter/loranull/basis_cache.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Versioned, hashable safetensors cache for per-module null bases."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from pathlib import Path
8
+ from typing import Any, Mapping
9
+
10
+ import torch
11
+ from safetensors import safe_open
12
+ from safetensors.torch import save_file
13
+
14
+
15
+ SCHEMA_VERSION = 1
16
+
17
+
18
+ def sha256_file(path: str | Path) -> str:
19
+ digest = hashlib.sha256()
20
+ with Path(path).open("rb") as stream:
21
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
22
+ digest.update(chunk)
23
+ return digest.hexdigest()
24
+
25
+
26
+ def _validate_basis(name: str, basis: torch.Tensor) -> torch.Tensor:
27
+ if basis.ndim != 2 or min(basis.shape) <= 0:
28
+ raise ValueError(f"basis {name!r} must have shape [in_features, rank]")
29
+ value = basis.detach().to(device="cpu", dtype=torch.float32).contiguous()
30
+ gram = value.mT @ value
31
+ identity = torch.eye(value.shape[1], dtype=value.dtype)
32
+ if not torch.allclose(gram, identity, atol=2e-4, rtol=2e-4):
33
+ raise ValueError(f"basis {name!r} is not orthonormal")
34
+ return value
35
+
36
+
37
+ def save_basis_cache(
38
+ path: str | Path,
39
+ bases: Mapping[str, torch.Tensor],
40
+ metadata: Mapping[str, Any],
41
+ ) -> str:
42
+ """Atomically-ish write a self-describing basis cache and return SHA-256."""
43
+
44
+ destination = Path(path)
45
+ if destination.suffix != ".safetensors":
46
+ raise ValueError("basis cache path must end in .safetensors")
47
+ if not bases:
48
+ raise ValueError("cannot save an empty basis cache")
49
+ destination.parent.mkdir(parents=True, exist_ok=True)
50
+ tensors = {name: _validate_basis(name, value) for name, value in sorted(bases.items())}
51
+ payload = dict(metadata)
52
+ payload["schema_version"] = SCHEMA_VERSION
53
+ payload["modules"] = {
54
+ name: {"in_features": value.shape[0], "rank": value.shape[1]}
55
+ for name, value in tensors.items()
56
+ }
57
+ encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"))
58
+ temporary = destination.with_suffix(destination.suffix + ".tmp")
59
+ save_file(tensors, temporary, metadata={"loranull_metadata": encoded})
60
+ temporary.replace(destination)
61
+ sidecar = destination.with_suffix(destination.suffix + ".json")
62
+ sidecar_temporary = sidecar.with_suffix(sidecar.suffix + ".tmp")
63
+ sidecar_temporary.write_text(
64
+ json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8"
65
+ )
66
+ sidecar_temporary.replace(sidecar)
67
+ return sha256_file(destination)
68
+
69
+
70
+ def load_basis_cache(
71
+ path: str | Path,
72
+ *,
73
+ expected_sha256: str | None = None,
74
+ ) -> tuple[dict[str, torch.Tensor], dict[str, Any]]:
75
+ source = Path(path)
76
+ if not source.is_file():
77
+ raise FileNotFoundError(f"null-basis cache not found: {source}")
78
+ observed = sha256_file(source)
79
+ if expected_sha256 is not None and observed != expected_sha256:
80
+ raise RuntimeError(
81
+ f"null-basis SHA-256 mismatch: expected {expected_sha256}, got {observed}"
82
+ )
83
+ with safe_open(source, framework="pt", device="cpu") as handle:
84
+ header = handle.metadata() or {}
85
+ if "loranull_metadata" not in header:
86
+ raise RuntimeError("basis cache lacks lorannull metadata")
87
+ metadata = json.loads(header["loranull_metadata"])
88
+ bases = {name: _validate_basis(name, handle.get_tensor(name)) for name in handle.keys()}
89
+ sidecar = source.with_suffix(source.suffix + ".json")
90
+ if not sidecar.is_file():
91
+ raise RuntimeError(f"basis cache sidecar not found: {sidecar}")
92
+ sidecar_metadata = json.loads(sidecar.read_text(encoding="utf-8"))
93
+ if sidecar_metadata != metadata:
94
+ raise RuntimeError("basis-cache sidecar disagrees with safetensors metadata")
95
+ if metadata.get("schema_version") != SCHEMA_VERSION:
96
+ raise RuntimeError(f"unsupported basis-cache schema: {metadata.get('schema_version')}")
97
+ declared = metadata.get("modules", {})
98
+ if set(declared) != set(bases):
99
+ raise RuntimeError("basis-cache tensor keys disagree with metadata")
100
+ for name, basis in bases.items():
101
+ shape = declared[name]
102
+ if [shape.get("in_features"), shape.get("rank")] != list(basis.shape):
103
+ raise RuntimeError(f"basis shape metadata mismatch for {name}")
104
+ metadata["cache_sha256"] = observed
105
+ return bases, metadata
native_adapter/loranull/math.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Numerically stable linear algebra used by the OmniVoice LoRA-Null port.
2
+
3
+ This is a clean-room implementation of the equations in LoRA-Null. It avoids
4
+ forming the dense projector ``U U.T``: only ``W @ U`` (out_features by rank)
5
+ is decomposed.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import torch
11
+
12
+
13
+ def _check_rank(rank: int, dimension: int) -> None:
14
+ if rank <= 0 or rank > dimension:
15
+ raise ValueError(f"rank must be in [1, {dimension}], got {rank}")
16
+
17
+
18
+ def smallest_eigenbasis(
19
+ covariance: torch.Tensor,
20
+ rank: int,
21
+ ) -> tuple[torch.Tensor, torch.Tensor]:
22
+ """Return the ``rank`` lowest-energy orthonormal directions of ``X.T @ X``.
23
+
24
+ ``torch.linalg.eigh`` returns eigenvalues in ascending order, so this is the
25
+ covariance equivalent of taking the trailing left singular vectors of the
26
+ paper's activation matrix ``X_pre``.
27
+ """
28
+
29
+ if covariance.ndim != 2 or covariance.shape[0] != covariance.shape[1]:
30
+ raise ValueError("covariance must be a square matrix")
31
+ _check_rank(rank, covariance.shape[0])
32
+ work = covariance.to(dtype=torch.float64)
33
+ work = (work + work.mT) * 0.5
34
+ eigenvalues, eigenvectors = torch.linalg.eigh(work)
35
+ basis = eigenvectors[:, :rank].to(dtype=torch.float32).contiguous()
36
+ values = eigenvalues[:rank].clamp_min(0).to(dtype=torch.float64).contiguous()
37
+ return basis, values
38
+
39
+
40
+ def factor_projected_weight(
41
+ weight: torch.Tensor,
42
+ null_basis: torch.Tensor,
43
+ *,
44
+ scaling: float,
45
+ init_scale: float = 1.0,
46
+ ) -> tuple[torch.Tensor, torch.Tensor]:
47
+ """Factor ``(init_scale/scaling) * W U U.T`` into LoRA ``B @ A``.
48
+
49
+ The returned shapes are ``B=[out, rank]`` and ``A=[rank, in]``. With the
50
+ centered forward ``W x + scaling * (B_t A_t - B_0 A_0) x``, initialization
51
+ is an exact no-op while the paper's projected component has magnitude
52
+ ``init_scale`` after LoRA scaling is applied.
53
+ """
54
+
55
+ if weight.ndim != 2 or null_basis.ndim != 2:
56
+ raise ValueError("weight and null_basis must both be matrices")
57
+ out_features, in_features = weight.shape
58
+ if null_basis.shape[0] != in_features:
59
+ raise ValueError(
60
+ f"basis input dimension {null_basis.shape[0]} != weight input {in_features}"
61
+ )
62
+ rank = null_basis.shape[1]
63
+ _check_rank(rank, min(in_features, out_features))
64
+ if scaling <= 0 or init_scale < 0:
65
+ raise ValueError("scaling must be positive and init_scale non-negative")
66
+
67
+ work_weight = weight.detach().to(dtype=torch.float32)
68
+ basis = null_basis.detach().to(device=work_weight.device, dtype=torch.float32)
69
+ gram = basis.mT @ basis
70
+ identity = torch.eye(rank, device=gram.device, dtype=gram.dtype)
71
+ if not torch.allclose(gram, identity, atol=2e-4, rtol=2e-4):
72
+ raise ValueError("null_basis columns must be orthonormal")
73
+
74
+ projected_thin = work_weight @ basis
75
+ left, singular, right_t = torch.linalg.svd(projected_thin, full_matrices=False)
76
+ singular = singular[:rank].clamp_min(0) * (float(init_scale) / float(scaling))
77
+ root = singular.sqrt()
78
+ b_weight = left[:, :rank] * root.unsqueeze(0)
79
+ a_weight = (root.unsqueeze(1) * right_t[:rank]) @ basis.mT
80
+ return b_weight.contiguous(), a_weight.contiguous()
81
+
82
+
83
+ def projected_factor_relative_error(
84
+ weight: torch.Tensor,
85
+ null_basis: torch.Tensor,
86
+ b_weight: torch.Tensor,
87
+ a_weight: torch.Tensor,
88
+ *,
89
+ scaling: float,
90
+ init_scale: float = 1.0,
91
+ ) -> float:
92
+ """Diagnostic relative error for ``scaling * BA == init_scale * WUU.T``."""
93
+
94
+ work = weight.detach().to(dtype=torch.float64)
95
+ basis = null_basis.detach().to(device=work.device, dtype=torch.float64)
96
+ expected = float(init_scale) * (work @ basis) @ basis.mT
97
+ observed = float(scaling) * (
98
+ b_weight.detach().to(device=work.device, dtype=torch.float64)
99
+ @ a_weight.detach().to(device=work.device, dtype=torch.float64)
100
+ )
101
+ denominator = expected.norm().clamp_min(torch.finfo(torch.float64).eps)
102
+ return float(((observed - expected).norm() / denominator).item())
103
+
104
+
105
+ def basis_energy_fraction(covariance: torch.Tensor, basis: torch.Tensor) -> float:
106
+ """Fraction of total activation energy lying in ``basis``."""
107
+
108
+ cov = covariance.detach().to(dtype=torch.float64)
109
+ directions = basis.detach().to(device=cov.device, dtype=torch.float64)
110
+ numerator = torch.trace(directions.mT @ cov @ directions)
111
+ denominator = torch.trace(cov).clamp_min(torch.finfo(torch.float64).eps)
112
+ return float((numerator / denominator).item())
peft_config.json ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "experiment_id": "P2",
3
+ "strategy": "lora",
4
+ "base_model": "k2-fsa/OmniVoice",
5
+ "rank": 8,
6
+ "alpha": 16.0,
7
+ "dropout": 0.05,
8
+ "target_modules": [
9
+ "audio_heads_delta",
10
+ "q_proj",
11
+ "k_proj",
12
+ "v_proj",
13
+ "o_proj",
14
+ "gate_proj",
15
+ "up_proj",
16
+ "down_proj"
17
+ ],
18
+ "layer_indices": [
19
+ 0,
20
+ 1,
21
+ 2,
22
+ 3,
23
+ 4,
24
+ 5,
25
+ 6,
26
+ 7,
27
+ 8,
28
+ 9,
29
+ 10,
30
+ 11,
31
+ 12,
32
+ 13,
33
+ 14,
34
+ 15,
35
+ 16,
36
+ 17,
37
+ 18,
38
+ 19,
39
+ 20,
40
+ 21,
41
+ 22,
42
+ 23,
43
+ 24,
44
+ 25,
45
+ 26,
46
+ 27
47
+ ],
48
+ "adapter_layers": null,
49
+ "bottleneck": null,
50
+ "routing": "text_prediction",
51
+ "initialization": "vanilla",
52
+ "null_basis_path": null,
53
+ "null_basis_sha256": null,
54
+ "base_model_sha256": "730839316de585f4c8298ec0e1712efc10fb19c6fa4e36eb741cb8d51ebcf6aa",
55
+ "null_init_scale": 1.0,
56
+ "freeze_a": false,
57
+ "hard_project_a": false
58
+ }
snapshot.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "adapter_backend": "local_experiment_peft",
3
+ "base_model": "k2-fsa/OmniVoice",
4
+ "base_model_sha256": "730839316de585f4c8298ec0e1712efc10fb19c6fa4e36eb741cb8d51ebcf6aa",
5
+ "checkpoint_kind": "model-only",
6
+ "experiment_id": "P2_TESTSET_FT_OMNI_COMMON400_W050_E1",
7
+ "format_version": 1,
8
+ "inference_ready_with_referenced_base": true,
9
+ "metrics": {
10
+ "anchor_kl": 0.0,
11
+ "anchor_tokens": 0,
12
+ "non_target_kl": 0.0,
13
+ "non_target_tokens": 0,
14
+ "recovery_used": false,
15
+ "recovery_visible_tokens": 0,
16
+ "replay": 0.0,
17
+ "replay_tokens": 0,
18
+ "target_ce": 6.36165189743042,
19
+ "target_objective": {
20
+ "anchor_kl_weight": 0.0,
21
+ "checkpoint_kl_chunks": true,
22
+ "codebook_weights": [
23
+ 8.0,
24
+ 8.0,
25
+ 6.0,
26
+ 6.0,
27
+ 4.0,
28
+ 4.0,
29
+ 2.0,
30
+ 2.0
31
+ ],
32
+ "kl_chunk_tokens": 256,
33
+ "non_target_kl_weight": 0.0,
34
+ "prompt_guard_tokens": 0,
35
+ "recovery_probability": 0.0,
36
+ "recovery_visible_ratio_max": 0.5,
37
+ "recovery_visible_ratio_min": 0.25,
38
+ "replay_weight": 1.0,
39
+ "student_eval_mode": true,
40
+ "target_ce_weight": 0.5,
41
+ "temperature": 2.0
42
+ },
43
+ "target_tokens": 2832,
44
+ "teacher_batches": 0,
45
+ "total": 3.18082594871521
46
+ },
47
+ "model_only": true,
48
+ "optimizer_saved": false,
49
+ "run_id": "untracked",
50
+ "run_steps": 200,
51
+ "scheduler_total_steps": 200,
52
+ "step": 200
53
+ }
source_checksums.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "adapter_model.safetensors": {
3
+ "sha256": "1084cea52a8e9f5cb4fc9e4ef85c3be43e10181a9305d37cd63ad59282fbf81b",
4
+ "size": 53816712
5
+ },
6
+ "chat_template.jinja": {
7
+ "sha256": "a55ee1b1660128b7098723e0abcd92caa0788061051c62d51cbe87d9cf1974d8",
8
+ "size": 4168
9
+ },
10
+ "COMPLETE.json": {
11
+ "sha256": "93ee76929e87eb025f845b3e33b8a11b0f0338198d86e479fec5b4b0026a9258",
12
+ "size": 1443
13
+ },
14
+ "peft_config.json": {
15
+ "sha256": "5f7cd85ee3f13499c66bbbde39e2c2c4cf1c1c425b3276182ac2935e2eb59438",
16
+ "size": 849
17
+ },
18
+ "run_config.json": {
19
+ "sha256": "20e0e878f348b269df27943945a81b3c0c766de3e1ae4b7adb6dd79b682252cc",
20
+ "size": 5243
21
+ },
22
+ "snapshot.json": {
23
+ "sha256": "93ee76929e87eb025f845b3e33b8a11b0f0338198d86e479fec5b4b0026a9258",
24
+ "size": 1443
25
+ },
26
+ "tokenizer.json": {
27
+ "sha256": "408f669b7e2b045fdf54201d815bd364e6667dbd845115da81239c40bc6dcfd1",
28
+ "size": 11423986
29
+ },
30
+ "tokenizer_config.json": {
31
+ "sha256": "bcfa316f973c5cd33821a3d35f16cf2453b641d6048104602453b4e550760214",
32
+ "size": 561
33
+ },
34
+ "trainable_audit.json": {
35
+ "sha256": "cfc73d6c986879613a0252269418309ca8e708d422ded72a38fc6d6ab202046e",
36
+ "size": 20012
37
+ }
38
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:408f669b7e2b045fdf54201d815bd364e6667dbd845115da81239c40bc6dcfd1
3
+ size 11423986
tokenizer_config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": null,
5
+ "clean_up_tokenization_spaces": false,
6
+ "eos_token": "<|im_end|>",
7
+ "errors": "replace",
8
+ "extra_special_tokens": [
9
+ "<|denoise|>",
10
+ "<|lang_start|>",
11
+ "<|lang_end|>",
12
+ "<|instruct_start|>",
13
+ "<|instruct_end|>",
14
+ "<|text_start|>",
15
+ "<|text_end|>"
16
+ ],
17
+ "is_local": true,
18
+ "local_files_only": true,
19
+ "model_max_length": 131072,
20
+ "pad_token": "<|endoftext|>",
21
+ "split_special_tokens": false,
22
+ "tokenizer_class": "Qwen2Tokenizer",
23
+ "unk_token": null
24
+ }
training_recipe.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "checkpoint": "omni_common400/checkpoint-200",
3
+ "base_model": "k2-fsa/OmniVoice",
4
+ "base_revision": "c5fdb5ccb189668d56333f77ba2629f4cd7535f4",
5
+ "base_weights_sha256": "730839316de585f4c8298ec0e1712efc10fb19c6fa4e36eb741cb8d51ebcf6aa",
6
+ "language": "my",
7
+ "parent_adapter_sha256": "60a453c590cb7cfd002fde4cf251eaf29ce4d366448d639a5bbc65084855609d",
8
+ "training_set": "Common400",
9
+ "rows": 400,
10
+ "unique_target_audio": 150,
11
+ "epochs": 1,
12
+ "steps": 200,
13
+ "seed": 7,
14
+ "learning_rate": 2e-07,
15
+ "gradient_accumulation_steps": 2,
16
+ "max_batch_size": 1,
17
+ "uniform_target_ce_weight": 0.5,
18
+ "scheduler": "cosine",
19
+ "warmup_ratio": 0.03,
20
+ "optimizer_restarted": true,
21
+ "training_reference": "first up to 3 seconds of target audio",
22
+ "evaluation_scope": "Common400 evaluation is in-sample, not held-out",
23
+ "paper_main_results_checkpoint": false
24
+ }