jennyxue commited on
Commit
039d16b
·
verified ·
1 Parent(s): f547c0f

int8 build of Fish Audio S2 Pro

Browse files
.gitattributes CHANGED
@@ -36,3 +36,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
36
  fp16/decoder.onnx.data filter=lfs diff=lfs merge=lfs -text
37
  fp16/tokenizer.json filter=lfs diff=lfs merge=lfs -text
38
  overview.png filter=lfs diff=lfs merge=lfs -text
 
 
 
36
  fp16/decoder.onnx.data filter=lfs diff=lfs merge=lfs -text
37
  fp16/tokenizer.json filter=lfs diff=lfs merge=lfs -text
38
  overview.png filter=lfs diff=lfs merge=lfs -text
39
+ int8/decoder.onnx.data filter=lfs diff=lfs merge=lfs -text
40
+ int8/tokenizer.json filter=lfs diff=lfs merge=lfs -text
int8/codec_dec.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2ff21755871d815c82e5d9a65816bed17902d199aa2179220310f84349287ed4
3
+ size 188298891
int8/codec_enc.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ba47cacf744f64c08bc348ceae6bddd2508b26901118697f06ba3fdda54bd817
3
+ size 831995041
int8/decoder.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:75ebe7c93987d6989e82cd484f80048dd0b61313b2ca27dfa2a0b38ac2cf38ba
3
+ size 409128
int8/decoder.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3baa04b0f2cb18ef43a4b32591a84f2d6f9c69043d00cadd4b09bcf7af39e1f9
3
+ size 3869160448
int8/embed.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:432b4c11b5719b542b00a8240fe60877beb4b9c768fa6a32f1ec49e07b71972c
3
+ size 504433802
int8/fast.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3c133d6c1c0266b642c84e43709d9e962831bf2e0807daa13c0417caef8a8220
3
+ size 849614981
int8/head.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:18c9dc13e36820d0e4f6c448e2b5606963dffd573c2eb9965041715291f8b3cf
3
+ size 20977062
int8/pipeline.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fish Audio S2 Pro voice cloning with ONNX Runtime: the dual-AR text-to-semantic model (36-layer slow transformer,
2
+ 4-layer fast transformer over 10 codebooks) and the codec as ONNX graphs, with numpy for the rest, following the
3
+ official `generate_long(text, prompt_text=[ref_text], prompt_tokens=[codes])` (fish-speech @0f8a12e): the same prompt,
4
+ constrained decoding to the semantic tokens and <|im_end|>, temperature 0.7, top-p 0.7, top-k 30 and the
5
+ repetition-aware fallback (temperature 1.0, top-p 0.9 when the token is in the last 10 frames), at most 1024 frames.
6
+ 44.1 kHz output. Needs numpy, onnxruntime (or onnxruntime-gpu), tokenizers and soundfile.
7
+
8
+ python fp16/pipeline.py "Text to say." out.wav --ref voice.wav --ref-text "What voice.wav says." [--cuda]
9
+
10
+ This model is licensed under the Fish Audio Research License, Copyright (c) 39 AI, INC. All Rights Reserved.
11
+ Built with Fish Audio.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import math
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+
21
+ SR = 44100
22
+ FRAME = 2048 # codec samples per frame
23
+ NCB, CBS = 10, 4096
24
+ SEM0, IM_END = 151678, 151645
25
+ MAX_NEW = 1024
26
+ TEMP, TOP_P, TOP_K = 0.7, 0.7, 30
27
+ RAS_WIN, RAS_TEMP, RAS_TOP_P = 10, 1.0, 0.9
28
+
29
+
30
+ def resample(x, orig, new, lowpass_filter_width=6, rolloff=0.99):
31
+ """torchaudio.functional.resample (sinc_interp_hann), which the official encode_audio uses, in numpy."""
32
+ g = math.gcd(int(orig), int(new))
33
+ o, n = int(orig) // g, int(new) // g
34
+ if o == n:
35
+ return np.asarray(x, np.float32)
36
+ base = min(o, n) * rolloff
37
+ width = math.ceil(lowpass_filter_width * o / base)
38
+ idx = np.arange(-width, width + o, dtype=np.float64)[None, :] / o
39
+ t = (np.arange(0, -n, -1, dtype=np.float64)[:, None] / n + idx) * base
40
+ t = np.clip(t, -lowpass_filter_width, lowpass_filter_width)
41
+ win = np.cos(t * math.pi / lowpass_filter_width / 2) ** 2
42
+ t = t * math.pi
43
+ with np.errstate(invalid="ignore", divide="ignore"):
44
+ k = np.where(t == 0, 1.0, np.sin(t) / t)
45
+ k = (k * win * base / o).astype(np.float32)
46
+ xp = np.pad(np.asarray(x, np.float32), (width, width + o))
47
+ frames = np.lib.stride_tricks.sliding_window_view(xp, k.shape[1])[::o]
48
+ y = (frames @ k.T).reshape(-1)
49
+ return y[: math.ceil(n * len(x) / o)].astype(np.float32)
50
+
51
+
52
+ def sample(logits, temp, top_p, top_k, rng):
53
+ """logits_to_probs + multinomial_sample_one_no_sync: top-k and top-p on the untempered distribution, then the
54
+ temperature; one draw by argmax(p / Exp(1))."""
55
+ logits = np.asarray(logits, np.float64)
56
+ order = np.argsort(-logits, kind="stable")
57
+ s = logits[order]
58
+ p = np.exp(s - s.max())
59
+ cum = np.cumsum(p / p.sum())
60
+ remove = (cum > top_p) | (np.arange(len(s)) >= top_k)
61
+ remove[0] = False
62
+ keep = order[~remove]
63
+ z = logits[keep] / max(temp, 1e-5)
64
+ q = np.exp(z - z.max())
65
+ q /= q.sum()
66
+ return int(keep[np.argmax(q / rng.exponential(size=len(q)))])
67
+
68
+
69
+ class FishS2Pro:
70
+ def __init__(self, folder, provider="cpu", threads=4):
71
+ import onnxruntime as ort
72
+ from tokenizers import Tokenizer
73
+ folder = Path(folder)
74
+ self.tok = Tokenizer.from_file(str(folder / "tokenizer.json"))
75
+ if provider != "cpu" and hasattr(ort, "preload_dlls"):
76
+ try:
77
+ ort.preload_dlls()
78
+ except Exception:
79
+ pass
80
+ so = ort.SessionOptions()
81
+ so.intra_op_num_threads = threads
82
+ so.log_severity_level = 3
83
+ so.enable_cpu_mem_arena = False
84
+ so.add_session_config_entry("session.use_device_allocator_for_initializers", "1")
85
+ prov = ["CPUExecutionProvider"] if provider == "cpu" else [
86
+ ("CUDAExecutionProvider", {"arena_extend_strategy": "kSameAsRequested",
87
+ "cudnn_conv_algo_search": "HEURISTIC"}), "CPUExecutionProvider"]
88
+ self.s = {n: ort.InferenceSession(str(folder / f"{n}.onnx"), so, providers=prov)
89
+ for n in ("embed", "decoder", "head", "fast", "codec_enc", "codec_dec")}
90
+ self.ort = ort
91
+ self.cuda = "CUDAExecutionProvider" in self.s["decoder"].get_providers()
92
+ if provider != "cpu" and not self.cuda:
93
+ print("note: CUDA provider not available, running on the CPU", flush=True)
94
+ self.ro = ort.RunOptions()
95
+ if self.cuda: # Windows: every input length differs, and the GPU arena would keep each step's buffers
96
+ self.ro.add_run_config_entry("memory.enable_memory_arena_shrinkage", "gpu:0")
97
+ d = self.s["decoder"]
98
+ ins = {i.name: i for i in d.get_inputs()}
99
+ self.past_names = [n for n in ins if n.startswith("past_key_values.")]
100
+ pk = ins[self.past_names[0]]
101
+ self.kvh, self.hd = pk.shape[1], pk.shape[3]
102
+ self.kv_type = pk.type # tensor(bfloat16) in the bf16 / int folders
103
+ self.e_dt = np.float16 if ins["inputs_embeds"].type == "tensor(float16)" else np.float32
104
+ self.out_names = [o.name for o in d.get_outputs()]
105
+
106
+ def run(self, name, **feeds):
107
+ return self.s[name].run(None, feeds, self.ro if self.cuda else None)
108
+
109
+ def ids(self, text):
110
+ return self.tok.encode(text, add_special_tokens=False).ids
111
+
112
+ # -- the prompt ------------------------------------------------------------------------------------------------
113
+ def prompt(self, text, ref_text, ref_codes):
114
+ """Conversation.encode_for_inference of generate_long's conversation: system (instruction, reference text,
115
+ reference codes), user (text), assistant (voice): [11, S] rows = token ids, then the 10 codebooks."""
116
+ if "<|speaker:" not in ref_text:
117
+ ref_text = "<|speaker:0|>" + ref_text
118
+ parts = ["<|im_start|>system\n", "convert the provided text to speech reference to the following:\n\nText:\n",
119
+ ref_text, "\n\nSpeech:\n", None, "<|im_end|>\n", "<|im_start|>user\n", text, "<|im_end|>\n",
120
+ "<|im_start|>assistant\n<|voice|>"]
121
+ cols = []
122
+ for p in parts:
123
+ if p is None:
124
+ c = np.zeros((NCB + 1, ref_codes.shape[1]), np.int64)
125
+ c[0] = ref_codes[0] + SEM0
126
+ c[1:] = ref_codes
127
+ else:
128
+ t = self.ids(p)
129
+ c = np.zeros((NCB + 1, len(t)), np.int64)
130
+ c[0] = t
131
+ cols.append(c)
132
+ return np.concatenate(cols, 1)
133
+
134
+ # -- the dual AR -----------------------------------------------------------------------------------------------
135
+ def _step(self, x, total, past):
136
+ ort = self.ort
137
+ if not self.cuda:
138
+ res = self.s["decoder"].run(None, {"inputs_embeds": x.astype(self.e_dt), "attention_mask":
139
+ np.ones((1, total), np.int64), **past})
140
+ out = dict(zip(self.out_names, res))
141
+ return out["hidden_states"][0, -1].astype(np.float32), \
142
+ {n.replace("present", "past_key_values"): out[n] for n in self.out_names if n.startswith("present")}
143
+ io = self.s["decoder"].io_binding()
144
+ io.bind_ortvalue_input("inputs_embeds", ort.OrtValue.ortvalue_from_numpy(
145
+ np.ascontiguousarray(x.astype(self.e_dt)), "cuda", 0))
146
+ io.bind_cpu_input("attention_mask", np.ones((1, total), np.int64))
147
+ for n, v in past.items():
148
+ io.bind_ortvalue_input(n, v)
149
+ for n in self.out_names:
150
+ io.bind_output(n, "cuda", 0) if n.startswith("present") else io.bind_output(n, "cpu")
151
+ self.s["decoder"].run_with_iobinding(io, self.ro)
152
+ outs = dict(zip(self.out_names, io.get_outputs()))
153
+ return outs["hidden_states"].numpy()[0, -1].astype(np.float32), \
154
+ {n.replace("present", "past_key_values"): outs[n] for n in self.out_names if n.startswith("present")}
155
+
156
+ def frame(self, h, rng, window):
157
+ """decode_one_token_ar after the slow transformer: the main token (constrained, with the repetition-aware
158
+ fallback when `window` is given), then codebooks 1-9 from the fast transformer."""
159
+ logits = self.run("head", hidden=h[None].astype(np.float32))[0][0] # 4096 semantic + <|im_end|>
160
+ i = sample(logits, TEMP, TOP_P, TOP_K, rng)
161
+ hi = sample(logits, RAS_TEMP, RAS_TOP_P, TOP_K, rng)
162
+ tok = lambda j: IM_END if j == CBS else SEM0 + j
163
+ main = tok(i)
164
+ if window is not None and main != IM_END and (window == main).any():
165
+ main = tok(hi)
166
+ a = [min(max(main - SEM0, 0), CBS - 1)]
167
+ for _ in range(1, NCB):
168
+ lg = self.run("fast", hidden=h[None].astype(np.float32), codes=np.asarray(a, np.int64)[None])[0][0]
169
+ a.append(sample(lg, TEMP, TOP_P, TOP_K, rng))
170
+ return np.asarray([main] + a, np.int64)
171
+
172
+ def _empty_kv(self):
173
+ shape = (1, self.kvh, 0, self.hd)
174
+ if self.kv_type == "tensor(bfloat16)": # numpy has no bfloat16: uint16 data typed as bf16 (CUDA builds)
175
+ return self.ort.OrtValue.ortvalue_from_numpy_with_onnx_type(np.zeros(shape, np.uint16), 16)
176
+ z = np.zeros(shape, np.float16 if self.kv_type == "tensor(float16)" else np.float32)
177
+ return self.ort.OrtValue.ortvalue_from_numpy(z, "cuda", 0) if self.cuda else z
178
+
179
+ def generate(self, prompt, rng):
180
+ past = {n: self._empty_kv() for n in self.past_names}
181
+ x = self.run("embed", codes=prompt[None])[0]
182
+ total = prompt.shape[1]
183
+ h, past = self._step(x, total, past)
184
+ cur = self.frame(h, rng, None)
185
+ out, window = [cur], np.zeros(RAS_WIN, np.int64)
186
+ for _ in range(MAX_NEW - 1):
187
+ if cur[0] == IM_END:
188
+ break
189
+ x = self.run("embed", codes=cur[None, :, None])[0]
190
+ total += 1
191
+ h, past = self._step(x, total, past)
192
+ cur = self.frame(h, rng, window)
193
+ window = np.roll(window, -1)
194
+ window[-1] = cur[0]
195
+ out.append(cur)
196
+ codes = np.stack(out, 1)[1:] # [10, frames]
197
+ return codes[:, :-1] if out[-1][0] == IM_END else codes
198
+
199
+ # -- the codec -------------------------------------------------------------------------------------------------
200
+ def encode(self, wav, sr):
201
+ w = resample(wav, sr, SR)
202
+ n = math.ceil(len(w) / FRAME)
203
+ w = np.pad(w, (0, n * FRAME - len(w)))
204
+ return self.run("codec_enc", wav=w[None, None].astype(np.float32))[0][0][:, :n].astype(np.int64)
205
+
206
+ def decode(self, codes):
207
+ return self.run("codec_dec", codes=codes[None].astype(np.int64))[0].reshape(-1)
208
+
209
+ def __call__(self, text, ref_wav, ref_sr, ref_text, seed=0):
210
+ rng = np.random.default_rng(seed)
211
+ w = np.asarray(ref_wav, np.float32)
212
+ w = w.mean(-1) if w.ndim > 1 else w
213
+ codes = self.generate(self.prompt(text, ref_text, self.encode(w, ref_sr)), rng)
214
+ if codes.shape[1] == 0:
215
+ return np.zeros(0, np.float32), SR
216
+ return self.decode(codes).astype(np.float32), SR
217
+
218
+
219
+ if __name__ == "__main__":
220
+ import argparse
221
+ import soundfile as sf
222
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
223
+ ap.add_argument("text"); ap.add_argument("output")
224
+ ap.add_argument("--ref", required=True); ap.add_argument("--ref-text", required=True)
225
+ ap.add_argument("--dir", default=str(Path(__file__).resolve().parent))
226
+ ap.add_argument("--cuda", action="store_true"); ap.add_argument("--seed", type=int, default=0)
227
+ a = ap.parse_args()
228
+ w, sr = sf.read(a.ref, dtype="float32", always_2d=True)
229
+ tts = FishS2Pro(a.dir, "cuda" if a.cuda else "cpu")
230
+ y, osr = tts(a.text, w.mean(1), sr, a.ref_text, a.seed)
231
+ sf.write(a.output, y, osr)
int8/special_tokens_map.json ADDED
The diff for this file is too large to render. See raw diff
 
int8/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f24e08099d45a8adf3f52f5f0b03276e433bb9d689bb15fcbcc48ce58744588b
3
+ size 12217872
int8/tokenizer_config.json ADDED
The diff for this file is too large to render. See raw diff