levzalt Localsong commited on
Commit
9781faf
·
0 Parent(s):

Duplicate from Localsong/Localsong

Browse files

Co-authored-by: Localsong <Localsong@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz 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
LICENSE ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ -------------------------------------------------------------------------------
24
+
25
+ Third-party code
26
+
27
+ same_l_decoder.py is adapted from Stability AI's stable-audio-3
28
+ (https://github.com/Stability-AI/stable-audio-3), used under the MIT License:
29
+
30
+ MIT License
31
+
32
+ Copyright (c) 2026 Stability AI
33
+
34
+ Permission is hereby granted, free of charge, to any person obtaining a copy
35
+ of this software and associated documentation files (the "Software"), to deal
36
+ in the Software without restriction, including without limitation the rights
37
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
38
+ copies of the Software, and to permit persons to whom the Software is
39
+ furnished to do so, subject to the following conditions:
40
+
41
+ The above copyright notice and this permission notice shall be included in all
42
+ copies or substantial portions of the Software.
43
+
44
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
45
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
46
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
47
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
48
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
49
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
50
+ SOFTWARE.
51
+
52
+ Third-party weights
53
+
54
+ The SAME-L autoencoder weights that same_l_decoder.py loads are released
55
+ separately by Stability AI under the Stable Audio Community License
56
+ (https://stability.ai/license).
57
+
58
+ This Stability AI Model is licensed under the Stability AI Community License, Copyright © Stability AI Ltd. All Rights Reserved
README.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ ---
4
+ # Audio DiT
5
+
6
+ Tag-conditioned music generation focused on instrumental game and anime songs. Choose 1-8 tags (recommend to start with 1). Generates 95s songs.
7
+ Set a seed to reproduce a generation, or leave it at `-1` for a random seed.
8
+
9
+ ## Run it
10
+
11
+ Needs [uv](https://docs.astral.sh/uv/). CUDA, MPS or CPU.
12
+
13
+ ```bash
14
+ hf download Localsong/Localsong --local-dir Localsong
15
+ uv run webui.py # http://127.0.0.1:7860
16
+ ```
17
+
18
+ ## Architecture
19
+
20
+ ```
21
+ tags ──► AudioDiT ──► 256×1024 latents ──► SAME-L decoder ──► 95 s of stereo audio
22
+ 0.84B params
23
+ ```
24
+
25
+ **Latents.** [SAME-L](https://huggingface.co/stabilityai/SAME-L) autoencoder by Stability AI.
26
+
27
+ **Denoiser.** `audio_dit.py` is a 1-D latent transformer DiT.
28
+ RMSNorm and QK-RMSNorm, RoPE, SwiGLU
29
+ Timestep conditioning is adaLN-single (PixArt)
30
+ offset. Tags condition via cross-attention.
31
+
32
+ **Sparse-dense fusion** ([SPRINT](https://arxiv.org/abs/2510.21986)). The blocks
33
+ are split into a dense 2-block encoder, a 20-block middle stack, and a dense
34
+ 2-block decoder. The encoder output is concatenated with the middle output and
35
+ projected back down before the decoder:
36
+
37
+ ```
38
+ frames ──► encoder ──┬─────────────────────────► f ──┐
39
+ └─► middle (20 blocks) ──► g ──► linear([f;g]) ──► decoder ──► velocity
40
+ ```
41
+
42
+ Training ran the middle stack on a random 25 % of frames and sometimes dropped
43
+ it entirely, which makes the shallow encoder→fusion→decoder route a usable weak
44
+ model on its own. Inference runs the middle stack on every frame
45
+ (`AudioDiT.forward`) and keeps the shallow route as the guidance branch
46
+ (`AudioDiT.shallow`).
47
+
48
+ **Sampling.** Rectified flow: v-prediction, 50 steps Euler shift=2
49
+ Guidance alternates between normal CFG and the shallow-path PDG.
50
+
51
+ ## License
52
+
53
+ MIT, see [LICENSE](LICENSE).
54
+
55
+ `same_l_decoder.py` is adapted from Stability AI's
56
+ [stable-audio-3](https://github.com/Stability-AI/stable-audio-3) (MIT). The
57
+ SAME-L weights it loads are released by Stability AI under the Stable Audio
58
+ Community License; commercial use of them is subject to
59
+ <https://stability.ai/license>.
60
+
61
+ The model also builds on SPRINT ([2510.21986](https://arxiv.org/abs/2510.21986)),
62
+ PixArt-α ([2310.00426](https://arxiv.org/abs/2310.00426)),
63
+ DiT ([2212.09748](https://arxiv.org/abs/2212.09748)) and
64
+ rectified flow ([2209.03003](https://arxiv.org/abs/2209.03003)).
audio_dit.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tag-conditioned diffusion transformer over SAME-L music latents (0.84B params)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from pathlib import Path
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from safetensors.torch import load_file
12
+
13
+ WEIGHTS = Path(__file__).parent / "audio_dit.safetensors"
14
+
15
+ CHANNELS = 256 # SAME-L latent channels
16
+ FRAMES = 1024 # latent frames per sample, at 10.77 frames/second
17
+ DIM = 1536
18
+ HEADS = 24
19
+ HEAD_DIM = 64
20
+ MLP_HIDDEN = 4096
21
+ NUM_TAGS = 1470 # vocabulary rows; index 0 is padding
22
+ MAX_TAGS = 8
23
+ ROPE_THETA = 10000.0
24
+
25
+ # SPRINT sparse-dense fusion: a dense encoder, a deep middle stack, a dense
26
+ # decoder. Encoder and decoder blocks cross-attend to the tags, middle blocks
27
+ # every second block. Training subsampled the middle stack; inference runs it on
28
+ # every frame.
29
+ ENCODER_BLOCKS = 2
30
+ MIDDLE_BLOCKS = 20
31
+ DECODER_BLOCKS = 2
32
+
33
+
34
+ def rms_norm(x: torch.Tensor) -> torch.Tensor:
35
+ return F.rms_norm(x.float(), (x.shape[-1],), eps=1e-6).to(x.dtype)
36
+
37
+
38
+ class RMSNorm(nn.Module):
39
+ def __init__(self, dim: int):
40
+ super().__init__()
41
+ self.weight = nn.Parameter(torch.ones(dim))
42
+
43
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
44
+ return rms_norm(x) * self.weight
45
+
46
+
47
+ def rope_tables() -> tuple[torch.Tensor, torch.Tensor]:
48
+ freqs = torch.outer(
49
+ torch.arange(FRAMES).float(),
50
+ 1.0 / (ROPE_THETA ** (torch.arange(0, HEAD_DIM, 2).float() / HEAD_DIM)),
51
+ )
52
+ return freqs.cos()[None, None], freqs.sin()[None, None]
53
+
54
+
55
+ def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
56
+ x1, x2 = x.float().chunk(2, dim=-1)
57
+ return torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1).to(x.dtype)
58
+
59
+
60
+ class SelfAttention(nn.Module):
61
+ def __init__(self):
62
+ super().__init__()
63
+ self.qkv_x = nn.Linear(DIM, 3 * DIM, bias=False)
64
+ self.q_norm = RMSNorm(HEAD_DIM)
65
+ self.k_norm = RMSNorm(HEAD_DIM)
66
+ self.proj = nn.Linear(DIM, DIM, bias=False)
67
+
68
+ def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
69
+ B, S, _ = x.shape
70
+ q, k, v = self.qkv_x(x).view(B, S, 3, HEADS, HEAD_DIM).permute(2, 0, 3, 1, 4)
71
+ q = apply_rope(self.q_norm(q), cos, sin)
72
+ k = apply_rope(self.k_norm(k), cos, sin)
73
+ out = F.scaled_dot_product_attention(q, k, v)
74
+ return self.proj(out.transpose(1, 2).reshape(B, S, DIM))
75
+
76
+
77
+ class CrossAttention(nn.Module):
78
+ def __init__(self):
79
+ super().__init__()
80
+ self.q_y = nn.Linear(DIM, DIM, bias=False)
81
+ self.kv_y = nn.Linear(DIM, 2 * DIM, bias=False)
82
+ self.q_norm = RMSNorm(HEAD_DIM)
83
+ self.k_norm = RMSNorm(HEAD_DIM)
84
+ self.proj_y = nn.Linear(DIM, DIM, bias=False)
85
+
86
+ def forward(self, x: torch.Tensor, y: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
87
+ B, S, _ = x.shape
88
+ q = self.q_norm(self.q_y(x).view(B, S, HEADS, HEAD_DIM).transpose(1, 2))
89
+ k, v = self.kv_y(y).view(B, MAX_TAGS, 2, HEADS, HEAD_DIM).permute(2, 0, 3, 1, 4)
90
+ out = F.scaled_dot_product_attention(q, self.k_norm(k), v,
91
+ attn_mask=mask[:, None, None, :])
92
+ return self.proj_y(out.transpose(1, 2).reshape(B, S, DIM))
93
+
94
+
95
+ class SwiGLU(nn.Module):
96
+ def __init__(self):
97
+ super().__init__()
98
+ self.w12 = nn.Linear(DIM, 2 * MLP_HIDDEN, bias=False)
99
+ self.w3 = nn.Linear(MLP_HIDDEN, DIM, bias=False)
100
+
101
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
102
+ gate, up = self.w12(x).chunk(2, dim=-1)
103
+ return self.w3(F.silu(gate) * up)
104
+
105
+
106
+ class Block(nn.Module):
107
+ """adaLN-single: shared timestep modulation plus a learned per-block offset."""
108
+
109
+ def __init__(self):
110
+ super().__init__()
111
+ self.attn = SelfAttention()
112
+ self.mlp = SwiGLU()
113
+ self.adaLN_offset = nn.Parameter(torch.zeros(6 * DIM))
114
+
115
+ def forward(self, x, mod, y, mask, cos, sin):
116
+ shift1, scale1, gate1, shift2, scale2, gate2 = (mod + self.adaLN_offset).chunk(6, -1)
117
+ x = x + gate1 * self.attn(rms_norm(x) * (1 + scale1) + shift1, cos, sin)
118
+ return x + gate2 * self.mlp(rms_norm(x) * (1 + scale2) + shift2)
119
+
120
+
121
+ class CrossBlock(Block):
122
+ def __init__(self):
123
+ super().__init__()
124
+ self.cross = CrossAttention()
125
+ self.cross_gate = nn.Parameter(torch.zeros(DIM))
126
+
127
+ def forward(self, x, mod, y, mask, cos, sin):
128
+ shift1, scale1, gate1, shift2, scale2, gate2 = (mod + self.adaLN_offset).chunk(6, -1)
129
+ x = x + gate1 * self.attn(rms_norm(x) * (1 + scale1) + shift1, cos, sin)
130
+ x = x + self.cross_gate * self.cross(rms_norm(x), y, mask)
131
+ return x + gate2 * self.mlp(rms_norm(x) * (1 + scale2) + shift2)
132
+
133
+
134
+ class Timestep(nn.Module):
135
+ def __init__(self):
136
+ super().__init__()
137
+ self.mlp = nn.Sequential(nn.Linear(256, DIM), nn.SiLU(), nn.Linear(DIM, DIM))
138
+
139
+ def forward(self, t: float, batch: int, device) -> torch.Tensor:
140
+ freqs = torch.exp(-math.log(10000.0) * torch.arange(128, device=device) / 128)
141
+ args = t * 1000.0 * freqs[None]
142
+ return self.mlp(torch.cat([args.cos(), args.sin()], dim=-1)).expand(batch, DIM)
143
+
144
+
145
+ class FinalLayer(nn.Module):
146
+ def __init__(self):
147
+ super().__init__()
148
+ self.adaLN_modulation = nn.Linear(DIM, 2 * DIM)
149
+ self.linear = nn.Linear(DIM, CHANNELS)
150
+
151
+ def forward(self, x: torch.Tensor, c: torch.Tensor) -> torch.Tensor:
152
+ shift, scale = self.adaLN_modulation(F.silu(c)).unsqueeze(1).chunk(2, dim=-1)
153
+ return self.linear(rms_norm(x) * (1 + scale) + shift)
154
+
155
+
156
+ class AudioDiT(nn.Module):
157
+ def __init__(self):
158
+ super().__init__()
159
+ self.x_embedder = nn.Linear(CHANNELS, DIM)
160
+ self.t_embedder = Timestep()
161
+ self.tag_embedding = nn.Embedding(NUM_TAGS, DIM, padding_idx=0)
162
+ self.tag_norm = RMSNorm(DIM)
163
+ self.null_tag = nn.Parameter(torch.zeros(DIM))
164
+ self.mask_token = nn.Parameter(torch.zeros(DIM))
165
+ self.fusion_proj = nn.Linear(2 * DIM, DIM)
166
+ self.adaLN_shared = nn.Linear(DIM, 6 * DIM)
167
+ self.encoder = nn.ModuleList(CrossBlock() for _ in range(ENCODER_BLOCKS))
168
+ self.middle = nn.ModuleList(
169
+ (CrossBlock if i % 2 == 0 else Block)() for i in range(MIDDLE_BLOCKS))
170
+ self.decoder = nn.ModuleList(CrossBlock() for _ in range(DECODER_BLOCKS))
171
+ self.final_layer = FinalLayer()
172
+ cos, sin = rope_tables()
173
+ self.register_buffer("cos", cos, persistent=False)
174
+ self.register_buffer("sin", sin, persistent=False)
175
+
176
+ def _condition(self, t: float, tags: torch.Tensor):
177
+ y = self.tag_norm(self.tag_embedding(tags))
178
+ valid = tags != 0
179
+ # An all-padding row is unconditional: it attends to the learned null tag.
180
+ empty = ~valid.any(dim=1)
181
+ y = torch.where(empty[:, None, None], self.tag_norm(self.null_tag).expand_as(y), y)
182
+ mask = valid.clone()
183
+ mask[:, 0] |= empty
184
+ c = self.t_embedder(t, tags.shape[0], tags.device)
185
+ return c, self.adaLN_shared(F.silu(c)).unsqueeze(1), y, mask
186
+
187
+ def _run(self, blocks, x, mod, y, mask):
188
+ for block in blocks:
189
+ x = block(x, mod, y, mask, self.cos, self.sin)
190
+ return x
191
+
192
+ def _fuse(self, f, g, c, mod, y, mask):
193
+ h = self.fusion_proj(torch.cat([f, g], dim=-1))
194
+ return self.final_layer(self._run(self.decoder, h, mod, y, mask), c).transpose(1, 2)
195
+
196
+ def forward(self, x: torch.Tensor, t: float, tags: torch.Tensor) -> torch.Tensor:
197
+ """Velocity at (x, t), for latents (B, 256, 1024) and tag indices (B, 8)."""
198
+ c, mod, y, mask = self._condition(t, tags)
199
+ f = self._run(self.encoder, self.x_embedder(x.transpose(1, 2)), mod, y, mask)
200
+ return self._fuse(f, self._run(self.middle, f, mod, y, mask), c, mod, y, mask)
201
+
202
+ def shallow(self, x: torch.Tensor, t: float, tags: torch.Tensor) -> torch.Tensor:
203
+ """Path-drop branch: the middle stack is replaced by [MASK] tokens."""
204
+ c, mod, y, mask = self._condition(t, tags)
205
+ f = self._run(self.encoder, self.x_embedder(x.transpose(1, 2)), mod, y, mask)
206
+ return self._fuse(f, self.mask_token.expand_as(f), c, mod, y, mask)
207
+
208
+
209
+ def load_model(device: str = "cuda") -> tuple[AudioDiT, torch.Tensor, torch.Tensor]:
210
+ """The model plus the per-channel mean/std the training latents were scaled by."""
211
+ state = load_file(WEIGHTS, device=device)
212
+ mean = state.pop("latent_mean").view(1, CHANNELS, 1)
213
+ std = state.pop("latent_std").view(1, CHANNELS, 1)
214
+ model = AudioDiT()
215
+ model.load_state_dict(state)
216
+ return model.to(device).eval().requires_grad_(False), mean, std
audio_dit.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:68d4d5c1ccb9501905a32f9d6364460eb7de4555af7500354e9ce98414915197
3
+ size 3365063088
pyproject.toml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "audio-dit"
3
+ version = "0.1.0"
4
+ description = "Instrumental music generation."
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ dependencies = [
8
+ "gradio>=6.2.0",
9
+ "numpy>=2.0",
10
+ "safetensors>=0.7.0",
11
+ "torch>=2.9.1",
12
+ ]
13
+
14
+ [tool.uv.sources]
15
+ torch = [
16
+ { index = "pytorch-cu130", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },
17
+ ]
18
+
19
+ [[tool.uv.index]]
20
+ name = "pytorch-cu130"
21
+ url = "https://download.pytorch.org/whl/cu130"
22
+ explicit = true
same_l_decoder.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from Stability AI's stable-audio-3 (MIT License). See LICENSE.
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+ from safetensors.torch import load_file
11
+
12
+ WEIGHTS = Path(__file__).parent / "samel" / "model.safetensors"
13
+
14
+ SAMPLE_RATE = 44100
15
+ LATENT_DIM = 256
16
+ DIM = 1536
17
+ DEPTH = 12
18
+ HEADS = 24
19
+ HEAD_DIM = 64
20
+ ROPE_DIM = 32
21
+ FF_HIDDEN = 3 * DIM
22
+ SINUSOIDAL_FROM = 5
23
+ PATCH = 256
24
+ STRIDE = 16
25
+ GROUP = STRIDE + 1
26
+ WINDOW = GROUP
27
+
28
+ CHUNK = 128
29
+ OVERLAP = 32
30
+ SEQ = CHUNK * GROUP
31
+ SAMPLES_PER_FRAME = PATCH * STRIDE
32
+ MASK_NOISE = 0.1
33
+ LATENT_NOISE = 1e-3
34
+
35
+
36
+ class DynamicTanh(nn.Module):
37
+ def __init__(self, dim: int):
38
+ super().__init__()
39
+ self.alpha = nn.Parameter(torch.ones(1))
40
+ self.gamma = nn.Parameter(torch.ones(dim))
41
+ self.beta = nn.Parameter(torch.zeros(dim))
42
+
43
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
44
+ return self.gamma * F.tanh(self.alpha * x) + self.beta
45
+
46
+
47
+ def apply_rope(t: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
48
+ rot, keep = t[..., :ROPE_DIM], t[..., ROPE_DIM:]
49
+ x1, x2 = rot.chunk(2, dim=-1)
50
+ rotated = torch.cat([-x2, x1], dim=-1)
51
+ return torch.cat([rot * freqs.cos() + rotated * freqs.sin(), keep], dim=-1)
52
+
53
+
54
+ class Attention(nn.Module):
55
+ """Differential attention: two attention maps per head, subtracted."""
56
+
57
+ def __init__(self):
58
+ super().__init__()
59
+ self.to_qkv = nn.Linear(DIM, 5 * DIM, bias=False)
60
+ self.to_out = nn.Linear(DIM, DIM, bias=False)
61
+ self.q_norm = DynamicTanh(HEAD_DIM)
62
+ self.k_norm = DynamicTanh(HEAD_DIM)
63
+
64
+ def forward(self, x: torch.Tensor, freqs: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
65
+ B, N, _ = x.shape
66
+ q, k, v, q_diff, k_diff = (
67
+ self.to_qkv(x).view(B, N, 5, HEADS, HEAD_DIM).permute(2, 0, 3, 1, 4))
68
+ q, q_diff = apply_rope(self.q_norm(q).float(), freqs), apply_rope(
69
+ self.q_norm(q_diff).float(), freqs)
70
+ k, k_diff = apply_rope(self.k_norm(k).float(), freqs), apply_rope(
71
+ self.k_norm(k_diff).float(), freqs)
72
+ out = F.scaled_dot_product_attention(q.to(v.dtype), k.to(v.dtype), v, attn_mask=mask)
73
+ out = out - F.scaled_dot_product_attention(
74
+ q_diff.to(v.dtype), k_diff.to(v.dtype), v, attn_mask=mask)
75
+ return self.to_out(out.transpose(1, 2).reshape(B, N, DIM))
76
+
77
+
78
+ class Sin(nn.Module):
79
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
80
+ return torch.sin(torch.pi * x)
81
+
82
+
83
+ class GatedProjection(nn.Module):
84
+ def __init__(self, activation: nn.Module):
85
+ super().__init__()
86
+ self.proj = nn.Linear(DIM, 2 * FF_HIDDEN)
87
+ self.act = activation
88
+
89
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
90
+ value, gate = self.proj(x).chunk(2, dim=-1)
91
+ return value * self.act(gate)
92
+
93
+
94
+ class FeedForward(nn.Module):
95
+ def __init__(self, activation: nn.Module):
96
+ super().__init__()
97
+
98
+ self.ff = nn.Sequential(
99
+ GatedProjection(activation), nn.Identity(), nn.Linear(FF_HIDDEN, DIM))
100
+
101
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
102
+ return self.ff(x)
103
+
104
+
105
+ class Block(nn.Module):
106
+ def __init__(self, sinusoidal: bool):
107
+ super().__init__()
108
+ self.pre_norm = DynamicTanh(DIM)
109
+ self.self_attn = Attention()
110
+ self.ff_norm = DynamicTanh(DIM)
111
+ self.ff = FeedForward(Sin() if sinusoidal else nn.SiLU())
112
+
113
+ def forward(self, x: torch.Tensor, freqs: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
114
+ x = x + self.self_attn(self.pre_norm(x), freqs, mask)
115
+ return x + self.ff(self.ff_norm(x))
116
+
117
+
118
+ class Resampler(nn.Module):
119
+ def __init__(self):
120
+ super().__init__()
121
+ self.new_tokens = nn.Parameter(torch.zeros(1, 1, DIM))
122
+ self.blocks = nn.ModuleList(Block(i >= SINUSOIDAL_FROM) for i in range(DEPTH))
123
+ self.mapping = nn.Conv1d(DIM, 2 * PATCH, 1)
124
+
125
+ def forward(self, x: torch.Tensor, freqs: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
126
+ B, T, _ = x.shape
127
+ slots = self.new_tokens.expand(B * T, STRIDE, DIM)
128
+ slots = slots + torch.randn_like(slots) * MASK_NOISE
129
+ x = torch.cat([x.reshape(B * T, 1, DIM), slots], dim=1).reshape(B, T * GROUP, DIM)
130
+ for block in self.blocks:
131
+ x = block(x, freqs, mask)
132
+ x = x.reshape(B * T, GROUP, DIM)[:, 1:]
133
+ return self.mapping(x.reshape(B, T * STRIDE, DIM).transpose(1, 2))
134
+
135
+
136
+ class SameLDecoder(nn.Module):
137
+ def __init__(self):
138
+ super().__init__()
139
+ self.proj_in = nn.Linear(LATENT_DIM, DIM)
140
+ self.resampler = Resampler()
141
+ self.register_buffer("running_std", torch.ones(1))
142
+ position = torch.arange(SEQ)
143
+ self.register_buffer(
144
+ "mask", (position[None, :] - position[:, None]).abs() <= WINDOW, persistent=False)
145
+ self.register_buffer(
146
+ "inv_freq", 1.0 / (10000.0 ** (torch.arange(0, ROPE_DIM, 2) / ROPE_DIM)),
147
+ persistent=False)
148
+
149
+ def _rope_freqs(self) -> torch.Tensor:
150
+ freqs = torch.outer(torch.arange(SEQ, device=self.inv_freq.device).float(),
151
+ self.inv_freq.float())
152
+ return torch.cat([freqs, freqs], dim=-1)
153
+
154
+ def _decode_chunk(self, latents: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
155
+ x = latents * self.running_std
156
+ x = x + torch.randn_like(x) * self.running_std * LATENT_NOISE
157
+ x = self.resampler(self.proj_in(x.transpose(1, 2)), freqs, self.mask)
158
+ B, _, L = x.shape
159
+ return x.view(B, 2, PATCH, L).permute(0, 1, 3, 2).reshape(B, 2, L * PATCH)
160
+
161
+ @torch.no_grad()
162
+ def decode(self, latents: torch.Tensor) -> torch.Tensor:
163
+ """(B, 256, T) latents, T >= CHUNK, to (B, 2, T * 4096) audio."""
164
+ frames = latents.shape[-1]
165
+ starts = list(range(0, frames - CHUNK + 1, CHUNK - OVERLAP))
166
+ if starts[-1] != frames - CHUNK:
167
+ starts.append(frames - CHUNK)
168
+ freqs = self._rope_freqs()
169
+ edge = OVERLAP // 2 * SAMPLES_PER_FRAME
170
+ audio = latents.new_zeros(latents.shape[0], 2, frames * SAMPLES_PER_FRAME)
171
+ for i, start in enumerate(starts):
172
+ chunk = self._decode_chunk(latents[..., start:start + CHUNK], freqs)
173
+ left = 0 if i == 0 else edge
174
+ right = chunk.shape[-1] if i == len(starts) - 1 else chunk.shape[-1] - edge
175
+ at = start * SAMPLES_PER_FRAME
176
+ audio[..., at + left:at + right] = chunk[..., left:right]
177
+ return audio
178
+
179
+
180
+ def load_decoder(device: str = "cuda",
181
+ dtype: torch.dtype = torch.float16) -> SameLDecoder:
182
+ """Load the bundled SAME-L weights, keeping only what decoding needs."""
183
+ raw = load_file(WEIGHTS)
184
+ state = {"running_std": raw["bottleneck.running_std"]}
185
+
186
+ g, v = raw["decoder.layers.3.mapping.weight_g"], raw["decoder.layers.3.mapping.weight_v"]
187
+ state["resampler.mapping.weight"] = g * v / v.norm(dim=(1, 2), keepdim=True)
188
+ for key, tensor in raw.items():
189
+ if key.startswith("decoder.layers.1."):
190
+ state[key.replace("decoder.layers.1.", "proj_in.")] = tensor
191
+ elif key.startswith("decoder.layers.3.") and not key.endswith(
192
+ ("rope.inv_freq", "mapping.weight_g", "mapping.weight_v")):
193
+ state[key.replace("decoder.layers.3.", "resampler.")
194
+ .replace("transformers.", "blocks.")] = tensor
195
+
196
+ decoder = SameLDecoder()
197
+ decoder.load_state_dict(state)
198
+ return decoder.to(device=device, dtype=dtype).eval().requires_grad_(False)
samel/.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz 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
samel/LICENSE.md ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ STABILITY AI COMMUNITY LICENSE AGREEMENT
2
+
3
+ Last Updated: July 5, 2024
4
+
5
+ 1. INTRODUCTION
6
+
7
+ This Agreement applies to any individual person or entity (“You”, “Your” or “Licensee”) that uses or distributes any portion or element of the Stability AI Materials or Derivative Works thereof for any Research & Non-Commercial or Commercial purpose. Capitalized terms not otherwise defined herein are defined in Section V below.
8
+
9
+ This Agreement is intended to allow research, non-commercial, and limited commercial uses of the Models free of charge. In order to ensure that certain limited commercial uses of the Models continue to be allowed, this Agreement preserves free access to the Models for people or organizations generating annual revenue of less than US $1,000,000 (or local currency equivalent).
10
+
11
+ By clicking “I Accept” or by using or distributing or using any portion or element of the Stability Materials or Derivative Works, You agree that You have read, understood and are bound by the terms of this Agreement. If You are acting on behalf of a company, organization or other entity, then “You” includes you and that entity, and You agree that You: (i) are an authorized representative of such entity with the authority to bind such entity to this Agreement, and (ii) You agree to the terms of this Agreement on that entity’s behalf.
12
+
13
+ 2. RESEARCH & NON-COMMERCIAL USE LICENSE
14
+
15
+ Subject to the terms of this Agreement, Stability AI grants You a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable and royalty-free limited license under Stability AI’s intellectual property or other rights owned by Stability AI embodied in the Stability AI Materials to use, reproduce, distribute, and create Derivative Works of, and make modifications to, the Stability AI Materials for any Research or Non-Commercial Purpose. “Research Purpose” means academic or scientific advancement, and in each case, is not primarily intended for commercial advantage or monetary compensation to You or others. “Non-Commercial Purpose” means any purpose other than a Research Purpose that is not primarily intended for commercial advantage or monetary compensation to You or others, such as personal use (i.e., hobbyist) or evaluation and testing.
16
+
17
+ 3. COMMERCIAL USE LICENSE
18
+
19
+ Subject to the terms of this Agreement (including the remainder of this Section III), Stability AI grants You a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable and royalty-free limited license under Stability AI’s intellectual property or other rights owned by Stability AI embodied in the Stability AI Materials to use, reproduce, distribute, and create Derivative Works of, and make modifications to, the Stability AI Materials for any Commercial Purpose. “Commercial Purpose” means any purpose other than a Research Purpose or Non-Commercial Purpose that is primarily intended for commercial advantage or monetary compensation to You or others, including but not limited to, (i) creating, modifying, or distributing Your product or service, including via a hosted service or application programming interface, and (ii) for Your business’s or organization’s internal operations.
20
+ If You are using or distributing the Stability AI Materials for a Commercial Purpose, You must register with Stability AI at (https://stability.ai/community-license). If at any time You or Your Affiliate(s), either individually or in aggregate, generate more than USD $1,000,000 in annual revenue (or the equivalent thereof in Your local currency), regardless of whether that revenue is generated directly or indirectly from the Stability AI Materials or Derivative Works, any licenses granted to You under this Agreement shall terminate as of such date. You must request a license from Stability AI at (https://stability.ai/enterprise) , which Stability AI may grant to You in its sole discretion. If you receive Stability AI Materials, or any Derivative Works thereof, from a Licensee as part of an integrated end user product, then Section III of this Agreement will not apply to you.
21
+
22
+ 4. GENERAL TERMS
23
+
24
+ Your Research, Non-Commercial, and Commercial License(s) under this Agreement are subject to the following terms.
25
+ a. Distribution & Attribution. If You distribute or make available the Stability AI Materials or a Derivative Work to a third party, or a product or service that uses any portion of them, You shall: (i) provide a copy of this Agreement to that third party, (ii) retain the following attribution notice within a "Notice" text file distributed as a part of such copies: "This Stability AI Model is licensed under the Stability AI Community License, Copyright © Stability AI Ltd. All Rights Reserved”, and (iii) prominently display “Powered by Stability AI” on a related website, user interface, blogpost, about page, or product documentation. If You create a Derivative Work, You may add your own attribution notice(s) to the “Notice” text file included with that Derivative Work, provided that You clearly indicate which attributions apply to the Stability AI Materials and state in the “Notice” text file that You changed the Stability AI Materials and how it was modified.
26
+ b. Use Restrictions. Your use of the Stability AI Materials and Derivative Works, including any output or results of the Stability AI Materials or Derivative Works, must comply with applicable laws and regulations (including Trade Control Laws and equivalent regulations) and adhere to the Documentation and Stability AI’s AUP, which is hereby incorporated by reference. Furthermore, You will not use the Stability AI Materials or Derivative Works, or any output or results of the Stability AI Materials or Derivative Works, to create or improve any foundational generative AI model (excluding the Models or Derivative Works).
27
+ c. Intellectual Property.
28
+ (i) Trademark License. No trademark licenses are granted under this Agreement, and in connection with the Stability AI Materials or Derivative Works, You may not use any name or mark owned by or associated with Stability AI or any of its Affiliates, except as required under Section IV(a) herein.
29
+ (ii) Ownership of Derivative Works. As between You and Stability AI, You are the owner of Derivative Works You create, subject to Stability AI’s ownership of the Stability AI Materials and any Derivative Works made by or for Stability AI.
30
+ (iii) Ownership of Outputs. As between You and Stability AI, You own any outputs generated from the Models or Derivative Works to the extent permitted by applicable law.
31
+ (iv) Disputes. If You or Your Affiliate(s) institute litigation or other proceedings against Stability AI (including a cross-claim or counterclaim in a lawsuit) alleging that the Stability AI Materials, Derivative Works or associated outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by You, then any licenses granted to You under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Stability AI from and against any claim by any third party arising out of or related to Your use or distribution of the Stability AI Materials or Derivative Works in violation of this Agreement.
32
+ (v) Feedback. From time to time, You may provide Stability AI with verbal and/or written suggestions, comments or other feedback related to Stability AI’s existing or prospective technology, products or services (collectively, “Feedback”). You are not obligated to provide Stability AI with Feedback, but to the extent that You do, You hereby grant Stability AI a perpetual, irrevocable, royalty-free, fully-paid, sub-licensable, transferable, non-exclusive, worldwide right and license to exploit the Feedback in any manner without restriction. Your Feedback is provided “AS IS” and You make no warranties whatsoever about any Feedback.
33
+ d. Disclaimer Of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE STABILITY AI MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OR LAWFULNESS OF USING OR REDISTRIBUTING THE STABILITY AI MATERIALS, DERIVATIVE WORKS OR ANY OUTPUT OR RESULTS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE STABILITY AI MATERIALS, DERIVATIVE WORKS AND ANY OUTPUT AND RESULTS.
34
+ e. Limitation Of Liability. IN NO EVENT WILL STABILITY AI OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF STABILITY AI OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
35
+ f. Term And Termination. The term of this Agreement will commence upon Your acceptance of this Agreement or access to the Stability AI Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Stability AI may terminate this Agreement if You are in breach of any term or condition of this Agreement. Upon termination of this Agreement, You shall delete and cease use of any Stability AI Materials or Derivative Works. Section IV(d), (e), and (g) shall survive the termination of this Agreement.
36
+ g. Governing Law. This Agreement will be governed by and constructed in accordance with the laws of the United States and the State of California without regard to choice of law principles, and the UN Convention on Contracts for International Sale of Goods does not apply to this Agreement.
37
+
38
+ 5. DEFINITIONS
39
+
40
+ “Affiliate(s)” means any entity that directly or indirectly controls, is controlled by, or is under common control with the subject entity; for purposes of this definition, “control” means direct or indirect ownership or control of more than 50% of the voting interests of the subject entity.
41
+
42
+ "Agreement" means this Stability AI Community License Agreement.
43
+
44
+ “AUP” means the Stability AI Acceptable Use Policy available at (https://stability.ai/use-policy), as may be updated from time to time.
45
+
46
+ "Derivative Work(s)” means (a) any derivative work of the Stability AI Materials as recognized by U.S. copyright laws and (b) any modifications to a Model, and any other model created which is based on or derived from the Model or the Model’s output, including “fine tune” and “low-rank adaptation” models derived from a Model or a Model’s output, but do not include the output of any Model.
47
+
48
+ “Documentation” means any specifications, manuals, documentation, and other written information provided by Stability AI related to the Software or Models.
49
+
50
+ “Model(s)" means, collectively, Stability AI’s proprietary models and algorithms, including machine-learning models, trained model weights and other elements of the foregoing listed on Stability’s Core Models Webpage available at (https://stability.ai/core-models), as may be updated from time to time.
51
+
52
+ "Stability AI" or "we" means Stability AI Ltd. and its Affiliates.
53
+
54
+ "Software" means Stability AI’s proprietary software made available under this Agreement now or in the future.
55
+
56
+ “Stability AI Materials” means, collectively, Stability’s proprietary Models, Software and Documentation (and any portion or combination thereof) made available under this Agreement.
57
+
58
+ “Trade Control Laws” means any applicable U.S. and non-U.S. export control and trade sanctions laws and regulations.
samel/LICENSE_GEMMA.md ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Gemma Terms of Use
2
+
3
+ The terms below apply to Gemma models listed in the Appendix at bottom of this page. For Gemma 4 terms, see the [Gemma 4 license](https://ai.google.dev/gemma/apache_2).
4
+
5
+ Last modified: April 1, 2026
6
+
7
+ By using, reproducing, modifying, distributing, performing or displaying any
8
+ portion or element of Gemma, Model Derivatives including via any Hosted Service,
9
+ (each as defined below) (collectively, the "**Gemma Services**") or otherwise
10
+ accepting the terms of this Agreement, you agree to be bound by this Agreement.
11
+
12
+ ## Section 1: DEFINITIONS
13
+
14
+ ### 1.1 Definitions
15
+
16
+ (a) "**Agreement** " or "**Gemma Terms of Use**" means these terms and conditions
17
+ that govern the use, reproduction, Distribution or modification of the Gemma
18
+ Services and any terms and conditions incorporated by reference.
19
+
20
+ (b) "**Distribution** " or "**Distribute** " means any transmission, publication,
21
+ or other sharing of Gemma or Model Derivatives to a third party, including by
22
+ providing or making Gemma or its functionality available as a hosted service via
23
+ API, web access, or any other electronic or remote means ("**Hosted Service**").
24
+
25
+ (c) "**Gemma** " means the set of machine learning language models, trained model
26
+ weights and parameters identified in the [Appendix](https://ai.google.dev/gemma/terms#appendix),
27
+ regardless of the source that you obtained it from.
28
+
29
+ (d) "**Google**" means Google LLC.
30
+
31
+ (e) "**Model Derivatives**" means all (i) modifications to Gemma, (ii) works based
32
+ on Gemma, or (iii) any other machine learning model which is created by transfer
33
+ of patterns of the weights, parameters, operations, or Output of Gemma, to that
34
+ model in order to cause that model to perform similarly to Gemma, including
35
+ distillation methods that use intermediate data representations or methods based
36
+ on the generation of synthetic data Outputs by Gemma for training that model.
37
+ For clarity, Outputs are not deemed Model Derivatives.
38
+
39
+ (f) "**Output**" means the information content output of Gemma or a Model
40
+ Derivative that results from operating or otherwise using Gemma or the Model
41
+ Derivative, including via a Hosted Service.
42
+
43
+ ### 1.2
44
+
45
+ As used in this Agreement, "**including** " means
46
+ "**including without limitation**".
47
+
48
+ ## Section 2: ELIGIBILITY AND USAGE
49
+
50
+ ### 2.1 Eligibility
51
+
52
+ You represent and warrant that you have the legal capacity to enter into this
53
+ Agreement (including being of sufficient age of consent). If you are accessing
54
+ or using any of the Gemma Services for or on behalf of a legal entity, (a) you
55
+ are entering into this Agreement on behalf of yourself and that legal entity,
56
+ (b) you represent and warrant that you have the authority to act on behalf of
57
+ and bind that entity to this Agreement and (c) references to "**you** " or
58
+ "**your**" in the remainder of this Agreement refers to both you (as an
59
+ individual) and that entity.
60
+
61
+ ### 2.2 Use
62
+
63
+ You may use, reproduce, modify, Distribute, perform or display any of the Gemma
64
+ Services only in accordance with the terms of this Agreement, and must not
65
+ violate (or encourage or permit anyone else to violate) any term of this
66
+ Agreement.
67
+
68
+ ## Section 3: DISTRIBUTION AND RESTRICTIONS
69
+
70
+ ### 3.1 Distribution and Redistribution
71
+
72
+ You may reproduce or Distribute copies of Gemma or Model Derivatives if you meet
73
+ all of the following conditions:
74
+
75
+ 1. You must include the use restrictions referenced in Section 3.2 as an enforceable provision in any agreement (e.g., license agreement, terms of use, etc.) governing the use and/or distribution of Gemma or Model Derivatives and you must provide notice to subsequent users you Distribute to that Gemma or Model Derivatives are subject to the use restrictions in Section 3.2.
76
+ 2. You must provide all third party recipients of Gemma or Model Derivatives a copy of this Agreement.
77
+ 3. You must cause any modified files to carry prominent notices stating that you modified the files.
78
+ 4. All Distributions (other than through a Hosted Service) must be accompanied by a "**Notice** " text file that contains the following notice: "**Gemma is provided under and subject to the Gemma Terms of Use found at ai.google.dev/gemma/terms**".
79
+
80
+ You may add your own intellectual property statement to your modifications and,
81
+ except as set forth in this Section, may provide additional or different terms
82
+ and conditions for use, reproduction, or Distribution of your modifications, or
83
+ for any such Model Derivatives as a whole, provided your use, reproduction,
84
+ modification, Distribution, performance, and display of Gemma otherwise complies
85
+ with the terms and conditions of this Agreement. Any additional or different
86
+ terms and conditions you impose must not conflict with the terms of this
87
+ Agreement.
88
+
89
+ ### 3.2 Use Restrictions
90
+
91
+ You must not use any of the Gemma Services:
92
+
93
+ 1. for the restricted uses set forth in the Gemma Prohibited Use Policy at [ai.google.dev/gemma/prohibited_use_policy](https://ai.google.dev/gemma/prohibited_use_policy) ("**Prohibited Use Policy**"), which is hereby incorporated by reference into this Agreement; or
94
+ 2. in violation of applicable laws and regulations.
95
+
96
+ To the maximum extent permitted by law, Google reserves the right to restrict
97
+ (remotely or otherwise) usage of any of the Gemma Services that Google
98
+ reasonably believes are in violation of this Agreement.
99
+
100
+ ### 3.3 Generated Output
101
+
102
+ Google claims no rights in Outputs you generate using Gemma. You and your users
103
+ are solely responsible for Outputs and their subsequent uses.
104
+
105
+ ## Section 4: ADDITIONAL PROVISIONS
106
+
107
+ ### 4.1 Updates
108
+
109
+ Google may update Gemma from time to time.
110
+
111
+ ### 4.2 Trademarks
112
+
113
+ Nothing in this Agreement grants you any rights to use Google's trademarks,
114
+ trade names, logos or to otherwise suggest endorsement or misrepresent the
115
+ relationship between you and Google. Google reserves any rights not expressly
116
+ granted herein.
117
+
118
+ ### 4.3 DISCLAIMER OF WARRANTY
119
+
120
+ UNLESS REQUIRED BY APPLICABLE LAW, THE GEMMA SERVICES, AND OUTPUTS, ARE PROVIDED
121
+ ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER
122
+ EXPRESS OR IMPLIED, INCLUDING ANY WARRANTIES OR CONDITIONS OF TITLE,
123
+ NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE
124
+ SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING, REPRODUCING,
125
+ MODIFYING, PERFORMING, DISPLAYING OR DISTRIBUTING ANY OF THE GEMMA SERVICES
126
+ OR OUTPUTS AND ASSUME ANY AND ALL RISKS ASSOCIATED WITH YOUR USE OR DISTRIBUTION
127
+ OF ANY OF THE GEMMA SERVICES OR OUTPUTS AND YOUR EXERCISE OF RIGHTS AND
128
+ PERMISSIONS UNDER THIS AGREEMENT.
129
+
130
+ ### 4.4 LIMITATION OF LIABILITY
131
+
132
+ TO THE FULLEST EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO
133
+ LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), PRODUCT LIABILITY,
134
+ CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW, SHALL GOOGLE OR ITS
135
+ AFFILIATES BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY DIRECT, INDIRECT,
136
+ SPECIAL, INCIDENTAL, EXEMPLARY, CONSEQUENTIAL, OR PUNITIVE DAMAGES, OR LOST
137
+ PROFITS OF ANY KIND ARISING FROM THIS AGREEMENT OR RELATED TO, ANY OF THE GEMMA
138
+ SERVICES OR OUTPUTS EVEN IF GOOGLE OR ITS AFFILIATES HAVE BEEN ADVISED OF THE
139
+ POSSIBILITY OF SUCH DAMAGES.
140
+
141
+ ### 4.5 Term, Termination, and Survival
142
+
143
+ The term of this Agreement will commence upon your acceptance of this Agreement
144
+ (including acceptance by your use, modification, or Distribution, reproduction,
145
+ performance or display of any portion or element of the Gemma Services) and will
146
+ continue in full force and effect until terminated in accordance with the terms
147
+ of this Agreement. Google may terminate this Agreement if you are in breach of
148
+ any term of this Agreement. Upon termination of this Agreement, you must delete
149
+ and cease use and Distribution of all copies of Gemma and Model Derivatives in
150
+ your possession or control. Sections 1, 2.1, 3.3, 4.2 to 4.9 shall survive the
151
+ termination of this Agreement.
152
+
153
+ ### 4.6 Governing Law and Jurisdiction
154
+
155
+ This Agreement will be governed by the laws of the State of California without
156
+ regard to choice of law principles. The UN Convention on Contracts for the
157
+ International Sale of Goods does not apply to this Agreement. The state and
158
+ federal courts of Santa Clara County, California shall have exclusive
159
+ jurisdiction of any dispute arising out of this Agreement.
160
+
161
+ ### 4.7 Severability
162
+
163
+ If any provision of this Agreement is held to be invalid, illegal or
164
+ unenforceable, the remaining provisions shall be unaffected thereby and remain
165
+ valid as if such provision had not been set forth herein.
166
+
167
+ ### 4.8 Entire Agreement
168
+
169
+ This Agreement states all the terms agreed between the parties and supersedes
170
+ all other agreements between the parties as of the date of acceptance relating
171
+ to its subject matter.
172
+
173
+ ### 4.9 No Waiver
174
+
175
+ Google will not be treated as having waived any rights by not exercising (or
176
+ delaying the exercise of) any rights under this Agreement.
177
+
178
+ ## Appendix
179
+
180
+ - [Gemma 1](https://ai.google.dev/gemma/docs/core/model_card)
181
+ - [Gemma 1.1](https://ai.google.dev/gemma/docs/core/model_card)
182
+ - [Gemma 2](https://ai.google.dev/gemma/docs/core/model_card_2)
183
+ - [Gemma 3](https://ai.google.dev/gemma/docs/core/model_card_3)
184
+ - [Gemma 3n](https://ai.google.dev/gemma/docs/3n)
185
+ - [FunctionGemma](https://ai.google.dev/gemma/docs/functiongemma)
186
+ - [EmbeddingGemma](https://ai.google.dev/gemma/docs/embeddinggemma)
187
+ - [PaliGemma](https://ai.google.dev/gemma/docs/paligemma/model-card)
188
+ - [PaliGemma 2](https://ai.google.dev/gemma/docs/paligemma/model-card-2)
189
+ - [ShieldGemma](https://ai.google.dev/gemma/docs/shieldgemma/model_card)
190
+ - [ShieldGemma 2](https://ai.google.dev/gemma/docs/shieldgemma/model_card_2)
191
+ - [CodeGemma](https://ai.google.dev/gemma/docs/codegemma/model_card)
192
+ - [CodeGemma 1.1](https://ai.google.dev/gemma/docs/codegemma/model_card)
193
+ - [Gemma 2 JPN](https://huggingface.co/google/gemma-2-2b-jpn-it)
194
+ - [DataGemma RIG](https://www.kaggle.com/models/google/datagemma-rig)
195
+ - [DataGemma RAG](https://www.kaggle.com/models/google/datagemma-rag)
196
+ - [RecurrentGemma](https://ai.google.dev/gemma/docs/recurrentgemma/model_card)
197
+ - [Gemma Scope](https://ai.google.dev/gemma/docs/gemma_scope)
198
+ - [Gemma-APS](https://ai.google.dev/gemma/docs/gemma-aps)
199
+ - [T5Gemma](https://www.kaggle.com/models/google/t5gemma)
200
+ - [VaultGemma](https://www.kaggle.com/models/google/vaultgemma)
201
+ - [FunctionGemma](https://www.kaggle.com/models/google/functiongemma)
202
+ - [T5Gemma 2](https://www.kaggle.com/models/google/t5gemma-2)
203
+ - [TranslateGemma](https://www.kaggle.com/models/google/translategemma)
204
+
205
+ > [!NOTE]
206
+ > **Note:** Previous versions of these Terms are [archived here](https://ai.google.dev/gemma/terms-archive).
samel/NOTICE ADDED
@@ -0,0 +1 @@
 
 
1
+ Gemma is provided under and subject to the Gemma Terms of Use found at ai.google.dev/gemma/terms
samel/README.md ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ library_name: stable-audio-3
5
+ license: other
6
+ license_name: stable-audio-community
7
+ license_link: LICENSE
8
+ tags:
9
+ - music
10
+ - sound-effects
11
+ - audio
12
+ - autoencoder
13
+ ---
14
+
15
+ # SAME: A Semantically-Aligned Music Autoencoder
16
+
17
+ Please note: For commercial use, please refer to [https://stability.ai/license](https://stability.ai/license)
18
+
19
+ ## Model Description
20
+ Latent representations are at the heart of the majority of modern generative models.
21
+ In the audio domain they are typically produced by a neural-audio-codec autoencoder.
22
+ In this work we introduce SAME (Semantically Aligned Music autoEncoder),
23
+ a transformer-based autoencoder for stereo music and general audio that reaches a 4096x temporal compression ratio (roughly twice the current standard)
24
+ while maintaining excellent reconstruction quality and strong downstream generative performance.
25
+ We achieve this by combining a set of semantic regularisation approaches with phase-aware reconstruction losses.
26
+ The architecture also delivers substantial computational cost benefits, through both its high compression ratio and its reliance on well-optimised transformer primitives.
27
+ Two variants (a large SAME-L and a CPU-deployable SAME-S) are released in open-weights form.
28
+
29
+ ## Usage
30
+
31
+ This model can be used with:
32
+ 1. the [`stable-audio-3`](https://github.com/Stability-AI/stable-audio-3) inference and fine-tuning library
33
+ 2. the [`stable-audio-tools`](https://github.com/Stability-AI/stable-audio-tools) research library
34
+
35
+
36
+ ### Using with `stable-audio-3`
37
+ import torchaudio
38
+ from stable_audio_3 import AutoencoderModel
39
+
40
+ ae = AutoencoderModel.from_pretrained("same-l")
41
+ waveform, sr = torchaudio.load("audio.wav")
42
+ latents = ae.encode(waveform, sr)
43
+ audio_out = ae.decode(latents)
44
+
45
+
46
+ ### Using with `stable-audio-tools`
47
+
48
+ ```python
49
+ import torch
50
+ import torchaudio
51
+ from einops import rearrange
52
+ from stable_audio_tools import get_pretrained_model
53
+ from stable_audio_tools.inference.generation import generate_diffusion_cond
54
+
55
+ device = "cuda" if torch.cuda.is_available() else "cpu"
56
+ if device == "cuda":
57
+ model_half = True
58
+
59
+ # Download model
60
+ model, model_config = get_pretrained_model("stabilityai/SAME-L")
61
+ sample_rate = model_config["sample_rate"]
62
+ sample_size = model_config["sample_size"]
63
+
64
+ model = model.to(device)
65
+ if model_half:
66
+ model = model.to(torch.float16)
67
+
68
+ audio, sr = torchaudio.load(/path/to/audiofile) # [channels, samples]
69
+ if audio.shape[0] == 1:
70
+ audio = audio.repeat(2, 1)
71
+
72
+ audio = audio.unsqueeze(0).to(device)
73
+ if model_half:
74
+ audio = audio.half()
75
+ with torch.no_grad():
76
+ latents = model.encode_audio(audio)
77
+ reconstructed = model.decode_audio(latents)
78
+ reconstructed = reconstructed.squeeze(0).cpu()
79
+ reconstructed = reconstructed.to(torch.float32).clamp(-1, 1).mul(32767).to(torch.int16).cpu()
80
+
81
+ ```
82
+
83
+
84
+ ## Model Details
85
+ * **Model type**: `SAME` is a continuous autoencoder model based on a transformer architecture.
86
+ * **Language(s)**: English
87
+ * **License**: [Stability AI Community License](https://stability.ai/license).
88
+ * **Research Paper**: [https://arxiv.org/abs/2605.18613](https://arxiv.org/abs/2605.18613)
89
+
90
+
91
+ ## Training dataset
92
+
93
+ ### Datasets Used
94
+ Our dataset consists of ~19,500 hours of licensed production audio from [AudioSparx](https://www.audiosparx.com/) which includes a 66/25/9% mix of music, sound effects, and instrument stems.
95
+
96
+
97
+
98
+
99
+
100
+
101
+
samel/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8cf93d5345c559307fc429bde896f594516fd6a1a23014c2f6055f78d8e13378
3
+ size 3408566892
samel/model_config.json ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "autoencoder",
3
+ "sample_size": 196608,
4
+ "sample_rate": 44100,
5
+ "audio_channels": 2,
6
+ "model": {
7
+ "pretransform": {
8
+ "type": "patched",
9
+ "config": {
10
+ "patch_size": 256,
11
+ "channels": 2
12
+ }
13
+ },
14
+ "encoder": {
15
+ "type": "same",
16
+ "requires_grad": false,
17
+ "config": {
18
+ "in_channels": 512,
19
+ "channels": 256,
20
+ "c_mults": [6],
21
+ "strides": [16],
22
+ "latent_dim": 256,
23
+ "transformer_depths": [12],
24
+ "checkpointing": true,
25
+ "differential": true,
26
+ "dyt": true,
27
+ "dim_heads": 64,
28
+ "sliding_window": [1,1],
29
+ "variable_stride": true,
30
+ "mask_noise": 0.001
31
+ }
32
+ },
33
+ "decoder": {
34
+ "type": "same",
35
+ "requires_grad": false,
36
+ "config": {
37
+ "out_channels": 512,
38
+ "channels": 256,
39
+ "c_mults": [6],
40
+ "strides": [16],
41
+ "latent_dim": 256,
42
+ "transformer_depths": [12],
43
+ "sinusoidal_blocks": [8],
44
+ "checkpointing": false,
45
+ "differential": true,
46
+ "dyt": true,
47
+ "dim_heads": 64,
48
+ "sliding_window": [1,1],
49
+ "variable_stride": true,
50
+ "mask_noise": 0.1
51
+ }
52
+ },
53
+ "bottleneck": {
54
+ "type": "softnorm",
55
+ "config": {
56
+ "dim": 256,
57
+ "noise_augment_dim": 0,
58
+ "noise_regularize": true,
59
+ "auto_scale": true,
60
+ "freeze": true
61
+ }
62
+ },
63
+ "latent_dim": 256,
64
+ "downsampling_ratio": 4096,
65
+ "io_channels": 2
66
+ }
67
+ }
tags.json ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "acoustic": 28,
4
+ "acoustic guitar": 25,
5
+ "afrobeat": 275,
6
+ "aggressive": 77,
7
+ "alternative": 286,
8
+ "alternative metal": 150,
9
+ "alternative pop": 267,
10
+ "alternative r&b": 355,
11
+ "alternative rock": 39,
12
+ "ambient": 63,
13
+ "ambient pop": 333,
14
+ "americana": 271,
15
+ "angry": 162,
16
+ "anthem": 244,
17
+ "anthemic": 24,
18
+ "arena rock": 192,
19
+ "art pop": 338,
20
+ "art rock": 301,
21
+ "atmospheric": 30,
22
+ "avant-garde": 249,
23
+ "ballad": 11,
24
+ "bass": 97,
25
+ "bass guitar": 137,
26
+ "beats": 322,
27
+ "big band": 305,
28
+ "big beat": 396,
29
+ "bittersweet": 65,
30
+ "bluegrass": 314,
31
+ "blues": 131,
32
+ "blues rock": 207,
33
+ "boastful": 117,
34
+ "boom bap": 250,
35
+ "bossa nova": 344,
36
+ "breakbeat": 241,
37
+ "c-pop": 22,
38
+ "calm": 80,
39
+ "caribbean music": 374,
40
+ "catchy": 96,
41
+ "cello": 142,
42
+ "chamber pop": 413,
43
+ "chill": 222,
44
+ "chillout": 210,
45
+ "chillwave": 277,
46
+ "chiptune": 272,
47
+ "choir": 173,
48
+ "choral": 253,
49
+ "cinematic": 75,
50
+ "cinematic classical": 214,
51
+ "classic rock": 329,
52
+ "classical": 143,
53
+ "classical music": 132,
54
+ "cloud rap": 324,
55
+ "club": 125,
56
+ "complex": 170,
57
+ "conscious": 199,
58
+ "conscious hip hop": 226,
59
+ "contemporary country": 323,
60
+ "contemporary folk": 160,
61
+ "country": 81,
62
+ "country pop": 265,
63
+ "country rock": 227,
64
+ "cyberpunk": 299,
65
+ "dance": 38,
66
+ "dance-pop": 52,
67
+ "dancehall": 318,
68
+ "dark": 53,
69
+ "dark ambient": 291,
70
+ "dark pop": 348,
71
+ "darkwave": 331,
72
+ "death metal": 264,
73
+ "deep": 189,
74
+ "deep bass": 239,
75
+ "deep house": 221,
76
+ "disco": 161,
77
+ "djent": 297,
78
+ "doom metal": 390,
79
+ "downtempo": 138,
80
+ "dramatic": 181,
81
+ "dream pop": 92,
82
+ "dreamy": 95,
83
+ "drill": 304,
84
+ "drum and bass": 156,
85
+ "drum machine": 43,
86
+ "drums": 51,
87
+ "dub": 341,
88
+ "dubstep": 133,
89
+ "dynamic": 255,
90
+ "east coast hip hop": 219,
91
+ "eclectic": 120,
92
+ "edm": 88,
93
+ "electric": 279,
94
+ "electric guitar": 37,
95
+ "electro": 99,
96
+ "electro house": 184,
97
+ "electro pop": 632,
98
+ "electro swing": 307,
99
+ "electronic": 19,
100
+ "emo": 155,
101
+ "emotional": 21,
102
+ "empowering": 124,
103
+ "empowerment": 257,
104
+ "energetic": 18,
105
+ "epic": 56,
106
+ "epic music": 351,
107
+ "ethereal": 44,
108
+ "euphoric": 208,
109
+ "european music": 398,
110
+ "experimental": 106,
111
+ "fantasy": 230,
112
+ "fast": 223,
113
+ "female vocal": 12,
114
+ "film score": 157,
115
+ "flute": 169,
116
+ "folk": 34,
117
+ "folk pop": 94,
118
+ "folk rock": 177,
119
+ "fun": 270,
120
+ "funk": 107,
121
+ "funky": 258,
122
+ "future bass": 193,
123
+ "futuristic": 119,
124
+ "gangsta rap": 200,
125
+ "gentle": 32,
126
+ "glam metal": 418,
127
+ "glam rock": 353,
128
+ "glitch": 183,
129
+ "gospel": 243,
130
+ "gothic metal": 313,
131
+ "gothic rock": 381,
132
+ "gritty": 289,
133
+ "groove metal": 391,
134
+ "groovy": 202,
135
+ "grunge": 233,
136
+ "guitar": 62,
137
+ "happy": 122,
138
+ "hard rock": 70,
139
+ "hardcore": 346,
140
+ "hardcore hip hop": 149,
141
+ "harmonica": 276,
142
+ "harp": 354,
143
+ "haunting": 260,
144
+ "heartfelt": 136,
145
+ "heavy": 89,
146
+ "heavy bass": 280,
147
+ "heavy metal": 108,
148
+ "high-energy": 445,
149
+ "hip hop": 47,
150
+ "hispanic american music": 356,
151
+ "hispanic music": 361,
152
+ "hopeful": 66,
153
+ "house": 87,
154
+ "humorous": 292,
155
+ "hypnotic": 114,
156
+ "idm": 262,
157
+ "indie": 201,
158
+ "indie folk": 48,
159
+ "indie pop": 50,
160
+ "indie rock": 98,
161
+ "industrial": 185,
162
+ "inspirational": 49,
163
+ "instrumental": 35,
164
+ "intense": 176,
165
+ "introspective": 71,
166
+ "j-pop": 191,
167
+ "j-rock": 393,
168
+ "jamaican music": 412,
169
+ "jazz": 84,
170
+ "jazz fusion": 259,
171
+ "jazz rap": 384,
172
+ "kpop": 6,
173
+ "latin": 325,
174
+ "latin pop": 387,
175
+ "lo-fi": 148,
176
+ "longing": 121,
177
+ "love": 69,
178
+ "lush": 78,
179
+ "male vocal": 20,
180
+ "mechanical": 251,
181
+ "medieval": 281,
182
+ "meditative": 212,
183
+ "melancholic": 33,
184
+ "melancholy": 365,
185
+ "mellow": 90,
186
+ "melodic": 16,
187
+ "melodic death metal": 452,
188
+ "melodic metalcore": 438,
189
+ "metal": 55,
190
+ "metalcore": 196,
191
+ "minimal": 360,
192
+ "minimalist": 287,
193
+ "modern classical": 290,
194
+ "mysterious": 163,
195
+ "nature": 206,
196
+ "neo-psychedelia": 362,
197
+ "neo-soul": 285,
198
+ "neon": 218,
199
+ "new age": 198,
200
+ "new wave": 167,
201
+ "nocturnal": 105,
202
+ "nostalgic": 101,
203
+ "nu metal": 164,
204
+ "ominous": 171,
205
+ "opera": 232,
206
+ "optimistic": 153,
207
+ "orchestral": 57,
208
+ "outlaw country": 375,
209
+ "party": 86,
210
+ "passionate": 42,
211
+ "phonk": 215,
212
+ "piano": 14,
213
+ "playful": 82,
214
+ "poetic": 242,
215
+ "pop": 10,
216
+ "pop punk": 205,
217
+ "pop rap": 100,
218
+ "pop rock": 45,
219
+ "pop soul": 236,
220
+ "post-grunge": 273,
221
+ "post-hardcore": 268,
222
+ "post-industrial": 340,
223
+ "post-punk": 245,
224
+ "power ballad": 118,
225
+ "power metal": 151,
226
+ "power pop": 166,
227
+ "powerful": 102,
228
+ "powerful vocals": 158,
229
+ "progressive": 127,
230
+ "progressive electronic": 306,
231
+ "progressive house": 220,
232
+ "progressive metal": 203,
233
+ "progressive rock": 152,
234
+ "progressive trance": 377,
235
+ "psychedelic": 109,
236
+ "psychedelic pop": 342,
237
+ "psychedelic rock": 225,
238
+ "punk": 154,
239
+ "punk rock": 188,
240
+ "quirky": 231,
241
+ "r&b": 67,
242
+ "rap": 41,
243
+ "raw": 139,
244
+ "rebellious": 213,
245
+ "reflective": 46,
246
+ "reggae": 147,
247
+ "reggaeton": 274,
248
+ "regional music": 85,
249
+ "repetitive": 128,
250
+ "retro": 317,
251
+ "reverb": 302,
252
+ "rhythmic": 27,
253
+ "rock": 13,
254
+ "rock and roll": 541,
255
+ "romantic": 17,
256
+ "sad": 123,
257
+ "sampling": 134,
258
+ "saxophone": 248,
259
+ "sensual": 180,
260
+ "sentimental": 113,
261
+ "shoegaze": 371,
262
+ "singer-songwriter": 40,
263
+ "ska": 368,
264
+ "slow": 126,
265
+ "slow tempo": 320,
266
+ "smooth": 187,
267
+ "smooth jazz": 269,
268
+ "smooth soul": 339,
269
+ "soft": 76,
270
+ "soft pop": 115,
271
+ "soft rock": 26,
272
+ "sombre": 174,
273
+ "soothing": 112,
274
+ "soul": 93,
275
+ "soulful": 178,
276
+ "soundtrack": 7,
277
+ "southern hip hop": 316,
278
+ "southern rock": 453,
279
+ "spiritual": 263,
280
+ "spoken word": 312,
281
+ "storytelling": 186,
282
+ "strings": 29,
283
+ "summer": 179,
284
+ "surreal": 235,
285
+ "suspenseful": 195,
286
+ "swing": 197,
287
+ "symphonic": 337,
288
+ "symphonic metal": 175,
289
+ "synth": 60,
290
+ "synth pad": 79,
291
+ "synth pop": 172,
292
+ "synthesizer": 31,
293
+ "synthetic": 1,
294
+ "synthwave": 72,
295
+ "tech house": 311,
296
+ "technical": 209,
297
+ "techno": 110,
298
+ "thrash metal": 359,
299
+ "trance": 129,
300
+ "trap": 73,
301
+ "trip hop": 211,
302
+ "triumphant": 159,
303
+ "trumpet": 308,
304
+ "upbeat": 61,
305
+ "uplifting": 15,
306
+ "urban": 103,
307
+ "violin": 91,
308
+ "vocal": 294,
309
+ "vocal jazz": 388,
310
+ "warm": 54,
311
+ "west coast hip hop": 392,
312
+ "western classical music": 140
313
+ },
314
+ "other": {
315
+ "A Hat in Time": 1394,
316
+ "Ace Attorney": 922,
317
+ "Ace Combat 7": 923,
318
+ "Animal Crossing New Horizons": 937,
319
+ "Aquaria": 1456,
320
+ "Ar Tonelico": 938,
321
+ "Arknights": 1447,
322
+ "Assasins Creed Valhalla": 944,
323
+ "Atelier Series": 956,
324
+ "Baldur's Gate 3": 963,
325
+ "Banjo Kazooie": 964,
326
+ "Banjo Tooie": 965,
327
+ "battle": 8,
328
+ "Black Myth Wukong": 972,
329
+ "Blue Reflection": 976,
330
+ "Bravely Default": 979,
331
+ "Castlevania Symphony of the Night": 991,
332
+ "Cave Story": 992,
333
+ "Celeste": 993,
334
+ "Chrono Cross": 996,
335
+ "Chrono Trigger": 997,
336
+ "Clair Obscur": 999,
337
+ "Clannad": 1000,
338
+ "Cowboy Bebop": 1003,
339
+ "credits": 9,
340
+ "Crosscode": 1004,
341
+ "Cuphead": 1005,
342
+ "Deltarune": 1011,
343
+ "Devil May Cry 4": 1020,
344
+ "Devil May Cry 5": 1430,
345
+ "Diddy Kong Racing": 1016,
346
+ "Divinity Original Sin 2": 1457,
347
+ "Doki Doki Literature Club": 1021,
348
+ "Donkey Kong Country": 1024,
349
+ "Dragon Quest IX": 1031,
350
+ "Elder Scrolls 3 Morrowind": 1035,
351
+ "EverQuest": 1038,
352
+ "Fate Grand Order": 1047,
353
+ "Final Fantasy I": 869,
354
+ "Final Fantasy II": 870,
355
+ "Final Fantasy III": 871,
356
+ "Final Fantasy IV": 874,
357
+ "Final Fantasy IX": 882,
358
+ "Final Fantasy V": 876,
359
+ "Final Fantasy VI": 877,
360
+ "Final Fantasy VII": 879,
361
+ "Final Fantasy VII Remake": 880,
362
+ "Final Fantasy VIII": 881,
363
+ "Final Fantasy X": 883,
364
+ "Final Fantasy X-2": 894,
365
+ "Final Fantasy XI": 884,
366
+ "Final Fantasy XII": 885,
367
+ "Final Fantasy XIII": 886,
368
+ "Final Fantasy XIII-2": 897,
369
+ "Final Fantasy XIII-3": 898,
370
+ "Final Fantasy XIV": 887,
371
+ "Final Fantasy XV": 888,
372
+ "Fire Emblem Awakening": 1056,
373
+ "Fire Emblem Three Houses": 1058,
374
+ "Frieren": 1059,
375
+ "Genshin Impact": 1065,
376
+ "Golden Sun": 1067,
377
+ "Granblue Fantasy": 1069,
378
+ "Granblue Fantasy Versus": 1070,
379
+ "Guilty Gear Strive": 1462,
380
+ "Hades 2": 1077,
381
+ "Haikyuu": 1078,
382
+ "Harvest Moon": 1079,
383
+ "Hollow Knight": 1086,
384
+ "Hollow Knight Silksong": 1087,
385
+ "Honkai Impact 3rd": 1105,
386
+ "Honkai Star Rail": 1108,
387
+ "K-ON": 1123,
388
+ "Kingdom Hearts": 1129,
389
+ "Kirby": 1359,
390
+ "Lies of P": 1151,
391
+ "Maple Story": 1157,
392
+ "Mario & Luigi - Superstar Saga": 1163,
393
+ "Mario Kart 8": 1444,
394
+ "Mario Kart World": 1173,
395
+ "Mega Man": 1181,
396
+ "Mega Man X": 1187,
397
+ "Metaphor Refantazio": 1429,
398
+ "Minecraft": 1199,
399
+ "My Hero Academia": 1206,
400
+ "Nausicaa Valley of the Wind": 1207,
401
+ "Neon White": 1209,
402
+ "Nier Automata": 1216,
403
+ "One Piece": 1222,
404
+ "Osu!": 1389,
405
+ "Outer Wilds": 1223,
406
+ "Perfect Dark": 1227,
407
+ "Persona": 1228,
408
+ "Pokemon Black and White": 1235,
409
+ "Pokemon Crystal": 1236,
410
+ "Pokemon Diamond and Pearl": 1237,
411
+ "Pokemon Fire Red and Leaf Green": 1239,
412
+ "Pokemon Heart Gold & Soul Silver": 1240,
413
+ "Pokemon Mystery Dungeon - Explorers of Sky": 1243,
414
+ "Pokemon Red and Blue": 1246,
415
+ "Pokemon Ruby and Sapphire": 1247,
416
+ "Pokemon Scarlet and Violet": 1249,
417
+ "Pokemon Sun and Moon": 1250,
418
+ "Pokemon X and Y": 1252,
419
+ "Pokemon XD - Gale of Darkness": 1253,
420
+ "Pokopia": 1255,
421
+ "RuneScape": 1403,
422
+ "Sayonara Wild Hearts": 1281,
423
+ "Sea of Stars": 1282,
424
+ "Secret of Mana": 1283,
425
+ "Sonic Adventure": 1302,
426
+ "Sonic the Hedgehog 3": 1307,
427
+ "Spirited Away": 1309,
428
+ "Splatoon": 1467,
429
+ "Star Ocean": 1312,
430
+ "Stellar Blade": 1426,
431
+ "Super Mario Galaxy": 1327,
432
+ "Super Mario Odyssey": 1328,
433
+ "Super Mario RPG": 1329,
434
+ "Super Meat Boy": 1451,
435
+ "Super Monkey Ball 2": 1331,
436
+ "Super Smash Bros. Brawl": 1333,
437
+ "Tales of Symphonia": 1338,
438
+ "The Elder Scrolls IV: Oblivion": 1468,
439
+ "The Legend of Zelda": 1144,
440
+ "The Legend of Zelda A Link to the Past": 1145,
441
+ "The Legend of Zelda Ocarina of Time": 1383,
442
+ "Touhou": 1345,
443
+ "Umamusume": 1355,
444
+ "Umineko": 1396,
445
+ "Undertale": 1356,
446
+ "Utamonogatari": 1358,
447
+ "Vampire Survivors": 1469,
448
+ "Vocaloid": 1415,
449
+ "Wild Arms 2": 1368,
450
+ "Witcher 3": 1369,
451
+ "Wuchang Fallen Feathers": 1459,
452
+ "Wuthering Waves": 1370,
453
+ "Xenoblade Chronicles": 1372,
454
+ "Xenoblade Chronicles 2": 1373,
455
+ "Xenoblade Chronicles 3": 1375,
456
+ "Xenogears": 1376,
457
+ "Ys": 1380,
458
+ "Yuki Kajiura": 1401,
459
+ "Zenless Zone Zero": 1385
460
+ }
461
+ }
webui.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import secrets
5
+ from itertools import pairwise
6
+ from pathlib import Path
7
+
8
+ import gradio as gr
9
+ import torch
10
+
11
+ from audio_dit import CHANNELS, FRAMES, MAX_TAGS, load_model
12
+ from same_l_decoder import SAMPLE_RATE, load_decoder
13
+
14
+ DEVICE = ("cuda" if torch.cuda.is_available() else
15
+ "mps" if torch.backends.mps.is_available() else "cpu")
16
+ DTYPE = torch.float32 if DEVICE == "cpu" else torch.float16
17
+ AUTOCAST = torch.bfloat16 if DEVICE == "cuda" else torch.float16
18
+
19
+ STEPS = 50
20
+ DEFAULT_CFG = 3.5
21
+ TIME_SHIFT = 2.0
22
+
23
+ TAG_GROUPS = json.loads((Path(__file__).parent / "tags.json").read_text(encoding="utf-8"))
24
+ METADATA_TAGS = TAG_GROUPS["metadata"]
25
+ OTHER_TAGS = TAG_GROUPS["other"]
26
+ SYNTHETIC_TAG_ID = METADATA_TAGS["synthetic"]
27
+ TAGS = METADATA_TAGS | OTHER_TAGS
28
+ del TAGS["synthetic"] # Source conditioning is added automatically, not shown in the UI.
29
+
30
+ TIMESTEPS = [1 - i / STEPS for i in range(STEPS + 1)]
31
+ TIMESTEPS = [TIME_SHIFT * t / (1 + (TIME_SHIFT - 1) * t) for t in TIMESTEPS]
32
+
33
+ model, latent_mean, latent_std = load_model(DEVICE)
34
+ decoder = load_decoder(device=DEVICE, dtype=DTYPE)
35
+
36
+
37
+ @torch.no_grad()
38
+ def generate(tag_names: list[str], cfg_scale: float, seed: int):
39
+ if not tag_names:
40
+ raise gr.Error("Pick at least one tag.")
41
+ seed = secrets.randbits(63) if seed == -1 else seed
42
+ torch.manual_seed(seed)
43
+ ids = [TAGS[name] for name in tag_names]
44
+ if all(name in METADATA_TAGS for name in tag_names):
45
+ if len(ids) == MAX_TAGS:
46
+ raise gr.Error(f"Choose at most {MAX_TAGS - 1} metadata tags.")
47
+ ids.append(SYNTHETIC_TAG_ID)
48
+ tags = torch.tensor([ids + [0] * (MAX_TAGS - len(ids))], device=DEVICE)
49
+ null = torch.zeros_like(tags)
50
+ x = torch.randn(1, CHANNELS, FRAMES, device=DEVICE)
51
+
52
+ for i, (t, t_next) in enumerate(pairwise(TIMESTEPS)):
53
+ # Guidance alternates between the shallow path-drop branch and a full
54
+ # unconditional pass as the weak model to steer away from.
55
+ weak = (model.shallow, model)[i % 2]
56
+ with torch.autocast(DEVICE, dtype=AUTOCAST, enabled=DEVICE != "cpu"):
57
+ cond = model(x, t, tags).float()
58
+ uncond = weak(x, t, null).float()
59
+ x = x + (t_next - t) * (uncond + cfg_scale * (cond - uncond))
60
+
61
+ audio = decoder.decode((x * latent_std + latent_mean).to(DTYPE))
62
+ return SAMPLE_RATE, audio[0].float().clamp(-1, 1).T.cpu().numpy()
63
+
64
+
65
+ with gr.Blocks(title="Audio DiT") as demo:
66
+ gr.Markdown("# Audio DiT\nChoose 1-8 tags.")
67
+ tag_box = gr.Dropdown(choices=list(TAGS), value=[], multiselect=True,
68
+ max_choices=MAX_TAGS, label="Tags", filterable=True)
69
+ cfg_scale = gr.Slider(2.0, 6.0, value=DEFAULT_CFG, step=0.5,
70
+ label="CFG scale")
71
+ seed = gr.Number(value=-1, precision=0, minimum=-1,
72
+ label="Seed (-1 = random)")
73
+ button = gr.Button("Generate", variant="primary")
74
+ audio_out = gr.Audio(label="Output", interactive=False)
75
+ button.click(generate, inputs=[tag_box, cfg_scale, seed], outputs=audio_out,
76
+ concurrency_limit=1)
77
+
78
+ if __name__ == "__main__":
79
+ demo.queue().launch()