Akash Chavda commited on
Commit
ab2e354
·
1 Parent(s): 547826f

feat: update modal with new code

Browse files
.DS_Store ADDED
Binary file (10.2 kB). View file
 
Dockerfile CHANGED
@@ -1,6 +1,6 @@
1
  # syntax=docker/dockerfile:1
2
 
3
- FROM nvidia/cuda:11.6.2-cudnn8-runtime-ubuntu20.04
4
 
5
  EXPOSE 7865
6
 
@@ -8,27 +8,9 @@ WORKDIR /app
8
 
9
  COPY . .
10
 
11
- # Install dependenceis to add PPAs
12
- RUN apt-get update && \
13
- apt-get install -y -qq ffmpeg aria2 && apt clean && \
14
- apt-get install -y software-properties-common && \
15
- apt-get clean && \
16
- rm -rf /var/lib/apt/lists/*
17
 
18
- # Add the deadsnakes PPA to get Python 3.9
19
- RUN add-apt-repository ppa:deadsnakes/ppa
20
-
21
- # Install Python 3.9 and pip
22
- RUN apt-get update && \
23
- apt-get install -y build-essential python-dev python3-dev python3.9-distutils python3.9-dev python3.9 curl && \
24
- apt-get clean && \
25
- update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.9 1 && \
26
- curl https://bootstrap.pypa.io/get-pip.py | python3.9
27
-
28
- # Set Python 3.9 as the default
29
- RUN update-alternatives --install /usr/bin/python python /usr/bin/python3.9 1
30
-
31
- RUN python3 -m pip install --no-cache-dir -r requirements.txt
32
 
33
  RUN aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/main/pretrained_v2/D40k.pth -d assets/pretrained_v2/ -o D40k.pth
34
  RUN aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/main/pretrained_v2/G40k.pth -d assets/pretrained_v2/ -o G40k.pth
 
1
  # syntax=docker/dockerfile:1
2
 
3
+ FROM python:3.10-bullseye
4
 
5
  EXPOSE 7865
6
 
 
8
 
9
  COPY . .
10
 
11
+ RUN apt update && apt install -y -qq ffmpeg aria2 && apt clean
 
 
 
 
 
12
 
13
+ RUN pip3 install --no-cache-dir -r requirements.txt
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  RUN aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/main/pretrained_v2/D40k.pth -d assets/pretrained_v2/ -o D40k.pth
16
  RUN aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/main/pretrained_v2/G40k.pth -d assets/pretrained_v2/ -o G40k.pth
GUI.py ADDED
@@ -0,0 +1,1410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, sys
2
+ import datetime, subprocess
3
+ from mega import Mega
4
+ now_dir = os.getcwd()
5
+ sys.path.append(now_dir)
6
+ import logging
7
+ import shutil
8
+ import threading
9
+ import traceback
10
+ import warnings
11
+ from random import shuffle
12
+ from subprocess import Popen
13
+ from time import sleep
14
+ import json
15
+ import pathlib
16
+
17
+ import fairseq
18
+ import faiss
19
+ import gradio as gr
20
+ import numpy as np
21
+ import torch
22
+ from dotenv import load_dotenv
23
+ from sklearn.cluster import MiniBatchKMeans
24
+
25
+ from configs.config import Config
26
+ from i18n.i18n import I18nAuto
27
+ from infer.lib.train.process_ckpt import (
28
+ change_info,
29
+ extract_small_model,
30
+ merge,
31
+ show_info,
32
+ )
33
+ from infer.modules.uvr5.modules import uvr
34
+ from infer.modules.vc.modules import VC
35
+ logging.getLogger("numba").setLevel(logging.WARNING)
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+ tmp = os.path.join(now_dir, "TEMP")
40
+ shutil.rmtree(tmp, ignore_errors=True)
41
+ shutil.rmtree("%s/runtime/Lib/site-packages/infer_pack" % (now_dir), ignore_errors=True)
42
+ shutil.rmtree("%s/runtime/Lib/site-packages/uvr5_pack" % (now_dir), ignore_errors=True)
43
+ os.makedirs(tmp, exist_ok=True)
44
+ os.makedirs(os.path.join(now_dir, "logs"), exist_ok=True)
45
+ os.makedirs(os.path.join(now_dir, "assets/weights"), exist_ok=True)
46
+ os.environ["TEMP"] = tmp
47
+ warnings.filterwarnings("ignore")
48
+ torch.manual_seed(114514)
49
+
50
+
51
+ load_dotenv()
52
+ config = Config()
53
+ vc = VC(config)
54
+
55
+ if config.dml == True:
56
+
57
+ def forward_dml(ctx, x, scale):
58
+ ctx.scale = scale
59
+ res = x.clone().detach()
60
+ return res
61
+
62
+ fairseq.modules.grad_multiply.GradMultiply.forward = forward_dml
63
+ i18n = I18nAuto()
64
+ logger.info(i18n)
65
+ # 判断是否有能用来训练和加速推理的N卡
66
+ ngpu = torch.cuda.device_count()
67
+ gpu_infos = []
68
+ mem = []
69
+ if_gpu_ok = False
70
+
71
+ if torch.cuda.is_available() or ngpu != 0:
72
+ for i in range(ngpu):
73
+ gpu_name = torch.cuda.get_device_name(i)
74
+ if any(
75
+ value in gpu_name.upper()
76
+ for value in [
77
+ "10",
78
+ "16",
79
+ "20",
80
+ "30",
81
+ "40",
82
+ "A2",
83
+ "A3",
84
+ "A4",
85
+ "P4",
86
+ "A50",
87
+ "500",
88
+ "A60",
89
+ "70",
90
+ "80",
91
+ "90",
92
+ "M4",
93
+ "T4",
94
+ "TITAN",
95
+ ]
96
+ ):
97
+ # A10#A100#V100#A40#P40#M40#K80#A4500
98
+ if_gpu_ok = True # 至少有一张能用的N卡
99
+ gpu_infos.append("%s\t%s" % (i, gpu_name))
100
+ mem.append(
101
+ int(
102
+ torch.cuda.get_device_properties(i).total_memory
103
+ / 1024
104
+ / 1024
105
+ / 1024
106
+ + 0.4
107
+ )
108
+ )
109
+ if if_gpu_ok and len(gpu_infos) > 0:
110
+ gpu_info = "\n".join(gpu_infos)
111
+ default_batch_size = min(mem) // 2
112
+ else:
113
+ gpu_info = i18n("很遗憾您这没有能用的显卡来支持您训练")
114
+ default_batch_size = 1
115
+ gpus = "-".join([i[0] for i in gpu_infos])
116
+
117
+
118
+ class ToolButton(gr.Button, gr.components.FormComponent):
119
+ """Small button with single emoji as text, fits inside gradio forms"""
120
+
121
+ def __init__(self, **kwargs):
122
+ super().__init__(variant="tool", **kwargs)
123
+
124
+ def get_block_name(self):
125
+ return "button"
126
+
127
+
128
+ weight_root = os.getenv("weight_root")
129
+ weight_uvr5_root = os.getenv("weight_uvr5_root")
130
+ index_root = os.getenv("index_root")
131
+
132
+ names = []
133
+ for name in os.listdir(weight_root):
134
+ if name.endswith(".pth"):
135
+ names.append(name)
136
+ index_paths = []
137
+ for root, dirs, files in os.walk(index_root, topdown=False):
138
+ for name in files:
139
+ if name.endswith(".index") and "trained" not in name:
140
+ index_paths.append("%s/%s" % (root, name))
141
+ uvr5_names = []
142
+ for name in os.listdir(weight_uvr5_root):
143
+ if name.endswith(".pth") or "onnx" in name:
144
+ uvr5_names.append(name.replace(".pth", ""))
145
+
146
+
147
+ def change_choices():
148
+ names = []
149
+ for name in os.listdir(weight_root):
150
+ if name.endswith(".pth"):
151
+ names.append(name)
152
+ index_paths = []
153
+ for root, dirs, files in os.walk(index_root, topdown=False):
154
+ for name in files:
155
+ if name.endswith(".index") and "trained" not in name:
156
+ index_paths.append("%s/%s" % (root, name))
157
+ audio_files=[]
158
+ for filename in os.listdir("./audios"):
159
+ if filename.endswith(('.wav','.mp3','.ogg')):
160
+ audio_files.append('./audios/'+filename)
161
+ return {"choices": sorted(names), "__type__": "update"}, {
162
+ "choices": sorted(index_paths),
163
+ "__type__": "update",
164
+ }, {"choices": sorted(audio_files), "__type__": "update"}
165
+
166
+ def clean():
167
+ return {"value": "", "__type__": "update"}
168
+
169
+
170
+ def export_onnx():
171
+ from infer.modules.onnx.export import export_onnx as eo
172
+
173
+ eo()
174
+
175
+
176
+ sr_dict = {
177
+ "32k": 32000,
178
+ "40k": 40000,
179
+ "48k": 48000,
180
+ }
181
+
182
+
183
+ def if_done(done, p):
184
+ while 1:
185
+ if p.poll() is None:
186
+ sleep(0.5)
187
+ else:
188
+ break
189
+ done[0] = True
190
+
191
+
192
+ def if_done_multi(done, ps):
193
+ while 1:
194
+ # poll==None代表进程未结束
195
+ # 只要有一个进程未结束都不停
196
+ flag = 1
197
+ for p in ps:
198
+ if p.poll() is None:
199
+ flag = 0
200
+ sleep(0.5)
201
+ break
202
+ if flag == 1:
203
+ break
204
+ done[0] = True
205
+
206
+
207
+ def preprocess_dataset(trainset_dir, exp_dir, sr, n_p):
208
+ sr = sr_dict[sr]
209
+ os.makedirs("%s/logs/%s" % (now_dir, exp_dir), exist_ok=True)
210
+ f = open("%s/logs/%s/preprocess.log" % (now_dir, exp_dir), "w")
211
+ f.close()
212
+ per = 3.0 if config.is_half else 3.7
213
+ cmd = '"%s" infer/modules/train/preprocess.py "%s" %s %s "%s/logs/%s" %s %.1f' % (
214
+ config.python_cmd,
215
+ trainset_dir,
216
+ sr,
217
+ n_p,
218
+ now_dir,
219
+ exp_dir,
220
+ config.noparallel,
221
+ per,
222
+ )
223
+ logger.info(cmd)
224
+ p = Popen(cmd, shell=True) # , stdin=PIPE, stdout=PIPE,stderr=PIPE,cwd=now_dir
225
+ ###煞笔gr, popen read都非得全跑完了再一次性读取, 不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读
226
+ done = [False]
227
+ threading.Thread(
228
+ target=if_done,
229
+ args=(
230
+ done,
231
+ p,
232
+ ),
233
+ ).start()
234
+ while 1:
235
+ with open("%s/logs/%s/preprocess.log" % (now_dir, exp_dir), "r") as f:
236
+ yield (f.read())
237
+ sleep(1)
238
+ if done[0]:
239
+ break
240
+ with open("%s/logs/%s/preprocess.log" % (now_dir, exp_dir), "r") as f:
241
+ log = f.read()
242
+ logger.info(log)
243
+ yield log
244
+
245
+
246
+ # but2.click(extract_f0,[gpus6,np7,f0method8,if_f0_3,trainset_dir4],[info2])
247
+ def extract_f0_feature(gpus, n_p, f0method, if_f0, exp_dir, version19, gpus_rmvpe):
248
+ gpus = gpus.split("-")
249
+ os.makedirs("%s/logs/%s" % (now_dir, exp_dir), exist_ok=True)
250
+ f = open("%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "w")
251
+ f.close()
252
+ if if_f0:
253
+ if f0method != "rmvpe_gpu":
254
+ cmd = (
255
+ '"%s" infer/modules/train/extract/extract_f0_print.py "%s/logs/%s" %s %s'
256
+ % (
257
+ config.python_cmd,
258
+ now_dir,
259
+ exp_dir,
260
+ n_p,
261
+ f0method,
262
+ )
263
+ )
264
+ logger.info(cmd)
265
+ p = Popen(
266
+ cmd, shell=True, cwd=now_dir
267
+ ) # , stdin=PIPE, stdout=PIPE,stderr=PIPE
268
+ ###煞笔gr, popen read都非得全跑完了再一次性读取, 不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读
269
+ done = [False]
270
+ threading.Thread(
271
+ target=if_done,
272
+ args=(
273
+ done,
274
+ p,
275
+ ),
276
+ ).start()
277
+ else:
278
+ if gpus_rmvpe != "-":
279
+ gpus_rmvpe = gpus_rmvpe.split("-")
280
+ leng = len(gpus_rmvpe)
281
+ ps = []
282
+ for idx, n_g in enumerate(gpus_rmvpe):
283
+ cmd = (
284
+ '"%s" infer/modules/train/extract/extract_f0_rmvpe.py %s %s %s "%s/logs/%s" %s '
285
+ % (
286
+ config.python_cmd,
287
+ leng,
288
+ idx,
289
+ n_g,
290
+ now_dir,
291
+ exp_dir,
292
+ config.is_half,
293
+ )
294
+ )
295
+ logger.info(cmd)
296
+ p = Popen(
297
+ cmd, shell=True, cwd=now_dir
298
+ ) # , shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=now_dir
299
+ ps.append(p)
300
+ ###煞笔gr, popen read都非得全跑完了再一次性读取, 不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读
301
+ done = [False]
302
+ threading.Thread(
303
+ target=if_done_multi, #
304
+ args=(
305
+ done,
306
+ ps,
307
+ ),
308
+ ).start()
309
+ else:
310
+ cmd = (
311
+ config.python_cmd
312
+ + ' infer/modules/train/extract/extract_f0_rmvpe_dml.py "%s/logs/%s" '
313
+ % (
314
+ now_dir,
315
+ exp_dir,
316
+ )
317
+ )
318
+ logger.info(cmd)
319
+ p = Popen(
320
+ cmd, shell=True, cwd=now_dir
321
+ ) # , shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=now_dir
322
+ p.wait()
323
+ done = [True]
324
+ while 1:
325
+ with open(
326
+ "%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "r"
327
+ ) as f:
328
+ yield (f.read())
329
+ sleep(1)
330
+ if done[0]:
331
+ break
332
+ with open("%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "r") as f:
333
+ log = f.read()
334
+ logger.info(log)
335
+ yield log
336
+ ####对不同part分别开多进程
337
+ """
338
+ n_part=int(sys.argv[1])
339
+ i_part=int(sys.argv[2])
340
+ i_gpu=sys.argv[3]
341
+ exp_dir=sys.argv[4]
342
+ os.environ["CUDA_VISIBLE_DEVICES"]=str(i_gpu)
343
+ """
344
+ leng = len(gpus)
345
+ ps = []
346
+ for idx, n_g in enumerate(gpus):
347
+ cmd = (
348
+ '"%s" infer/modules/train/extract_feature_print.py %s %s %s %s "%s/logs/%s" %s'
349
+ % (
350
+ config.python_cmd,
351
+ config.device,
352
+ leng,
353
+ idx,
354
+ n_g,
355
+ now_dir,
356
+ exp_dir,
357
+ version19,
358
+ )
359
+ )
360
+ logger.info(cmd)
361
+ p = Popen(
362
+ cmd, shell=True, cwd=now_dir
363
+ ) # , shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=now_dir
364
+ ps.append(p)
365
+ ###煞笔gr, popen read都非得全跑完了再一次性读取, 不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读
366
+ done = [False]
367
+ threading.Thread(
368
+ target=if_done_multi,
369
+ args=(
370
+ done,
371
+ ps,
372
+ ),
373
+ ).start()
374
+ while 1:
375
+ with open("%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "r") as f:
376
+ yield (f.read())
377
+ sleep(1)
378
+ if done[0]:
379
+ break
380
+ with open("%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "r") as f:
381
+ log = f.read()
382
+ logger.info(log)
383
+ yield log
384
+
385
+
386
+ def get_pretrained_models(path_str, f0_str, sr2):
387
+ if_pretrained_generator_exist = os.access(
388
+ "assets/pretrained%s/%sG%s.pth" % (path_str, f0_str, sr2), os.F_OK
389
+ )
390
+ if_pretrained_discriminator_exist = os.access(
391
+ "assets/pretrained%s/%sD%s.pth" % (path_str, f0_str, sr2), os.F_OK
392
+ )
393
+ if not if_pretrained_generator_exist:
394
+ logger.warn(
395
+ "assets/pretrained%s/%sG%s.pth not exist, will not use pretrained model",
396
+ path_str,
397
+ f0_str,
398
+ sr2,
399
+ )
400
+ if not if_pretrained_discriminator_exist:
401
+ logger.warn(
402
+ "assets/pretrained%s/%sD%s.pth not exist, will not use pretrained model",
403
+ path_str,
404
+ f0_str,
405
+ sr2,
406
+ )
407
+ return (
408
+ "assets/pretrained%s/%sG%s.pth" % (path_str, f0_str, sr2)
409
+ if if_pretrained_generator_exist
410
+ else "",
411
+ "assets/pretrained%s/%sD%s.pth" % (path_str, f0_str, sr2)
412
+ if if_pretrained_discriminator_exist
413
+ else "",
414
+ )
415
+
416
+
417
+ def change_sr2(sr2, if_f0_3, version19):
418
+ path_str = "" if version19 == "v1" else "_v2"
419
+ f0_str = "f0" if if_f0_3 else ""
420
+ return get_pretrained_models(path_str, f0_str, sr2)
421
+
422
+
423
+ def change_version19(sr2, if_f0_3, version19):
424
+ path_str = "" if version19 == "v1" else "_v2"
425
+ if sr2 == "32k" and version19 == "v1":
426
+ sr2 = "40k"
427
+ to_return_sr2 = (
428
+ {"choices": ["40k", "48k"], "__type__": "update", "value": sr2}
429
+ if version19 == "v1"
430
+ else {"choices": ["40k", "48k", "32k"], "__type__": "update", "value": sr2}
431
+ )
432
+ f0_str = "f0" if if_f0_3 else ""
433
+ return (
434
+ *get_pretrained_models(path_str, f0_str, sr2),
435
+ to_return_sr2,
436
+ )
437
+
438
+
439
+ def change_f0(if_f0_3, sr2, version19): # f0method8,pretrained_G14,pretrained_D15
440
+ path_str = "" if version19 == "v1" else "_v2"
441
+ return (
442
+ {"visible": if_f0_3, "__type__": "update"},
443
+ *get_pretrained_models(path_str, "f0", sr2),
444
+ )
445
+
446
+
447
+ # but3.click(click_train,[exp_dir1,sr2,if_f0_3,save_epoch10,total_epoch11,batch_size12,if_save_latest13,pretrained_G14,pretrained_D15,gpus16])
448
+ def click_train(
449
+ exp_dir1,
450
+ sr2,
451
+ if_f0_3,
452
+ spk_id5,
453
+ save_epoch10,
454
+ total_epoch11,
455
+ batch_size12,
456
+ if_save_latest13,
457
+ pretrained_G14,
458
+ pretrained_D15,
459
+ gpus16,
460
+ if_cache_gpu17,
461
+ if_save_every_weights18,
462
+ version19,
463
+ ):
464
+ # 生成filelist
465
+ exp_dir = "%s/logs/%s" % (now_dir, exp_dir1)
466
+ os.makedirs(exp_dir, exist_ok=True)
467
+ gt_wavs_dir = "%s/0_gt_wavs" % (exp_dir)
468
+ feature_dir = (
469
+ "%s/3_feature256" % (exp_dir)
470
+ if version19 == "v1"
471
+ else "%s/3_feature768" % (exp_dir)
472
+ )
473
+ if if_f0_3:
474
+ f0_dir = "%s/2a_f0" % (exp_dir)
475
+ f0nsf_dir = "%s/2b-f0nsf" % (exp_dir)
476
+ names = (
477
+ set([name.split(".")[0] for name in os.listdir(gt_wavs_dir)])
478
+ & set([name.split(".")[0] for name in os.listdir(feature_dir)])
479
+ & set([name.split(".")[0] for name in os.listdir(f0_dir)])
480
+ & set([name.split(".")[0] for name in os.listdir(f0nsf_dir)])
481
+ )
482
+ else:
483
+ names = set([name.split(".")[0] for name in os.listdir(gt_wavs_dir)]) & set(
484
+ [name.split(".")[0] for name in os.listdir(feature_dir)]
485
+ )
486
+ opt = []
487
+ for name in names:
488
+ if if_f0_3:
489
+ opt.append(
490
+ "%s/%s.wav|%s/%s.npy|%s/%s.wav.npy|%s/%s.wav.npy|%s"
491
+ % (
492
+ gt_wavs_dir.replace("\\", "\\\\"),
493
+ name,
494
+ feature_dir.replace("\\", "\\\\"),
495
+ name,
496
+ f0_dir.replace("\\", "\\\\"),
497
+ name,
498
+ f0nsf_dir.replace("\\", "\\\\"),
499
+ name,
500
+ spk_id5,
501
+ )
502
+ )
503
+ else:
504
+ opt.append(
505
+ "%s/%s.wav|%s/%s.npy|%s"
506
+ % (
507
+ gt_wavs_dir.replace("\\", "\\\\"),
508
+ name,
509
+ feature_dir.replace("\\", "\\\\"),
510
+ name,
511
+ spk_id5,
512
+ )
513
+ )
514
+ fea_dim = 256 if version19 == "v1" else 768
515
+ if if_f0_3:
516
+ for _ in range(2):
517
+ opt.append(
518
+ "%s/logs/mute/0_gt_wavs/mute%s.wav|%s/logs/mute/3_feature%s/mute.npy|%s/logs/mute/2a_f0/mute.wav.npy|%s/logs/mute/2b-f0nsf/mute.wav.npy|%s"
519
+ % (now_dir, sr2, now_dir, fea_dim, now_dir, now_dir, spk_id5)
520
+ )
521
+ else:
522
+ for _ in range(2):
523
+ opt.append(
524
+ "%s/logs/mute/0_gt_wavs/mute%s.wav|%s/logs/mute/3_feature%s/mute.npy|%s"
525
+ % (now_dir, sr2, now_dir, fea_dim, spk_id5)
526
+ )
527
+ shuffle(opt)
528
+ with open("%s/filelist.txt" % exp_dir, "w") as f:
529
+ f.write("\n".join(opt))
530
+ logger.debug("Write filelist done")
531
+ # 生成config#无需生成config
532
+ # cmd = python_cmd + " train_nsf_sim_cache_sid_load_pretrain.py -e mi-test -sr 40k -f0 1 -bs 4 -g 0 -te 10 -se 5 -pg pretrained/f0G40k.pth -pd pretrained/f0D40k.pth -l 1 -c 0"
533
+ logger.info("Use gpus: %s", str(gpus16))
534
+ if pretrained_G14 == "":
535
+ logger.info("No pretrained Generator")
536
+ if pretrained_D15 == "":
537
+ logger.info("No pretrained Discriminator")
538
+ if version19 == "v1" or sr2 == "40k":
539
+ config_path = "v1/%s.json" % sr2
540
+ else:
541
+ config_path = "v2/%s.json" % sr2
542
+ config_save_path = os.path.join(exp_dir, "config.json")
543
+ if not pathlib.Path(config_save_path).exists():
544
+ with open(config_save_path, "w", encoding="utf-8") as f:
545
+ json.dump(
546
+ config.json_config[config_path],
547
+ f,
548
+ ensure_ascii=False,
549
+ indent=4,
550
+ sort_keys=True,
551
+ )
552
+ f.write("\n")
553
+ if gpus16:
554
+ cmd = (
555
+ '"%s" infer/modules/train/train.py -e "%s" -sr %s -f0 %s -bs %s -g %s -te %s -se %s %s %s -l %s -c %s -sw %s -v %s'
556
+ % (
557
+ config.python_cmd,
558
+ exp_dir1,
559
+ sr2,
560
+ 1 if if_f0_3 else 0,
561
+ batch_size12,
562
+ gpus16,
563
+ total_epoch11,
564
+ save_epoch10,
565
+ "-pg %s" % pretrained_G14 if pretrained_G14 != "" else "",
566
+ "-pd %s" % pretrained_D15 if pretrained_D15 != "" else "",
567
+ 1 if if_save_latest13 == i18n("是") else 0,
568
+ 1 if if_cache_gpu17 == i18n("是") else 0,
569
+ 1 if if_save_every_weights18 == i18n("是") else 0,
570
+ version19,
571
+ )
572
+ )
573
+ else:
574
+ cmd = (
575
+ '"%s" infer/modules/train/train.py -e "%s" -sr %s -f0 %s -bs %s -te %s -se %s %s %s -l %s -c %s -sw %s -v %s'
576
+ % (
577
+ config.python_cmd,
578
+ exp_dir1,
579
+ sr2,
580
+ 1 if if_f0_3 else 0,
581
+ batch_size12,
582
+ total_epoch11,
583
+ save_epoch10,
584
+ "-pg %s" % pretrained_G14 if pretrained_G14 != "" else "",
585
+ "-pd %s" % pretrained_D15 if pretrained_D15 != "" else "",
586
+ 1 if if_save_latest13 == i18n("是") else 0,
587
+ 1 if if_cache_gpu17 == i18n("是") else 0,
588
+ 1 if if_save_every_weights18 == i18n("是") else 0,
589
+ version19,
590
+ )
591
+ )
592
+ logger.info(cmd)
593
+ p = Popen(cmd, shell=True, cwd=now_dir)
594
+ p.wait()
595
+ return "训练结束, 您可查看控制台训练日志或实验文件夹下的train.log"
596
+
597
+
598
+ # but4.click(train_index, [exp_dir1], info3)
599
+ def train_index(exp_dir1, version19):
600
+ # exp_dir = "%s/logs/%s" % (now_dir, exp_dir1)
601
+ exp_dir = "logs/%s" % (exp_dir1)
602
+ os.makedirs(exp_dir, exist_ok=True)
603
+ feature_dir = (
604
+ "%s/3_feature256" % (exp_dir)
605
+ if version19 == "v1"
606
+ else "%s/3_feature768" % (exp_dir)
607
+ )
608
+ if not os.path.exists(feature_dir):
609
+ return "请先进行特征提取!"
610
+ listdir_res = list(os.listdir(feature_dir))
611
+ if len(listdir_res) == 0:
612
+ return "请先进行特征提取!"
613
+ infos = []
614
+ npys = []
615
+ for name in sorted(listdir_res):
616
+ phone = np.load("%s/%s" % (feature_dir, name))
617
+ npys.append(phone)
618
+ big_npy = np.concatenate(npys, 0)
619
+ big_npy_idx = np.arange(big_npy.shape[0])
620
+ np.random.shuffle(big_npy_idx)
621
+ big_npy = big_npy[big_npy_idx]
622
+ if big_npy.shape[0] > 2e5:
623
+ infos.append("Trying doing kmeans %s shape to 10k centers." % big_npy.shape[0])
624
+ yield "\n".join(infos)
625
+ try:
626
+ big_npy = (
627
+ MiniBatchKMeans(
628
+ n_clusters=10000,
629
+ verbose=True,
630
+ batch_size=256 * config.n_cpu,
631
+ compute_labels=False,
632
+ init="random",
633
+ )
634
+ .fit(big_npy)
635
+ .cluster_centers_
636
+ )
637
+ except:
638
+ info = traceback.format_exc()
639
+ logger.info(info)
640
+ infos.append(info)
641
+ yield "\n".join(infos)
642
+
643
+ np.save("%s/total_fea.npy" % exp_dir, big_npy)
644
+ n_ivf = min(int(16 * np.sqrt(big_npy.shape[0])), big_npy.shape[0] // 39)
645
+ infos.append("%s,%s" % (big_npy.shape, n_ivf))
646
+ yield "\n".join(infos)
647
+ index = faiss.index_factory(256 if version19 == "v1" else 768, "IVF%s,Flat" % n_ivf)
648
+ # index = faiss.index_factory(256if version19=="v1"else 768, "IVF%s,PQ128x4fs,RFlat"%n_ivf)
649
+ infos.append("training")
650
+ yield "\n".join(infos)
651
+ index_ivf = faiss.extract_index_ivf(index) #
652
+ index_ivf.nprobe = 1
653
+ index.train(big_npy)
654
+ faiss.write_index(
655
+ index,
656
+ "%s/trained_IVF%s_Flat_nprobe_%s_%s_%s.index"
657
+ % (exp_dir, n_ivf, index_ivf.nprobe, exp_dir1, version19),
658
+ )
659
+
660
+ infos.append("adding")
661
+ yield "\n".join(infos)
662
+ batch_size_add = 8192
663
+ for i in range(0, big_npy.shape[0], batch_size_add):
664
+ index.add(big_npy[i : i + batch_size_add])
665
+ faiss.write_index(
666
+ index,
667
+ "%s/added_IVF%s_Flat_nprobe_%s_%s_%s.index"
668
+ % (exp_dir, n_ivf, index_ivf.nprobe, exp_dir1, version19),
669
+ )
670
+ infos.append(
671
+ "成功构建索引,added_IVF%s_Flat_nprobe_%s_%s_%s.index"
672
+ % (n_ivf, index_ivf.nprobe, exp_dir1, version19)
673
+ )
674
+ # faiss.write_index(index, '%s/added_IVF%s_Flat_FastScan_%s.index'%(exp_dir,n_ivf,version19))
675
+ # infos.append("成功构建索引,added_IVF%s_Flat_FastScan_%s.index"%(n_ivf,version19))
676
+ yield "\n".join(infos)
677
+
678
+
679
+ # but5.click(train1key, [exp_dir1, sr2, if_f0_3, trainset_dir4, spk_id5, gpus6, np7, f0method8, save_epoch10, total_epoch11, batch_size12, if_save_latest13, pretrained_G14, pretrained_D15, gpus16, if_cache_gpu17], info3)
680
+ def train1key(
681
+ exp_dir1,
682
+ sr2,
683
+ if_f0_3,
684
+ trainset_dir4,
685
+ spk_id5,
686
+ np7,
687
+ f0method8,
688
+ save_epoch10,
689
+ total_epoch11,
690
+ batch_size12,
691
+ if_save_latest13,
692
+ pretrained_G14,
693
+ pretrained_D15,
694
+ gpus16,
695
+ if_cache_gpu17,
696
+ if_save_every_weights18,
697
+ version19,
698
+ gpus_rmvpe,
699
+ ):
700
+ infos = []
701
+
702
+ def get_info_str(strr):
703
+ infos.append(strr)
704
+ return "\n".join(infos)
705
+
706
+ ####### step1:处理数据
707
+ yield get_info_str(i18n("step1:正在处理数据"))
708
+ [get_info_str(_) for _ in preprocess_dataset(trainset_dir4, exp_dir1, sr2, np7)]
709
+
710
+ ####### step2a:提取音高
711
+ yield get_info_str(i18n("step2:正在提取音高&正在提取特征"))
712
+ [
713
+ get_info_str(_)
714
+ for _ in extract_f0_feature(
715
+ gpus16, np7, f0method8, if_f0_3, exp_dir1, version19, gpus_rmvpe
716
+ )
717
+ ]
718
+
719
+ ####### step3a:训练模型
720
+ yield get_info_str(i18n("step3a:正在训练模型"))
721
+ click_train(
722
+ exp_dir1,
723
+ sr2,
724
+ if_f0_3,
725
+ spk_id5,
726
+ save_epoch10,
727
+ total_epoch11,
728
+ batch_size12,
729
+ if_save_latest13,
730
+ pretrained_G14,
731
+ pretrained_D15,
732
+ gpus16,
733
+ if_cache_gpu17,
734
+ if_save_every_weights18,
735
+ version19,
736
+ )
737
+ yield get_info_str(i18n("训练结束, 您可查看控制台训练日志或实验文件夹下的train.log"))
738
+
739
+ ####### step3b:训练索引
740
+ [get_info_str(_) for _ in train_index(exp_dir1, version19)]
741
+ yield get_info_str(i18n("全流程结束!"))
742
+
743
+
744
+ # ckpt_path2.change(change_info_,[ckpt_path2],[sr__,if_f0__])
745
+ def change_info_(ckpt_path):
746
+ if not os.path.exists(ckpt_path.replace(os.path.basename(ckpt_path), "train.log")):
747
+ return {"__type__": "update"}, {"__type__": "update"}, {"__type__": "update"}
748
+ try:
749
+ with open(
750
+ ckpt_path.replace(os.path.basename(ckpt_path), "train.log"), "r"
751
+ ) as f:
752
+ info = eval(f.read().strip("\n").split("\n")[0].split("\t")[-1])
753
+ sr, f0 = info["sample_rate"], info["if_f0"]
754
+ version = "v2" if ("version" in info and info["version"] == "v2") else "v1"
755
+ return sr, str(f0), version
756
+ except:
757
+ traceback.print_exc()
758
+ return {"__type__": "update"}, {"__type__": "update"}, {"__type__": "update"}
759
+
760
+
761
+ F0GPUVisible = config.dml == False
762
+
763
+
764
+ def change_f0_method(f0method8):
765
+ if f0method8 == "rmvpe_gpu":
766
+ visible = F0GPUVisible
767
+ else:
768
+ visible = False
769
+ return {"visible": visible, "__type__": "update"}
770
+
771
+ def find_model():
772
+ if len(names) > 0:
773
+ vc.get_vc(sorted(names)[0],None,None)
774
+ return sorted(names)[0]
775
+ else:
776
+ try:
777
+ gr.Info("Do not forget to choose a model.")
778
+ except:
779
+ pass
780
+ return ''
781
+
782
+ def find_audios(index=False):
783
+ audio_files=[]
784
+ if not os.path.exists('./audios'): os.mkdir("./audios")
785
+ for filename in os.listdir("./audios"):
786
+ if filename.endswith(('.wav','.mp3','.ogg')):
787
+ audio_files.append("./audios/"+filename)
788
+ if index:
789
+ if len(audio_files) > 0: return sorted(audio_files)[0]
790
+ else: return ""
791
+ elif len(audio_files) > 0: return sorted(audio_files)
792
+ else: return []
793
+
794
+ def get_index():
795
+ if find_model() != '':
796
+ chosen_model=sorted(names)[0].split(".")[0]
797
+ logs_path="./logs/"+chosen_model
798
+ if os.path.exists(logs_path):
799
+ for file in os.listdir(logs_path):
800
+ if file.endswith(".index"):
801
+ return os.path.join(logs_path, file)
802
+ return ''
803
+ else:
804
+ return ''
805
+
806
+ def get_indexes():
807
+ indexes_list=[]
808
+ for dirpath, dirnames, filenames in os.walk("./logs/"):
809
+ for filename in filenames:
810
+ if filename.endswith(".index"):
811
+ indexes_list.append(os.path.join(dirpath,filename))
812
+ if len(indexes_list) > 0:
813
+ return indexes_list
814
+ else:
815
+ return ''
816
+
817
+ def save_wav(file):
818
+ try:
819
+ file_path=file.name
820
+ shutil.move(file_path,'./audios')
821
+ return './audios/'+os.path.basename(file_path)
822
+ except AttributeError:
823
+ try:
824
+ new_name = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")+'.wav'
825
+ new_path='./audios/'+new_name
826
+ shutil.move(file,new_path)
827
+ return new_path
828
+ except TypeError:
829
+ return None
830
+
831
+ def download_from_url(url, model):
832
+ if url == '':
833
+ return "URL cannot be left empty."
834
+ if model =='':
835
+ return "You need to name your model. For example: My-Model"
836
+ url = url.strip()
837
+ zip_dirs = ["zips", "unzips"]
838
+ for directory in zip_dirs:
839
+ if os.path.exists(directory):
840
+ shutil.rmtree(directory)
841
+ os.makedirs("zips", exist_ok=True)
842
+ os.makedirs("unzips", exist_ok=True)
843
+ zipfile = model + '.zip'
844
+ zipfile_path = './zips/' + zipfile
845
+ try:
846
+ if "drive.google.com" in url:
847
+ subprocess.run(["gdown", url, "--fuzzy", "-O", zipfile_path])
848
+ elif "mega.nz" in url:
849
+ m = Mega()
850
+ m.download_url(url, './zips')
851
+ else:
852
+ subprocess.run(["wget", url, "-O", zipfile_path])
853
+ for filename in os.listdir("./zips"):
854
+ if filename.endswith(".zip"):
855
+ zipfile_path = os.path.join("./zips/",filename)
856
+ shutil.unpack_archive(zipfile_path, "./unzips", 'zip')
857
+ else:
858
+ return "No zipfile found."
859
+ for root, dirs, files in os.walk('./unzips'):
860
+ for file in files:
861
+ file_path = os.path.join(root, file)
862
+ if file.endswith(".index"):
863
+ os.mkdir(f'./logs/{model}')
864
+ shutil.copy2(file_path,f'./logs/{model}')
865
+ elif "G_" not in file and "D_" not in file and file.endswith(".pth"):
866
+ shutil.copy(file_path,f'./assets/weights/{model}.pth')
867
+ shutil.rmtree("zips")
868
+ shutil.rmtree("unzips")
869
+ return "Success."
870
+ except:
871
+ return "There's been an error."
872
+
873
+ def upload_to_dataset(files, dir):
874
+ if dir == '':
875
+ dir = './dataset/'+datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
876
+ if not os.path.exists(dir):
877
+ os.makedirs(dir)
878
+ for file in files:
879
+ path=file.name
880
+ shutil.copy2(path,dir)
881
+ try:
882
+ gr.Info(i18n("处理数据"))
883
+ except:
884
+ pass
885
+ return i18n("处理数据"), {"value":dir,"__type__":"update"}
886
+
887
+ with gr.Blocks(title="EasyGUI v2.9",theme=gr.themes.Base()) as app:
888
+ gr.HTML("<h1> EasyGUI v2.9 </h1>")
889
+ with gr.Tabs():
890
+ with gr.TabItem(i18n("模型推理")):
891
+ with gr.Row():
892
+ sid0 = gr.Dropdown(label=i18n("推理音色"), choices=sorted(names), value=find_model())
893
+ refresh_button = gr.Button(i18n("刷新音色列表和索引路径"), variant="primary")
894
+ #clean_button = gr.Button(i18n("卸载音色省显存"), variant="primary")
895
+ spk_item = gr.Slider(
896
+ minimum=0,
897
+ maximum=2333,
898
+ step=1,
899
+ label=i18n("请选择说话人id"),
900
+ value=0,
901
+ visible=False,
902
+ interactive=True,
903
+ )
904
+ #clean_button.click(
905
+ # fn=clean, inputs=[], outputs=[sid0], api_name="infer_clean"
906
+ #)
907
+ vc_transform0 = gr.Number(
908
+ label=i18n("变调(整数, 半音数量, 升八度12降八度-12)"), value=0
909
+ )
910
+ but0 = gr.Button(i18n("转换"), variant="primary")
911
+ with gr.Row():
912
+ with gr.Column():
913
+ with gr.Row():
914
+ dropbox = gr.File(label="Drop your audio here & hit the Reload button.")
915
+ with gr.Row():
916
+ record_button=gr.Audio(source="microphone", label="OR Record audio.", type="filepath")
917
+ with gr.Row():
918
+ input_audio0 = gr.Dropdown(
919
+ label=i18n("输入待处理音频文件路径(默认是正确格式示例)"),
920
+ value=find_audios(True),
921
+ choices=find_audios()
922
+ )
923
+ record_button.change(fn=save_wav, inputs=[record_button], outputs=[input_audio0])
924
+ dropbox.upload(fn=save_wav, inputs=[dropbox], outputs=[input_audio0])
925
+ with gr.Column():
926
+ with gr.Accordion(label=i18n("自动检测index路径,下拉式选择(dropdown)"), open=False):
927
+ file_index2 = gr.Dropdown(
928
+ label=i18n("自动检测index路径,下拉式选择(dropdown)"),
929
+ choices=get_indexes(),
930
+ interactive=True,
931
+ value=get_index()
932
+ )
933
+ index_rate1 = gr.Slider(
934
+ minimum=0,
935
+ maximum=1,
936
+ label=i18n("检索特征占比"),
937
+ value=0.66,
938
+ interactive=True,
939
+ )
940
+ vc_output2 = gr.Audio(label=i18n("输出音频(右下角三个点,点了可以下载)"))
941
+ with gr.Accordion(label=i18n("常规设置"), open=False):
942
+ f0method0 = gr.Radio(
943
+ label=i18n(
944
+ "选择音高提取算法,输入歌声可用pm提速,harvest低音好但巨慢无比,crepe效果好但吃GPU,rmvpe效果最好且微吃GPU"
945
+ ),
946
+ choices=["pm", "harvest", "crepe", "rmvpe"]
947
+ if config.dml == False
948
+ else ["pm", "harvest", "rmvpe"],
949
+ value="rmvpe",
950
+ interactive=True,
951
+ )
952
+ filter_radius0 = gr.Slider(
953
+ minimum=0,
954
+ maximum=7,
955
+ label=i18n(">=3则使用对harvest音高识别的结果使用中值滤波,数值为滤波半径,使用可以削弱哑音"),
956
+ value=3,
957
+ step=1,
958
+ interactive=True,
959
+ )
960
+ resample_sr0 = gr.Slider(
961
+ minimum=0,
962
+ maximum=48000,
963
+ label=i18n("后处理重采样至最终采样率,0为不进行重采样"),
964
+ value=0,
965
+ step=1,
966
+ interactive=True,
967
+ )
968
+ rms_mix_rate0 = gr.Slider(
969
+ minimum=0,
970
+ maximum=1,
971
+ label=i18n("输入源音量包络替换输出音量包络融合比例,越靠近1越使用输出包络"),
972
+ value=0.21,
973
+ interactive=True,
974
+ )
975
+ protect0 = gr.Slider(
976
+ minimum=0,
977
+ maximum=0.5,
978
+ label=i18n(
979
+ "保护清辅音和呼吸声,防止电音撕裂等artifact,拉满0.5不开启,调低加大保护力度但可能降低索引��果"
980
+ ),
981
+ value=0.33,
982
+ step=0.01,
983
+ interactive=True,
984
+ )
985
+ file_index1 = gr.Textbox(
986
+ label=i18n("特征检索库文件路径,为空则使用下拉的选择结果"),
987
+ value="",
988
+ interactive=True,
989
+ visible=False
990
+ )
991
+ refresh_button.click(
992
+ fn=change_choices,
993
+ inputs=[],
994
+ outputs=[sid0, file_index2, input_audio0],
995
+ api_name="infer_refresh",
996
+ )
997
+ # file_big_npy1 = gr.Textbox(
998
+ # label=i18n("特征文件路径"),
999
+ # value="E:\\codes\py39\\vits_vc_gpu_train\\logs\\mi-test-1key\\total_fea.npy",
1000
+ # interactive=True,
1001
+ # )
1002
+ with gr.Row():
1003
+ f0_file = gr.File(label=i18n("F0曲线文件, 可选, 一行一个音高, 代替默认F0及升降调"), visible=False)
1004
+ with gr.Row():
1005
+ vc_output1 = gr.Textbox(label=i18n("输出信息"))
1006
+ but0.click(
1007
+ vc.vc_single,
1008
+ [
1009
+ spk_item,
1010
+ input_audio0,
1011
+ vc_transform0,
1012
+ f0_file,
1013
+ f0method0,
1014
+ file_index1,
1015
+ file_index2,
1016
+ # file_big_npy1,
1017
+ index_rate1,
1018
+ filter_radius0,
1019
+ resample_sr0,
1020
+ rms_mix_rate0,
1021
+ protect0,
1022
+ ],
1023
+ [vc_output1, vc_output2],
1024
+ api_name="infer_convert",
1025
+ )
1026
+ with gr.Row():
1027
+ with gr.Accordion(open=False, label=i18n("批量转换, 输入待转换音频文件夹, 或上传多个音频文件, 在指定文件夹(默认opt)下输出转换的音频. ")):
1028
+ with gr.Column():
1029
+ vc_transform1 = gr.Number(
1030
+ label=i18n("变调(整数, 半音数量, 升八度12降八度-12)"), value=0
1031
+ )
1032
+ opt_input = gr.Textbox(label=i18n("指定输出文件夹"), value="opt")
1033
+ f0method1 = gr.Radio(
1034
+ label=i18n(
1035
+ "选择音高提取算法,输入歌声可用pm提速,harvest低音好但巨慢无比,crepe效果好但吃GPU,rmvpe效果最好且微吃GPU"
1036
+ ),
1037
+ choices=["pm", "harvest", "crepe", "rmvpe"]
1038
+ if config.dml == False
1039
+ else ["pm", "harvest", "rmvpe"],
1040
+ value="pm",
1041
+ interactive=True,
1042
+ )
1043
+ filter_radius1 = gr.Slider(
1044
+ minimum=0,
1045
+ maximum=7,
1046
+ label=i18n(">=3则使用对harvest音高识别的结果使用中值滤波,数值为滤波半径,使用可以削弱哑音"),
1047
+ value=3,
1048
+ step=1,
1049
+ interactive=True,
1050
+ )
1051
+ with gr.Column():
1052
+ file_index3 = gr.Textbox(
1053
+ label=i18n("特征检索库文件路径,为空则使用下拉的选择结果"),
1054
+ value="",
1055
+ interactive=True,
1056
+ visible=False
1057
+ )
1058
+ file_index4 = gr.Dropdown(
1059
+ label=i18n("自动检测index路径,下拉式选择(dropdown)"),
1060
+ choices=sorted(index_paths),
1061
+ interactive=True,
1062
+ )
1063
+ refresh_button.click(
1064
+ fn=lambda: change_choices()[1],
1065
+ inputs=[],
1066
+ outputs=file_index4,
1067
+ api_name="infer_refresh_batch",
1068
+ )
1069
+ # file_big_npy2 = gr.Textbox(
1070
+ # label=i18n("特征文件路径"),
1071
+ # value="E:\\codes\\py39\\vits_vc_gpu_train\\logs\\mi-test-1key\\total_fea.npy",
1072
+ # interactive=True,
1073
+ # )
1074
+ index_rate2 = gr.Slider(
1075
+ minimum=0,
1076
+ maximum=1,
1077
+ label=i18n("检索特��占比"),
1078
+ value=1,
1079
+ interactive=True,
1080
+ )
1081
+ with gr.Column():
1082
+ resample_sr1 = gr.Slider(
1083
+ minimum=0,
1084
+ maximum=48000,
1085
+ label=i18n("后处理重采样至最终采样率,0为不进行重采样"),
1086
+ value=0,
1087
+ step=1,
1088
+ interactive=True,
1089
+ )
1090
+ rms_mix_rate1 = gr.Slider(
1091
+ minimum=0,
1092
+ maximum=1,
1093
+ label=i18n("输入源音量包络替换输出音量包络融合比例,越靠近1越使用输出包络"),
1094
+ value=1,
1095
+ interactive=True,
1096
+ )
1097
+ protect1 = gr.Slider(
1098
+ minimum=0,
1099
+ maximum=0.5,
1100
+ label=i18n(
1101
+ "保护清辅音和呼吸声,防止电音撕裂等artifact,拉满0.5不开启,调低加大保护力度但可能降低索引效果"
1102
+ ),
1103
+ value=0.33,
1104
+ step=0.01,
1105
+ interactive=True,
1106
+ )
1107
+ with gr.Column():
1108
+ dir_input = gr.Textbox(
1109
+ label=i18n("输入待处理音频文件夹路径(去文件管理器地址栏拷就行了)"),
1110
+ value="E:\codes\py39\\test-20230416b\\todo-songs",
1111
+ )
1112
+ inputs = gr.File(
1113
+ file_count="multiple", label=i18n("也可批量输入音频文件, 二选一, 优先读文件夹")
1114
+ )
1115
+ with gr.Row():
1116
+ format1 = gr.Radio(
1117
+ label=i18n("导出文件格式"),
1118
+ choices=["wav", "flac", "mp3", "m4a"],
1119
+ value="flac",
1120
+ interactive=True,
1121
+ )
1122
+ but1 = gr.Button(i18n("转换"), variant="primary")
1123
+ vc_output3 = gr.Textbox(label=i18n("输出信息"))
1124
+ but1.click(
1125
+ vc.vc_multi,
1126
+ [
1127
+ spk_item,
1128
+ dir_input,
1129
+ opt_input,
1130
+ inputs,
1131
+ vc_transform1,
1132
+ f0method1,
1133
+ file_index3,
1134
+ file_index4,
1135
+ # file_big_npy2,
1136
+ index_rate2,
1137
+ filter_radius1,
1138
+ resample_sr1,
1139
+ rms_mix_rate1,
1140
+ protect1,
1141
+ format1,
1142
+ ],
1143
+ [vc_output3],
1144
+ api_name="infer_convert_batch",
1145
+ )
1146
+ sid0.change(
1147
+ fn=vc.get_vc,
1148
+ inputs=[sid0, protect0, protect1],
1149
+ outputs=[spk_item, protect0, protect1, file_index2, file_index4],
1150
+ )
1151
+ with gr.TabItem("Download Model"):
1152
+ with gr.Row():
1153
+ url=gr.Textbox(label="Enter the URL to the Model:")
1154
+ with gr.Row():
1155
+ model = gr.Textbox(label="Name your model:")
1156
+ download_button=gr.Button("Download")
1157
+ with gr.Row():
1158
+ status_bar=gr.Textbox(label="")
1159
+ download_button.click(fn=download_from_url, inputs=[url, model], outputs=[status_bar])
1160
+ with gr.Row():
1161
+ gr.Markdown(
1162
+ """
1163
+ ❤️ If you like the EasyGUI, help me keep it.❤️
1164
+ https://paypal.me/lesantillan
1165
+ """
1166
+ )
1167
+ with gr.TabItem(i18n("训练")):
1168
+ with gr.Row():
1169
+ with gr.Column():
1170
+ exp_dir1 = gr.Textbox(label=i18n("输入实验名"), value="My-Voice")
1171
+ np7 = gr.Slider(
1172
+ minimum=0,
1173
+ maximum=config.n_cpu,
1174
+ step=1,
1175
+ label=i18n("提取音高和处理数据使用的CPU进程数"),
1176
+ value=int(np.ceil(config.n_cpu / 1.5)),
1177
+ interactive=True,
1178
+ )
1179
+ sr2 = gr.Radio(
1180
+ label=i18n("目标采样率"),
1181
+ choices=["40k", "48k"],
1182
+ value="40k",
1183
+ interactive=True,
1184
+ visible=False
1185
+ )
1186
+ if_f0_3 = gr.Radio(
1187
+ label=i18n("模型是否带音高指导(唱歌一定要, 语音可以不要)"),
1188
+ choices=[True, False],
1189
+ value=True,
1190
+ interactive=True,
1191
+ visible=False
1192
+ )
1193
+ version19 = gr.Radio(
1194
+ label=i18n("版本"),
1195
+ choices=["v1", "v2"],
1196
+ value="v2",
1197
+ interactive=True,
1198
+ visible=False,
1199
+ )
1200
+ trainset_dir4 = gr.Textbox(
1201
+ label=i18n("输入训练文件夹路径"), value='./dataset/'+datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
1202
+ )
1203
+ easy_uploader = gr.Files(label=i18n("也可批量输入音频文件, 二选一, 优先读文件夹"),file_types=['audio'])
1204
+ but1 = gr.Button(label=i18n("处理数据"), variant="primary")
1205
+ info1 = gr.Textbox(label=i18n("输出信息"), value="")
1206
+ easy_uploader.upload(fn=upload_to_dataset, inputs=[easy_uploader, trainset_dir4], outputs=[info1, trainset_dir4])
1207
+ gpus6 = gr.Textbox(
1208
+ label=i18n("以-分隔输入使用的卡号, 例如 0-1-2 使用卡0和卡1和卡2"),
1209
+ value=gpus,
1210
+ interactive=True,
1211
+ visible=F0GPUVisible,
1212
+ )
1213
+ gpu_info9 = gr.Textbox(
1214
+ label=i18n("显卡信息"), value=gpu_info, visible=F0GPUVisible
1215
+ )
1216
+ spk_id5 = gr.Slider(
1217
+ minimum=0,
1218
+ maximum=4,
1219
+ step=1,
1220
+ label=i18n("请指定说话人id"),
1221
+ value=0,
1222
+ interactive=True,
1223
+ visible=False
1224
+ )
1225
+ but1.click(
1226
+ preprocess_dataset,
1227
+ [trainset_dir4, exp_dir1, sr2, np7],
1228
+ [info1],
1229
+ api_name="train_preprocess",
1230
+ )
1231
+ with gr.Column():
1232
+ f0method8 = gr.Radio(
1233
+ label=i18n(
1234
+ "选择音高提取算法:输入歌声可用pm提速,高质量语音但CPU差可用dio提速,harvest质量更好但慢,rmvpe效果最好且微吃CPU/GPU"
1235
+ ),
1236
+ choices=["pm", "harvest", "dio", "rmvpe", "rmvpe_gpu"],
1237
+ value="rmvpe_gpu",
1238
+ interactive=True,
1239
+ )
1240
+ gpus_rmvpe = gr.Textbox(
1241
+ label=i18n(
1242
+ "rmvpe卡号配置:以-分隔输入使用的不同进程卡号,例如0-0-1使用在卡0上跑2个进程并在卡1上跑1个进程"
1243
+ ),
1244
+ value="%s-%s" % (gpus, gpus),
1245
+ interactive=True,
1246
+ visible=F0GPUVisible,
1247
+ )
1248
+ but2 = gr.Button(i18n("特征提取"), variant="primary")
1249
+ info2 = gr.Textbox(label=i18n("输出信息"), value="", max_lines=8)
1250
+ f0method8.change(
1251
+ fn=change_f0_method,
1252
+ inputs=[f0method8],
1253
+ outputs=[gpus_rmvpe],
1254
+ )
1255
+ but2.click(
1256
+ extract_f0_feature,
1257
+ [
1258
+ gpus6,
1259
+ np7,
1260
+ f0method8,
1261
+ if_f0_3,
1262
+ exp_dir1,
1263
+ version19,
1264
+ gpus_rmvpe,
1265
+ ],
1266
+ [info2],
1267
+ api_name="train_extract_f0_feature",
1268
+ )
1269
+ with gr.Column():
1270
+ total_epoch11 = gr.Slider(
1271
+ minimum=2,
1272
+ maximum=1000,
1273
+ step=1,
1274
+ label=i18n("总训练轮数total_epoch"),
1275
+ value=150,
1276
+ interactive=True,
1277
+ )
1278
+ gpus16 = gr.Textbox(
1279
+ label=i18n("以-分隔输入使用的卡号, 例如 0-1-2 使用卡0和卡1和卡2"),
1280
+ value="0",
1281
+ interactive=True,
1282
+ visible=True
1283
+ )
1284
+ but3 = gr.Button(i18n("训练模型"), variant="primary")
1285
+ but4 = gr.Button(i18n("训练特征索引"), variant="primary")
1286
+ info3 = gr.Textbox(label=i18n("输出信息"), value="", max_lines=10)
1287
+ with gr.Accordion(label=i18n("常规设置"), open=False):
1288
+ save_epoch10 = gr.Slider(
1289
+ minimum=1,
1290
+ maximum=50,
1291
+ step=1,
1292
+ label=i18n("保存频率save_every_epoch"),
1293
+ value=25,
1294
+ interactive=True,
1295
+ )
1296
+ batch_size12 = gr.Slider(
1297
+ minimum=1,
1298
+ maximum=40,
1299
+ step=1,
1300
+ label=i18n("每张显卡的batch_size"),
1301
+ value=default_batch_size,
1302
+ interactive=True,
1303
+ )
1304
+ if_save_latest13 = gr.Radio(
1305
+ label=i18n("是否仅保存最新的ckpt文件以节省硬盘空间"),
1306
+ choices=[i18n("是"), i18n("否")],
1307
+ value=i18n("是"),
1308
+ interactive=True,
1309
+ )
1310
+ if_cache_gpu17 = gr.Radio(
1311
+ label=i18n(
1312
+ "是否缓存所有训练集至显存. 10min以下小数据可缓存以加速训练, 大数据缓存会炸显存也加不了多少速"
1313
+ ),
1314
+ choices=[i18n("是"), i18n("否")],
1315
+ value=i18n("否"),
1316
+ interactive=True,
1317
+ )
1318
+ if_save_every_weights18 = gr.Radio(
1319
+ label=i18n("是否在每次保存时间点将最终小模型保存至weights文件夹"),
1320
+ choices=[i18n("是"), i18n("否")],
1321
+ value=i18n("是"),
1322
+ interactive=True,
1323
+ )
1324
+ with gr.Row():
1325
+ pretrained_G14 = gr.Textbox(
1326
+ label=i18n("加载预训练底模G路径"),
1327
+ value="assets/pretrained_v2/f0G40k.pth",
1328
+ interactive=True,
1329
+ visible=False
1330
+ )
1331
+ pretrained_D15 = gr.Textbox(
1332
+ label=i18n("加载预训练底模D路径"),
1333
+ value="assets/pretrained_v2/f0D40k.pth",
1334
+ interactive=True,
1335
+ visible=False
1336
+ )
1337
+ sr2.change(
1338
+ change_sr2,
1339
+ [sr2, if_f0_3, version19],
1340
+ [pretrained_G14, pretrained_D15],
1341
+ )
1342
+ version19.change(
1343
+ change_version19,
1344
+ [sr2, if_f0_3, version19],
1345
+ [pretrained_G14, pretrained_D15, sr2],
1346
+ )
1347
+ if_f0_3.change(
1348
+ change_f0,
1349
+ [if_f0_3, sr2, version19],
1350
+ [f0method8, pretrained_G14, pretrained_D15],
1351
+ )
1352
+ with gr.Row():
1353
+ but5 = gr.Button(i18n("一键训练"), variant="primary", visible=False)
1354
+ but3.click(
1355
+ click_train,
1356
+ [
1357
+ exp_dir1,
1358
+ sr2,
1359
+ if_f0_3,
1360
+ spk_id5,
1361
+ save_epoch10,
1362
+ total_epoch11,
1363
+ batch_size12,
1364
+ if_save_latest13,
1365
+ pretrained_G14,
1366
+ pretrained_D15,
1367
+ gpus16,
1368
+ if_cache_gpu17,
1369
+ if_save_every_weights18,
1370
+ version19,
1371
+ ],
1372
+ info3,
1373
+ api_name="train_start",
1374
+ )
1375
+ but4.click(train_index, [exp_dir1, version19], info3)
1376
+ but5.click(
1377
+ train1key,
1378
+ [
1379
+ exp_dir1,
1380
+ sr2,
1381
+ if_f0_3,
1382
+ trainset_dir4,
1383
+ spk_id5,
1384
+ np7,
1385
+ f0method8,
1386
+ save_epoch10,
1387
+ total_epoch11,
1388
+ batch_size12,
1389
+ if_save_latest13,
1390
+ pretrained_G14,
1391
+ pretrained_D15,
1392
+ gpus16,
1393
+ if_cache_gpu17,
1394
+ if_save_every_weights18,
1395
+ version19,
1396
+ gpus_rmvpe,
1397
+ ],
1398
+ info3,
1399
+ api_name="train_start_all",
1400
+ )
1401
+
1402
+ if config.iscolab:
1403
+ app.queue(concurrency_count=511, max_size=1022).launch(share=True)
1404
+ else:
1405
+ app.queue(concurrency_count=511, max_size=1022).launch(
1406
+ server_name="0.0.0.0",
1407
+ inbrowser=not config.noautoopen,
1408
+ server_port=config.listen_port,
1409
+ quiet=True,
1410
+ )
a.png ADDED
app.py CHANGED
The diff for this file is too large to render. See raw diff
 
audios/somegirl.mp3 ADDED
Binary file (32.2 kB). View file
 
audios/someguy.mp3 ADDED
Binary file (24.9 kB). View file
 
audios/unachica.mp3 ADDED
Binary file (36.4 kB). View file
 
audios/unchico.mp3 ADDED
Binary file (35.9 kB). View file
 
configs/config.py CHANGED
@@ -5,13 +5,10 @@ import json
5
  from multiprocessing import cpu_count
6
 
7
  import torch
8
-
9
  try:
10
- import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
11
-
12
  if torch.xpu.is_available():
13
  from infer.modules.ipex import ipex_init
14
-
15
  ipex_init()
16
  except Exception:
17
  pass
 
5
  from multiprocessing import cpu_count
6
 
7
  import torch
 
8
  try:
9
+ import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
 
10
  if torch.xpu.is_available():
11
  from infer.modules.ipex import ipex_init
 
12
  ipex_init()
13
  except Exception:
14
  pass
docker-compose.yml CHANGED
@@ -10,11 +10,4 @@ services:
10
  - ./opt:/app/opt
11
  # - ./dataset:/app/dataset # you can use this folder in order to provide your dataset for model training
12
  ports:
13
- - 7865:7865
14
- deploy:
15
- resources:
16
- reservations:
17
- devices:
18
- - driver: nvidia
19
- count: 1
20
- capabilities: [gpu]
 
10
  - ./opt:/app/opt
11
  # - ./dataset:/app/dataset # you can use this folder in order to provide your dataset for model training
12
  ports:
13
+ - 7865:7865
 
 
 
 
 
 
 
docs/en/README.en.md CHANGED
@@ -57,9 +57,6 @@ pip install torch torchvision torchaudio
57
 
58
  #For Windows + Nvidia Ampere Architecture(RTX30xx), you need to specify the cuda version corresponding to pytorch according to the experience of https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI/issues/21
59
  #pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu117
60
-
61
- #For Linux + AMD Cards, you need to use the following pytorch versions:
62
- #pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/rocm5.4.2
63
  ```
64
 
65
  Then can use poetry to install the other dependencies:
@@ -78,14 +75,12 @@ You can also use pip to install them:
78
  for Nvidia graphics cards
79
  pip install -r requirements.txt
80
 
81
- for AMD/Intel graphics cards on Windows (DirectML)
82
  pip install -r requirements-dml.txt
83
 
84
  for Intel ARC graphics cards on Linux / WSL using Python 3.10:
85
  pip install -r requirements-ipex.txt
86
 
87
- for AMD graphics cards on Linux (ROCm):
88
- pip install -r requirements-amd.txt
89
  ```
90
 
91
  ------
@@ -140,32 +135,8 @@ Then use this command to start Webui:
140
  ```bash
141
  python infer-web.py
142
  ```
143
-
144
  If you are using Windows or macOS, you can download and extract `RVC-beta.7z` to use RVC directly by using `go-web.bat` on windows or `sh ./run.sh` on macOS to start Webui.
145
 
146
- ## ROCm Support for AMD graphic cards (Linux only)
147
- To use ROCm on Linux install all required drivers as described [here](https://rocm.docs.amd.com/en/latest/deploy/linux/os-native/install.html).
148
-
149
- On Arch use pacman to install the driver:
150
- ````
151
- pacman -S rocm-hip-sdk rocm-opencl-sdk
152
- ````
153
-
154
- You might also need to set these environment variables (e.g. on a RX6700XT):
155
- ````
156
- export ROCM_PATH=/opt/rocm
157
- export HSA_OVERRIDE_GFX_VERSION=10.3.0
158
- ````
159
- Also make sure your user is part of the `render` and `video` group:
160
- ````
161
- sudo usermod -aG render $USERNAME
162
- sudo usermod -aG video $USERNAME
163
- ````
164
- After that you can run the WebUI:
165
- ```bash
166
- python infer-web.py
167
- ```
168
-
169
  ## Credits
170
  + [ContentVec](https://github.com/auspicious3000/contentvec/)
171
  + [VITS](https://github.com/jaywalnut310/vits)
 
57
 
58
  #For Windows + Nvidia Ampere Architecture(RTX30xx), you need to specify the cuda version corresponding to pytorch according to the experience of https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI/issues/21
59
  #pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu117
 
 
 
60
  ```
61
 
62
  Then can use poetry to install the other dependencies:
 
75
  for Nvidia graphics cards
76
  pip install -r requirements.txt
77
 
78
+ for AMD/Intel graphics cards:
79
  pip install -r requirements-dml.txt
80
 
81
  for Intel ARC graphics cards on Linux / WSL using Python 3.10:
82
  pip install -r requirements-ipex.txt
83
 
 
 
84
  ```
85
 
86
  ------
 
135
  ```bash
136
  python infer-web.py
137
  ```
 
138
  If you are using Windows or macOS, you can download and extract `RVC-beta.7z` to use RVC directly by using `go-web.bat` on windows or `sh ./run.sh` on macOS to start Webui.
139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  ## Credits
141
  + [ContentVec](https://github.com/auspicious3000/contentvec/)
142
  + [VITS](https://github.com/jaywalnut310/vits)
download_files.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess, os
2
+ assets_folder = "./assets/"
3
+ if not os.path.exists(assets_folder):
4
+ os.makedirs(assets_folder)
5
+ files = {
6
+ "rmvpe/rmvpe.pt":"https://huggingface.co/Rejekts/project/resolve/main/rmvpe.pt",
7
+ "hubert/hubert_base.pt":"https://huggingface.co/Rejekts/project/resolve/main/hubert_base.pt",
8
+ "pretrained_v2/D40k.pth":"https://huggingface.co/Rejekts/project/resolve/main/D40k.pth",
9
+ "pretrained_v2/G40k.pth":"https://huggingface.co/Rejekts/project/resolve/main/G40k.pth",
10
+ "pretrained_v2/f0D40k.pth":"https://huggingface.co/Rejekts/project/resolve/main/f0D40k.pth",
11
+ "pretrained_v2/f0G40k.pth":"https://huggingface.co/Rejekts/project/resolve/main/f0G40k.pth"
12
+ }
13
+ for file, link in files.items():
14
+ file_path = os.path.join(assets_folder, file)
15
+ if not os.path.exists(file_path):
16
+ try:
17
+ subprocess.run(['wget', link, '-O', file_path], check=True)
18
+ except subprocess.CalledProcessError as e:
19
+ print(f"Error downloading {file}: {e}")
gui_v1.py CHANGED
@@ -377,7 +377,7 @@ if __name__ == "__main__":
377
  )
378
  if event == "start_vc" and self.flag_vc == False:
379
  if self.set_values(values) == True:
380
- logger.info("cuda_is_available: %s", torch.cuda.is_available())
381
  self.start_vc()
382
  settings = {
383
  "pth_path": values["pth_path"],
@@ -478,28 +478,15 @@ if __name__ == "__main__":
478
  inp_q,
479
  opt_q,
480
  device,
481
- self.rvc if hasattr(self, "rvc") else None,
482
  )
483
  self.config.samplerate = self.rvc.tgt_sr
484
  self.zc = self.rvc.tgt_sr // 100
485
- self.block_frame = (
486
- int(np.round(self.config.block_time * self.config.samplerate / self.zc))
487
- * self.zc
488
- )
489
  self.block_frame_16k = 160 * self.block_frame // self.zc
490
- self.crossfade_frame = (
491
- int(
492
- np.round(
493
- self.config.crossfade_time * self.config.samplerate / self.zc
494
- )
495
- )
496
- * self.zc
497
- )
498
  self.sola_search_frame = self.zc
499
- self.extra_frame = (
500
- int(np.round(self.config.extra_time * self.config.samplerate / self.zc))
501
- * self.zc
502
- )
503
  self.input_wav: torch.Tensor = torch.zeros(
504
  self.extra_frame
505
  + self.crossfade_frame
@@ -508,11 +495,7 @@ if __name__ == "__main__":
508
  device=device,
509
  dtype=torch.float32,
510
  )
511
- self.input_wav_res: torch.Tensor = torch.zeros(
512
- 160 * self.input_wav.shape[0] // self.zc,
513
- device=device,
514
- dtype=torch.float32,
515
- )
516
  self.pitch: np.ndarray = np.zeros(
517
  self.input_wav.shape[0] // self.zc,
518
  dtype="int32",
@@ -526,9 +509,7 @@ if __name__ == "__main__":
526
  )
527
  self.nr_buffer: torch.Tensor = self.sola_buffer.clone()
528
  self.output_buffer: torch.Tensor = self.input_wav.clone()
529
- self.res_buffer: torch.Tensor = torch.zeros(
530
- 2 * self.zc, device=device, dtype=torch.float32
531
- )
532
  self.valid_rate = 1 - (self.extra_frame - 1) / self.input_wav.shape[0]
533
  self.fade_in_window: torch.Tensor = (
534
  torch.sin(
@@ -548,9 +529,7 @@ if __name__ == "__main__":
548
  self.resampler = tat.Resample(
549
  orig_freq=self.config.samplerate, new_freq=16000, dtype=torch.float32
550
  ).to(device)
551
- self.tg = TorchGate(
552
- sr=self.config.samplerate, n_fft=4 * self.zc, prop_decrease=0.9
553
- ).to(device)
554
  thread_vc = threading.Thread(target=self.soundinput)
555
  thread_vc.start()
556
 
@@ -581,7 +560,7 @@ if __name__ == "__main__":
581
  indata = librosa.to_mono(indata.T)
582
  if self.config.threhold > -60:
583
  rms = librosa.feature.rms(
584
- y=indata, frame_length=4 * self.zc, hop_length=self.zc
585
  )
586
  db_threhold = (
587
  librosa.amplitude_to_db(rms, ref=1.0)[0] < self.config.threhold
@@ -589,44 +568,28 @@ if __name__ == "__main__":
589
  for i in range(db_threhold.shape[0]):
590
  if db_threhold[i]:
591
  indata[i * self.zc : (i + 1) * self.zc] = 0
592
- self.input_wav[: -self.block_frame] = self.input_wav[
593
- self.block_frame :
594
- ].clone()
595
- self.input_wav[-self.block_frame :] = torch.from_numpy(indata).to(device)
596
- self.input_wav_res[: -self.block_frame_16k] = self.input_wav_res[
597
- self.block_frame_16k :
598
- ].clone()
599
  # input noise reduction and resampling
600
  if self.config.I_noise_reduce:
601
- input_wav = self.input_wav[
602
- -self.crossfade_frame - self.block_frame - 2 * self.zc :
603
- ]
604
- input_wav = self.tg(
605
- input_wav.unsqueeze(0), self.input_wav.unsqueeze(0)
606
- )[0, 2 * self.zc :]
607
  input_wav[: self.crossfade_frame] *= self.fade_in_window
608
- input_wav[: self.crossfade_frame] += (
609
- self.nr_buffer * self.fade_out_window
610
- )
611
- self.nr_buffer[:] = input_wav[-self.crossfade_frame :]
612
- input_wav = torch.cat(
613
- (self.res_buffer[:], input_wav[: self.block_frame])
614
- )
615
- self.res_buffer[:] = input_wav[-2 * self.zc :]
616
- self.input_wav_res[-self.block_frame_16k - 160 :] = self.resampler(
617
- input_wav
618
- )[160:]
619
  else:
620
- self.input_wav_res[-self.block_frame_16k - 160 :] = self.resampler(
621
- self.input_wav[-self.block_frame - 2 * self.zc :]
622
- )[160:]
623
  # infer
624
  f0_extractor_frame = self.block_frame_16k + 800
625
- if self.config.f0method == "rmvpe":
626
  f0_extractor_frame = 5120 * ((f0_extractor_frame - 1) // 5120 + 1)
627
  infer_wav = self.rvc.infer(
628
  self.input_wav_res,
629
- self.input_wav_res[-f0_extractor_frame:].cpu().numpy(),
630
  self.block_frame_16k,
631
  self.valid_rate,
632
  self.pitch,
@@ -638,77 +601,48 @@ if __name__ == "__main__":
638
  ]
639
  # output noise reduction
640
  if self.config.O_noise_reduce:
641
- self.output_buffer[: -self.block_frame] = self.output_buffer[
642
- self.block_frame :
643
- ].clone()
644
- self.output_buffer[-self.block_frame :] = infer_wav[-self.block_frame :]
645
- infer_wav = self.tg(
646
- infer_wav.unsqueeze(0), self.output_buffer.unsqueeze(0)
647
- ).squeeze(0)
648
  # volume envelop mixing
649
  if self.config.rms_mix_rate < 1:
650
  rms1 = librosa.feature.rms(
651
- y=self.input_wav_res[-160 * infer_wav.shape[0] // self.zc :]
652
- .cpu()
653
- .numpy(),
654
- frame_length=640,
655
- hop_length=160,
656
  )
657
  rms1 = torch.from_numpy(rms1).to(device)
658
  rms1 = F.interpolate(
659
- rms1.unsqueeze(0),
660
- size=infer_wav.shape[0] + 1,
661
- mode="linear",
662
- align_corners=True,
663
- )[0, 0, :-1]
664
  rms2 = librosa.feature.rms(
665
- y=infer_wav[:].cpu().numpy(),
666
- frame_length=4 * self.zc,
667
- hop_length=self.zc,
668
  )
669
  rms2 = torch.from_numpy(rms2).to(device)
670
  rms2 = F.interpolate(
671
- rms2.unsqueeze(0),
672
- size=infer_wav.shape[0] + 1,
673
- mode="linear",
674
- align_corners=True,
675
- )[0, 0, :-1]
676
  rms2 = torch.max(rms2, torch.zeros_like(rms2) + 1e-3)
677
- infer_wav *= torch.pow(
678
- rms1 / rms2, torch.tensor(1 - self.config.rms_mix_rate)
679
- )
680
  # SOLA algorithm from https://github.com/yxlllc/DDSP-SVC
681
- conv_input = infer_wav[
682
- None, None, : self.crossfade_frame + self.sola_search_frame
683
- ]
684
  cor_nom = F.conv1d(conv_input, self.sola_buffer[None, None, :])
685
  cor_den = torch.sqrt(
686
- F.conv1d(
687
- conv_input**2,
688
- torch.ones(1, 1, self.crossfade_frame, device=device),
689
- )
690
- + 1e-8
691
- )
692
  if sys.platform == "darwin":
693
  _, sola_offset = torch.max(cor_nom[0, 0] / cor_den[0, 0])
694
  sola_offset = sola_offset.item()
695
  else:
696
  sola_offset = torch.argmax(cor_nom[0, 0] / cor_den[0, 0])
697
  logger.debug("sola_offset = %d", int(sola_offset))
698
- infer_wav = infer_wav[
699
- sola_offset : sola_offset + self.block_frame + self.crossfade_frame
700
- ]
701
  infer_wav[: self.crossfade_frame] *= self.fade_in_window
702
- infer_wav[: self.crossfade_frame] += self.sola_buffer * self.fade_out_window
703
- self.sola_buffer[:] = infer_wav[-self.crossfade_frame :]
704
  if sys.platform == "darwin":
705
- outdata[:] = (
706
- infer_wav[: -self.crossfade_frame].cpu().numpy()[:, np.newaxis]
707
- )
708
  else:
709
- outdata[:] = (
710
- infer_wav[: -self.crossfade_frame].repeat(2, 1).t().cpu().numpy()
711
- )
712
  total_time = time.perf_counter() - start_time
713
  self.window["infer_time"].update(int(total_time * 1000))
714
  logger.info("Infer time: %.2f", total_time)
@@ -764,7 +698,9 @@ if __name__ == "__main__":
764
  sd.default.device[1] = output_device_indices[
765
  output_devices.index(output_device)
766
  ]
767
- logger.info("Input device: %s:%s", str(sd.default.device[0]), input_device)
 
 
768
  logger.info(
769
  "Output device: %s:%s", str(sd.default.device[1]), output_device
770
  )
 
377
  )
378
  if event == "start_vc" and self.flag_vc == False:
379
  if self.set_values(values) == True:
380
+ logger.info("Use CUDA: %s", torch.cuda.is_available())
381
  self.start_vc()
382
  settings = {
383
  "pth_path": values["pth_path"],
 
478
  inp_q,
479
  opt_q,
480
  device,
481
+ self.rvc if hasattr(self, "rvc") else None
482
  )
483
  self.config.samplerate = self.rvc.tgt_sr
484
  self.zc = self.rvc.tgt_sr // 100
485
+ self.block_frame = int(np.round(self.config.block_time * self.config.samplerate / self.zc)) * self.zc
 
 
 
486
  self.block_frame_16k = 160 * self.block_frame // self.zc
487
+ self.crossfade_frame = int(np.round(self.config.crossfade_time * self.config.samplerate / self.zc)) * self.zc
 
 
 
 
 
 
 
488
  self.sola_search_frame = self.zc
489
+ self.extra_frame = int(np.round(self.config.extra_time * self.config.samplerate / self.zc)) * self.zc
 
 
 
490
  self.input_wav: torch.Tensor = torch.zeros(
491
  self.extra_frame
492
  + self.crossfade_frame
 
495
  device=device,
496
  dtype=torch.float32,
497
  )
498
+ self.input_wav_res: torch.Tensor= torch.zeros(160 * self.input_wav.shape[0] // self.zc, device=device,dtype=torch.float32)
 
 
 
 
499
  self.pitch: np.ndarray = np.zeros(
500
  self.input_wav.shape[0] // self.zc,
501
  dtype="int32",
 
509
  )
510
  self.nr_buffer: torch.Tensor = self.sola_buffer.clone()
511
  self.output_buffer: torch.Tensor = self.input_wav.clone()
512
+ self.res_buffer: torch.Tensor = torch.zeros(2 * self.zc, device=device,dtype=torch.float32)
 
 
513
  self.valid_rate = 1 - (self.extra_frame - 1) / self.input_wav.shape[0]
514
  self.fade_in_window: torch.Tensor = (
515
  torch.sin(
 
529
  self.resampler = tat.Resample(
530
  orig_freq=self.config.samplerate, new_freq=16000, dtype=torch.float32
531
  ).to(device)
532
+ self.tg = TorchGate(sr=self.config.samplerate, n_fft=4*self.zc, prop_decrease=0.9).to(device)
 
 
533
  thread_vc = threading.Thread(target=self.soundinput)
534
  thread_vc.start()
535
 
 
560
  indata = librosa.to_mono(indata.T)
561
  if self.config.threhold > -60:
562
  rms = librosa.feature.rms(
563
+ y=indata, frame_length=4*self.zc, hop_length=self.zc
564
  )
565
  db_threhold = (
566
  librosa.amplitude_to_db(rms, ref=1.0)[0] < self.config.threhold
 
568
  for i in range(db_threhold.shape[0]):
569
  if db_threhold[i]:
570
  indata[i * self.zc : (i + 1) * self.zc] = 0
571
+ self.input_wav[: -self.block_frame] = self.input_wav[self.block_frame :].clone()
572
+ self.input_wav[-self.block_frame: ] = torch.from_numpy(indata).to(device)
573
+ self.input_wav_res[ : -self.block_frame_16k] = self.input_wav_res[self.block_frame_16k :].clone()
 
 
 
 
574
  # input noise reduction and resampling
575
  if self.config.I_noise_reduce:
576
+ input_wav = self.input_wav[-self.crossfade_frame -self.block_frame-2*self.zc: ]
577
+ input_wav = self.tg(input_wav.unsqueeze(0), self.input_wav.unsqueeze(0))[0, 2*self.zc:]
 
 
 
 
578
  input_wav[: self.crossfade_frame] *= self.fade_in_window
579
+ input_wav[: self.crossfade_frame] += self.nr_buffer * self.fade_out_window
580
+ self.nr_buffer[:] = input_wav[-self.crossfade_frame: ]
581
+ input_wav = torch.cat((self.res_buffer[:], input_wav[: self.block_frame]))
582
+ self.res_buffer[:] = input_wav[-2*self.zc: ]
583
+ self.input_wav_res[-self.block_frame_16k-160: ] = self.resampler(input_wav)[160: ]
 
 
 
 
 
 
584
  else:
585
+ self.input_wav_res[-self.block_frame_16k-160: ] = self.resampler(self.input_wav[-self.block_frame-2*self.zc: ])[160: ]
 
 
586
  # infer
587
  f0_extractor_frame = self.block_frame_16k + 800
588
+ if self.config.f0method == 'rmvpe':
589
  f0_extractor_frame = 5120 * ((f0_extractor_frame - 1) // 5120 + 1)
590
  infer_wav = self.rvc.infer(
591
  self.input_wav_res,
592
+ self.input_wav_res[-f0_extractor_frame :].cpu().numpy(),
593
  self.block_frame_16k,
594
  self.valid_rate,
595
  self.pitch,
 
601
  ]
602
  # output noise reduction
603
  if self.config.O_noise_reduce:
604
+ self.output_buffer[: -self.block_frame] = self.output_buffer[self.block_frame :].clone()
605
+ self.output_buffer[-self.block_frame: ] = infer_wav[-self.block_frame:]
606
+ infer_wav = self.tg(infer_wav.unsqueeze(0), self.output_buffer.unsqueeze(0)).squeeze(0)
 
 
 
 
607
  # volume envelop mixing
608
  if self.config.rms_mix_rate < 1:
609
  rms1 = librosa.feature.rms(
610
+ y=self.input_wav_res[-160*infer_wav.shape[0]//self.zc :].cpu().numpy(),
611
+ frame_length=640,
612
+ hop_length=160,
 
 
613
  )
614
  rms1 = torch.from_numpy(rms1).to(device)
615
  rms1 = F.interpolate(
616
+ rms1.unsqueeze(0), size=infer_wav.shape[0] + 1, mode="linear",align_corners=True,
617
+ )[0,0,:-1]
 
 
 
618
  rms2 = librosa.feature.rms(
619
+ y=infer_wav[:].cpu().numpy(), frame_length=4*self.zc, hop_length=self.zc
 
 
620
  )
621
  rms2 = torch.from_numpy(rms2).to(device)
622
  rms2 = F.interpolate(
623
+ rms2.unsqueeze(0), size=infer_wav.shape[0] + 1, mode="linear",align_corners=True,
624
+ )[0,0,:-1]
 
 
 
625
  rms2 = torch.max(rms2, torch.zeros_like(rms2) + 1e-3)
626
+ infer_wav *= torch.pow(rms1 / rms2, torch.tensor(1 - self.config.rms_mix_rate))
 
 
627
  # SOLA algorithm from https://github.com/yxlllc/DDSP-SVC
628
+ conv_input = infer_wav[None, None, : self.crossfade_frame + self.sola_search_frame]
 
 
629
  cor_nom = F.conv1d(conv_input, self.sola_buffer[None, None, :])
630
  cor_den = torch.sqrt(
631
+ F.conv1d(conv_input ** 2, torch.ones(1, 1, self.crossfade_frame, device=device)) + 1e-8)
 
 
 
 
 
632
  if sys.platform == "darwin":
633
  _, sola_offset = torch.max(cor_nom[0, 0] / cor_den[0, 0])
634
  sola_offset = sola_offset.item()
635
  else:
636
  sola_offset = torch.argmax(cor_nom[0, 0] / cor_den[0, 0])
637
  logger.debug("sola_offset = %d", int(sola_offset))
638
+ infer_wav = infer_wav[sola_offset: sola_offset + self.block_frame + self.crossfade_frame]
 
 
639
  infer_wav[: self.crossfade_frame] *= self.fade_in_window
640
+ infer_wav[: self.crossfade_frame] += self.sola_buffer *self.fade_out_window
641
+ self.sola_buffer[:] = infer_wav[-self.crossfade_frame:]
642
  if sys.platform == "darwin":
643
+ outdata[:] = infer_wav[:-self.crossfade_frame].cpu().numpy()[:, np.newaxis]
 
 
644
  else:
645
+ outdata[:] = infer_wav[:-self.crossfade_frame].repeat(2, 1).t().cpu().numpy()
 
 
646
  total_time = time.perf_counter() - start_time
647
  self.window["infer_time"].update(int(total_time * 1000))
648
  logger.info("Infer time: %.2f", total_time)
 
698
  sd.default.device[1] = output_device_indices[
699
  output_devices.index(output_device)
700
  ]
701
+ logger.info(
702
+ "Input device: %s:%s", str(sd.default.device[0]), input_device
703
+ )
704
  logger.info(
705
  "Output device: %s:%s", str(sd.default.device[1]), output_device
706
  )
infer-web.py CHANGED
@@ -1028,7 +1028,6 @@ with gr.Blocks(title="RVC WebUI") as app:
1028
  fn=vc.get_vc,
1029
  inputs=[sid0, protect0, protect1],
1030
  outputs=[spk_item, protect0, protect1, file_index2, file_index4],
1031
- api_name="infer_change_voice",
1032
  )
1033
  with gr.TabItem(i18n("伴奏人声分离&去混响&去回声")):
1034
  with gr.Group():
 
1028
  fn=vc.get_vc,
1029
  inputs=[sid0, protect0, protect1],
1030
  outputs=[spk_item, protect0, protect1, file_index2, file_index4],
 
1031
  )
1032
  with gr.TabItem(i18n("伴奏人声分离&去混响&去回声")):
1033
  with gr.Group():
infer/lib/audio.py CHANGED
@@ -3,49 +3,38 @@ import numpy as np
3
  import av
4
  from io import BytesIO
5
 
6
-
7
  def wav2(i, o, format):
8
- inp = av.open(i, "rb")
9
- if format == "m4a":
10
- format = "mp4"
11
- out = av.open(o, "wb", format=format)
12
- if format == "ogg":
13
- format = "libvorbis"
14
- if format == "mp4":
15
- format = "aac"
16
 
17
  ostream = out.add_stream(format)
18
 
19
  for frame in inp.decode(audio=0):
20
- for p in ostream.encode(frame):
21
- out.mux(p)
22
 
23
- for p in ostream.encode(None):
24
- out.mux(p)
25
 
26
  out.close()
27
  inp.close()
28
 
29
-
30
  def audio2(i, o, format, sr):
31
- inp = av.open(i, "rb")
32
- out = av.open(o, "wb", format=format)
33
- if format == "ogg":
34
- format = "libvorbis"
35
- if format == "f32le":
36
- format = "pcm_f32le"
37
 
38
  ostream = out.add_stream(format, channels=1)
39
  ostream.sample_rate = sr
40
 
41
  for frame in inp.decode(audio=0):
42
- for p in ostream.encode(frame):
43
- out.mux(p)
44
 
45
  out.close()
46
  inp.close()
47
 
48
-
49
  def load_audio(file, sr):
50
  try:
51
  file = (
 
3
  import av
4
  from io import BytesIO
5
 
 
6
  def wav2(i, o, format):
7
+ inp = av.open(i, 'rb')
8
+ if format == "m4a": format = "mp4"
9
+ out = av.open(o, 'wb', format=format)
10
+ if format == "ogg": format = "libvorbis"
11
+ if format == "mp4": format = "aac"
 
 
 
12
 
13
  ostream = out.add_stream(format)
14
 
15
  for frame in inp.decode(audio=0):
16
+ for p in ostream.encode(frame): out.mux(p)
 
17
 
18
+ for p in ostream.encode(None): out.mux(p)
 
19
 
20
  out.close()
21
  inp.close()
22
 
 
23
  def audio2(i, o, format, sr):
24
+ inp = av.open(i, 'rb')
25
+ out = av.open(o, 'wb', format=format)
26
+ if format == "ogg": format = "libvorbis"
27
+ if format == "f32le": format = "pcm_f32le"
 
 
28
 
29
  ostream = out.add_stream(format, channels=1)
30
  ostream.sample_rate = sr
31
 
32
  for frame in inp.decode(audio=0):
33
+ for p in ostream.encode(frame): out.mux(p)
 
34
 
35
  out.close()
36
  inp.close()
37
 
 
38
  def load_audio(file, sr):
39
  try:
40
  file = (
infer/lib/infer_pack/models.py CHANGED
@@ -15,7 +15,6 @@ from infer.lib.infer_pack.commons import get_padding, init_weights
15
 
16
  has_xpu = bool(hasattr(torch, "xpu") and torch.xpu.is_available())
17
 
18
-
19
  class TextEncoder256(nn.Module):
20
  def __init__(
21
  self,
@@ -1159,9 +1158,7 @@ class DiscriminatorP(torch.nn.Module):
1159
  if t % self.period != 0: # pad first
1160
  n_pad = self.period - (t % self.period)
1161
  if has_xpu and x.dtype == torch.bfloat16:
1162
- x = F.pad(x.to(dtype=torch.float16), (0, n_pad), "reflect").to(
1163
- dtype=torch.bfloat16
1164
- )
1165
  else:
1166
  x = F.pad(x, (0, n_pad), "reflect")
1167
  t = t + n_pad
 
15
 
16
  has_xpu = bool(hasattr(torch, "xpu") and torch.xpu.is_available())
17
 
 
18
  class TextEncoder256(nn.Module):
19
  def __init__(
20
  self,
 
1158
  if t % self.period != 0: # pad first
1159
  n_pad = self.period - (t % self.period)
1160
  if has_xpu and x.dtype == torch.bfloat16:
1161
+ x = F.pad(x.to(dtype=torch.float16), (0, n_pad), "reflect").to(dtype=torch.bfloat16)
 
 
1162
  else:
1163
  x = F.pad(x, (0, n_pad), "reflect")
1164
  t = t + n_pad
infer/lib/rmvpe.py CHANGED
@@ -2,14 +2,11 @@ import pdb, os
2
 
3
  import numpy as np
4
  import torch
5
-
6
  try:
7
- # Fix "Torch not compiled with CUDA enabled"
8
- import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
9
-
10
  if torch.xpu.is_available():
11
  from infer.modules.ipex import ipex_init
12
-
13
  ipex_init()
14
  except Exception:
15
  pass
 
2
 
3
  import numpy as np
4
  import torch
 
5
  try:
6
+ #Fix "Torch not compiled with CUDA enabled"
7
+ import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
 
8
  if torch.xpu.is_available():
9
  from infer.modules.ipex import ipex_init
 
10
  ipex_init()
11
  except Exception:
12
  pass
infer/modules/ipex/__init__.py CHANGED
@@ -2,16 +2,15 @@ import os
2
  import sys
3
  import contextlib
4
  import torch
5
- import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
6
  from .hijacks import ipex_hijacks
7
  from .attention import attention_init
8
 
9
  # pylint: disable=protected-access, missing-function-docstring, line-too-long
10
 
11
-
12
- def ipex_init(): # pylint: disable=too-many-statements
13
  try:
14
- # Replace cuda with xpu:
15
  torch.cuda.current_device = torch.xpu.current_device
16
  torch.cuda.current_stream = torch.xpu.current_stream
17
  torch.cuda.device = torch.xpu.device
@@ -92,11 +91,11 @@ def ipex_init(): # pylint: disable=too-many-statements
92
  torch.cuda.CharStorage = torch.xpu.CharStorage
93
  torch.cuda.__file__ = torch.xpu.__file__
94
  torch.cuda._is_in_bad_fork = torch.xpu.lazy_init._is_in_bad_fork
95
- # torch.cuda.is_current_stream_capturing = torch.xpu.is_current_stream_capturing
96
 
97
- # Memory:
98
  torch.cuda.memory = torch.xpu.memory
99
- if "linux" in sys.platform and "WSL2" in os.popen("uname -a").read():
100
  torch.xpu.empty_cache = lambda: None
101
  torch.cuda.empty_cache = torch.xpu.empty_cache
102
  torch.cuda.memory_stats = torch.xpu.memory_stats
@@ -112,11 +111,9 @@ def ipex_init(): # pylint: disable=too-many-statements
112
  torch.cuda.reset_max_memory_cached = torch.xpu.reset_peak_memory_stats
113
  torch.cuda.reset_max_memory_allocated = torch.xpu.reset_peak_memory_stats
114
  torch.cuda.memory_stats_as_nested_dict = torch.xpu.memory_stats_as_nested_dict
115
- torch.cuda.reset_accumulated_memory_stats = (
116
- torch.xpu.reset_accumulated_memory_stats
117
- )
118
 
119
- # RNG:
120
  torch.cuda.get_rng_state = torch.xpu.get_rng_state
121
  torch.cuda.get_rng_state_all = torch.xpu.get_rng_state_all
122
  torch.cuda.set_rng_state = torch.xpu.set_rng_state
@@ -127,44 +124,35 @@ def ipex_init(): # pylint: disable=too-many-statements
127
  torch.cuda.seed_all = torch.xpu.seed_all
128
  torch.cuda.initial_seed = torch.xpu.initial_seed
129
 
130
- # AMP:
131
  torch.cuda.amp = torch.xpu.amp
132
  if not hasattr(torch.cuda.amp, "common"):
133
  torch.cuda.amp.common = contextlib.nullcontext()
134
  torch.cuda.amp.common.amp_definitely_not_available = lambda: False
135
  try:
136
  torch.cuda.amp.GradScaler = torch.xpu.amp.GradScaler
137
- except Exception: # pylint: disable=broad-exception-caught
138
  try:
139
- from .gradscaler import (
140
- gradscaler_init,
141
- ) # pylint: disable=import-outside-toplevel, import-error
142
-
143
  gradscaler_init()
144
  torch.cuda.amp.GradScaler = torch.xpu.amp.GradScaler
145
- except Exception: # pylint: disable=broad-exception-caught
146
  torch.cuda.amp.GradScaler = ipex.cpu.autocast._grad_scaler.GradScaler
147
 
148
- # C
149
  torch._C._cuda_getCurrentRawStream = ipex._C._getCurrentStream
150
  ipex._C._DeviceProperties.major = 2023
151
  ipex._C._DeviceProperties.minor = 2
152
 
153
- # Fix functions with ipex:
154
- torch.cuda.mem_get_info = lambda device=None: [
155
- (
156
- torch.xpu.get_device_properties(device).total_memory
157
- - torch.xpu.memory_allocated(device)
158
- ),
159
- torch.xpu.get_device_properties(device).total_memory,
160
- ]
161
  torch._utils._get_available_device_type = lambda: "xpu"
162
  torch.has_cuda = True
163
  torch.cuda.has_half = True
164
  torch.cuda.is_bf16_supported = lambda *args, **kwargs: True
165
  torch.cuda.is_fp16_supported = lambda *args, **kwargs: True
166
  torch.version.cuda = "11.7"
167
- torch.cuda.get_device_capability = lambda *args, **kwargs: [11, 7]
168
  torch.cuda.get_device_properties.major = 11
169
  torch.cuda.get_device_properties.minor = 7
170
  torch.cuda.ipc_collect = lambda *args, **kwargs: None
 
2
  import sys
3
  import contextlib
4
  import torch
5
+ import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
6
  from .hijacks import ipex_hijacks
7
  from .attention import attention_init
8
 
9
  # pylint: disable=protected-access, missing-function-docstring, line-too-long
10
 
11
+ def ipex_init(): # pylint: disable=too-many-statements
 
12
  try:
13
+ #Replace cuda with xpu:
14
  torch.cuda.current_device = torch.xpu.current_device
15
  torch.cuda.current_stream = torch.xpu.current_stream
16
  torch.cuda.device = torch.xpu.device
 
91
  torch.cuda.CharStorage = torch.xpu.CharStorage
92
  torch.cuda.__file__ = torch.xpu.__file__
93
  torch.cuda._is_in_bad_fork = torch.xpu.lazy_init._is_in_bad_fork
94
+ #torch.cuda.is_current_stream_capturing = torch.xpu.is_current_stream_capturing
95
 
96
+ #Memory:
97
  torch.cuda.memory = torch.xpu.memory
98
+ if 'linux' in sys.platform and "WSL2" in os.popen("uname -a").read():
99
  torch.xpu.empty_cache = lambda: None
100
  torch.cuda.empty_cache = torch.xpu.empty_cache
101
  torch.cuda.memory_stats = torch.xpu.memory_stats
 
111
  torch.cuda.reset_max_memory_cached = torch.xpu.reset_peak_memory_stats
112
  torch.cuda.reset_max_memory_allocated = torch.xpu.reset_peak_memory_stats
113
  torch.cuda.memory_stats_as_nested_dict = torch.xpu.memory_stats_as_nested_dict
114
+ torch.cuda.reset_accumulated_memory_stats = torch.xpu.reset_accumulated_memory_stats
 
 
115
 
116
+ #RNG:
117
  torch.cuda.get_rng_state = torch.xpu.get_rng_state
118
  torch.cuda.get_rng_state_all = torch.xpu.get_rng_state_all
119
  torch.cuda.set_rng_state = torch.xpu.set_rng_state
 
124
  torch.cuda.seed_all = torch.xpu.seed_all
125
  torch.cuda.initial_seed = torch.xpu.initial_seed
126
 
127
+ #AMP:
128
  torch.cuda.amp = torch.xpu.amp
129
  if not hasattr(torch.cuda.amp, "common"):
130
  torch.cuda.amp.common = contextlib.nullcontext()
131
  torch.cuda.amp.common.amp_definitely_not_available = lambda: False
132
  try:
133
  torch.cuda.amp.GradScaler = torch.xpu.amp.GradScaler
134
+ except Exception: # pylint: disable=broad-exception-caught
135
  try:
136
+ from .gradscaler import gradscaler_init # pylint: disable=import-outside-toplevel, import-error
 
 
 
137
  gradscaler_init()
138
  torch.cuda.amp.GradScaler = torch.xpu.amp.GradScaler
139
+ except Exception: # pylint: disable=broad-exception-caught
140
  torch.cuda.amp.GradScaler = ipex.cpu.autocast._grad_scaler.GradScaler
141
 
142
+ #C
143
  torch._C._cuda_getCurrentRawStream = ipex._C._getCurrentStream
144
  ipex._C._DeviceProperties.major = 2023
145
  ipex._C._DeviceProperties.minor = 2
146
 
147
+ #Fix functions with ipex:
148
+ torch.cuda.mem_get_info = lambda device=None: [(torch.xpu.get_device_properties(device).total_memory - torch.xpu.memory_allocated(device)), torch.xpu.get_device_properties(device).total_memory]
 
 
 
 
 
 
149
  torch._utils._get_available_device_type = lambda: "xpu"
150
  torch.has_cuda = True
151
  torch.cuda.has_half = True
152
  torch.cuda.is_bf16_supported = lambda *args, **kwargs: True
153
  torch.cuda.is_fp16_supported = lambda *args, **kwargs: True
154
  torch.version.cuda = "11.7"
155
+ torch.cuda.get_device_capability = lambda *args, **kwargs: [11,7]
156
  torch.cuda.get_device_properties.major = 11
157
  torch.cuda.get_device_properties.minor = 7
158
  torch.cuda.ipc_collect = lambda *args, **kwargs: None
infer/modules/ipex/attention.py CHANGED
@@ -1,32 +1,22 @@
1
  import torch
2
- import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
3
 
4
  # pylint: disable=protected-access, missing-function-docstring, line-too-long
5
 
6
  original_torch_bmm = torch.bmm
7
-
8
-
9
  def torch_bmm(input, mat2, *, out=None):
10
  if input.dtype != mat2.dtype:
11
  mat2 = mat2.to(input.dtype)
12
 
13
- # ARC GPUs can't allocate more than 4GB to a single block, Slice it:
14
- batch_size_attention, input_tokens, mat2_shape = (
15
- input.shape[0],
16
- input.shape[1],
17
- mat2.shape[2],
18
- )
19
  block_multiply = 2.4 if input.dtype == torch.float32 else 1.2
20
- block_size = (
21
- (batch_size_attention * input_tokens * mat2_shape) / 1024 * block_multiply
22
- ) # MB
23
  split_slice_size = batch_size_attention
24
  if block_size >= 4000:
25
  do_split = True
26
- # Find something divisible with the input_tokens
27
- while (
28
- (split_slice_size * input_tokens * mat2_shape) / 1024 * block_multiply
29
- ) > 4000:
30
  split_slice_size = split_slice_size // 2
31
  if split_slice_size <= 1:
32
  split_slice_size = 1
@@ -34,16 +24,12 @@ def torch_bmm(input, mat2, *, out=None):
34
  else:
35
  do_split = False
36
 
37
- split_block_size = (
38
- (split_slice_size * input_tokens * mat2_shape) / 1024 * block_multiply
39
- ) # MB
40
  split_2_slice_size = input_tokens
41
  if split_block_size >= 4000:
42
  do_split_2 = True
43
- # Find something divisible with the input_tokens
44
- while (
45
- (split_slice_size * split_2_slice_size * mat2_shape) / 1024 * block_multiply
46
- ) > 4000:
47
  split_2_slice_size = split_2_slice_size // 2
48
  if split_2_slice_size <= 1:
49
  split_2_slice_size = 1
@@ -52,61 +38,40 @@ def torch_bmm(input, mat2, *, out=None):
52
  do_split_2 = False
53
 
54
  if do_split:
55
- hidden_states = torch.zeros(
56
- input.shape[0],
57
- input.shape[1],
58
- mat2.shape[2],
59
- device=input.device,
60
- dtype=input.dtype,
61
- )
62
  for i in range(batch_size_attention // split_slice_size):
63
  start_idx = i * split_slice_size
64
  end_idx = (i + 1) * split_slice_size
65
  if do_split_2:
66
- for i2 in range(
67
- input_tokens // split_2_slice_size
68
- ): # pylint: disable=invalid-name
69
  start_idx_2 = i2 * split_2_slice_size
70
  end_idx_2 = (i2 + 1) * split_2_slice_size
71
- hidden_states[
72
- start_idx:end_idx, start_idx_2:end_idx_2
73
- ] = original_torch_bmm(
74
  input[start_idx:end_idx, start_idx_2:end_idx_2],
75
  mat2[start_idx:end_idx, start_idx_2:end_idx_2],
76
- out=out,
77
  )
78
  else:
79
  hidden_states[start_idx:end_idx] = original_torch_bmm(
80
- input[start_idx:end_idx], mat2[start_idx:end_idx], out=out
 
 
81
  )
82
  else:
83
  return original_torch_bmm(input, mat2, out=out)
84
  return hidden_states
85
 
86
-
87
  original_scaled_dot_product_attention = torch.nn.functional.scaled_dot_product_attention
88
-
89
-
90
- def scaled_dot_product_attention(
91
- query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False
92
- ):
93
- # ARC GPUs can't allocate more than 4GB to a single block, Slice it:
94
  shape_one, batch_size_attention, query_tokens, shape_four = query.shape
95
  block_multiply = 2.4 if query.dtype == torch.float32 else 1.2
96
- block_size = (
97
- (shape_one * batch_size_attention * query_tokens * shape_four)
98
- / 1024
99
- * block_multiply
100
- ) # MB
101
  split_slice_size = batch_size_attention
102
  if block_size >= 4000:
103
  do_split = True
104
- # Find something divisible with the shape_one
105
- while (
106
- (shape_one * split_slice_size * query_tokens * shape_four)
107
- / 1024
108
- * block_multiply
109
- ) > 4000:
110
  split_slice_size = split_slice_size // 2
111
  if split_slice_size <= 1:
112
  split_slice_size = 1
@@ -114,20 +79,12 @@ def scaled_dot_product_attention(
114
  else:
115
  do_split = False
116
 
117
- split_block_size = (
118
- (shape_one * split_slice_size * query_tokens * shape_four)
119
- / 1024
120
- * block_multiply
121
- ) # MB
122
  split_2_slice_size = query_tokens
123
  if split_block_size >= 4000:
124
  do_split_2 = True
125
- # Find something divisible with the batch_size_attention
126
- while (
127
- (shape_one * split_slice_size * split_2_slice_size * shape_four)
128
- / 1024
129
- * block_multiply
130
- ) > 4000:
131
  split_2_slice_size = split_2_slice_size // 2
132
  if split_2_slice_size <= 1:
133
  split_2_slice_size = 1
@@ -141,49 +98,31 @@ def scaled_dot_product_attention(
141
  start_idx = i * split_slice_size
142
  end_idx = (i + 1) * split_slice_size
143
  if do_split_2:
144
- for i2 in range(
145
- query_tokens // split_2_slice_size
146
- ): # pylint: disable=invalid-name
147
  start_idx_2 = i2 * split_2_slice_size
148
  end_idx_2 = (i2 + 1) * split_2_slice_size
149
- hidden_states[
150
- :, start_idx:end_idx, start_idx_2:end_idx_2
151
- ] = original_scaled_dot_product_attention(
152
  query[:, start_idx:end_idx, start_idx_2:end_idx_2],
153
  key[:, start_idx:end_idx, start_idx_2:end_idx_2],
154
  value[:, start_idx:end_idx, start_idx_2:end_idx_2],
155
- attn_mask=attn_mask[:, start_idx:end_idx, start_idx_2:end_idx_2]
156
- if attn_mask is not None
157
- else attn_mask,
158
- dropout_p=dropout_p,
159
- is_causal=is_causal,
160
  )
161
  else:
162
- hidden_states[
163
- :, start_idx:end_idx
164
- ] = original_scaled_dot_product_attention(
165
  query[:, start_idx:end_idx],
166
  key[:, start_idx:end_idx],
167
  value[:, start_idx:end_idx],
168
- attn_mask=attn_mask[:, start_idx:end_idx]
169
- if attn_mask is not None
170
- else attn_mask,
171
- dropout_p=dropout_p,
172
- is_causal=is_causal,
173
  )
174
  else:
175
  return original_scaled_dot_product_attention(
176
- query,
177
- key,
178
- value,
179
- attn_mask=attn_mask,
180
- dropout_p=dropout_p,
181
- is_causal=is_causal,
182
  )
183
  return hidden_states
184
 
185
-
186
  def attention_init():
187
- # ARC GPUs can't allocate more than 4GB to a single block:
188
  torch.bmm = torch_bmm
189
  torch.nn.functional.scaled_dot_product_attention = scaled_dot_product_attention
 
1
  import torch
2
+ import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
3
 
4
  # pylint: disable=protected-access, missing-function-docstring, line-too-long
5
 
6
  original_torch_bmm = torch.bmm
 
 
7
  def torch_bmm(input, mat2, *, out=None):
8
  if input.dtype != mat2.dtype:
9
  mat2 = mat2.to(input.dtype)
10
 
11
+ #ARC GPUs can't allocate more than 4GB to a single block, Slice it:
12
+ batch_size_attention, input_tokens, mat2_shape = input.shape[0], input.shape[1], mat2.shape[2]
 
 
 
 
13
  block_multiply = 2.4 if input.dtype == torch.float32 else 1.2
14
+ block_size = (batch_size_attention * input_tokens * mat2_shape) / 1024 * block_multiply #MB
 
 
15
  split_slice_size = batch_size_attention
16
  if block_size >= 4000:
17
  do_split = True
18
+ #Find something divisible with the input_tokens
19
+ while ((split_slice_size * input_tokens * mat2_shape) / 1024 * block_multiply) > 4000:
 
 
20
  split_slice_size = split_slice_size // 2
21
  if split_slice_size <= 1:
22
  split_slice_size = 1
 
24
  else:
25
  do_split = False
26
 
27
+ split_block_size = (split_slice_size * input_tokens * mat2_shape) / 1024 * block_multiply #MB
 
 
28
  split_2_slice_size = input_tokens
29
  if split_block_size >= 4000:
30
  do_split_2 = True
31
+ #Find something divisible with the input_tokens
32
+ while ((split_slice_size * split_2_slice_size * mat2_shape) / 1024 * block_multiply) > 4000:
 
 
33
  split_2_slice_size = split_2_slice_size // 2
34
  if split_2_slice_size <= 1:
35
  split_2_slice_size = 1
 
38
  do_split_2 = False
39
 
40
  if do_split:
41
+ hidden_states = torch.zeros(input.shape[0], input.shape[1], mat2.shape[2], device=input.device, dtype=input.dtype)
 
 
 
 
 
 
42
  for i in range(batch_size_attention // split_slice_size):
43
  start_idx = i * split_slice_size
44
  end_idx = (i + 1) * split_slice_size
45
  if do_split_2:
46
+ for i2 in range(input_tokens // split_2_slice_size): # pylint: disable=invalid-name
 
 
47
  start_idx_2 = i2 * split_2_slice_size
48
  end_idx_2 = (i2 + 1) * split_2_slice_size
49
+ hidden_states[start_idx:end_idx, start_idx_2:end_idx_2] = original_torch_bmm(
 
 
50
  input[start_idx:end_idx, start_idx_2:end_idx_2],
51
  mat2[start_idx:end_idx, start_idx_2:end_idx_2],
52
+ out=out
53
  )
54
  else:
55
  hidden_states[start_idx:end_idx] = original_torch_bmm(
56
+ input[start_idx:end_idx],
57
+ mat2[start_idx:end_idx],
58
+ out=out
59
  )
60
  else:
61
  return original_torch_bmm(input, mat2, out=out)
62
  return hidden_states
63
 
 
64
  original_scaled_dot_product_attention = torch.nn.functional.scaled_dot_product_attention
65
+ def scaled_dot_product_attention(query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False):
66
+ #ARC GPUs can't allocate more than 4GB to a single block, Slice it:
 
 
 
 
67
  shape_one, batch_size_attention, query_tokens, shape_four = query.shape
68
  block_multiply = 2.4 if query.dtype == torch.float32 else 1.2
69
+ block_size = (shape_one * batch_size_attention * query_tokens * shape_four) / 1024 * block_multiply #MB
 
 
 
 
70
  split_slice_size = batch_size_attention
71
  if block_size >= 4000:
72
  do_split = True
73
+ #Find something divisible with the shape_one
74
+ while ((shape_one * split_slice_size * query_tokens * shape_four) / 1024 * block_multiply) > 4000:
 
 
 
 
75
  split_slice_size = split_slice_size // 2
76
  if split_slice_size <= 1:
77
  split_slice_size = 1
 
79
  else:
80
  do_split = False
81
 
82
+ split_block_size = (shape_one * split_slice_size * query_tokens * shape_four) / 1024 * block_multiply #MB
 
 
 
 
83
  split_2_slice_size = query_tokens
84
  if split_block_size >= 4000:
85
  do_split_2 = True
86
+ #Find something divisible with the batch_size_attention
87
+ while ((shape_one * split_slice_size * split_2_slice_size * shape_four) / 1024 * block_multiply) > 4000:
 
 
 
 
88
  split_2_slice_size = split_2_slice_size // 2
89
  if split_2_slice_size <= 1:
90
  split_2_slice_size = 1
 
98
  start_idx = i * split_slice_size
99
  end_idx = (i + 1) * split_slice_size
100
  if do_split_2:
101
+ for i2 in range(query_tokens // split_2_slice_size): # pylint: disable=invalid-name
 
 
102
  start_idx_2 = i2 * split_2_slice_size
103
  end_idx_2 = (i2 + 1) * split_2_slice_size
104
+ hidden_states[:, start_idx:end_idx, start_idx_2:end_idx_2] = original_scaled_dot_product_attention(
 
 
105
  query[:, start_idx:end_idx, start_idx_2:end_idx_2],
106
  key[:, start_idx:end_idx, start_idx_2:end_idx_2],
107
  value[:, start_idx:end_idx, start_idx_2:end_idx_2],
108
+ attn_mask=attn_mask[:, start_idx:end_idx, start_idx_2:end_idx_2] if attn_mask is not None else attn_mask,
109
+ dropout_p=dropout_p, is_causal=is_causal
 
 
 
110
  )
111
  else:
112
+ hidden_states[:, start_idx:end_idx] = original_scaled_dot_product_attention(
 
 
113
  query[:, start_idx:end_idx],
114
  key[:, start_idx:end_idx],
115
  value[:, start_idx:end_idx],
116
+ attn_mask=attn_mask[:, start_idx:end_idx] if attn_mask is not None else attn_mask,
117
+ dropout_p=dropout_p, is_causal=is_causal
 
 
 
118
  )
119
  else:
120
  return original_scaled_dot_product_attention(
121
+ query, key, value, attn_mask=attn_mask, dropout_p=dropout_p, is_causal=is_causal
 
 
 
 
 
122
  )
123
  return hidden_states
124
 
 
125
  def attention_init():
126
+ #ARC GPUs can't allocate more than 4GB to a single block:
127
  torch.bmm = torch_bmm
128
  torch.nn.functional.scaled_dot_product_attention = scaled_dot_product_attention
infer/modules/ipex/gradscaler.py CHANGED
@@ -1,20 +1,15 @@
1
  from collections import defaultdict
2
  import torch
3
- import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
4
- import intel_extension_for_pytorch._C as core # pylint: disable=import-error, unused-import
5
 
6
  # pylint: disable=protected-access, missing-function-docstring, line-too-long
7
 
8
  OptState = ipex.cpu.autocast._grad_scaler.OptState
9
  _MultiDeviceReplicator = ipex.cpu.autocast._grad_scaler._MultiDeviceReplicator
10
- _refresh_per_optimizer_state = (
11
- ipex.cpu.autocast._grad_scaler._refresh_per_optimizer_state
12
- )
13
 
14
-
15
- def _unscale_grads_(
16
- self, optimizer, inv_scale, found_inf, allow_fp16
17
- ): # pylint: disable=unused-argument
18
  per_device_inv_scale = _MultiDeviceReplicator(inv_scale)
19
  per_device_found_inf = _MultiDeviceReplicator(found_inf)
20
 
@@ -48,9 +43,9 @@ def _unscale_grads_(
48
 
49
  # -: is there a way to split by device and dtype without appending in the inner loop?
50
  to_unscale = to_unscale.to("cpu")
51
- per_device_and_dtype_grads[to_unscale.device][to_unscale.dtype].append(
52
- to_unscale
53
- )
54
 
55
  for _, per_dtype_grads in per_device_and_dtype_grads.items():
56
  for grads in per_dtype_grads.values():
@@ -62,7 +57,6 @@ def _unscale_grads_(
62
 
63
  return per_device_found_inf._per_device_tensors
64
 
65
-
66
  def unscale_(self, optimizer):
67
  """
68
  Divides ("unscales") the optimizer's gradient tensors by the scale factor.
@@ -93,7 +87,7 @@ def unscale_(self, optimizer):
93
 
94
  optimizer_state = self._per_optimizer_states[id(optimizer)]
95
 
96
- if optimizer_state["stage"] is OptState.UNSCALED: # pylint: disable=no-else-raise
97
  raise RuntimeError(
98
  "unscale_() has already been called on this optimizer since the last update()."
99
  )
@@ -102,17 +96,16 @@ def unscale_(self, optimizer):
102
 
103
  # FP32 division can be imprecise for certain compile options, so we carry out the reciprocal in FP64.
104
  assert self._scale is not None
105
- inv_scale = (
106
- self._scale.to("cpu").double().reciprocal().float().to(self._scale.device)
 
107
  )
108
- found_inf = torch.full((1,), 0.0, dtype=torch.float32, device=self._scale.device)
109
 
110
  optimizer_state["found_inf_per_device"] = self._unscale_grads_(
111
  optimizer, inv_scale, found_inf, False
112
  )
113
  optimizer_state["stage"] = OptState.UNSCALED
114
 
115
-
116
  def update(self, new_scale=None):
117
  """
118
  Updates the scale factor.
@@ -178,7 +171,6 @@ def update(self, new_scale=None):
178
  # To prepare for next iteration, clear the data collected from optimizers this iteration.
179
  self._per_optimizer_states = defaultdict(_refresh_per_optimizer_state)
180
 
181
-
182
  def gradscaler_init():
183
  torch.xpu.amp.GradScaler = ipex.cpu.autocast._grad_scaler.GradScaler
184
  torch.xpu.amp.GradScaler._unscale_grads_ = _unscale_grads_
 
1
  from collections import defaultdict
2
  import torch
3
+ import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
4
+ import intel_extension_for_pytorch._C as core # pylint: disable=import-error, unused-import
5
 
6
  # pylint: disable=protected-access, missing-function-docstring, line-too-long
7
 
8
  OptState = ipex.cpu.autocast._grad_scaler.OptState
9
  _MultiDeviceReplicator = ipex.cpu.autocast._grad_scaler._MultiDeviceReplicator
10
+ _refresh_per_optimizer_state = ipex.cpu.autocast._grad_scaler._refresh_per_optimizer_state
 
 
11
 
12
+ def _unscale_grads_(self, optimizer, inv_scale, found_inf, allow_fp16): # pylint: disable=unused-argument
 
 
 
13
  per_device_inv_scale = _MultiDeviceReplicator(inv_scale)
14
  per_device_found_inf = _MultiDeviceReplicator(found_inf)
15
 
 
43
 
44
  # -: is there a way to split by device and dtype without appending in the inner loop?
45
  to_unscale = to_unscale.to("cpu")
46
+ per_device_and_dtype_grads[to_unscale.device][
47
+ to_unscale.dtype
48
+ ].append(to_unscale)
49
 
50
  for _, per_dtype_grads in per_device_and_dtype_grads.items():
51
  for grads in per_dtype_grads.values():
 
57
 
58
  return per_device_found_inf._per_device_tensors
59
 
 
60
  def unscale_(self, optimizer):
61
  """
62
  Divides ("unscales") the optimizer's gradient tensors by the scale factor.
 
87
 
88
  optimizer_state = self._per_optimizer_states[id(optimizer)]
89
 
90
+ if optimizer_state["stage"] is OptState.UNSCALED: # pylint: disable=no-else-raise
91
  raise RuntimeError(
92
  "unscale_() has already been called on this optimizer since the last update()."
93
  )
 
96
 
97
  # FP32 division can be imprecise for certain compile options, so we carry out the reciprocal in FP64.
98
  assert self._scale is not None
99
+ inv_scale = self._scale.to("cpu").double().reciprocal().float().to(self._scale.device)
100
+ found_inf = torch.full(
101
+ (1,), 0.0, dtype=torch.float32, device=self._scale.device
102
  )
 
103
 
104
  optimizer_state["found_inf_per_device"] = self._unscale_grads_(
105
  optimizer, inv_scale, found_inf, False
106
  )
107
  optimizer_state["stage"] = OptState.UNSCALED
108
 
 
109
  def update(self, new_scale=None):
110
  """
111
  Updates the scale factor.
 
171
  # To prepare for next iteration, clear the data collected from optimizers this iteration.
172
  self._per_optimizer_states = defaultdict(_refresh_per_optimizer_state)
173
 
 
174
  def gradscaler_init():
175
  torch.xpu.amp.GradScaler = ipex.cpu.autocast._grad_scaler.GradScaler
176
  torch.xpu.amp.GradScaler._unscale_grads_ = _unscale_grads_
infer/modules/ipex/hijacks.py CHANGED
@@ -1,59 +1,45 @@
1
  import contextlib
2
  import importlib
3
  import torch
4
- import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
5
 
6
  # pylint: disable=protected-access, missing-function-docstring, line-too-long, unnecessary-lambda, no-else-return
7
 
8
-
9
- class CondFunc: # pylint: disable=missing-class-docstring
10
  def __new__(cls, orig_func, sub_func, cond_func):
11
  self = super(CondFunc, cls).__new__(cls)
12
  if isinstance(orig_func, str):
13
- func_path = orig_func.split(".")
14
- for i in range(len(func_path) - 1, -1, -1):
15
  try:
16
- resolved_obj = importlib.import_module(".".join(func_path[:i]))
17
  break
18
  except ImportError:
19
  pass
20
  for attr_name in func_path[i:-1]:
21
  resolved_obj = getattr(resolved_obj, attr_name)
22
  orig_func = getattr(resolved_obj, func_path[-1])
23
- setattr(
24
- resolved_obj,
25
- func_path[-1],
26
- lambda *args, **kwargs: self(*args, **kwargs),
27
- )
28
  self.__init__(orig_func, sub_func, cond_func)
29
  return lambda *args, **kwargs: self(*args, **kwargs)
30
-
31
  def __init__(self, orig_func, sub_func, cond_func):
32
  self.__orig_func = orig_func
33
  self.__sub_func = sub_func
34
  self.__cond_func = cond_func
35
-
36
  def __call__(self, *args, **kwargs):
37
  if not self.__cond_func or self.__cond_func(self.__orig_func, *args, **kwargs):
38
  return self.__sub_func(self.__orig_func, *args, **kwargs)
39
  else:
40
  return self.__orig_func(*args, **kwargs)
41
 
42
-
43
  _utils = torch.utils.data._utils
44
-
45
-
46
  def _shutdown_workers(self):
47
- if (
48
- torch.utils.data._utils is None
49
- or torch.utils.data._utils.python_exit_status is True
50
- or torch.utils.data._utils.python_exit_status is None
51
- ):
52
  return
53
  if hasattr(self, "_shutdown") and not self._shutdown:
54
  self._shutdown = True
55
  try:
56
- if hasattr(self, "_pin_memory_thread"):
57
  self._pin_memory_thread_done_event.set()
58
  self._worker_result_queue.put((None, None))
59
  self._pin_memory_thread.join()
@@ -63,292 +49,145 @@ def _shutdown_workers(self):
63
  for worker_id in range(len(self._workers)):
64
  if self._persistent_workers or self._workers_status[worker_id]:
65
  self._mark_worker_as_unavailable(worker_id, shutdown=True)
66
- for w in self._workers: # pylint: disable=invalid-name
67
  w.join(timeout=torch.utils.data._utils.MP_STATUS_CHECK_INTERVAL)
68
- for q in self._index_queues: # pylint: disable=invalid-name
69
  q.cancel_join_thread()
70
  q.close()
71
  finally:
72
  if self._worker_pids_set:
73
  torch.utils.data._utils.signal_handling._remove_worker_pids(id(self))
74
  self._worker_pids_set = False
75
- for w in self._workers: # pylint: disable=invalid-name
76
  if w.is_alive():
77
  w.terminate()
78
 
79
-
80
- class DummyDataParallel(
81
- torch.nn.Module
82
- ): # pylint: disable=missing-class-docstring, unused-argument, too-few-public-methods
83
- def __new__(
84
- cls, module, device_ids=None, output_device=None, dim=0
85
- ): # pylint: disable=unused-argument
86
  if isinstance(device_ids, list) and len(device_ids) > 1:
87
  print("IPEX backend doesn't support DataParallel on multiple XPU devices")
88
  return module.to("xpu")
89
 
90
-
91
- def return_null_context(*args, **kwargs): # pylint: disable=unused-argument
92
  return contextlib.nullcontext()
93
 
94
-
95
  def check_device(device):
96
- return bool(
97
- (isinstance(device, torch.device) and device.type == "cuda")
98
- or (isinstance(device, str) and "cuda" in device)
99
- or isinstance(device, int)
100
- )
101
-
102
 
103
  def return_xpu(device):
104
- return (
105
- f"xpu:{device[-1]}"
106
- if isinstance(device, str) and ":" in device
107
- else f"xpu:{device}"
108
- if isinstance(device, int)
109
- else torch.device("xpu")
110
- if isinstance(device, torch.device)
111
- else "xpu"
112
- )
113
-
114
 
115
  def ipex_no_cuda(orig_func, *args, **kwargs):
116
  torch.cuda.is_available = lambda: False
117
  orig_func(*args, **kwargs)
118
  torch.cuda.is_available = torch.xpu.is_available
119
 
120
-
121
  original_autocast = torch.autocast
122
-
123
-
124
  def ipex_autocast(*args, **kwargs):
125
  if len(args) > 0 and args[0] == "cuda":
126
  return original_autocast("xpu", *args[1:], **kwargs)
127
  else:
128
  return original_autocast(*args, **kwargs)
129
 
130
-
131
  original_torch_cat = torch.cat
132
-
133
-
134
  def torch_cat(tensor, *args, **kwargs):
135
- if len(tensor) == 3 and (
136
- tensor[0].dtype != tensor[1].dtype or tensor[2].dtype != tensor[1].dtype
137
- ):
138
- return original_torch_cat(
139
- [tensor[0].to(tensor[1].dtype), tensor[1], tensor[2].to(tensor[1].dtype)],
140
- *args,
141
- **kwargs,
142
- )
143
  else:
144
  return original_torch_cat(tensor, *args, **kwargs)
145
 
146
-
147
  original_interpolate = torch.nn.functional.interpolate
148
-
149
-
150
- def interpolate(
151
- tensor,
152
- size=None,
153
- scale_factor=None,
154
- mode="nearest",
155
- align_corners=None,
156
- recompute_scale_factor=None,
157
- antialias=False,
158
- ): # pylint: disable=too-many-arguments
159
  if antialias or align_corners is not None:
160
  return_device = tensor.device
161
  return_dtype = tensor.dtype
162
- return original_interpolate(
163
- tensor.to("cpu", dtype=torch.float32),
164
- size=size,
165
- scale_factor=scale_factor,
166
- mode=mode,
167
- align_corners=align_corners,
168
- recompute_scale_factor=recompute_scale_factor,
169
- antialias=antialias,
170
- ).to(return_device, dtype=return_dtype)
171
  else:
172
- return original_interpolate(
173
- tensor,
174
- size=size,
175
- scale_factor=scale_factor,
176
- mode=mode,
177
- align_corners=align_corners,
178
- recompute_scale_factor=recompute_scale_factor,
179
- antialias=antialias,
180
- )
181
-
182
 
183
  original_linalg_solve = torch.linalg.solve
184
-
185
-
186
- def linalg_solve(A, B, *args, **kwargs): # pylint: disable=invalid-name
187
  if A.device != torch.device("cpu") or B.device != torch.device("cpu"):
188
  return_device = A.device
189
- return original_linalg_solve(A.to("cpu"), B.to("cpu"), *args, **kwargs).to(
190
- return_device
191
- )
192
  else:
193
  return original_linalg_solve(A, B, *args, **kwargs)
194
 
195
-
196
  def ipex_hijacks():
197
- CondFunc(
198
- "torch.Tensor.to",
199
- lambda orig_func, self, device=None, *args, **kwargs: orig_func(
200
- self, return_xpu(device), *args, **kwargs
201
- ),
202
- lambda orig_func, self, device=None, *args, **kwargs: check_device(device),
203
- )
204
- CondFunc(
205
- "torch.Tensor.cuda",
206
- lambda orig_func, self, device=None, *args, **kwargs: orig_func(
207
- self, return_xpu(device), *args, **kwargs
208
- ),
209
- lambda orig_func, self, device=None, *args, **kwargs: check_device(device),
210
- )
211
- CondFunc(
212
- "torch.empty",
213
- lambda orig_func, *args, device=None, **kwargs: orig_func(
214
- *args, device=return_xpu(device), **kwargs
215
- ),
216
- lambda orig_func, *args, device=None, **kwargs: check_device(device),
217
- )
218
- CondFunc(
219
- "torch.load",
220
- lambda orig_func, *args, map_location=None, **kwargs: orig_func(
221
- *args, return_xpu(map_location), **kwargs
222
- ),
223
- lambda orig_func, *args, map_location=None, **kwargs: map_location is None
224
- or check_device(map_location),
225
- )
226
- CondFunc(
227
- "torch.randn",
228
- lambda orig_func, *args, device=None, **kwargs: orig_func(
229
- *args, device=return_xpu(device), **kwargs
230
- ),
231
- lambda orig_func, *args, device=None, **kwargs: check_device(device),
232
- )
233
- CondFunc(
234
- "torch.ones",
235
- lambda orig_func, *args, device=None, **kwargs: orig_func(
236
- *args, device=return_xpu(device), **kwargs
237
- ),
238
- lambda orig_func, *args, device=None, **kwargs: check_device(device),
239
- )
240
- CondFunc(
241
- "torch.zeros",
242
- lambda orig_func, *args, device=None, **kwargs: orig_func(
243
- *args, device=return_xpu(device), **kwargs
244
- ),
245
- lambda orig_func, *args, device=None, **kwargs: check_device(device),
246
- )
247
- CondFunc(
248
- "torch.tensor",
249
- lambda orig_func, *args, device=None, **kwargs: orig_func(
250
- *args, device=return_xpu(device), **kwargs
251
- ),
252
- lambda orig_func, *args, device=None, **kwargs: check_device(device),
253
- )
254
- CondFunc(
255
- "torch.linspace",
256
- lambda orig_func, *args, device=None, **kwargs: orig_func(
257
- *args, device=return_xpu(device), **kwargs
258
- ),
259
- lambda orig_func, *args, device=None, **kwargs: check_device(device),
260
- )
261
-
262
- CondFunc(
263
- "torch.Generator",
264
  lambda orig_func, device=None: torch.xpu.Generator(device),
265
- lambda orig_func, device=None: device is not None
266
- and device != torch.device("cpu")
267
- and device != "cpu",
268
- )
269
-
270
- CondFunc(
271
- "torch.batch_norm",
272
- lambda orig_func, input, weight, bias, *args, **kwargs: orig_func(
273
- input,
274
- weight
275
- if weight is not None
276
- else torch.ones(input.size()[1], device=input.device),
277
- bias
278
- if bias is not None
279
- else torch.zeros(input.size()[1], device=input.device),
280
- *args,
281
- **kwargs,
282
- ),
283
- lambda orig_func, input, *args, **kwargs: input.device != torch.device("cpu"),
284
- )
285
- CondFunc(
286
- "torch.instance_norm",
287
- lambda orig_func, input, weight, bias, *args, **kwargs: orig_func(
288
- input,
289
- weight
290
- if weight is not None
291
- else torch.ones(input.size()[1], device=input.device),
292
- bias
293
- if bias is not None
294
- else torch.zeros(input.size()[1], device=input.device),
295
- *args,
296
- **kwargs,
297
- ),
298
- lambda orig_func, input, *args, **kwargs: input.device != torch.device("cpu"),
299
- )
300
-
301
- # Functions with dtype errors:
302
- CondFunc(
303
- "torch.nn.modules.GroupNorm.forward",
304
- lambda orig_func, self, input: orig_func(
305
- self, input.to(self.weight.data.dtype)
306
- ),
307
- lambda orig_func, self, input: input.dtype != self.weight.data.dtype,
308
- )
309
- CondFunc(
310
- "torch.nn.modules.linear.Linear.forward",
311
- lambda orig_func, self, input: orig_func(
312
- self, input.to(self.weight.data.dtype)
313
- ),
314
- lambda orig_func, self, input: input.dtype != self.weight.data.dtype,
315
- )
316
- CondFunc(
317
- "torch.nn.modules.conv.Conv2d.forward",
318
- lambda orig_func, self, input: orig_func(
319
- self, input.to(self.weight.data.dtype)
320
- ),
321
- lambda orig_func, self, input: input.dtype != self.weight.data.dtype,
322
- )
323
- CondFunc(
324
- "torch.nn.functional.layer_norm",
325
- lambda orig_func, input, normalized_shape=None, weight=None, *args, **kwargs: orig_func(
326
- input.to(weight.data.dtype), normalized_shape, weight, *args, **kwargs
327
- ),
328
- lambda orig_func, input, normalized_shape=None, weight=None, *args, **kwargs: weight
329
- is not None
330
- and input.dtype != weight.data.dtype,
331
- )
332
-
333
- # Diffusers Float64 (ARC GPUs doesn't support double or Float64):
334
  if not torch.xpu.has_fp64_dtype():
335
- CondFunc(
336
- "torch.from_numpy",
337
- lambda orig_func, ndarray: orig_func(ndarray.astype("float32")),
338
- lambda orig_func, ndarray: ndarray.dtype == float,
339
- )
340
 
341
- # Broken functions when torch.cuda.is_available is True:
342
- CondFunc(
343
- "torch.utils.data.dataloader._BaseDataLoaderIter.__init__",
344
  lambda orig_func, *args, **kwargs: ipex_no_cuda(orig_func, *args, **kwargs),
345
- lambda orig_func, *args, **kwargs: True,
346
- )
347
 
348
- # Functions that make compile mad with CondFunc:
349
- torch.utils.data.dataloader._MultiProcessingDataLoaderIter._shutdown_workers = (
350
- _shutdown_workers
351
- )
352
  torch.nn.DataParallel = DummyDataParallel
353
  torch.autocast = ipex_autocast
354
  torch.cat = torch_cat
 
1
  import contextlib
2
  import importlib
3
  import torch
4
+ import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
5
 
6
  # pylint: disable=protected-access, missing-function-docstring, line-too-long, unnecessary-lambda, no-else-return
7
 
8
+ class CondFunc: # pylint: disable=missing-class-docstring
 
9
  def __new__(cls, orig_func, sub_func, cond_func):
10
  self = super(CondFunc, cls).__new__(cls)
11
  if isinstance(orig_func, str):
12
+ func_path = orig_func.split('.')
13
+ for i in range(len(func_path)-1, -1, -1):
14
  try:
15
+ resolved_obj = importlib.import_module('.'.join(func_path[:i]))
16
  break
17
  except ImportError:
18
  pass
19
  for attr_name in func_path[i:-1]:
20
  resolved_obj = getattr(resolved_obj, attr_name)
21
  orig_func = getattr(resolved_obj, func_path[-1])
22
+ setattr(resolved_obj, func_path[-1], lambda *args, **kwargs: self(*args, **kwargs))
 
 
 
 
23
  self.__init__(orig_func, sub_func, cond_func)
24
  return lambda *args, **kwargs: self(*args, **kwargs)
 
25
  def __init__(self, orig_func, sub_func, cond_func):
26
  self.__orig_func = orig_func
27
  self.__sub_func = sub_func
28
  self.__cond_func = cond_func
 
29
  def __call__(self, *args, **kwargs):
30
  if not self.__cond_func or self.__cond_func(self.__orig_func, *args, **kwargs):
31
  return self.__sub_func(self.__orig_func, *args, **kwargs)
32
  else:
33
  return self.__orig_func(*args, **kwargs)
34
 
 
35
  _utils = torch.utils.data._utils
 
 
36
  def _shutdown_workers(self):
37
+ if torch.utils.data._utils is None or torch.utils.data._utils.python_exit_status is True or torch.utils.data._utils.python_exit_status is None:
 
 
 
 
38
  return
39
  if hasattr(self, "_shutdown") and not self._shutdown:
40
  self._shutdown = True
41
  try:
42
+ if hasattr(self, '_pin_memory_thread'):
43
  self._pin_memory_thread_done_event.set()
44
  self._worker_result_queue.put((None, None))
45
  self._pin_memory_thread.join()
 
49
  for worker_id in range(len(self._workers)):
50
  if self._persistent_workers or self._workers_status[worker_id]:
51
  self._mark_worker_as_unavailable(worker_id, shutdown=True)
52
+ for w in self._workers: # pylint: disable=invalid-name
53
  w.join(timeout=torch.utils.data._utils.MP_STATUS_CHECK_INTERVAL)
54
+ for q in self._index_queues: # pylint: disable=invalid-name
55
  q.cancel_join_thread()
56
  q.close()
57
  finally:
58
  if self._worker_pids_set:
59
  torch.utils.data._utils.signal_handling._remove_worker_pids(id(self))
60
  self._worker_pids_set = False
61
+ for w in self._workers: # pylint: disable=invalid-name
62
  if w.is_alive():
63
  w.terminate()
64
 
65
+ class DummyDataParallel(torch.nn.Module): # pylint: disable=missing-class-docstring, unused-argument, too-few-public-methods
66
+ def __new__(cls, module, device_ids=None, output_device=None, dim=0): # pylint: disable=unused-argument
 
 
 
 
 
67
  if isinstance(device_ids, list) and len(device_ids) > 1:
68
  print("IPEX backend doesn't support DataParallel on multiple XPU devices")
69
  return module.to("xpu")
70
 
71
+ def return_null_context(*args, **kwargs): # pylint: disable=unused-argument
 
72
  return contextlib.nullcontext()
73
 
 
74
  def check_device(device):
75
+ return bool((isinstance(device, torch.device) and device.type == "cuda") or (isinstance(device, str) and "cuda" in device) or isinstance(device, int))
 
 
 
 
 
76
 
77
  def return_xpu(device):
78
+ return f"xpu:{device[-1]}" if isinstance(device, str) and ":" in device else f"xpu:{device}" if isinstance(device, int) else torch.device("xpu") if isinstance(device, torch.device) else "xpu"
 
 
 
 
 
 
 
 
 
79
 
80
  def ipex_no_cuda(orig_func, *args, **kwargs):
81
  torch.cuda.is_available = lambda: False
82
  orig_func(*args, **kwargs)
83
  torch.cuda.is_available = torch.xpu.is_available
84
 
 
85
  original_autocast = torch.autocast
 
 
86
  def ipex_autocast(*args, **kwargs):
87
  if len(args) > 0 and args[0] == "cuda":
88
  return original_autocast("xpu", *args[1:], **kwargs)
89
  else:
90
  return original_autocast(*args, **kwargs)
91
 
 
92
  original_torch_cat = torch.cat
 
 
93
  def torch_cat(tensor, *args, **kwargs):
94
+ if len(tensor) == 3 and (tensor[0].dtype != tensor[1].dtype or tensor[2].dtype != tensor[1].dtype):
95
+ return original_torch_cat([tensor[0].to(tensor[1].dtype), tensor[1], tensor[2].to(tensor[1].dtype)], *args, **kwargs)
 
 
 
 
 
 
96
  else:
97
  return original_torch_cat(tensor, *args, **kwargs)
98
 
 
99
  original_interpolate = torch.nn.functional.interpolate
100
+ def interpolate(tensor, size=None, scale_factor=None, mode='nearest', align_corners=None, recompute_scale_factor=None, antialias=False): # pylint: disable=too-many-arguments
 
 
 
 
 
 
 
 
 
 
101
  if antialias or align_corners is not None:
102
  return_device = tensor.device
103
  return_dtype = tensor.dtype
104
+ return original_interpolate(tensor.to("cpu", dtype=torch.float32), size=size, scale_factor=scale_factor, mode=mode,
105
+ align_corners=align_corners, recompute_scale_factor=recompute_scale_factor, antialias=antialias).to(return_device, dtype=return_dtype)
 
 
 
 
 
 
 
106
  else:
107
+ return original_interpolate(tensor, size=size, scale_factor=scale_factor, mode=mode,
108
+ align_corners=align_corners, recompute_scale_factor=recompute_scale_factor, antialias=antialias)
 
 
 
 
 
 
 
 
109
 
110
  original_linalg_solve = torch.linalg.solve
111
+ def linalg_solve(A, B, *args, **kwargs): # pylint: disable=invalid-name
 
 
112
  if A.device != torch.device("cpu") or B.device != torch.device("cpu"):
113
  return_device = A.device
114
+ return original_linalg_solve(A.to("cpu"), B.to("cpu"), *args, **kwargs).to(return_device)
 
 
115
  else:
116
  return original_linalg_solve(A, B, *args, **kwargs)
117
 
 
118
  def ipex_hijacks():
119
+ CondFunc('torch.Tensor.to',
120
+ lambda orig_func, self, device=None, *args, **kwargs: orig_func(self, return_xpu(device), *args, **kwargs),
121
+ lambda orig_func, self, device=None, *args, **kwargs: check_device(device))
122
+ CondFunc('torch.Tensor.cuda',
123
+ lambda orig_func, self, device=None, *args, **kwargs: orig_func(self, return_xpu(device), *args, **kwargs),
124
+ lambda orig_func, self, device=None, *args, **kwargs: check_device(device))
125
+ CondFunc('torch.empty',
126
+ lambda orig_func, *args, device=None, **kwargs: orig_func(*args, device=return_xpu(device), **kwargs),
127
+ lambda orig_func, *args, device=None, **kwargs: check_device(device))
128
+ CondFunc('torch.load',
129
+ lambda orig_func, *args, map_location=None, **kwargs: orig_func(*args, return_xpu(map_location), **kwargs),
130
+ lambda orig_func, *args, map_location=None, **kwargs: map_location is None or check_device(map_location))
131
+ CondFunc('torch.randn',
132
+ lambda orig_func, *args, device=None, **kwargs: orig_func(*args, device=return_xpu(device), **kwargs),
133
+ lambda orig_func, *args, device=None, **kwargs: check_device(device))
134
+ CondFunc('torch.ones',
135
+ lambda orig_func, *args, device=None, **kwargs: orig_func(*args, device=return_xpu(device), **kwargs),
136
+ lambda orig_func, *args, device=None, **kwargs: check_device(device))
137
+ CondFunc('torch.zeros',
138
+ lambda orig_func, *args, device=None, **kwargs: orig_func(*args, device=return_xpu(device), **kwargs),
139
+ lambda orig_func, *args, device=None, **kwargs: check_device(device))
140
+ CondFunc('torch.tensor',
141
+ lambda orig_func, *args, device=None, **kwargs: orig_func(*args, device=return_xpu(device), **kwargs),
142
+ lambda orig_func, *args, device=None, **kwargs: check_device(device))
143
+ CondFunc('torch.linspace',
144
+ lambda orig_func, *args, device=None, **kwargs: orig_func(*args, device=return_xpu(device), **kwargs),
145
+ lambda orig_func, *args, device=None, **kwargs: check_device(device))
146
+
147
+ CondFunc('torch.Generator',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  lambda orig_func, device=None: torch.xpu.Generator(device),
149
+ lambda orig_func, device=None: device is not None and device != torch.device("cpu") and device != "cpu")
150
+
151
+ CondFunc('torch.batch_norm',
152
+ lambda orig_func, input, weight, bias, *args, **kwargs: orig_func(input,
153
+ weight if weight is not None else torch.ones(input.size()[1], device=input.device),
154
+ bias if bias is not None else torch.zeros(input.size()[1], device=input.device), *args, **kwargs),
155
+ lambda orig_func, input, *args, **kwargs: input.device != torch.device("cpu"))
156
+ CondFunc('torch.instance_norm',
157
+ lambda orig_func, input, weight, bias, *args, **kwargs: orig_func(input,
158
+ weight if weight is not None else torch.ones(input.size()[1], device=input.device),
159
+ bias if bias is not None else torch.zeros(input.size()[1], device=input.device), *args, **kwargs),
160
+ lambda orig_func, input, *args, **kwargs: input.device != torch.device("cpu"))
161
+
162
+ #Functions with dtype errors:
163
+ CondFunc('torch.nn.modules.GroupNorm.forward',
164
+ lambda orig_func, self, input: orig_func(self, input.to(self.weight.data.dtype)),
165
+ lambda orig_func, self, input: input.dtype != self.weight.data.dtype)
166
+ CondFunc('torch.nn.modules.linear.Linear.forward',
167
+ lambda orig_func, self, input: orig_func(self, input.to(self.weight.data.dtype)),
168
+ lambda orig_func, self, input: input.dtype != self.weight.data.dtype)
169
+ CondFunc('torch.nn.modules.conv.Conv2d.forward',
170
+ lambda orig_func, self, input: orig_func(self, input.to(self.weight.data.dtype)),
171
+ lambda orig_func, self, input: input.dtype != self.weight.data.dtype)
172
+ CondFunc('torch.nn.functional.layer_norm',
173
+ lambda orig_func, input, normalized_shape=None, weight=None, *args, **kwargs:
174
+ orig_func(input.to(weight.data.dtype), normalized_shape, weight, *args, **kwargs),
175
+ lambda orig_func, input, normalized_shape=None, weight=None, *args, **kwargs:
176
+ weight is not None and input.dtype != weight.data.dtype)
177
+
178
+ #Diffusers Float64 (ARC GPUs doesn't support double or Float64):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  if not torch.xpu.has_fp64_dtype():
180
+ CondFunc('torch.from_numpy',
181
+ lambda orig_func, ndarray: orig_func(ndarray.astype('float32')),
182
+ lambda orig_func, ndarray: ndarray.dtype == float)
 
 
183
 
184
+ #Broken functions when torch.cuda.is_available is True:
185
+ CondFunc('torch.utils.data.dataloader._BaseDataLoaderIter.__init__',
 
186
  lambda orig_func, *args, **kwargs: ipex_no_cuda(orig_func, *args, **kwargs),
187
+ lambda orig_func, *args, **kwargs: True)
 
188
 
189
+ #Functions that make compile mad with CondFunc:
190
+ torch.utils.data.dataloader._MultiProcessingDataLoaderIter._shutdown_workers = _shutdown_workers
 
 
191
  torch.nn.DataParallel = DummyDataParallel
192
  torch.autocast = ipex_autocast
193
  torch.cat = torch_cat
infer/modules/train/train.py CHANGED
@@ -17,15 +17,12 @@ n_gpus = len(hps.gpus.split("-"))
17
  from random import randint, shuffle
18
 
19
  import torch
20
-
21
  try:
22
- import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
23
-
24
  if torch.xpu.is_available():
25
  from infer.modules.ipex import ipex_init
26
  from infer.modules.ipex.gradscaler import gradscaler_init
27
  from torch.xpu.amp import autocast
28
-
29
  GradScaler = gradscaler_init()
30
  ipex_init()
31
  else:
 
17
  from random import randint, shuffle
18
 
19
  import torch
 
20
  try:
21
+ import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
 
22
  if torch.xpu.is_available():
23
  from infer.modules.ipex import ipex_init
24
  from infer.modules.ipex.gradscaler import gradscaler_init
25
  from torch.xpu.amp import autocast
 
26
  GradScaler = gradscaler_init()
27
  ipex_init()
28
  else:
infer/modules/vc/modules.py CHANGED
@@ -209,9 +209,7 @@ class VC:
209
  f0_file,
210
  )
211
  if self.tgt_sr != resample_sr >= 16000:
212
- tgt_sr = resample_sr
213
- else:
214
- tgt_sr = self.tgt_sr
215
  index_info = (
216
  "Index:\n%s." % file_index
217
  if os.path.exists(file_index)
@@ -220,7 +218,7 @@ class VC:
220
  return (
221
  "Success.\n%s\nTime:\nnpy: %.2fs, f0: %.2fs, infer: %.2fs."
222
  % (index_info, *times),
223
- (tgt_sr, audio_opt),
224
  )
225
  except:
226
  info = traceback.format_exc()
@@ -288,13 +286,14 @@ class VC:
288
  tgt_sr,
289
  )
290
  else:
291
- path = "%s/%s.%s" % (
292
- opt_root,
293
- os.path.basename(path),
294
- format1,
295
- )
296
  with BytesIO() as wavf:
297
- sf.write(wavf, audio_opt, tgt_sr, format="wav")
 
 
 
 
 
298
  wavf.seek(0, 0)
299
  with open(path, "wb") as outf:
300
  wav2(wavf, outf, format1)
 
209
  f0_file,
210
  )
211
  if self.tgt_sr != resample_sr >= 16000:
212
+ self.tgt_sr = resample_sr
 
 
213
  index_info = (
214
  "Index:\n%s." % file_index
215
  if os.path.exists(file_index)
 
218
  return (
219
  "Success.\n%s\nTime:\nnpy: %.2fs, f0: %.2fs, infer: %.2fs."
220
  % (index_info, *times),
221
+ (self.tgt_sr, audio_opt),
222
  )
223
  except:
224
  info = traceback.format_exc()
 
286
  tgt_sr,
287
  )
288
  else:
289
+ path = "%s/%s.%s" % (opt_root, os.path.basename(path), format1)
 
 
 
 
290
  with BytesIO() as wavf:
291
+ sf.write(
292
+ wavf,
293
+ audio_opt,
294
+ tgt_sr,
295
+ format="wav"
296
+ )
297
  wavf.seek(0, 0)
298
  with open(path, "wb") as outf:
299
  wav2(wavf, outf, format1)
requirements-dml.txt CHANGED
@@ -1,3 +1,5 @@
 
 
1
  joblib>=1.1.0
2
  numba==0.56.4
3
  numpy==1.23.5
 
1
+ gdown
2
+ mega.py
3
  joblib>=1.1.0
4
  numba==0.56.4
5
  numpy==1.23.5
requirements.txt CHANGED
@@ -1,12 +1,17 @@
 
 
 
 
 
1
  joblib>=1.1.0
2
  numba==0.56.4
3
- numpy==1.23.5
4
  scipy
5
  librosa==0.9.1
6
  llvmlite==0.39.0
7
  fairseq==0.12.2
8
  faiss-cpu==1.7.3
9
- gradio==3.34.0
10
  Cython
11
  pydub>=0.25.1
12
  soundfile>=0.12.1
@@ -45,3 +50,4 @@ fastapi==0.88
45
  ffmpy==0.3.1
46
  python-dotenv>=1.0.0
47
  av
 
 
1
+ torch
2
+ torchvision
3
+ torchaudio
4
+ gdown
5
+ mega.py
6
  joblib>=1.1.0
7
  numba==0.56.4
8
+ numpy==1.22.0
9
  scipy
10
  librosa==0.9.1
11
  llvmlite==0.39.0
12
  fairseq==0.12.2
13
  faiss-cpu==1.7.3
14
+ gradio==3.43.2
15
  Cython
16
  pydub>=0.25.1
17
  soundfile>=0.12.1
 
50
  ffmpy==0.3.1
51
  python-dotenv>=1.0.0
52
  av
53
+ pydantic==1.10.12
tools/rvc_for_realtime.py CHANGED
@@ -357,13 +357,19 @@ class RVC:
357
  with torch.no_grad():
358
  if self.if_f0 == 1:
359
  # print(12222222222,feats.device,p_len.device,cache_pitch.device,cache_pitchf.device,sid.device,rate2)
360
- infered_audio = self.net_g.infer(
361
- feats, p_len, cache_pitch, cache_pitchf, sid, rate
362
- )[0][0, 0].data.float()
 
 
 
 
363
  else:
364
- infered_audio = self.net_g.infer(feats, p_len, sid, rate)[0][
365
- 0, 0
366
- ].data.float()
 
 
367
  t5 = ttime()
368
  logger.info(
369
  "Spent time: fea = %.2fs, index = %.2fs, f0 = %.2fs, model = %.2fs",
 
357
  with torch.no_grad():
358
  if self.if_f0 == 1:
359
  # print(12222222222,feats.device,p_len.device,cache_pitch.device,cache_pitchf.device,sid.device,rate2)
360
+ infered_audio = (
361
+ self.net_g.infer(
362
+ feats, p_len, cache_pitch, cache_pitchf, sid, rate
363
+ )[0][0, 0]
364
+ .data
365
+ .float()
366
+ )
367
  else:
368
+ infered_audio = (
369
+ self.net_g.infer(feats, p_len, sid, rate)[0][0, 0]
370
+ .data
371
+ .float()
372
+ )
373
  t5 = ttime()
374
  logger.info(
375
  "Spent time: fea = %.2fs, index = %.2fs, f0 = %.2fs, model = %.2fs",
tools/torchgate/utils.py CHANGED
@@ -3,9 +3,7 @@ from torch.types import Number
3
 
4
 
5
  @torch.no_grad()
6
- def amp_to_db(
7
- x: torch.Tensor, eps=torch.finfo(torch.float64).eps, top_db=40
8
- ) -> torch.Tensor:
9
  """
10
  Convert the input tensor from amplitude to decibel scale.
11
 
@@ -42,9 +40,7 @@ def temperature_sigmoid(x: torch.Tensor, x0: float, temp_coeff: float) -> torch.
42
 
43
 
44
  @torch.no_grad()
45
- def linspace(
46
- start: Number, stop: Number, num: int = 50, endpoint: bool = True, **kwargs
47
- ) -> torch.Tensor:
48
  """
49
  Generate a linearly spaced 1-D tensor.
50
 
 
3
 
4
 
5
  @torch.no_grad()
6
+ def amp_to_db(x: torch.Tensor, eps=torch.finfo(torch.float64).eps, top_db=40) -> torch.Tensor:
 
 
7
  """
8
  Convert the input tensor from amplitude to decibel scale.
9
 
 
40
 
41
 
42
  @torch.no_grad()
43
+ def linspace(start: Number, stop: Number, num: int = 50, endpoint: bool = True, **kwargs) -> torch.Tensor:
 
 
44
  """
45
  Generate a linearly spaced 1-D tensor.
46