zhoukz commited on
Commit
2f0baa1
·
verified ·
1 Parent(s): cc937c5

Upload folder using huggingface_hub

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
added_tokens.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</tool_call>": 151658,
3
+ "<tool_call>": 151657,
4
+ "<|AUDIO|>": 151646,
5
+ "<|IMAGE|>": 151655,
6
+ "<|VIDEO|>": 151656,
7
+ "<|ar|>": 151679,
8
+ "<|audio_bos|>": 151647,
9
+ "<|audio_eos|>": 151648,
10
+ "<|box_end|>": 151649,
11
+ "<|de|>": 151667,
12
+ "<|endoftext|>": 151643,
13
+ "<|en|>": 151665,
14
+ "<|es|>": 151668,
15
+ "<|file_sep|>": 151664,
16
+ "<|fim_middle|>": 151660,
17
+ "<|fim_pad|>": 151662,
18
+ "<|fim_prefix|>": 151659,
19
+ "<|fim_suffix|>": 151661,
20
+ "<|fr|>": 151669,
21
+ "<|hi|>": 151670,
22
+ "<|id|>": 151676,
23
+ "<|im_end|>": 151645,
24
+ "<|im_start|>": 151644,
25
+ "<|it|>": 151678,
26
+ "<|jp|>": 151680,
27
+ "<|kr|>": 151666,
28
+ "<|nl|>": 151674,
29
+ "<|pt|>": 151675,
30
+ "<|quad_end|>": 151651,
31
+ "<|quad_start|>": 151650,
32
+ "<|repo_name|>": 151663,
33
+ "<|ru|>": 151677,
34
+ "<|th|>": 151672,
35
+ "<|uk|>": 151671,
36
+ "<|unknown|>": 151681,
37
+ "<|vision_bos|>": 151652,
38
+ "<|vision_eos|>": 151653,
39
+ "<|vision_pad|>": 151654,
40
+ "<|vi|>": 151673
41
+ }
chat_template.jinja ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {% set audio_count = namespace(value=0) %}{% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system
2
+ You are a helpful assistant.<|im_end|>
3
+ {% endif %}<|im_start|>{{ message['role'] }}
4
+ {% if message['content'] is string %}{{ message['content'] }}<|im_end|>
5
+ {% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|vision_bos|><|IMAGE|><|vision_eos|>{% elif content['type'] == 'audio' or 'audio' in content or 'audio_url' in content %}{% set audio_count.value = audio_count.value + 1 %}{% if add_audio_id %}Audio {{ audio_count.value }}: {% endif %}<|audio_bos|><|AUDIO|><|audio_eos|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|vision_bos|><|VIDEO|><|vision_eos|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|>
6
+ {% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant
7
+ {% endif %}
config.json ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "MiDashengLMModel"
4
+ ],
5
+ "audio_encoder_config": {
6
+ "attn_drop_rate": 0.0,
7
+ "center": true,
8
+ "depth": 32,
9
+ "drop_rate": 0.0,
10
+ "embed_dim": 1280,
11
+ "f_max": 8000.0,
12
+ "f_min": 0.0,
13
+ "hop_length": 160,
14
+ "init_values": null,
15
+ "input_channels": 1,
16
+ "mlp_ratio": 4.0,
17
+ "model_type": "midashenglm_dasheng_encoder",
18
+ "n_fft": 512,
19
+ "n_mels": 64,
20
+ "num_heads": 16,
21
+ "outputdim": 527,
22
+ "patch_size": [
23
+ 64,
24
+ 4
25
+ ],
26
+ "patch_stride": [
27
+ 64,
28
+ 4
29
+ ],
30
+ "qkv_bias": true,
31
+ "sample_rate": 16000,
32
+ "target_length": 1008,
33
+ "win_length": 512
34
+ },
35
+ "audio_token_id": 151646,
36
+ "auto_map": {
37
+ "AutoConfig": "configuration_midashenglm.MiDashengLMConfig",
38
+ "AutoModelForCausalLM": "modeling_midashenglm.MiDashengLMModel"
39
+ },
40
+ "model_type": "midashenglm",
41
+ "quantization_config": {
42
+ "_load_in_4bit": true,
43
+ "_load_in_8bit": false,
44
+ "bnb_4bit_compute_dtype": "bfloat16",
45
+ "bnb_4bit_quant_storage": "uint8",
46
+ "bnb_4bit_quant_type": "fp4",
47
+ "bnb_4bit_use_double_quant": false,
48
+ "llm_int8_enable_fp32_cpu_offload": false,
49
+ "llm_int8_has_fp16_weight": false,
50
+ "llm_int8_skip_modules": null,
51
+ "llm_int8_threshold": 6.0,
52
+ "load_in_4bit": true,
53
+ "load_in_8bit": false,
54
+ "quant_method": "bitsandbytes"
55
+ },
56
+ "subsample_factor": 5,
57
+ "text_config": {
58
+ "attention_dropout": 0.0,
59
+ "hidden_act": "silu",
60
+ "hidden_size": 3584,
61
+ "init_std": 0.02,
62
+ "initializer_range": 0.02,
63
+ "intermediate_size": 18944,
64
+ "layer_types": [
65
+ "full_attention",
66
+ "full_attention",
67
+ "full_attention",
68
+ "full_attention",
69
+ "full_attention",
70
+ "full_attention",
71
+ "full_attention",
72
+ "full_attention",
73
+ "full_attention",
74
+ "full_attention",
75
+ "full_attention",
76
+ "full_attention",
77
+ "full_attention",
78
+ "full_attention",
79
+ "full_attention",
80
+ "full_attention",
81
+ "full_attention",
82
+ "full_attention",
83
+ "full_attention",
84
+ "full_attention",
85
+ "full_attention",
86
+ "full_attention",
87
+ "full_attention",
88
+ "full_attention",
89
+ "full_attention",
90
+ "full_attention",
91
+ "full_attention",
92
+ "full_attention"
93
+ ],
94
+ "max_position_embeddings": 32768,
95
+ "max_window_layers": 28,
96
+ "model_type": "qwen2_5_omni_text",
97
+ "num_attention_heads": 28,
98
+ "num_hidden_layers": 28,
99
+ "num_key_value_heads": 4,
100
+ "rms_norm_eps": 1e-06,
101
+ "rope_scaling": {
102
+ "mrope_section": [
103
+ 16,
104
+ 24,
105
+ 24
106
+ ],
107
+ "rope_type": "default",
108
+ "type": "default"
109
+ },
110
+ "rope_theta": 1000000.0,
111
+ "sliding_window": null,
112
+ "use_cache": true,
113
+ "use_sliding_window": false,
114
+ "vocab_size": 152064
115
+ },
116
+ "torch_dtype": "bfloat16",
117
+ "transformers_version": "4.54.0"
118
+ }
configuration_midashenglm.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Optional, Tuple, Union
2
+
3
+ from transformers import PretrainedConfig
4
+ from transformers.models.qwen2_5_omni.configuration_qwen2_5_omni import (
5
+ Qwen2_5OmniTextConfig,
6
+ )
7
+
8
+
9
+ class DashengConfig(PretrainedConfig):
10
+ model_type = "midashenglm_dasheng_encoder"
11
+
12
+ def __init__(
13
+ self,
14
+ embed_dim: int = 768,
15
+ outputdim: int = 527,
16
+ patch_size: Union[int, Tuple[int, int]] = 16,
17
+ patch_stride: Union[int, Tuple[int, int]] = 16,
18
+ input_channels: int = 1,
19
+ target_length: int = 1012,
20
+ depth: int = 12,
21
+ num_heads: int = 12,
22
+ mlp_ratio: float = 4.0,
23
+ qkv_bias: bool = True,
24
+ init_values: Optional[float] = None,
25
+ drop_rate: float = 0.0,
26
+ attn_drop_rate: float = 0.0,
27
+ f_min: float = 0.0,
28
+ f_max: float = 8000.0,
29
+ center: bool = True,
30
+ win_length: int = 512,
31
+ hop_length: int = 160,
32
+ sample_rate: int = 16000,
33
+ n_fft: int = 512,
34
+ n_mels: int = 64,
35
+ **kwargs,
36
+ ):
37
+ self.embed_dim = embed_dim
38
+ self.outputdim = outputdim
39
+ self.patch_size = patch_size
40
+ self.patch_stride = patch_stride
41
+ self.input_channels = input_channels
42
+ self.target_length = target_length
43
+ self.depth = depth
44
+ self.num_heads = num_heads
45
+ self.mlp_ratio = mlp_ratio
46
+ self.qkv_bias = qkv_bias
47
+ self.init_values = init_values
48
+ self.drop_rate = drop_rate
49
+ self.attn_drop_rate = attn_drop_rate
50
+ self.f_min = f_min
51
+ self.f_max = f_max
52
+ self.center = center
53
+ self.win_length = win_length
54
+ self.hop_length = hop_length
55
+ self.sample_rate = sample_rate
56
+ self.n_fft = n_fft
57
+ self.n_mels = n_mels
58
+ super().__init__(**kwargs)
59
+
60
+
61
+ class MiDashengLMConfig(PretrainedConfig):
62
+ model_type = "midashenglm"
63
+
64
+ def __init__(
65
+ self,
66
+ audio_encoder_config: Dict = {},
67
+ subsample_factor: int = 5,
68
+ text_config: Dict = {},
69
+ audio_token_id: Optional[int] = None,
70
+ **kwargs,
71
+ ):
72
+ self.audio_encoder_config = DashengConfig(**audio_encoder_config)
73
+ self.subsample_factor = subsample_factor
74
+ self.text_config = (
75
+ Qwen2_5OmniTextConfig(**text_config)
76
+ if text_config
77
+ else Qwen2_5OmniTextConfig()
78
+ )
79
+ self.audio_token_id = audio_token_id
80
+ super().__init__(**kwargs)
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "eos_token_id": [
3
+ 151643,
4
+ 151645
5
+ ],
6
+ "max_length": 32768,
7
+ "pad_token_id": 151643,
8
+ "transformers_version": "4.54.0"
9
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d9f59b51dba695e593883438352090cfccc61ca527595511215dca21b22ab6b7
3
+ size 4968475550
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:45f8c2d13ba443773868202a754c4e37d1a519aa4fa556875d7fc9d9cbd705ae
3
+ size 1259325658
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_midashenglm.py ADDED
@@ -0,0 +1,660 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import collections.abc
3
+ from dataclasses import dataclass
4
+ from typing import Any, Callable, Iterable, List, Optional, Sequence, Tuple, Union, cast
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torchaudio.functional as F
9
+ from torch import Tensor
10
+ from transformers import GenerationMixin, PreTrainedModel
11
+ from transformers.cache_utils import Cache
12
+ from transformers.modeling_outputs import BaseModelOutputWithPast, ModelOutput
13
+ from transformers.models.qwen2_5_omni.configuration_qwen2_5_omni import (
14
+ Qwen2_5OmniTextConfig,
15
+ )
16
+ from transformers.models.qwen2_5_omni.modeling_qwen2_5_omni import (
17
+ Qwen2_5OmniThinkerTextModel,
18
+ )
19
+ from transformers.utils import can_return_tuple
20
+
21
+ from .configuration_midashenglm import DashengConfig, MiDashengLMConfig
22
+
23
+ _Tuple2 = Union[int, Tuple[int, int], Sequence[int]]
24
+
25
+
26
+ def _resolve_tuple2(x: _Tuple2) -> Tuple[int, int]:
27
+ if isinstance(x, collections.abc.Sequence):
28
+ assert len(x) == 2, (
29
+ f"Expected a sequence of length 2, got {x} with length {len(x)}"
30
+ )
31
+ return cast(Tuple[int, int], tuple(x))
32
+ return (x, x)
33
+
34
+
35
+ class AudioPatchEmbed(nn.Module):
36
+ def __init__(
37
+ self,
38
+ input_size: _Tuple2 = 64,
39
+ patch_size: _Tuple2 = 16,
40
+ patch_stride: _Tuple2 = 16,
41
+ in_chans: int = 1,
42
+ embed_dim: int = 768,
43
+ norm_layer: Optional[Callable] = None,
44
+ flatten: bool = False,
45
+ ):
46
+ super().__init__()
47
+ self.input_size = _resolve_tuple2(input_size)
48
+ self.patch_size = _resolve_tuple2(patch_size)
49
+ self.patch_stride = _resolve_tuple2(patch_stride)
50
+ self.grid_size = (
51
+ self.input_size[0] // self.patch_stride[0],
52
+ self.input_size[1] // self.patch_stride[1],
53
+ )
54
+ self.num_patches = self.grid_size[0] * self.grid_size[1]
55
+ self.flatten = flatten
56
+
57
+ self.proj = nn.Conv2d(
58
+ in_chans,
59
+ embed_dim,
60
+ kernel_size=self.patch_size,
61
+ stride=self.patch_stride,
62
+ )
63
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
64
+
65
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
66
+ x = self.proj(x)
67
+ if self.flatten:
68
+ x = torch.permute(
69
+ torch.flatten(x, 2, 3), (0, 2, 1)
70
+ ) # rearrange(x, "b c f t -> b (f t) c")
71
+ x = self.norm(x)
72
+ return x
73
+
74
+
75
+ class LayerScale(nn.Module):
76
+ def __init__(self, dim, init_values=1e-5, inplace=False):
77
+ super().__init__()
78
+ self.inplace = inplace
79
+ self.gamma = nn.Parameter(init_values * torch.ones(dim))
80
+
81
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
82
+ return x.mul_(self.gamma) if self.inplace else x * self.gamma
83
+
84
+
85
+ class DashengMlp(nn.Module):
86
+ def __init__(
87
+ self,
88
+ in_features: int,
89
+ hidden_features: Optional[int] = None,
90
+ out_features: Optional[int] = None,
91
+ drop: float = 0.0,
92
+ ):
93
+ super().__init__()
94
+ out_features = out_features or in_features
95
+ hidden_features = hidden_features or in_features
96
+ self.fc1 = nn.Linear(in_features, hidden_features)
97
+ self.act = nn.GELU()
98
+ self.fc2 = nn.Linear(hidden_features, out_features)
99
+ self.drop = nn.Dropout(drop)
100
+
101
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
102
+ x = self.fc1(x)
103
+ x = self.act(x)
104
+ x = self.drop(x)
105
+ x = self.fc2(x)
106
+ x = self.drop(x)
107
+ return x
108
+
109
+
110
+ class DashengAttention(nn.Module):
111
+ def __init__(
112
+ self,
113
+ dim: int,
114
+ num_heads: int = 8,
115
+ qkv_bias: bool = False,
116
+ attn_drop: float = 0.0,
117
+ proj_drop: float = 0.0,
118
+ causal: bool = False,
119
+ ):
120
+ super().__init__()
121
+ assert dim % num_heads == 0, "dim should be divisible by num_heads"
122
+ self.num_heads = num_heads
123
+ head_dim = dim // num_heads
124
+ self.scale = head_dim**-0.5
125
+
126
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
127
+ self.attn_drop = nn.Dropout(attn_drop)
128
+ self.proj = nn.Linear(dim, dim)
129
+ self.proj_drop = nn.Dropout(proj_drop)
130
+ self.causal = causal
131
+
132
+ def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None):
133
+ B, N, C = x.shape
134
+ qkv = (
135
+ self.qkv(x)
136
+ .reshape(B, N, 3, self.num_heads, C // self.num_heads)
137
+ .permute(2, 0, 3, 1, 4)
138
+ )
139
+ q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
140
+
141
+ attn = (q @ k.transpose(-2, -1)) * self.scale
142
+ # if mask is not None:
143
+ # # Mask is a tensor of shape [B, T, T]
144
+ # # Different from self.causal == True, the mask might be something like:
145
+ # # [False, False, True]
146
+ # # [False, False, True]
147
+ # # [True, True, True]
148
+ # # We use -inf to pad here, since if we would pad by any number, the entries at rows only containing
149
+ # # [True, True, True] would lead to weights such as: [0.33,0.33,0.33], which is not correct
150
+ if self.causal:
151
+ mask_value = -torch.finfo(attn.dtype).max
152
+ i, j = attn.shape[-2:]
153
+ mask = torch.ones(i, j, device=q.device, dtype=torch.bool).triu(j - i + 1)
154
+ attn = attn.masked_fill(mask, mask_value)
155
+ if mask is not None:
156
+ # mask value as the lowest possible value in fp32
157
+ mask_value = torch.finfo(attn.dtype).min
158
+ # Mask is of shape [1, SRC_LEN]
159
+ attn_mask = mask[:, None, None, :].expand(B, 1, N, N)
160
+ # Mask should be of shape
161
+ # [B,1,Target_len, Source_len]
162
+ attn = attn.masked_fill(attn_mask, mask_value)
163
+ attn = attn.softmax(dim=-1)
164
+ attn = torch.nan_to_num(attn)
165
+ # Only for the case that a mask with all True entries on a row is passed.
166
+ # attn = torch.nan_to_num(attn)
167
+ attn = self.attn_drop(attn)
168
+
169
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
170
+ x = self.proj(x)
171
+ x = self.proj_drop(x)
172
+ return x
173
+
174
+
175
+ class DashengBlock(nn.Module):
176
+ def __init__(
177
+ self,
178
+ dim: int,
179
+ num_heads: int,
180
+ mlp_ratio: float = 4.0,
181
+ qkv_bias: bool = False,
182
+ drop: float = 0.0,
183
+ attn_drop: float = 0.0,
184
+ init_values: Optional[float] = None,
185
+ ):
186
+ super().__init__()
187
+ self.norm1 = nn.LayerNorm(dim, eps=1e-6)
188
+ self.attn = DashengAttention(
189
+ dim,
190
+ num_heads=num_heads,
191
+ qkv_bias=qkv_bias,
192
+ attn_drop=attn_drop,
193
+ proj_drop=drop,
194
+ )
195
+ self.ls1 = (
196
+ LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
197
+ )
198
+
199
+ self.norm2 = nn.LayerNorm(dim, eps=1e-6)
200
+ self.mlp = DashengMlp(
201
+ in_features=dim,
202
+ hidden_features=int(dim * mlp_ratio),
203
+ drop=drop,
204
+ )
205
+ self.ls2 = (
206
+ LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
207
+ )
208
+
209
+ # Kwargs usually has a mask parameter that is passed to Attention
210
+ def forward(
211
+ self,
212
+ x: torch.Tensor,
213
+ mask: Optional[torch.Tensor] = None,
214
+ ) -> torch.Tensor:
215
+ x = x + self.ls1(self.attn(self.norm1(x), mask))
216
+ x = x + self.ls2(self.mlp(self.norm2(x)))
217
+ return x
218
+
219
+
220
+ class DashengFrontend(nn.Module):
221
+ def __init__(self, config: DashengConfig):
222
+ super().__init__()
223
+ self.config = config
224
+
225
+ spectrogram_window = torch.hann_window(self.config.win_length)
226
+ self.register_buffer(
227
+ "spectrogram_window",
228
+ spectrogram_window,
229
+ persistent=False,
230
+ )
231
+ self.spectrogram_window: torch.Tensor
232
+
233
+ melscale_fbanks = F.melscale_fbanks(
234
+ n_freqs=self.config.n_fft // 2 + 1,
235
+ f_min=self.config.f_min,
236
+ f_max=self.config.f_max,
237
+ n_mels=self.config.n_mels,
238
+ sample_rate=self.config.sample_rate,
239
+ )
240
+ self.register_buffer("melscale_fbanks", melscale_fbanks, persistent=False)
241
+ self.melscale_fbanks: torch.Tensor
242
+
243
+ def forward(self, waveform: torch.Tensor) -> torch.Tensor:
244
+ spectrogram = F.spectrogram(
245
+ waveform=waveform.to(torch.float32),
246
+ pad=0,
247
+ window=self.spectrogram_window,
248
+ n_fft=self.config.n_fft,
249
+ hop_length=self.config.hop_length,
250
+ win_length=self.config.win_length,
251
+ power=2,
252
+ normalized=False,
253
+ center=self.config.center,
254
+ )
255
+ mel_spectrogram = (spectrogram.mT @ self.melscale_fbanks.to(torch.float32)).mT
256
+ # x has shape [batch, freq, time].
257
+ # F.amplitude_to_DB accepts inputs shaped as:
258
+ # - [freq, time]
259
+ # - [channel, freq, time]
260
+ # - [..., channel, freq, time]
261
+ # Here we insert a channel dimension of size 1 before calling it,
262
+ # then remove that extra dimension afterward.
263
+ log_mel_spectrogram = F.amplitude_to_DB(
264
+ mel_spectrogram.unsqueeze(1),
265
+ multiplier=10,
266
+ amin=1e-10,
267
+ db_multiplier=0,
268
+ top_db=120,
269
+ ).squeeze(1)
270
+ return log_mel_spectrogram.to(waveform.dtype)
271
+
272
+
273
+ class DashengAudioTransformer(PreTrainedModel):
274
+ config_class = DashengConfig
275
+ supports_gradient_checkpointing = True
276
+
277
+ def __init__(self, config: DashengConfig):
278
+ super().__init__(config)
279
+
280
+ self.target_length = config.target_length
281
+ self.embed_dim = config.embed_dim
282
+ self.hop_length = config.hop_length
283
+ self.gradient_checkpointing = False
284
+
285
+ self.front_end = DashengFrontend(config)
286
+
287
+ self.init_bn = nn.BatchNorm2d(config.n_mels, momentum=0.01)
288
+
289
+ self.patch_embed = AudioPatchEmbed(
290
+ input_size=(config.n_mels, config.target_length),
291
+ embed_dim=config.embed_dim,
292
+ in_chans=config.input_channels,
293
+ patch_size=config.patch_size,
294
+ flatten=False,
295
+ patch_stride=config.patch_stride,
296
+ )
297
+
298
+ self.time_pos_embed = nn.Parameter(
299
+ torch.randn(1, config.embed_dim, 1, self.patch_embed.grid_size[1]) * 0.02
300
+ )
301
+ self.freq_pos_embed = nn.Parameter(
302
+ torch.randn(1, config.embed_dim, self.patch_embed.grid_size[0], 1) * 0.02
303
+ )
304
+
305
+ self.pos_drop = nn.Dropout(p=config.drop_rate)
306
+ self.blocks = nn.ModuleList(
307
+ DashengBlock(
308
+ dim=config.embed_dim,
309
+ num_heads=config.num_heads,
310
+ mlp_ratio=config.mlp_ratio,
311
+ qkv_bias=config.qkv_bias,
312
+ init_values=config.init_values,
313
+ drop=config.drop_rate,
314
+ attn_drop=config.attn_drop_rate,
315
+ )
316
+ for _ in range(config.depth)
317
+ )
318
+ self.norm = nn.LayerNorm(config.embed_dim, eps=1e-6)
319
+
320
+ self.post_init()
321
+
322
+ def forward_features(
323
+ self,
324
+ x: torch.Tensor,
325
+ mask: Optional[torch.Tensor] = None,
326
+ ) -> torch.Tensor:
327
+ t = x.shape[-1]
328
+ x = x + self.time_pos_embed[:, :, :, :t]
329
+ x = (
330
+ x + self.freq_pos_embed[:, :, :, :]
331
+ ) # Just to support __getitem__ in posembed
332
+ x = torch.permute(
333
+ torch.flatten(x, 2, 3), (0, 2, 1)
334
+ ) # rearrange(x, "b c f t -> b (f t) c")
335
+ x = self.pos_drop(x)
336
+ for block in self.blocks:
337
+ if self.gradient_checkpointing and self.training:
338
+ x = self._gradient_checkpointing_func(block, x, mask)
339
+ else:
340
+ x = block(x, mask)
341
+ x = self.norm(x)
342
+ return x
343
+
344
+ def _to_mask(self, lengths: torch.Tensor, max_length: int) -> torch.Tensor:
345
+ batch_size = len(lengths)
346
+ idx = torch.arange(max_length, device=lengths.device)
347
+ idx = idx.repeat(batch_size).view(batch_size, max_length)
348
+ mask = (idx < lengths.unsqueeze(-1)).bool()
349
+ return mask
350
+
351
+ def forward(
352
+ self,
353
+ x: torch.Tensor,
354
+ x_length: Optional[torch.Tensor] = None,
355
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
356
+ x = self.front_end(x)
357
+ target_length_in_patches = self.target_length // 4
358
+ x = x.unsqueeze(1)
359
+ x = torch.permute(x, (0, 2, 1, 3))
360
+ x = self.init_bn(x)
361
+ x = torch.permute(x, (0, 2, 1, 3))
362
+
363
+ x = self.patch_embed(x)
364
+ t = x.shape[-1]
365
+
366
+ input_splits = x.split(target_length_in_patches, dim=-1)
367
+
368
+ if x_length is not None:
369
+ assert len(x_length) == len(x), (
370
+ "batchsizes of input x and x_length need to be same"
371
+ )
372
+ assert x_length.ndim == 1, "Lengths are of size (B,)"
373
+ scaled_lengths = (x_length / (self.hop_length * 4)).long()
374
+ mask = self._to_mask(max_length=t, lengths=scaled_lengths)
375
+ split_masks = mask.logical_not().split(target_length_in_patches, dim=-1)
376
+ else:
377
+ mask = None
378
+ split_masks = [None] * len(input_splits)
379
+
380
+ outputs = []
381
+
382
+ for split_x, split_mask in zip(input_splits, split_masks):
383
+ forward_kwargs = {}
384
+ forward_kwargs["mask"] = split_mask
385
+ split_x = self.forward_features(split_x, **forward_kwargs)
386
+ outputs.append(split_x)
387
+ x = torch.cat(outputs, dim=1)
388
+ return x, mask
389
+
390
+
391
+ class AudioProjectorSubsample(nn.Module):
392
+ def __init__(
393
+ self,
394
+ in_dim: int,
395
+ out_dim: int,
396
+ downsample_rate=5,
397
+ dtype: Optional[torch.dtype] = None,
398
+ ):
399
+ super().__init__()
400
+ self.k = downsample_rate
401
+ self.net = nn.Sequential(
402
+ nn.Linear(in_dim * self.k, out_dim, dtype=dtype),
403
+ nn.GELU(),
404
+ nn.Linear(out_dim, out_dim, dtype=dtype),
405
+ )
406
+
407
+ def forward(self, x, mask=None):
408
+ batch_size, seq_len, dim = x.shape
409
+ num_frames_to_discard = seq_len % self.k
410
+ if num_frames_to_discard > 0:
411
+ x = x[:, :-num_frames_to_discard, :]
412
+ if mask is not None:
413
+ mask = mask[:, :-num_frames_to_discard]
414
+ if mask is None:
415
+ mask = torch.ones(x.shape[:-1], dtype=torch.long, device=x.device)
416
+ x = x.reshape(
417
+ batch_size, -1, self.k * dim
418
+ ) # rearrange(x, "b (s k) d -> b s (k d)", k=self.k)
419
+ x = self.net(x)
420
+ mask = mask.reshape(
421
+ batch_size, -1, self.k
422
+ ) # rearrange(mask, "b (s k) -> b s k", k=self.k)
423
+ mask = mask.any(dim=-1).long()
424
+ return x, mask
425
+
426
+
427
+ @dataclass
428
+ class Qwen25OmniTextModelOutput(ModelOutput):
429
+ loss: Optional[torch.FloatTensor] = None
430
+ logits: Optional[torch.FloatTensor] = None
431
+ past_key_values: Optional[Cache] = None
432
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
433
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
434
+
435
+
436
+ class Qwen25OmniThinkerTextOnlyDecoder(PreTrainedModel, GenerationMixin):
437
+ config_class = Qwen2_5OmniTextConfig
438
+ _supports_flash_attn_2 = True
439
+ _supports_sdpa = True
440
+ _supports_cache_class = True
441
+ _supports_static_cache = True
442
+
443
+ def __init__(self, config: Qwen2_5OmniTextConfig):
444
+ super().__init__(config)
445
+ self.model = Qwen2_5OmniThinkerTextModel._from_config(config)
446
+ self.lm_head = nn.Linear(
447
+ config.hidden_size,
448
+ config.vocab_size,
449
+ bias=False,
450
+ )
451
+ self.post_init()
452
+
453
+ @can_return_tuple
454
+ def forward(
455
+ self,
456
+ input_ids: Optional[torch.LongTensor] = None,
457
+ attention_mask: Optional[torch.Tensor] = None,
458
+ position_ids: Optional[torch.LongTensor] = None,
459
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
460
+ inputs_embeds: Optional[torch.FloatTensor] = None,
461
+ use_cache: Optional[bool] = None,
462
+ output_attentions: Optional[bool] = None,
463
+ output_hidden_states: Optional[bool] = None,
464
+ cache_position: Optional[torch.LongTensor] = None,
465
+ labels: Optional[torch.Tensor] = None,
466
+ **kwargs,
467
+ ) -> Union[Tuple, Qwen25OmniTextModelOutput]:
468
+ if attention_mask is not None and position_ids is None:
469
+ position_ids = (
470
+ attention_mask.long()
471
+ .cumsum(dim=-1)
472
+ .masked_fill_(attention_mask == 0, 1)
473
+ - 1
474
+ )
475
+
476
+ outputs: BaseModelOutputWithPast = self.model(
477
+ input_ids=input_ids,
478
+ attention_mask=attention_mask,
479
+ position_ids=position_ids,
480
+ past_key_values=past_key_values,
481
+ inputs_embeds=inputs_embeds,
482
+ use_cache=use_cache,
483
+ output_attentions=output_attentions,
484
+ output_hidden_states=output_hidden_states,
485
+ cache_position=cache_position,
486
+ return_dict=True,
487
+ )
488
+ hidden_states = outputs.last_hidden_state
489
+ logits = self.lm_head(hidden_states)
490
+
491
+ loss = (
492
+ self.loss_function(
493
+ logits=logits,
494
+ labels=labels,
495
+ vocab_size=self.config.vocab_size,
496
+ **kwargs,
497
+ )
498
+ if labels is not None
499
+ else None
500
+ )
501
+
502
+ return Qwen25OmniTextModelOutput(
503
+ loss=loss,
504
+ logits=logits,
505
+ past_key_values=outputs.past_key_values,
506
+ hidden_states=outputs.hidden_states,
507
+ attentions=outputs.attentions,
508
+ )
509
+
510
+
511
+ class MiDashengLMModel(PreTrainedModel):
512
+ config_class = MiDashengLMConfig
513
+ _supports_flash_attn_2 = True
514
+ _supports_sdpa = True
515
+ _supports_cache_class = True
516
+ _supports_static_cache = True
517
+ supports_gradient_checkpointing = True
518
+
519
+ def __init__(self, config: MiDashengLMConfig):
520
+ super().__init__(config)
521
+
522
+ self.audio_token_id = config.audio_token_id
523
+
524
+ self.audio_encoder = DashengAudioTransformer._from_config(
525
+ config.audio_encoder_config,
526
+ )
527
+ self.audio_projector = AudioProjectorSubsample(
528
+ self.audio_encoder.embed_dim,
529
+ config.text_config.hidden_size,
530
+ config.subsample_factor,
531
+ )
532
+ self.decoder = Qwen25OmniThinkerTextOnlyDecoder._from_config(
533
+ config.text_config,
534
+ attn_implementation=config._attn_implementation,
535
+ )
536
+
537
+ self.post_init()
538
+
539
+ def get_input_embeddings(self):
540
+ return self.decoder.model.embed_tokens
541
+
542
+ def get_output_embeddings(self):
543
+ return self.decoder.lm_head
544
+
545
+ def _forward_audio_encoder(
546
+ self,
547
+ audios: torch.Tensor,
548
+ audio_length: Optional[Iterable[int]],
549
+ ) -> torch.Tensor:
550
+ encoder_out, encoder_atts = self.audio_encoder(audios, audio_length)
551
+
552
+ # audio projector
553
+ encoder_out, encoder_atts = self.audio_projector(encoder_out, encoder_atts)
554
+
555
+ return encoder_out
556
+
557
+ def _prepare_inputs_embeds(
558
+ self,
559
+ input_ids: Optional[torch.Tensor],
560
+ input_values: Optional[torch.Tensor],
561
+ inputs_embeds: Optional[torch.Tensor],
562
+ audio_length: Optional[Iterable[int]] = None,
563
+ ) -> torch.Tensor:
564
+ if input_ids is not None:
565
+ if inputs_embeds is not None:
566
+ raise ValueError(
567
+ "Both `inputs_embeds` and `input_ids` are passed. Please pass only one of them."
568
+ )
569
+ inputs_embeds = cast(
570
+ torch.Tensor, self.decoder.model.embed_tokens(input_ids)
571
+ )
572
+
573
+ if input_values is not None:
574
+ if self.audio_token_id is None:
575
+ raise ValueError(
576
+ "Audio input is provided, but `audio_token_id` is not configured."
577
+ )
578
+
579
+ audio_embeddings = self._forward_audio_encoder(
580
+ input_values,
581
+ audio_length=audio_length,
582
+ ).to(inputs_embeds.dtype)
583
+
584
+ audio_mask = (input_ids == self.audio_token_id).flatten()
585
+ diff = torch.diff(
586
+ audio_mask.long(),
587
+ prepend=torch.zeros(
588
+ (1,),
589
+ dtype=torch.long,
590
+ device=audio_mask.device,
591
+ ),
592
+ )
593
+ audio_span_starts = (diff == 1).nonzero()
594
+ audio_span_ends = (diff == -1).nonzero()
595
+
596
+ embeds_view = inputs_embeds.view(-1, inputs_embeds.shape[-1])
597
+ for span_start, span_end, audio in zip(
598
+ audio_span_starts,
599
+ audio_span_ends,
600
+ audio_embeddings,
601
+ strict=True,
602
+ ):
603
+ embeds_view[span_start:span_end] = audio[: span_end - span_start]
604
+ else:
605
+ if inputs_embeds is None:
606
+ raise ValueError(
607
+ "Either `input_ids` or `inputs_embeds` must be passed."
608
+ )
609
+ if input_values is not None:
610
+ raise ValueError(
611
+ "Cannot pass `input_values` when `inputs_embeds` is provided."
612
+ )
613
+
614
+ return inputs_embeds
615
+
616
+ def forward(
617
+ self,
618
+ input_ids: Optional[Tensor] = None,
619
+ input_values: Optional[Tensor] = None,
620
+ inputs_embeds: Optional[Tensor] = None,
621
+ audio_length: Optional[Iterable[int]] = None,
622
+ attention_mask: Optional[Tensor] = None,
623
+ position_ids: Optional[torch.Tensor] = None,
624
+ labels: Optional[torch.Tensor] = None,
625
+ **kwargs: Any,
626
+ ):
627
+ inputs_embeds = self._prepare_inputs_embeds(
628
+ input_ids=input_ids,
629
+ input_values=input_values,
630
+ inputs_embeds=inputs_embeds,
631
+ audio_length=audio_length,
632
+ )
633
+ return self.decoder(
634
+ input_ids=None,
635
+ inputs_embeds=inputs_embeds,
636
+ attention_mask=attention_mask,
637
+ position_ids=position_ids,
638
+ labels=labels,
639
+ **kwargs,
640
+ )
641
+
642
+ def generate(
643
+ self,
644
+ input_ids: Optional[Tensor] = None,
645
+ input_values: Optional[Tensor] = None,
646
+ inputs_embeds: Optional[Tensor] = None,
647
+ audio_length: Optional[Iterable[int]] = None,
648
+ **kwargs,
649
+ ):
650
+ inputs_embeds = self._prepare_inputs_embeds(
651
+ input_ids=input_ids,
652
+ input_values=input_values,
653
+ inputs_embeds=inputs_embeds,
654
+ audio_length=audio_length,
655
+ )
656
+ return self.decoder.generate(
657
+ inputs_embeds=inputs_embeds,
658
+ generation_config=kwargs.pop("generation_config", self.generation_config),
659
+ **kwargs,
660
+ )
preprocessor_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "processing_midashenglm.MiDashengLMProcessor"
4
+ },
5
+ "do_normalize": false,
6
+ "feature_extractor_type": "Wav2Vec2FeatureExtractor",
7
+ "feature_size": 1,
8
+ "padding_side": "right",
9
+ "padding_value": 0.0,
10
+ "processor_class": "MiDashengLMProcessor",
11
+ "return_attention_mask": false,
12
+ "sampling_rate": 16000
13
+ }
processing_midashenglm.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Optional, Union, cast
2
+
3
+ import numpy as np
4
+ import torch
5
+ from transformers import Qwen2Tokenizer, Qwen2TokenizerFast, Wav2Vec2FeatureExtractor
6
+ from transformers.feature_extraction_utils import BatchFeature
7
+ from transformers.processing_utils import ProcessingKwargs, ProcessorMixin
8
+ from typing_extensions import Unpack
9
+
10
+
11
+ class MiDashengLMProcessorKwargs(ProcessingKwargs):
12
+ _defaults = { # type: ignore
13
+ "text_kwargs": {
14
+ "padding": True,
15
+ "padding_side": "left",
16
+ },
17
+ "audio_kwargs": {},
18
+ }
19
+
20
+
21
+ def calculate_mel_frames_dasheng(
22
+ audio_length_samples: int,
23
+ n_fft: int = 512,
24
+ hop_size: int = 160,
25
+ dasheng_subsampling: int = 4,
26
+ center=True,
27
+ model_subsampling: int = 5,
28
+ ) -> int:
29
+ """Calculate the number of Mel-spectrogram frames."""
30
+ if center:
31
+ audio_length_samples = audio_length_samples + n_fft
32
+
33
+ return (
34
+ int(1 + ((audio_length_samples - n_fft) / hop_size))
35
+ // dasheng_subsampling
36
+ // model_subsampling
37
+ )
38
+
39
+
40
+ class MiDashengLMProcessor(ProcessorMixin):
41
+ attributes = ["feature_extractor", "tokenizer"]
42
+ valid_kwargs = [
43
+ "chat_template",
44
+ "audio_token",
45
+ "audio_bos_token",
46
+ "audio_eos_token",
47
+ ]
48
+ feature_extractor_class = "Wav2Vec2FeatureExtractor"
49
+ tokenizer_class = ("Qwen2Tokenizer", "Qwen2TokenizerFast")
50
+
51
+ def __init__(
52
+ self,
53
+ feature_extractor: Wav2Vec2FeatureExtractor,
54
+ tokenizer: Union[Qwen2Tokenizer, Qwen2TokenizerFast],
55
+ model_subsampling: int = 5,
56
+ chat_template: Optional[Union[str, Dict[str, str]]] = None,
57
+ audio_token: Optional[str] = None,
58
+ audio_bos_token: Optional[str] = None,
59
+ audio_eos_token: Optional[str] = None,
60
+ ):
61
+ assert audio_token is not None or hasattr(tokenizer, "audio_token"), (
62
+ "Either `audio_token` must be provided or tokenizer must have `audio_token` attribute."
63
+ )
64
+ assert audio_bos_token is not None or hasattr(tokenizer, "audio_bos_token"), (
65
+ "Either `audio_bos_token` must be provided or tokenizer must have `audio_bos_token` attribute."
66
+ )
67
+ assert audio_eos_token is not None or hasattr(tokenizer, "audio_eos_token"), (
68
+ "Either `audio_eos_token` must be provided or tokenizer must have `audio_eos_token` attribute."
69
+ )
70
+ assert not feature_extractor.do_normalize, (
71
+ "This model does not use normalization. Please set `do_normalize=False` in the feature extractor."
72
+ )
73
+
74
+ if chat_template is None:
75
+ chat_template = tokenizer.chat_template
76
+
77
+ def get_token(token_name: str) -> str:
78
+ if not hasattr(tokenizer, token_name):
79
+ raise ValueError(
80
+ f"Tokenizer does not have attribute `{token_name}`. "
81
+ "Please provide it as an argument to the processor."
82
+ )
83
+ token = getattr(tokenizer, token_name)
84
+ if not isinstance(token, str):
85
+ raise TypeError(
86
+ f"Expected token {token_name} to be a string, but got {type(token)}."
87
+ )
88
+ return token
89
+
90
+ self.audio_token = audio_token or get_token("audio_token")
91
+ self.audio_bos_token = audio_bos_token or get_token("audio_bos_token")
92
+ self.audio_eos_token = audio_eos_token or get_token("audio_eos_token")
93
+
94
+ self.audio_token_id = cast(
95
+ int, tokenizer.convert_tokens_to_ids(self.audio_token)
96
+ )
97
+ self.model_subsampling = model_subsampling
98
+ self.sampling_rate = feature_extractor.sampling_rate
99
+
100
+ super().__init__(feature_extractor, tokenizer, chat_template=chat_template)
101
+ self.feature_extractor: Wav2Vec2FeatureExtractor
102
+ self.tokenizer: Union[Qwen2Tokenizer, Qwen2TokenizerFast]
103
+ self.chat_template: Optional[Union[str, Dict[str, str]]]
104
+
105
+ def _process_messages_for_chat_template(
106
+ self,
107
+ conversation,
108
+ batch_images,
109
+ batch_videos,
110
+ batch_video_metadata,
111
+ **mm_load_kwargs,
112
+ ):
113
+ if (sr := mm_load_kwargs.get("sampling_rate", None)) is not None:
114
+ if sr != self.sampling_rate:
115
+ raise ValueError(
116
+ f"This model is trained with a sampling rate of {self.sampling_rate}, "
117
+ f"but the sampling rate {sr} is used to load audio."
118
+ )
119
+ return super()._process_messages_for_chat_template(
120
+ conversation,
121
+ batch_images,
122
+ batch_videos,
123
+ batch_video_metadata,
124
+ **mm_load_kwargs,
125
+ )
126
+
127
+ @classmethod
128
+ def _validate_audio_sample(
129
+ cls,
130
+ sample: Union[np.ndarray, torch.Tensor],
131
+ ) -> np.ndarray:
132
+ if isinstance(sample, torch.Tensor):
133
+ if sample.ndim != 1:
134
+ raise ValueError("Audio tensor must be 1D.")
135
+ return sample.numpy()
136
+ if isinstance(sample, np.ndarray):
137
+ if sample.ndim != 1:
138
+ raise ValueError("Audio array must be 1D.")
139
+ return sample
140
+ if isinstance(sample, str):
141
+ # When passing audio paths through `apply_chat_template`, transformers
142
+ # will attempt to load the audio file, but only succeeds if the path
143
+ # is a valid URL (starting with http:// or https://) or an existing local
144
+ # file. Otherwise, the string is passed as-is. This captures that case and
145
+ # raises an error to inform the user.
146
+ raise TypeError(
147
+ "Expected audio to be a numpy array or torch tensor, but got a string. "
148
+ "If you passed audios through `apply_chat_template`, "
149
+ "make sure the audio paths are valid URLs starting with http:// or https://, "
150
+ "or existing local files."
151
+ )
152
+ raise TypeError(
153
+ f"Expected audio to be a numpy array, torch tensor, or string, but got {type(sample)}."
154
+ )
155
+
156
+ def __call__(
157
+ self,
158
+ text: Optional[List[str]] = None,
159
+ audio: Optional[Union[List[np.ndarray], List[torch.Tensor]]] = None,
160
+ **kwargs: Unpack[MiDashengLMProcessorKwargs],
161
+ ) -> BatchFeature:
162
+ if text is None:
163
+ raise ValueError("You need to specify `text` input to process.")
164
+ elif isinstance(text, str):
165
+ text = [text]
166
+ elif not isinstance(text, list) and not isinstance(text[0], str):
167
+ raise ValueError(
168
+ "Invalid input text. Please provide a string, or a list of strings"
169
+ )
170
+
171
+ if (
172
+ kwargs.get("images", None) is not None
173
+ or kwargs.get("videos", None) is not None
174
+ ):
175
+ raise ValueError("This model does not support images or videos.")
176
+
177
+ output_kwargs = self._merge_kwargs(
178
+ MiDashengLMProcessorKwargs, # type: ignore # Bad type hint in transformers
179
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
180
+ **kwargs,
181
+ )
182
+
183
+ if audio is not None:
184
+ audio = [self._validate_audio_sample(sample) for sample in audio]
185
+ # ensure we have as much audios as audio tokens
186
+ num_audio_tokens = sum(sample.count(self.audio_token) for sample in text)
187
+ num_audios = 1 if type(audio) is np.ndarray else len(audio)
188
+ if num_audio_tokens != num_audios:
189
+ raise ValueError(
190
+ f"Found {num_audio_tokens} {self.audio_token} token{'s' if num_audio_tokens > 1 else ''} in provided text but received {num_audios} audio{'s' if num_audios > 1 else ''}"
191
+ )
192
+
193
+ # Some kwargs should not be changed so we can expand text with audio tokens below
194
+ output_kwargs["audio_kwargs"]["return_attention_mask"] = True
195
+ output_kwargs["audio_kwargs"]["padding"] = True
196
+ output_kwargs["audio_kwargs"]["return_tensors"] = "pt"
197
+
198
+ # + Padding
199
+ audio_inputs = self.feature_extractor(
200
+ audio,
201
+ sampling_rate=self.sampling_rate,
202
+ **output_kwargs["audio_kwargs"],
203
+ )
204
+
205
+ # remove attention mask, dasheng uses lengths
206
+ audio_feature_mask = audio_inputs.pop("attention_mask")
207
+
208
+ expanded_text = []
209
+ audio_lengths = audio_feature_mask.sum(-1).tolist()
210
+ audio_inputs["audio_length"] = torch.tensor(audio_lengths).long()
211
+
212
+ for sample in text:
213
+ replace_str = []
214
+ while self.audio_token in sample:
215
+ audio_length = audio_lengths.pop(0)
216
+ num_audio_tokens = calculate_mel_frames_dasheng(
217
+ audio_length, model_subsampling=self.model_subsampling
218
+ )
219
+
220
+ expanded_audio_token = self.audio_token * num_audio_tokens
221
+
222
+ audio_token_start_idx = sample.find(self.audio_token)
223
+ audio_token_end_idx = audio_token_start_idx + len(self.audio_token)
224
+
225
+ has_bos = (
226
+ sample[
227
+ audio_token_start_idx
228
+ - len(self.audio_bos_token) : audio_token_start_idx
229
+ ]
230
+ == self.audio_bos_token
231
+ )
232
+ has_eos = (
233
+ sample[
234
+ audio_token_end_idx : audio_token_end_idx
235
+ + len(self.audio_eos_token)
236
+ ]
237
+ == self.audio_eos_token
238
+ )
239
+
240
+ # Check if this audio token is surrounded by bos/eos tokens
241
+ if not has_bos and not has_eos:
242
+ expanded_audio_token = (
243
+ self.audio_bos_token
244
+ + expanded_audio_token
245
+ + self.audio_eos_token
246
+ )
247
+
248
+ replace_str.append(expanded_audio_token)
249
+ sample = sample.replace(self.audio_token, "<placeholder>", 1)
250
+
251
+ while "<placeholder>" in sample:
252
+ sample = sample.replace("<placeholder>", replace_str.pop(0), 1)
253
+ expanded_text.append(sample)
254
+ text = expanded_text
255
+
256
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", "pt")
257
+ inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
258
+ self._check_special_mm_tokens(
259
+ text,
260
+ BatchFeature(inputs), # type: ignore
261
+ modalities=["audio"],
262
+ )
263
+
264
+ if audio is not None:
265
+ inputs.update(audio_inputs)
266
+
267
+ return BatchFeature(data={**inputs}, tensor_type=return_tensors)
268
+
269
+ @property
270
+ def model_input_names(self):
271
+ tokenizer_input_names = self.tokenizer.model_input_names
272
+ feature_extractor_input_names = self.feature_extractor.model_input_names
273
+ return list(
274
+ dict.fromkeys(
275
+ tokenizer_input_names + feature_extractor_input_names + ["audio_length"]
276
+ )
277
+ )
processor_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "audio_bos_token": "<|audio_bos|>",
3
+ "audio_eos_token": "<|audio_eos|>",
4
+ "audio_token": "<|AUDIO|>",
5
+ "auto_map": {
6
+ "AutoProcessor": "processing_midashenglm.MiDashengLMProcessor"
7
+ },
8
+ "model_subsampling": 5,
9
+ "processor_class": "MiDashengLMProcessor"
10
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|en|>",
4
+ "<|kr|>",
5
+ "<|de|>",
6
+ "<|es|>",
7
+ "<|fr|>",
8
+ "<|hi|>",
9
+ "<|uk|>",
10
+ "<|th|>",
11
+ "<|vi|>",
12
+ "<|nl|>",
13
+ "<|pt|>",
14
+ "<|id|>",
15
+ "<|ru|>",
16
+ "<|it|>",
17
+ "<|ar|>",
18
+ "<|jp|>",
19
+ "<|unknown|>"
20
+ ],
21
+ "audio_bos_token": "<|audio_bos|>",
22
+ "audio_eos_token": "<|audio_eos|>",
23
+ "audio_token": "<|AUDIO|>",
24
+ "eos_token": {
25
+ "content": "<|im_end|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ "image_token": "<|IMAGE|>",
32
+ "pad_token": {
33
+ "content": "<|endoftext|>",
34
+ "lstrip": false,
35
+ "normalized": false,
36
+ "rstrip": false,
37
+ "single_word": false
38
+ },
39
+ "video_token": "<|VIDEO|>",
40
+ "vision_bos_token": "<|vision_bos|>",
41
+ "vision_eos_token": "<|vision_eos|>"
42
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c40343a9d670f4fadbe6415ed2cff441055f663e51d813f2315c3368399914d5
3
+ size 11424986
tokenizer_config.json ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "151643": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "151644": {
13
+ "content": "<|im_start|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "151645": {
21
+ "content": "<|im_end|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "151646": {
29
+ "content": "<|AUDIO|>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "151647": {
37
+ "content": "<|audio_bos|>",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "151648": {
45
+ "content": "<|audio_eos|>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false,
50
+ "special": true
51
+ },
52
+ "151649": {
53
+ "content": "<|box_end|>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false,
58
+ "special": true
59
+ },
60
+ "151650": {
61
+ "content": "<|quad_start|>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false,
66
+ "special": true
67
+ },
68
+ "151651": {
69
+ "content": "<|quad_end|>",
70
+ "lstrip": false,
71
+ "normalized": false,
72
+ "rstrip": false,
73
+ "single_word": false,
74
+ "special": true
75
+ },
76
+ "151652": {
77
+ "content": "<|vision_bos|>",
78
+ "lstrip": false,
79
+ "normalized": false,
80
+ "rstrip": false,
81
+ "single_word": false,
82
+ "special": true
83
+ },
84
+ "151653": {
85
+ "content": "<|vision_eos|>",
86
+ "lstrip": false,
87
+ "normalized": false,
88
+ "rstrip": false,
89
+ "single_word": false,
90
+ "special": true
91
+ },
92
+ "151654": {
93
+ "content": "<|vision_pad|>",
94
+ "lstrip": false,
95
+ "normalized": false,
96
+ "rstrip": false,
97
+ "single_word": false,
98
+ "special": true
99
+ },
100
+ "151655": {
101
+ "content": "<|IMAGE|>",
102
+ "lstrip": false,
103
+ "normalized": false,
104
+ "rstrip": false,
105
+ "single_word": false,
106
+ "special": true
107
+ },
108
+ "151656": {
109
+ "content": "<|VIDEO|>",
110
+ "lstrip": false,
111
+ "normalized": false,
112
+ "rstrip": false,
113
+ "single_word": false,
114
+ "special": true
115
+ },
116
+ "151657": {
117
+ "content": "<tool_call>",
118
+ "lstrip": false,
119
+ "normalized": false,
120
+ "rstrip": false,
121
+ "single_word": false,
122
+ "special": false
123
+ },
124
+ "151658": {
125
+ "content": "</tool_call>",
126
+ "lstrip": false,
127
+ "normalized": false,
128
+ "rstrip": false,
129
+ "single_word": false,
130
+ "special": false
131
+ },
132
+ "151659": {
133
+ "content": "<|fim_prefix|>",
134
+ "lstrip": false,
135
+ "normalized": false,
136
+ "rstrip": false,
137
+ "single_word": false,
138
+ "special": false
139
+ },
140
+ "151660": {
141
+ "content": "<|fim_middle|>",
142
+ "lstrip": false,
143
+ "normalized": false,
144
+ "rstrip": false,
145
+ "single_word": false,
146
+ "special": false
147
+ },
148
+ "151661": {
149
+ "content": "<|fim_suffix|>",
150
+ "lstrip": false,
151
+ "normalized": false,
152
+ "rstrip": false,
153
+ "single_word": false,
154
+ "special": false
155
+ },
156
+ "151662": {
157
+ "content": "<|fim_pad|>",
158
+ "lstrip": false,
159
+ "normalized": false,
160
+ "rstrip": false,
161
+ "single_word": false,
162
+ "special": false
163
+ },
164
+ "151663": {
165
+ "content": "<|repo_name|>",
166
+ "lstrip": false,
167
+ "normalized": false,
168
+ "rstrip": false,
169
+ "single_word": false,
170
+ "special": false
171
+ },
172
+ "151664": {
173
+ "content": "<|file_sep|>",
174
+ "lstrip": false,
175
+ "normalized": false,
176
+ "rstrip": false,
177
+ "single_word": false,
178
+ "special": false
179
+ },
180
+ "151665": {
181
+ "content": "<|en|>",
182
+ "lstrip": false,
183
+ "normalized": false,
184
+ "rstrip": false,
185
+ "single_word": false,
186
+ "special": true
187
+ },
188
+ "151666": {
189
+ "content": "<|kr|>",
190
+ "lstrip": false,
191
+ "normalized": false,
192
+ "rstrip": false,
193
+ "single_word": false,
194
+ "special": true
195
+ },
196
+ "151667": {
197
+ "content": "<|de|>",
198
+ "lstrip": false,
199
+ "normalized": false,
200
+ "rstrip": false,
201
+ "single_word": false,
202
+ "special": true
203
+ },
204
+ "151668": {
205
+ "content": "<|es|>",
206
+ "lstrip": false,
207
+ "normalized": false,
208
+ "rstrip": false,
209
+ "single_word": false,
210
+ "special": true
211
+ },
212
+ "151669": {
213
+ "content": "<|fr|>",
214
+ "lstrip": false,
215
+ "normalized": false,
216
+ "rstrip": false,
217
+ "single_word": false,
218
+ "special": true
219
+ },
220
+ "151670": {
221
+ "content": "<|hi|>",
222
+ "lstrip": false,
223
+ "normalized": false,
224
+ "rstrip": false,
225
+ "single_word": false,
226
+ "special": true
227
+ },
228
+ "151671": {
229
+ "content": "<|uk|>",
230
+ "lstrip": false,
231
+ "normalized": false,
232
+ "rstrip": false,
233
+ "single_word": false,
234
+ "special": true
235
+ },
236
+ "151672": {
237
+ "content": "<|th|>",
238
+ "lstrip": false,
239
+ "normalized": false,
240
+ "rstrip": false,
241
+ "single_word": false,
242
+ "special": true
243
+ },
244
+ "151673": {
245
+ "content": "<|vi|>",
246
+ "lstrip": false,
247
+ "normalized": false,
248
+ "rstrip": false,
249
+ "single_word": false,
250
+ "special": true
251
+ },
252
+ "151674": {
253
+ "content": "<|nl|>",
254
+ "lstrip": false,
255
+ "normalized": false,
256
+ "rstrip": false,
257
+ "single_word": false,
258
+ "special": true
259
+ },
260
+ "151675": {
261
+ "content": "<|pt|>",
262
+ "lstrip": false,
263
+ "normalized": false,
264
+ "rstrip": false,
265
+ "single_word": false,
266
+ "special": true
267
+ },
268
+ "151676": {
269
+ "content": "<|id|>",
270
+ "lstrip": false,
271
+ "normalized": false,
272
+ "rstrip": false,
273
+ "single_word": false,
274
+ "special": true
275
+ },
276
+ "151677": {
277
+ "content": "<|ru|>",
278
+ "lstrip": false,
279
+ "normalized": false,
280
+ "rstrip": false,
281
+ "single_word": false,
282
+ "special": true
283
+ },
284
+ "151678": {
285
+ "content": "<|it|>",
286
+ "lstrip": false,
287
+ "normalized": false,
288
+ "rstrip": false,
289
+ "single_word": false,
290
+ "special": true
291
+ },
292
+ "151679": {
293
+ "content": "<|ar|>",
294
+ "lstrip": false,
295
+ "normalized": false,
296
+ "rstrip": false,
297
+ "single_word": false,
298
+ "special": true
299
+ },
300
+ "151680": {
301
+ "content": "<|jp|>",
302
+ "lstrip": false,
303
+ "normalized": false,
304
+ "rstrip": false,
305
+ "single_word": false,
306
+ "special": true
307
+ },
308
+ "151681": {
309
+ "content": "<|unknown|>",
310
+ "lstrip": false,
311
+ "normalized": false,
312
+ "rstrip": false,
313
+ "single_word": false,
314
+ "special": true
315
+ }
316
+ },
317
+ "additional_special_tokens": [
318
+ "<|en|>",
319
+ "<|kr|>",
320
+ "<|de|>",
321
+ "<|es|>",
322
+ "<|fr|>",
323
+ "<|hi|>",
324
+ "<|uk|>",
325
+ "<|th|>",
326
+ "<|vi|>",
327
+ "<|nl|>",
328
+ "<|pt|>",
329
+ "<|id|>",
330
+ "<|ru|>",
331
+ "<|it|>",
332
+ "<|ar|>",
333
+ "<|jp|>",
334
+ "<|unknown|>"
335
+ ],
336
+ "audio_bos_token": "<|audio_bos|>",
337
+ "audio_eos_token": "<|audio_eos|>",
338
+ "audio_token": "<|AUDIO|>",
339
+ "auto_map": {
340
+ "AutoProcessor": "processing_midashenglm.MiDashengLMProcessor"
341
+ },
342
+ "bos_token": null,
343
+ "clean_up_tokenization_spaces": false,
344
+ "eos_token": "<|im_end|>",
345
+ "errors": "replace",
346
+ "extra_special_tokens": {
347
+ "audio_bos_token": "<|audio_bos|>",
348
+ "audio_eos_token": "<|audio_eos|>",
349
+ "audio_token": "<|AUDIO|>",
350
+ "image_token": "<|IMAGE|>",
351
+ "video_token": "<|VIDEO|>",
352
+ "vision_bos_token": "<|vision_bos|>",
353
+ "vision_eos_token": "<|vision_eos|>"
354
+ },
355
+ "image_token": "<|IMAGE|>",
356
+ "model_max_length": 32768,
357
+ "pad_token": "<|endoftext|>",
358
+ "processor_class": "MiDashengLMProcessor",
359
+ "split_special_tokens": false,
360
+ "tokenizer_class": "Qwen2Tokenizer",
361
+ "unk_token": null,
362
+ "video_token": "<|VIDEO|>",
363
+ "vision_bos_token": "<|vision_bos|>",
364
+ "vision_eos_token": "<|vision_eos|>"
365
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff