kiiic commited on
Commit
15d6fac
·
1 Parent(s): ea7cb64

Add application file

Browse files
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
app.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import subprocess
5
+ import tempfile
6
+ import time
7
+ from functools import lru_cache
8
+ from pathlib import Path
9
+
10
+ import gradio as gr
11
+
12
+ try:
13
+ import spaces # type: ignore[import-not-found]
14
+ except ImportError:
15
+ class _SpacesFallback:
16
+ @staticmethod
17
+ def GPU(func):
18
+ return func
19
+
20
+ spaces = _SpacesFallback()
21
+
22
+ from src.hf_inference import MossAudioHFInference, read_env_model_id, resolve_device
23
+
24
+ TITLE = "MOSS-Audio-8B-Thinking Demo"
25
+
26
+ DEFAULT_QUESTION = "Describe this audio."
27
+ DEFAULT_MAX_NEW_TOKENS = 1024
28
+ DEFAULT_TEMPERATURE = 1.0
29
+ DEFAULT_TOP_P = 1.0
30
+ DEFAULT_TOP_K = 50
31
+ VIDEO_EXTENSIONS = {".mp4"}
32
+
33
+
34
+ @lru_cache(maxsize=2)
35
+ def get_inference(model_name_or_path: str, device: str) -> MossAudioHFInference:
36
+ return MossAudioHFInference(
37
+ model_name_or_path=model_name_or_path,
38
+ device=device,
39
+ torch_dtype="auto",
40
+ enable_time_marker=True,
41
+ )
42
+
43
+
44
+ def format_status(model_name_or_path: str, device: str, elapsed_seconds: float) -> str:
45
+ return (
46
+ f"Model: `{model_name_or_path}` \n"
47
+ f"Device: `{device}` \n"
48
+ f"Elapsed: `{elapsed_seconds:.2f}s`"
49
+ )
50
+
51
+
52
+ def convert_media_to_mp3(media_path: str, output_path: str) -> None:
53
+ command = [
54
+ "ffmpeg",
55
+ "-y",
56
+ "-i",
57
+ media_path,
58
+ "-vn",
59
+ "-acodec",
60
+ "libmp3lame",
61
+ output_path,
62
+ ]
63
+ try:
64
+ subprocess.run(
65
+ command,
66
+ check=True,
67
+ stdout=subprocess.DEVNULL,
68
+ stderr=subprocess.PIPE,
69
+ text=True,
70
+ )
71
+ except subprocess.CalledProcessError as exc:
72
+ raise gr.Error(
73
+ f"Failed to extract audio from the uploaded media. Please make sure the mp4 file is valid and decodable.\n{exc.stderr}"
74
+ ) from exc
75
+
76
+
77
+ def resolve_media_path(audio_path: str | None, video_path: str | None) -> str | None:
78
+ if video_path:
79
+ return video_path
80
+ return audio_path
81
+
82
+
83
+ @spaces.GPU
84
+ def run_inference(
85
+ audio_path: str | None,
86
+ video_path: str | None,
87
+ question: str,
88
+ max_new_tokens: int,
89
+ temperature: float,
90
+ top_p: float,
91
+ top_k: int,
92
+ ):
93
+ prompt = (question or "").strip() or DEFAULT_QUESTION
94
+ model_name_or_path = read_env_model_id()
95
+ device = resolve_device()
96
+
97
+ try:
98
+ inference = get_inference(model_name_or_path, device)
99
+ except Exception as exc: # pragma: no cover - runtime environment dependent
100
+ raise gr.Error(
101
+ f"Failed to load the model. Please check the weights path or Hugging Face download status.\n{exc}"
102
+ ) from exc
103
+
104
+ media_path = resolve_media_path(audio_path, video_path)
105
+
106
+ try:
107
+ started_at = time.perf_counter()
108
+ with tempfile.TemporaryDirectory(prefix="moss-audio-") as temp_dir:
109
+ prepared_audio_path = media_path
110
+ if media_path and Path(media_path).suffix.lower() in VIDEO_EXTENSIONS:
111
+ prepared_audio_path = os.path.join(temp_dir, "input.mp3")
112
+ convert_media_to_mp3(media_path, prepared_audio_path)
113
+
114
+ answer = inference.generate(
115
+ question=prompt,
116
+ audio_path=prepared_audio_path,
117
+ max_new_tokens=max_new_tokens,
118
+ do_sample=temperature > 0,
119
+ temperature=temperature,
120
+ top_p=top_p,
121
+ top_k=top_k,
122
+ )
123
+ elapsed_seconds = time.perf_counter() - started_at
124
+ except Exception as exc: # pragma: no cover - runtime environment dependent
125
+ raise gr.Error(
126
+ f"Inference failed. Please make sure the uploaded file is readable and the format is supported.\n{exc}"
127
+ ) from exc
128
+
129
+ return answer, format_status(model_name_or_path, device, elapsed_seconds)
130
+
131
+
132
+ with gr.Blocks(title=TITLE) as demo:
133
+ gr.Markdown(f"# {TITLE}")
134
+
135
+ with gr.Row():
136
+ with gr.Column(scale=5):
137
+ audio_input = gr.Audio(
138
+ label="Audio",
139
+ sources=["upload", "microphone"],
140
+ type="filepath",
141
+ )
142
+ with gr.Accordion("Optional Video Input (.mp4)", open=False):
143
+ gr.Markdown(
144
+ "Upload an mp4 only when needed. If a video is provided, its audio track will be extracted and used for inference."
145
+ )
146
+ video_input = gr.File(
147
+ label="Video File",
148
+ file_types=[".mp4"],
149
+ type="filepath",
150
+ )
151
+ question_input = gr.Textbox(
152
+ label="Prompt",
153
+ lines=4,
154
+ value=DEFAULT_QUESTION,
155
+ placeholder="For example: Please transcribe this audio. Describe the sounds in this clip. What emotion does the speaker convey?",
156
+ )
157
+
158
+ with gr.Accordion("Advanced Settings", open=False):
159
+ max_new_tokens_input = gr.Slider(
160
+ minimum=64,
161
+ maximum=2048,
162
+ value=DEFAULT_MAX_NEW_TOKENS,
163
+ step=32,
164
+ label="Max New Tokens",
165
+ )
166
+ temperature_input = gr.Slider(
167
+ minimum=0.0,
168
+ maximum=1.5,
169
+ value=DEFAULT_TEMPERATURE,
170
+ step=0.1,
171
+ label="Temperature",
172
+ )
173
+ top_p_input = gr.Slider(
174
+ minimum=0.1,
175
+ maximum=1.0,
176
+ value=DEFAULT_TOP_P,
177
+ step=0.05,
178
+ label="Top-p",
179
+ )
180
+ top_k_input = gr.Slider(
181
+ minimum=1,
182
+ maximum=100,
183
+ value=DEFAULT_TOP_K,
184
+ step=1,
185
+ label="Top-k",
186
+ )
187
+
188
+ with gr.Row():
189
+ submit_btn = gr.Button("Generate", variant="primary")
190
+ gr.ClearButton(
191
+ [
192
+ audio_input,
193
+ video_input,
194
+ question_input,
195
+ max_new_tokens_input,
196
+ temperature_input,
197
+ top_p_input,
198
+ top_k_input,
199
+ ],
200
+ value="Clear",
201
+ )
202
+
203
+ with gr.Column(scale=5):
204
+ output_text = gr.Textbox(label="Output", lines=16)
205
+ status_text = gr.Markdown("Waiting for input.")
206
+
207
+ gr.Examples(
208
+ examples=[
209
+ ["Describe this audio."],
210
+ ["Please transcribe this audio."],
211
+ ["What is happening in this audio clip?"],
212
+ ["Describe the speaker's voice characteristics in detail."],
213
+ ["What emotion does the speaker convey?"],
214
+ ],
215
+ inputs=[question_input],
216
+ label="Prompt Examples",
217
+ )
218
+
219
+ submit_btn.click(
220
+ fn=run_inference,
221
+ inputs=[
222
+ audio_input,
223
+ video_input,
224
+ question_input,
225
+ max_new_tokens_input,
226
+ temperature_input,
227
+ top_p_input,
228
+ top_k_input,
229
+ ],
230
+ outputs=[output_text, status_text],
231
+ )
232
+
233
+
234
+ if __name__ == "__main__":
235
+ server_name = os.environ.get("MOSS_AUDIO_SERVER_NAME", "0.0.0.0")
236
+ server_port = int(os.environ.get("MOSS_AUDIO_SERVER_PORT", "7860"))
237
+ demo.queue(max_size=8).launch(
238
+ server_name=server_name,
239
+ server_port=server_port,
240
+ )
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ ffmpeg
requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu128
2
+ accelerate
3
+ einops>=0.8.0
4
+ gradio
5
+ numpy>=2.0
6
+ packaging
7
+ requests
8
+ safetensors>=0.4.0
9
+ scipy>=1.12.0
10
+ soundfile>=0.12.0
11
+ spaces
12
+ tiktoken>=0.12.0
13
+ torch==2.9.1
14
+ torchaudio==2.9.1
15
+ transformers==4.57.1
src/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """MOSS-Audio source package."""
src/audio_io.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import torchaudio
4
+
5
+
6
+ def load_audio(path: str, sample_rate: int):
7
+ waveform, original_sample_rate = torchaudio.load(path)
8
+ if waveform.size(0) > 1:
9
+ waveform = waveform.mean(dim=0, keepdim=True)
10
+ if original_sample_rate != sample_rate:
11
+ waveform = torchaudio.functional.resample(
12
+ waveform, orig_freq=original_sample_rate, new_freq=sample_rate
13
+ )
14
+ return waveform.squeeze(0).cpu().numpy()
src/configuration_moss_audio.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass, field
2
+ from typing import List, Optional
3
+
4
+ from transformers import PretrainedConfig, Qwen3Config
5
+
6
+
7
+ @dataclass
8
+ class MossAudioEncoderConfig:
9
+ d_model: int = 1280
10
+ output_dim: int = 1280
11
+ num_mel_bins: int = 128
12
+ encoder_layers: int = 32
13
+ encoder_attention_heads: int = 20
14
+ encoder_ffn_dim: int = 5120
15
+ downsample_rate: int = 8
16
+ downsample_hidden_size: int = 480
17
+ encoder_attention_window_size: int = 100
18
+ max_source_positions: int = 1500
19
+ dropout: float = 0.1
20
+ attention_dropout: float = 0.1
21
+ activation_dropout: float = 0.0
22
+ activation_function: str = "gelu"
23
+ layer_norm_eps: float = 1e-5
24
+ _attn_implementation: str = "eager"
25
+ pretrained_path: str = ""
26
+ deepstack_encoder_layer_indexes: List[int] = field(
27
+ default_factory=lambda: [8, 16, 24]
28
+ )
29
+
30
+ @classmethod
31
+ def from_dict(cls, config_dict):
32
+ if config_dict is None:
33
+ return cls()
34
+ allowed_keys = set(cls.__dataclass_fields__.keys())
35
+ filtered = {k: v for k, v in config_dict.items() if k in allowed_keys}
36
+ return cls(**filtered)
37
+
38
+ def to_dict(self):
39
+ return {
40
+ "d_model": self.d_model,
41
+ "output_dim": self.output_dim,
42
+ "num_mel_bins": self.num_mel_bins,
43
+ "encoder_layers": self.encoder_layers,
44
+ "encoder_attention_heads": self.encoder_attention_heads,
45
+ "encoder_ffn_dim": self.encoder_ffn_dim,
46
+ "downsample_rate": self.downsample_rate,
47
+ "downsample_hidden_size": self.downsample_hidden_size,
48
+ "encoder_attention_window_size": self.encoder_attention_window_size,
49
+ "max_source_positions": self.max_source_positions,
50
+ "dropout": self.dropout,
51
+ "attention_dropout": self.attention_dropout,
52
+ "activation_dropout": self.activation_dropout,
53
+ "activation_function": self.activation_function,
54
+ "layer_norm_eps": self.layer_norm_eps,
55
+ "_attn_implementation": self._attn_implementation,
56
+ "pretrained_path": self.pretrained_path,
57
+ "deepstack_encoder_layer_indexes": list(
58
+ self.deepstack_encoder_layer_indexes or []
59
+ ),
60
+ }
61
+
62
+
63
+ class MossAudioConfig(PretrainedConfig):
64
+ model_type = "moss_audio"
65
+ is_composition = True
66
+
67
+ def __init__(
68
+ self,
69
+ audio_config=None,
70
+ language_config=None,
71
+ adapter_hidden_size=8192,
72
+ ignore_index=-100,
73
+ deepstack_num_inject_layers: Optional[int] = None,
74
+ **kwargs,
75
+ ):
76
+ if isinstance(audio_config, dict):
77
+ audio_config = MossAudioEncoderConfig.from_dict(audio_config)
78
+ elif audio_config is None:
79
+ audio_config = MossAudioEncoderConfig()
80
+
81
+ if isinstance(language_config, dict):
82
+ language_config = Qwen3Config(**language_config)
83
+ elif language_config is None:
84
+ language_config = Qwen3Config()
85
+
86
+ self.audio_config = audio_config
87
+ self.language_config = language_config
88
+ self.adapter_hidden_size = adapter_hidden_size
89
+ self.ignore_index = ignore_index
90
+ self.deepstack_num_inject_layers = deepstack_num_inject_layers
91
+
92
+ propagate_keys = {
93
+ "num_hidden_layers",
94
+ "eos_token_id",
95
+ "bos_token_id",
96
+ "vocab_size",
97
+ "tie_word_embeddings",
98
+ }
99
+ for key in ("num_hidden_layers", "eos_token_id", "bos_token_id", "vocab_size"):
100
+ kwargs.setdefault(key, getattr(language_config, key, None))
101
+ kwargs.setdefault("tie_word_embeddings", False)
102
+
103
+ if hasattr(language_config, "to_dict"):
104
+ language_keys = set(language_config.to_dict().keys())
105
+ for key in list(kwargs.keys()):
106
+ if key in language_keys and key not in propagate_keys:
107
+ kwargs.pop(key)
108
+
109
+ super().__init__(**kwargs)
110
+
111
+ def to_dict(self):
112
+ output = super().to_dict()
113
+ output["audio_config"] = (
114
+ self.audio_config.to_dict()
115
+ if hasattr(self.audio_config, "to_dict")
116
+ else self.audio_config
117
+ )
118
+ output["language_config"] = (
119
+ self.language_config.to_dict()
120
+ if hasattr(self.language_config, "to_dict")
121
+ else self.language_config
122
+ )
123
+ output["adapter_hidden_size"] = self.adapter_hidden_size
124
+ output["ignore_index"] = self.ignore_index
125
+ output["deepstack_num_inject_layers"] = self.deepstack_num_inject_layers
126
+ return output
127
+
128
+
129
+ __all__ = ["MossAudioEncoderConfig", "MossAudioConfig"]
src/hf_inference.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HuggingFace inference wrapper for MOSS-Audio."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Optional
7
+
8
+ import torch
9
+
10
+ from src.audio_io import load_audio
11
+ from src.modeling_moss_audio import MossAudioModel
12
+ from src.processing_moss_audio import MossAudioProcessor
13
+
14
+ DEFAULT_MODEL_ID = "OpenMOSS-Team/MOSS-Audio-8B-Thinking"
15
+
16
+
17
+ def read_env_model_id() -> str:
18
+ return os.environ.get("MOSS_AUDIO_MODEL_ID", DEFAULT_MODEL_ID)
19
+
20
+
21
+ def resolve_device() -> str:
22
+ if torch.cuda.is_available():
23
+ return "cuda:0"
24
+ return "cpu"
25
+
26
+
27
+ class MossAudioHFInference:
28
+ """Thin wrapper that loads model + processor and exposes a single
29
+ ``generate`` method for both audio-grounded and text-only queries."""
30
+
31
+ def __init__(
32
+ self,
33
+ model_name_or_path: str = DEFAULT_MODEL_ID,
34
+ device: str = "cuda:0",
35
+ torch_dtype: str = "auto",
36
+ enable_time_marker: bool = True,
37
+ ):
38
+ self.device = device
39
+ load_kwargs = {
40
+ "trust_remote_code": True,
41
+ "torch_dtype": torch_dtype,
42
+ "low_cpu_mem_usage": True,
43
+ }
44
+ load_kwargs["device_map"] = {"": device}
45
+
46
+ self.model = MossAudioModel.from_pretrained(
47
+ model_name_or_path,
48
+ **load_kwargs,
49
+ )
50
+ self.model.eval()
51
+ self.processor = MossAudioProcessor.from_pretrained(
52
+ model_name_or_path,
53
+ trust_remote_code=True,
54
+ enable_time_marker=enable_time_marker,
55
+ )
56
+
57
+ @torch.no_grad()
58
+ def generate(
59
+ self,
60
+ question: str,
61
+ audio_path: Optional[str] = None,
62
+ max_new_tokens: int = 1024,
63
+ num_beams: int = 1,
64
+ do_sample: bool = True,
65
+ temperature: float = 1.0,
66
+ top_p: float = 1.0,
67
+ top_k: int = 50,
68
+ ) -> str:
69
+ if audio_path is not None:
70
+ raw_audio = load_audio(audio_path, sample_rate=self.processor.config.mel_sr)
71
+ inputs = self.processor(text=question, audios=[raw_audio], return_tensors="pt")
72
+ else:
73
+ inputs = self.processor(text=question, return_tensors="pt")
74
+
75
+ inputs = inputs.to(self.model.device)
76
+ if inputs.get("audio_data") is not None:
77
+ inputs["audio_data"] = inputs["audio_data"].to(self.model.dtype)
78
+
79
+ audio_input_mask = inputs["input_ids"] == self.processor.audio_token_id
80
+ inputs["audio_input_mask"] = audio_input_mask
81
+
82
+ gen_kwargs = dict(
83
+ max_new_tokens=max_new_tokens,
84
+ num_beams=num_beams,
85
+ use_cache=True,
86
+ )
87
+ if do_sample:
88
+ gen_kwargs.update(
89
+ do_sample=True, temperature=temperature, top_p=top_p, top_k=top_k
90
+ )
91
+ else:
92
+ gen_kwargs["do_sample"] = False
93
+
94
+ generated_ids = self.model.generate(**inputs, **gen_kwargs)
95
+
96
+ input_len = inputs["input_ids"].shape[1]
97
+ return self.processor.decode(
98
+ generated_ids[0, input_len:], skip_special_tokens=True
99
+ )
100
+
101
+
102
+ __all__ = ["MossAudioHFInference", "read_env_model_id", "resolve_device"]
src/modeling_moss_audio.py ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Optional, Tuple, Union
2
+
3
+ import math
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ from transformers.generation.utils import GenerationMixin
8
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
9
+ from transformers.modeling_utils import PreTrainedModel
10
+ from transformers.models.qwen3.modeling_qwen3 import Qwen3DecoderLayer, Qwen3Model
11
+ from transformers.models.whisper.modeling_whisper import WhisperEncoderLayer
12
+ from transformers.utils.auto_docstring import auto_docstring
13
+
14
+ from src.configuration_moss_audio import MossAudioConfig, MossAudioEncoderConfig
15
+
16
+
17
+ class SinusoidsPositionEmbedding(nn.Module):
18
+ def __init__(self, num_positions: int, embedding_dim: int):
19
+ super().__init__()
20
+ max_timescale = 10000.0
21
+ log_timescale_increment = math.log(max_timescale) / (embedding_dim // 2 - 1)
22
+ inv_timescales = torch.exp(
23
+ -log_timescale_increment * torch.arange(embedding_dim // 2).float()
24
+ )
25
+ self.register_buffer("inv_timescales", inv_timescales, persistent=False)
26
+
27
+ def forward(self, seq_len: int, device: torch.device):
28
+ scaled_time = torch.arange(
29
+ seq_len, device=device, dtype=self.inv_timescales.dtype
30
+ ).unsqueeze(1) * self.inv_timescales.unsqueeze(0)
31
+ sin_emb = torch.sin(scaled_time)
32
+ cos_emb = torch.cos(scaled_time)
33
+ pos_emb = torch.cat([sin_emb, cos_emb], dim=1)
34
+ return pos_emb.unsqueeze(0)
35
+
36
+
37
+ class MossAudioEncoder(nn.Module):
38
+ """Audio encoder with conv-stem downsampling and Whisper transformer layers."""
39
+
40
+ def __init__(self, config: MossAudioEncoderConfig):
41
+ super().__init__()
42
+ self.config = config
43
+ self.gelu = nn.GELU()
44
+
45
+ self.conv1 = nn.Conv2d(
46
+ 1,
47
+ config.downsample_hidden_size,
48
+ kernel_size=(3, 3),
49
+ stride=(2, 2),
50
+ padding=(1, 1),
51
+ )
52
+ self.conv2 = nn.Conv2d(
53
+ config.downsample_hidden_size,
54
+ config.downsample_hidden_size,
55
+ kernel_size=(3, 3),
56
+ stride=(2, 2),
57
+ padding=(1, 1),
58
+ )
59
+ self.conv3 = nn.Conv2d(
60
+ config.downsample_hidden_size,
61
+ config.downsample_hidden_size,
62
+ kernel_size=(3, 3),
63
+ stride=(2, 2),
64
+ padding=(1, 1),
65
+ )
66
+
67
+ self.stem_proj = nn.Linear(config.downsample_hidden_size * 16, config.d_model)
68
+ self.embed_positions = SinusoidsPositionEmbedding(
69
+ config.max_source_positions, config.d_model
70
+ )
71
+ self.layers = nn.ModuleList(
72
+ [WhisperEncoderLayer(config) for _ in range(config.encoder_layers)]
73
+ )
74
+ self.layer_norm = nn.LayerNorm(config.d_model, eps=config.layer_norm_eps)
75
+ self.out_proj = (
76
+ nn.Linear(config.d_model, config.output_dim, bias=False)
77
+ if config.output_dim != config.d_model
78
+ else nn.Identity()
79
+ )
80
+
81
+ self._deepstack_indexes_set = set(config.deepstack_encoder_layer_indexes or [])
82
+
83
+ def _compute_downsampled_length(self, lengths: torch.Tensor) -> torch.Tensor:
84
+ def conv_out_len(length):
85
+ return (length - 1) // 2 + 1
86
+
87
+ length1 = conv_out_len(lengths)
88
+ length2 = conv_out_len(length1)
89
+ length3 = conv_out_len(length2)
90
+ return length3
91
+
92
+ def forward(
93
+ self,
94
+ input_features: torch.Tensor,
95
+ feature_lens: Optional[torch.Tensor] = None,
96
+ output_deepstack_hidden_states: bool = True,
97
+ ):
98
+ if input_features.dim() == 2:
99
+ input_features = input_features.unsqueeze(0)
100
+
101
+ if feature_lens is None:
102
+ feature_lens = torch.full(
103
+ (input_features.size(0),),
104
+ input_features.size(-1),
105
+ device=input_features.device,
106
+ dtype=torch.long,
107
+ )
108
+
109
+ downsampled_lengths = self._compute_downsampled_length(feature_lens)
110
+
111
+ x = input_features.unsqueeze(1)
112
+ x = self.gelu(self.conv1(x))
113
+ x = self.gelu(self.conv2(x))
114
+ x = self.gelu(self.conv3(x))
115
+
116
+ x = x.permute(0, 3, 1, 2).contiguous().flatten(2)
117
+ x = self.stem_proj(x)
118
+
119
+ max_len = int(downsampled_lengths.max().item())
120
+ if x.size(1) > max_len:
121
+ x = x[:, :max_len, :]
122
+
123
+ positions = self.embed_positions(x.shape[1], x.device)
124
+ x = x + positions.to(x.dtype)
125
+
126
+ padding_mask = (
127
+ torch.arange(x.size(1), device=x.device)[None, :]
128
+ >= downsampled_lengths[:, None]
129
+ )
130
+ attention_mask = (1.0 - (~padding_mask).to(dtype=x.dtype)) * torch.finfo(
131
+ x.dtype
132
+ ).min
133
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(1)
134
+
135
+ deepstack_states: List[torch.Tensor] = []
136
+ for layer_idx, layer in enumerate(self.layers):
137
+ layer_outputs = layer(
138
+ x,
139
+ attention_mask,
140
+ layer_head_mask=None,
141
+ output_attentions=False,
142
+ )
143
+ x = layer_outputs[0]
144
+ if output_deepstack_hidden_states and layer_idx in self._deepstack_indexes_set:
145
+ deepstack_states.append(x)
146
+
147
+ x = self.layer_norm(x)
148
+ x = self.out_proj(x)
149
+
150
+ return BaseModelOutputWithPast(
151
+ last_hidden_state=x,
152
+ hidden_states=tuple(deepstack_states) if output_deepstack_hidden_states else None,
153
+ )
154
+
155
+
156
+ class GatedMLP(nn.Module):
157
+ def __init__(self, input_size, hidden_size, output_size):
158
+ super().__init__()
159
+ self.gate_proj = nn.Linear(input_size, hidden_size, bias=False)
160
+ self.up_proj = nn.Linear(input_size, hidden_size, bias=False)
161
+ self.down_proj = nn.Linear(hidden_size, output_size, bias=False)
162
+ self.act_fn = nn.SiLU()
163
+
164
+ def forward(self, x):
165
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
166
+
167
+
168
+ @auto_docstring
169
+ class MossAudioPreTrainedModel(PreTrainedModel):
170
+ config_class = MossAudioConfig
171
+ config: MossAudioConfig
172
+ base_model_prefix = ""
173
+ supports_gradient_checkpointing = True
174
+ _no_split_modules = ["Qwen3DecoderLayer"]
175
+ _skip_keys_device_placement = ["past_key_values"]
176
+ _supports_flash_attn = True
177
+ _supports_sdpa = True
178
+ _supports_flex_attn = True
179
+ _can_compile_fullgraph = False
180
+ _supports_attention_backend = True
181
+ _can_record_outputs = {"hidden_states": Qwen3DecoderLayer}
182
+
183
+
184
+ class MossAudioModel(MossAudioPreTrainedModel, GenerationMixin):
185
+ config_class = MossAudioConfig
186
+ _tied_weights_keys: List[str] = []
187
+
188
+ def __init__(self, config: MossAudioConfig):
189
+ super().__init__(config)
190
+
191
+ self.audio_encoder = MossAudioEncoder(config.audio_config)
192
+ self.language_model = Qwen3Model(config.language_config)
193
+
194
+ self.audio_adapter = GatedMLP(
195
+ input_size=config.audio_config.output_dim,
196
+ hidden_size=config.adapter_hidden_size,
197
+ output_size=config.language_config.hidden_size,
198
+ )
199
+
200
+ deepstack_k = len(
201
+ getattr(config.audio_config, "deepstack_encoder_layer_indexes", []) or []
202
+ )
203
+ if config.deepstack_num_inject_layers is not None:
204
+ deepstack_k = min(deepstack_k, int(config.deepstack_num_inject_layers))
205
+ self.deepstack_audio_merger_list = nn.ModuleList(
206
+ [
207
+ GatedMLP(
208
+ input_size=config.audio_config.output_dim,
209
+ hidden_size=config.adapter_hidden_size,
210
+ output_size=config.language_config.hidden_size,
211
+ )
212
+ for _ in range(deepstack_k)
213
+ ]
214
+ )
215
+
216
+ self.vocab_size = config.language_config.vocab_size
217
+ self.lm_head = nn.Linear(
218
+ config.language_config.hidden_size, self.vocab_size, bias=False
219
+ )
220
+ self.post_init()
221
+
222
+ def get_input_embeddings(self):
223
+ return self.language_model.get_input_embeddings()
224
+
225
+ def set_input_embeddings(self, value):
226
+ self.language_model.set_input_embeddings(value)
227
+
228
+ def get_output_embeddings(self):
229
+ return self.lm_head
230
+
231
+ def set_output_embeddings(self, new_embeddings):
232
+ self.lm_head = new_embeddings
233
+
234
+ def get_audio_features(self, input_features, feature_lens):
235
+ audio_outputs = self.audio_encoder(
236
+ input_features=input_features,
237
+ feature_lens=feature_lens,
238
+ output_deepstack_hidden_states=True,
239
+ )
240
+ deepstack = (
241
+ list(audio_outputs.hidden_states)
242
+ if audio_outputs.hidden_states is not None
243
+ else None
244
+ )
245
+ return audio_outputs.last_hidden_state, deepstack
246
+
247
+ def _apply_deepstack_to_hidden_states(
248
+ self,
249
+ hidden_states: torch.Tensor,
250
+ audio_input_mask: torch.Tensor,
251
+ deepstack_embeds: torch.Tensor,
252
+ ) -> torch.Tensor:
253
+ audio_input_mask = audio_input_mask.to(hidden_states.device)
254
+ deepstack_embeds = deepstack_embeds.to(hidden_states.device, hidden_states.dtype)
255
+ flat = deepstack_embeds.reshape(-1, deepstack_embeds.shape[-1])
256
+ updated_hidden_states = hidden_states.clone()
257
+ updated_hidden_states[audio_input_mask] = (
258
+ updated_hidden_states[audio_input_mask] + flat
259
+ )
260
+ return updated_hidden_states
261
+
262
+ def _register_llm_deepstack_hooks(
263
+ self,
264
+ audio_input_mask: torch.Tensor,
265
+ deepstack_audio_embeds: List[torch.Tensor],
266
+ ):
267
+ if deepstack_audio_embeds is None or len(deepstack_audio_embeds) == 0:
268
+ return []
269
+
270
+ layers = getattr(self.language_model, "layers", None)
271
+ if layers is None:
272
+ raise RuntimeError(
273
+ "Qwen3Model does not expose `.layers`; cannot register DeepStack hooks."
274
+ )
275
+
276
+ num_inject = len(deepstack_audio_embeds)
277
+ handles = []
278
+
279
+ for layer_idx, layer in enumerate(layers):
280
+ if layer_idx >= num_inject:
281
+ break
282
+
283
+ def _make_llm_hook(k: int):
284
+ def _hook(_module, _inputs, _output):
285
+ if isinstance(_output, (tuple, list)):
286
+ hidden_states = _output[0]
287
+ new_hidden_states = self._apply_deepstack_to_hidden_states(
288
+ hidden_states, audio_input_mask, deepstack_audio_embeds[k]
289
+ )
290
+ return (new_hidden_states,) + tuple(_output[1:])
291
+ return self._apply_deepstack_to_hidden_states(
292
+ _output, audio_input_mask, deepstack_audio_embeds[k]
293
+ )
294
+
295
+ return _hook
296
+
297
+ handles.append(layer.register_forward_hook(_make_llm_hook(layer_idx)))
298
+
299
+ return handles
300
+
301
+ def forward(
302
+ self,
303
+ input_ids: torch.LongTensor = None,
304
+ attention_mask: Optional[torch.Tensor] = None,
305
+ position_ids: Optional[torch.LongTensor] = None,
306
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
307
+ inputs_embeds: Optional[torch.FloatTensor] = None,
308
+ labels: Optional[torch.LongTensor] = None,
309
+ use_cache: Optional[bool] = None,
310
+ output_attentions: Optional[bool] = None,
311
+ output_hidden_states: Optional[bool] = None,
312
+ return_dict: Optional[bool] = None,
313
+ audio_data: Optional[torch.FloatTensor] = None,
314
+ audio_data_seqlens: Optional[torch.Tensor] = None,
315
+ audio_input_mask: Optional[torch.Tensor] = None,
316
+ cache_position: Optional[torch.LongTensor] = None,
317
+ **kwargs: Any,
318
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
319
+ output_attentions = (
320
+ output_attentions
321
+ if output_attentions is not None
322
+ else self.config.output_attentions
323
+ )
324
+ output_hidden_states = (
325
+ output_hidden_states
326
+ if output_hidden_states is not None
327
+ else self.config.output_hidden_states
328
+ )
329
+ return_dict = (
330
+ return_dict if return_dict is not None else self.config.use_return_dict
331
+ )
332
+
333
+ if inputs_embeds is None:
334
+ inputs_embeds = self.get_input_embeddings()(input_ids)
335
+
336
+ hook_handles = []
337
+ if audio_data is not None:
338
+ if audio_input_mask is None:
339
+ raise ValueError("audio_input_mask is required when audio_data is provided.")
340
+
341
+ audio_embeds, deepstack = self.get_audio_features(
342
+ audio_data, audio_data_seqlens
343
+ )
344
+ audio_embeds = self.audio_adapter(audio_embeds)
345
+
346
+ audio_token_count = int(audio_input_mask.to(torch.int32).sum().item())
347
+ if audio_token_count != int(audio_embeds.shape[1]):
348
+ raise ValueError(
349
+ f"Audio token count mismatch: audio_input_mask has {audio_token_count} audio tokens, "
350
+ f"but audio_embeds has length {int(audio_embeds.shape[1])}."
351
+ )
352
+
353
+ mask_expanded = audio_input_mask.unsqueeze(-1).expand_as(inputs_embeds)
354
+ inputs_embeds = inputs_embeds.clone()
355
+ inputs_embeds.masked_scatter_(mask_expanded, audio_embeds)
356
+
357
+ if deepstack is not None and len(self.deepstack_audio_merger_list) > 0:
358
+ deepstack_audio_embeds = []
359
+ for index, one_hidden_state in enumerate(
360
+ deepstack[: len(self.deepstack_audio_merger_list)]
361
+ ):
362
+ deepstack_embed = self.deepstack_audio_merger_list[index](
363
+ one_hidden_state
364
+ )
365
+ if int(deepstack_embed.shape[1]) != audio_token_count:
366
+ raise ValueError(
367
+ f"DeepStack audio seq_len mismatch at index {index}: "
368
+ f"expected {audio_token_count}, got {int(deepstack_embed.shape[1])}."
369
+ )
370
+ deepstack_audio_embeds.append(deepstack_embed)
371
+
372
+ try:
373
+ hook_handles = self._register_llm_deepstack_hooks(
374
+ audio_input_mask, deepstack_audio_embeds
375
+ )
376
+ except Exception:
377
+ for handle in hook_handles:
378
+ handle.remove()
379
+ raise
380
+
381
+ try:
382
+ outputs = self.language_model(
383
+ input_ids=None,
384
+ attention_mask=attention_mask,
385
+ position_ids=position_ids,
386
+ past_key_values=past_key_values,
387
+ inputs_embeds=inputs_embeds,
388
+ use_cache=use_cache,
389
+ output_attentions=output_attentions,
390
+ output_hidden_states=output_hidden_states,
391
+ return_dict=return_dict,
392
+ cache_position=cache_position,
393
+ **kwargs,
394
+ )
395
+ finally:
396
+ for handle in hook_handles:
397
+ handle.remove()
398
+
399
+ hidden_states = outputs[0]
400
+ logits = self.lm_head(hidden_states)
401
+
402
+ loss = None
403
+ if labels is not None:
404
+ shift_logits = logits[..., :-1, :].contiguous()
405
+ shift_labels = labels[..., 1:].contiguous()
406
+ loss_fct = nn.CrossEntropyLoss(ignore_index=self.config.ignore_index)
407
+ shift_logits = shift_logits.view(
408
+ -1, self.config.language_config.vocab_size
409
+ )
410
+ shift_labels = shift_labels.view(-1)
411
+ shift_labels = shift_labels.to(shift_logits.device)
412
+ loss = loss_fct(shift_logits, shift_labels)
413
+
414
+ if not return_dict:
415
+ output = (logits,) + outputs[1:]
416
+ return ((loss,) + output) if loss is not None else output
417
+
418
+ return CausalLMOutputWithPast(
419
+ loss=loss,
420
+ logits=logits,
421
+ past_key_values=outputs.past_key_values,
422
+ hidden_states=outputs.hidden_states,
423
+ attentions=outputs.attentions,
424
+ )
425
+
426
+ def prepare_inputs_for_generation(
427
+ self,
428
+ input_ids,
429
+ past_key_values=None,
430
+ attention_mask=None,
431
+ inputs_embeds=None,
432
+ cache_position=None,
433
+ **kwargs,
434
+ ):
435
+ position_ids = kwargs.get("position_ids", None)
436
+ if cache_position is not None and cache_position[0] > 0:
437
+ input_ids = input_ids[:, -1:]
438
+ if position_ids is not None:
439
+ position_ids = position_ids[:, -1:]
440
+ audio_data = None
441
+ audio_input_mask = None
442
+ audio_data_seqlens = None
443
+ else:
444
+ audio_data = kwargs.get("audio_data", None)
445
+ audio_input_mask = kwargs.get("audio_input_mask", None)
446
+ audio_data_seqlens = kwargs.get("audio_data_seqlens", None)
447
+
448
+ if inputs_embeds is not None and past_key_values is None:
449
+ model_inputs = {"inputs_embeds": inputs_embeds}
450
+ else:
451
+ model_inputs = {"input_ids": input_ids}
452
+
453
+ model_inputs.update(
454
+ {
455
+ "past_key_values": past_key_values,
456
+ "use_cache": kwargs.get("use_cache"),
457
+ "attention_mask": attention_mask,
458
+ "position_ids": position_ids,
459
+ "audio_data": audio_data,
460
+ "audio_input_mask": audio_input_mask,
461
+ "audio_data_seqlens": audio_data_seqlens,
462
+ }
463
+ )
464
+
465
+ return model_inputs
466
+
467
+
468
+ __all__ = [
469
+ "MossAudioEncoderConfig",
470
+ "MossAudioConfig",
471
+ "MossAudioModel",
472
+ ]
src/processing_moss_audio.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.util
2
+ import os
3
+ import re
4
+ import sys
5
+ import types
6
+ from dataclasses import dataclass
7
+ from typing import List, Optional, Sequence, Union
8
+
9
+ import numpy as np
10
+ import torch
11
+ from transformers import AutoTokenizer, BatchEncoding
12
+
13
+
14
+ @dataclass
15
+ class MelConfig:
16
+ mel_sr: int = 16000
17
+ mel_dim: int = 128
18
+ mel_n_fft: int = 400
19
+ mel_hop_length: int = 160
20
+ mel_dtype: torch.dtype = torch.bfloat16
21
+ use_whisper_feature_extractor: bool = True
22
+
23
+
24
+ def load_chat_template(template_path: str, mossflux_path: str = None) -> List:
25
+ if mossflux_path is None:
26
+ template_dir = os.path.dirname(os.path.abspath(template_path))
27
+ current = template_dir
28
+ while current and os.path.basename(current) != "mossLite":
29
+ parent = os.path.dirname(current)
30
+ if parent == current:
31
+ break
32
+ current = parent
33
+ if os.path.basename(current) == "mossLite":
34
+ mossflux_path = os.path.join(current, "mossflux")
35
+
36
+ if mossflux_path and mossflux_path not in sys.path:
37
+ sys.path.insert(0, mossflux_path)
38
+
39
+ spec = importlib.util.spec_from_file_location("chat_template_module", template_path)
40
+ module = importlib.util.module_from_spec(spec)
41
+ sys.modules["chat_template_module"] = module
42
+ spec.loader.exec_module(module)
43
+ return module.chat_template
44
+
45
+
46
+ class MossAudioProcessor:
47
+ _AUDIO_SPAN_RE = re.compile(r"<\|audio_bos\|>(?:<\|AUDIO\|>)+<\|audio_eos\|>")
48
+ _auto_class = None
49
+
50
+ @classmethod
51
+ def register_for_auto_class(cls, auto_class="AutoProcessor"):
52
+ if not isinstance(auto_class, str):
53
+ auto_class = auto_class.__name__
54
+ cls._auto_class = auto_class
55
+
56
+ def __init__(
57
+ self,
58
+ tokenizer,
59
+ *,
60
+ mel_config: Optional[MelConfig] = None,
61
+ template_path: Optional[str] = None,
62
+ enable_time_marker: bool = True,
63
+ audio_token_id: int = 151654,
64
+ audio_start_id: int = 151669,
65
+ audio_end_id: int = 151670,
66
+ ):
67
+ self._base_tokenizer = tokenizer
68
+ self.tokenizer = tokenizer
69
+ self.audio_token_id = int(audio_token_id)
70
+ self.audio_start_id = int(audio_start_id)
71
+ self.audio_end_id = int(audio_end_id)
72
+ self.chat_template = (
73
+ None if template_path is None else load_chat_template(template_path)
74
+ )
75
+ self.custom_texts = {}
76
+ self.enable_time_marker = bool(enable_time_marker)
77
+ self.config = mel_config or MelConfig()
78
+ self._whisper_feature_extractor = None
79
+
80
+ alias_map = {
81
+ "<|AUDIO|>": self.audio_token_id,
82
+ "<|audio_bos|>": self.audio_start_id,
83
+ "<|audio_eos|>": self.audio_end_id,
84
+ }
85
+ orig_convert_tokens_to_ids = self.tokenizer.convert_tokens_to_ids
86
+
87
+ def _patched_convert_tokens_to_ids(tokenizer_self, tokens):
88
+ if isinstance(tokens, (list, tuple)):
89
+ converted = [
90
+ _patched_convert_tokens_to_ids(tokenizer_self, token)
91
+ for token in tokens
92
+ ]
93
+ return converted if isinstance(tokens, list) else tuple(converted)
94
+ if isinstance(tokens, str) and tokens in alias_map:
95
+ return alias_map[tokens]
96
+ return orig_convert_tokens_to_ids(tokens)
97
+
98
+ self.tokenizer.convert_tokens_to_ids = types.MethodType(
99
+ _patched_convert_tokens_to_ids, self.tokenizer
100
+ )
101
+
102
+ self._digit_token_ids = {
103
+ "0": 15,
104
+ "1": 16,
105
+ "2": 17,
106
+ "3": 18,
107
+ "4": 19,
108
+ "5": 20,
109
+ "6": 21,
110
+ "7": 22,
111
+ "8": 23,
112
+ "9": 24,
113
+ }
114
+ self.audio_tokens_per_second = 12.5
115
+ self.time_marker_every_seconds = 2
116
+ self.time_marker_every_audio_tokens = int(
117
+ self.audio_tokens_per_second * self.time_marker_every_seconds
118
+ )
119
+ self.model_input_names = [
120
+ "input_ids",
121
+ "attention_mask",
122
+ "audio_data",
123
+ "audio_data_seqlens",
124
+ ]
125
+
126
+ @classmethod
127
+ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
128
+ tokenizer_kwargs = {}
129
+ for key in ["cache_dir", "revision", "token", "local_files_only"]:
130
+ if key in kwargs:
131
+ tokenizer_kwargs[key] = kwargs[key]
132
+
133
+ tokenizer = AutoTokenizer.from_pretrained(
134
+ pretrained_model_name_or_path,
135
+ use_fast=False,
136
+ **tokenizer_kwargs,
137
+ )
138
+
139
+ mel_config = kwargs.pop("mel_config", None)
140
+ template_path = kwargs.pop("template_path", None)
141
+ enable_time_marker = kwargs.pop("enable_time_marker", False)
142
+ audio_token_id = kwargs.pop("audio_token_id", 151654)
143
+ audio_start_id = kwargs.pop("audio_start_id", 151669)
144
+ audio_end_id = kwargs.pop("audio_end_id", 151670)
145
+
146
+ return cls(
147
+ tokenizer,
148
+ mel_config=mel_config,
149
+ template_path=template_path,
150
+ enable_time_marker=enable_time_marker,
151
+ audio_token_id=audio_token_id,
152
+ audio_start_id=audio_start_id,
153
+ audio_end_id=audio_end_id,
154
+ )
155
+
156
+ def load_template(self, template_path: str):
157
+ self.chat_template = load_chat_template(template_path)
158
+ return self
159
+
160
+ def set_custom_text(self, key: str, text: str):
161
+ self.custom_texts[key] = text
162
+ return self
163
+
164
+ def clear_custom_text(self, key: Optional[str] = None):
165
+ if key is None:
166
+ self.custom_texts.clear()
167
+ else:
168
+ self.custom_texts.pop(key, None)
169
+ return self
170
+
171
+ def _template_requires_audio(self) -> bool:
172
+ if self.chat_template is None:
173
+ return False
174
+ for segment in self.chat_template:
175
+ if segment.type in {"audio_contiguous", "audio_token"}:
176
+ return True
177
+ return False
178
+
179
+ @staticmethod
180
+ def _conv3_downsample_len(raw_mel_len: int) -> int:
181
+ def conv_out_len(length: int) -> int:
182
+ return (length - 1) // 2 + 1
183
+
184
+ length1 = conv_out_len(int(raw_mel_len))
185
+ length2 = conv_out_len(length1)
186
+ length3 = conv_out_len(length2)
187
+ return int(length3)
188
+
189
+ def _get_whisper_feature_extractor(self):
190
+ if self._whisper_feature_extractor is not None:
191
+ return self._whisper_feature_extractor
192
+
193
+ from transformers.models.whisper.feature_extraction_whisper import (
194
+ WhisperFeatureExtractor,
195
+ )
196
+
197
+ self._whisper_feature_extractor = WhisperFeatureExtractor(
198
+ feature_size=int(self.config.mel_dim),
199
+ sampling_rate=int(self.config.mel_sr),
200
+ hop_length=int(self.config.mel_hop_length),
201
+ n_fft=int(self.config.mel_n_fft),
202
+ )
203
+ return self._whisper_feature_extractor
204
+
205
+ def _extract_mel(self, audio: Union[np.ndarray, torch.Tensor]) -> torch.Tensor:
206
+ if isinstance(audio, np.ndarray):
207
+ wav = torch.from_numpy(audio)
208
+ else:
209
+ wav = audio
210
+ wav = wav.to(dtype=torch.float32)
211
+ if wav.dim() == 1:
212
+ wav = wav.unsqueeze(0)
213
+
214
+ if bool(getattr(self.config, "use_whisper_feature_extractor", False)):
215
+ feature_extractor = self._get_whisper_feature_extractor()
216
+ wav_np = wav.detach().to("cpu", torch.float32).contiguous().numpy()
217
+ if wav_np.ndim == 2:
218
+ wav_np = wav_np[0]
219
+ feats = feature_extractor._np_extract_fbank_features(
220
+ wav_np[None, ...], device="cpu"
221
+ )
222
+ mel = torch.from_numpy(feats[0])
223
+
224
+ return mel.to(dtype=self.config.mel_dtype)
225
+
226
+ def _get_time_marker_token_ids(self, second: int) -> List[int]:
227
+ return [self._digit_token_ids[digit] for digit in str(second)]
228
+
229
+ def _build_audio_tokens_with_time_markers(self, audio_seq_len: int) -> List[int]:
230
+ total_duration_seconds = audio_seq_len / self.audio_tokens_per_second
231
+ num_full_seconds = int(total_duration_seconds)
232
+
233
+ token_ids: List[int] = []
234
+ audio_tokens_consumed = 0
235
+ for second in range(
236
+ self.time_marker_every_seconds,
237
+ num_full_seconds + 1,
238
+ self.time_marker_every_seconds,
239
+ ):
240
+ marker_pos = (
241
+ second // self.time_marker_every_seconds
242
+ ) * self.time_marker_every_audio_tokens
243
+ audio_segment_len = marker_pos - audio_tokens_consumed
244
+ if audio_segment_len > 0:
245
+ token_ids.extend([self.audio_token_id] * audio_segment_len)
246
+ audio_tokens_consumed += audio_segment_len
247
+ token_ids.extend(self._get_time_marker_token_ids(second))
248
+
249
+ remaining = audio_seq_len - audio_tokens_consumed
250
+ if remaining > 0:
251
+ token_ids.extend([self.audio_token_id] * remaining)
252
+ return token_ids
253
+
254
+ def _build_audio_placeholder_ids(self, num_audio_tokens: int) -> List[int]:
255
+ if self.enable_time_marker:
256
+ return self._build_audio_tokens_with_time_markers(num_audio_tokens)
257
+ return [self.audio_token_id] * num_audio_tokens
258
+
259
+ def _build_input_from_template(
260
+ self, num_audio_tokens: int, include_answer: bool = False
261
+ ) -> List[int]:
262
+ if self.chat_template is None:
263
+ raise ValueError("Chat template not loaded.")
264
+
265
+ input_ids: List[int] = []
266
+ for segment in self.chat_template:
267
+ seg_type = segment.type
268
+ if seg_type == "constant_text_token":
269
+ input_ids.extend(segment.text_ids.tolist())
270
+ elif seg_type in {"audio_contiguous", "audio_token"}:
271
+ input_ids.extend(self._build_audio_placeholder_ids(num_audio_tokens))
272
+ elif seg_type == "text_token":
273
+ text_token_key = segment.text_token_key
274
+ if "answer" in text_token_key.lower() and not include_answer:
275
+ break
276
+ if text_token_key not in self.custom_texts:
277
+ break
278
+ text_ids = self._base_tokenizer.encode(
279
+ self.custom_texts[text_token_key], add_special_tokens=False
280
+ )
281
+ input_ids.extend(text_ids)
282
+
283
+ return input_ids
284
+
285
+ def _build_default_prompt(self, text: str, has_audio: bool) -> str:
286
+ if has_audio:
287
+ return (
288
+ "<|im_start|>system\n"
289
+ "You are a helpful assistant.<|im_end|>\n"
290
+ "<|im_start|>user\n"
291
+ "<|audio_bos|><|AUDIO|><|audio_eos|>\n"
292
+ f"{text}<|im_end|>\n"
293
+ "<|im_start|>assistant\n"
294
+ )
295
+ return (
296
+ "<|im_start|>system\n"
297
+ "You are a helpful assistant.<|im_end|>\n"
298
+ "<|im_start|>user\n"
299
+ f"{text}<|im_end|>\n"
300
+ "<|im_start|>assistant\n"
301
+ )
302
+
303
+ def _build_input_from_prompt(self, prompt: str, token_lens: List[int]) -> List[int]:
304
+ spans = list(self._AUDIO_SPAN_RE.finditer(prompt))
305
+ if len(spans) != len(token_lens):
306
+ raise ValueError(
307
+ f"Audio placeholder count mismatch: found {len(spans)} spans in text, "
308
+ f"but got {len(token_lens)} audio inputs."
309
+ )
310
+
311
+ input_ids: List[int] = []
312
+ cursor = 0
313
+ for index, match in enumerate(spans):
314
+ prefix = prompt[cursor : match.start()]
315
+ if prefix:
316
+ input_ids.extend(
317
+ self._base_tokenizer.encode(prefix, add_special_tokens=False)
318
+ )
319
+
320
+ input_ids.append(self.audio_start_id)
321
+ input_ids.extend(self._build_audio_placeholder_ids(int(token_lens[index])))
322
+ input_ids.append(self.audio_end_id)
323
+ cursor = match.end()
324
+
325
+ suffix = prompt[cursor:]
326
+ if suffix:
327
+ input_ids.extend(
328
+ self._base_tokenizer.encode(suffix, add_special_tokens=False)
329
+ )
330
+ return input_ids
331
+
332
+ def __call__(
333
+ self,
334
+ *,
335
+ text: Union[str, Sequence[str], None] = None,
336
+ audios: Optional[Sequence[Union[np.ndarray, torch.Tensor]]] = None,
337
+ audio: Optional[Sequence[Union[np.ndarray, torch.Tensor]]] = None,
338
+ return_tensors: str = "pt",
339
+ **kwargs,
340
+ ):
341
+ if isinstance(text, (list, tuple)):
342
+ if len(text) != 1:
343
+ raise ValueError(f"Expected text batch size 1, got {len(text)}")
344
+ prompt_text = text[0]
345
+ else:
346
+ prompt_text = text
347
+
348
+ audio_list = audios if audios is not None else audio
349
+ audio_list = [] if audio_list is None else list(audio_list)
350
+
351
+ mels: List[torch.Tensor] = []
352
+ raw_lengths: List[int] = []
353
+ token_lens: List[int] = []
354
+ for one_audio in audio_list:
355
+ mel = self._extract_mel(one_audio)
356
+ raw_len = int(mel.shape[-1])
357
+ mels.append(mel)
358
+ raw_lengths.append(raw_len)
359
+ token_lens.append(self._conv3_downsample_len(raw_len))
360
+
361
+ if mels:
362
+ max_length = max(raw_lengths)
363
+ audio_batch = torch.zeros(
364
+ (len(mels), self.config.mel_dim, max_length),
365
+ dtype=self.config.mel_dtype,
366
+ )
367
+ for index, mel in enumerate(mels):
368
+ audio_batch[index, :, : mel.shape[-1]] = mel
369
+ seqlens_tensor = torch.tensor(raw_lengths, dtype=torch.long)
370
+ else:
371
+ audio_batch = None
372
+ seqlens_tensor = None
373
+
374
+ if prompt_text is not None:
375
+ if self._AUDIO_SPAN_RE.search(prompt_text) is None and audio_list:
376
+ prompt_text = self._build_default_prompt(prompt_text, has_audio=True)
377
+ elif self._AUDIO_SPAN_RE.search(prompt_text) is None and not audio_list:
378
+ prompt_text = self._build_default_prompt(prompt_text, has_audio=False)
379
+ input_ids_list = self._build_input_from_prompt(prompt_text, token_lens)
380
+ elif self.chat_template is not None:
381
+ input_ids_list = self._build_input_from_template(
382
+ token_lens[0] if token_lens else 0
383
+ )
384
+ else:
385
+ raise ValueError(
386
+ "Either provide text or load a chat_template before calling the processor."
387
+ )
388
+
389
+ input_ids_tensor = torch.tensor([input_ids_list], dtype=torch.long)
390
+ attention_mask_tensor = torch.ones_like(input_ids_tensor)
391
+
392
+ data = {
393
+ "input_ids": input_ids_tensor,
394
+ "attention_mask": attention_mask_tensor,
395
+ }
396
+ if audio_batch is not None:
397
+ data["audio_data"] = audio_batch
398
+ data["audio_data_seqlens"] = seqlens_tensor
399
+ return BatchEncoding(data=data, tensor_type=return_tensors)
400
+
401
+ def batch_decode(self, *args, **kwargs):
402
+ return self._base_tokenizer.batch_decode(*args, **kwargs)
403
+
404
+ def decode(self, *args, **kwargs):
405
+ return self._base_tokenizer.decode(*args, **kwargs)
406
+
407
+
408
+ __all__ = ["MelConfig", "MossAudioProcessor"]