Add files using upload-large-folder tool
Browse files- .gitattributes +1 -0
- chat_template.jinja +14 -0
- config.json +56 -0
- configuration_soda_hier.py +128 -0
- model.safetensors +3 -0
- modeling_soda_hier.py +261 -0
- tokenizer.json +3 -0
- tokenizer_config.json +14 -0
.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
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{ bos_token }}
|
| 2 |
+
{%- for message in messages -%}
|
| 3 |
+
{%- if message['role'] == 'assistant' -%}
|
| 4 |
+
<|start_header_id|>{{ message['role'] }}<|end_header_id|>
|
| 5 |
+
{% generation %}{{- message['content'] | trim }}<|eot_id|>{% endgeneration %}
|
| 6 |
+
|
| 7 |
+
{% else %}
|
| 8 |
+
<|start_header_id|>{{ message['role'] }}<|end_header_id|>
|
| 9 |
+
{{ message['content'] | trim }}<|eot_id|>
|
| 10 |
+
{% endif %}
|
| 11 |
+
{%- endfor -%}
|
| 12 |
+
{%- if add_generation_prompt -%}
|
| 13 |
+
<|start_header_id|>assistant<|end_header_id|>
|
| 14 |
+
{% endif -%}
|
config.json
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_name_or_path": "",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"SodaHierForCausalLM"
|
| 5 |
+
],
|
| 6 |
+
"audio_id_lo": 128260,
|
| 7 |
+
"auto_map": {
|
| 8 |
+
"AutoConfig": "configuration_soda_hier.SodaHierConfig",
|
| 9 |
+
"AutoModelForCausalLM": "modeling_soda_hier.SodaHierForCausalLM"
|
| 10 |
+
},
|
| 11 |
+
"bos_token_id": 128000,
|
| 12 |
+
"chunk_size_feed_forward": 0,
|
| 13 |
+
"codebook_size": 2048,
|
| 14 |
+
"depth_head_dim": 128,
|
| 15 |
+
"depth_hidden_size": 384,
|
| 16 |
+
"depth_intermediate_size": 1536,
|
| 17 |
+
"depth_num_heads": 3,
|
| 18 |
+
"depth_num_kv_heads": 3,
|
| 19 |
+
"depth_num_layers": 4,
|
| 20 |
+
"dtype": null,
|
| 21 |
+
"eos_token_id": 128001,
|
| 22 |
+
"hidden_size": 768,
|
| 23 |
+
"id2label": {
|
| 24 |
+
"0": "LABEL_0",
|
| 25 |
+
"1": "LABEL_1"
|
| 26 |
+
},
|
| 27 |
+
"intermediate_size": 3072,
|
| 28 |
+
"is_encoder_decoder": false,
|
| 29 |
+
"label2id": {
|
| 30 |
+
"LABEL_0": 0,
|
| 31 |
+
"LABEL_1": 1
|
| 32 |
+
},
|
| 33 |
+
"max_position_embeddings": 1024,
|
| 34 |
+
"model_type": "soda_hier",
|
| 35 |
+
"num_attention_heads": 6,
|
| 36 |
+
"num_codebooks": 8,
|
| 37 |
+
"num_hidden_layers": 8,
|
| 38 |
+
"num_key_value_heads": 6,
|
| 39 |
+
"output_attentions": false,
|
| 40 |
+
"output_hidden_states": false,
|
| 41 |
+
"problem_type": null,
|
| 42 |
+
"return_dict": true,
|
| 43 |
+
"rms_norm_eps": 1e-05,
|
| 44 |
+
"rope_scaling": {
|
| 45 |
+
"factor": 8.0,
|
| 46 |
+
"high_freq_factor": 4.0,
|
| 47 |
+
"low_freq_factor": 1.0,
|
| 48 |
+
"original_max_position_embeddings": 8192,
|
| 49 |
+
"rope_type": "llama3"
|
| 50 |
+
},
|
| 51 |
+
"rope_theta": 500000.0,
|
| 52 |
+
"tie_word_embeddings": false,
|
| 53 |
+
"transformers_version": "5.12.1",
|
| 54 |
+
"unified_vocab_size": 130308,
|
| 55 |
+
"vocab_size": 144644
|
| 56 |
+
}
|
configuration_soda_hier.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Marin Authors
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
|
| 4 |
+
"""HF configuration for the SODA hierarchical (backbone + depth) audio LM.
|
| 5 |
+
|
| 6 |
+
This file is copied verbatim into every exported checkpoint directory and
|
| 7 |
+
loaded via trust_remote_code, so it may import only torch/transformers —
|
| 8 |
+
never marin/levanter code.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from transformers import PretrainedConfig
|
| 12 |
+
from transformers.models.qwen3.configuration_qwen3 import Qwen3Config
|
| 13 |
+
|
| 14 |
+
# Llama-3-style long-rope parameters shared by backbone and depth (the values
|
| 15 |
+
# the runs were trained with). Written as legacy keys so transformers 4.x and
|
| 16 |
+
# 5.x both read them.
|
| 17 |
+
_DEFAULT_ROPE_THETA = 500000.0
|
| 18 |
+
_DEFAULT_ROPE_SCALING = {
|
| 19 |
+
"rope_type": "llama3",
|
| 20 |
+
"factor": 8.0,
|
| 21 |
+
"low_freq_factor": 1.0,
|
| 22 |
+
"high_freq_factor": 4.0,
|
| 23 |
+
"original_max_position_embeddings": 8192,
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class SodaHierConfig(PretrainedConfig):
|
| 28 |
+
"""Backbone-over-steps + depth-over-codebooks factorization of Mimi audio.
|
| 29 |
+
|
| 30 |
+
One backbone position ("step") is a text/special token or one whole audio
|
| 31 |
+
frame (8 Mimi codebooks summed at the input). The unified head predicts
|
| 32 |
+
the next step's text/special/semantic id over ids 0..unified_vocab_size-1
|
| 33 |
+
(identical to the flat id space); a small depth transformer predicts the
|
| 34 |
+
7 acoustic codebooks within each frame.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
model_type = "soda_hier"
|
| 38 |
+
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
# id space
|
| 42 |
+
vocab_size: int = 144644,
|
| 43 |
+
unified_vocab_size: int = 130308,
|
| 44 |
+
num_codebooks: int = 8,
|
| 45 |
+
codebook_size: int = 2048,
|
| 46 |
+
audio_id_lo: int = 128260,
|
| 47 |
+
# backbone
|
| 48 |
+
hidden_size: int = 768,
|
| 49 |
+
intermediate_size: int = 3072,
|
| 50 |
+
num_hidden_layers: int = 8,
|
| 51 |
+
num_attention_heads: int = 6,
|
| 52 |
+
num_key_value_heads: int = 6,
|
| 53 |
+
max_position_embeddings: int = 1024,
|
| 54 |
+
# depth transformer
|
| 55 |
+
depth_hidden_size: int = 384,
|
| 56 |
+
depth_intermediate_size: int = 1536,
|
| 57 |
+
depth_num_layers: int = 4,
|
| 58 |
+
depth_num_heads: int = 3,
|
| 59 |
+
depth_num_kv_heads: int = 3,
|
| 60 |
+
depth_head_dim: int = 128,
|
| 61 |
+
# shared
|
| 62 |
+
rope_theta: float = _DEFAULT_ROPE_THETA,
|
| 63 |
+
rope_scaling: dict | None = None,
|
| 64 |
+
rms_norm_eps: float = 1e-5,
|
| 65 |
+
bos_token_id: int = 128000,
|
| 66 |
+
eos_token_id: int = 128001,
|
| 67 |
+
**kwargs,
|
| 68 |
+
):
|
| 69 |
+
self.vocab_size = vocab_size
|
| 70 |
+
self.unified_vocab_size = unified_vocab_size
|
| 71 |
+
self.num_codebooks = num_codebooks
|
| 72 |
+
self.codebook_size = codebook_size
|
| 73 |
+
self.audio_id_lo = audio_id_lo
|
| 74 |
+
self.hidden_size = hidden_size
|
| 75 |
+
self.intermediate_size = intermediate_size
|
| 76 |
+
self.num_hidden_layers = num_hidden_layers
|
| 77 |
+
self.num_attention_heads = num_attention_heads
|
| 78 |
+
self.num_key_value_heads = num_key_value_heads
|
| 79 |
+
self.max_position_embeddings = max_position_embeddings
|
| 80 |
+
self.depth_hidden_size = depth_hidden_size
|
| 81 |
+
self.depth_intermediate_size = depth_intermediate_size
|
| 82 |
+
self.depth_num_layers = depth_num_layers
|
| 83 |
+
self.depth_num_heads = depth_num_heads
|
| 84 |
+
self.depth_num_kv_heads = depth_num_kv_heads
|
| 85 |
+
self.depth_head_dim = depth_head_dim
|
| 86 |
+
self.rope_theta = rope_theta
|
| 87 |
+
self.rope_scaling = dict(rope_scaling) if rope_scaling else dict(_DEFAULT_ROPE_SCALING)
|
| 88 |
+
self.rms_norm_eps = rms_norm_eps
|
| 89 |
+
kwargs.setdefault("tie_word_embeddings", False)
|
| 90 |
+
super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 91 |
+
|
| 92 |
+
def backbone_config(self) -> Qwen3Config:
|
| 93 |
+
return Qwen3Config(
|
| 94 |
+
vocab_size=self.vocab_size,
|
| 95 |
+
hidden_size=self.hidden_size,
|
| 96 |
+
intermediate_size=self.intermediate_size,
|
| 97 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 98 |
+
num_attention_heads=self.num_attention_heads,
|
| 99 |
+
num_key_value_heads=self.num_key_value_heads,
|
| 100 |
+
head_dim=self.hidden_size // self.num_attention_heads,
|
| 101 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 102 |
+
rope_theta=self.rope_theta,
|
| 103 |
+
rope_scaling=dict(self.rope_scaling),
|
| 104 |
+
rms_norm_eps=self.rms_norm_eps,
|
| 105 |
+
attention_bias=False,
|
| 106 |
+
tie_word_embeddings=False,
|
| 107 |
+
use_sliding_window=False,
|
| 108 |
+
use_cache=True,
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
def depth_config(self) -> Qwen3Config:
|
| 112 |
+
return Qwen3Config(
|
| 113 |
+
vocab_size=self.num_codebooks * self.codebook_size,
|
| 114 |
+
hidden_size=self.depth_hidden_size,
|
| 115 |
+
intermediate_size=self.depth_intermediate_size,
|
| 116 |
+
num_hidden_layers=self.depth_num_layers,
|
| 117 |
+
num_attention_heads=self.depth_num_heads,
|
| 118 |
+
num_key_value_heads=self.depth_num_kv_heads,
|
| 119 |
+
head_dim=self.depth_head_dim,
|
| 120 |
+
max_position_embeddings=self.num_codebooks,
|
| 121 |
+
rope_theta=self.rope_theta,
|
| 122 |
+
rope_scaling=dict(self.rope_scaling),
|
| 123 |
+
rms_norm_eps=self.rms_norm_eps,
|
| 124 |
+
attention_bias=False,
|
| 125 |
+
tie_word_embeddings=False,
|
| 126 |
+
use_sliding_window=False,
|
| 127 |
+
use_cache=False,
|
| 128 |
+
)
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1b68cb3ad1bbffaa87e635cc2e600cf3bb76d1baf12d022eff079c0ff5bd38f0
|
| 3 |
+
size 1232851184
|
modeling_soda_hier.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Marin Authors
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
|
| 4 |
+
"""HF modeling for the SODA hierarchical (backbone + depth) audio LM.
|
| 5 |
+
|
| 6 |
+
This file is copied verbatim into every exported checkpoint directory and
|
| 7 |
+
loaded via trust_remote_code, so it may import only torch/transformers.
|
| 8 |
+
|
| 9 |
+
The model consumes and produces the same flat frame-interleaved token stream
|
| 10 |
+
as the flattened arm (8 audio ids per Mimi frame: semantic then 7 acoustics),
|
| 11 |
+
so it is a drop-in for likelihood evals that gather next-token log-probs from
|
| 12 |
+
``model(ids).logits`` and for ``model.generate``:
|
| 13 |
+
|
| 14 |
+
- Internally, positions are grouped into backbone "steps": one text/special
|
| 15 |
+
token, or one whole frame (its 8 codebook embeddings summed).
|
| 16 |
+
- ``logits[t]`` is the model's true factorized conditional for token ``t+1``:
|
| 17 |
+
the 130,308-way unified head (text/special/semantic ids — identical to flat
|
| 18 |
+
ids 0..130307) when ``t+1`` starts a step, or the 2,048-way depth head for
|
| 19 |
+
codebook k mapped into its flat id block when ``t+1`` is acoustic. All other
|
| 20 |
+
vocabulary entries are -inf, so ``log_softmax`` reproduces the factorized
|
| 21 |
+
log-prob exactly.
|
| 22 |
+
- The depth factorization matches training exactly: codebook k is predicted
|
| 23 |
+
from the backbone hidden of the PREVIOUS step plus codebooks 0..k-2 of the
|
| 24 |
+
same frame (the immediately preceding codebook is not in the conditioning
|
| 25 |
+
set for k >= 2 — a property of the trained shifted-prefix scheme, replicated
|
| 26 |
+
verbatim).
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
from typing import ClassVar
|
| 30 |
+
|
| 31 |
+
import torch
|
| 32 |
+
import torch.nn as nn
|
| 33 |
+
from transformers import PreTrainedModel
|
| 34 |
+
from transformers.cache_utils import DynamicCache
|
| 35 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 36 |
+
from transformers.models.qwen3.modeling_qwen3 import Qwen3Model
|
| 37 |
+
|
| 38 |
+
from .configuration_soda_hier import SodaHierConfig
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _group_steps(ids: torch.Tensor, audio_id_lo: int, num_codebooks: int):
|
| 42 |
+
"""Map a flat interleaved stream to steps.
|
| 43 |
+
|
| 44 |
+
Returns (steps, step_of, slot_of): ``steps`` is (S, num_codebooks) with -1
|
| 45 |
+
padding on non-frame steps; ``step_of[t]``/``slot_of[t]`` locate position t.
|
| 46 |
+
"""
|
| 47 |
+
T = ids.shape[0]
|
| 48 |
+
step_of = torch.empty(T, dtype=torch.long)
|
| 49 |
+
slot_of = torch.empty(T, dtype=torch.long)
|
| 50 |
+
rows: list[list[int]] = []
|
| 51 |
+
run = 0
|
| 52 |
+
for t in range(T):
|
| 53 |
+
tok = int(ids[t])
|
| 54 |
+
if tok < audio_id_lo:
|
| 55 |
+
rows.append([tok] + [-1] * (num_codebooks - 1))
|
| 56 |
+
run = 0
|
| 57 |
+
else:
|
| 58 |
+
if run % num_codebooks == 0:
|
| 59 |
+
rows.append([-1] * num_codebooks)
|
| 60 |
+
rows[-1][run % num_codebooks] = tok
|
| 61 |
+
slot_of[t] = run % num_codebooks
|
| 62 |
+
step_of[t] = len(rows) - 1
|
| 63 |
+
run += 1
|
| 64 |
+
continue
|
| 65 |
+
step_of[t] = len(rows) - 1
|
| 66 |
+
slot_of[t] = 0
|
| 67 |
+
steps = torch.tensor(rows, dtype=torch.long)
|
| 68 |
+
return steps, step_of, slot_of
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class SodaHierForCausalLM(PreTrainedModel):
|
| 72 |
+
config_class = SodaHierConfig
|
| 73 |
+
_no_split_modules: ClassVar[list[str]] = ["Qwen3DecoderLayer"]
|
| 74 |
+
main_input_name = "input_ids"
|
| 75 |
+
_tied_weights_keys: ClassVar[list[str]] = []
|
| 76 |
+
|
| 77 |
+
def __init__(self, config: SodaHierConfig):
|
| 78 |
+
super().__init__(config)
|
| 79 |
+
self.backbone = Qwen3Model(config.backbone_config())
|
| 80 |
+
self.depth = Qwen3Model(config.depth_config())
|
| 81 |
+
e, e_d = config.hidden_size, config.depth_hidden_size
|
| 82 |
+
self.unified_head = nn.Linear(e, config.unified_vocab_size, bias=False)
|
| 83 |
+
self.bd_proj = nn.Linear(e, e_d, bias=False)
|
| 84 |
+
self.acoustic_heads = nn.ModuleList(
|
| 85 |
+
nn.Linear(e_d, config.codebook_size, bias=False) for _ in range(config.num_codebooks - 1)
|
| 86 |
+
)
|
| 87 |
+
self.post_init()
|
| 88 |
+
|
| 89 |
+
# ------------------------------------------------------------------ core
|
| 90 |
+
|
| 91 |
+
def _embed_steps(self, steps: torch.Tensor) -> torch.Tensor:
|
| 92 |
+
"""(S, num_codebooks) step ids (-1 = empty slot) -> (S, E) summed embeddings."""
|
| 93 |
+
valid = steps >= 0
|
| 94 |
+
emb = self.backbone.embed_tokens(steps.clamp(min=0))
|
| 95 |
+
return (emb * valid.unsqueeze(-1)).sum(dim=1)
|
| 96 |
+
|
| 97 |
+
def _depth_hidden_for_frames(self, cond: torch.Tensor, frames: torch.Tensor) -> torch.Tensor:
|
| 98 |
+
"""Teacher-forced depth pass. cond (F, E_d); frames (F, 8) LM ids -> (F, 8, E_d)."""
|
| 99 |
+
cfg = self.config
|
| 100 |
+
audio_idx = (frames - cfg.audio_id_lo).clamp(0, cfg.num_codebooks * cfg.codebook_size - 1)
|
| 101 |
+
prefix = self.depth.embed_tokens(audio_idx) # (F, 8, E_d)
|
| 102 |
+
shifted = torch.roll(prefix, 1, dims=1)
|
| 103 |
+
shifted[:, 0] = 0.0
|
| 104 |
+
x = cond.unsqueeze(1) + shifted
|
| 105 |
+
return self.depth(inputs_embeds=x).last_hidden_state
|
| 106 |
+
|
| 107 |
+
def _forward_one(self, ids: torch.Tensor) -> torch.Tensor:
|
| 108 |
+
"""One unpadded row (T,) -> logits (T, vocab)."""
|
| 109 |
+
cfg = self.config
|
| 110 |
+
dev = ids.device
|
| 111 |
+
steps, step_of, slot_of = _group_steps(ids.cpu(), cfg.audio_id_lo, cfg.num_codebooks)
|
| 112 |
+
steps, step_of, slot_of = steps.to(dev), step_of.to(dev), slot_of.to(dev)
|
| 113 |
+
T = ids.shape[0]
|
| 114 |
+
|
| 115 |
+
emb = self._embed_steps(steps) # (S, E)
|
| 116 |
+
h = self.backbone(inputs_embeds=emb.unsqueeze(0)).last_hidden_state[0] # (S, E)
|
| 117 |
+
u = self.unified_head(h) # (S, unified)
|
| 118 |
+
|
| 119 |
+
is_audio = ids >= cfg.audio_id_lo
|
| 120 |
+
is_frame_step = steps[:, 1] >= 0 # frame steps have slot-1 filled
|
| 121 |
+
frame_steps = torch.nonzero(is_frame_step, as_tuple=False)[:, 0]
|
| 122 |
+
# depth conditions on the hidden of the step BEFORE the frame
|
| 123 |
+
cond_frames = frame_steps[frame_steps >= 1]
|
| 124 |
+
d = None
|
| 125 |
+
frame_row = torch.full((steps.shape[0],), -1, dtype=torch.long, device=dev)
|
| 126 |
+
if len(cond_frames):
|
| 127 |
+
d = self._depth_hidden_for_frames(self.bd_proj(h[cond_frames - 1]), steps[cond_frames])
|
| 128 |
+
frame_row[cond_frames] = torch.arange(len(cond_frames), device=dev)
|
| 129 |
+
|
| 130 |
+
logits = torch.full((T, cfg.vocab_size), float("-inf"), dtype=h.dtype, device=dev)
|
| 131 |
+
# positions whose NEXT token starts a step: non-audio positions and slot-7 audio positions
|
| 132 |
+
primary = (~is_audio) | (slot_of == cfg.num_codebooks - 1)
|
| 133 |
+
logits[primary, : cfg.unified_vocab_size] = u[step_of[primary]]
|
| 134 |
+
# positions whose next token is acoustic codebook k+1 of the SAME frame
|
| 135 |
+
for k in range(cfg.num_codebooks - 1):
|
| 136 |
+
pos = torch.nonzero(is_audio & (slot_of == k), as_tuple=False)[:, 0]
|
| 137 |
+
if not len(pos):
|
| 138 |
+
continue
|
| 139 |
+
rows = frame_row[step_of[pos]]
|
| 140 |
+
ok = rows >= 0
|
| 141 |
+
lo = cfg.audio_id_lo + (k + 1) * cfg.codebook_size
|
| 142 |
+
if ok.any():
|
| 143 |
+
logits[pos[ok], lo : lo + cfg.codebook_size] = self.acoustic_heads[k](d[rows[ok], k])
|
| 144 |
+
if (~ok).any():
|
| 145 |
+
# frame at step 0: the factorization defines no conditional; keep finite
|
| 146 |
+
logits[pos[~ok]] = 0.0
|
| 147 |
+
return logits
|
| 148 |
+
|
| 149 |
+
def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs) -> CausalLMOutputWithPast:
|
| 150 |
+
if input_ids is None:
|
| 151 |
+
raise ValueError("SodaHierForCausalLM.forward requires input_ids")
|
| 152 |
+
rows = []
|
| 153 |
+
for b in range(input_ids.shape[0]):
|
| 154 |
+
ids = input_ids[b]
|
| 155 |
+
if attention_mask is not None:
|
| 156 |
+
length = int(attention_mask[b].sum())
|
| 157 |
+
logits_b = torch.zeros((ids.shape[0], self.config.vocab_size), dtype=torch.float32, device=ids.device)
|
| 158 |
+
logits_b[:length] = self._forward_one(ids[:length])
|
| 159 |
+
rows.append(logits_b)
|
| 160 |
+
else:
|
| 161 |
+
rows.append(self._forward_one(ids))
|
| 162 |
+
logits = torch.stack(rows)
|
| 163 |
+
loss = None
|
| 164 |
+
if labels is not None:
|
| 165 |
+
shift_logits = logits[:, :-1].reshape(-1, self.config.vocab_size)
|
| 166 |
+
shift_labels = labels[:, 1:].reshape(-1)
|
| 167 |
+
loss = nn.functional.cross_entropy(shift_logits, shift_labels, ignore_index=-100)
|
| 168 |
+
return CausalLMOutputWithPast(loss=loss, logits=logits)
|
| 169 |
+
|
| 170 |
+
# -------------------------------------------------------------- sampling
|
| 171 |
+
|
| 172 |
+
@staticmethod
|
| 173 |
+
def _sample(logits: torch.Tensor, do_sample: bool, temperature: float, top_p: float) -> int:
|
| 174 |
+
if not do_sample or temperature <= 0:
|
| 175 |
+
return int(logits.argmax())
|
| 176 |
+
probs = torch.softmax(logits / temperature, dim=-1)
|
| 177 |
+
if top_p is not None and top_p < 1.0:
|
| 178 |
+
sorted_probs, sorted_idx = probs.sort(descending=True)
|
| 179 |
+
cum = sorted_probs.cumsum(-1)
|
| 180 |
+
# drop tokens entirely beyond the nucleus; the crossing token stays
|
| 181 |
+
remove = (cum - sorted_probs) > top_p
|
| 182 |
+
sorted_probs[remove] = 0.0
|
| 183 |
+
sorted_probs /= sorted_probs.sum()
|
| 184 |
+
return int(sorted_idx[torch.multinomial(sorted_probs, 1)])
|
| 185 |
+
return int(torch.multinomial(probs, 1))
|
| 186 |
+
|
| 187 |
+
@torch.no_grad()
|
| 188 |
+
def generate(
|
| 189 |
+
self,
|
| 190 |
+
input_ids=None,
|
| 191 |
+
attention_mask=None,
|
| 192 |
+
max_new_tokens: int = 200,
|
| 193 |
+
do_sample: bool = False,
|
| 194 |
+
temperature: float = 1.0,
|
| 195 |
+
top_p: float = 1.0,
|
| 196 |
+
eos_token_id=None,
|
| 197 |
+
pad_token_id=None,
|
| 198 |
+
**ignored,
|
| 199 |
+
) -> torch.Tensor:
|
| 200 |
+
"""Two-stage autoregressive decode over the flat interleaved stream.
|
| 201 |
+
|
| 202 |
+
The backbone advances once per step with a KV cache; whenever the
|
| 203 |
+
unified head emits a semantic token, the depth transformer fills in
|
| 204 |
+
the frame's 7 acoustic codebooks before the backbone moves on. Only
|
| 205 |
+
whole frames are emitted: if fewer than 8 tokens of budget remain
|
| 206 |
+
when a frame starts, generation stops early instead.
|
| 207 |
+
"""
|
| 208 |
+
cfg = self.config
|
| 209 |
+
if input_ids.shape[0] != 1:
|
| 210 |
+
raise NotImplementedError("SodaHierForCausalLM.generate supports batch size 1")
|
| 211 |
+
dev = input_ids.device
|
| 212 |
+
eos = set()
|
| 213 |
+
if eos_token_id is not None:
|
| 214 |
+
eos = {eos_token_id} if isinstance(eos_token_id, int) else set(eos_token_id)
|
| 215 |
+
|
| 216 |
+
ids = input_ids[0]
|
| 217 |
+
steps, _, _ = _group_steps(ids.cpu(), cfg.audio_id_lo, cfg.num_codebooks)
|
| 218 |
+
steps = steps.to(dev)
|
| 219 |
+
emb = self._embed_steps(steps)
|
| 220 |
+
|
| 221 |
+
cache = DynamicCache()
|
| 222 |
+
out = self.backbone(inputs_embeds=emb.unsqueeze(0), past_key_values=cache, use_cache=True)
|
| 223 |
+
cache = out.past_key_values
|
| 224 |
+
h_last = out.last_hidden_state[0, -1]
|
| 225 |
+
step_pos = steps.shape[0]
|
| 226 |
+
|
| 227 |
+
generated: list[int] = []
|
| 228 |
+
while len(generated) < max_new_tokens:
|
| 229 |
+
primary = self._sample(self.unified_head(h_last), do_sample, temperature, top_p)
|
| 230 |
+
if primary < cfg.audio_id_lo: # text or special: a one-token step
|
| 231 |
+
generated.append(primary)
|
| 232 |
+
next_emb = self.backbone.embed_tokens(torch.tensor([primary], device=dev))[0]
|
| 233 |
+
if primary in eos:
|
| 234 |
+
break
|
| 235 |
+
else: # semantic token: emit a whole frame via the depth transformer
|
| 236 |
+
if max_new_tokens - len(generated) < cfg.num_codebooks:
|
| 237 |
+
break
|
| 238 |
+
cond = self.bd_proj(h_last)
|
| 239 |
+
frame = [primary]
|
| 240 |
+
xs = [cond]
|
| 241 |
+
for j in range(cfg.num_codebooks - 1):
|
| 242 |
+
d = self.depth(inputs_embeds=torch.stack(xs).unsqueeze(0)).last_hidden_state[0, -1]
|
| 243 |
+
idx = self._sample(self.acoustic_heads[j](d), do_sample, temperature, top_p)
|
| 244 |
+
frame.append(cfg.audio_id_lo + (j + 1) * cfg.codebook_size + idx)
|
| 245 |
+
xs.append(cond + self.depth.embed_tokens(torch.tensor(frame[-1] - cfg.audio_id_lo, device=dev)))
|
| 246 |
+
generated.extend(frame)
|
| 247 |
+
frame_t = torch.tensor(frame, device=dev)
|
| 248 |
+
next_emb = self.backbone.embed_tokens(frame_t).sum(dim=0)
|
| 249 |
+
if eos & set(frame):
|
| 250 |
+
break
|
| 251 |
+
out = self.backbone(
|
| 252 |
+
inputs_embeds=next_emb.view(1, 1, -1),
|
| 253 |
+
past_key_values=cache,
|
| 254 |
+
use_cache=True,
|
| 255 |
+
position_ids=torch.tensor([[step_pos]], device=dev),
|
| 256 |
+
)
|
| 257 |
+
cache = out.past_key_values
|
| 258 |
+
h_last = out.last_hidden_state[0, -1]
|
| 259 |
+
step_pos += 1
|
| 260 |
+
|
| 261 |
+
return torch.cat([ids, torch.tensor(generated, dtype=ids.dtype, device=dev)]).unsqueeze(0)
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d7c2f8c6c93d178640aabccd2c24b0a45fd2b0e31eb2e550ca6d76767e9dc49c
|
| 3 |
+
size 20167966
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": "<|begin_of_text|>",
|
| 4 |
+
"clean_up_tokenization_spaces": true,
|
| 5 |
+
"eos_token": "<|end_of_text|>",
|
| 6 |
+
"is_local": false,
|
| 7 |
+
"local_files_only": false,
|
| 8 |
+
"model_input_names": [
|
| 9 |
+
"input_ids",
|
| 10 |
+
"attention_mask"
|
| 11 |
+
],
|
| 12 |
+
"model_max_length": 131072,
|
| 13 |
+
"tokenizer_class": "PreTrainedTokenizerFast"
|
| 14 |
+
}
|