feizhai123 commited on
Commit
4651adf
·
verified ·
1 Parent(s): b3258a4

Add Ref2VA shared components (1-20)

Browse files
Ref2VA/audio_vae/config.json ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "MiniMaxH3AudioVAE",
3
+ "_diffusers_version": "0.32.2",
4
+ "auto_map": {
5
+ "AutoModel": "minimax_h3_audio_vae.MiniMaxH3AudioVAE"
6
+ },
7
+ "output_channel": 2,
8
+ "sample_rate": 32000,
9
+ "source_config_path": "config.yaml",
10
+ "source_safetensors_path": "model.safetensors",
11
+ "source_metadata_path": "metadata.json",
12
+ "latent_channels": 32,
13
+ "latents_mean": [
14
+ -0.020211687488382354,
15
+ 0.3876466479950502,
16
+ -0.04398279799186767,
17
+ -0.28591514936373,
18
+ 0.08179686214561671,
19
+ -0.35782641352446604,
20
+ 0.040623809960919084,
21
+ -0.01552534501956604,
22
+ -0.223362481667332,
23
+ 0.1821006842509091,
24
+ 0.2941778783780663,
25
+ -0.07901167601970885,
26
+ -0.056815072777201,
27
+ -0.3699028221860095,
28
+ -0.31616315591624855,
29
+ 0.5905951377425391,
30
+ -0.052139568068853864,
31
+ 0.013673160263486295,
32
+ -0.03691647864630577,
33
+ 0.09732660653298163,
34
+ -0.3394662328788498,
35
+ -0.30685677538541667,
36
+ -0.24504598907458763,
37
+ -0.034698524462007344,
38
+ 0.02868032184767538,
39
+ -0.21217779266454084,
40
+ -0.1678263169941987,
41
+ 0.3221287889040614,
42
+ -0.1223055851554907,
43
+ 0.4356604928128464,
44
+ -0.0502599202236253,
45
+ 0.3979258376211797
46
+ ],
47
+ "latents_std": [
48
+ 1.6895524230479284,
49
+ 2.76263727217653,
50
+ 1.7945344281264435,
51
+ 1.6801681847309828,
52
+ 1.6390226546605453,
53
+ 2.7788298348882177,
54
+ 1.7659090095747236,
55
+ 1.6199757612137327,
56
+ 2.6336525640336896,
57
+ 1.8539356672817833,
58
+ 2.5056497896915633,
59
+ 1.811019237886178,
60
+ 1.9579657790720237,
61
+ 1.6685498243529284,
62
+ 1.4922469314453364,
63
+ 3.298670198067373,
64
+ 1.9491804496832168,
65
+ 1.8720003270431442,
66
+ 1.8334080103291832,
67
+ 1.6488070416529093,
68
+ 1.6176957696319716,
69
+ 1.9131449234774398,
70
+ 1.5695245398428617,
71
+ 1.6943659940415912,
72
+ 1.8318420762504692,
73
+ 1.5540637421583379,
74
+ 1.9344930328968526,
75
+ 1.599198216109855,
76
+ 1.718045989838149,
77
+ 1.6307219190837705,
78
+ 1.8661226051202384,
79
+ 1.5613768203168363
80
+ ]
81
+ }
Ref2VA/audio_vae/config.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ model_config:
2
+ sr: 32000
3
+ decoder_dim: 1024
4
+ audio_channel: 1
5
+ vae_latent_channels: 32
Ref2VA/audio_vae/dac_activations.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+ # Implementation adapted from https://github.com/EdwardDixon/snake under the MIT license.
3
+
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import Parameter
7
+
8
+
9
+ @torch.jit.script
10
+ def snakebeta(x, alpha, beta):
11
+ shape = x.shape
12
+ x = x.reshape(shape[0], shape[1], -1)
13
+ x = x + (beta + 1e-9).reciprocal() * torch.sin(alpha * x).pow(2)
14
+ x = x.reshape(shape)
15
+ return x
16
+
17
+
18
+ class SnakeBeta(nn.Module):
19
+ def __init__(self, in_features, alpha=1.0, alpha_trainable=True, alpha_logscale=False):
20
+ """
21
+ Initialization.
22
+ INPUT:
23
+ - in_features: shape of the input
24
+ - alpha - trainable parameter that controls frequency
25
+ - beta - trainable parameter that controls magnitude
26
+ alpha is initialized to 1 by default, higher values = higher-frequency.
27
+ beta is initialized to 1 by default, higher values = higher-magnitude.
28
+ alpha will be trained along with the rest of your model.
29
+ """
30
+ super(SnakeBeta, self).__init__()
31
+ self.in_features = in_features
32
+
33
+ # Initialize alpha
34
+ self.alpha_logscale = alpha_logscale
35
+ if self.alpha_logscale: # Log scale alphas initialized to zeros
36
+ self.alpha = Parameter(torch.zeros(in_features) * alpha)
37
+ self.beta = Parameter(torch.zeros(in_features) * alpha)
38
+ else: # Linear scale alphas initialized to ones
39
+ self.alpha = Parameter(torch.ones(in_features) * alpha)
40
+ self.beta = Parameter(torch.ones(in_features) * alpha)
41
+
42
+ self.alpha.requires_grad = alpha_trainable
43
+ self.beta.requires_grad = alpha_trainable
44
+
45
+ self.no_div_by_zero = 0.000000001
46
+
47
+ def forward(self, x):
48
+ """
49
+ Forward pass of the function.
50
+ Applies the function to the input elementwise.
51
+ SnakeBeta := x + 1/b * sin^2 (xa)
52
+ """
53
+ alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # Line up with x to [B, C, T]
54
+ beta = self.beta.unsqueeze(0).unsqueeze(-1)
55
+ if self.alpha_logscale:
56
+ alpha = torch.exp(alpha)
57
+ beta = torch.exp(beta)
58
+ x = snakebeta(x, alpha, beta)
59
+
60
+ return x
Ref2VA/audio_vae/dac_alias_free_act.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Adapted from https://github.com/junjun3518/alias-free-torch under the Apache License 2.0
3
+
4
+ import torch.nn as nn
5
+ from .dac_alias_free_resample import UpSample1d, DownSample1d
6
+
7
+
8
+ class Activation1d(nn.Module):
9
+ def __init__(
10
+ self,
11
+ activation,
12
+ up_ratio: int = 2,
13
+ down_ratio: int = 2,
14
+ up_kernel_size: int = 12,
15
+ down_kernel_size: int = 12,
16
+ ):
17
+ super().__init__()
18
+ self.up_ratio = up_ratio
19
+ self.down_ratio = down_ratio
20
+ self.act = activation
21
+ self.upsample = UpSample1d(up_ratio, up_kernel_size)
22
+ self.downsample = DownSample1d(down_ratio, down_kernel_size)
23
+
24
+ # x: [B,C,T]
25
+ def forward(self, x):
26
+ x = self.upsample(x)
27
+ x = self.act(x)
28
+ x = self.downsample(x)
29
+
30
+ return x
Ref2VA/audio_vae/dac_alias_free_filter.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Adapted from https://github.com/junjun3518/alias-free-torch under the Apache License 2.0
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ import math
8
+
9
+ if "sinc" in dir(torch):
10
+ sinc = torch.sinc
11
+ else:
12
+ # This code is adopted from adefossez's julius.core.sinc under the MIT License
13
+ # https://adefossez.github.io/julius/julius/core.html
14
+ def sinc(x: torch.Tensor):
15
+ """
16
+ Implementation of sinc, i.e. sin(pi * x) / (pi * x)
17
+ __Warning__: Different to julius.sinc, the input is multiplied by `pi`!
18
+ """
19
+ return torch.where(
20
+ x == 0,
21
+ torch.tensor(1.0, device=x.device, dtype=x.dtype),
22
+ torch.sin(math.pi * x) / math.pi / x,
23
+ )
24
+
25
+
26
+ # This code is adopted from adefossez's julius.lowpass.LowPassFilters under the MIT License
27
+ # https://adefossez.github.io/julius/julius/lowpass.html
28
+ def kaiser_sinc_filter1d(cutoff, half_width, kernel_size): # return filter [1,1,kernel_size]
29
+ even = kernel_size % 2 == 0
30
+ half_size = kernel_size // 2
31
+
32
+ # For kaiser window
33
+ delta_f = 4 * half_width
34
+ A = 2.285 * (half_size - 1) * math.pi * delta_f + 7.95
35
+ if A > 50.0:
36
+ beta = 0.1102 * (A - 8.7)
37
+ elif A >= 21.0:
38
+ beta = 0.5842 * (A - 21) ** 0.4 + 0.07886 * (A - 21.0)
39
+ else:
40
+ beta = 0.0
41
+ window = torch.kaiser_window(kernel_size, beta=beta, periodic=False)
42
+
43
+ # ratio = 0.5/cutoff -> 2 * cutoff = 1 / ratio
44
+ if even:
45
+ time = torch.arange(-half_size, half_size) + 0.5
46
+ else:
47
+ time = torch.arange(kernel_size) - half_size
48
+ if cutoff == 0:
49
+ filter_ = torch.zeros_like(time)
50
+ else:
51
+ filter_ = 2 * cutoff * window * sinc(2 * cutoff * time)
52
+ """
53
+ Normalize filter to have sum = 1, otherwise we will have a small leakage of the constant component in the input signal.
54
+ """
55
+ filter_ /= filter_.sum()
56
+ filter = filter_.view(1, 1, kernel_size)
57
+
58
+ return filter
59
+
60
+
61
+ class LowPassFilter1d(nn.Module):
62
+ def __init__(
63
+ self,
64
+ cutoff=0.5,
65
+ half_width=0.6,
66
+ stride: int = 1,
67
+ padding: bool = True,
68
+ padding_mode: str = "replicate",
69
+ kernel_size: int = 12,
70
+ ):
71
+ """
72
+ kernel_size should be even number for stylegan3 setup, in this implementation, odd number is also possible.
73
+ """
74
+ super().__init__()
75
+ if cutoff < -0.0:
76
+ raise ValueError("Minimum cutoff must be larger than zero.")
77
+ if cutoff > 0.5:
78
+ raise ValueError("A cutoff above 0.5 does not make sense.")
79
+ self.kernel_size = kernel_size
80
+ self.even = kernel_size % 2 == 0
81
+ self.pad_left = kernel_size // 2 - int(self.even)
82
+ self.pad_right = kernel_size // 2
83
+ self.stride = stride
84
+ self.padding = padding
85
+ self.padding_mode = padding_mode
86
+ filter = kaiser_sinc_filter1d(cutoff, half_width, kernel_size)
87
+ self.register_buffer("filter", filter)
88
+
89
+ # Input [B, C, T]
90
+ def forward(self, x):
91
+ _, C, _ = x.shape
92
+
93
+ if self.padding:
94
+ x = F.pad(x, (self.pad_left, self.pad_right), mode=self.padding_mode)
95
+ out = F.conv1d(x, self.filter.expand(C, -1, -1), stride=self.stride, groups=C)
96
+
97
+ return out
Ref2VA/audio_vae/dac_alias_free_resample.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Adapted from https://github.com/junjun3518/alias-free-torch under the Apache License 2.0
3
+
4
+ import torch.nn as nn
5
+ from torch.nn import functional as F
6
+ from .dac_alias_free_filter import LowPassFilter1d
7
+ from .dac_alias_free_filter import kaiser_sinc_filter1d
8
+
9
+
10
+ class UpSample1d(nn.Module):
11
+ def __init__(self, ratio=2, kernel_size=None):
12
+ super().__init__()
13
+ self.ratio = ratio
14
+ self.kernel_size = int(6 * ratio // 2) * 2 if kernel_size is None else kernel_size
15
+ self.stride = ratio
16
+ self.pad = self.kernel_size // ratio - 1
17
+ self.pad_left = self.pad * self.stride + (self.kernel_size - self.stride) // 2
18
+ self.pad_right = self.pad * self.stride + (self.kernel_size - self.stride + 1) // 2
19
+ filter = kaiser_sinc_filter1d(cutoff=0.5 / ratio, half_width=0.6 / ratio, kernel_size=self.kernel_size)
20
+ self.register_buffer("filter", filter)
21
+
22
+ # x: [B, C, T]
23
+ def forward(self, x):
24
+ _, C, _ = x.shape
25
+
26
+ x = F.pad(x, (self.pad, self.pad), mode="replicate")
27
+ x = self.ratio * F.conv_transpose1d(x, self.filter.expand(C, -1, -1), stride=self.stride, groups=C)
28
+ x = x[..., self.pad_left : -self.pad_right]
29
+
30
+ return x
31
+
32
+
33
+ class DownSample1d(nn.Module):
34
+ def __init__(self, ratio=2, kernel_size=None):
35
+ super().__init__()
36
+ self.ratio = ratio
37
+ self.kernel_size = int(6 * ratio // 2) * 2 if kernel_size is None else kernel_size
38
+ self.lowpass = LowPassFilter1d(
39
+ cutoff=0.5 / ratio,
40
+ half_width=0.6 / ratio,
41
+ stride=ratio,
42
+ kernel_size=self.kernel_size,
43
+ )
44
+
45
+ def forward(self, x):
46
+ xx = self.lowpass(x)
47
+
48
+ return xx
Ref2VA/audio_vae/dac_attn_proj.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from torch.nn.functional import scaled_dot_product_attention
6
+
7
+
8
+ class GeGluMlp(nn.Module):
9
+ def __init__(
10
+ self,
11
+ in_features,
12
+ hidden_features,
13
+ ):
14
+ super().__init__()
15
+ self.norm = nn.LayerNorm(in_features)
16
+ self.act = nn.GELU(approximate="tanh")
17
+ self.w0 = nn.Linear(in_features, hidden_features)
18
+ self.w1 = nn.Linear(in_features, hidden_features)
19
+ self.w2 = nn.Linear(hidden_features, in_features)
20
+
21
+ def forward(self, x):
22
+ x = self.norm(x)
23
+ x = self.act(self.w0(x)) * self.w1(x)
24
+ x = self.w2(x)
25
+ return x
26
+
27
+
28
+ class CausalAttention(nn.Module):
29
+ def __init__(self, in_dim, out_dim, num_heads):
30
+ super().__init__()
31
+ if in_dim > out_dim:
32
+ # assert in_dim // num_heads == out_dim
33
+ self.head_dim = in_dim // num_heads
34
+ self.qkv = nn.Linear(in_dim, in_dim * 3, bias=False)
35
+ self.q_bias = nn.Parameter(torch.zeros(in_dim))
36
+ self.v_bias = nn.Parameter(torch.zeros(in_dim))
37
+ self.register_buffer("zero_k_bias", torch.zeros(in_dim))
38
+ else:
39
+ # assert out_dim // num_heads == in_dim
40
+ self.head_dim = out_dim // num_heads
41
+ self.qkv = nn.Linear(in_dim, out_dim * 3, bias=False)
42
+ self.q_bias = nn.Parameter(torch.zeros(out_dim))
43
+ self.v_bias = nn.Parameter(torch.zeros(out_dim))
44
+ self.register_buffer("zero_k_bias", torch.zeros(out_dim))
45
+
46
+ self.in_dim = in_dim
47
+ self.out_dim = out_dim
48
+ self.num_heads = num_heads
49
+ self.scale = self.head_dim**-0.5
50
+ self.proj = nn.Linear(out_dim, out_dim)
51
+
52
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
53
+ B, N, C = x.shape
54
+ qkv = F.linear(input=x, weight=self.qkv.weight, bias=torch.cat((self.q_bias, self.zero_k_bias, self.v_bias)))
55
+ q, k, v = qkv.reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4).unbind(0)
56
+
57
+ x = scaled_dot_product_attention(q, k, v, attn_mask=None, dropout_p=0.0, is_causal=True)
58
+
59
+ if self.in_dim > self.out_dim:
60
+ x = torch.mean(x, dim=1)
61
+ if self.in_dim // self.num_heads != self.out_dim:
62
+ x = nn.functional.adaptive_avg_pool1d(x, self.out_dim)
63
+ else:
64
+ x = x.transpose(1, 2).reshape(B, N, -1)
65
+ x = self.proj(x)
66
+ return x
67
+
68
+
69
+ class AttnProjection(nn.Module):
70
+ def __init__(self, in_dim, out_dim, num_heads, norm_layer=nn.LayerNorm, mlp_ratio=2):
71
+ super().__init__()
72
+ assert out_dim % in_dim == 0 or in_dim % out_dim == 0
73
+ self.in_dim = in_dim
74
+ self.out_dim = out_dim
75
+ self.norm1 = norm_layer(in_dim)
76
+ self.attn = CausalAttention(in_dim, out_dim, num_heads)
77
+ self.proj = nn.Linear(in_dim, out_dim)
78
+ self.norm3 = norm_layer(in_dim)
79
+
80
+ self.norm2 = norm_layer(out_dim)
81
+ hidden_dim = int(out_dim * mlp_ratio)
82
+ self.mlp = GeGluMlp(in_features=out_dim, hidden_features=hidden_dim)
83
+ # self.mlp = FeedForward(out_dim, out_dim)
84
+
85
+ def forward(self, x):
86
+ x = self.proj(self.norm3(x)) + self.attn(self.norm1(x))
87
+ x = x + self.mlp(self.norm2(x))
88
+ return x
Ref2VA/audio_vae/dac_audio_vae.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # DAC-lineage audio VAE: waveform encoder + BigVGAN decoder (inference-only bundle).
3
+ import math
4
+ from typing import List
5
+
6
+ import numpy as np
7
+ import torch
8
+ from torch import nn
9
+ from torch.nn.utils.parametrizations import weight_norm
10
+
11
+ from .dac_bigvgan import BigVGAN
12
+ from .dac_attn_proj import AttnProjection
13
+
14
+
15
+ class AttrDict(dict):
16
+ def __init__(self, *args, **kwargs):
17
+ super(AttrDict, self).__init__(*args, **kwargs)
18
+ self.__dict__ = self
19
+
20
+
21
+ def WNConv1d(*args, **kwargs):
22
+ return weight_norm(nn.Conv1d(*args, **kwargs))
23
+
24
+
25
+ @torch.jit.script
26
+ def snake(x, alpha):
27
+ shape = x.shape
28
+ x = x.reshape(shape[0], shape[1], -1)
29
+ x = x + (alpha + 1e-9).reciprocal() * torch.sin(alpha * x).pow(2)
30
+ x = x.reshape(shape)
31
+ return x
32
+
33
+
34
+ class Snake1d(nn.Module):
35
+ def __init__(self, channels):
36
+ super().__init__()
37
+ self.alpha = nn.Parameter(torch.ones(1, channels, 1))
38
+
39
+ def forward(self, x):
40
+ return snake(x, self.alpha)
41
+
42
+
43
+ def init_weights(m):
44
+ if isinstance(m, nn.Conv1d):
45
+ nn.init.trunc_normal_(m.weight, std=0.02)
46
+ if m.bias is not None:
47
+ nn.init.constant_(m.bias, 0)
48
+
49
+
50
+ class ResidualUnit(nn.Module):
51
+ def __init__(self, dim: int = 16, dilation: int = 1):
52
+ super().__init__()
53
+ pad = ((7 - 1) * dilation) // 2
54
+ self.block = nn.Sequential(
55
+ Snake1d(dim),
56
+ WNConv1d(dim, dim, kernel_size=7, dilation=dilation, padding=pad),
57
+ Snake1d(dim),
58
+ WNConv1d(dim, dim, kernel_size=1),
59
+ )
60
+
61
+ def forward(self, x):
62
+ y = self.block(x)
63
+ pad = (x.shape[-1] - y.shape[-1]) // 2
64
+ if pad > 0:
65
+ x = x[..., pad:-pad]
66
+ return x + y
67
+
68
+
69
+ class EncoderBlock(nn.Module):
70
+ def __init__(self, dim: int = 16, stride: int = 1):
71
+ super().__init__()
72
+ self.block = nn.Sequential(
73
+ ResidualUnit(dim // 2, dilation=1),
74
+ ResidualUnit(dim // 2, dilation=3),
75
+ ResidualUnit(dim // 2, dilation=9),
76
+ Snake1d(dim // 2),
77
+ WNConv1d(
78
+ dim // 2,
79
+ dim,
80
+ kernel_size=2 * stride,
81
+ stride=stride,
82
+ padding=math.ceil(stride / 2),
83
+ ),
84
+ )
85
+
86
+ def forward(self, x):
87
+ return self.block(x)
88
+
89
+
90
+ class Encoder(nn.Module):
91
+ def __init__(
92
+ self,
93
+ d_model: int = 64,
94
+ strides: list = [2, 4, 8, 8],
95
+ d_latent: int = 64,
96
+ ):
97
+ super().__init__()
98
+ # Create first convolution
99
+ self.block = [WNConv1d(1, d_model, kernel_size=7, padding=3)]
100
+
101
+ # Create EncoderBlocks that double channels as they downsample by `stride`
102
+ for stride in strides:
103
+ d_model *= 2
104
+ self.block += [EncoderBlock(d_model, stride=stride)]
105
+
106
+ # Create last convolution
107
+ self.block += [
108
+ Snake1d(d_model),
109
+ WNConv1d(d_model, d_latent, kernel_size=3, padding=1),
110
+ ]
111
+
112
+ # Wrap black into nn.Sequential
113
+ self.block = nn.Sequential(*self.block)
114
+ self.enc_dim = d_model
115
+
116
+ def forward(self, x):
117
+ return self.block(x)
118
+
119
+
120
+ class DacAudioVAE(nn.Module):
121
+ def __init__(
122
+ self,
123
+ encoder_dim: int = 64,
124
+ encoder_rates: List[int] = [2, 4, 8, 8],
125
+ latent_dim: int = None,
126
+ decoder_dim: int = 1536,
127
+ decoder_rates: List[int] = [8, 8, 4, 2],
128
+ sample_rate: int = 44100,
129
+ vae_latent_channels: int = 64,
130
+ attn_proj: bool = False,
131
+ decoder_type: str = "bigvgan",
132
+ ):
133
+ super().__init__()
134
+
135
+ self.encoder_dim = encoder_dim
136
+ self.encoder_rates = encoder_rates
137
+ self.decoder_dim = decoder_dim
138
+ self.decoder_rates = decoder_rates
139
+ self.sample_rate = sample_rate
140
+ self.attn_proj = attn_proj
141
+ self.decoder_type = decoder_type
142
+
143
+ if latent_dim is None:
144
+ latent_dim = encoder_dim * (2 ** len(encoder_rates))
145
+
146
+ self.latent_dim = latent_dim
147
+
148
+ self.hop_length = np.prod(encoder_rates)
149
+ self.encoder = Encoder(encoder_dim, encoder_rates, latent_dim)
150
+
151
+ if latent_dim % vae_latent_channels == 0:
152
+ self.attn_proj_dim = vae_latent_channels
153
+ else:
154
+ # smallest power of two >= vae_latent_channels
155
+ self.attn_proj_dim = 2 ** int(np.ceil(np.log2(vae_latent_channels)))
156
+
157
+ self.mean_proj = nn.Conv1d(self.attn_proj_dim, vae_latent_channels, 1)
158
+ self.logs_proj = nn.Conv1d(self.attn_proj_dim, vae_latent_channels, 1)
159
+
160
+ self.dec_in_proj = nn.Conv1d(vae_latent_channels, latent_dim, 1)
161
+
162
+ if self.decoder_type == "bigvgan":
163
+ if sample_rate == 16000:
164
+ bigvgan_conf = {"resblock": "1",
165
+ "num_mels": latent_dim,
166
+ "upsample_rates": [5,5,2,2,2,2],
167
+ "upsample_kernel_sizes": [9,9,4,4,4,4],
168
+ "upsample_initial_channel": decoder_dim,
169
+ "resblock_kernel_sizes": [3,7,11],
170
+ "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]],
171
+ "use_tanh_at_final": False,
172
+ "use_bias_at_final": False,
173
+ "activation": "snakebeta",
174
+ "snake_logscale": True}
175
+ elif sample_rate == 32000:
176
+ bigvgan_conf = {"resblock": "1",
177
+ "num_mels": latent_dim,
178
+ "upsample_rates": [5,5,2,2,2,2,2],
179
+ "upsample_kernel_sizes": [9,9,4,4,4,4,4],
180
+ "upsample_initial_channel": decoder_dim,
181
+ "resblock_kernel_sizes": [3,7,11],
182
+ "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]],
183
+ "use_tanh_at_final": False,
184
+ "use_bias_at_final": False,
185
+ "activation": "snakebeta",
186
+ "snake_logscale": True}
187
+ else:
188
+ raise ValueError(f"Invalid sample_rate: {sample_rate}")
189
+
190
+ h = AttrDict(**bigvgan_conf)
191
+ self.decoder = BigVGAN(h)
192
+ else:
193
+ raise ValueError(f"Invalid decoder type: {self.decoder_type}")
194
+
195
+ if self.attn_proj:
196
+ self.pre_block = AttnProjection(latent_dim, self.attn_proj_dim, num_heads=8)
197
+
198
+ self.sample_rate = sample_rate
199
+ self.apply(init_weights)
200
+
201
+ def preprocess(self, audio_data, sample_rate):
202
+ if sample_rate is None:
203
+ sample_rate = self.sample_rate
204
+
205
+ length = audio_data.shape[-1]
206
+ right_pad = math.ceil(length / self.hop_length) * self.hop_length - length
207
+ audio_data = nn.functional.pad(audio_data, (0, right_pad))
208
+
209
+ return audio_data
210
+
211
+ def decode(self, z: torch.Tensor):
212
+ """Decode given latent codes and return audio data
213
+
214
+ Parameters
215
+ ----------
216
+ z : Tensor[B x D x T]
217
+ Continuous latent representation
218
+
219
+ Returns
220
+ -------
221
+ Tensor[B x 1 x length]
222
+ Decoded audio data.
223
+ """
224
+ z = self.dec_in_proj(z)
225
+ return self.decoder(z)
Ref2VA/audio_vae/dac_bigvgan.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2024 NVIDIA CORPORATION.
3
+ # Licensed under the MIT license.
4
+
5
+ # Adapted from https://github.com/jik876/hifi-gan under the MIT license.
6
+
7
+ from .dac_activations import SnakeBeta
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from torch.nn import Conv1d, ConvTranspose1d
12
+ from torch.nn.utils.parametrizations import weight_norm
13
+
14
+ from .dac_utils import init_weights, get_padding
15
+ from .dac_alias_free_act import Activation1d
16
+
17
+
18
+ class AttrDict(dict):
19
+ def __init__(self, *args, **kwargs):
20
+ super(AttrDict, self).__init__(*args, **kwargs)
21
+ self.__dict__ = self
22
+
23
+
24
+ class AMPBlock1(torch.nn.Module):
25
+ """
26
+ AMPBlock applies SnakeBeta activation functions with trainable parameters that control periodicity, defined for each layer.
27
+ AMPBlock1 has additional self.convs2 that contains additional Conv1d layers with a fixed dilation=1 followed by each layer in self.convs1
28
+
29
+ Args:
30
+ h (AttrDict): Hyperparameters.
31
+ channels (int): Number of convolution channels.
32
+ kernel_size (int): Size of the convolution kernel. Default is 3.
33
+ dilation (tuple): Dilation rates for the convolutions. Each dilation layer has two convolutions. Default is (1, 3, 5).
34
+ activation (str): Activation function type. Must be 'snakebeta'.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ h: AttrDict,
40
+ channels: int,
41
+ kernel_size: int = 3,
42
+ dilation: tuple = (1, 3, 5),
43
+ activation: str = None,
44
+ ):
45
+ super().__init__()
46
+
47
+ self.h = h
48
+
49
+ self.convs1 = nn.ModuleList(
50
+ [
51
+ weight_norm(
52
+ Conv1d(
53
+ channels,
54
+ channels,
55
+ kernel_size,
56
+ stride=1,
57
+ dilation=d,
58
+ padding=get_padding(kernel_size, d),
59
+ )
60
+ )
61
+ for d in dilation
62
+ ]
63
+ )
64
+ self.convs1.apply(init_weights)
65
+
66
+ self.convs2 = nn.ModuleList(
67
+ [
68
+ weight_norm(
69
+ Conv1d(
70
+ channels,
71
+ channels,
72
+ kernel_size,
73
+ stride=1,
74
+ dilation=1,
75
+ padding=get_padding(kernel_size, 1),
76
+ )
77
+ )
78
+ for _ in range(len(dilation))
79
+ ]
80
+ )
81
+ self.convs2.apply(init_weights)
82
+
83
+ self.num_layers = len(self.convs1) + len(self.convs2) # Total number of conv layers
84
+
85
+ if activation == "snakebeta":
86
+ self.activations = nn.ModuleList(
87
+ [
88
+ Activation1d(activation=SnakeBeta(channels, alpha_logscale=h.snake_logscale))
89
+ for _ in range(self.num_layers)
90
+ ]
91
+ )
92
+ else:
93
+ raise NotImplementedError(
94
+ "activation incorrectly specified. check the config file and look for 'activation'."
95
+ )
96
+
97
+ def forward(self, x):
98
+ acts1, acts2 = self.activations[::2], self.activations[1::2]
99
+ for c1, c2, a1, a2 in zip(self.convs1, self.convs2, acts1, acts2):
100
+ xt = a1(x)
101
+ xt = c1(xt)
102
+ xt = a2(xt)
103
+ xt = c2(xt)
104
+ x = xt + x
105
+
106
+ return x
107
+
108
+
109
+ class BigVGAN(torch.nn.Module):
110
+ """
111
+ BigVGAN is a neural vocoder model that applies anti-aliased periodic activation for residual blocks (resblocks).
112
+
113
+ Args:
114
+ h (AttrDict): Hyperparameters.
115
+ """
116
+
117
+ def __init__(self, h: AttrDict):
118
+ super().__init__()
119
+ self.h = h
120
+
121
+ self.num_kernels = len(h.resblock_kernel_sizes)
122
+ self.num_upsamples = len(h.upsample_rates)
123
+
124
+ # Pre-conv
125
+ self.conv_pre = weight_norm(Conv1d(h.num_mels, h.upsample_initial_channel, 7, 1, padding=3))
126
+
127
+ # Define which AMPBlock to use. BigVGAN uses AMPBlock1 as default
128
+ if h.resblock == "1":
129
+ resblock_class = AMPBlock1
130
+ else:
131
+ raise ValueError(f"Incorrect resblock class specified in hyperparameters. Got {h.resblock}")
132
+
133
+ # Transposed conv-based upsamplers. does not apply anti-aliasing
134
+ self.ups = nn.ModuleList()
135
+ for i, (u, k) in enumerate(zip(h.upsample_rates, h.upsample_kernel_sizes)):
136
+ self.ups.append(
137
+ nn.ModuleList(
138
+ [
139
+ weight_norm(
140
+ ConvTranspose1d(
141
+ h.upsample_initial_channel // (2**i),
142
+ h.upsample_initial_channel // (2 ** (i + 1)),
143
+ k,
144
+ u,
145
+ padding=(k - u) // 2,
146
+ )
147
+ )
148
+ ]
149
+ )
150
+ )
151
+
152
+ # Residual blocks using anti-aliased multi-periodicity composition modules (AMP)
153
+ self.resblocks = nn.ModuleList()
154
+ for i in range(len(self.ups)):
155
+ ch = h.upsample_initial_channel // (2 ** (i + 1))
156
+ for j, (k, d) in enumerate(zip(h.resblock_kernel_sizes, h.resblock_dilation_sizes)):
157
+ self.resblocks.append(resblock_class(h, ch, k, d, activation=h.activation))
158
+
159
+ # Post-conv
160
+ if h.activation != "snakebeta":
161
+ raise NotImplementedError(
162
+ "activation incorrectly specified. check the config file and look for 'activation'."
163
+ )
164
+ activation_post = SnakeBeta(ch, alpha_logscale=h.snake_logscale)
165
+
166
+ self.activation_post = Activation1d(activation=activation_post)
167
+
168
+ # Whether to use bias for the final conv_post. Default to True for backward compatibility
169
+ self.use_bias_at_final = h.get("use_bias_at_final", True)
170
+ self.conv_post = weight_norm(Conv1d(ch, 1, 7, 1, padding=3, bias=self.use_bias_at_final))
171
+
172
+ # Weight initialization
173
+ for i in range(len(self.ups)):
174
+ self.ups[i].apply(init_weights)
175
+ self.conv_post.apply(init_weights)
176
+
177
+ # Final tanh activation. Defaults to True for backward compatibility
178
+ self.use_tanh_at_final = h.get("use_tanh_at_final", True)
179
+
180
+ def forward(self, x):
181
+ # Pre-conv
182
+ x = self.conv_pre(x)
183
+
184
+ for i in range(self.num_upsamples):
185
+ # Upsampling
186
+ for i_up in range(len(self.ups[i])):
187
+ x = self.ups[i][i_up](x)
188
+ # AMP blocks
189
+ xs = None
190
+ for j in range(self.num_kernels):
191
+ if xs is None:
192
+ xs = self.resblocks[i * self.num_kernels + j](x)
193
+ else:
194
+ xs += self.resblocks[i * self.num_kernels + j](x)
195
+ x = xs / self.num_kernels
196
+
197
+ # Post-conv
198
+ x = self.activation_post(x)
199
+ x = self.conv_post(x)
200
+ # Final tanh activation
201
+ if self.use_tanh_at_final:
202
+ x = torch.tanh(x)
203
+ else:
204
+ x = torch.clamp(x, min=-1.0, max=1.0) # Bound the output to [-1, 1]
205
+
206
+ return x
Ref2VA/audio_vae/dac_utils.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+ # Adapted from https://github.com/jik876/hifi-gan under the MIT license.
3
+
4
+
5
+ def init_weights(m, mean=0.0, std=0.01):
6
+ classname = m.__class__.__name__
7
+ if classname.find("Conv") != -1:
8
+ m.weight.data.normal_(mean, std)
9
+
10
+
11
+ def get_padding(kernel_size, dilation=1):
12
+ return int((kernel_size * dilation - dilation) / 2)
Ref2VA/audio_vae/metadata.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "kwargs": {
4
+ "attn_proj": true,
5
+ "decoder_dim": 1024,
6
+ "decoder_rates": [
7
+ 5,
8
+ 5,
9
+ 2,
10
+ 2,
11
+ 2,
12
+ 2,
13
+ 2
14
+ ],
15
+ "decoder_type": "bigvgan",
16
+ "encoder_dim": 64,
17
+ "encoder_rates": [
18
+ 2,
19
+ 4,
20
+ 4,
21
+ 5,
22
+ 5
23
+ ],
24
+ "latent_dim": 2048,
25
+ "sample_rate": 32000,
26
+ "vae_latent_channels": 32
27
+ }
28
+ }
29
+ }
Ref2VA/audio_vae/minimax_h3_audio_vae.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Remote entry: self-contained MiniMax H3 audio VAE (DAC-lineage encoder + BigVGAN decoder).
3
+ # Loaded via config.json:auto_map with trust_remote_code; weights are safetensors-only.
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ from pathlib import Path
8
+
9
+ import torch.nn as nn
10
+
11
+ # --- dependency manifest ---
12
+ # diffusers' dynamic-module loader only copies ONE level of relative
13
+ # imports into its cache; list every bundle module here so all files
14
+ # are copied, letting their own second-level imports resolve.
15
+ from .dac_activations import SnakeBeta as _dep_dac_activations # noqa: F401
16
+ from .dac_alias_free_act import Activation1d as _dep_dac_alias_free_act # noqa: F401
17
+ from .dac_alias_free_filter import kaiser_sinc_filter1d as _dep_dac_alias_free_filter # noqa: F401
18
+ from .dac_alias_free_resample import UpSample1d as _dep_dac_alias_free_resample # noqa: F401
19
+ from .dac_attn_proj import GeGluMlp as _dep_dac_attn_proj # noqa: F401
20
+ from .dac_bigvgan import AttrDict as _dep_dac_bigvgan # noqa: F401
21
+ from .dac_audio_vae import AttrDict as _dep_dac_audio_vae # noqa: F401
22
+ from .dac_utils import init_weights as _dep_dac_utils # noqa: F401
23
+ # --- end dependency manifest ---
24
+ from safetensors.torch import load_file
25
+
26
+ from .dac_audio_vae import DacAudioVAE
27
+
28
+
29
+ def _load_yaml(path: Path) -> dict:
30
+ try:
31
+ import yaml
32
+ except ImportError as exc:
33
+ raise ImportError("MiniMax H3 audio VAE requires PyYAML.") from exc
34
+ with path.open("r", encoding="utf-8") as f:
35
+ return yaml.safe_load(f)
36
+
37
+
38
+ class MiniMaxH3AudioVAE(nn.Module):
39
+ def __init__(self, model: nn.Module) -> None:
40
+ super().__init__()
41
+ self.model = model
42
+
43
+ @classmethod
44
+ def from_pretrained(cls, pretrained_model_name_or_path: str, **kwargs):
45
+ component_dir = Path(pretrained_model_name_or_path)
46
+ with (component_dir / "config.json").open("r", encoding="utf-8") as f:
47
+ config = json.load(f)
48
+
49
+ audio_config = _load_yaml(component_dir / config["source_config_path"])
50
+ if "source_safetensors_path" not in config:
51
+ raise KeyError(
52
+ "source_safetensors_path is required; pickle checkpoints are not supported"
53
+ )
54
+ if "source_metadata_path" not in config:
55
+ raise KeyError(
56
+ "source_metadata_path is required when source_safetensors_path is set"
57
+ )
58
+ state_dict = load_file(
59
+ component_dir / config["source_safetensors_path"], device="cpu"
60
+ )
61
+ with (component_dir / config["source_metadata_path"]).open(
62
+ "r", encoding="utf-8"
63
+ ) as f:
64
+ metadata_doc = json.load(f)
65
+ metadata = metadata_doc["metadata"]["kwargs"]
66
+
67
+ model = DacAudioVAE(
68
+ encoder_rates=metadata["encoder_rates"],
69
+ decoder_rates=metadata["decoder_rates"],
70
+ attn_proj=metadata["attn_proj"],
71
+ decoder_type=metadata["decoder_type"],
72
+ decoder_dim=audio_config["model_config"]["decoder_dim"],
73
+ vae_latent_channels=audio_config["model_config"]["vae_latent_channels"],
74
+ sample_rate=metadata["sample_rate"],
75
+ )
76
+ model.load_state_dict(state_dict, strict=True)
77
+ return cls(model.eval())
78
+
79
+ def decode(self, *args, **kwargs):
80
+ return self.model.decode(*args, **kwargs)
81
+
82
+ def __getattr__(self, name: str):
83
+ try:
84
+ return super().__getattr__(name)
85
+ except AttributeError:
86
+ return getattr(self.model, name)
Ref2VA/audio_vae/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:37dddc2f3e6d5d5139d823d5ea283bbf304dadcb885b1ccda818aa13dade5ea2
3
+ size 605429308
Ref2VA/processor/chat_template.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].role == 'system' %}\n {%- if messages[0].content is string %}\n {{- messages[0].content }}\n {%- else %}\n {%- for content in messages[0].content %}\n {%- if 'text' in content %}\n {{- content.text }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {{- '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].content is string %}\n {{- messages[0].content }}\n {%- else %}\n {%- for content in messages[0].content %}\n {%- if 'text' in content %}\n {{- content.text }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- for message in messages %}\n {%- if message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' }}\n {%- if message.content is string %}\n {{- message.content }}\n {%- else %}\n {%- for content in message.content %}\n {%- if content.type == 'image' or 'image' in content or 'image_url' in content %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%}\n <|vision_start|><|image_pad|><|vision_end|>\n {%- elif content.type == 'video' or 'video' in content %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%}\n <|vision_start|><|video_pad|><|vision_end|>\n {%- elif 'text' in content %}\n {{- content.text }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role + '\\n' }}\n {%- if message.content is string %}\n {{- message.content }}\n {%- else %}\n {%- for content_item in message.content %}\n {%- if 'text' in content_item %}\n {{- content_item.text }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and message.content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {%- if tool_call.arguments is string %}\n {{- tool_call.arguments }}\n {%- else %}\n {{- tool_call.arguments | tojson }}\n {%- endif %}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {%- if message.content is string %}\n {{- message.content }}\n {%- else %}\n {%- for content in message.content %}\n {%- if content.type == 'image' or 'image' in content or 'image_url' in content %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%}\n <|vision_start|><|image_pad|><|vision_end|>\n {%- elif content.type == 'video' or 'video' in content %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%}\n <|vision_start|><|video_pad|><|vision_end|>\n {%- elif 'text' in content %}\n {{- content.text }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n"
3
+ }
Ref2VA/processor/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
Ref2VA/processor/preprocessor_config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "size": {
3
+ "longest_edge": 16777216,
4
+ "shortest_edge": 65536
5
+ },
6
+ "patch_size": 16,
7
+ "temporal_patch_size": 2,
8
+ "merge_size": 2,
9
+ "image_mean": [
10
+ 0.5,
11
+ 0.5,
12
+ 0.5
13
+ ],
14
+ "image_std": [
15
+ 0.5,
16
+ 0.5,
17
+ 0.5
18
+ ],
19
+ "processor_class": "Qwen3VLProcessor",
20
+ "image_processor_type": "Qwen2VLImageProcessorFast"
21
+ }
Ref2VA/processor/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
Ref2VA/processor/tokenizer_config.json ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ },
181
+ "151665": {
182
+ "content": "<tool_response>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": false
188
+ },
189
+ "151666": {
190
+ "content": "</tool_response>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": false
196
+ },
197
+ "151667": {
198
+ "content": "<think>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": false
204
+ },
205
+ "151668": {
206
+ "content": "</think>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": false
212
+ }
213
+ },
214
+ "additional_special_tokens": [
215
+ "<|im_start|>",
216
+ "<|im_end|>",
217
+ "<|object_ref_start|>",
218
+ "<|object_ref_end|>",
219
+ "<|box_start|>",
220
+ "<|box_end|>",
221
+ "<|quad_start|>",
222
+ "<|quad_end|>",
223
+ "<|vision_start|>",
224
+ "<|vision_end|>",
225
+ "<|vision_pad|>",
226
+ "<|image_pad|>",
227
+ "<|video_pad|>",
228
+ "<d>",
229
+ "</d>",
230
+ "<|cutoff|>",
231
+ "<|lyrics_start|>",
232
+ "<|lyrics_end|>",
233
+ "<|caption_start|>",
234
+ "<|caption_end|>"
235
+ ],
236
+ "bos_token": null,
237
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].role == 'system' %}\n {%- if messages[0].content is string %}\n {{- messages[0].content }}\n {%- else %}\n {%- for content in messages[0].content %}\n {%- if 'text' in content %}\n {{- content.text }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {{- '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].content is string %}\n {{- messages[0].content }}\n {%- else %}\n {%- for content in messages[0].content %}\n {%- if 'text' in content %}\n {{- content.text }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- for message in messages %}\n {%- if message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' }}\n {%- if message.content is string %}\n {{- message.content }}\n {%- else %}\n {%- for content in message.content %}\n {%- if content.type == 'image' or 'image' in content or 'image_url' in content %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%}\n <|vision_start|><|image_pad|><|vision_end|>\n {%- elif content.type == 'video' or 'video' in content %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%}\n <|vision_start|><|video_pad|><|vision_end|>\n {%- elif 'text' in content %}\n {{- content.text }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role + '\\n' }}\n {%- if message.content is string %}\n {{- message.content }}\n {%- else %}\n {%- for content_item in message.content %}\n {%- if 'text' in content_item %}\n {{- content_item.text }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and message.content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {%- if tool_call.arguments is string %}\n {{- tool_call.arguments }}\n {%- else %}\n {{- tool_call.arguments | tojson }}\n {%- endif %}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {%- if message.content is string %}\n {{- message.content }}\n {%- else %}\n {%- for content in message.content %}\n {%- if content.type == 'image' or 'image' in content or 'image_url' in content %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%}\n <|vision_start|><|image_pad|><|vision_end|>\n {%- elif content.type == 'video' or 'video' in content %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%}\n <|vision_start|><|video_pad|><|vision_end|>\n {%- elif 'text' in content %}\n {{- content.text }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n",
238
+ "clean_up_tokenization_spaces": false,
239
+ "eos_token": "<|im_end|>",
240
+ "errors": "replace",
241
+ "model_max_length": 262144,
242
+ "pad_token": "<|endoftext|>",
243
+ "split_special_tokens": false,
244
+ "tokenizer_class": "Qwen2Tokenizer",
245
+ "unk_token": null
246
+ }
Ref2VA/processor/video_preprocessor_config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "size": {
3
+ "longest_edge": 25165824,
4
+ "shortest_edge": 4096
5
+ },
6
+ "patch_size": 16,
7
+ "temporal_patch_size": 2,
8
+ "merge_size": 2,
9
+ "image_mean": [
10
+ 0.5,
11
+ 0.5,
12
+ 0.5
13
+ ],
14
+ "image_std": [
15
+ 0.5,
16
+ 0.5,
17
+ 0.5
18
+ ],
19
+ "processor_class": "Qwen3VLProcessor",
20
+ "video_processor_type": "Qwen3VLVideoProcessor"
21
+ }
Ref2VA/processor/vocab.json ADDED
The diff for this file is too large to render. See raw diff