id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
9,162
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import os import math import argparse import numpy as np import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms from torch.autograd import Variable from torch.nn import init from models import nin_gc, nin, resnet import quantize def adjust_learning_rate(optimizer, epoch): update_list = [80, 130, 180, 230, 280] if epoch in update_list: for param_group in optimizer.param_groups: param_group["lr"] = param_group["lr"] * 0.1 return
null
9,163
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import os import math import argparse import numpy as np import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms from torch.autograd import Variable from torch.nn import init from models import nin_gc, nin, resnet import quantize def train(epoch): model.train() batch_num = 0 for batch_idx, (data, target) in enumerate(trainloader): if not args.cpu: data, target = data.cuda(), target.cuda() data, target = Variable(data), Variable(target) output = model(data) loss = criterion(output, target) # PTQ doesn't need backward if not args.ptq_control: optimizer.zero_grad() loss.backward() optimizer.step() if batch_idx % 100 == 0: print( "Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}\tLR: {}".format( epoch, batch_idx * len(data), len(trainloader.dataset), 100.0 * batch_idx / len(trainloader), loss.data.item(), optimizer.param_groups[0]["lr"], ) ) else: batch_num += 1 if batch_num > args.ptq_batch: break print("Batch:", batch_num) return
null
9,164
import copy import torch import torch.nn as nn import torch.nn.functional as F from torch import distributed from torch.nn import init from torch.nn.parameter import Parameter from torch.autograd import Function from micronet.base_module.op import * def reshape_to_activation(input): return input.reshape(1, -1, 1, 1) def reshape_to_weight(input): return input.reshape(-1, 1, 1, 1) def reshape_to_bias(input): return input.reshape(-1) def __init__( self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False, padding_mode="zeros", eps=1e-5, momentum=0.1, a_bits=8, w_bits=8, q_type=0, q_level=0, weight_observer=0, pretrained_model=False, qaft=False, ptq=False, percentile=0.9999, bn_fuse_calib=False, ): super(QuantBNFuseConv2d, self).__init__( in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, padding_mode, ) self.num_flag = 0 self.pretrained_model = pretrained_model self.qaft = qaft self.bn_fuse_calib = bn_fuse_calib self.eps = eps self.momentum = momentum self.gamma = Parameter(torch.Tensor(out_channels)) self.beta = Parameter(torch.Tensor(out_channels)) self.register_buffer( "running_mean", torch.zeros((out_channels), dtype=torch.float32) ) self.register_buffer( "running_var", torch.ones((out_channels), dtype=torch.float32) ) init.uniform_(self.gamma) init.zeros_(self.beta) if not ptq: if q_type == 0: self.activation_quantizer = SymmetricQuantizer( bits=a_bits, observer=MovingAverageMinMaxObserver( q_level="L", out_channels=None ), activation_weight_flag=1, qaft=qaft, ) if weight_observer == 0: if q_level == 0: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MinMaxObserver( q_level="C", out_channels=out_channels ), activation_weight_flag=0, qaft=qaft, ) else: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MinMaxObserver(q_level="L", out_channels=None), activation_weight_flag=0, qaft=qaft, ) else: if q_level == 0: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MovingAverageMinMaxObserver( q_level="C", out_channels=out_channels ), activation_weight_flag=0, qaft=qaft, ) else: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MovingAverageMinMaxObserver( q_level="L", out_channels=None ), activation_weight_flag=0, qaft=qaft, ) else: self.activation_quantizer = AsymmetricQuantizer( bits=a_bits, observer=MovingAverageMinMaxObserver( q_level="L", out_channels=None ), activation_weight_flag=1, qaft=qaft, ) if weight_observer == 0: if q_level == 0: self.weight_quantizer = AsymmetricQuantizer( bits=w_bits, observer=MinMaxObserver( q_level="C", out_channels=out_channels ), activation_weight_flag=0, qaft=qaft, ) else: self.weight_quantizer = AsymmetricQuantizer( bits=w_bits, observer=MinMaxObserver(q_level="L", out_channels=None), activation_weight_flag=0, qaft=qaft, ) else: if q_level == 0: self.weight_quantizer = AsymmetricQuantizer( bits=w_bits, observer=MovingAverageMinMaxObserver( q_level="C", out_channels=out_channels ), activation_weight_flag=0, qaft=qaft, ) else: self.weight_quantizer = AsymmetricQuantizer( bits=w_bits, observer=MovingAverageMinMaxObserver( q_level="L", out_channels=None ), activation_weight_flag=0, qaft=qaft, ) else: self.activation_quantizer = SymmetricQuantizer( bits=a_bits, observer=HistogramObserver(q_level="L", percentile=percentile), activation_weight_flag=1, qaft=qaft, ) if weight_observer == 0: if q_level == 0: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MinMaxObserver(q_level="C", out_channels=out_channels), activation_weight_flag=0, qaft=qaft, ) else: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MinMaxObserver(q_level="L", out_channels=None), activation_weight_flag=0, qaft=qaft, ) else: if q_level == 0: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MovingAverageMinMaxObserver( q_level="C", out_channels=out_channels ), activation_weight_flag=0, qaft=qaft, ) else: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MovingAverageMinMaxObserver( q_level="L", out_channels=None ), activation_weight_flag=0, qaft=qaft, ) def forward(self, input): if not self.qaft: # qat, calibrate bn_statis_para # 训练态 if self.training: # 先做普通卷积得到A,以取得BN参数 output = F.conv2d( input, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups, ) # 更新BN统计参数(batch和running) dims = [dim for dim in range(4) if dim != 1] batch_mean = torch.mean(output, dim=dims) batch_var = torch.var(output, dim=dims) with torch.no_grad(): if not self.pretrained_model: if self.num_flag == 0: self.num_flag += 1 running_mean = batch_mean running_var = batch_var else: running_mean = ( 1 - self.momentum ) * self.running_mean + self.momentum * batch_mean running_var = ( 1 - self.momentum ) * self.running_var + self.momentum * batch_var self.running_mean.copy_(running_mean) self.running_var.copy_(running_var) else: running_mean = ( 1 - self.momentum ) * self.running_mean + self.momentum * batch_mean running_var = ( 1 - self.momentum ) * self.running_var + self.momentum * batch_var self.running_mean.copy_(running_mean) self.running_var.copy_(running_var) # bn融合 if self.bias is not None: bias_fused = reshape_to_bias( self.beta + (self.bias - batch_mean) * (self.gamma / torch.sqrt(batch_var + self.eps)) ) else: bias_fused = reshape_to_bias( self.beta - batch_mean * (self.gamma / torch.sqrt(batch_var + self.eps)) ) # b融batch # bn融合不校准 if not self.bn_fuse_calib: weight_fused = self.weight * reshape_to_weight( self.gamma / torch.sqrt(batch_var + self.eps) ) # w融batch # bn融合校准 else: weight_fused = self.weight * reshape_to_weight( self.gamma / torch.sqrt(self.running_var + self.eps) ) # w融running # 测试态 else: if self.bias is not None: bias_fused = reshape_to_bias( self.beta + (self.bias - self.running_mean) * (self.gamma / torch.sqrt(self.running_var + self.eps)) ) else: bias_fused = reshape_to_bias( self.beta - self.running_mean * (self.gamma / torch.sqrt(self.running_var + self.eps)) ) # b融running weight_fused = self.weight * reshape_to_weight( self.gamma / torch.sqrt(self.running_var + self.eps) ) # w融running else: # qaft, freeze bn_statis_para if self.bias is not None: bias_fused = reshape_to_bias( self.beta + (self.bias - self.running_mean) * (self.gamma / torch.sqrt(self.running_var + self.eps)) ) else: bias_fused = reshape_to_bias( self.beta - self.running_mean * (self.gamma / torch.sqrt(self.running_var + self.eps)) ) # b融running weight_fused = self.weight * reshape_to_weight( self.gamma / torch.sqrt(self.running_var + self.eps) ) # w融running # 量化A和bn融合后的W quant_input = self.activation_quantizer(input) quant_weight = self.weight_quantizer(weight_fused) if not self.qaft: # qat, quant_bn_fuse_conv # 量化卷积 if self.training: # 训练态 # bn融合不校准 if not self.bn_fuse_calib: output = F.conv2d( quant_input, quant_weight, bias_fused, self.stride, self.padding, self.dilation, self.groups, ) # bn融合校准 else: output = F.conv2d( quant_input, quant_weight, None, self.stride, self.padding, self.dilation, self.groups, ) # 注意,这里不加bias(self.bias为None) # (这里将训练态下,卷积中w融合running参数的效果转为融合batch参数的效果)running ——> batch output *= reshape_to_activation( torch.sqrt(self.running_var + self.eps) / torch.sqrt(batch_var + self.eps) ) output += reshape_to_activation(bias_fused) else: # 测试态 output = F.conv2d( quant_input, quant_weight, bias_fused, self.stride, self.padding, self.dilation, self.groups, ) # 注意,这里加bias,做完整的conv+bn else: # qaft, quant_bn_fuse_conv output = F.conv2d( quant_input, quant_weight, bias_fused, self.stride, self.padding, self.dilation, self.groups, ) return output def add_quant_op( module, a_bits=8, w_bits=8, q_type=0, q_level=0, weight_observer=0, bn_fuse=False, bn_fuse_calib=False, quant_inference=False, pretrained_model=False, qaft=False, ptq=False, percentile=0.9999, ): for name, child in module.named_children(): if isinstance(child, nn.Conv2d): if bn_fuse: conv_name_temp = name conv_child_temp = child else: if child.bias is not None: quant_conv = QuantConv2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, dilation=child.dilation, groups=child.groups, bias=True, padding_mode=child.padding_mode, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, quant_inference=quant_inference, qaft=qaft, ptq=ptq, percentile=percentile, ) quant_conv.bias.data = child.bias else: quant_conv = QuantConv2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, dilation=child.dilation, groups=child.groups, bias=False, padding_mode=child.padding_mode, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, quant_inference=quant_inference, qaft=qaft, ptq=ptq, percentile=percentile, ) quant_conv.weight.data = child.weight module._modules[name] = quant_conv elif isinstance(child, nn.BatchNorm2d): if bn_fuse: if conv_child_temp.bias is not None: quant_bn_fuse_conv = QuantBNFuseConv2d( conv_child_temp.in_channels, conv_child_temp.out_channels, conv_child_temp.kernel_size, stride=conv_child_temp.stride, padding=conv_child_temp.padding, dilation=conv_child_temp.dilation, groups=conv_child_temp.groups, bias=True, padding_mode=conv_child_temp.padding_mode, eps=child.eps, momentum=child.momentum, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, pretrained_model=pretrained_model, qaft=qaft, ptq=ptq, percentile=percentile, bn_fuse_calib=bn_fuse_calib, ) quant_bn_fuse_conv.bias.data = conv_child_temp.bias else: quant_bn_fuse_conv = QuantBNFuseConv2d( conv_child_temp.in_channels, conv_child_temp.out_channels, conv_child_temp.kernel_size, stride=conv_child_temp.stride, padding=conv_child_temp.padding, dilation=conv_child_temp.dilation, groups=conv_child_temp.groups, bias=False, padding_mode=conv_child_temp.padding_mode, eps=child.eps, momentum=child.momentum, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, pretrained_model=pretrained_model, qaft=qaft, ptq=ptq, percentile=percentile, bn_fuse_calib=bn_fuse_calib, ) quant_bn_fuse_conv.weight.data = conv_child_temp.weight quant_bn_fuse_conv.gamma.data = child.weight quant_bn_fuse_conv.beta.data = child.bias quant_bn_fuse_conv.running_mean.copy_(child.running_mean) quant_bn_fuse_conv.running_var.copy_(child.running_var) module._modules[conv_name_temp] = quant_bn_fuse_conv module._modules[name] = nn.Identity() elif isinstance(child, nn.ConvTranspose2d): if child.bias is not None: quant_conv_transpose = QuantConvTranspose2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, output_padding=child.output_padding, groups=child.groups, bias=True, dilation=child.dilation, padding_mode=child.padding_mode, a_bits=a_bits, w_bits=w_bits, q_type=q_type, weight_observer=weight_observer, quant_inference=quant_inference, qaft=qaft, ptq=ptq, percentile=percentile, ) quant_conv_transpose.bias.data = child.bias else: quant_conv_transpose = QuantConvTranspose2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, output_padding=child.output_padding, groups=child.groups, bias=False, dilation=child.dilation, padding_mode=child.padding_mode, a_bits=a_bits, w_bits=w_bits, q_type=q_type, weight_observer=weight_observer, quant_inference=quant_inference, qaft=qaft, ptq=ptq, percentile=percentile, ) quant_conv_transpose.weight.data = child.weight module._modules[name] = quant_conv_transpose elif isinstance(child, nn.Linear): if child.bias is not None: quant_linear = QuantLinear( child.in_features, child.out_features, bias=True, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, quant_inference=quant_inference, qaft=qaft, ptq=ptq, percentile=percentile, ) quant_linear.bias.data = child.bias else: quant_linear = QuantLinear( child.in_features, child.out_features, bias=False, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, quant_inference=quant_inference, qaft=qaft, ptq=ptq, percentile=percentile, ) quant_linear.weight.data = child.weight module._modules[name] = quant_linear # relu needn’t quantize, it will be fused in quant_inference # elif isinstance(child, nn.ReLU): # quant_relu = QuantReLU(inplace=child.inplace, a_bits=a_bits, # q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile) # module._modules[name] = quant_relu elif isinstance(child, nn.LeakyReLU): quant_leaky_relu = QuantLeakyReLU( negative_slope=child.negative_slope, inplace=child.inplace, a_bits=a_bits, q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile, ) module._modules[name] = quant_leaky_relu elif isinstance(child, nn.Sigmoid): quant_sigmoid = QuantSigmoid( a_bits=a_bits, q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile ) module._modules[name] = quant_sigmoid elif isinstance(child, nn.MaxPool2d): quant_max_pool = QuantMaxPool2d( kernel_size=child.kernel_size, stride=child.stride, padding=child.padding, a_bits=a_bits, q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile, ) module._modules[name] = quant_max_pool elif isinstance(child, nn.AvgPool2d): quant_avg_pool = QuantAvgPool2d( kernel_size=child.kernel_size, stride=child.stride, padding=child.padding, a_bits=a_bits, q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile, ) module._modules[name] = quant_avg_pool elif isinstance(child, nn.AdaptiveAvgPool2d): quant_adaptive_avg_pool = QuantAdaptiveAvgPool2d( output_size=child.output_size, a_bits=a_bits, q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile, ) module._modules[name] = quant_adaptive_avg_pool elif isinstance(child, Add): quant_add = QuantAdd( a_bits=a_bits, q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile ) module._modules[name] = quant_add # elif isinstance(child, Concat): # quant_concat = QuantConcat(dim=child.dim, # a_bits=a_bits, # q_type=q_type, # qaft=qaft, # ptq=ptq, # percentile=percentile) # module._modules[name] = quant_concat else: add_quant_op( child, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, bn_fuse=bn_fuse, bn_fuse_calib=bn_fuse_calib, quant_inference=quant_inference, pretrained_model=pretrained_model, qaft=qaft, ptq=ptq, percentile=percentile, ) def reshape_to_activation(input): return input.reshape(1, -1, 1, 1)
null
9,165
import copy import torch import torch.nn as nn import torch.nn.functional as F from torch import distributed from torch.nn import init from torch.nn.parameter import Parameter from torch.autograd import Function from micronet.base_module.op import * def reshape_to_activation(input): return input.reshape(1, -1, 1, 1) def reshape_to_weight(input): return input.reshape(-1, 1, 1, 1) def reshape_to_bias(input): return input.reshape(-1) def __init__( self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False, padding_mode="zeros", eps=1e-5, momentum=0.1, a_bits=8, w_bits=8, q_type=0, q_level=0, weight_observer=0, pretrained_model=False, qaft=False, ptq=False, percentile=0.9999, bn_fuse_calib=False, ): super(QuantBNFuseConv2d, self).__init__( in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, padding_mode, ) self.num_flag = 0 self.pretrained_model = pretrained_model self.qaft = qaft self.bn_fuse_calib = bn_fuse_calib self.eps = eps self.momentum = momentum self.gamma = Parameter(torch.Tensor(out_channels)) self.beta = Parameter(torch.Tensor(out_channels)) self.register_buffer( "running_mean", torch.zeros((out_channels), dtype=torch.float32) ) self.register_buffer( "running_var", torch.ones((out_channels), dtype=torch.float32) ) init.uniform_(self.gamma) init.zeros_(self.beta) if not ptq: if q_type == 0: self.activation_quantizer = SymmetricQuantizer( bits=a_bits, observer=MovingAverageMinMaxObserver( q_level="L", out_channels=None ), activation_weight_flag=1, qaft=qaft, ) if weight_observer == 0: if q_level == 0: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MinMaxObserver( q_level="C", out_channels=out_channels ), activation_weight_flag=0, qaft=qaft, ) else: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MinMaxObserver(q_level="L", out_channels=None), activation_weight_flag=0, qaft=qaft, ) else: if q_level == 0: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MovingAverageMinMaxObserver( q_level="C", out_channels=out_channels ), activation_weight_flag=0, qaft=qaft, ) else: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MovingAverageMinMaxObserver( q_level="L", out_channels=None ), activation_weight_flag=0, qaft=qaft, ) else: self.activation_quantizer = AsymmetricQuantizer( bits=a_bits, observer=MovingAverageMinMaxObserver( q_level="L", out_channels=None ), activation_weight_flag=1, qaft=qaft, ) if weight_observer == 0: if q_level == 0: self.weight_quantizer = AsymmetricQuantizer( bits=w_bits, observer=MinMaxObserver( q_level="C", out_channels=out_channels ), activation_weight_flag=0, qaft=qaft, ) else: self.weight_quantizer = AsymmetricQuantizer( bits=w_bits, observer=MinMaxObserver(q_level="L", out_channels=None), activation_weight_flag=0, qaft=qaft, ) else: if q_level == 0: self.weight_quantizer = AsymmetricQuantizer( bits=w_bits, observer=MovingAverageMinMaxObserver( q_level="C", out_channels=out_channels ), activation_weight_flag=0, qaft=qaft, ) else: self.weight_quantizer = AsymmetricQuantizer( bits=w_bits, observer=MovingAverageMinMaxObserver( q_level="L", out_channels=None ), activation_weight_flag=0, qaft=qaft, ) else: self.activation_quantizer = SymmetricQuantizer( bits=a_bits, observer=HistogramObserver(q_level="L", percentile=percentile), activation_weight_flag=1, qaft=qaft, ) if weight_observer == 0: if q_level == 0: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MinMaxObserver(q_level="C", out_channels=out_channels), activation_weight_flag=0, qaft=qaft, ) else: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MinMaxObserver(q_level="L", out_channels=None), activation_weight_flag=0, qaft=qaft, ) else: if q_level == 0: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MovingAverageMinMaxObserver( q_level="C", out_channels=out_channels ), activation_weight_flag=0, qaft=qaft, ) else: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MovingAverageMinMaxObserver( q_level="L", out_channels=None ), activation_weight_flag=0, qaft=qaft, ) def forward(self, input): if not self.qaft: # qat, calibrate bn_statis_para # 训练态 if self.training: # 先做普通卷积得到A,以取得BN参数 output = F.conv2d( input, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups, ) # 更新BN统计参数(batch和running) dims = [dim for dim in range(4) if dim != 1] batch_mean = torch.mean(output, dim=dims) batch_var = torch.var(output, dim=dims) with torch.no_grad(): if not self.pretrained_model: if self.num_flag == 0: self.num_flag += 1 running_mean = batch_mean running_var = batch_var else: running_mean = ( 1 - self.momentum ) * self.running_mean + self.momentum * batch_mean running_var = ( 1 - self.momentum ) * self.running_var + self.momentum * batch_var self.running_mean.copy_(running_mean) self.running_var.copy_(running_var) else: running_mean = ( 1 - self.momentum ) * self.running_mean + self.momentum * batch_mean running_var = ( 1 - self.momentum ) * self.running_var + self.momentum * batch_var self.running_mean.copy_(running_mean) self.running_var.copy_(running_var) # bn融合 if self.bias is not None: bias_fused = reshape_to_bias( self.beta + (self.bias - batch_mean) * (self.gamma / torch.sqrt(batch_var + self.eps)) ) else: bias_fused = reshape_to_bias( self.beta - batch_mean * (self.gamma / torch.sqrt(batch_var + self.eps)) ) # b融batch # bn融合不校准 if not self.bn_fuse_calib: weight_fused = self.weight * reshape_to_weight( self.gamma / torch.sqrt(batch_var + self.eps) ) # w融batch # bn融合校准 else: weight_fused = self.weight * reshape_to_weight( self.gamma / torch.sqrt(self.running_var + self.eps) ) # w融running # 测试态 else: if self.bias is not None: bias_fused = reshape_to_bias( self.beta + (self.bias - self.running_mean) * (self.gamma / torch.sqrt(self.running_var + self.eps)) ) else: bias_fused = reshape_to_bias( self.beta - self.running_mean * (self.gamma / torch.sqrt(self.running_var + self.eps)) ) # b融running weight_fused = self.weight * reshape_to_weight( self.gamma / torch.sqrt(self.running_var + self.eps) ) # w融running else: # qaft, freeze bn_statis_para if self.bias is not None: bias_fused = reshape_to_bias( self.beta + (self.bias - self.running_mean) * (self.gamma / torch.sqrt(self.running_var + self.eps)) ) else: bias_fused = reshape_to_bias( self.beta - self.running_mean * (self.gamma / torch.sqrt(self.running_var + self.eps)) ) # b融running weight_fused = self.weight * reshape_to_weight( self.gamma / torch.sqrt(self.running_var + self.eps) ) # w融running # 量化A和bn融合后的W quant_input = self.activation_quantizer(input) quant_weight = self.weight_quantizer(weight_fused) if not self.qaft: # qat, quant_bn_fuse_conv # 量化卷积 if self.training: # 训练态 # bn融合不校准 if not self.bn_fuse_calib: output = F.conv2d( quant_input, quant_weight, bias_fused, self.stride, self.padding, self.dilation, self.groups, ) # bn融合校准 else: output = F.conv2d( quant_input, quant_weight, None, self.stride, self.padding, self.dilation, self.groups, ) # 注意,这里不加bias(self.bias为None) # (这里将训练态下,卷积中w融合running参数的效果转为融合batch参数的效果)running ——> batch output *= reshape_to_activation( torch.sqrt(self.running_var + self.eps) / torch.sqrt(batch_var + self.eps) ) output += reshape_to_activation(bias_fused) else: # 测试态 output = F.conv2d( quant_input, quant_weight, bias_fused, self.stride, self.padding, self.dilation, self.groups, ) # 注意,这里加bias,做完整的conv+bn else: # qaft, quant_bn_fuse_conv output = F.conv2d( quant_input, quant_weight, bias_fused, self.stride, self.padding, self.dilation, self.groups, ) return output def add_quant_op( module, a_bits=8, w_bits=8, q_type=0, q_level=0, weight_observer=0, bn_fuse=False, bn_fuse_calib=False, quant_inference=False, pretrained_model=False, qaft=False, ptq=False, percentile=0.9999, ): for name, child in module.named_children(): if isinstance(child, nn.Conv2d): if bn_fuse: conv_name_temp = name conv_child_temp = child else: if child.bias is not None: quant_conv = QuantConv2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, dilation=child.dilation, groups=child.groups, bias=True, padding_mode=child.padding_mode, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, quant_inference=quant_inference, qaft=qaft, ptq=ptq, percentile=percentile, ) quant_conv.bias.data = child.bias else: quant_conv = QuantConv2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, dilation=child.dilation, groups=child.groups, bias=False, padding_mode=child.padding_mode, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, quant_inference=quant_inference, qaft=qaft, ptq=ptq, percentile=percentile, ) quant_conv.weight.data = child.weight module._modules[name] = quant_conv elif isinstance(child, nn.BatchNorm2d): if bn_fuse: if conv_child_temp.bias is not None: quant_bn_fuse_conv = QuantBNFuseConv2d( conv_child_temp.in_channels, conv_child_temp.out_channels, conv_child_temp.kernel_size, stride=conv_child_temp.stride, padding=conv_child_temp.padding, dilation=conv_child_temp.dilation, groups=conv_child_temp.groups, bias=True, padding_mode=conv_child_temp.padding_mode, eps=child.eps, momentum=child.momentum, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, pretrained_model=pretrained_model, qaft=qaft, ptq=ptq, percentile=percentile, bn_fuse_calib=bn_fuse_calib, ) quant_bn_fuse_conv.bias.data = conv_child_temp.bias else: quant_bn_fuse_conv = QuantBNFuseConv2d( conv_child_temp.in_channels, conv_child_temp.out_channels, conv_child_temp.kernel_size, stride=conv_child_temp.stride, padding=conv_child_temp.padding, dilation=conv_child_temp.dilation, groups=conv_child_temp.groups, bias=False, padding_mode=conv_child_temp.padding_mode, eps=child.eps, momentum=child.momentum, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, pretrained_model=pretrained_model, qaft=qaft, ptq=ptq, percentile=percentile, bn_fuse_calib=bn_fuse_calib, ) quant_bn_fuse_conv.weight.data = conv_child_temp.weight quant_bn_fuse_conv.gamma.data = child.weight quant_bn_fuse_conv.beta.data = child.bias quant_bn_fuse_conv.running_mean.copy_(child.running_mean) quant_bn_fuse_conv.running_var.copy_(child.running_var) module._modules[conv_name_temp] = quant_bn_fuse_conv module._modules[name] = nn.Identity() elif isinstance(child, nn.ConvTranspose2d): if child.bias is not None: quant_conv_transpose = QuantConvTranspose2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, output_padding=child.output_padding, groups=child.groups, bias=True, dilation=child.dilation, padding_mode=child.padding_mode, a_bits=a_bits, w_bits=w_bits, q_type=q_type, weight_observer=weight_observer, quant_inference=quant_inference, qaft=qaft, ptq=ptq, percentile=percentile, ) quant_conv_transpose.bias.data = child.bias else: quant_conv_transpose = QuantConvTranspose2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, output_padding=child.output_padding, groups=child.groups, bias=False, dilation=child.dilation, padding_mode=child.padding_mode, a_bits=a_bits, w_bits=w_bits, q_type=q_type, weight_observer=weight_observer, quant_inference=quant_inference, qaft=qaft, ptq=ptq, percentile=percentile, ) quant_conv_transpose.weight.data = child.weight module._modules[name] = quant_conv_transpose elif isinstance(child, nn.Linear): if child.bias is not None: quant_linear = QuantLinear( child.in_features, child.out_features, bias=True, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, quant_inference=quant_inference, qaft=qaft, ptq=ptq, percentile=percentile, ) quant_linear.bias.data = child.bias else: quant_linear = QuantLinear( child.in_features, child.out_features, bias=False, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, quant_inference=quant_inference, qaft=qaft, ptq=ptq, percentile=percentile, ) quant_linear.weight.data = child.weight module._modules[name] = quant_linear # relu needn’t quantize, it will be fused in quant_inference # elif isinstance(child, nn.ReLU): # quant_relu = QuantReLU(inplace=child.inplace, a_bits=a_bits, # q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile) # module._modules[name] = quant_relu elif isinstance(child, nn.LeakyReLU): quant_leaky_relu = QuantLeakyReLU( negative_slope=child.negative_slope, inplace=child.inplace, a_bits=a_bits, q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile, ) module._modules[name] = quant_leaky_relu elif isinstance(child, nn.Sigmoid): quant_sigmoid = QuantSigmoid( a_bits=a_bits, q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile ) module._modules[name] = quant_sigmoid elif isinstance(child, nn.MaxPool2d): quant_max_pool = QuantMaxPool2d( kernel_size=child.kernel_size, stride=child.stride, padding=child.padding, a_bits=a_bits, q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile, ) module._modules[name] = quant_max_pool elif isinstance(child, nn.AvgPool2d): quant_avg_pool = QuantAvgPool2d( kernel_size=child.kernel_size, stride=child.stride, padding=child.padding, a_bits=a_bits, q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile, ) module._modules[name] = quant_avg_pool elif isinstance(child, nn.AdaptiveAvgPool2d): quant_adaptive_avg_pool = QuantAdaptiveAvgPool2d( output_size=child.output_size, a_bits=a_bits, q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile, ) module._modules[name] = quant_adaptive_avg_pool elif isinstance(child, Add): quant_add = QuantAdd( a_bits=a_bits, q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile ) module._modules[name] = quant_add # elif isinstance(child, Concat): # quant_concat = QuantConcat(dim=child.dim, # a_bits=a_bits, # q_type=q_type, # qaft=qaft, # ptq=ptq, # percentile=percentile) # module._modules[name] = quant_concat else: add_quant_op( child, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, bn_fuse=bn_fuse, bn_fuse_calib=bn_fuse_calib, quant_inference=quant_inference, pretrained_model=pretrained_model, qaft=qaft, ptq=ptq, percentile=percentile, ) def reshape_to_weight(input): return input.reshape(-1, 1, 1, 1)
null
9,166
import copy import torch import torch.nn as nn import torch.nn.functional as F from torch import distributed from torch.nn import init from torch.nn.parameter import Parameter from torch.autograd import Function from micronet.base_module.op import * def reshape_to_activation(input): def reshape_to_weight(input): def reshape_to_bias(input): def __init__( self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False, padding_mode="zeros", eps=1e-5, momentum=0.1, a_bits=8, w_bits=8, q_type=0, q_level=0, weight_observer=0, pretrained_model=False, qaft=False, ptq=False, percentile=0.9999, bn_fuse_calib=False, ): def forward(self, input): def add_quant_op( module, a_bits=8, w_bits=8, q_type=0, q_level=0, weight_observer=0, bn_fuse=False, bn_fuse_calib=False, quant_inference=False, pretrained_model=False, qaft=False, ptq=False, percentile=0.9999, ): def reshape_to_bias(input): return input.reshape(-1)
null
9,167
import copy import torch import torch.nn as nn import torch.nn.functional as F from torch import distributed from torch.nn import init from torch.nn.parameter import Parameter from torch.autograd import Function from micronet.base_module.op import * def reshape_to_activation(input): return input.reshape(1, -1, 1, 1) def reshape_to_weight(input): return input.reshape(-1, 1, 1, 1) def reshape_to_bias(input): return input.reshape(-1) def __init__( self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False, padding_mode="zeros", eps=1e-5, momentum=0.1, a_bits=8, w_bits=8, q_type=0, q_level=0, weight_observer=0, pretrained_model=False, qaft=False, ptq=False, percentile=0.9999, bn_fuse_calib=False, ): super(QuantBNFuseConv2d, self).__init__( in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, padding_mode, ) self.num_flag = 0 self.pretrained_model = pretrained_model self.qaft = qaft self.bn_fuse_calib = bn_fuse_calib self.eps = eps self.momentum = momentum self.gamma = Parameter(torch.Tensor(out_channels)) self.beta = Parameter(torch.Tensor(out_channels)) self.register_buffer( "running_mean", torch.zeros((out_channels), dtype=torch.float32) ) self.register_buffer( "running_var", torch.ones((out_channels), dtype=torch.float32) ) init.uniform_(self.gamma) init.zeros_(self.beta) if not ptq: if q_type == 0: self.activation_quantizer = SymmetricQuantizer( bits=a_bits, observer=MovingAverageMinMaxObserver( q_level="L", out_channels=None ), activation_weight_flag=1, qaft=qaft, ) if weight_observer == 0: if q_level == 0: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MinMaxObserver( q_level="C", out_channels=out_channels ), activation_weight_flag=0, qaft=qaft, ) else: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MinMaxObserver(q_level="L", out_channels=None), activation_weight_flag=0, qaft=qaft, ) else: if q_level == 0: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MovingAverageMinMaxObserver( q_level="C", out_channels=out_channels ), activation_weight_flag=0, qaft=qaft, ) else: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MovingAverageMinMaxObserver( q_level="L", out_channels=None ), activation_weight_flag=0, qaft=qaft, ) else: self.activation_quantizer = AsymmetricQuantizer( bits=a_bits, observer=MovingAverageMinMaxObserver( q_level="L", out_channels=None ), activation_weight_flag=1, qaft=qaft, ) if weight_observer == 0: if q_level == 0: self.weight_quantizer = AsymmetricQuantizer( bits=w_bits, observer=MinMaxObserver( q_level="C", out_channels=out_channels ), activation_weight_flag=0, qaft=qaft, ) else: self.weight_quantizer = AsymmetricQuantizer( bits=w_bits, observer=MinMaxObserver(q_level="L", out_channels=None), activation_weight_flag=0, qaft=qaft, ) else: if q_level == 0: self.weight_quantizer = AsymmetricQuantizer( bits=w_bits, observer=MovingAverageMinMaxObserver( q_level="C", out_channels=out_channels ), activation_weight_flag=0, qaft=qaft, ) else: self.weight_quantizer = AsymmetricQuantizer( bits=w_bits, observer=MovingAverageMinMaxObserver( q_level="L", out_channels=None ), activation_weight_flag=0, qaft=qaft, ) else: self.activation_quantizer = SymmetricQuantizer( bits=a_bits, observer=HistogramObserver(q_level="L", percentile=percentile), activation_weight_flag=1, qaft=qaft, ) if weight_observer == 0: if q_level == 0: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MinMaxObserver(q_level="C", out_channels=out_channels), activation_weight_flag=0, qaft=qaft, ) else: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MinMaxObserver(q_level="L", out_channels=None), activation_weight_flag=0, qaft=qaft, ) else: if q_level == 0: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MovingAverageMinMaxObserver( q_level="C", out_channels=out_channels ), activation_weight_flag=0, qaft=qaft, ) else: self.weight_quantizer = SymmetricQuantizer( bits=w_bits, observer=MovingAverageMinMaxObserver( q_level="L", out_channels=None ), activation_weight_flag=0, qaft=qaft, ) def forward(self, input): if not self.qaft: # qat, calibrate bn_statis_para # 训练态 if self.training: # 先做普通卷积得到A,以取得BN参数 output = F.conv2d( input, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups, ) # 更新BN统计参数(batch和running) dims = [dim for dim in range(4) if dim != 1] batch_mean = torch.mean(output, dim=dims) batch_var = torch.var(output, dim=dims) with torch.no_grad(): if not self.pretrained_model: if self.num_flag == 0: self.num_flag += 1 running_mean = batch_mean running_var = batch_var else: running_mean = ( 1 - self.momentum ) * self.running_mean + self.momentum * batch_mean running_var = ( 1 - self.momentum ) * self.running_var + self.momentum * batch_var self.running_mean.copy_(running_mean) self.running_var.copy_(running_var) else: running_mean = ( 1 - self.momentum ) * self.running_mean + self.momentum * batch_mean running_var = ( 1 - self.momentum ) * self.running_var + self.momentum * batch_var self.running_mean.copy_(running_mean) self.running_var.copy_(running_var) # bn融合 if self.bias is not None: bias_fused = reshape_to_bias( self.beta + (self.bias - batch_mean) * (self.gamma / torch.sqrt(batch_var + self.eps)) ) else: bias_fused = reshape_to_bias( self.beta - batch_mean * (self.gamma / torch.sqrt(batch_var + self.eps)) ) # b融batch # bn融合不校准 if not self.bn_fuse_calib: weight_fused = self.weight * reshape_to_weight( self.gamma / torch.sqrt(batch_var + self.eps) ) # w融batch # bn融合校准 else: weight_fused = self.weight * reshape_to_weight( self.gamma / torch.sqrt(self.running_var + self.eps) ) # w融running # 测试态 else: if self.bias is not None: bias_fused = reshape_to_bias( self.beta + (self.bias - self.running_mean) * (self.gamma / torch.sqrt(self.running_var + self.eps)) ) else: bias_fused = reshape_to_bias( self.beta - self.running_mean * (self.gamma / torch.sqrt(self.running_var + self.eps)) ) # b融running weight_fused = self.weight * reshape_to_weight( self.gamma / torch.sqrt(self.running_var + self.eps) ) # w融running else: # qaft, freeze bn_statis_para if self.bias is not None: bias_fused = reshape_to_bias( self.beta + (self.bias - self.running_mean) * (self.gamma / torch.sqrt(self.running_var + self.eps)) ) else: bias_fused = reshape_to_bias( self.beta - self.running_mean * (self.gamma / torch.sqrt(self.running_var + self.eps)) ) # b融running weight_fused = self.weight * reshape_to_weight( self.gamma / torch.sqrt(self.running_var + self.eps) ) # w融running # 量化A和bn融合后的W quant_input = self.activation_quantizer(input) quant_weight = self.weight_quantizer(weight_fused) if not self.qaft: # qat, quant_bn_fuse_conv # 量化卷积 if self.training: # 训练态 # bn融合不校准 if not self.bn_fuse_calib: output = F.conv2d( quant_input, quant_weight, bias_fused, self.stride, self.padding, self.dilation, self.groups, ) # bn融合校准 else: output = F.conv2d( quant_input, quant_weight, None, self.stride, self.padding, self.dilation, self.groups, ) # 注意,这里不加bias(self.bias为None) # (这里将训练态下,卷积中w融合running参数的效果转为融合batch参数的效果)running ——> batch output *= reshape_to_activation( torch.sqrt(self.running_var + self.eps) / torch.sqrt(batch_var + self.eps) ) output += reshape_to_activation(bias_fused) else: # 测试态 output = F.conv2d( quant_input, quant_weight, bias_fused, self.stride, self.padding, self.dilation, self.groups, ) # 注意,这里加bias,做完整的conv+bn else: # qaft, quant_bn_fuse_conv output = F.conv2d( quant_input, quant_weight, bias_fused, self.stride, self.padding, self.dilation, self.groups, ) return output def add_quant_op( module, a_bits=8, w_bits=8, q_type=0, q_level=0, weight_observer=0, bn_fuse=False, bn_fuse_calib=False, quant_inference=False, pretrained_model=False, qaft=False, ptq=False, percentile=0.9999, ): for name, child in module.named_children(): if isinstance(child, nn.Conv2d): if bn_fuse: conv_name_temp = name conv_child_temp = child else: if child.bias is not None: quant_conv = QuantConv2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, dilation=child.dilation, groups=child.groups, bias=True, padding_mode=child.padding_mode, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, quant_inference=quant_inference, qaft=qaft, ptq=ptq, percentile=percentile, ) quant_conv.bias.data = child.bias else: quant_conv = QuantConv2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, dilation=child.dilation, groups=child.groups, bias=False, padding_mode=child.padding_mode, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, quant_inference=quant_inference, qaft=qaft, ptq=ptq, percentile=percentile, ) quant_conv.weight.data = child.weight module._modules[name] = quant_conv elif isinstance(child, nn.BatchNorm2d): if bn_fuse: if conv_child_temp.bias is not None: quant_bn_fuse_conv = QuantBNFuseConv2d( conv_child_temp.in_channels, conv_child_temp.out_channels, conv_child_temp.kernel_size, stride=conv_child_temp.stride, padding=conv_child_temp.padding, dilation=conv_child_temp.dilation, groups=conv_child_temp.groups, bias=True, padding_mode=conv_child_temp.padding_mode, eps=child.eps, momentum=child.momentum, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, pretrained_model=pretrained_model, qaft=qaft, ptq=ptq, percentile=percentile, bn_fuse_calib=bn_fuse_calib, ) quant_bn_fuse_conv.bias.data = conv_child_temp.bias else: quant_bn_fuse_conv = QuantBNFuseConv2d( conv_child_temp.in_channels, conv_child_temp.out_channels, conv_child_temp.kernel_size, stride=conv_child_temp.stride, padding=conv_child_temp.padding, dilation=conv_child_temp.dilation, groups=conv_child_temp.groups, bias=False, padding_mode=conv_child_temp.padding_mode, eps=child.eps, momentum=child.momentum, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, pretrained_model=pretrained_model, qaft=qaft, ptq=ptq, percentile=percentile, bn_fuse_calib=bn_fuse_calib, ) quant_bn_fuse_conv.weight.data = conv_child_temp.weight quant_bn_fuse_conv.gamma.data = child.weight quant_bn_fuse_conv.beta.data = child.bias quant_bn_fuse_conv.running_mean.copy_(child.running_mean) quant_bn_fuse_conv.running_var.copy_(child.running_var) module._modules[conv_name_temp] = quant_bn_fuse_conv module._modules[name] = nn.Identity() elif isinstance(child, nn.ConvTranspose2d): if child.bias is not None: quant_conv_transpose = QuantConvTranspose2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, output_padding=child.output_padding, groups=child.groups, bias=True, dilation=child.dilation, padding_mode=child.padding_mode, a_bits=a_bits, w_bits=w_bits, q_type=q_type, weight_observer=weight_observer, quant_inference=quant_inference, qaft=qaft, ptq=ptq, percentile=percentile, ) quant_conv_transpose.bias.data = child.bias else: quant_conv_transpose = QuantConvTranspose2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, output_padding=child.output_padding, groups=child.groups, bias=False, dilation=child.dilation, padding_mode=child.padding_mode, a_bits=a_bits, w_bits=w_bits, q_type=q_type, weight_observer=weight_observer, quant_inference=quant_inference, qaft=qaft, ptq=ptq, percentile=percentile, ) quant_conv_transpose.weight.data = child.weight module._modules[name] = quant_conv_transpose elif isinstance(child, nn.Linear): if child.bias is not None: quant_linear = QuantLinear( child.in_features, child.out_features, bias=True, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, quant_inference=quant_inference, qaft=qaft, ptq=ptq, percentile=percentile, ) quant_linear.bias.data = child.bias else: quant_linear = QuantLinear( child.in_features, child.out_features, bias=False, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, quant_inference=quant_inference, qaft=qaft, ptq=ptq, percentile=percentile, ) quant_linear.weight.data = child.weight module._modules[name] = quant_linear # relu needn’t quantize, it will be fused in quant_inference # elif isinstance(child, nn.ReLU): # quant_relu = QuantReLU(inplace=child.inplace, a_bits=a_bits, # q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile) # module._modules[name] = quant_relu elif isinstance(child, nn.LeakyReLU): quant_leaky_relu = QuantLeakyReLU( negative_slope=child.negative_slope, inplace=child.inplace, a_bits=a_bits, q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile, ) module._modules[name] = quant_leaky_relu elif isinstance(child, nn.Sigmoid): quant_sigmoid = QuantSigmoid( a_bits=a_bits, q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile ) module._modules[name] = quant_sigmoid elif isinstance(child, nn.MaxPool2d): quant_max_pool = QuantMaxPool2d( kernel_size=child.kernel_size, stride=child.stride, padding=child.padding, a_bits=a_bits, q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile, ) module._modules[name] = quant_max_pool elif isinstance(child, nn.AvgPool2d): quant_avg_pool = QuantAvgPool2d( kernel_size=child.kernel_size, stride=child.stride, padding=child.padding, a_bits=a_bits, q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile, ) module._modules[name] = quant_avg_pool elif isinstance(child, nn.AdaptiveAvgPool2d): quant_adaptive_avg_pool = QuantAdaptiveAvgPool2d( output_size=child.output_size, a_bits=a_bits, q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile, ) module._modules[name] = quant_adaptive_avg_pool elif isinstance(child, Add): quant_add = QuantAdd( a_bits=a_bits, q_type=q_type, qaft=qaft, ptq=ptq, percentile=percentile ) module._modules[name] = quant_add # elif isinstance(child, Concat): # quant_concat = QuantConcat(dim=child.dim, # a_bits=a_bits, # q_type=q_type, # qaft=qaft, # ptq=ptq, # percentile=percentile) # module._modules[name] = quant_concat else: add_quant_op( child, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, bn_fuse=bn_fuse, bn_fuse_calib=bn_fuse_calib, quant_inference=quant_inference, pretrained_model=pretrained_model, qaft=qaft, ptq=ptq, percentile=percentile, ) def prepare( model, inplace=False, a_bits=8, w_bits=8, q_type=0, q_level=0, weight_observer=0, bn_fuse=False, bn_fuse_calib=False, quant_inference=False, pretrained_model=False, qaft=False, ptq=False, percentile=0.9999, ): if not inplace: model = copy.deepcopy(model) add_quant_op( model, a_bits=a_bits, w_bits=w_bits, q_type=q_type, q_level=q_level, weight_observer=weight_observer, bn_fuse=bn_fuse, bn_fuse_calib=bn_fuse_calib, quant_inference=quant_inference, pretrained_model=pretrained_model, qaft=qaft, ptq=ptq, percentile=percentile, ) return model
null
9,168
import copy import sys import os import argparse import numpy as np import torch import torch.nn as nn from models import nin_gc, nin import quantize def bn_fuse_module(module): for name, child in module.named_children(): if isinstance(child, quantize.QuantBNFuseConv2d): bn_fused_conv = bn_fuse(child) module._modules[name] = bn_fused_conv else: bn_fuse_module(child) def model_bn_fuse(model, inplace=False): if not inplace: model = copy.deepcopy(model) bn_fuse_module(model) return model
null
9,169
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import os import math import argparse import numpy as np import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms from torch.autograd import Variable from torch.nn import init from models import nin_gc, nin import quantize def setup_seed(seed): torch.manual_seed(seed) # torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) torch.backends.cudnn.deterministic = True
null
9,170
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import os import math import argparse import numpy as np import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms from torch.autograd import Variable from torch.nn import init from models import nin_gc, nin import quantize def save_state(model, best_acc): print("==> Saving model ...") state = { "best_acc": best_acc, "state_dict": model.state_dict(), } state_copy = state["state_dict"].copy() for key in state_copy.keys(): if "module" in key: state["state_dict"][key.replace("module.", "")] = state["state_dict"].pop( key ) if args.model_type == 0: if args.prune_qat: torch.save( {"cfg": cfg, "best_acc": best_acc, "state_dict": state["state_dict"]}, "models_save/nin.pth", ) else: torch.save(state, "models_save/nin.pth") else: if args.prune_qat: torch.save( {"cfg": cfg, "best_acc": best_acc, "state_dict": state["state_dict"]}, "models_save/nin_gc.pth", ) else: torch.save(state, "models_save/nin_gc.pth")
null
9,171
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import os import math import argparse import numpy as np import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms from torch.autograd import Variable from torch.nn import init from models import nin_gc, nin import quantize def adjust_learning_rate(optimizer, epoch): update_list = [80, 130, 180, 230, 280] if epoch in update_list: for param_group in optimizer.param_groups: param_group["lr"] = param_group["lr"] * 0.1 return
null
9,172
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import os import math import argparse import numpy as np import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms from torch.autograd import Variable from torch.nn import init from models import nin_gc, nin import quantize def train(epoch): model.train() for batch_idx, (data, target) in enumerate(trainloader): if not args.cpu: data, target = data.cuda(), target.cuda() data, target = Variable(data), Variable(target) output = model(data) loss = criterion(output, target) optimizer.zero_grad() loss.backward() optimizer.step() if batch_idx % 100 == 0: print( "Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}\tLR: {}".format( epoch, batch_idx * len(data), len(trainloader.dataset), 100.0 * batch_idx / len(trainloader), loss.data.item(), optimizer.param_groups[0]["lr"], ) ) return
null
9,173
import copy import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Function def __init__(self, a_bits): def prepare(model, inplace=False, a_bits=8, w_bits=8, quant_inference=False): if not inplace: model = copy.deepcopy(model) layer_counter = [0] add_quant_op( model, layer_counter, a_bits=a_bits, w_bits=w_bits, quant_inference=quant_inference, ) return model
null
9,177
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import os import math import argparse import numpy as np import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms from torch.autograd import Variable from torch.nn import init from models import nin_gc, nin import quantize def train(epoch): model.train() for batch_idx, (data, target) in enumerate(trainloader): # 前向传播 if not args.cpu: data, target = data.cuda(), target.cuda() data, target = Variable(data), Variable(target) output = model(data) loss = criterion(output, target) # 反向传播 optimizer.zero_grad() loss.backward() # 求梯度 optimizer.step() # 参数更新 # 显示训练集loss(/100个batch) if batch_idx % 100 == 0: print( "Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}\tLR: {}".format( epoch, batch_idx * len(data), len(trainloader.dataset), 100.0 * batch_idx / len(trainloader), loss.data.item(), optimizer.param_groups[0]["lr"], ) ) return
null
9,178
import copy import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Function def __init__(self, A=2): for name, child in module.named_children(): if isinstance(child, nn.Conv2d): layer_counter[0] += 1 if layer_counter[0] > 1 and layer_counter[0] < layer_num: if child.bias is not None: quant_conv = QuantConv2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, dilation=child.dilation, groups=child.groups, bias=True, padding_mode=child.padding_mode, W=W, quant_inference=quant_inference, ) quant_conv.bias.data = child.bias else: quant_conv = QuantConv2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, dilation=child.dilation, groups=child.groups, bias=False, padding_mode=child.padding_mode, W=W, quant_inference=quant_inference, ) quant_conv.weight.data = child.weight module._modules[name] = quant_conv elif isinstance(child, nn.ConvTranspose2d): layer_counter[0] += 1 if layer_counter[0] > 1 and layer_counter[0] < layer_num: if child.bias is not None: quant_conv_transpose = QuantConvTranspose2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, output_padding=child.output_padding, dilation=child.dilation, groups=child.groups, bias=True, padding_mode=child.padding_mode, W=W, quant_inference=quant_inference, ) quant_conv_transpose.bias.data = child.bias else: quant_conv_transpose = QuantConvTranspose2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, output_padding=child.output_padding, dilation=child.dilation, groups=child.groups, bias=False, padding_mode=child.padding_mode, W=W, quant_inference=quant_inference, ) quant_conv_transpose.weight.data = child.weight module._modules[name] = quant_conv_transpose elif isinstance(child, nn.ReLU): if layer_counter[0] > 0 and layer_counter[0] < layer_num: quant_relu = ActivationQuantizer(A=A) module._modules[name] = quant_relu else: add_quant_op( child, layer_counter, layer_num, A=A, W=W, quant_inference=quant_inference, ) def meancenter_clamp_convparams(w): mean = w.data.mean(1, keepdim=True) w.data.sub_(mean) # W中心化(C方向) w.data.clamp_(-1.0, 1.0) # W截断 return w
null
9,179
import copy import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Function def __init__(self, A=2): for name, child in module.named_children(): if isinstance(child, nn.Conv2d): layer_counter[0] += 1 if layer_counter[0] > 1 and layer_counter[0] < layer_num: if child.bias is not None: quant_conv = QuantConv2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, dilation=child.dilation, groups=child.groups, bias=True, padding_mode=child.padding_mode, W=W, quant_inference=quant_inference, ) quant_conv.bias.data = child.bias else: quant_conv = QuantConv2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, dilation=child.dilation, groups=child.groups, bias=False, padding_mode=child.padding_mode, W=W, quant_inference=quant_inference, ) quant_conv.weight.data = child.weight module._modules[name] = quant_conv elif isinstance(child, nn.ConvTranspose2d): layer_counter[0] += 1 if layer_counter[0] > 1 and layer_counter[0] < layer_num: if child.bias is not None: quant_conv_transpose = QuantConvTranspose2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, output_padding=child.output_padding, dilation=child.dilation, groups=child.groups, bias=True, padding_mode=child.padding_mode, W=W, quant_inference=quant_inference, ) quant_conv_transpose.bias.data = child.bias else: quant_conv_transpose = QuantConvTranspose2d( child.in_channels, child.out_channels, child.kernel_size, stride=child.stride, padding=child.padding, output_padding=child.output_padding, dilation=child.dilation, groups=child.groups, bias=False, padding_mode=child.padding_mode, W=W, quant_inference=quant_inference, ) quant_conv_transpose.weight.data = child.weight module._modules[name] = quant_conv_transpose elif isinstance(child, nn.ReLU): if layer_counter[0] > 0 and layer_counter[0] < layer_num: quant_relu = ActivationQuantizer(A=A) module._modules[name] = quant_relu else: add_quant_op( child, layer_counter, layer_num, A=A, W=W, quant_inference=quant_inference, ) def prepare(model, inplace=False, A=2, W=2, quant_inference=False): if not inplace: model = copy.deepcopy(model) layer_counter = [0] layer_num = 0 for m in model.modules(): if isinstance(m, nn.Conv2d): layer_num += 1 elif isinstance(m, nn.ConvTranspose2d): layer_num += 1 add_quant_op( model, layer_counter, layer_num, A=A, W=W, quant_inference=quant_inference ) return model
null
9,180
import copy import sys import os import argparse import numpy as np import torch import torch.nn as nn from models import nin_gc, nin import quantize def bn_fuse_module(module): for name, child in module.named_children(): if isinstance(child, nn.Conv2d): conv_name_temp = name conv_child_temp = child elif isinstance(child, nn.BatchNorm2d): bn_fused_conv = bn_fuse(conv_child_temp, child) module._modules[conv_name_temp] = bn_fused_conv module._modules[name] = nn.Identity() else: bn_fuse_module(child) def model_bn_fuse(model, inplace=False): if not inplace: model = copy.deepcopy(model) bn_fuse_module(model) return model
null
9,181
import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `channel_shuffle` function. Write a Python function `def channel_shuffle(x, groups)` to solve the following problem: shuffle channels of a 4-D Tensor Here is the function: def channel_shuffle(x, groups): """shuffle channels of a 4-D Tensor""" batch_size, channels, height, width = x.size() assert channels % groups == 0 channels_per_group = channels // groups # split into groups x = x.view(batch_size, groups, channels_per_group, height, width) # transpose 1, 2 axis x = x.transpose(1, 2).contiguous() # reshape into orignal x = x.view(batch_size, channels, height, width) return x
shuffle channels of a 4-D Tensor
9,182
import torch import torch.nn as nn from micronet.base_module.op import * class BasicBlock(nn.Module): """Basic Block for resnet 18 and resnet 34""" # BasicBlock and BottleNeck block # have different output size # we use class attribute expansion # to distinct expansion = 1 def __init__(self, in_channels, out_channels, stride=1): super().__init__() # residual function self.residual_function = nn.Sequential( nn.Conv2d( in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False, ), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d( out_channels, out_channels * BasicBlock.expansion, kernel_size=3, padding=1, bias=False, ), nn.BatchNorm2d(out_channels * BasicBlock.expansion), ) # shortcut self.shortcut = nn.Sequential() # the shortcut output dimension is not the same with residual function # use 1*1 convolution to match the dimension if stride != 1 or in_channels != BasicBlock.expansion * out_channels: self.shortcut = nn.Sequential( nn.Conv2d( in_channels, out_channels * BasicBlock.expansion, kernel_size=1, stride=stride, bias=False, ), nn.BatchNorm2d(out_channels * BasicBlock.expansion), ) # +++ self.add = Add() def forward(self, x): # return nn.ReLU(inplace=True)(self.residual_function(x) + self.shortcut(x)) # +++ return nn.ReLU(inplace=True)( self.add(self.residual_function(x), self.shortcut(x)) ) class ResNet(nn.Module): def __init__(self, block, num_block, num_classes=10): super().__init__() self.in_channels = 64 self.conv1 = nn.Sequential( nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True), ) # we use a different inputsize than the original paper # so conv2_x's stride is 1 self.conv2_x = self._make_layer(block, 64, num_block[0], 1) self.conv3_x = self._make_layer(block, 128, num_block[1], 2) self.conv4_x = self._make_layer(block, 256, num_block[2], 2) self.conv5_x = self._make_layer(block, 512, num_block[3], 2) self.avg_pool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(512 * block.expansion, num_classes) def _make_layer(self, block, out_channels, num_blocks, stride): """make resnet layers(by layer i didnt mean this 'layer' was the same as a neuron netowork layer, ex. conv layer), one layer may contain more than one residual block Args: block: block type, basic block or bottle neck block out_channels: output depth channel number of this layer num_blocks: how many blocks per layer stride: the stride of the first block of this layer Return: return a resnet layer """ # we have num_block blocks per layer, the first block # could be 1 or 2, other blocks would always be 1 strides = [stride] + [1] * (num_blocks - 1) layers = [] for stride in strides: layers.append(block(self.in_channels, out_channels, stride)) self.in_channels = out_channels * block.expansion return nn.Sequential(*layers) def forward(self, x): output = self.conv1(x) output = self.conv2_x(output) output = self.conv3_x(output) output = self.conv4_x(output) output = self.conv5_x(output) output = self.avg_pool(output) output = output.view(output.size(0), -1) output = self.fc(output) return output The provided code snippet includes necessary dependencies for implementing the `resnet18` function. Write a Python function `def resnet18()` to solve the following problem: return a ResNet 18 object Here is the function: def resnet18(): """return a ResNet 18 object""" return ResNet(BasicBlock, [2, 2, 2, 2])
return a ResNet 18 object
9,183
import torch import torch.nn as nn from micronet.base_module.op import * class BasicBlock(nn.Module): """Basic Block for resnet 18 and resnet 34""" # BasicBlock and BottleNeck block # have different output size # we use class attribute expansion # to distinct expansion = 1 def __init__(self, in_channels, out_channels, stride=1): super().__init__() # residual function self.residual_function = nn.Sequential( nn.Conv2d( in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False, ), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d( out_channels, out_channels * BasicBlock.expansion, kernel_size=3, padding=1, bias=False, ), nn.BatchNorm2d(out_channels * BasicBlock.expansion), ) # shortcut self.shortcut = nn.Sequential() # the shortcut output dimension is not the same with residual function # use 1*1 convolution to match the dimension if stride != 1 or in_channels != BasicBlock.expansion * out_channels: self.shortcut = nn.Sequential( nn.Conv2d( in_channels, out_channels * BasicBlock.expansion, kernel_size=1, stride=stride, bias=False, ), nn.BatchNorm2d(out_channels * BasicBlock.expansion), ) # +++ self.add = Add() def forward(self, x): # return nn.ReLU(inplace=True)(self.residual_function(x) + self.shortcut(x)) # +++ return nn.ReLU(inplace=True)( self.add(self.residual_function(x), self.shortcut(x)) ) class ResNet(nn.Module): def __init__(self, block, num_block, num_classes=10): super().__init__() self.in_channels = 64 self.conv1 = nn.Sequential( nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True), ) # we use a different inputsize than the original paper # so conv2_x's stride is 1 self.conv2_x = self._make_layer(block, 64, num_block[0], 1) self.conv3_x = self._make_layer(block, 128, num_block[1], 2) self.conv4_x = self._make_layer(block, 256, num_block[2], 2) self.conv5_x = self._make_layer(block, 512, num_block[3], 2) self.avg_pool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(512 * block.expansion, num_classes) def _make_layer(self, block, out_channels, num_blocks, stride): """make resnet layers(by layer i didnt mean this 'layer' was the same as a neuron netowork layer, ex. conv layer), one layer may contain more than one residual block Args: block: block type, basic block or bottle neck block out_channels: output depth channel number of this layer num_blocks: how many blocks per layer stride: the stride of the first block of this layer Return: return a resnet layer """ # we have num_block blocks per layer, the first block # could be 1 or 2, other blocks would always be 1 strides = [stride] + [1] * (num_blocks - 1) layers = [] for stride in strides: layers.append(block(self.in_channels, out_channels, stride)) self.in_channels = out_channels * block.expansion return nn.Sequential(*layers) def forward(self, x): output = self.conv1(x) output = self.conv2_x(output) output = self.conv3_x(output) output = self.conv4_x(output) output = self.conv5_x(output) output = self.avg_pool(output) output = output.view(output.size(0), -1) output = self.fc(output) return output The provided code snippet includes necessary dependencies for implementing the `resnet34` function. Write a Python function `def resnet34()` to solve the following problem: return a ResNet 34 object Here is the function: def resnet34(): """return a ResNet 34 object""" return ResNet(BasicBlock, [3, 4, 6, 3])
return a ResNet 34 object
9,184
import torch import torch.nn as nn from micronet.base_module.op import * class BottleNeck(nn.Module): """Residual block for resnet over 50 layers""" expansion = 4 def __init__(self, in_channels, out_channels, stride=1): super().__init__() self.residual_function = nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d( out_channels, out_channels, stride=stride, kernel_size=3, padding=1, bias=False, ), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d( out_channels, out_channels * BottleNeck.expansion, kernel_size=1, bias=False, ), nn.BatchNorm2d(out_channels * BottleNeck.expansion), ) self.shortcut = nn.Sequential() if stride != 1 or in_channels != out_channels * BottleNeck.expansion: self.shortcut = nn.Sequential( nn.Conv2d( in_channels, out_channels * BottleNeck.expansion, stride=stride, kernel_size=1, bias=False, ), nn.BatchNorm2d(out_channels * BottleNeck.expansion), ) # +++ self.add = Add() def forward(self, x): # return nn.ReLU(inplace=True)(self.residual_function(x) + self.shortcut(x)) # +++ return nn.ReLU(inplace=True)( self.add(self.residual_function(x), self.shortcut(x)) ) class ResNet(nn.Module): def __init__(self, block, num_block, num_classes=10): super().__init__() self.in_channels = 64 self.conv1 = nn.Sequential( nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True), ) # we use a different inputsize than the original paper # so conv2_x's stride is 1 self.conv2_x = self._make_layer(block, 64, num_block[0], 1) self.conv3_x = self._make_layer(block, 128, num_block[1], 2) self.conv4_x = self._make_layer(block, 256, num_block[2], 2) self.conv5_x = self._make_layer(block, 512, num_block[3], 2) self.avg_pool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(512 * block.expansion, num_classes) def _make_layer(self, block, out_channels, num_blocks, stride): """make resnet layers(by layer i didnt mean this 'layer' was the same as a neuron netowork layer, ex. conv layer), one layer may contain more than one residual block Args: block: block type, basic block or bottle neck block out_channels: output depth channel number of this layer num_blocks: how many blocks per layer stride: the stride of the first block of this layer Return: return a resnet layer """ # we have num_block blocks per layer, the first block # could be 1 or 2, other blocks would always be 1 strides = [stride] + [1] * (num_blocks - 1) layers = [] for stride in strides: layers.append(block(self.in_channels, out_channels, stride)) self.in_channels = out_channels * block.expansion return nn.Sequential(*layers) def forward(self, x): output = self.conv1(x) output = self.conv2_x(output) output = self.conv3_x(output) output = self.conv4_x(output) output = self.conv5_x(output) output = self.avg_pool(output) output = output.view(output.size(0), -1) output = self.fc(output) return output The provided code snippet includes necessary dependencies for implementing the `resnet50` function. Write a Python function `def resnet50()` to solve the following problem: return a ResNet 50 object Here is the function: def resnet50(): """return a ResNet 50 object""" return ResNet(BottleNeck, [3, 4, 6, 3])
return a ResNet 50 object
9,185
import torch import torch.nn as nn from micronet.base_module.op import * class BottleNeck(nn.Module): """Residual block for resnet over 50 layers""" expansion = 4 def __init__(self, in_channels, out_channels, stride=1): super().__init__() self.residual_function = nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d( out_channels, out_channels, stride=stride, kernel_size=3, padding=1, bias=False, ), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d( out_channels, out_channels * BottleNeck.expansion, kernel_size=1, bias=False, ), nn.BatchNorm2d(out_channels * BottleNeck.expansion), ) self.shortcut = nn.Sequential() if stride != 1 or in_channels != out_channels * BottleNeck.expansion: self.shortcut = nn.Sequential( nn.Conv2d( in_channels, out_channels * BottleNeck.expansion, stride=stride, kernel_size=1, bias=False, ), nn.BatchNorm2d(out_channels * BottleNeck.expansion), ) # +++ self.add = Add() def forward(self, x): # return nn.ReLU(inplace=True)(self.residual_function(x) + self.shortcut(x)) # +++ return nn.ReLU(inplace=True)( self.add(self.residual_function(x), self.shortcut(x)) ) class ResNet(nn.Module): def __init__(self, block, num_block, num_classes=10): super().__init__() self.in_channels = 64 self.conv1 = nn.Sequential( nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True), ) # we use a different inputsize than the original paper # so conv2_x's stride is 1 self.conv2_x = self._make_layer(block, 64, num_block[0], 1) self.conv3_x = self._make_layer(block, 128, num_block[1], 2) self.conv4_x = self._make_layer(block, 256, num_block[2], 2) self.conv5_x = self._make_layer(block, 512, num_block[3], 2) self.avg_pool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(512 * block.expansion, num_classes) def _make_layer(self, block, out_channels, num_blocks, stride): """make resnet layers(by layer i didnt mean this 'layer' was the same as a neuron netowork layer, ex. conv layer), one layer may contain more than one residual block Args: block: block type, basic block or bottle neck block out_channels: output depth channel number of this layer num_blocks: how many blocks per layer stride: the stride of the first block of this layer Return: return a resnet layer """ # we have num_block blocks per layer, the first block # could be 1 or 2, other blocks would always be 1 strides = [stride] + [1] * (num_blocks - 1) layers = [] for stride in strides: layers.append(block(self.in_channels, out_channels, stride)) self.in_channels = out_channels * block.expansion return nn.Sequential(*layers) def forward(self, x): output = self.conv1(x) output = self.conv2_x(output) output = self.conv3_x(output) output = self.conv4_x(output) output = self.conv5_x(output) output = self.avg_pool(output) output = output.view(output.size(0), -1) output = self.fc(output) return output The provided code snippet includes necessary dependencies for implementing the `resnet101` function. Write a Python function `def resnet101()` to solve the following problem: return a ResNet 101 object Here is the function: def resnet101(): """return a ResNet 101 object""" return ResNet(BottleNeck, [3, 4, 23, 3])
return a ResNet 101 object
9,186
import torch import torch.nn as nn from micronet.base_module.op import * class BottleNeck(nn.Module): """Residual block for resnet over 50 layers""" expansion = 4 def __init__(self, in_channels, out_channels, stride=1): super().__init__() self.residual_function = nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d( out_channels, out_channels, stride=stride, kernel_size=3, padding=1, bias=False, ), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d( out_channels, out_channels * BottleNeck.expansion, kernel_size=1, bias=False, ), nn.BatchNorm2d(out_channels * BottleNeck.expansion), ) self.shortcut = nn.Sequential() if stride != 1 or in_channels != out_channels * BottleNeck.expansion: self.shortcut = nn.Sequential( nn.Conv2d( in_channels, out_channels * BottleNeck.expansion, stride=stride, kernel_size=1, bias=False, ), nn.BatchNorm2d(out_channels * BottleNeck.expansion), ) # +++ self.add = Add() def forward(self, x): # return nn.ReLU(inplace=True)(self.residual_function(x) + self.shortcut(x)) # +++ return nn.ReLU(inplace=True)( self.add(self.residual_function(x), self.shortcut(x)) ) class ResNet(nn.Module): def __init__(self, block, num_block, num_classes=10): super().__init__() self.in_channels = 64 self.conv1 = nn.Sequential( nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True), ) # we use a different inputsize than the original paper # so conv2_x's stride is 1 self.conv2_x = self._make_layer(block, 64, num_block[0], 1) self.conv3_x = self._make_layer(block, 128, num_block[1], 2) self.conv4_x = self._make_layer(block, 256, num_block[2], 2) self.conv5_x = self._make_layer(block, 512, num_block[3], 2) self.avg_pool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(512 * block.expansion, num_classes) def _make_layer(self, block, out_channels, num_blocks, stride): """make resnet layers(by layer i didnt mean this 'layer' was the same as a neuron netowork layer, ex. conv layer), one layer may contain more than one residual block Args: block: block type, basic block or bottle neck block out_channels: output depth channel number of this layer num_blocks: how many blocks per layer stride: the stride of the first block of this layer Return: return a resnet layer """ # we have num_block blocks per layer, the first block # could be 1 or 2, other blocks would always be 1 strides = [stride] + [1] * (num_blocks - 1) layers = [] for stride in strides: layers.append(block(self.in_channels, out_channels, stride)) self.in_channels = out_channels * block.expansion return nn.Sequential(*layers) def forward(self, x): output = self.conv1(x) output = self.conv2_x(output) output = self.conv3_x(output) output = self.conv4_x(output) output = self.conv5_x(output) output = self.avg_pool(output) output = output.view(output.size(0), -1) output = self.fc(output) return output The provided code snippet includes necessary dependencies for implementing the `resnet152` function. Write a Python function `def resnet152()` to solve the following problem: return a ResNet 152 object Here is the function: def resnet152(): """return a ResNet 152 object""" return ResNet(BottleNeck, [3, 8, 36, 3])
return a ResNet 152 object
9,187
import argparse import os import sys import tempfile import threading import webbrowser import time import gradio as gr import librosa.display import numpy as np import os import torch import torchaudio import traceback from utils.formatter import format_audio_list from utils.cfg import TTSMODEL_DIR from TTS.demos.xtts_ft_demo.utils.gpt_train import train_gpt from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts import datetime import shutil import json import random from dotenv import load_dotenv XTTS_MODEL = Noneger: def __init__(self, filename="log.out"): self.log_file = filename def write(self, message): self.terminal.write(message) self.log.write(message) def flush(self): self.terminal.flush() self.log.flush() def isatty(self): return False import logging def run_tts(lang, tts_text, speaker_audio_file): if XTTS_MODEL is None: gr.Error("模型还未训练完毕或尚未加载,请稍等") return "模型还未训练完毕或尚未加载,请稍等 !!", None, None if speaker_audio_file and not speaker_audio_file.endswith(".wav"): speaker_audio_file+='.wav' if not speaker_audio_file or not os.path.exists(speaker_audio_file): gr.Error('必须填写参考音频') return '必须填写参考音频',None,None gpt_cond_latent, speaker_embedding = XTTS_MODEL.get_conditioning_latents(audio_path=speaker_audio_file, gpt_cond_len=XTTS_MODEL.config.gpt_cond_len, max_ref_length=XTTS_MODEL.config.max_ref_len, sound_norm_refs=XTTS_MODEL.config.sound_norm_refs) out = XTTS_MODEL.inference( text=tts_text, language=lang, gpt_cond_latent=gpt_cond_latent, speaker_embedding=speaker_embedding, temperature=XTTS_MODEL.config.temperature, # Add custom parameters here length_penalty=XTTS_MODEL.config.length_penalty, repetition_penalty=XTTS_MODEL.config.repetition_penalty, top_k=XTTS_MODEL.config.top_k, top_p=XTTS_MODEL.config.top_p, ) with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as fp: out["wav"] = torch.tensor(out["wav"]).unsqueeze(0) out_path = fp.name torchaudio.save(out_path, out["wav"], 24000) return "已创建好了声音 !", out_path, speaker_audio_file
null
9,188
import argparse import os import sys import tempfile import threading import webbrowser import time import gradio as gr import librosa.display import numpy as np import os import torch import torchaudio import traceback from utils.formatter import format_audio_list from utils.cfg import TTSMODEL_DIR from TTS.demos.xtts_ft_demo.utils.gpt_train import train_gpt from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts import datetime import shutil import json import random from dotenv import load_dotenv def write(self, message): def flush(self): def isatty(self): sys.stdout = Logger() sys.stderr = sys.stdout import logging def read_logs(): sys.stdout.flush() with open(sys.stdout.log_file, "r") as f: return f.read()
null
9,189
import argparse import os import sys import tempfile import threading import webbrowser import time import gradio as gr import librosa.display import numpy as np import os import torch import torchaudio import traceback from utils.formatter import format_audio_list from utils.cfg import TTSMODEL_DIR from TTS.demos.xtts_ft_demo.utils.gpt_train import train_gpt from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts import datetime import shutil import json import random from dotenv import load_dotenv def write(self, message): self.terminal.write(message) self.log.write(message) def flush(self): self.terminal.flush() self.log.flush() def isatty(self): return False import logging def openweb(port): time.sleep(10) webbrowser.open(f"http://127.0.0.1:{port}")
null
9,190
import argparse import os import sys import tempfile import threading import webbrowser import time import gradio as gr import librosa.display import numpy as np import os import torch import torchaudio import traceback from utils.formatter import format_audio_list from utils.cfg import TTSMODEL_DIR from TTS.demos.xtts_ft_demo.utils.gpt_train import train_gpt from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts import datetime import shutil import json import random from dotenv import load_dotenv print(f'{proxy=}') def clear_gpu_cache(): # clear the GPU cache if torch.cuda.is_available(): torch.cuda.empty_cache() def load_model(xtts_checkpoint, xtts_config, xtts_vocab): global XTTS_MODEL clear_gpu_cache() if not xtts_checkpoint or not xtts_config or not xtts_vocab: gr.Error('训练尚未结束,请稍等') return "训练尚未结束,请稍等" config = XttsConfig() config.load_json(xtts_config) XTTS_MODEL = Xtts.init_from_config(config) print("Loading XTTS model! ") XTTS_MODEL.load_checkpoint(config, checkpoint_path=xtts_checkpoint, vocab_path=xtts_vocab, use_deepspeed=False) if torch.cuda.is_available(): XTTS_MODEL.cuda() print("Model Loaded!") return "模型已加载!" def write(self, message): self.terminal.write(message) self.log.write(message) def flush(self): self.terminal.flush() self.log.flush() def isatty(self): return False import logging def train_model(language, train_text, eval_text,trainfile,evalfile): clear_gpu_cache() if not trainfile or not evalfile: gr.Error("请等待数据处理完毕,目前不存在有效的训练数据集!") return "请等待数据处理完毕,目前不存在有效的训练数据集!","", "", "", "" try: with open(trainfile,'w',encoding='utf-8') as f: f.write(train_text.replace('\r\n','\n')) with open(evalfile,'w',encoding='utf-8') as f: f.write(eval_text.replace('\r\n','\n')) print(f'{trainfile=}') print(f'{evalfile=}') #sys.exit() # convert seconds to waveform frames max_audio_length = int(args['max_audio_length'] * 22050) config_path, original_xtts_checkpoint, vocab_file, exp_path, speaker_wav = train_gpt(language, args['num_epochs'], args['batch_size'], args['grad_acumm'], trainfile, evalfile, output_path=args['out_path'], max_audio_length=max_audio_length) except: traceback.print_exc() error = traceback.format_exc() print(error) gr.Error(f"训练出错了: {error}") return f"训练出错了: {error}","", "", "", "" # copy original files to avoid parameters changes issues shutil.copy2(config_path,exp_path) shutil.copy2(vocab_file,exp_path) ft_xtts_checkpoint = os.path.join(exp_path, "best_model.pth") print("训练完毕!") clear_gpu_cache() msg=load_model( ft_xtts_checkpoint, config_path, vocab_file ) gr.Info("训练完毕,可以测试了") return "训练完毕,可以测试了",config_path, vocab_file, ft_xtts_checkpoint, speaker_wav
null
9,191
import argparse import os import sys import tempfile import threading import webbrowser import time import gradio as gr import librosa.display import numpy as np import os import torch import torchaudio import traceback from utils.formatter import format_audio_list from utils.cfg import TTSMODEL_DIR from TTS.demos.xtts_ft_demo.utils.gpt_train import train_gpt from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts import datetime import shutil import json import random from dotenv import load_dotenv print(f'{proxy=}') def clear_gpu_cache(): # clear the GPU cache if torch.cuda.is_available(): torch.cuda.empty_cache() def write(self, message): self.terminal.write(message) self.log.write(message) def flush(self): self.terminal.flush() self.log.flush() def isatty(self): return False import logging def format_audio_list(audio_files, target_language="en", out_path=None, buffer=0.2, eval_percentage=0.15, speaker_name="coqui", gradio_progress=None): audio_total_size = 0 # make sure that ooutput file exists os.makedirs(out_path, exist_ok=True) # Loading Whisper device = "cuda" if torch.cuda.is_available() else "cpu" print("Loading Whisper Model!") asr_model = WhisperModel("medium", download_root=FASTERMODEL_DIR,device=device, compute_type="float32") metadata = {"audio_file": [], "text": [], "speaker_name": []} if gradio_progress is not None: tqdm_object = gradio_progress.tqdm(audio_files, desc="Formatting...") else: tqdm_object = tqdm(audio_files) for audio_path in tqdm_object: wav, sr = torchaudio.load(audio_path) # stereo to mono if needed if wav.size(0) != 1: wav = torch.mean(wav, dim=0, keepdim=True) wav = wav.squeeze() audio_total_size += (wav.size(-1) / sr) if target_language.lower() in ["zh","ja","ko"]: segments, _ = asr_model.transcribe(audio_path, vad_filter=True, vad_parameters=dict( min_silence_duration_ms=500, max_speech_duration_s=10.5), language=target_language,initial_prompt=ZH_PROMPT if target_language=='zh' else None) text = "" i = 0 for segment in segments: text = segment.text audio = wav[int(sr * segment.start):int(sr * segment.end)].unsqueeze(0) audio_file_name, _ = os.path.splitext(os.path.basename(audio_path)) audio_file = f"wavs/{audio_file_name}_{str(i).zfill(8)}.wav" absoulte_path = os.path.join(out_path, audio_file) os.makedirs(os.path.dirname(absoulte_path), exist_ok=True) if audio.size(-1) >= sr / 3: torchaudio.save(absoulte_path, audio, sr ) else: continue i += 1 metadata["audio_file"].append(audio_file) metadata["text"].append(text.strip()) metadata["speaker_name"].append(speaker_name) continue segments, _ = asr_model.transcribe(audio_path, word_timestamps=True, language=target_language) segments = list(segments) i = 0 sentence = "" sentence_start = None first_word = True # added all segments words in a unique list words_list = [] for _, segment in enumerate(segments): words = list(segment.words) words_list.extend(words) # process each word for word_idx, word in enumerate(words_list): if first_word: sentence_start = word.start # If it is the first sentence, add buffer or get the begining of the file if word_idx == 0: sentence_start = max(sentence_start - buffer, 0) # Add buffer to the sentence start else: # get previous sentence end previous_word_end = words_list[word_idx - 1].end # add buffer or get the silence midle between the previous sentence and the current one sentence_start = max(sentence_start - buffer, (previous_word_end + sentence_start)/2) sentence = word.word first_word = False else: sentence += word.word if word.word[-1] in ["!", ".", "?"]: sentence = sentence[1:] # Expand number and abbreviations plus normalization sentence = multilingual_cleaners(sentence, target_language) audio_file_name, _ = os.path.splitext(os.path.basename(audio_path)) audio_file = f"wavs/{audio_file_name}_{str(i).zfill(8)}.wav" # Check for the next word's existence if word_idx + 1 < len(words_list): next_word_start = words_list[word_idx + 1].start else: # If don't have more words it means that it is the last sentence then use the audio len as next word start next_word_start = (wav.shape[0] - 1) / sr # Average the current word end and next word start word_end = min((word.end + next_word_start) / 2, word.end + buffer) absoulte_path = os.path.join(out_path, audio_file) os.makedirs(os.path.dirname(absoulte_path), exist_ok=True) i += 1 first_word = True audio = wav[int(sr*sentence_start):int(sr*word_end)].unsqueeze(0) # if the audio is too short ignore it (i.e < 0.33 seconds) if audio.size(-1) >= sr/3: torchaudio.save(absoulte_path, audio, sr ) else: continue metadata["audio_file"].append(audio_file) metadata["text"].append(sentence) metadata["speaker_name"].append(speaker_name) df = pandas.DataFrame(metadata) df = df.sample(frac=1) num_val_samples = int(len(df)*eval_percentage) df_eval = df[:num_val_samples] df_train = df[num_val_samples:] df_train = df_train.sort_values('audio_file') train_metadata_path = os.path.join(out_path, "metadata_train.csv") df_train.to_csv(train_metadata_path, sep="|", index=False) eval_metadata_path = os.path.join(out_path, "metadata_eval.csv") df_eval = df_eval.sort_values('audio_file') df_eval.to_csv(eval_metadata_path, sep="|", index=False) # deallocate VRAM and RAM del asr_model, df_train, df_eval, df, metadata gc.collect() return train_metadata_path, eval_metadata_path, audio_total_size def preprocess_dataset(audio_path, language, progress=gr.Progress(track_tqdm=True)): clear_gpu_cache() out_path = os.path.join(args['out_path'], dataset_name) os.makedirs(out_path, exist_ok=True) try: train_meta, eval_meta, audio_total_size = format_audio_list(audio_path, target_language=language, out_path=out_path, gradio_progress=progress) except: traceback.print_exc() error = traceback.format_exc() gr.Error(f"处理训练数据出错了! \n Error summary: {error}") return "", "","","" clear_gpu_cache() # if audio total len is less than 2 minutes raise an error if audio_total_size < 120: message = "素材总时长不得小于2分钟!" print(message) gr.Error(message) return "", "","","" print("数据处理完毕,开始训练!") traindata="" evaldata="" with open(train_meta,'r',encoding="utf-8") as f: traindata=f.read() with open(eval_meta,'r',encoding="utf-8") as f: evaldata=f.read() return traindata,evaldata,train_meta,eval_meta
null
9,192
import argparse import os import sys import tempfile import threading import webbrowser import time import gradio as gr import librosa.display import numpy as np import os import torch import torchaudio import traceback from utils.formatter import format_audio_list from utils.cfg import TTSMODEL_DIR from TTS.demos.xtts_ft_demo.utils.gpt_train import train_gpt from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts import datetime import shutil import json import random from dotenv import load_dotenv print(f'{proxy=}') def write(self, message): self.terminal.write(message) self.log.write(message) def flush(self): self.terminal.flush() self.log.flush() def isatty(self): return False import logging def move_to_clone(model_name,model_file,vocab,cfg,audio_file): if not audio_file or not os.path.exists(audio_file): gr.Warning("必须填写参考音频") return "必须填写参考音频" gr.Info('开始复制到clone自定义模型下,请耐心等待提示完成') print(f'{model_name=}') print(f'{model_file=}') print(f'{vocab=}') print(f'{cfg=}') print(f'{audio_file=}') model_dir=os.path.join(os.getcwd(),f'models/mymodels/{model_name}') os.makedirs(model_dir,exist_ok=True) shutil.copy2(model_file,os.path.join(model_dir,'model.pth')) shutil.copy2(vocab,os.path.join(model_dir,'vocab.json')) shutil.copy2(cfg,os.path.join(model_dir,'config.json')) shutil.copy2(audio_file,os.path.join(model_dir,'base.wav')) gr.Info('已复制到clone自定义模型目录下了,可以去使用咯') return "已复制到clone自定义模型目录下了,可以去使用咯"
null
9,193
import datetime import logging import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os from gevent.pywsgi import WSGIServer, WSGIHandler import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic from gevent.pywsgi import LoggingLogAdapter import shutil import subprocess from dotenv import load_dotenv app = Flask(__name__, static_folder=os.path.join(ROOT_DIR, 'static'), static_url_path='/static', template_folder=os.path.join(ROOT_DIR, 'templates')) app.logger.setLevel(logging.INFO) .path.join(ROOT_DIR, 'app.log'), maxBytes=1024 * 1024, r.info('所有文件处理完毕') def static_files(filename): return send_from_directory(app.config['STATIC_FOLDER'], filename)
null
9,194
import datetime import logging import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os from gevent.pywsgi import WSGIServer, WSGIHandler import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic from gevent.pywsgi import LoggingLogAdapter import shutil import subprocess from dotenv import load_dotenv language = request.form.get("language") ROOT_DIR = os.getcwd() else: else: (ROOT_DIR,'tts','mymodels') def index(): return render_template("index.html", text_model=TEXT_MODEL_EXITS, voice_model=VOICE_MODEL_EXITS, version=clone.ver, language=cfg.LANG, root_dir=ROOT_DIR.replace('\\', '/'))
null
9,195
import datetime import logging import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os from gevent.pywsgi import WSGIServer, WSGIHandler import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic from gevent.pywsgi import LoggingLogAdapter import shutil import subprocess from dotenv import load_dotenv language = request.form.get("language") ROOT_DIR = os.getcwd() else: else: (ROOT_DIR,'tts','mymodels') def txt(): return render_template("txt.html", text_model=True,#TEXT_MODEL_EXITS, version=clone.ver, language=cfg.LANG, root_dir=ROOT_DIR.replace('\\', '/'))
null
9,196
import datetime import logging import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os from gevent.pywsgi import WSGIServer, WSGIHandler import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic from gevent.pywsgi import LoggingLogAdapter import shutil import subprocess from dotenv import load_dotenv app = Flask(__name__, static_folder=os.path.join(ROOT_DIR, 'static'), static_url_path='/static', template_folder=os.path.join(ROOT_DIR, 'templates')) app.logger.setLevel(logging.INFO) .path.join(ROOT_DIR, 'app.log'), maxBytes=1024 * 1024, return jsonify(result r.info('所有文件处理完毕') return jsonify({"code":0,"msg":"ok"} ROOT_DIR = os.getcwd() else: else: (ROOT_DIR,'tts','mymodels') def upload(): try: # 获取上传的文件 audio_file = request.files['audio'] save_dir = request.form.get("save_dir") save_dir = VOICE_DIR if not save_dir else os.path.join(ROOT_DIR, f'static/{save_dir}') app.logger.info(f"[upload]{audio_file.filename=},{save_dir=}") # 检查文件是否存在且是 WAV/mp3格式 noextname, ext = os.path.splitext(os.path.basename(audio_file.filename.lower())) noextname = noextname.replace(' ', '') if audio_file and ext in [".wav", ".mp3", ".flac"]: # 保存文件到服务器指定目录 name = f'{noextname}{ext}' if os.path.exists(os.path.join(save_dir, f'{noextname}{ext}')): name = f'{datetime.datetime.now().strftime("%m%d-%H%M%S")}-{noextname}{ext}' # mp3 or wav tmp_wav = os.path.join(TMP_DIR, "tmp_" + name) audio_file.save(tmp_wav) # save to wav if ext != '.wav': name = f"{name[:-len(ext)]}.wav" savename = os.path.join(save_dir, name) os.system(f'ffmpeg -hide_banner -y -i "{tmp_wav}" "{savename}"') try: os.unlink(tmp_wav) except: pass # 返回成功的响应 return jsonify({'code': 0, 'msg': 'ok', "data": name}) else: # 返回错误的响应 return jsonify({'code': 1, 'msg': 'not wav'}) except Exception as e: app.logger.error(f'[upload]error: {e}') return jsonify({'code': 2, 'msg': 'error'})
null
9,197
import datetime import logging import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os from gevent.pywsgi import WSGIServer, WSGIHandler import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic from gevent.pywsgi import LoggingLogAdapter import shutil import subprocess from dotenv import load_dotenv wavs = glob.glob(f"{VOICE_DIR}/*.wav") result = [] for it in wavs: if os.path.getsize(it) > 0: result.append(os.path.basename(it)) return jsonify(result return jsonify({"code":0,"msg":"ok"} else: else: def init(): wavs = glob.glob(f"{VOICE_DIR}/*.wav") result = [] for it in wavs: if os.path.getsize(it) > 0: result.append(os.path.basename(it)) return jsonify(result)
null
9,198
import datetime import logging import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os from gevent.pywsgi import WSGIServer, WSGIHandler import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic from gevent.pywsgi import LoggingLogAdapter import shutil import subprocess from dotenv import load_dotenv return jsonify(result return jsonify({"code":0,"msg":"ok"} else: else: langlist = langdict[LANG] def isstart(): total = cfg.tts_n + cfg.sts_n return jsonify({"code": 0, "msg": total, "tts": cfg.langlist['lang15'] if cfg.tts_n < 1 else "", "sts": cfg.langlist['lang16'] if cfg.sts_n < 1 else ""})
null
9,199
import datetime import logging import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os from gevent.pywsgi import WSGIServer, WSGIHandler import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic from gevent.pywsgi import LoggingLogAdapter import shutil import subprocess from dotenv import load_dotenv web_address = os.getenv('WEB_ADDRESS', '127.0.0.1:9988') app = Flask(__name__, static_folder=os.path.join(ROOT_DIR, 'static'), static_url_path='/static', template_folder=os.path.join(ROOT_DIR, 'templates')) app.logger.setLevel(logging.INFO) .path.join(ROOT_DIR, 'app.log'), maxBytes=1024 * 1024, result = [] return jsonify(result voice, src, dst, speed, language=pams r.info('所有文件处理完毕') voice = request.form.get("voice") speed = 1.0 try: speed = float(request.form.get("speed")) except: pass language = request.form.get("language") print(f'{src=},{dst=},{language=},{speed=},{voice=}') return jsonify({"code":0,"msg":"ok"} else: else: return Non # 获得md5 # 合成后的名字 #不是srt直接返回 # start is not 0 # join #去掉空行 # 时间格式 #再次遍历,去掉text为空的 # 行号 # 行格式 # 时间格式 # 先判断是否符合srt格式,不符合返回None # 再次遍历,删掉美元text的行 The provided code snippet includes necessary dependencies for implementing the `apitts` function. Write a Python function `def apitts()` to solve the following problem: audio:原始声音wav,作为音色克隆源 voice:已有的声音名字,如果存在 voice则先使用,否则使用audio text:文字一行 language:语言代码 Returns: Here is the function: def apitts(): ''' audio:原始声音wav,作为音色克隆源 voice:已有的声音名字,如果存在 voice则先使用,否则使用audio text:文字一行 language:语言代码 Returns: ''' try: langcodelist=["zh-cn","en","ja","ko","es","de","fr","it","tr","ru","pt","pl","nl","ar","hu","cs"] text = request.form.get("text").strip() text = text.replace("\n", ' . ') language = request.form.get("language","").lower() if language.startswith("zh"): language="zh-cn" if language not in langcodelist: return jsonify({"code":1,"msg":f"dont support language {language}"}) md5_hash = hashlib.md5() audio_name = request.form.get('voice') # 存在传来的声音文件名字 if audio_name: voicename = os.path.join(VOICE_DIR, audio_name) else: # 获取上传的文件 audio_file = request.files['audio'] print(f'{audio_file.filename}') # 保存临时上传过来的声音文件 audio_name = f'video_{audio_file.filename}.wav' voicename = os.path.join(TMP_DIR, audio_name) audio_file.save(voicename) md5_hash.update(f"{text}-{language}-{audio_name}".encode('utf-8')) app.logger.info(f"[apitts]{voicename=}") if re.match(r'^[~`!@#$%^&*()_+=,./;\':\[\]{}<>?\\|",。?;‘:“”’{【】}!·¥、\s\n\r -]*$', text): return jsonify({"code": 1, "msg": "lost text for translate"}) if not text or not language: return jsonify({"code": 1, "msg": "text & language params lost"}) app.logger.info(f"[apitts]{text=},{language=}") # 存放结果 # 合成后的语音文件, 以wav格式存放和返回 filename = md5_hash.hexdigest() + ".wav" app.logger.info(f"[apitts]{filename=}") # 合成语音 rs = create_tts(text=text, speed=1.0, voice=voicename, language=language, filename=filename) # 已有结果或错误,直接返回 if rs is not None: result = rs else: # 循环等待 最多7200s time_tmp = 0 while filename not in cfg.global_tts_result: time.sleep(3) time_tmp += 3 if time_tmp % 30 == 0: app.logger.info(f"[apitts][tts]{time_tmp=},{filename=}") # 当前行已完成合成 if cfg.global_tts_result[filename] != 1: msg = {"code": 1, "msg": cfg.global_tts_result[filename]} else: target_wav = os.path.normpath(os.path.join(TTS_DIR, filename)) msg = {"code": 0, "filename": target_wav, 'name': filename} app.logger.info(f"[apitts][tts] {filename=},{msg=}") cfg.global_tts_result.pop(filename) result = msg app.logger.info(f"[apitts]{msg=}") if result['code'] == 0: result['url'] = f'http://{web_address}/static/ttslist/{filename}' return jsonify(result) except Exception as e: msg=f'{str(e)} {str(e.args)}' app.logger.error(f"[apitts]{msg}") return jsonify({'code': 2, 'msg': msg})
audio:原始声音wav,作为音色克隆源 voice:已有的声音名字,如果存在 voice则先使用,否则使用audio text:文字一行 language:语言代码 Returns:
9,200
import datetime import logging import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os from gevent.pywsgi import WSGIServer, WSGIHandler import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic from gevent.pywsgi import LoggingLogAdapter import shutil import subprocess from dotenv import load_dotenv return jsonify(result chuliing={"name":"","line":0,"end":False} global chuliing chuliing={"name":"","line":0,"end":False} nd']=Tru return jsonify({"code":0,"msg":"ok"} def ttslistjindu(): return jsonify(chuliing)
null
9,201
import datetime import logging import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os from gevent.pywsgi import WSGIServer, WSGIHandler import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic from gevent.pywsgi import LoggingLogAdapter import shutil import subprocess from dotenv import load_dotenv return jsonify(result) start', methods=['GET', 'POST']) voice, src, dst, speed, language=pams voice = request.form.get("voice") src = request.form.get("src") dst = request.form.get("dst") speed = 1.0 try: speed = float(request.form.get("speed")) except: pass language = request.form.get("language") path.normpath(src) print(f'{src=},{dst=},{language=},{speed=},{voice=}') if not src or not dst or not os.path.exists(src) or not os.path.exists(dst): return jsonify({"code":1,"msg":"必须正确填写txt所在目录以及目标目录的完整路径"}) threading.Thread(target=detail_task, args=(voice, src, dst, speed, language)).start() return jsonify({"code":0,"msg":"ok"} def ttslist(): voice = request.form.get("voice") src = request.form.get("src") dst = request.form.get("dst") speed = 1.0 try: speed = float(request.form.get("speed")) except: pass language = request.form.get("language") #根据src获取所有txt src=os.path.normpath(src) print(f'{src=},{dst=},{language=},{speed=},{voice=}') if not src or not dst or not os.path.exists(src) or not os.path.exists(dst): return jsonify({"code":1,"msg":"必须正确填写txt所在目录以及目标目录的完整路径"}) threading.Thread(target=detail_task, args=(voice, src, dst, speed, language)).start() return jsonify({"code":0,"msg":"ok"})
null
9,202
import datetime import logging import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os from gevent.pywsgi import WSGIServer, WSGIHandler import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic from gevent.pywsgi import LoggingLogAdapter import shutil import subprocess from dotenv import load_dotenv app = Flask(__name__, static_folder=os.path.join(ROOT_DIR, 'static'), static_url_path='/static', template_folder=os.path.join(ROOT_DIR, 'templates')) app.logger.setLevel(logging.INFO) .path.join(ROOT_DIR, 'app.log'), maxBytes=1024 * 1024, for it in wavs: if os.path.getsize(it) > 0: result.append(os.path.basename(it)) return jsonify(result voice, src, dst, speed, language=pams n os.listdir(src): if not t.lower().endswith('.txt'): continue concat_txt=os.path.join(cfg.TTS_DIR, re.sub(r'[ \s\[\]\{\}\(\)<>\?\, :]+','', t, re.I) + '.txt') app.logger.info(f'####开始处理文件:{t}, 每行结果保存在:{concat_txt}') with open(concat_txt,'w',encoding='utf-8') as f: f.write("") #需要等待执行完毕的数据 [{}, {}] waitlist=[] #已执行完毕的 {1:{}, 2:{}} result={} with open(os.path.join(src,t),'r',encoding='utf-8') as f: num=0 for line in f.readlines(): num+=1 line=line.strip() if re.match(r'^[~`!@#$%^&*()_+=,./;\':\[\]{}<>?\\|",。?;‘:“”’{【】}!·¥、\s\n\r -]*$', line): app.logger.info(f'\t第{num}不存在有效文字,跳过') continue md5_hash = hashlib.md5() md5_hash.update(f"{line}-{voice}-{language}-{speed}".encode('utf-8')) filename = md5_hash.hexdigest() + ".wav" app.logger.info(f'\t开始合成第{num}行声音:{filename=}') # 合成语音 rs = create_tts(text=line, speed=speed, voice=voice, language=language, filename=filename) # 已有结果或错误,直接返回 if rs is not None and rs['code']==1: app.logger.error(f'\t{t}:文件内容第{num}行【 {line} 】出错了,跳过') continue if rs is not None and rs['code']==0: #已存在直接使用 result[f'{num}']={"filename":filename, "num":num} chuliing['name']=t chuliing['line']=num app.logger.info(f'\t第{num}行合成完毕:{filename=}') continue waitlist.append({"filename":filename, "num":num, "t":t}) #for it in waitlist: time_tmp = 0 chuliing['name']=t if len(waitlist)>0: chuliing['line']=waitlist[0]['num'] while len(waitlist)>0: it=waitlist.pop(0) filename, num, t=it.values() #需要等待 if time_tmp>7200: continue # 当前行已完成合成 if filename in cfg.global_tts_result and cfg.global_tts_result[filename] != 1: #出错了 app.logger.error(f'\t{t}:文件内容第{num}行出错了,{cfg.global_tts_result[filename]}, 跳过') continue if os.path.exists(os.path.join(cfg.TTS_DIR, filename)): chuliing['name']=t chuliing['line']=num app.logger.info(f'\t第{num}行合成完毕:{filename}') #成功了 result[f'{num}']={"filename":filename, "num":num} continue #未完成,插入重新开 waitlist.append(it) time_tmp+=1 time.sleep(1) if len(result.keys())<1: app.logger.error(f'\t该文件合成失败,没有生成任何声音') continue sorted_result = {k: result[k] for k in sorted(result, key=lambda x: int(x))} for i, it in sorted_result.items(): theaudio = os.path.normpath(os.path.join(cfg.TTS_DIR, it['filename'])) with open(concat_txt, 'a', encoding='utf-8') as f: f.write(f"file '{theaudio}'\n") #当前txt执行完成 合并音频 target_mp3=os.path.normpath((os.path.join(dst,f'{t}.mp3'))) p=subprocess.run(['ffmpeg',"-hide_banner", "-ignore_unknown", '-y', '-f', 'concat', '-safe', '0', '-i', concat_txt, target_mp3]) if p.returncode!=0: app.logger.error(f'\t处理文件:{t},将所有音频连接一起时出错') continue app.logger.info(f'\t已生成完整音频:{target_mp3}') if speed != 1.0 and speed > 0 and speed <= 2.0: p= subprocess.run(['ffmpeg', '-hide_banner', '-ignore_unknown', '-y', '-i', target_mp3, '-af', f"atempo={speed}",f'{target_mp3}-speed{speed}.mp3'], encoding="utf-8", capture_output=True) if p.returncode != 0: app.logger.error(f'\t处理文件{t}:将{target_mp3}音频改变速度{speed}倍时失败') continue os.unlink(target_mp3) target_mp3=f'{target_mp3}-speed{speed}.mp3' app.logger.info(f'\t文件:{t} 处理完成,mp3:{target_mp3}') app.logger.info('所有文件处理完毕') voice = request.form.get("voice") speed = 1.0 try: speed = float(request.form.get("speed")) except: pass language = request.form.get("language") return jsonify({"code":0,"msg":"ok"} else: else: return None def merge_audio_segments(text_list,is_srt=True): # 获得md5 # 合成后的名字 #不是srt直接返回 # start is not 0 # join #去掉空行 # 时间格式 #再次遍历,去掉text为空的 def get_subtitle_from_srt(srtfile): # 行号 # 行格式 # 时间格式 # 先判断是否符合srt格式,不符合返回None # 再次遍历,删掉美元text的行 def tts(): # 原始字符串 text = request.form.get("text").strip() voice = request.form.get("voice") speed = 1.0 try: speed = float(request.form.get("speed")) except: pass language = request.form.get("language") app.logger.info(f"[tts][tts]recev {text=}\n{voice=},{language=}\n") if re.match(r'^[~`!@#$%^&*()_+=,./;\':\[\]{}<>?\\|",。?;‘:“”’{【】}!·¥、\s\n\r -]*$', text): return jsonify({"code": 1, "msg": "no text"}) if not text or not voice or not language: return jsonify({"code": 1, "msg": "text/voice/language params lost"}) # 判断是否是srt text_list = get_subtitle_from_srt(text) app.logger.info(f"[tts][tts]{text_list=}") is_srt = True # 不是srt格式,则按行分割 if text_list is None: is_srt = False text_list = [] for it in text.split("\n"): text_list.append({"text": it.strip()}) app.logger.info(f"[tts][tts] its not srt") num = 0 while num < len(text_list): t = text_list[num] # 换行符改成 . t['text'] = t['text'].replace("\n", ' . ') md5_hash = hashlib.md5() md5_hash.update(f"{t['text']}-{voice}-{language}-{speed}".encode('utf-8')) filename = md5_hash.hexdigest() + ".wav" app.logger.info(f"[tts][tts]{filename=}") # 合成语音 rs = create_tts(text=t['text'], speed=speed, voice=voice, language=language, filename=filename) # 已有结果或错误,直接返回 if rs is not None: text_list[num]['result'] = rs num += 1 continue # 循环等待 最多7200s time_tmp = 0 while filename not in cfg.global_tts_result: time.sleep(3) time_tmp += 3 if time_tmp % 30 == 0: app.logger.info(f"[tts][tts]{time_tmp=},{filename=}") # 当前行已完成合成 if cfg.global_tts_result[filename] != 1: msg = {"code": 1, "msg": cfg.global_tts_result[filename]} else: target_wav = os.path.normpath(os.path.join(TTS_DIR, filename)) if speed != 1.0 and speed > 0 and speed <= 2.0: # 生成的加速音频 speed_tmp = os.path.join(TMP_DIR, f'speed_{time.time()}.wav') p = subprocess.run( ['ffmpeg', '-hide_banner', '-ignore_unknown', '-y', '-i', target_wav, '-af', f"atempo={speed}", os.path.normpath(speed_tmp)], encoding="utf-8", capture_output=True) if p.returncode != 0: return jsonify({"code": 1, "msg": str(p.stderr)}) shutil.copy2(speed_tmp, target_wav) msg = {"code": 0, "filename": target_wav, 'name': filename} app.logger.info(f"[tts][tts] {filename=},{msg=}") cfg.global_tts_result.pop(filename) text_list[num]['result'] = msg app.logger.info(f"[tts][tts]{num=}") num += 1 filename, errors = merge_audio_segments(text_list, is_srt=is_srt) app.logger.info(f"[tts][tts]is srt,{filename=},{errors=}") if filename and os.path.exists(filename) and os.path.getsize(filename) > 0: res = {"code": 0, "filename": filename, "name": os.path.basename(filename), "msg": errors} else: res = {"code": 1, "msg": f"error:{filename=},{errors=}"} app.logger.info(f"[tts][tts]end result:{res=}") return jsonify(res)
null
9,203
import datetime import logging import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os from gevent.pywsgi import WSGIServer, WSGIHandler import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic from gevent.pywsgi import LoggingLogAdapter import shutil import subprocess from dotenv import load_dotenv app = Flask(__name__, static_folder=os.path.join(ROOT_DIR, 'static'), static_url_path='/static', template_folder=os.path.join(ROOT_DIR, 'templates')) app.logger.setLevel(logging.INFO) .path.join(ROOT_DIR, 'app.log'), maxBytes=1024 * 1024, return jsonify(result voice, src, dst, speed, language=pams r.info('所有文件处理完毕') voice = request.form.get("voice") return jsonify({"code":0,"msg":"ok"} else: else: def sts(): try: # 保存文件到服务器指定目录 # 目标 voice = request.form.get("voice") filename = request.form.get("name") app.logger.info(f"[sts][sts]sts {voice=},{filename=}\n") if not voice: return jsonify({"code": 1, "msg": "voice params lost"}) obj = {"filename": filename, "voice": voice} # 压入队列,准备转换语音 app.logger.info(f"[sts][sts]push sts") cfg.q_sts.put(obj) # 已有结果或错误,直接返回 # 循环等待 最多7200s time_tmp = 0 while filename not in cfg.global_sts_result: time.sleep(3) time_tmp += 3 if time_tmp % 30 == 0: app.logger.info(f"{time_tmp=},{filename=}") # 当前行已完成合成 if cfg.global_sts_result[filename] != 1: msg = {"code": 1, "msg": cfg.global_sts_result[filename]} app.logger.error(f"[sts][sts]error,{msg=}") else: msg = {"code": 0, "filename": os.path.join(TTS_DIR, filename), 'name': filename} app.logger.info(f"[sts][sts]ok,{msg=}") cfg.global_sts_result.pop(filename) return jsonify(msg) except Exception as e: app.logger.error(f"[sts][sts]error:{str(e)}") return jsonify({'code': 2, 'msg': f'voice->voice:{str(e)}'})
null
9,204
import datetime import logging import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os from gevent.pywsgi import WSGIServer, WSGIHandler import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic from gevent.pywsgi import LoggingLogAdapter import shutil import subprocess from dotenv import load_dotenv return jsonify(result return jsonify({"code":0,"msg":"ok"} else: else: def checkupdate(): return jsonify({'code': 0, "msg": cfg.updatetips})
null
9,205
import argparse import os import sys import tempfile import gradio as gr import librosa.display import numpy as np import os import torch import torchaudio import traceback from TTS.demos.xtts_ft_demo.utils.formatter import format_audio_list from TTS.demos.xtts_ft_demo.utils.gpt_train import train_gpt from TTS.demos.xtts_ft_demo.utils.cfg import TTSMODEL_DIR from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts XTTS_MODEL = None import logging def run_tts(lang, tts_text, speaker_audio_file): if XTTS_MODEL is None or not speaker_audio_file: return "You need to run the previous step to load the model !!", None, None gpt_cond_latent, speaker_embedding = XTTS_MODEL.get_conditioning_latents(audio_path=speaker_audio_file, gpt_cond_len=XTTS_MODEL.config.gpt_cond_len, max_ref_length=XTTS_MODEL.config.max_ref_len, sound_norm_refs=XTTS_MODEL.config.sound_norm_refs) out = XTTS_MODEL.inference( text=tts_text, language=lang, gpt_cond_latent=gpt_cond_latent, speaker_embedding=speaker_embedding, temperature=XTTS_MODEL.config.temperature, # Add custom parameters here length_penalty=XTTS_MODEL.config.length_penalty, repetition_penalty=XTTS_MODEL.config.repetition_penalty, top_k=XTTS_MODEL.config.top_k, top_p=XTTS_MODEL.config.top_p, ) with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as fp: out["wav"] = torch.tensor(out["wav"]).unsqueeze(0) out_path = fp.name torchaudio.save(out_path, out["wav"], 24000) return "Speech generated !", out_path, speaker_audio_file
null
9,206
import argparse import os import sys import tempfile import gradio as gr import librosa.display import numpy as np import os import torch import torchaudio import traceback from TTS.demos.xtts_ft_demo.utils.formatter import format_audio_list from TTS.demos.xtts_ft_demo.utils.gpt_train import train_gpt from TTS.demos.xtts_ft_demo.utils.cfg import TTSMODEL_DIR from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts sys.stdout = Logger() sys.stderr = sys.stdout import logging def read_logs(): sys.stdout.flush() with open(sys.stdout.log_file, "r") as f: return f.read()
null
9,207
import argparse import os import sys import tempfile import gradio as gr import librosa.display import numpy as np import os import torch import torchaudio import traceback from TTS.demos.xtts_ft_demo.utils.formatter import format_audio_list from TTS.demos.xtts_ft_demo.utils.gpt_train import train_gpt from TTS.demos.xtts_ft_demo.utils.cfg import TTSMODEL_DIR from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts def clear_gpu_cache(): # clear the GPU cache if torch.cuda.is_available(): torch.cuda.empty_cache() def load_model(xtts_checkpoint, xtts_config, xtts_vocab): global XTTS_MODEL clear_gpu_cache() if not xtts_checkpoint or not xtts_config or not xtts_vocab: return "You need to run the previous steps or manually set the `XTTS checkpoint path`, `XTTS config path`, and `XTTS vocab path` fields !!" config = XttsConfig() config.load_json(xtts_config) XTTS_MODEL = Xtts.init_from_config(config) print("Loading XTTS model! ") XTTS_MODEL.load_checkpoint(config, checkpoint_path=xtts_checkpoint, vocab_path=xtts_vocab, use_deepspeed=False) if torch.cuda.is_available(): XTTS_MODEL.cuda() print("Model Loaded!") return "Model Loaded!" import logging def preprocess_dataset(audio_path, language, progress=gr.Progress(track_tqdm=True)): clear_gpu_cache() out_path = os.path.join(args.out_path, "dataset") os.makedirs(out_path, exist_ok=True) try: train_meta, eval_meta, audio_total_size = format_audio_list(audio_path, target_language=language, out_path=out_path, gradio_progress=progress) except: traceback.print_exc() error = traceback.format_exc() return f"处理训练数据出错了! \n Error summary: {error}", "", "","","" clear_gpu_cache() # if audio total len is less than 2 minutes raise an error if audio_total_size < 120: message = "素材总时长不得小于2分钟!" print(message) return message, "", "","","" print("数据处理完毕,开始训练!") msg, config_path, vocab_file, ft_xtts_checkpoint, speaker_wav=train_model(language, train_meta, eval_meta, args.num_epochs, args.batch_size, args.grad_acumm, args.out_path, args.max_audio_length) progress_data, xtts_config, xtts_vocab, xtts_checkpoint, speaker_reference_audio msg=load_model( ft_xtts_checkpoint, config_path, vocab_file ) return msg, config_path, vocab_file, ft_xtts_checkpoint, speaker_wav
null
9,208
import datetime import logging import queue import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic import shutil import subprocess from dotenv import load_dotenv from waitress import serve app = Flask(__name__, static_folder=os.path.join(ROOT_DIR, 'static'), static_url_path='/static', template_folder=os.path.join(ROOT_DIR, 'templates')) app.logger.setLevel(logging.WARNING) .path.join(ROOT_DIR, 'app.log'), maxBytes=1024 * 1024, def static_files(filename): return send_from_directory(app.config['STATIC_FOLDER'], filename)
null
9,209
import datetime import logging import queue import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic import shutil import subprocess from dotenv import load_dotenv from waitress import serve ROOT_DIR = os.getcwd() else: else: (ROOT_DIR,'tts','mymodels') langlist = langdict[LANG] def index(): return render_template("index.html", text_model=TEXT_MODEL_EXITS, voice_model=VOICE_MODEL_EXITS, version=clone.ver, mymodels=cfg.MYMODEL_OBJS, language=cfg.LANG, langlist=cfg.langlist, root_dir=ROOT_DIR.replace('\\', '/'))
null
9,210
import datetime import logging import queue import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic import shutil import subprocess from dotenv import load_dotenv from waitress import serve app = Flask(__name__, static_folder=os.path.join(ROOT_DIR, 'static'), static_url_path='/static', template_folder=os.path.join(ROOT_DIR, 'templates')) app.logger.setLevel(logging.WARNING) .path.join(ROOT_DIR, 'app.log'), maxBytes=1024 * 1024, return jsonify(result ROOT_DIR = os.getcwd() else: else: (ROOT_DIR,'tts','mymodels') def upload(): try: # 获取上传的文件 audio_file = request.files['audio'] save_dir = request.form.get("save_dir",'') save_dir = VOICE_DIR if not save_dir else os.path.join(ROOT_DIR, f'static/{save_dir}') app.logger.info(f"[upload]{audio_file.filename=},{save_dir=}") # 检查文件是否存在且是 WAV/mp3格式 noextname, ext = os.path.splitext(os.path.basename(audio_file.filename.lower())) noextname = noextname.replace(' ', '') if audio_file and ext in [".wav", ".mp3", ".flac"]: # 保存文件到服务器指定目录 name = f'{noextname}{ext}' if os.path.exists(os.path.join(save_dir, f'{noextname}{ext}')): name = f'{datetime.datetime.now().strftime("%m%d-%H%M%S")}-{noextname}{ext}' # mp3 or wav tmp_wav = os.path.join(TMP_DIR, "tmp_" + name) audio_file.save(tmp_wav) # save to wav if ext != '.wav': name = f"{name[:-len(ext)]}.wav" savename = os.path.join(save_dir, name) os.system(f'ffmpeg -hide_banner -y -i "{tmp_wav}" "{savename}"') try: os.unlink(tmp_wav) except: pass # 返回成功的响应 return jsonify({'code': 0, 'msg': 'ok', "data": name}) else: # 返回错误的响应 return jsonify({'code': 1, 'msg': 'not wav'}) except Exception as e: app.logger.error(f'[upload]error: {e}') return jsonify({'code': 2, 'msg': 'error'})
null
9,211
import datetime import logging import queue import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic import shutil import subprocess from dotenv import load_dotenv from waitress import serve wavs = glob.glob(f"{VOICE_DIR}/*.wav") result = [] for it in wavs: if os.path.getsize(it) > 0: result.append(os.path.basename(it)) result.extend(cfg.MYMODEL_OBJS.keys()) return jsonify(result else: else: def init(): wavs = glob.glob(f"{VOICE_DIR}/*.wav") result = [] for it in wavs: if os.path.getsize(it) > 0: result.append(os.path.basename(it)) result.extend(cfg.MYMODEL_OBJS.keys()) return jsonify(result)
null
9,212
import datetime import logging import queue import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic import shutil import subprocess from dotenv import load_dotenv from waitress import serve return jsonify(result else: else: def isstart(): return jsonify(cfg.MYMODEL_OBJS)
null
9,213
import datetime import logging import queue import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic import shutil import subprocess from dotenv import load_dotenv from waitress import serve web_address = os.getenv('WEB_ADDRESS', '127.0.0.1:9988') app = Flask(__name__, static_folder=os.path.join(ROOT_DIR, 'static'), static_url_path='/static', template_folder=os.path.join(ROOT_DIR, 'templates')) app.logger.setLevel(logging.WARNING) .path.join(ROOT_DIR, 'app.log'), maxBytes=1024 * 1024, result = [] result.extend(cfg.MYMODEL_OBJS.keys()) return jsonify(result else: else: return Non # 获得md5 # 合成后的名字 #不是srt直接返回 # start is not 0 # join #去掉空行 # 时间格式 #再次遍历,去掉text为空的 # 行号 # 行格式 # 时间格式 # 先判断是否符合srt格式,不符合返回None # 再次遍历,删掉美元text的行 The provided code snippet includes necessary dependencies for implementing the `apitts` function. Write a Python function `def apitts()` to solve the following problem: audio:原始声音wav,作为音色克隆源 voice:已有的声音名字,如果存在 voice则先使用,否则使用audio text:文字一行 language:语言代码 Returns: Here is the function: def apitts(): ''' audio:原始声音wav,作为音色克隆源 voice:已有的声音名字,如果存在 voice则先使用,否则使用audio text:文字一行 language:语言代码 Returns: ''' try: langcodelist = ["zh-cn", "en", "ja", "ko", "es", "de", "fr", "it", "tr", "ru", "pt", "pl", "nl", "ar", "hu", "cs"] text = request.form.get("text","").strip() model = request.form.get("model","").strip() text = text.replace("\n", ' . ') language = request.form.get("language", "").lower() if language.startswith("zh"): language = "zh-cn" if language not in langcodelist: return jsonify({"code": 1, "msg": f" {language} dont support language "}) md5_hash = hashlib.md5() audio_name = request.form.get('voice','') voicename="" model="" # 存在传来的声音文件名字 print(f'1,{text=},{model=},{audio_name=},{language=}') if audio_name and audio_name.lower().endswith('.wav'): voicename = os.path.join(VOICE_DIR, audio_name) if not os.path.exists(voicename): return jsonify({"code": 2, "msg": f"{audio_name} 不存在"}) if os.path.isdir(voicename): model=audio_name voicename="" elif audio_name: #存在,是新模型 model=audio_name elif not audio_name: # 不存在,原声复制 clone 获取上传的文件 audio_file = request.files['audio'] print(f'{audio_file.filename}') # 保存临时上传过来的声音文件 audio_name = f'video_{audio_file.filename}.wav' voicename = os.path.join(TMP_DIR, audio_name) audio_file.save(voicename) print(f'22={text=},{model=},{audio_name=},{language=}') md5_hash.update(f"{text}-{language}-{audio_name}-{model}".encode('utf-8')) app.logger.info(f"[apitts]{voicename=}") if re.match(r'^[~`!@#$%^&*()_+=,./;\':\[\]{}<>?\\|",。?;‘:“”’{【】}!·¥、\s\n\r -]*$', text): return jsonify({"code": 3, "msg": "lost text for translate"}) if not text or not language: return jsonify({"code": 4, "msg": "text & language params lost"}) app.logger.info(f"[apitts]{text=},{language=}") # 存放结果 # 合成后的语音文件, 以wav格式存放和返回 filename = md5_hash.hexdigest() + ".wav" app.logger.info(f"[apitts]{filename=}") # 合成语音 rs = create_tts(text=text,model=model, speed=1.0, voice=voicename, language=language, filename=filename) # 已有结果或错误,直接返回 if rs is not None: print(f'{rs=}') result = rs else: # 循环等待 最多7200s time_tmp = 0 while filename not in cfg.global_tts_result: time.sleep(3) time_tmp += 3 if time_tmp % 30 == 0: app.logger.info(f"[apitts][tts]{time_tmp=},{filename=}") if time_tmp>3600: return jsonify({"code": 5, "msg": f'error:{text}'}) # 当前行已完成合成 target_wav = os.path.normpath(os.path.join(TTS_DIR, filename)) if not os.path.exists(target_wav): msg = {"code": 6, "msg": cfg.global_tts_result[filename] if filename in cfg.global_tts_result else "error"} else: msg = {"code": 0, "filename": target_wav, 'name': filename} app.logger.info(f"[apitts][tts] {filename=},{msg=}") try: cfg.global_tts_result.pop(filename) except: pass result = msg app.logger.info(f"[apitts]{msg=}") if result['code'] == 0: result['url'] = f'http://{web_address}/static/ttslist/{filename}' return jsonify(result) except Exception as e: msg = f'{str(e)} {str(e.args)}' app.logger.error(f"[apitts]{msg}") return jsonify({'code': 7, 'msg': msg})
audio:原始声音wav,作为音色克隆源 voice:已有的声音名字,如果存在 voice则先使用,否则使用audio text:文字一行 language:语言代码 Returns:
9,214
import datetime import logging import queue import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic import shutil import subprocess from dotenv import load_dotenv from waitress import serve app = Flask(__name__, static_folder=os.path.join(ROOT_DIR, 'static'), static_url_path='/static', template_folder=os.path.join(ROOT_DIR, 'templates')) app.logger.setLevel(logging.WARNING) .path.join(ROOT_DIR, 'app.log'), maxBytes=1024 * 1024, for it in wavs: if os.path.getsize(it) > 0: result.append(os.path.basename(it)) return jsonify(result else: else: return None def merge_audio_segments(text_list,is_srt=True): # 获得md5 # 合成后的名字 #不是srt直接返回 # start is not 0 # join #去掉空行 # 时间格式 #再次遍历,去掉text为空的 def get_subtitle_from_srt(srtfile): # 行号 # 行格式 # 时间格式 # 先判断是否符合srt格式,不符合返回None # 再次遍历,删掉美元text的行 def tts(): # 原始字符串 text = request.form.get("text","").strip() voice = request.form.get("voice",'') speed = 1.0 try: speed = float(request.form.get("speed",1)) except: pass language = request.form.get("language",'') model = request.form.get("model","") app.logger.info(f"[tts][tts]recev {text=}\n{voice=},{language=}\n") if re.match(r'^[~`!@#$%^&*()_+=,./;\':\[\]{}<>?\\|",。?;‘:“”’{【】}!·¥、\s\n\r -]*$', text): return jsonify({"code": 1, "msg": "no text"}) if not text or not voice or not language: return jsonify({"code": 1, "msg": "text/voice/language params lost"}) # 判断是否是srt text_list = get_subtitle_from_srt(text) app.logger.info(f"[tts][tts]{text_list=}") is_srt = True # 不是srt格式,则按行分割 if text_list is None: is_srt = False text_list = [] for it in text.split("\n"): text_list.append({"text": it.strip()}) app.logger.info(f"[tts][tts] its not srt") num = 0 while num < len(text_list): t = text_list[num] # 换行符改成 . t['text'] = t['text'].replace("\n", ' . ') md5_hash = hashlib.md5() md5_hash.update(f"{t['text']}-{voice}-{language}-{speed}-{model}".encode('utf-8')) filename = md5_hash.hexdigest() + ".wav" app.logger.info(f"[tts][tts]{filename=}") # 合成语音 rs = create_tts(text=t['text'], model=model,speed=speed, voice=os.path.join(cfg.VOICE_DIR, voice), language=language, filename=filename) # 已有结果或错误,直接返回 if rs is not None: text_list[num]['result'] = rs num += 1 continue # 循环等待 最多7200s time_tmp = 0 # 生成的目标音频 target_wav = os.path.normpath(os.path.join(TTS_DIR, filename)) msg=None while filename not in cfg.global_tts_result and not os.path.exists(target_wav): time.sleep(3) time_tmp += 3 if time_tmp % 30 == 0: app.logger.info(f"[tts][tts]{time_tmp=},{filename=}") if time_tmp>3600: msg={"code": 1, "msg":f'{filename} error'} text_list[num]['result'] = msg num+=1 break if msg is not None: continue # 当前行已完成合成 if not os.path.exists(target_wav): msg = {"code": 1, "msg": "not exists"} else: if speed != 1.0 and speed > 0 and speed <= 2.0: # 生成的加速音频 speed_tmp = os.path.join(TMP_DIR, f'speed_{time.time()}.wav') p = subprocess.run( ['ffmpeg', '-hide_banner', '-ignore_unknown', '-y', '-i', target_wav, '-af', f"atempo={speed}", os.path.normpath(speed_tmp)], encoding="utf-8", capture_output=True) if p.returncode != 0: return jsonify({"code": 1, "msg": str(p.stderr)}) shutil.copy2(speed_tmp, target_wav) msg = {"code": 0, "filename": target_wav, 'name': filename} app.logger.info(f"[tts][tts] {filename=},{msg=}") try: cfg.global_tts_result.pop(filename) except: pass text_list[num]['result'] = msg app.logger.info(f"[tts][tts]{num=}") num += 1 filename, errors = merge_audio_segments(text_list, is_srt=is_srt) app.logger.info(f"[tts][tts]is srt,{filename=},{errors=}") if filename and os.path.exists(filename) and os.path.getsize(filename) > 0: res = {"code": 0, "filename": filename, "name": os.path.basename(filename), "msg": errors} else: res = {"code": 1, "msg": f"error:{filename=},{errors=}"} app.logger.info(f"[tts][tts]end result:{res=}") return jsonify(res)
null
9,215
import datetime import logging import queue import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic import shutil import subprocess from dotenv import load_dotenv from waitress import serve app = Flask(__name__, static_folder=os.path.join(ROOT_DIR, 'static'), static_url_path='/static', template_folder=os.path.join(ROOT_DIR, 'templates')) app.logger.setLevel(logging.WARNING) .path.join(ROOT_DIR, 'app.log'), maxBytes=1024 * 1024, return jsonify(result else: else: def sts(): try: # 保存文件到服务器指定目录 # 目标 voice = request.form.get("voice",'') filename = request.form.get("name",'') app.logger.info(f"[sts][sts]sts {voice=},{filename=}\n") if not voice: return jsonify({"code": 1, "msg": "voice params lost"}) obj = {"filename": filename, "voice": voice} # 压入队列,准备转换语音 app.logger.info(f"[sts][sts]push sts") cfg.q_sts.put(obj) # 已有结果或错误,直接返回 # 循环等待 最多7200s time_tmp = 0 while filename not in cfg.global_sts_result: time.sleep(3) time_tmp += 3 if time_tmp % 30 == 0: app.logger.info(f"{time_tmp=},{filename=}") # 当前行已完成合成 if cfg.global_sts_result[filename] != 1: msg = {"code": 1, "msg": cfg.global_sts_result[filename]} app.logger.error(f"[sts][sts]error,{msg=}") else: msg = {"code": 0, "filename": os.path.join(TTS_DIR, filename), 'name': filename} app.logger.info(f"[sts][sts]ok,{msg=}") cfg.global_sts_result.pop(filename) return jsonify(msg) except Exception as e: app.logger.error(f"[sts][sts]error:{str(e)}") return jsonify({'code': 2, 'msg': f'voice->voice:{str(e)}'})
null
9,216
import datetime import logging import queue import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic import shutil import subprocess from dotenv import load_dotenv from waitress import serve return jsonify(result else: else: return Non # 获得md5 # 合成后的名字 #不是srt直接返回 # start is not 0 # join #去掉空行 # 时间格式 #再次遍历,去掉text为空的 # 行号 # 行格式 # 时间格式 # 先判断是否符合srt格式,不符合返回None # 再次遍历,删掉美元text的行 def onoroff(): name = request.form.get("name",'') status_new = request.form.get("status_new",'') if status_new=='on': if not cfg.MYMODEL_OBJS[name] or isinstance(cfg.MYMODEL_OBJS[name],str): try: print(f'start {name}...') res=logic.load_model(name) print(f'{res=}') return jsonify({"code":0,"msg":res}) except Exception as e: return jsonify({"code":1,"msg":str(e)}) elif cfg.MYMODEL_OBJS[name] in ['error','no']: return jsonify({"code":0,"msg":"模型启动出错或不存在"}) return jsonify({"code":0,"msg":"已启动"}) else: #关闭 cfg.MYMODEL_OBJS[name]=None #删除队列 cfg.MYMODEL_QUEUE[name]=None return jsonify({"code":0,"msg":"已启动"})
null
9,217
import datetime import logging import queue import re import threading import time import sys from flask import Flask, request, render_template, jsonify, send_file, send_from_directory import os import glob import hashlib from logging.handlers import RotatingFileHandler import clone from clone import cfg from clone.cfg import ROOT_DIR, TTS_DIR, VOICE_MODEL_EXITS, TMP_DIR, VOICE_DIR, TEXT_MODEL_EXITS, langlist from clone.logic import ttsloop, stsloop, create_tts, openweb, merge_audio_segments, get_subtitle_from_srt, updatecache from clone import logic import shutil import subprocess from dotenv import load_dotenv from waitress import serve return jsonify(result else: else: def checkupdate(): return jsonify({'code': 0, "msg": cfg.updatetips})
null
9,218
import hashlib import json import os import re import shutil import tempfile import threading import time import webbrowser import aiohttp import requests import torch import torchaudio from pydub import AudioSegment import clone from clone import cfg from clone.cfg import langlist from TTS.api import TTS from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts from dotenv import load_dotenv if os.path.exists(absofilename) and os.path.getsize(absofilename) > 0: print(f"[tts][create_ts]{filename} {speed} has exists") cfg.global_tts_result[filename] = 1 return {"code": 0, "filename": absofilename, 'name': filename} if os.path.exists(absofilename): return (absofilename, "") for it in text_list: if "filename" in it['result'] and os.path.exists(it['result']['filename']): # 存在音频文件 seg=AudioSegment.from_wav(it['result']['filename']) if "start_time" in it: start_times.append(it['start_time']) segments.append(seg) else: merged_audio+=seg try: os.unlink(it['result']['filename']) except: pass elif "msg" in it['result']: # 出错 errors.append(str(it['result']['msg'])) for i in range(len(segments)): segment = segments[i] start_time = start_times[i] # add silence if i > 0: previous_end_time = start_times[i - 1] + len(segments[i - 1]) silence_duration = start_time - previous_end_time # 可能存在字幕 语音对应问题 if silence_duration > 0: silence = AudioSegment.silent(duration=silence_duration) merged_audio += silence merged_audio += segment while cfg.tts_n==0: time.sleep(5) for i,it in enumerate(content): #当前空行跳过 if not it.strip(): continue it=it.strip() is_time=re.match(timepat,it) if is_time: #当前行是时间格式,则添加 result.append({"time":it,"text":[]}) elif i==0: #当前是第一行,并且不是时间格式,跳过 continue elif re.match(r'^\s*?\d+\s*?$',it) and i<maxindex and re.match(timepat,content[i+1]): #当前不是时间格式,不是第一行,并且都是数字,并且下一行是时间格式,则当前是行号,跳过 continue elif len(result)>0 and not re.match(textpat,it): #当前不是时间格式,不是第一行,(不是行号),并且result中存在数据,则是内容,可加入最后一个数据 result[-1]['text'].append(it) for it in result: if "text" in it and len(it['text'].strip()) > 0: it['line'] = line startraw, endraw = it['time'].strip().split("-->") start = startraw.strip().replace(',', '.').replace(',','.').replace(':',':').split(":") end = endraw.strip().replace(',', '.').replace(',','.').replace(':',':').split(":") start_time = int(int(start[0]) * 3600000 + int(start[1]) * 60000 + float(start[2]) * 1000) end_time = int(int(end[0]) * 3600000 + int(end[1]) * 60000 + float(end[2]) * 1000) it['startraw'] = startraw it['endraw'] = endraw it['start_time'] = start_time it['end_time'] = end_time new_result.append(it) line += 1 for i, t in enumerate(txt): # 当前行 小于等于倒数第三行 并且匹配行号,并且下一行匹配时间戳,则是行号 if i < maxline - 2 and re.match(linepat, t) and re.match(timepat, txt[i + 1]): # 是行 line += 1 obj = {"line": line, "time": "", "text": ""} result.append(obj) elif re.match(timepat, t): # 是时间行 result[line - 1]['time'] = t elif len(t.strip()) > 0: # 是内容 result[line - 1]['text'] += t.strip().replace("\n", '') for it in result: if "text" in it and len(it['text'].strip()) > 0 and not re.match(r'^[,./?`!@#$%^&*()_+=\\|\[\]{}~\s \n-]*$', it['text']): it['line'] = line startraw, endraw = it['time'].strip().split(" --> ") start = startraw.replace(',', '.').split(":") start_time = int(int(start[0]) * 3600000 + int(start[1]) * 60000 + float(start[2]) * 1000) end = endraw.replace(',', '.').split(":") end_time = int(int(end[0]) * 3600000 + int(end[1]) * 60000 + float(end[2]) * 1000) it['startraw'] = startraw it['endraw'] = endraw it['start_time'] = start_time it['end_time'] = end_time new_result.append(it) line += 1 else: else: def updatecache(): # 禁止更新,避免无代理时报错 file=os.path.join(cfg.ROOT_DIR,'tts_cache/cache') if file: j=json.load(open(file,'r',encoding='utf-8')) for i,it in enumerate(j): if "time" in it and "fn" in it: cache_file=os.path.join(cfg.ROOT_DIR,f'tts_cache/{it["fn"]}') if os.path.exists(cache_file) and os.path.getsize(cache_file)>17000000: it['time']=time.time() j[i]=it json.dump(j,open(file,'w',encoding='utf-8'))
null
9,219
import hashlib import json import os import re import shutil import tempfile import threading import time import webbrowser import aiohttp import requests import torch import torchaudio from pydub import AudioSegment import clone from clone import cfg from clone.cfg import langlist from TTS.api import TTS from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts from dotenv import load_dotenv try: tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to(cfg.device) print(langlist['lang14']) cfg.tts_n=1 except aiohttp.client_exceptions.ClientOSError as e: print(f'{langlist["lang13"]}:{str(e)}') if not cfg.setorget_proxy(): print(f'.env {langlist["lang12"]}') else: print(langlist['lang11']) return except Exception as e: print(f'{langlist["lang13"]}:{str(e)}') return while 1: try: obj = cfg.q.get(block=True, timeout=1) print(f"[tts][ttsloop]start tts,{obj=}") if not os.path.exists(obj['voice']): cfg.global_tts_result[obj['filename']] = f'参考声音不存:{obj["voice"]}' continue try: tts.tts_to_file(text=obj['text'], speaker_wav=obj['voice'], language=obj['language'], file_path=os.path.join(cfg.TTS_DIR, obj['filename'])) cfg.global_tts_result[obj['filename']] = 1 print(f"[tts][ttsloop]end: {obj=}") except Exception as e: print(f"[tts][ttsloop]error:{str(e)}") cfg.global_tts_result[obj['filename']] = str(e) except Exception: continue try: tts = TTS(model_name='voice_conversion_models/multilingual/vctk/freevc24').to(cfg.device) print(langlist['lang10']) except aiohttp.client_exceptions.ClientOSError as e: print(f'{langlist["lang9"]}:{str(e)}') if not cfg.setorget_proxy(): print(f'.env {langlist["lang12"]}') else: print(f'{os.environ.get("HTTP_PROXY")} {langlist["lang11"]}') return except Exception as e: print(f'{langlist["lang9"]}:{str(e)}') return while 1: try: obj = cfg.q_sts.get(block=True, timeout=1) print(f"[sts][stsloop]start sts,{obj=}") try: #split_sentences=True tts.voice_conversion_to_file(source_wav=os.path.join(cfg.TMP_DIR, obj['filename']), target_wav=os.path.join(cfg.VOICE_DIR, obj['voice']), file_path=os.path.join(cfg.TTS_DIR, obj['filename'])) cfg.global_sts_result[obj['filename']] = 1 print(f"[sts][stsloop] end {obj=}") except Exception as e: print(f"[sts][stsloop]error:{str(e)}") cfg.global_sts_result[obj['filename']] = str(e) except Exception as e: continue text, voice, language, filename, speed=1.0 if os.path.exists(absofilename) and os.path.getsize(absofilename) > 0: print(f"[tts][create_ts]{filename} {speed} has exists") cfg.global_tts_result[filename] = 1 return {"code": 0, "filename": absofilename, 'name': filename} try: print(f"[tts][create_ts] **{text}** {voice=},{model=}") if not model or model =="default": cfg.q.put({"voice": voice, "text": text,"speed":speed, "language": language, "filename": filename}) else: #如果不存在该模型,就先启动 print(f'{model=}') if model not in cfg.MYMODEL_QUEUE or not cfg.MYMODEL_QUEUE[model]: run_tts(model) cfg.MYMODEL_QUEUE[model].put({"text": text,"speed":speed, "language": language, "filename": filename}) except Exception as e: print(e) print(f"error,{str(e)}") return {"code": 10, "msg": str(e)} if os.path.exists(absofilename): return (absofilename, "") print(f'{text_list=}') while cfg.tts_n==0: time.sleep(5) print(f"\n{langlist['lang8']} http://{web_address}" else: else: langlist = langdict[LANG] def ttsloop(): try: tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to(cfg.device) print(langlist['lang14']) cfg.tts_n=1 except aiohttp.client_exceptions.ClientOSError as e: print(f'{langlist["lang13"]}:{str(e)}') if not cfg.setorget_proxy(): print(f'.env {langlist["lang12"]}') else: print(langlist['lang11']) return except Exception as e: print(f'{langlist["lang13"]}:{str(e)}') return while 1: try: obj = cfg.q.get(block=True, timeout=1) print(f"[tts][ttsloop]start tts,{obj=}") if not os.path.exists(obj['voice']): cfg.global_tts_result[obj['filename']] = f'参考声音不存:{obj["voice"]}' continue try: tts.tts_to_file(text=obj['text'], speaker_wav=obj['voice'], language=obj['language'], file_path=os.path.join(cfg.TTS_DIR, obj['filename'])) cfg.global_tts_result[obj['filename']] = 1 print(f"[tts][ttsloop]end: {obj=}") except Exception as e: print(f"[tts][ttsloop]error:{str(e)}") cfg.global_tts_result[obj['filename']] = str(e) except Exception: continue
null
9,220
import hashlib import json import os import re import shutil import tempfile import threading import time import webbrowser import aiohttp import requests import torch import torchaudio from pydub import AudioSegment import clone from clone import cfg from clone.cfg import langlist from TTS.api import TTS from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts from dotenv import load_dotenv try: tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to(cfg.device) print(langlist['lang14']) cfg.tts_n=1 except aiohttp.client_exceptions.ClientOSError as e: print(f'{langlist["lang13"]}:{str(e)}') if not cfg.setorget_proxy(): print(f'.env {langlist["lang12"]}') else: print(langlist['lang11']) return except Exception as e: print(f'{langlist["lang13"]}:{str(e)}') return while 1: try: obj = cfg.q.get(block=True, timeout=1) print(f"[tts][ttsloop]start tts,{obj=}") if not os.path.exists(obj['voice']): cfg.global_tts_result[obj['filename']] = f'参考声音不存:{obj["voice"]}' continue try: tts.tts_to_file(text=obj['text'], speaker_wav=obj['voice'], language=obj['language'], file_path=os.path.join(cfg.TTS_DIR, obj['filename'])) cfg.global_tts_result[obj['filename']] = 1 print(f"[tts][ttsloop]end: {obj=}") except Exception as e: print(f"[tts][ttsloop]error:{str(e)}") cfg.global_tts_result[obj['filename']] = str(e) except Exception: continue try: tts = TTS(model_name='voice_conversion_models/multilingual/vctk/freevc24').to(cfg.device) print(langlist['lang10']) except aiohttp.client_exceptions.ClientOSError as e: print(f'{langlist["lang9"]}:{str(e)}') if not cfg.setorget_proxy(): print(f'.env {langlist["lang12"]}') else: print(f'{os.environ.get("HTTP_PROXY")} {langlist["lang11"]}') return except Exception as e: print(f'{langlist["lang9"]}:{str(e)}') return while 1: try: obj = cfg.q_sts.get(block=True, timeout=1) print(f"[sts][stsloop]start sts,{obj=}") try: #split_sentences=True tts.voice_conversion_to_file(source_wav=os.path.join(cfg.TMP_DIR, obj['filename']), target_wav=os.path.join(cfg.VOICE_DIR, obj['voice']), file_path=os.path.join(cfg.TTS_DIR, obj['filename'])) cfg.global_sts_result[obj['filename']] = 1 print(f"[sts][stsloop] end {obj=}") except Exception as e: print(f"[sts][stsloop]error:{str(e)}") cfg.global_sts_result[obj['filename']] = str(e) except Exception as e: continue if os.path.exists(absofilename) and os.path.getsize(absofilename) > 0: print(f"[tts][create_ts]{filename} {speed} has exists") cfg.global_tts_result[filename] = 1 return {"code": 0, "filename": absofilename, 'name': filename} try: print(f"[tts][create_ts] **{text}** {voice=},{model=}") if not model or model =="default": cfg.q.put({"voice": voice, "text": text,"speed":speed, "language": language, "filename": filename}) else: #如果不存在该模型,就先启动 print(f'{model=}') if model not in cfg.MYMODEL_QUEUE or not cfg.MYMODEL_QUEUE[model]: run_tts(model) cfg.MYMODEL_QUEUE[model].put({"text": text,"speed":speed, "language": language, "filename": filename}) except Exception as e: print(e) print(f"error,{str(e)}") return {"code": 10, "msg": str(e)} if os.path.exists(absofilename): return (absofilename, "") print(f'{text_list=}') while cfg.tts_n==0: time.sleep(5) print(f"\n{langlist['lang8']} http://{web_address}" else: else: langlist = langdict[LANG] def stsloop(): try: tts = TTS(model_name='voice_conversion_models/multilingual/vctk/freevc24').to(cfg.device) print(langlist['lang10']) except aiohttp.client_exceptions.ClientOSError as e: print(f'{langlist["lang9"]}:{str(e)}') if not cfg.setorget_proxy(): print(f'.env {langlist["lang12"]}') else: print(f'{os.environ.get("HTTP_PROXY")} {langlist["lang11"]}') return except Exception as e: print(f'{langlist["lang9"]}:{str(e)}') return while 1: try: obj = cfg.q_sts.get(block=True, timeout=1) print(f"[sts][stsloop]start sts,{obj=}") try: #split_sentences=True tts.voice_conversion_to_file(source_wav=os.path.join(cfg.TMP_DIR, obj['filename']), target_wav=os.path.join(cfg.VOICE_DIR, obj['voice']), file_path=os.path.join(cfg.TTS_DIR, obj['filename'])) cfg.global_sts_result[obj['filename']] = 1 print(f"[sts][stsloop] end {obj=}") except Exception as e: print(f"[sts][stsloop]error:{str(e)}") cfg.global_sts_result[obj['filename']] = str(e) except Exception as e: continue
null
9,221
import hashlib import json import os import re import shutil import tempfile import threading import time import webbrowser import aiohttp import requests import torch import torchaudio from pydub import AudioSegment import clone from clone import cfg from clone.cfg import langlist from TTS.api import TTS from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts from dotenv import load_dotenv try: print(f"[tts][create_ts] **{text}** {voice=},{model=}") if not model or model =="default": cfg.q.put({"voice": voice, "text": text,"speed":speed, "language": language, "filename": filename}) else: #如果不存在该模型,就先启动 print(f'{model=}') if model not in cfg.MYMODEL_QUEUE or not cfg.MYMODEL_QUEUE[model]: run_tts(model) cfg.MYMODEL_QUEUE[model].put({"text": text,"speed":speed, "language": language, "filename": filename}) except Exception as e: print(e) print(f"error,{str(e)}") return {"code": 10, "msg": str(e)} print(f'{text_list=}') while cfg.tts_n==0: time.sleep(5) webbrowser.open("http://"+web_address) print(f"\n{langlist['lang8']} http://{web_address}" else: else: langlist = langdict[LANG] def openweb(web_address): while cfg.tts_n==0: time.sleep(5) webbrowser.open("http://"+web_address) print(f"\n{langlist['lang8']} http://{web_address}")
null
9,222
import hashlib import json import os import re import shutil import tempfile import threading import time import webbrowser import aiohttp import requests import torch import torchaudio from pydub import AudioSegment import clone from clone import cfg from clone.cfg import langlist from TTS.api import TTS from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts from dotenv import load_dotenv while 1: try: obj = cfg.q.get(block=True, timeout=1) print(f"[tts][ttsloop]start tts,{obj=}") if not os.path.exists(obj['voice']): cfg.global_tts_result[obj['filename']] = f'参考声音不存:{obj["voice"]}' continue try: tts.tts_to_file(text=obj['text'], speaker_wav=obj['voice'], language=obj['language'], file_path=os.path.join(cfg.TTS_DIR, obj['filename'])) cfg.global_tts_result[obj['filename']] = 1 print(f"[tts][ttsloop]end: {obj=}") except Exception as e: print(f"[tts][ttsloop]error:{str(e)}") cfg.global_tts_result[obj['filename']] = str(e) except Exception: continue while 1: try: obj = cfg.q_sts.get(block=True, timeout=1) print(f"[sts][stsloop]start sts,{obj=}") try: #split_sentences=True tts.voice_conversion_to_file(source_wav=os.path.join(cfg.TMP_DIR, obj['filename']), target_wav=os.path.join(cfg.VOICE_DIR, obj['voice']), file_path=os.path.join(cfg.TTS_DIR, obj['filename'])) cfg.global_sts_result[obj['filename']] = 1 print(f"[sts][stsloop] end {obj=}") except Exception as e: print(f"[sts][stsloop]error:{str(e)}") cfg.global_sts_result[obj['filename']] = str(e) except Exception as e: continue for it in text_list: if "filename" in it['result'] and os.path.exists(it['result']['filename']): # 存在音频文件 seg=AudioSegment.from_wav(it['result']['filename']) if "start_time" in it: start_times.append(it['start_time']) segments.append(seg) else: merged_audio+=seg try: os.unlink(it['result']['filename']) except: pass elif "msg" in it['result']: # 出错 errors.append(str(it['result']['msg'])) for i in range(len(segments)): segment = segments[i] start_time = start_times[i] # add silence if i > 0: previous_end_time = start_times[i - 1] + len(segments[i - 1]) silence_duration = start_time - previous_end_time # 可能存在字幕 语音对应问题 if silence_duration > 0: silence = AudioSegment.silent(duration=silence_duration) merged_audio += silence merged_audio += segment t): if len(content)<1: return [] result=[] epat = r'^\s*?\d+:\d+:\d+([\,\.]\d+?)?\s*?-->\s*?\d+:\d+:\d+([\,\.]\d+?)?\s*?$' for i,it in enumerate(content): #当前空行跳过 if not it.strip(): continue it=it.strip() is_time=re.match(timepat,it) if is_time: #当前行是时间格式,则添加 result.append({"time":it,"text":[]}) elif i==0: #当前是第一行,并且不是时间格式,跳过 continue elif re.match(r'^\s*?\d+\s*?$',it) and i<maxindex and re.match(timepat,content[i+1]): #当前不是时间格式,不是第一行,并且都是数字,并且下一行是时间格式,则当前是行号,跳过 continue elif len(result)>0 and not re.match(textpat,it): #当前不是时间格式,不是第一行,(不是行号),并且result中存在数据,则是内容,可加入最后一个数据 result[-1]['text'].append(it) it in result if len(it['text'])>0] if len(result)>0: for i,it in enumerate(result): result[i]['line']=i+1 result[i]['text']="\n".join(it['text']) s,e=(it['time'].replace('.',',')).split('-->') s=s.strip() e=e.strip() if s.find(',')==-1: s+=',000' if len(s.split(':')[0])<2: s=f'0{s}' if e.find(',')==-1: e+=',000' if len(e.split(':')[0])<2: e=f'0{e}' result[i]['time']=f'{s} --> {e}' return resul timepat = r'^\s*?\d+:\d+:\d+(\,\d+?)?\s*?-->\s*?\d+:\d+:\d+(\,\d+?)?\s*?$' if not re.search(timepat,srtfile,re.I|re.M): return None if len(content)<1: return None result=format_srt(content) if len(result)<1: return None new_result = [] line = 1 for it in result: if "text" in it and len(it['text'].strip()) > 0: it['line'] = line startraw, endraw = it['time'].strip().split("-->") start = startraw.strip().replace(',', '.').replace(',','.').replace(':',':').split(":") end = endraw.strip().replace(',', '.').replace(',','.').replace(':',':').split(":") start_time = int(int(start[0]) * 3600000 + int(start[1]) * 60000 + float(start[2]) * 1000) end_time = int(int(end[0]) * 3600000 + int(end[1]) * 60000 + float(end[2]) * 1000) it['startraw'] = startraw it['endraw'] = endraw it['start_time'] = start_time it['end_time'] = end_time new_result.append(it) line += 1 return new_resul line = 0 maxline = len(txt) inepat = r'^\s*?\d+\s*?$' epat = r'^\s*?\d+:\d+:\d+\,?\d*?\s*?-->\s*?\d+:\d+:\d+\,?\d*?$' return None if not re.match(linepat, txt[0]) or not re.match(timepat, txt[1]): return None result = [] for i, t in enumerate(txt): # 当前行 小于等于倒数第三行 并且匹配行号,并且下一行匹配时间戳,则是行号 if i < maxline - 2 and re.match(linepat, t) and re.match(timepat, txt[i + 1]): # 是行 line += 1 obj = {"line": line, "time": "", "text": ""} result.append(obj) elif re.match(timepat, t): # 是时间行 result[line - 1]['time'] = t elif len(t.strip()) > 0: # 是内容 result[line - 1]['text'] += t.strip().replace("\n", '') line = 1 for it in result: if "text" in it and len(it['text'].strip()) > 0 and not re.match(r'^[,./?`!@#$%^&*()_+=\\|\[\]{}~\s \n-]*$', it['text']): it['line'] = line startraw, endraw = it['time'].strip().split(" --> ") start = startraw.replace(',', '.').split(":") start_time = int(int(start[0]) * 3600000 + int(start[1]) * 60000 + float(start[2]) * 1000) end = endraw.replace(',', '.').split(":") end_time = int(int(end[0]) * 3600000 + int(end[1]) * 60000 + float(end[2]) * 1000) it['startraw'] = startraw it['endraw'] = endraw it['start_time'] = start_time it['end_time'] = end_time new_result.append(it) line += 1 return new_resul def get_subtitle_from_srt0(txt): # 行号 line = 0 maxline = len(txt) # 行格式 linepat = r'^\s*?\d+\s*?$' # 时间格式 timepat = r'^\s*?\d+:\d+:\d+\,?\d*?\s*?-->\s*?\d+:\d+:\d+\,?\d*?$' txt = txt.strip().split("\n") # 先判断是否符合srt格式,不符合返回None if len(txt) < 3: return None if not re.match(linepat, txt[0]) or not re.match(timepat, txt[1]): return None result = [] for i, t in enumerate(txt): # 当前行 小于等于倒数第三行 并且匹配行号,并且下一行匹配时间戳,则是行号 if i < maxline - 2 and re.match(linepat, t) and re.match(timepat, txt[i + 1]): # 是行 line += 1 obj = {"line": line, "time": "", "text": ""} result.append(obj) elif re.match(timepat, t): # 是时间行 result[line - 1]['time'] = t elif len(t.strip()) > 0: # 是内容 result[line - 1]['text'] += t.strip().replace("\n", '') # 再次遍历,删掉美元text的行 new_result = [] line = 1 for it in result: if "text" in it and len(it['text'].strip()) > 0 and not re.match(r'^[,./?`!@#$%^&*()_+=\\|\[\]{}~\s \n-]*$', it['text']): it['line'] = line startraw, endraw = it['time'].strip().split(" --> ") start = startraw.replace(',', '.').split(":") start_time = int(int(start[0]) * 3600000 + int(start[1]) * 60000 + float(start[2]) * 1000) end = endraw.replace(',', '.').split(":") end_time = int(int(end[0]) * 3600000 + int(end[1]) * 60000 + float(end[2]) * 1000) it['startraw'] = startraw it['endraw'] = endraw it['start_time'] = start_time it['end_time'] = end_time new_result.append(it) line += 1 return new_result
null
9,223
import hashlib import json import os import re import shutil import tempfile import threading import time import webbrowser import aiohttp import requests import torch import torchaudio from pydub import AudioSegment import clone from clone import cfg from clone.cfg import langlist from TTS.api import TTS from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts from dotenv import load_dotenv try: print(f"[tts][create_ts] **{text}** {voice=},{model=}") if not model or model =="default": cfg.q.put({"voice": voice, "text": text,"speed":speed, "language": language, "filename": filename}) else: #如果不存在该模型,就先启动 print(f'{model=}') if model not in cfg.MYMODEL_QUEUE or not cfg.MYMODEL_QUEUE[model]: run_tts(model) cfg.MYMODEL_QUEUE[model].put({"text": text,"speed":speed, "language": language, "filename": filename}) except Exception as e: print(e) print(f"error,{str(e)}") return {"code": 10, "msg": str(e)} print(f'{text_list=}') while cfg.tts_n==0: time.sleep(5) print(f"\n{langlist['lang8']} http://{web_address}" else: else: def checkupdate(): try: res=requests.get("https://raw.githubusercontent.com/jianchang512/clone-voice/main/version.json") print(f"{res.status_code=}") if res.status_code==200: d=res.json() print(f"{d=}") if d['version_num']>clone.VERSION: cfg.updatetips=f'New version {d["version"]}' except Exception as e: pass
null
9,224
import locale import os import queue import re import sys import threading import torch from dotenv import load_dotenv os.environ['TTS_HOME'] = ROOT_DIR if os.path.exists(os.path.join(ROOT_DIR, "tts/tts_models--multilingual--multi-dataset--xtts_v2/model.pth")): if not os.path.exists(VOICE_DIR): os.makedirs(VOICE_DIR) if not os.path.exists(TTS_DIR): os.makedirs(TTS_DIR) if not os.path.exists(TMP_DIR): os.makedirs(TMP_DIR objs={} if not os.path.exists(path): return {} dirs=os.listdir(path) if len(dirs)<1: return {} for it in dirs: if re.match(r'^[0-9a-zA-Z_-]+$',it) and os.path.exists(os.path.join(path,it,'model.pth')): objs[it]=None return obj def get_models(path): objs={} if not os.path.exists(path): return {} dirs=os.listdir(path) if len(dirs)<1: return {} for it in dirs: if re.match(r'^[0-9a-zA-Z_-]+$',it) and os.path.exists(os.path.join(path,it,'model.pth')): objs[it]=None return objs
null
9,225
import torch import os rootdir=os.getcwd() os.environ['TTS_HOME']=rootdir from TTS.api import TTS from dotenv import load_dotenv def updatecache(): # 禁止更新,避免无代理时报错 file=os.path.join(rootdir,'tts_cache/cache') if file: import json,time j=json.load(open(file,'r',encoding='utf-8')) for i,it in enumerate(j): if "time" in it and "fn" in it: cache_file=os.path.join(rootdir,f'tts_cache/{it["fn"]}') if os.path.exists(cache_file) and os.path.getsize(cache_file)>17000000: it['time']=time.time() j[i]=it json.dump(j,open(file,'w',encoding='utf-8'))
null
9,226
import os import gc import torchaudio import pandas from faster_whisper import WhisperModel from glob import glob from tqdm import tqdm import torch import torchaudio from TTS.tts.layers.xtts.tokenizer import multilingual_cleaners import os from .cfg import FASTERMODEL_DIR,ZH_PROMPT audio_types = (".wav", ".mp3", ".flac") def list_files(basePath, validExts=None, contains=None): # loop over the directory structure for (rootDir, dirNames, filenames) in os.walk(basePath): # loop over the filenames in the current directory for filename in filenames: # if the contains string is not none and the filename does not contain # the supplied string, then ignore the file if contains is not None and filename.find(contains) == -1: continue # determine the file extension of the current file ext = filename[filename.rfind("."):].lower() # check to see if the file is an audio and should be processed if validExts is None or ext.endswith(validExts): # construct the path to the audio and yield it audioPath = os.path.join(rootDir, filename) yield audioPath def list_audios(basePath, contains=None): # return the set of files that are valid return list_files(basePath, validExts=audio_types, contains=contains)
null
9,227
from setuptools import find_packages import subprocess from difflib import get_close_matches from glob import glob import os import platform from distutils.core import setup, Extension from pathlib import Path def find_pkg_dirs(package): close_matches = get_close_matches(package.lower(), os.environ["PATH"].lower().split(';'), cutoff=0) dll_dir = None for close_match in close_matches: if (os.path.exists(close_match) and glob(os.path.join(close_match, '*.dll'))): dll_dir = close_match break if dll_dir is None: raise Exception( f"Could not find required package: {package}. " "Add directory containing .dll files to system environment path." ) dll_dir_split = dll_dir.replace('\\', '/').split('/') root = get_close_matches(package.lower(), dll_dir_split, cutoff=0)[0] root_dir = '/'.join(dll_dir_split[:dll_dir_split.index(root) + 1]) return os.path.normpath(root_dir), os.path.normpath(dll_dir) if platform.system() == 'Windows': extension_kwargs = pkgconfig_windows('opencv4', extension_kwargs) extension_kwargs = pkgconfig_windows('libturbojpeg', extension_kwargs) extension_kwargs = pkgconfig_windows('pthread', extension_kwargs) else: try: extension_kwargs = pkgconfig('opencv4', extension_kwargs) except RuntimeError: extension_kwargs = pkgconfig('opencv', extension_kwargs) extension_kwargs = pkgconfig('libturbojpeg', extension_kwargs) extension_kwargs['libraries'].append('pthread') def pkgconfig_windows(package, kw): is_x64 = platform.machine().endswith('64') root_dir, dll_dir = find_pkg_dirs(package) include_dir = None library_dir = None parent = None while parent != root_dir: parent = os.path.dirname(dll_dir if parent is None else parent) if include_dir is None and os.path.exists(os.path.join(parent, 'include')): include_dir = os.path.join(parent, 'include') library_dirs = set() libraries = glob(os.path.join(parent, '**', 'lib', '**', '*.lib'), recursive=True) for library in libraries: if ((is_x64 and 'x86' in library) or (not is_x64 and 'x64' in library)): continue library_dirs.add(os.path.dirname(library)) if library_dir is None and library_dirs: library_dir = sorted(library_dirs)[-1] if include_dir and library_dir: libraries = [os.path.splitext(library)[0] for library in glob(os.path.join(library_dir, '*.lib'))] break if not include_dir or not library_dir: raise Exception(f"Could not find required package: {package}.") kw.setdefault('include_dirs', []).append(include_dir) kw.setdefault('library_dirs', []).append(library_dir) kw.setdefault('libraries', []).extend(libraries) return kw
null
9,228
from setuptools import find_packages import subprocess from difflib import get_close_matches from glob import glob import os import platform from distutils.core import setup, Extension from pathlib import Path def pkgconfig(package, kw): flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'} output = subprocess.getoutput( 'pkg-config --cflags --libs {}'.format(package)) if 'not found' in output: raise RuntimeError(f"Could not find required package: {package}.") for token in output.strip().split(): kw.setdefault(flag_map.get(token[:2]), []).append(token[2:]) return kw
null
9,229
from argparse import ArgumentParser from typing import List import time import numpy as np from tqdm import tqdm import torch as ch from torch.cuda.amp import GradScaler, autocast from torch.nn import CrossEntropyLoss, Conv2d, BatchNorm2d from torch.optim import SGD, lr_scheduler import torchvision from fastargs import get_current_config, Param, Section from fastargs.decorators import param from fastargs.validation import And, OneOf from ffcv.fields import IntField, RGBImageField from ffcv.fields.decoders import IntDecoder, SimpleRGBImageDecoder from ffcv.loader import Loader, OrderOption from ffcv.pipeline.operation import Operation from ffcv.transforms import RandomHorizontalFlip, Cutout, \ RandomTranslate, Convert, ToDevice, ToTensor, ToTorchImage from ffcv.transforms.common import Squeeze from ffcv.writer import DatasetWriter class Operation(ABC): def __init__(self): self.metadata: np.ndarray = None self.memory_read: Callable[[np.uint64], np.ndarray] = None pass def accept_field(self, field: 'Field'): self.field: 'Field' = field def accept_globals(self, metadata, memory_read): self.metadata = metadata self.memory_read = memory_read # Return the code to run this operation def generate_code(self) -> Callable: raise NotImplementedError def declare_shared_memory(self, previous_state: State) -> Optional[AllocationQuery]: return None def generate_code_for_shared_state(self) -> Optional[Callable]: return None def declare_state_and_memory(self, previous_state: State) -> Tuple[State, Optional[AllocationQuery]]: raise NotImplementedError class Squeeze(Operation): """Remove given dimensions of input of size 1. Operates on tensors. Parameters ---------- *dims : List[int] Dimensions to squeeze. """ def __init__(self, *dims): super().__init__() self.dims = dims def generate_code(self) -> Callable: def squeeze(inp, _): inp.squeeze_(*self.dims) return inp return squeeze def declare_state_and_memory(self, previous_state: State) -> Tuple[State, Optional[AllocationQuery]]: return replace(previous_state, shape=[x for x in previous_state.shape if not x == 1]), None def make_dataloaders(train_dataset=None, val_dataset=None, batch_size=None, num_workers=None): paths = { 'train': train_dataset, 'test': val_dataset } start_time = time.time() CIFAR_MEAN = [125.307, 122.961, 113.8575] CIFAR_STD = [51.5865, 50.847, 51.255] loaders = {} for name in ['train', 'test']: label_pipeline: List[Operation] = [IntDecoder(), ToTensor(), ToDevice(ch.device('cuda:0')), Squeeze()] image_pipeline: List[Operation] = [SimpleRGBImageDecoder()] if name == 'train': image_pipeline.extend([ RandomHorizontalFlip(), RandomTranslate(padding=2, fill=tuple(map(int, CIFAR_MEAN))), Cutout(4, tuple(map(int, CIFAR_MEAN))), ]) image_pipeline.extend([ ToTensor(), ToDevice(ch.device('cuda:0'), non_blocking=True), ToTorchImage(), Convert(ch.float16), torchvision.transforms.Normalize(CIFAR_MEAN, CIFAR_STD), ]) ordering = OrderOption.RANDOM if name == 'train' else OrderOption.SEQUENTIAL loaders[name] = Loader(paths[name], batch_size=batch_size, num_workers=num_workers, order=ordering, drop_last=(name == 'train'), pipelines={'image': image_pipeline, 'label': label_pipeline}) return loaders, start_time
null
9,230
from argparse import ArgumentParser from typing import List import time import numpy as np from tqdm import tqdm import torch as ch from torch.cuda.amp import GradScaler, autocast from torch.nn import CrossEntropyLoss, Conv2d, BatchNorm2d from torch.optim import SGD, lr_scheduler import torchvision from fastargs import get_current_config, Param, Section from fastargs.decorators import param from fastargs.validation import And, OneOf from ffcv.fields import IntField, RGBImageField from ffcv.fields.decoders import IntDecoder, SimpleRGBImageDecoder from ffcv.loader import Loader, OrderOption from ffcv.pipeline.operation import Operation from ffcv.transforms import RandomHorizontalFlip, Cutout, \ RandomTranslate, Convert, ToDevice, ToTensor, ToTorchImage from ffcv.transforms.common import Squeeze from ffcv.writer import DatasetWriter class Mul(ch.nn.Module): def __init__(self, weight): super(Mul, self).__init__() self.weight = weight def forward(self, x): return x * self.weight class Flatten(ch.nn.Module): def forward(self, x): return x.view(x.size(0), -1) class Residual(ch.nn.Module): def __init__(self, module): super(Residual, self).__init__() self.module = module def forward(self, x): return x + self.module(x) def conv_bn(channels_in, channels_out, kernel_size=3, stride=1, padding=1, groups=1): return ch.nn.Sequential( ch.nn.Conv2d(channels_in, channels_out, kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, bias=False), ch.nn.BatchNorm2d(channels_out), ch.nn.ReLU(inplace=True) ) def construct_model(): num_class = 10 model = ch.nn.Sequential( conv_bn(3, 64, kernel_size=3, stride=1, padding=1), conv_bn(64, 128, kernel_size=5, stride=2, padding=2), Residual(ch.nn.Sequential(conv_bn(128, 128), conv_bn(128, 128))), conv_bn(128, 256, kernel_size=3, stride=1, padding=1), ch.nn.MaxPool2d(2), Residual(ch.nn.Sequential(conv_bn(256, 256), conv_bn(256, 256))), conv_bn(256, 128, kernel_size=3, stride=1, padding=0), ch.nn.AdaptiveMaxPool2d((1, 1)), Flatten(), ch.nn.Linear(128, num_class, bias=False), Mul(0.2) ) model = model.to(memory_format=ch.channels_last).cuda() return model
null
9,231
from argparse import ArgumentParser from typing import List import time import numpy as np from tqdm import tqdm import torch as ch from torch.cuda.amp import GradScaler, autocast from torch.nn import CrossEntropyLoss, Conv2d, BatchNorm2d from torch.optim import SGD, lr_scheduler import torchvision from fastargs import get_current_config, Param, Section from fastargs.decorators import param from fastargs.validation import And, OneOf from ffcv.fields import IntField, RGBImageField from ffcv.fields.decoders import IntDecoder, SimpleRGBImageDecoder from ffcv.loader import Loader, OrderOption from ffcv.pipeline.operation import Operation from ffcv.transforms import RandomHorizontalFlip, Cutout, \ RandomTranslate, Convert, ToDevice, ToTensor, ToTorchImage from ffcv.transforms.common import Squeeze from ffcv.writer import DatasetWriter def train(model, loaders, lr=None, epochs=None, label_smoothing=None, momentum=None, weight_decay=None, lr_peak_epoch=None): opt = SGD(model.parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay) iters_per_epoch = len(loaders['train']) # Cyclic LR with single triangle lr_schedule = np.interp(np.arange((epochs+1) * iters_per_epoch), [0, lr_peak_epoch * iters_per_epoch, epochs * iters_per_epoch], [0, 1, 0]) scheduler = lr_scheduler.LambdaLR(opt, lr_schedule.__getitem__) scaler = GradScaler() loss_fn = CrossEntropyLoss(label_smoothing=label_smoothing) for _ in range(epochs): for ims, labs in tqdm(loaders['train']): opt.zero_grad(set_to_none=True) with autocast(): out = model(ims) loss = loss_fn(out, labs) scaler.scale(loss).backward() scaler.step(opt) scaler.update() scheduler.step()
null
9,232
from argparse import ArgumentParser from typing import List import time import numpy as np from tqdm import tqdm import torch as ch from torch.cuda.amp import GradScaler, autocast from torch.nn import CrossEntropyLoss, Conv2d, BatchNorm2d from torch.optim import SGD, lr_scheduler import torchvision from fastargs import get_current_config, Param, Section from fastargs.decorators import param from fastargs.validation import And, OneOf from ffcv.fields import IntField, RGBImageField from ffcv.fields.decoders import IntDecoder, SimpleRGBImageDecoder from ffcv.loader import Loader, OrderOption from ffcv.pipeline.operation import Operation from ffcv.transforms import RandomHorizontalFlip, Cutout, \ RandomTranslate, Convert, ToDevice, ToTensor, ToTorchImage from ffcv.transforms.common import Squeeze from ffcv.writer import DatasetWriter def evaluate(model, loaders, lr_tta=False): model.eval() with ch.no_grad(): for name in ['train', 'test']: total_correct, total_num = 0., 0. for ims, labs in tqdm(loaders[name]): with autocast(): out = model(ims) if lr_tta: out += model(ims.flip(-1)) total_correct += out.argmax(1).eq(labs).sum().cpu().item() total_num += ims.shape[0] print(f'{name} accuracy: {total_correct / total_num * 100:.1f}%')
null
9,233
from tqdm import tqdm import time import numpy as np import pickle as pkl import torch as ch from torch.utils.data import TensorDataset, DataLoader from ffcv.fields import NDArrayField, FloatField from ffcv.fields.basics import FloatDecoder from ffcv.fields.decoders import NDArrayDecoder from ffcv.loader import Loader, OrderOption from ffcv.writer import DatasetWriter from ffcv.transforms import ToTensor, ToDevice, Squeeze import os mean, stdev = calculate_stats(train_loader, N) mean, stdev = mean.cuda(), stdev.cuda() for _ in range(num_epochs): total_loss, num_examples = 0., 0. start_time = time.time() for (x_batch, y_batch) in tqdm(train_loader): if not USE_FFCV: x_batch = x_batch.cuda() y_batch = y_batch.cuda() # Normalize the data for stability x_batch = (x_batch - mean) / stdev residual = x_batch @ w_est + b_est - y_batch # Gradients w_grad = x_batch.T @ residual / x_batch.shape[0] b_grad = ch.mean(residual, dim=0) w_est = w_est - lr * w_grad b_est = b_est - lr * b_grad total_loss += residual.pow(2).sum() num_examples += x_batch.shape[0] print('Epoch time:', time.time() - start_time) print(f'Average loss: {total_loss / num_examples:.3f}') def calculate_stats(loader, N): mean, stdev = 0., 0. for x_batch, _ in tqdm(loader): mean += x_batch.sum(0) / N stdev += x_batch.pow(2).sum(0) / N return mean, ch.sqrt(stdev - mean.pow(2))
null
9,234
from functools import partial from typing import Callable, List, Mapping from os import SEEK_END, path import numpy as np from time import sleep import ctypes from multiprocessing import (shared_memory, cpu_count, Queue, Process, Value) from tqdm import tqdm from tqdm.contrib.concurrent import thread_map from .utils import chunks, is_power_of_2 from .fields.base import Field from .memory_allocator import MemoryAllocator from .types import (TYPE_ID_HANDLER, get_metadata_type, HeaderType, FieldDescType, CURRENT_VERSION, ALLOC_TABLE_TYPE) def from_shard(shard, pipeline): # We import webdataset here so that it desn't crash if it's not required # (Webdataset is an optional depdency) from webdataset import WebDataset dataset = WebDataset(shard) dataset = pipeline(dataset) return dataset def count_samples_in_shard(shard, pipeline): # # We count the length of the dataset # We are not using __len__ since it might not be implemented count = 0 for _ in from_shard(shard, pipeline): count += 1 return count
null
9,235
from functools import partial from typing import Callable, List, Mapping from os import SEEK_END, path import numpy as np from time import sleep import ctypes from multiprocessing import (shared_memory, cpu_count, Queue, Process, Value) from tqdm import tqdm from tqdm.contrib.concurrent import thread_map from .utils import chunks, is_power_of_2 from .fields.base import Field from .memory_allocator import MemoryAllocator from .types import (TYPE_ID_HANDLER, get_metadata_type, HeaderType, FieldDescType, CURRENT_VERSION, ALLOC_TABLE_TYPE) def from_shard(shard, pipeline): # We import webdataset here so that it desn't crash if it's not required # (Webdataset is an optional depdency) from webdataset import WebDataset dataset = WebDataset(shard) dataset = pipeline(dataset) return dataset def handle_sample(sample, dest_ix, field_names, metadata, allocator, fields): # We should only have to retry at least one for i in range(2): try: allocator.set_current_sample(dest_ix) # We extract the sample in question from the dataset # We write each field individually to the metadata region for field_name, field, field_value in zip(field_names, fields.values(), sample): destination = metadata[field_name][dest_ix: dest_ix + 1] field.encode(destination, field_value, allocator.malloc) # We managed to write all the data without reaching # the end of the page so we stop retrying break # If we couldn't fit this sample in the previous page we retry once from a fresh page except MemoryError: # We raise the error if it happens on the second try if i == 1: raise def worker_job_webdataset(input_queue, metadata_sm, metadata_type, fields, allocator, done_number, allocations_queue, pipeline): metadata = np.frombuffer(metadata_sm.buf, dtype=metadata_type) field_names = metadata_type.names # This `with` block ensures that all the pages allocated have been written # onto the file with allocator: while True: todo = input_queue.get() if todo is None: # No more work left to do break shard, offset = todo # For each sample in the chunk done = 0 for i, sample in enumerate(from_shard(shard, pipeline)): done += 1 dest_ix = offset + i handle_sample(sample, dest_ix, field_names, metadata, allocator, fields) # We warn the main thread of our progress with done_number.get_lock(): done_number.value += done allocations_queue.put(allocator.allocations)
null
9,236
from functools import partial from typing import Callable, List, Mapping from os import SEEK_END, path import numpy as np from time import sleep import ctypes from multiprocessing import (shared_memory, cpu_count, Queue, Process, Value) from tqdm import tqdm from tqdm.contrib.concurrent import thread_map from .utils import chunks, is_power_of_2 from .fields.base import Field from .memory_allocator import MemoryAllocator from .types import (TYPE_ID_HANDLER, get_metadata_type, HeaderType, FieldDescType, CURRENT_VERSION, ALLOC_TABLE_TYPE) def handle_sample(sample, dest_ix, field_names, metadata, allocator, fields): # We should only have to retry at least one for i in range(2): try: allocator.set_current_sample(dest_ix) # We extract the sample in question from the dataset # We write each field individually to the metadata region for field_name, field, field_value in zip(field_names, fields.values(), sample): destination = metadata[field_name][dest_ix: dest_ix + 1] field.encode(destination, field_value, allocator.malloc) # We managed to write all the data without reaching # the end of the page so we stop retrying break # If we couldn't fit this sample in the previous page we retry once from a fresh page except MemoryError: # We raise the error if it happens on the second try if i == 1: raise def worker_job_indexed_dataset(input_queue, metadata_sm, metadata_type, fields, allocator, done_number, allocations_queue, dataset): metadata = np.frombuffer(metadata_sm.buf, dtype=metadata_type) field_names = metadata_type.names # This `with` block ensures that all the pages allocated have been written # onto the file with allocator: while True: chunk = input_queue.get() if chunk is None: # No more work left to do break # For each sample in the chunk for dest_ix, source_ix in chunk: sample = dataset[source_ix] handle_sample(sample, dest_ix, field_names, metadata, allocator, fields) # We warn the main thread of our progress with done_number.get_lock(): done_number.value += len(chunk) allocations_queue.put(allocator.allocations)
null
9,237
import numpy as np from numba import types from numba.extending import intrinsic from threading import Lock def chunks(lst, n): for i in range(0, len(lst), n): yield lst[i:i + n]
null
9,238
import numpy as np from numba import types from numba.extending import intrinsic from threading import Lock def is_power_of_2(n): return (n & (n-1) == 0) and n != 0
null
9,239
import numpy as np from numba import types from numba.extending import intrinsic from threading import Lock def align_to_page(ptr, page_size): # If we are not aligned with the start of a page: if ptr % page_size != 0: ptr = ptr + page_size - ptr % page_size return ptr
null
9,240
import numpy as np from numba import types from numba.extending import intrinsic from threading import Lock def decode_null_terminated_string(bytes: np.ndarray): return bytes.tobytes().decode('ascii').split('\x00')[0]
null
9,241
import numpy as np from numba import types from numba.extending import intrinsic from threading import Lock def cast_int_to_byte_ptr(typingctx, src): # check for accepted types if isinstance(src, types.Integer): # create the expected type signature result_type = types.CPointer(types.uint8) sig = result_type(types.uintp) # defines the custom code generation def codegen(context, builder, signature, args): # llvm IRBuilder code here [src] = args rtype = signature.return_type llrtype = context.get_value_type(rtype) return builder.inttoptr(src, llrtype) return sig, codegen
null
9,242
import numpy as np from numba import types from numba.extending import intrinsic from threading import Lock s_print_lock = Lock() The provided code snippet includes necessary dependencies for implementing the `s_print` function. Write a Python function `def s_print(*a, **b)` to solve the following problem: Thread safe print function Here is the function: def s_print(*a, **b): """Thread safe print function""" with s_print_lock: print(*a, **b)
Thread safe print function
9,243
import random from typing import Sequence, TYPE_CHECKING from numba import njit import numpy as np from torch.utils.data import DistributedSampler from .base import TraversalOrder def generate_order_inner(seed, page_to_samples_array, page_sizes, result, buffer_size=6): num_pages = len(page_sizes) random.seed(seed) np.random.seed(seed) current_pages = [0] current_pages.remove(0) # Force the type for page_ix in range(num_pages): page_size = page_sizes[page_ix] random.shuffle(page_to_samples_array[page_ix, :page_size]) next_page = 0 page_order = np.random.permutation(num_pages) samples_consumed = np.zeros_like(page_sizes) for s_ix in range(result.shape[0]): while next_page < num_pages and len(current_pages) < buffer_size: page_to_add = page_order[next_page] if page_sizes[page_to_add] > 0: current_pages.append(page_order[next_page]) next_page += 1 selected_page_ix = np.random.randint(0, len(current_pages)) page = current_pages[selected_page_ix] result[s_ix] = page_to_samples_array[page, samples_consumed[page]] samples_consumed[page] += 1 if samples_consumed[page] >= page_sizes[page]: current_pages.remove(page)
null
9,244
from typing import List import numpy as np from .fields.base import Field from .fields import ( FloatField, IntField, RGBImageField, BytesField, NDArrayField, JSONField, TorchTensorField ) TYPE_ID_HANDLER = { 255 : None, 0 : FloatField, 1 : IntField, 2 : RGBImageField, 3 : BytesField, 4 : NDArrayField, 5 : JSONField, 6 : TorchTensorField } def get_handlers(field_descriptors): handlers = [] for field_descriptor in field_descriptors: type_id = field_descriptor['type_id'] Handler = TYPE_ID_HANDLER[type_id] if Handler is None: handlers.append(None) else: handlers.append(Handler.from_binary(field_descriptor['arguments'])) return handlers
null
9,245
from typing import List import numpy as np from .fields.base import Field from .fields import ( FloatField, IntField, RGBImageField, BytesField, NDArrayField, JSONField, TorchTensorField ) class Field(ABC): """ Abstract Base Class for implementing fields (e.g., images, integers). Each dataset entry is comprised of one or more fields (for example, standard object detection datasets may have one field for images, and one for bounding boxes). Fields are responsible for implementing encode and get_decoder_class functions that determine how they will be written and read from the dataset file, respectively. .. note :: It is possible to have multiple potential decoder for a given Field. ``RGBImageField`` one example. Users can specify which decoder to use in the ``piplines`` argument of the ``Loader`` class. See :ref:`here <TODO>` for information on how to implement a subclass of Field. """ def metadata_type(self) -> np.dtype: raise NotImplemented def from_binary(binary: ARG_TYPE) -> Field: raise NotImplementedError def to_binary(self) -> ARG_TYPE: raise NotImplementedError def encode(field, metadata_destination, malloc): raise NotImplementedError def get_decoder_class(self) -> Type[Operation]: raise NotImplementedError def get_metadata_type(handlers: List[Field]) -> np.dtype: return np.dtype([('', handler.metadata_type) for handler in handlers], align=True)
null
9,246
from itertools import product from time import time from collections import defaultdict from contextlib import redirect_stderr import pathlib import numpy as np from tqdm import tqdm from .benchmark import Benchmark ALL_SUITES = {} def benchmark(arg_values={}): args_list = product(*arg_values.values()) runs = [dict(zip(arg_values.keys(), x)) for x in args_list] def wrapper(cls): ALL_SUITES[cls.__name__] = (cls, runs) return wrapper class Benchmark(AbstractContextManager, metaclass=ABCMeta): def __init__(self, **kwargs): pass def run(self): raise NotImplemented() def run_all(runs=3, warm_up=1, pattern='*'): results = defaultdict(list) selected_suites = {} for sname in ALL_SUITES.keys(): if pathlib.PurePath(sname).match(pattern): selected_suites[sname] = ALL_SUITES[sname] it_suite = tqdm(selected_suites.items(), desc='Suite', leave=False) for suite_name, (cls, args_list) in it_suite: it_suite.set_postfix({'name': suite_name}) it_args = tqdm(args_list, desc='configuration', leave=False) for args in it_args: # with redirect_stderr(FakeSink()): if True: benchmark: Benchmark = cls(**args) with benchmark: for _ in range(warm_up): benchmark.run() timings = [] for _ in range(runs): start = time() benchmark.run() timings.append(time() - start) median_time = np.median(timings) throughput = None if 'n' in args: throughput = args['n'] / median_time unit = 'it/sec' if throughput < 1: unit = 'sec/it' throughput = 1 /throughput throughput = np.round(throughput * 10) / 10 results[suite_name].append({ **args, 'time': median_time, 'throughput': str(throughput) + ' ' + unit }) it_args.close() it_suite.close() return results
null
9,247
from abc import ABCMeta, abstractmethod from dataclasses import replace from typing import Optional, Callable, TYPE_CHECKING, Tuple, Type import cv2 import numpy as np from numba.typed import Dict from PIL.Image import Image from .base import Field, ARG_TYPE from ..pipeline.operation import Operation from ..pipeline.state import State from ..pipeline.compiler import Compiler from ..pipeline.allocation_query import AllocationQuery from ..libffcv import imdecode, memcpy, resize_crop def encode_jpeg(numpy_image, quality): numpy_image = cv2.cvtColor(numpy_image, cv2.COLOR_RGB2BGR) success, result = cv2.imencode('.jpg', numpy_image, [int(cv2.IMWRITE_JPEG_QUALITY), quality]) if not success: raise ValueError("Impossible to encode image in jpeg") return result.reshape(-1)
null
9,248
from abc import ABCMeta, abstractmethod from dataclasses import replace from typing import Optional, Callable, TYPE_CHECKING, Tuple, Type import cv2 import numpy as np from numba.typed import Dict from PIL.Image import Image from .base import Field, ARG_TYPE from ..pipeline.operation import Operation from ..pipeline.state import State from ..pipeline.compiler import Compiler from ..pipeline.allocation_query import AllocationQuery from ..libffcv import imdecode, memcpy, resize_crop def resizer(image, target_resolution): if target_resolution is None: return image original_size = np.array([image.shape[1], image.shape[0]]) ratio = target_resolution / original_size.max() if ratio < 1: new_size = (ratio * original_size).astype(int) image = cv2.resize(image, tuple(new_size), interpolation=cv2.INTER_AREA) return image
null
9,249
from abc import ABCMeta, abstractmethod from dataclasses import replace from typing import Optional, Callable, TYPE_CHECKING, Tuple, Type import cv2 import numpy as np from numba.typed import Dict from PIL.Image import Image from .base import Field, ARG_TYPE from ..pipeline.operation import Operation from ..pipeline.state import State from ..pipeline.compiler import Compiler from ..pipeline.allocation_query import AllocationQuery from ..libffcv import imdecode, memcpy, resize_crop def get_random_crop(height, width, scale, ratio): area = height * width log_ratio = np.log(ratio) for _ in range(10): target_area = area * np.random.uniform(scale[0], scale[1]) aspect_ratio = np.exp(np.random.uniform(log_ratio[0], log_ratio[1])) w = int(round(np.sqrt(target_area * aspect_ratio))) h = int(round(np.sqrt(target_area / aspect_ratio))) if 0 < w <= width and 0 < h <= height: i = int(np.random.uniform(0, height - h + 1)) j = int(np.random.uniform(0, width - w + 1)) return i, j, h, w in_ratio = float(width) / float(height) if in_ratio < min(ratio): w = width h = int(round(w / min(ratio))) elif in_ratio > max(ratio): h = height w = int(round(h * max(ratio))) else: w = width h = height i = (height - h) // 2 j = (width - w) // 2 return i, j, h, w
null
9,250
from abc import ABCMeta, abstractmethod from dataclasses import replace from typing import Optional, Callable, TYPE_CHECKING, Tuple, Type import cv2 import numpy as np from numba.typed import Dict from PIL.Image import Image from .base import Field, ARG_TYPE from ..pipeline.operation import Operation from ..pipeline.state import State from ..pipeline.compiler import Compiler from ..pipeline.allocation_query import AllocationQuery from ..libffcv import imdecode, memcpy, resize_crop def get_center_crop(height, width, _, ratio): s = min(height, width) c = int(ratio * s) delta_h = (height - c) // 2 delta_w = (width - c) // 2 return delta_h, delta_w, c, c
null
9,251
from collections import defaultdict from dataclasses import dataclass from typing import Mapping from queue import Queue import numpy as np from .page_reader import PageReader class Schedule: # Number of slots needed num_slots: int # Which slot to use for each page page_to_slot: Mapping[int, int] # First iteration a page can be loaded can_prefetch_at: Mapping[int, int] # Iteration at which a page *has* to be loaded entering_at: Mapping[int, int] # Iteration at which we can discard a page leaving_at: Mapping[int, int] def compute_schedule(pages_in_batch, prefetch_ahead = 3): # We determine what is the early and latest times we will need a page page_end = {} page_start = {} for b_id, pages in enumerate(pages_in_batch): for page in pages: page_end[page] = b_id if page not in page_start: page_start[page] = b_id # We determine which pages are # - Can be preloaded # - Are needed # - Can be diposed of # At a given batch entering_at = defaultdict(set) can_prefetch_at = defaultdict(set) leaving_at = defaultdict(set) for page in page_start.keys(): prefetch_start = max(0, page_start[page] - prefetch_ahead) can_prefetch_at[prefetch_start].add(page) entering_at[page_start[page]].add(page) leaving_at[page_end[page] + 1].add(page) # We now find how many pages we need to keep in our buffer # We also determine where which page is going to reside next_slot = 0 page_to_slot = {} free_slots = set() # For each batch for b_id in range(len(pages_in_batch)): # First we free the pages that are leaving for page in leaving_at[b_id]: free_slots.add(page_to_slot[page]) # We use the prefetch timing here because we want to be able # To start prefetching ahead of time and not overwrite a slot # That is currently used for page in can_prefetch_at[b_id]: # Then we find a slot for the incoming pages if free_slots: # There is a slot available for this page slot = free_slots.pop() else: # We have to allocate a new slot because we ran out slot = next_slot next_slot += 1 page_to_slot[page] = slot return Schedule(next_slot, page_to_slot, can_prefetch_at, entering_at, leaving_at)
null
9,252
from collections import defaultdict from threading import Thread, Event from queue import Queue, Full from contextlib import nullcontext from typing import Sequence, TYPE_CHECKING import torch as ch from ..traversal_order.quasi_random import QuasiRandom from ..utils import chunks from ..pipeline.compiler import Compiler The provided code snippet includes necessary dependencies for implementing the `select_buffer` function. Write a Python function `def select_buffer(buffer, batch_slot, count)` to solve the following problem: Util function to select the relevent subpart of a buffer for a given batch_slot and batch size Here is the function: def select_buffer(buffer, batch_slot, count): """Util function to select the relevent subpart of a buffer for a given batch_slot and batch size""" if buffer is None: return None if isinstance(buffer, tuple): return tuple(select_buffer(x, batch_slot, count) for x in buffer) return buffer[batch_slot][:count]
Util function to select the relevent subpart of a buffer for a given batch_slot and batch size
9,253
from typing import Optional, Sequence, Tuple, Union from dataclasses import dataclass import numpy as np import torch as ch class AllocationQuery: shape: Tuple[int, ...] dtype: Union[np.dtype, ch.dtype] device: Optional[ch.device] = None def allocate_query(memory_allocation: AllocationQuery, batch_size: int, batches_ahead: int): # We compute the total amount of memory needed for this # operation final_shape = [batches_ahead, batch_size, *memory_allocation.shape] if isinstance(memory_allocation.dtype, ch.dtype): result = [] for _ in range(final_shape[0]): partial = ch.empty(*final_shape[1:], dtype=memory_allocation.dtype, device=memory_allocation.device) try: partial = partial.pin_memory() except: pass result.append(partial) else: ch_dtype = ch.from_numpy(np.empty(0, dtype=memory_allocation.dtype)).dtype result = ch.empty(*final_shape, dtype=ch_dtype) try: result = result.pin_memory() except: pass result = result.numpy() return result
null
9,254
import ctypes from numba import njit import numpy as np import platform from ctypes import CDLL, c_int64, c_uint8, c_uint64, POINTER, c_void_p, c_uint32, c_bool, cdll import ffcv._libffcv read_c.argtypes = [c_uint32, c_void_p, c_uint64, c_uint64] def read(fileno:int, destination:np.ndarray, offset:int): return read_c(fileno, destination.ctypes.data, destination.size, offset)
null
9,255
import ctypes from numba import njit import numpy as np import platform from ctypes import CDLL, c_int64, c_uint8, c_uint64, POINTER, c_void_p, c_uint32, c_bool, cdll import ffcv._libffcv ctypes_resize = lib.resize ctypes_resize.argtypes = 11 * [c_int64] def resize_crop(source, start_row, end_row, start_col, end_col, destination): ctypes_resize(0, source.ctypes.data, source.shape[0], source.shape[1], start_row, end_row, start_col, end_col, destination.ctypes.data, destination.shape[0], destination.shape[1])
null
9,256
import ctypes from numba import njit import numpy as np import platform from ctypes import CDLL, c_int64, c_uint8, c_uint64, POINTER, c_void_p, c_uint32, c_bool, cdll import ffcv._libffcv ctypes_imdecode = lib.imdecode ctypes_imdecode.argtypes = [ c_void_p, c_uint64, c_uint32, c_uint32, c_void_p, c_uint32, c_uint32, c_uint32, c_uint32, c_uint32, c_uint32, c_bool, c_bool ] def imdecode(source: np.ndarray, dst: np.ndarray, source_height: int, source_width: int, crop_height=None, crop_width=None, offset_x=0, offset_y=0, scale_factor_num=1, scale_factor_denom=1, enable_crop=False, do_flip=False): return ctypes_imdecode(source.ctypes.data, source.size, source_height, source_width, dst.ctypes.data, crop_height, crop_width, offset_x, offset_y, scale_factor_num, scale_factor_denom, enable_crop, do_flip)
null
9,257
import ctypes from numba import njit import numpy as np import platform from ctypes import CDLL, c_int64, c_uint8, c_uint64, POINTER, c_void_p, c_uint32, c_bool, cdll import ffcv._libffcv ctypes_memcopy = lib.my_memcpy ctypes_memcopy.argtypes = [c_void_p, c_void_p, c_uint64] def memcpy(source: np.ndarray, dest: np.ndarray): return ctypes_memcopy(source.ctypes.data, dest.ctypes.data, source.size*source.itemsize)
null
9,258
from collections.abc import Sequence from typing import Tuple import numpy as np import torch as ch from numpy import dtype from numpy.random import rand from dataclasses import replace from typing import Callable, Optional, Tuple from ..pipeline.allocation_query import AllocationQuery from ..pipeline.operation import Operation from ..pipeline.state import State from ..pipeline.compiler import Compiler def ch_dtype_from_numpy(dtype): return ch.from_numpy(np.zeros((), dtype=dtype)).dtype
null
9,259
import ctypes from numba import njit import numpy as np from ...libffcv import ctypes_resize ctypes_resize = lib.resize ctypes_resize.argtypes = 11 * [c_int64] def resize_crop(source, start_row, end_row, start_col, end_col, destination): ctypes_resize(0, source.ctypes.data, source.shape[0], source.shape[1], start_row, end_row, start_col, end_col, destination.ctypes.data, destination.shape[0], destination.shape[1])
null
9,260
import ctypes from numba import njit import numpy as np from ...libffcv import ctypes_resize def get_random_crop(height, width, scale, ratio): area = height * width log_ratio = np.log(ratio) for _ in range(10): target_area = area * np.random.uniform(scale[0], scale[1]) aspect_ratio = np.exp(np.random.uniform(log_ratio[0], log_ratio[1])) w = int(round(np.sqrt(target_area * aspect_ratio))) h = int(round(np.sqrt(target_area / aspect_ratio))) if 0 < w <= width and 0 < h <= height: i = int(np.random.uniform(0, height - h + 1)) j = int(np.random.uniform(0, width - w + 1)) return i, j, h, w in_ratio = float(width) / float(height) if in_ratio < min(ratio): w = width h = int(round(w / min(ratio))) elif in_ratio > max(ratio): h = height w = int(round(h * max(ratio))) else: w = width h = height i = (height - h) // 2 j = (width - w) // 2 return i, j, h, w
null
9,261
import ctypes from numba import njit import numpy as np from ...libffcv import ctypes_resize def get_center_crop(height, width, ratio): s = min(height, width) c = int(ratio * s) delta_h = (height - c) // 2 delta_w = (width - c) // 2 return delta_h, delta_w, c, c
null
9,262
import os import time import math import pickle from contextlib import nullcontext import numpy as np import torch from torch.nn.parallel import DistributedDataParallel as DDP from torch.distributed import init_process_group, destroy_process_group from model import GPTConfig, GPT eval_iters = 200 torch.manual_seed(1337 + seed_offset) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype) def get_batch(split): # We recreate np.memmap every batch to avoid a memory leak, as per # https://stackoverflow.com/questions/45132940/numpy-memmap-memory-usage-want-to-iterate-once/61472122#61472122 if split == 'train': data = np.memmap(os.path.join(data_dir, 'train.bin'), dtype=np.uint16, mode='r') else: data = np.memmap(os.path.join(data_dir, 'val.bin'), dtype=np.uint16, mode='r') ix = torch.randint(len(data) - block_size, (batch_size,)) x = torch.stack([torch.from_numpy((data[i:i+block_size]).astype(np.int64)) for i in ix]) y = torch.stack([torch.from_numpy((data[i+1:i+1+block_size]).astype(np.int64)) for i in ix]) if device_type == 'cuda': # pin arrays x,y, which allows us to move them to GPU asynchronously (non_blocking=True) x, y = x.pin_memory().to(device, non_blocking=True), y.pin_memory().to(device, non_blocking=True) else: x, y = x.to(device), y.to(device) return x, y model.to(device) X, Y = get_batch('train') def estimate_loss(): out = {} model.eval() for split in ['train', 'val']: losses = torch.zeros(eval_iters) for k in range(eval_iters): X, Y = get_batch(split) with ctx: logits, loss = model(X, Y) losses[k] = loss.item() out[split] = losses.mean() model.train() return out
null
9,263
import os import time import math import pickle from contextlib import nullcontext import numpy as np import torch from torch.nn.parallel import DistributedDataParallel as DDP from torch.distributed import init_process_group, destroy_process_group from model import GPTConfig, GPT learning_rate = 6e-4 warmup_iters = 2000 lr_decay_iters = 600000 min_lr = 6e-5 def get_lr(it): # 1) linear warmup for warmup_iters steps if it < warmup_iters: return learning_rate * it / warmup_iters # 2) if it > lr_decay_iters, return min learning rate if it > lr_decay_iters: return min_lr # 3) in between, use cosine decay down to min learning rate decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters) assert 0 <= decay_ratio <= 1 coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio)) # coeff ranges 0..1 return min_lr + coeff * (learning_rate - min_lr)
null
9,264
import os from contextlib import nullcontext import numpy as np import time import torch from model import GPTConfig, GPT batch_size = 12 block_size = 1024 device = 'cuda' torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True def get_batch(split): data = train_data # note ignore split in benchmarking script ix = torch.randint(len(data) - block_size, (batch_size,)) x = torch.stack([torch.from_numpy((data[i:i+block_size]).astype(np.int64)) for i in ix]) y = torch.stack([torch.from_numpy((data[i+1:i+1+block_size]).astype(np.int64)) for i in ix]) x, y = x.pin_memory().to(device, non_blocking=True), y.pin_memory().to(device, non_blocking=True) return x, y
null