python_code
stringlengths
0
229k
# from collections import deque import numpy as np import random import torch import pickle as pickle class rpm: # replay memory def __init__(self, buffer_size): self.buffer_size = buffer_size self.buffer = [] self.index = 0 def append(self, obj): if self.size() > self.buffer_size: print('buffer size larger than set value, trimming...') self.buffer = self.buffer[(self.size() - self.buffer_size):] elif self.size() == self.buffer_size: self.buffer[self.index] = obj self.index += 1 self.index %= self.buffer_size else: self.buffer.append(obj) def size(self): return len(self.buffer) def sample_batch(self, batch_size, device, only_state=False): if self.size() < batch_size: batch = random.sample(self.buffer, self.size()) else: batch = random.sample(self.buffer, batch_size) if only_state: res = torch.stack(tuple(item[3] for item in batch), dim=0) return res.to(device) else: item_count = 5 res = [] for i in range(5): k = torch.stack(tuple(item[i] for item in batch), dim=0) res.append(k.to(device)) return res[0], res[1], res[2], res[3], res[4]
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.utils.weight_norm as weightNorm from torch.autograd import Variable import sys def conv3x3(in_planes, out_planes, stride=1): return (nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)) def cfg(depth): depth_lst = [18, 34, 50, 101, 152] assert (depth in depth_lst), "Error : Resnet depth should be either 18, 34, 50, 101, 152" cf_dict = { '18': (BasicBlock, [2,2,2,2]), '34': (BasicBlock, [3,4,6,3]), '50': (Bottleneck, [3,4,6,3]), '101':(Bottleneck, [3,4,23,3]), '152':(Bottleneck, [3,8,36,3]), } return cf_dict[str(depth)] class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(in_planes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.shortcut = nn.Sequential() if stride != 1 or in_planes != self.expansion * planes: self.shortcut = nn.Sequential( (nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False)), nn.BatchNorm2d(self.expansion*planes) ) def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = self.bn2(self.conv2(out)) out += self.shortcut(x) out = F.relu(out) return out class Bottleneck(nn.Module): expansion = 4 def __init__(self, in_planes, planes, stride=1): super(Bottleneck, self).__init__() self.conv1 = (nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)) self.conv2 = (nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)) self.conv3 = (nn.Conv2d(planes, self.expansion*planes, kernel_size=1, bias=False)) self.bn1 = nn.BatchNorm2d(planes) self.bn2 = nn.BatchNorm2d(planes) self.bn3 = nn.BatchNorm2d(self.expansion*planes) self.shortcut = nn.Sequential() if stride != 1 or in_planes != self.expansion*planes: self.shortcut = nn.Sequential( (nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False)), ) def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = F.relu(self.bn2(self.conv2(out))) out = self.bn3(self.conv3(out)) out += self.shortcut(x) out = F.relu(out) return out class ResNet(nn.Module): def __init__(self, num_inputs, depth, num_outputs): super(ResNet, self).__init__() self.in_planes = 64 block, num_blocks = cfg(depth) self.conv1 = conv3x3(num_inputs, 64, 2) self.bn1 = nn.BatchNorm2d(64) self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=2) self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) self.fc = nn.Linear(512, num_outputs) def _make_layer(self, block, planes, num_blocks, stride): strides = [stride] + [1]*(num_blocks-1) layers = [] for stride in strides: layers.append(block(self.in_planes, planes, stride)) self.in_planes = planes * block.expansion return nn.Sequential(*layers) def forward(self, x): x = F.relu(self.bn1(self.conv1(x))) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = F.avg_pool2d(x, 4) x = x.view(x.size(0), -1) x = self.fc(x) x = torch.sigmoid(x) return x
import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.utils.weight_norm as weightNorm from torch.autograd import Variable import sys def conv3x3(in_planes, out_planes, stride=1): return weightNorm(nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") coord = torch.zeros([1, 2, 64, 64]) for i in range(64): for j in range(64): coord[0, 0, i, j] = i / 63. coord[0, 1, i, j] = j / 63. coord = coord.to(device) class TReLU(nn.Module): def __init__(self): super(TReLU, self).__init__() self.alpha = nn.Parameter(torch.FloatTensor(1), requires_grad=True) self.alpha.data.fill_(0) def forward(self, x): x = F.relu(x - self.alpha) + self.alpha return x def cfg(depth): depth_lst = [18, 34, 50, 101, 152] assert (depth in depth_lst), "Error : Resnet depth should be either 18, 34, 50, 101, 152" cf_dict = { '18': (BasicBlock, [2,2,2,2]), '34': (BasicBlock, [3,4,6,3]), '50': (Bottleneck, [3,4,6,3]), '101':(Bottleneck, [3,4,23,3]), '152':(Bottleneck, [3,8,36,3]), } return cf_dict[str(depth)] class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(in_planes, planes, stride) self.conv2 = conv3x3(planes, planes) self.shortcut = nn.Sequential() if stride != 1 or in_planes != self.expansion * planes: self.shortcut = nn.Sequential( weightNorm(nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=True)), ) self.relu_1 = TReLU() self.relu_2 = TReLU() def forward(self, x): out = self.relu_1(self.conv1(x)) out = self.conv2(out) out += self.shortcut(x) out = self.relu_2(out) return out class Bottleneck(nn.Module): expansion = 4 def __init__(self, in_planes, planes, stride=1): super(Bottleneck, self).__init__() self.conv1 = weightNorm(nn.Conv2d(in_planes, planes, kernel_size=1, bias=True)) self.conv2 = weightNorm(nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=True)) self.conv3 = weightNorm(nn.Conv2d(planes, self.expansion*planes, kernel_size=1, bias=True)) self.relu_1 = TReLU() self.relu_2 = TReLU() self.relu_3 = TReLU() self.shortcut = nn.Sequential() if stride != 1 or in_planes != self.expansion*planes: self.shortcut = nn.Sequential( weightNorm(nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=True)), ) def forward(self, x): out = self.relu_1(self.conv1(x)) out = self.relu_2(self.conv2(out)) out = self.conv3(out) out += self.shortcut(x) out = self.relu_3(out) return out class ResNet_wobn(nn.Module): def __init__(self, num_inputs, depth, num_outputs): super(ResNet_wobn, self).__init__() self.in_planes = 64 block, num_blocks = cfg(depth) self.conv0 = conv3x3(num_inputs, 32, 2) # 64 self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=2) # 32 self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) # 16 self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=1) self.conv4 = weightNorm(nn.Conv2d(512, 1, 1, 1, 0)) self.relu_1 = TReLU() self.conv1 = weightNorm(nn.Conv2d(65 + 2, 64, 1, 1, 0)) self.conv2 = weightNorm(nn.Conv2d(64, 64, 1, 1, 0)) self.conv3 = weightNorm(nn.Conv2d(64, 32, 1, 1, 0)) self.relu_2 = TReLU() self.relu_3 = TReLU() self.relu_4 = TReLU() def _make_layer(self, block, planes, num_blocks, stride): strides = [stride] + [1]*(num_blocks-1) layers = [] for stride in strides: layers.append(block(self.in_planes, planes, stride)) self.in_planes = planes * block.expansion return nn.Sequential(*layers) def a2img(self, x): tmp = coord.expand(x.shape[0], 2, 64, 64) x = x.repeat(64, 64, 1, 1).permute(2, 3, 0, 1) x = self.relu_2(self.conv1(torch.cat([x, tmp], 1))) x = self.relu_3(self.conv2(x)) x = self.relu_4(self.conv3(x)) return x def forward(self, input): x, a = input a = self.a2img(a) x = self.relu_1(self.conv0(x)) x = torch.cat([x, a], 1) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.conv4(x) return x.view(x.size(0), 64)
import numpy as np from utils.util import * class Evaluator: def __init__(self, args, writer): self.validate_episodes = args.validate_episodes self.max_step = args.max_step self.env_batch = args.env_batch self.writer = writer self.log = 0 def __call__(self, env, policy, debug=False): observation = None for episode in range(self.validate_episodes): # reset at the start of episode observation = env.reset(test=True, episode=episode) episode_steps = 0 episode_reward = 0. assert observation is not None # start episode episode_reward = np.zeros(self.env_batch) while (episode_steps < self.max_step or not self.max_step): action = policy(observation) observation, reward, done, (step_num) = env.step(action) episode_reward += reward episode_steps += 1 env.save_image(self.log, episode_steps) dist = env.get_dist() self.log += 1 return episode_reward, dist
import os import torch from torch.autograd import Variable USE_CUDA = torch.cuda.is_available() def prRed(prt): print("\033[91m {}\033[00m" .format(prt)) def prGreen(prt): print("\033[92m {}\033[00m" .format(prt)) def prYellow(prt): print("\033[93m {}\033[00m" .format(prt)) def prLightPurple(prt): print("\033[94m {}\033[00m" .format(prt)) def prPurple(prt): print("\033[95m {}\033[00m" .format(prt)) def prCyan(prt): print("\033[96m {}\033[00m" .format(prt)) def prLightGray(prt): print("\033[97m {}\033[00m" .format(prt)) def prBlack(prt): print("\033[98m {}\033[00m" .format(prt)) def to_numpy(var): return var.cpu().data.numpy() if USE_CUDA else var.data.numpy() def to_tensor(ndarray, device): return torch.tensor(ndarray, dtype=torch.float, device=device) def soft_update(target, source, tau): for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_( target_param.data * (1.0 - tau) + param.data * tau ) def hard_update(target, source): for m1, m2 in zip(target.modules(), source.modules()): m1._buffers = m2._buffers.copy() for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(param.data) def get_output_folder(parent_dir, env_name): """Return save folder. Assumes folders in the parent_dir have suffix -run{run number}. Finds the highest run number and sets the output folder to that number + 1. This is just convenient so that if you run the same script multiple times tensorboard can plot all of the results on the same plots with different names. Parameters ---------- parent_dir: str Path of the directory containing all experiment runs. Returns ------- parent_dir/run_dir Path to this run's save directory. """ os.makedirs(parent_dir, exist_ok=True) experiment_id = 0 for folder_name in os.listdir(parent_dir): if not os.path.isdir(os.path.join(parent_dir, folder_name)): continue try: folder_name = int(folder_name.split('-run')[-1]) if folder_name > experiment_id: experiment_id = folder_name except: pass experiment_id += 1 parent_dir = os.path.join(parent_dir, env_name) parent_dir = parent_dir + '-run{}'.format(experiment_id) os.makedirs(parent_dir, exist_ok=True) return parent_dir
import PIL import scipy.misc from io import BytesIO import tensorboardX as tb from tensorboardX.summary import Summary class TensorBoard: def __init__(self, model_dir): self.summary_writer = tb.FileWriter(model_dir) def add_image(self, tag, img, step): summary = Summary() bio = BytesIO() if type(img) == str: img = PIL.Image.open(img) elif type(img) == PIL.Image.Image: pass else: img = PIL.Image.fromarray(img) img.save(bio, format="png") image_summary = Summary.Image(encoded_image_string=bio.getvalue()) summary.value.add(tag=tag, image=image_summary) self.summary_writer.add_summary(summary, global_step=step) def add_scalar(self, tag, value, step): summary = Summary(value=[Summary.Value(tag=tag, simple_value=value)]) self.summary_writer.add_summary(summary, global_step=step)
import sys import json import torch import numpy as np import argparse import torchvision.transforms as transforms import cv2 from .DRL.ddpg import decode from .utils.util import * from PIL import Image # device = torch.device("cuda" if torch.cuda.is_available() else "cpu") aug = transforms.Compose([transforms.ToPILImage(), transforms.RandomHorizontalFlip(), ]) width = 128 convas_area = width * width img_train = [] img_test = [] train_num = 0 test_num = 0 class Paint: def __init__(self, batch_size, max_step, device='cpu', Decoder=None): self.batch_size = batch_size self.max_step = max_step self.action_space = (13) self.observation_space = (self.batch_size, width, width, 7) self.test = False self.device = device self.Decoder = Decoder def load_data(self, images=None): # CelebA global train_num, test_num for i in range(200000): img_id = '%06d' % (i + 1) # TorchBench created 2000 random tensors to load here. if images is not None: img = images[i % 2000] else: img = cv2.imread('./data/img_align_celeba/' + img_id + '.jpg', cv2.IMREAD_UNCHANGED) img = cv2.resize(img, (width, width)) if i > 2000: train_num += 1 img_train.append(img) else: test_num += 1 img_test.append(img) def pre_data(self, id, test): if test: img = img_test[id] else: img = img_train[id] return img # Find out why aug and transpose turns random tensor [3, 128, 128] into [128, 3, 128] which fails. # if not test: # img = aug(img) # img = np.asarray(img) # return np.transpose(img, (2, 0, 1)) def reset(self, test=False, begin_num=False): self.test = test self.imgid = [0] * self.batch_size self.gt = torch.zeros([self.batch_size, 3, width, width], dtype=torch.uint8).to(self.device) for i in range(self.batch_size): if test: id = (i + begin_num) % test_num else: id = np.random.randint(train_num) self.imgid[i] = id # self.gt[i] = torch.tensor(self.pre_data(id, test)) self.gt[i] = self.pre_data(id, test).clone().detach().to(device=self.device) self.tot_reward = ((self.gt.float() / 255) ** 2).mean(1).mean(1).mean(1) self.stepnum = 0 self.canvas = torch.zeros([self.batch_size, 3, width, width], dtype=torch.uint8).to(self.device) self.lastdis = self.ini_dis = self.cal_dis() return self.observation() def observation(self): # canvas B * 3 * width * width # gt B * 3 * width * width # T B * 1 * width * width ob = [] T = torch.ones([self.batch_size, 1, width, width], dtype=torch.uint8) * self.stepnum return torch.cat((self.canvas, self.gt, T.to(self.device)), 1) # canvas, img, T def cal_trans(self, s, t): return (s.transpose(0, 3) * t).transpose(0, 3) def step(self, action): self.canvas = (decode(action, self.canvas.float() / 255, self.Decoder) * 255).byte() self.stepnum += 1 ob = self.observation() done = (self.stepnum == self.max_step) reward = self.cal_reward() # np.array([0.] * self.batch_size) return ob.detach(), reward, np.array([done] * self.batch_size), None def cal_dis(self): return (((self.canvas.float() - self.gt.float()) / 255) ** 2).mean(1).mean(1).mean(1) def cal_reward(self): dis = self.cal_dis() reward = (self.lastdis - dis) / (self.ini_dis + 1e-8) self.lastdis = dis return to_numpy(reward)
import os import cv2 import torch import numpy as np import argparse import torch.nn as nn import torch.nn.functional as F from DRL.actor import * from Renderer.stroke_gen import * from Renderer.model import * device = torch.device("cuda" if torch.cuda.is_available() else "cpu") width = 128 parser = argparse.ArgumentParser(description='Learning to Paint') parser.add_argument('--max_step', default=40, type=int, help='max length for episode') parser.add_argument('--actor', default='./model/Paint-run1/actor.pkl', type=str, help='Actor model') parser.add_argument('--renderer', default='./renderer.pkl', type=str, help='renderer model') parser.add_argument('--img', default='image/test.png', type=str, help='test image') parser.add_argument('--imgid', default=0, type=int, help='set begin number for generated image') parser.add_argument('--divide', default=4, type=int, help='divide the target image to get better resolution') args = parser.parse_args() canvas_cnt = args.divide * args.divide T = torch.ones([1, 1, width, width], dtype=torch.float32).to(device) img = cv2.imread(args.img, cv2.IMREAD_COLOR) origin_shape = (img.shape[1], img.shape[0]) coord = torch.zeros([1, 2, width, width]) for i in range(width): for j in range(width): coord[0, 0, i, j] = i / (width - 1.) coord[0, 1, i, j] = j / (width - 1.) coord = coord.to(device) # Coordconv Decoder = FCN() Decoder.load_state_dict(torch.load(args.renderer)) def decode(x, canvas): # b * (10 + 3) x = x.view(-1, 10 + 3) stroke = 1 - Decoder(x[:, :10]) stroke = stroke.view(-1, width, width, 1) color_stroke = stroke * x[:, -3:].view(-1, 1, 1, 3) stroke = stroke.permute(0, 3, 1, 2) color_stroke = color_stroke.permute(0, 3, 1, 2) stroke = stroke.view(-1, 5, 1, width, width) color_stroke = color_stroke.view(-1, 5, 3, width, width) res = [] for i in range(5): canvas = canvas * (1 - stroke[:, i]) + color_stroke[:, i] res.append(canvas) return canvas, res def small2large(x): # (d * d, width, width) -> (d * width, d * width) x = x.reshape(args.divide, args.divide, width, width, -1) x = np.transpose(x, (0, 2, 1, 3, 4)) x = x.reshape(args.divide * width, args.divide * width, -1) return x def large2small(x): # (d * width, d * width) -> (d * d, width, width) x = x.reshape(args.divide, width, args.divide, width, 3) x = np.transpose(x, (0, 2, 1, 3, 4)) x = x.reshape(canvas_cnt, width, width, 3) return x def smooth(img): def smooth_pix(img, tx, ty): if tx == args.divide * width - 1 or ty == args.divide * width - 1 or tx == 0 or ty == 0: return img img[tx, ty] = (img[tx, ty] + img[tx + 1, ty] + img[tx, ty + 1] + img[tx - 1, ty] + img[tx, ty - 1] + img[tx + 1, ty - 1] + img[tx - 1, ty + 1] + img[tx - 1, ty - 1] + img[tx + 1, ty + 1]) / 9 return img for p in range(args.divide): for q in range(args.divide): x = p * width y = q * width for k in range(width): img = smooth_pix(img, x + k, y + width - 1) if q != args.divide - 1: img = smooth_pix(img, x + k, y + width) for k in range(width): img = smooth_pix(img, x + width - 1, y + k) if p != args.divide - 1: img = smooth_pix(img, x + width, y + k) return img def save_img(res, imgid, divide=False): output = res.detach().cpu().numpy() # d * d, 3, width, width output = np.transpose(output, (0, 2, 3, 1)) if divide: output = small2large(output) output = smooth(output) else: output = output[0] output = (output * 255).astype('uint8') output = cv2.resize(output, origin_shape) cv2.imwrite('output/generated' + str(imgid) + '.png', output) actor = ResNet(9, 18, 65) # action_bundle = 5, 65 = 5 * 13 actor.load_state_dict(torch.load(args.actor)) actor = actor.to(device).eval() Decoder = Decoder.to(device).eval() canvas = torch.zeros([1, 3, width, width]).to(device) patch_img = cv2.resize(img, (width * args.divide, width * args.divide)) patch_img = large2small(patch_img) patch_img = np.transpose(patch_img, (0, 3, 1, 2)) patch_img = torch.tensor(patch_img).to(device).float() / 255. img = cv2.resize(img, (width, width)) img = img.reshape(1, width, width, 3) img = np.transpose(img, (0, 3, 1, 2)) img = torch.tensor(img).to(device).float() / 255. os.system('mkdir output') with torch.no_grad(): if args.divide != 1: args.max_step = args.max_step // 2 for i in range(args.max_step): stepnum = T * i / args.max_step actions = actor(torch.cat([canvas, img, stepnum, coord], 1)) canvas, res = decode(actions, canvas) print('canvas step {}, L2Loss = {}'.format(i, ((canvas - img) ** 2).mean())) for j in range(5): save_img(res[j], args.imgid) args.imgid += 1 if args.divide != 1: canvas = canvas[0].detach().cpu().numpy() canvas = np.transpose(canvas, (1, 2, 0)) canvas = cv2.resize(canvas, (width * args.divide, width * args.divide)) canvas = large2small(canvas) canvas = np.transpose(canvas, (0, 3, 1, 2)) canvas = torch.tensor(canvas).to(device).float() coord = coord.expand(canvas_cnt, 2, width, width) T = T.expand(canvas_cnt, 1, width, width) for i in range(args.max_step): stepnum = T * i / args.max_step actions = actor(torch.cat([canvas, patch_img, stepnum, coord], 1)) canvas, res = decode(actions, canvas) print('divided canvas step {}, L2Loss = {}'.format(i, ((canvas - patch_img) ** 2).mean())) for j in range(5): save_img(res[j], args.imgid, True) args.imgid += 1
#!/usr/bin/env python3 import cv2 import random import numpy as np import argparse from DRL.evaluator import Evaluator from utils.util import * from utils.tensorboard import TensorBoard import time exp = os.path.abspath('.').split('/')[-1] writer = TensorBoard('../train_log/{}'.format(exp)) os.system('ln -sf ../train_log/{} ./log'.format(exp)) os.system('mkdir ./model') def train(agent, env, evaluate): train_times = args.train_times env_batch = args.env_batch validate_interval = args.validate_interval max_step = args.max_step debug = args.debug episode_train_times = args.episode_train_times resume = args.resume output = args.output time_stamp = time.time() step = episode = episode_steps = 0 tot_reward = 0. observation = None noise_factor = args.noise_factor while step <= train_times: step += 1 episode_steps += 1 # reset if it is the start of episode if observation is None: observation = env.reset() agent.reset(observation, noise_factor) action = agent.select_action(observation, noise_factor=noise_factor) observation, reward, done, _ = env.step(action) agent.observe(reward, observation, done, step) if (episode_steps >= max_step and max_step): if step > args.warmup: # [optional] evaluate if episode > 0 and validate_interval > 0 and episode % validate_interval == 0: reward, dist = evaluate(env, agent.select_action, debug=debug) if debug: prRed('Step_{:07d}: mean_reward:{:.3f} mean_dist:{:.3f} var_dist:{:.3f}'.format(step - 1, np.mean(reward), np.mean(dist), np.var(dist))) writer.add_scalar('validate/mean_reward', np.mean(reward), step) writer.add_scalar('validate/mean_dist', np.mean(dist), step) writer.add_scalar('validate/var_dist', np.var(dist), step) agent.save_model(output) train_time_interval = time.time() - time_stamp time_stamp = time.time() tot_Q = 0. tot_value_loss = 0. if step > args.warmup: if step < 10000 * max_step: lr = (3e-4, 1e-3) elif step < 20000 * max_step: lr = (1e-4, 3e-4) else: lr = (3e-5, 1e-4) for i in range(episode_train_times): Q, value_loss = agent.update_policy(lr) tot_Q += Q.data.cpu().numpy() tot_value_loss += value_loss.data.cpu().numpy() writer.add_scalar('train/critic_lr', lr[0], step) writer.add_scalar('train/actor_lr', lr[1], step) writer.add_scalar('train/Q', tot_Q / episode_train_times, step) writer.add_scalar('train/critic_loss', tot_value_loss / episode_train_times, step) if debug: prBlack('#{}: steps:{} interval_time:{:.2f} train_time:{:.2f}' \ .format(episode, step, train_time_interval, time.time()-time_stamp)) time_stamp = time.time() # reset observation = None episode_steps = 0 episode += 1 if __name__ == "__main__": parser = argparse.ArgumentParser(description='Learning to Paint') # hyper-parameter parser.add_argument('--warmup', default=400, type=int, help='timestep without training but only filling the replay memory') parser.add_argument('--discount', default=0.95**5, type=float, help='discount factor') parser.add_argument('--batch_size', default=96, type=int, help='minibatch size') parser.add_argument('--rmsize', default=800, type=int, help='replay memory size') parser.add_argument('--env_batch', default=96, type=int, help='concurrent environment number') parser.add_argument('--tau', default=0.001, type=float, help='moving average for target network') parser.add_argument('--max_step', default=40, type=int, help='max length for episode') parser.add_argument('--noise_factor', default=0, type=float, help='noise level for parameter space noise') parser.add_argument('--validate_interval', default=50, type=int, help='how many episodes to perform a validation') parser.add_argument('--validate_episodes', default=5, type=int, help='how many episode to perform during validation') parser.add_argument('--train_times', default=2000000, type=int, help='total traintimes') parser.add_argument('--episode_train_times', default=10, type=int, help='train times for each episode') parser.add_argument('--resume', default=None, type=str, help='Resuming model path for testing') parser.add_argument('--output', default='./model', type=str, help='Resuming model path for testing') parser.add_argument('--debug', dest='debug', action='store_true', help='print some info') parser.add_argument('--seed', default=1234, type=int, help='random seed') args = parser.parse_args() args.output = get_output_folder(args.output, "Paint") np.random.seed(args.seed) torch.manual_seed(args.seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(args.seed) random.seed(args.seed) torch.backends.cudnn.deterministic = False torch.backends.cudnn.benchmark = True from DRL.ddpg import DDPG from DRL.multi import fastenv fenv = fastenv(args.max_step, args.env_batch, writer) agent = DDPG(args.batch_size, args.env_batch, args.max_step, \ args.tau, args.discount, args.rmsize, \ writer, args.resume, args.output) evaluate = Evaluator(args, writer) print('observation_space', fenv.observation_space, 'action_space', fenv.action_space) train(agent, fenv, evaluate)
import cv2 import torch import numpy as np import sys import torch.nn as nn import torch.nn.functional as F from utils.tensorboard import TensorBoard from Renderer.model import FCN from Renderer.stroke_gen import * #writer = TensorBoard("../train_log/") import torch.optim as optim import argparse parser = argparse.ArgumentParser() parser.add_argument('--debug', metavar='fn', default="", help="Dump outputs into file") parser.add_argument('--script', default=False, help="Script the model") args = parser.parse_args() torch.manual_seed(1337) np.random.seed(1337) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False criterion = nn.MSELoss() net = FCN() if args.script: net = torch.jit.script(net) optimizer = optim.Adam(net.parameters(), lr=3e-6) batch_size = 64 use_cuda = torch.cuda.is_available() step = 0 def save_model(): if use_cuda: net.cpu() torch.save(net.state_dict(), "../renderer.pkl") if use_cuda: net.cuda() def load_weights(): pretrained_dict = torch.load("../renderer.pkl") model_dict = net.state_dict() pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict} model_dict.update(pretrained_dict) net.load_state_dict(model_dict) #load_weights() while step < 100: net.train() train_batch = [] ground_truth = [] for i in range(batch_size): f = np.random.uniform(0, 1, 10) train_batch.append(f) ground_truth.append(draw(f)) train_batch = torch.tensor(train_batch).float() ground_truth = torch.tensor(ground_truth).float() if use_cuda: net = net.cuda() train_batch = train_batch.cuda() ground_truth = ground_truth.cuda() gen = net(train_batch) optimizer.zero_grad() loss = criterion(gen, ground_truth) loss.backward() optimizer.step() print(step, loss.item()) if step < 200000: lr = 1e-4 elif step < 400000: lr = 1e-5 else: lr = 1e-6 for param_group in optimizer.param_groups: param_group["lr"] = lr #writer.add_scalar("train/loss", loss.item(), step) if step % 100 == 0: net.eval() gen = net(train_batch) loss = criterion(gen, ground_truth) #writer.add_scalar("val/loss", loss.item(), step) for i in range(32): G = gen[i].cpu().data.numpy() GT = ground_truth[i].cpu().data.numpy() #writer.add_image("train/gen{}.png".format(i), G, step) #writer.add_image("train/ground_truth{}.png".format(i), GT, step) if step % 1000 == 0: save_model() step += 1 if args.debug: torch.save(gen, args.debug)
import cv2 import numpy as np def normal(x, width): return (int)(x * (width - 1) + 0.5) def draw(f, width=128): x0, y0, x1, y1, x2, y2, z0, z2, w0, w2 = f x1 = x0 + (x2 - x0) * x1 y1 = y0 + (y2 - y0) * y1 x0 = normal(x0, width * 2) x1 = normal(x1, width * 2) x2 = normal(x2, width * 2) y0 = normal(y0, width * 2) y1 = normal(y1, width * 2) y2 = normal(y2, width * 2) z0 = (int)(1 + z0 * width // 2) z2 = (int)(1 + z2 * width // 2) canvas = np.zeros([width * 2, width * 2]).astype('float32') tmp = 1. / 100 for i in range(100): t = i * tmp x = (int)((1-t) * (1-t) * x0 + 2 * t * (1-t) * x1 + t * t * x2) y = (int)((1-t) * (1-t) * y0 + 2 * t * (1-t) * y1 + t * t * y2) z = (int)((1-t) * z0 + t * z2) w = (1-t) * w0 + t * w2 cv2.circle(canvas, (y, x), z, w, -1) return 1 - cv2.resize(canvas, dsize=(width, width))
import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.utils.weight_norm as weightNorm class FCN(nn.Module): def __init__(self): super(FCN, self).__init__() self.fc1 = (nn.Linear(10, 512)) self.fc2 = (nn.Linear(512, 1024)) self.fc3 = (nn.Linear(1024, 2048)) self.fc4 = (nn.Linear(2048, 4096)) self.conv1 = (nn.Conv2d(16, 32, 3, 1, 1)) self.conv2 = (nn.Conv2d(32, 32, 3, 1, 1)) self.conv3 = (nn.Conv2d(8, 16, 3, 1, 1)) self.conv4 = (nn.Conv2d(16, 16, 3, 1, 1)) self.conv5 = (nn.Conv2d(4, 8, 3, 1, 1)) self.conv6 = (nn.Conv2d(8, 4, 3, 1, 1)) self.pixel_shuffle = nn.PixelShuffle(2) def forward(self, x): x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = F.relu(self.fc3(x)) x = F.relu(self.fc4(x)) x = x.view(-1, 16, 16, 16) x = F.relu(self.conv1(x)) x = self.pixel_shuffle(self.conv2(x)) x = F.relu(self.conv3(x)) x = self.pixel_shuffle(self.conv4(x)) x = F.relu(self.conv5(x)) x = self.pixel_shuffle(self.conv6(x)) x = torch.sigmoid(x) return 1 - x.view(-1, 128, 128)
import torch import torch.nn as nn import numpy as np from torch.optim import Adam, SGD from torch import autograd from torch.autograd import Variable import torch.nn.functional as F from torch.autograd import grad as torch_grad import torch.nn.utils.weight_norm as weightNorm from ..utils.util import * device = torch.device("cuda" if torch.cuda.is_available() else "cpu") dim = 128 LAMBDA = 10 # Gradient penalty lambda hyperparameter class TReLU(nn.Module): def __init__(self): super(TReLU, self).__init__() self.alpha = nn.Parameter(torch.FloatTensor(1), requires_grad=True) self.alpha.data.fill_(0) def forward(self, x): x = F.relu(x - self.alpha) + self.alpha return x class Discriminator(nn.Module): def __init__(self): super(Discriminator, self).__init__() self.conv0 = weightNorm(nn.Conv2d(6, 16, 5, 2, 2)) self.conv1 = weightNorm(nn.Conv2d(16, 32, 5, 2, 2)) self.conv2 = weightNorm(nn.Conv2d(32, 64, 5, 2, 2)) self.conv3 = weightNorm(nn.Conv2d(64, 128, 5, 2, 2)) self.conv4 = weightNorm(nn.Conv2d(128, 1, 5, 2, 2)) self.relu0 = TReLU() self.relu1 = TReLU() self.relu2 = TReLU() self.relu3 = TReLU() def forward(self, x): x = self.conv0(x) x = self.relu0(x) x = self.conv1(x) x = self.relu1(x) x = self.conv2(x) x = self.relu2(x) x = self.conv3(x) x = self.relu3(x) x = self.conv4(x) x = F.avg_pool2d(x, 4) x = x.view(-1, 1) return x netD = Discriminator() target_netD = Discriminator() netD = netD.to(device) target_netD = target_netD.to(device) hard_update(target_netD, netD) optimizerD = Adam(netD.parameters(), lr=3e-4, betas=(0.5, 0.999)) def cal_gradient_penalty(netD, real_data, fake_data, batch_size): alpha = torch.rand(batch_size, 1) alpha = alpha.expand(batch_size, int(real_data.nelement()/batch_size)).contiguous() alpha = alpha.view(batch_size, 6, dim, dim) alpha = alpha.to(device) fake_data = fake_data.view(batch_size, 6, dim, dim) interpolates = Variable(alpha * real_data.data + ((1 - alpha) * fake_data.data), requires_grad=True) disc_interpolates = netD(interpolates) gradients = autograd.grad(disc_interpolates, interpolates, grad_outputs=torch.ones(disc_interpolates.size()).to(device), create_graph=True, retain_graph=True)[0] gradients = gradients.view(gradients.size(0), -1) gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean() * LAMBDA return gradient_penalty def cal_reward(fake_data, real_data): return target_netD(torch.cat([real_data, fake_data], 1)) def save_gan(path): netD.cpu() torch.save(netD.state_dict(),'{}/wgan.pkl'.format(path)) netD.to(device) def load_gan(path): netD.load_state_dict(torch.load('{}/wgan.pkl'.format(path))) def update(fake_data, real_data): fake_data = fake_data.detach() real_data = real_data.detach() fake = torch.cat([real_data, fake_data], 1) real = torch.cat([real_data, real_data], 1) D_real = netD(real) D_fake = netD(fake) gradient_penalty = cal_gradient_penalty(netD, real, fake, real.shape[0]) optimizerD.zero_grad() D_cost = D_fake.mean() - D_real.mean() + gradient_penalty D_cost.backward() optimizerD.step() soft_update(target_netD, netD, 0.001) return D_fake.mean(), D_real.mean(), gradient_penalty
import cv2 import torch import numpy as np from ..env import Paint from ..utils.util import * # device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class fastenv(): def __init__(self, max_episode_length=10, env_batch=64, writer=None, images=None, device="cpu", Decoder=None): self.max_episode_length = max_episode_length self.env_batch = env_batch self.device = device self.Decoder = Decoder self.env = Paint(self.env_batch, self.max_episode_length, device=self.device, Decoder=self.Decoder) self.env.load_data(images) self.observation_space = self.env.observation_space self.action_space = self.env.action_space self.writer = writer self.test = False self.log = 0 def save_image(self, log, step): for i in range(self.env_batch): if self.env.imgid[i] <= 10: canvas = cv2.cvtColor((to_numpy(self.env.canvas[i].permute(1, 2, 0))), cv2.COLOR_BGR2RGB) self.writer.add_image('{}/canvas_{}.png'.format(str(self.env.imgid[i]), str(step)), canvas, log) if step == self.max_episode_length: for i in range(self.env_batch): if self.env.imgid[i] < 50: gt = cv2.cvtColor((to_numpy(self.env.gt[i].permute(1, 2, 0))), cv2.COLOR_BGR2RGB) canvas = cv2.cvtColor((to_numpy(self.env.canvas[i].permute(1, 2, 0))), cv2.COLOR_BGR2RGB) self.writer.add_image(str(self.env.imgid[i]) + '/_target.png', gt, log) self.writer.add_image(str(self.env.imgid[i]) + '/_canvas.png', canvas, log) def step(self, action): with torch.no_grad(): ob, r, d, _ = self.env.step(torch.tensor(action).to(self.device)) if d[0]: if not self.test: self.dist = self.get_dist() for i in range(self.env_batch): if self.writer: self.writer.add_scalar('train/dist', self.dist[i], self.log) self.log += 1 return ob, r, d, _ def get_dist(self): return to_numpy((((self.env.gt.float() - self.env.canvas.float()) / 255) ** 2).mean(1).mean(1).mean(1)) def reset(self, test=False, episode=0): self.test = test ob = self.env.reset(self.test, episode * self.env_batch) return ob
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import Adam, SGD from ..Renderer.model import * from .rpm import rpm from .actor import * from .critic import * from .wgan import * from ..utils.util import * # device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Instead of having these as globals, create Decoder inside TB model and criterion in this DDPG model. # criterion = nn.MSELoss() # Use default Renderer instead of importing one. # Decoder = FCN() # Decoder.load_state_dict(torch.load('../renderer.pkl')) def decode(x, canvas, Decoder): # b * (10 + 3) x = x.view(-1, 10 + 3) stroke = 1 - Decoder(x[:, :10]) stroke = stroke.view(-1, 128, 128, 1) color_stroke = stroke * x[:, -3:].view(-1, 1, 1, 3) stroke = stroke.permute(0, 3, 1, 2) color_stroke = color_stroke.permute(0, 3, 1, 2) stroke = stroke.view(-1, 5, 1, 128, 128) color_stroke = color_stroke.view(-1, 5, 3, 128, 128) for i in range(5): canvas = canvas * (1 - stroke[:, i]) + color_stroke[:, i] return canvas def cal_trans(s, t): return (s.transpose(0, 3) * t).transpose(0, 3) class DDPG(object): def __init__(self, batch_size=64, env_batch=1, max_step=40, tau=0.001, discount=0.9, rmsize=800, writer=None, resume=None, output_path=None, device='cpu', Decoder=None): self.max_step = max_step self.env_batch = env_batch self.batch_size = batch_size self.device = device self.actor = ResNet(9, 18, 65) # target, canvas, stepnum, coordconv 3 + 3 + 1 + 2 self.actor_target = ResNet(9, 18, 65) self.critic = ResNet_wobn(3 + 9, 18, 1) # add the last canvas for better prediction self.critic_target = ResNet_wobn(3 + 9, 18, 1) self.criterion = nn.MSELoss() self.Decoder = Decoder self.actor_optim = Adam(self.actor.parameters(), lr=1e-2) self.critic_optim = Adam(self.critic.parameters(), lr=1e-2) if resume is not None: self.load_weights(resume) hard_update(self.actor_target, self.actor) hard_update(self.critic_target, self.critic) # Create replay buffer self.memory = rpm(rmsize * max_step) # Hyper-parameters self.tau = tau self.discount = discount # Tensorboard self.writer = writer self.log = 0 self.coord = torch.zeros([1, 2, 128, 128]) for i in range(128): for j in range(128): self.coord[0, 0, i, j] = i / 127. self.coord[0, 1, i, j] = j / 127. self.coord = self.coord.to(self.device) self.state = [None] * self.env_batch # Most recent state self.action = [None] * self.env_batch # Most recent action self.choose_device() def play(self, state, target=False): state = torch.cat((state[:, :6].float() / 255, state[:, 6:7].float() / self.max_step, self.coord.expand(state.shape[0], 2, 128, 128)), 1) if target: return self.actor_target(state) else: return self.actor(state) def update_gan(self, state): canvas = state[:, :3] gt = state[:, 3 : 6] fake, real, penal = update(canvas.float() / 255, gt.float() / 255) if self.log % 20 == 0 and self.writer: self.writer.add_scalar('train/gan_fake', fake, self.log) self.writer.add_scalar('train/gan_real', real, self.log) self.writer.add_scalar('train/gan_penal', penal, self.log) def evaluate(self, state, action, target=False): T = state[:, 6 : 7] gt = state[:, 3 : 6].float() / 255 canvas0 = state[:, :3].float() / 255 canvas1 = decode(action, canvas0, self.Decoder) gan_reward = cal_reward(canvas1, gt) - cal_reward(canvas0, gt) # L2_reward = ((canvas0 - gt) ** 2).mean(1).mean(1).mean(1) - ((canvas1 - gt) ** 2).mean(1).mean(1).mean(1) coord_ = self.coord.expand(state.shape[0], 2, 128, 128) merged_state = torch.cat([canvas0, canvas1, gt, (T + 1).float() / self.max_step, coord_], 1) # canvas0 is not necessarily added if target: Q = self.critic_target(merged_state) return (Q + gan_reward), gan_reward else: Q = self.critic(merged_state) if self.log % 20 == 0 and self.writer: self.writer.add_scalar('train/expect_reward', Q.mean(), self.log) self.writer.add_scalar('train/gan_reward', gan_reward.mean(), self.log) return (Q + gan_reward), gan_reward def update_policy(self, lr): self.log += 1 for param_group in self.critic_optim.param_groups: param_group['lr'] = lr[0] for param_group in self.actor_optim.param_groups: param_group['lr'] = lr[1] # Sample batch state, action, reward, \ next_state, terminal = self.memory.sample_batch(self.batch_size, self.device) self.update_gan(next_state) with torch.no_grad(): next_action = self.play(next_state, True) target_q, _ = self.evaluate(next_state, next_action, True) target_q = self.discount * ((1 - terminal.float()).view(-1, 1)) * target_q cur_q, step_reward = self.evaluate(state, action) target_q += step_reward.detach() value_loss = self.criterion(cur_q, target_q) self.critic.zero_grad() value_loss.backward(retain_graph=True) self.critic_optim.step() action = self.play(state) pre_q, _ = self.evaluate(state.detach(), action) policy_loss = -pre_q.mean() self.actor.zero_grad() policy_loss.backward(retain_graph=True) self.actor_optim.step() # Target update soft_update(self.actor_target, self.actor, self.tau) soft_update(self.critic_target, self.critic, self.tau) return -policy_loss, value_loss def observe(self, reward, state, done, step): s0 = torch.tensor(self.state, device='cpu') a = to_tensor(self.action, "cpu") r = to_tensor(reward, "cpu") s1 = torch.tensor(state, device='cpu') d = to_tensor(done.astype('float32'), "cpu") for i in range(self.env_batch): self.memory.append([s0[i], a[i], r[i], s1[i], d[i]]) self.state = state def noise_action(self, noise_factor, state, action): noise = np.zeros(action.shape) for i in range(self.env_batch): action[i] = action[i] + np.random.normal(0, self.noise_level[i], action.shape[1:]).astype('float32') return np.clip(action.astype('float32'), 0, 1) def select_action(self, state, return_fix=False, noise_factor=0): self.eval() with torch.no_grad(): action = self.play(state) action = to_numpy(action) if noise_factor > 0: action = self.noise_action(noise_factor, state, action) self.train() self.action = action if return_fix: return action return self.action def reset(self, obs, factor): self.state = obs self.noise_level = np.random.uniform(0, factor, self.env_batch) def load_weights(self, path): if path is None: return self.actor.load_state_dict(torch.load('{}/actor.pkl'.format(path))) self.critic.load_state_dict(torch.load('{}/critic.pkl'.format(path))) load_gan(path) def save_model(self, path): self.actor.cpu() self.critic.cpu() torch.save(self.actor.state_dict(), '{}/actor.pkl'.format(path)) torch.save(self.critic.state_dict(), '{}/critic.pkl'.format(path)) save_gan(path) self.choose_device() def eval(self): self.actor.eval() self.actor_target.eval() self.critic.eval() self.critic_target.eval() def train(self): self.actor.train() self.actor_target.train() self.critic.train() self.critic_target.train() def choose_device(self): self.Decoder.to(self.device) self.actor.to(self.device) self.actor_target.to(self.device) self.critic.to(self.device) self.critic_target.to(self.device)
# from collections import deque import numpy as np import random import torch import pickle as pickle class rpm(object): # replay memory def __init__(self, buffer_size): self.buffer_size = buffer_size self.buffer = [] self.index = 0 def append(self, obj): if self.size() > self.buffer_size: print('buffer size larger than set value, trimming...') self.buffer = self.buffer[(self.size() - self.buffer_size):] elif self.size() == self.buffer_size: self.buffer[self.index] = obj self.index += 1 self.index %= self.buffer_size else: self.buffer.append(obj) def size(self): return len(self.buffer) def sample_batch(self, batch_size, device, only_state=False): if self.size() < batch_size: batch = random.sample(self.buffer, self.size()) else: batch = random.sample(self.buffer, batch_size) if only_state: res = torch.stack(tuple(item[3] for item in batch), dim=0) return res.to(device) else: item_count = 5 res = [] for i in range(5): k = torch.stack(tuple(item[i] for item in batch), dim=0) res.append(k.to(device)) return res[0], res[1], res[2], res[3], res[4]
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.utils.weight_norm as weightNorm from torch.autograd import Variable import sys def conv3x3(in_planes, out_planes, stride=1): return (nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)) def cfg(depth): depth_lst = [18, 34, 50, 101, 152] assert (depth in depth_lst), "Error : Resnet depth should be either 18, 34, 50, 101, 152" cf_dict = { '18': (BasicBlock, [2,2,2,2]), '34': (BasicBlock, [3,4,6,3]), '50': (Bottleneck, [3,4,6,3]), '101':(Bottleneck, [3,4,23,3]), '152':(Bottleneck, [3,8,36,3]), } return cf_dict[str(depth)] class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(in_planes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.shortcut = nn.Sequential() if stride != 1 or in_planes != self.expansion * planes: self.shortcut = nn.Sequential( (nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False)), nn.BatchNorm2d(self.expansion*planes) ) def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = self.bn2(self.conv2(out)) out += self.shortcut(x) out = F.relu(out) return out class Bottleneck(nn.Module): expansion = 4 def __init__(self, in_planes, planes, stride=1): super(Bottleneck, self).__init__() self.conv1 = (nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)) self.conv2 = (nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)) self.conv3 = (nn.Conv2d(planes, self.expansion*planes, kernel_size=1, bias=False)) self.bn1 = nn.BatchNorm2d(planes) self.bn2 = nn.BatchNorm2d(planes) self.bn3 = nn.BatchNorm2d(self.expansion*planes) self.shortcut = nn.Sequential() if stride != 1 or in_planes != self.expansion*planes: self.shortcut = nn.Sequential( (nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False)), ) def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = F.relu(self.bn2(self.conv2(out))) out = self.bn3(self.conv3(out)) out += self.shortcut(x) out = F.relu(out) return out class ResNet(nn.Module): def __init__(self, num_inputs, depth, num_outputs): super(ResNet, self).__init__() self.in_planes = 64 block, num_blocks = cfg(depth) self.conv1 = conv3x3(num_inputs, 64, 2) self.bn1 = nn.BatchNorm2d(64) self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=2) self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) self.fc = nn.Linear(512, num_outputs) def _make_layer(self, block, planes, num_blocks, stride): strides = [stride] + [1]*(num_blocks-1) layers = [] for stride in strides: layers.append(block(self.in_planes, planes, stride)) self.in_planes = planes * block.expansion return nn.Sequential(*layers) def forward(self, x): x = F.relu(self.bn1(self.conv1(x))) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = F.avg_pool2d(x, 4) x = x.view(x.size(0), -1) x = self.fc(x) x = torch.sigmoid(x) return x
import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.utils.weight_norm as weightNorm from torch.autograd import Variable import sys def conv3x3(in_planes, out_planes, stride=1): return weightNorm(nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)) class TReLU(nn.Module): def __init__(self): super(TReLU, self).__init__() self.alpha = nn.Parameter(torch.FloatTensor(1), requires_grad=True) self.alpha.data.fill_(0) def forward(self, x): x = F.relu(x - self.alpha) + self.alpha return x def cfg(depth): depth_lst = [18, 34, 50, 101, 152] assert (depth in depth_lst), "Error : Resnet depth should be either 18, 34, 50, 101, 152" cf_dict = { '18': (BasicBlock, [2,2,2,2]), '34': (BasicBlock, [3,4,6,3]), '50': (Bottleneck, [3,4,6,3]), '101':(Bottleneck, [3,4,23,3]), '152':(Bottleneck, [3,8,36,3]), } return cf_dict[str(depth)] class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(in_planes, planes, stride) self.conv2 = conv3x3(planes, planes) self.shortcut = nn.Sequential() if stride != 1 or in_planes != self.expansion * planes: self.shortcut = nn.Sequential( weightNorm(nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=True)), ) self.relu_1 = TReLU() self.relu_2 = TReLU() def forward(self, x): out = self.relu_1(self.conv1(x)) out = self.conv2(out) out += self.shortcut(x) out = self.relu_2(out) return out class Bottleneck(nn.Module): expansion = 4 def __init__(self, in_planes, planes, stride=1): super(Bottleneck, self).__init__() self.conv1 = weightNorm(nn.Conv2d(in_planes, planes, kernel_size=1, bias=True)) self.conv2 = weightNorm(nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=True)) self.conv3 = weightNorm(nn.Conv2d(planes, self.expansion*planes, kernel_size=1, bias=True)) self.relu_1 = TReLU() self.relu_2 = TReLU() self.relu_3 = TReLU() self.shortcut = nn.Sequential() if stride != 1 or in_planes != self.expansion*planes: self.shortcut = nn.Sequential( weightNorm(nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=True)), ) def forward(self, x): out = self.relu_1(self.conv1(x)) out = self.relu_2(self.conv2(out)) out = self.conv3(out) out += self.shortcut(x) out = self.relu_3(out) return out class ResNet_wobn(nn.Module): def __init__(self, num_inputs, depth, num_outputs): super(ResNet_wobn, self).__init__() self.in_planes = 64 block, num_blocks = cfg(depth) self.conv1 = conv3x3(num_inputs, 64, 2) self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=2) self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) self.fc = nn.Linear(512, num_outputs) self.relu_1 = TReLU() def _make_layer(self, block, planes, num_blocks, stride): strides = [stride] + [1]*(num_blocks-1) layers = [] for stride in strides: layers.append(block(self.in_planes, planes, stride)) self.in_planes = planes * block.expansion return nn.Sequential(*layers) def forward(self, x): x = self.relu_1(self.conv1(x)) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = F.avg_pool2d(x, 4) x = x.view(x.size(0), -1) x = self.fc(x) return x
import numpy as np from ..utils.util import * class Evaluator(object): def __init__(self, args, env_batch, writer): self.validate_episodes = args.validate_episodes self.max_step = args.max_step self.env_batch = env_batch self.writer = writer self.log = 0 def __call__(self, env, policy, debug=False): observation = None for episode in range(self.validate_episodes): # reset at the start of episode observation = env.reset(test=True, episode=episode) episode_steps = 0 episode_reward = 0. assert observation is not None # start episode episode_reward = np.zeros(self.env_batch) while (episode_steps < self.max_step or not self.max_step): action = policy(observation) observation, reward, done, (step_num) = env.step(action) episode_reward += reward episode_steps += 1 if self.writer: env.save_image(self.log, episode_steps) dist = env.get_dist() self.log += 1 return episode_reward, dist
import os import torch from torch.autograd import Variable USE_CUDA = torch.cuda.is_available() def prRed(prt): print("\033[91m {}\033[00m" .format(prt)) def prGreen(prt): print("\033[92m {}\033[00m" .format(prt)) def prYellow(prt): print("\033[93m {}\033[00m" .format(prt)) def prLightPurple(prt): print("\033[94m {}\033[00m" .format(prt)) def prPurple(prt): print("\033[95m {}\033[00m" .format(prt)) def prCyan(prt): print("\033[96m {}\033[00m" .format(prt)) def prLightGray(prt): print("\033[97m {}\033[00m" .format(prt)) def prBlack(prt): print("\033[98m {}\033[00m" .format(prt)) def to_numpy(var): return var.cpu().data.numpy() if USE_CUDA else var.data.numpy() def to_tensor(ndarray, device): return torch.tensor(ndarray, dtype=torch.float, device=device) def soft_update(target, source, tau): for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_( target_param.data * (1.0 - tau) + param.data * tau ) def hard_update(target, source): for m1, m2 in zip(target.modules(), source.modules()): m1._buffers = m2._buffers.copy() for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(param.data) def get_output_folder(parent_dir, env_name): """Return save folder. Assumes folders in the parent_dir have suffix -run{run number}. Finds the highest run number and sets the output folder to that number + 1. This is just convenient so that if you run the same script multiple times tensorboard can plot all of the results on the same plots with different names. Parameters ---------- parent_dir: str Path of the directory containing all experiment runs. Returns ------- parent_dir/run_dir Path to this run's save directory. """ os.makedirs(parent_dir, exist_ok=True) experiment_id = 0 for folder_name in os.listdir(parent_dir): if not os.path.isdir(os.path.join(parent_dir, folder_name)): continue try: folder_name = int(folder_name.split('-run')[-1]) if folder_name > experiment_id: experiment_id = folder_name except: pass experiment_id += 1 parent_dir = os.path.join(parent_dir, env_name) parent_dir = parent_dir + '-run{}'.format(experiment_id) os.makedirs(parent_dir, exist_ok=True) return parent_dir
import PIL import scipy.misc from io import BytesIO import tensorboardX as tb from tensorboardX.summary import Summary class TensorBoard(object): def __init__(self, model_dir): self.summary_writer = tb.FileWriter(model_dir) def add_image(self, tag, img, step): summary = Summary() bio = BytesIO() if type(img) == str: img = PIL.Image.open(img) elif type(img) == PIL.Image.Image: pass else: img = scipy.misc.toimage(img) img.save(bio, format="png") image_summary = Summary.Image(encoded_image_string=bio.getvalue()) summary.value.add(tag=tag, image=image_summary) self.summary_writer.add_summary(summary, global_step=step) def add_scalar(self, tag, value, step): summary = Summary(value=[Summary.Value(tag=tag, simple_value=value)]) self.summary_writer.add_summary(summary, global_step=step)
from torchbenchmark.tasks import NLP from torchbenchmark.util.framework.huggingface.model_factory import HuggingFaceModel class Model(HuggingFaceModel): task = NLP.LANGUAGE_MODELING # Original train batch size per device: 8 # Source: https://github.com/huggingface/transformers/blob/master/examples/flax/language-modeling/run_t5_mlm_flax.py#L83 DEFAULT_TRAIN_BSIZE = 2 # Original eval batch size per device: 8 # Downscale to 1 to fit in Nvidia T4 of the infra DEFAULT_EVAL_BSIZE = 1 def __init__(self, test, device, batch_size=None, extra_args=[]): super().__init__(name="hf_T5_large", test=test, device=device, batch_size=batch_size, extra_args=extra_args)
import subprocess import sys import os from torchbenchmark.util.framework.huggingface.patch_hf import patch_transformers, cache_model def pip_install_requirements(): subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-q', '-r', 'requirements.txt']) if __name__ == '__main__': pip_install_requirements() patch_transformers() model_name = os.path.basename(os.path.dirname(os.path.abspath(__file__))) cache_model(model_name)
from torchbenchmark.util.framework.vision.model_factory import TorchVisionModel from torchbenchmark.tasks import COMPUTER_VISION import torchvision.models as models class Model(TorchVisionModel): task = COMPUTER_VISION.CLASSIFICATION # Train batch size: use the smallest example batch of 128 (assuming only 1 worker) # Source: https://arxiv.org/pdf/1404.5997.pdf DEFAULT_TRAIN_BSIZE = 128 DEFAULT_EVAL_BSIZE = 128 def __init__(self, test, device, batch_size=None, extra_args=[]): super().__init__(model_name="alexnet", test=test, device=device, batch_size=batch_size, weights=models.AlexNet_Weights.IMAGENET1K_V1, extra_args=extra_args)
from torchbenchmark.util.model import BenchmarkModel from torchbenchmark.tasks import COMPUTER_VISION import torch.nn as nn import torch from types import SimpleNamespace import torch.utils.data as data class DenseLayer(nn.Module): def __init__(self, c_in, bn_size, growth_rate, act_fn): """ Inputs: c_in - Number of input channels bn_size - Bottleneck size (factor of growth rate) for the output of the 1x1 convolution. Typically between 2 and 4. growth_rate - Number of output channels of the 3x3 convolution act_fn - Activation class constructor (e.g. nn.ReLU) """ super().__init__() self.net = nn.Sequential( nn.BatchNorm2d(c_in), act_fn(), nn.Conv2d(c_in, bn_size * growth_rate, kernel_size=1, bias=False), nn.BatchNorm2d(bn_size * growth_rate), act_fn(), nn.Conv2d(bn_size * growth_rate, growth_rate, kernel_size=3, padding=1, bias=False) ) def forward(self, x): out = self.net(x) out = torch.cat([out, x], dim=1) return out class DenseBlock(nn.Module): def __init__(self, c_in, num_layers, bn_size, growth_rate, act_fn): """ Inputs: c_in - Number of input channels num_layers - Number of dense layers to apply in the block bn_size - Bottleneck size to use in the dense layers growth_rate - Growth rate to use in the dense layers act_fn - Activation function to use in the dense layers """ super().__init__() layers = [] for layer_idx in range(num_layers): layers.append( DenseLayer(c_in=c_in + layer_idx * growth_rate, # Input channels are original plus the feature maps from previous layers bn_size=bn_size, growth_rate=growth_rate, act_fn=act_fn) ) self.block = nn.Sequential(*layers) def forward(self, x): out = self.block(x) return out class TransitionLayer(nn.Module): def __init__(self, c_in, c_out, act_fn): super().__init__() self.transition = nn.Sequential( nn.BatchNorm2d(c_in), act_fn(), nn.Conv2d(c_in, c_out, kernel_size=1, bias=False), # Average the output for each 2x2 pixel group nn.AvgPool2d(kernel_size=2, stride=2) ) def forward(self, x): return self.transition(x) class DenseNet(nn.Module): def __init__(self, num_classes=10, num_layers=[6, 6, 6, 6], bn_size=2, growth_rate=16, act_fn_name="relu", **kwargs): super().__init__() act_fn_by_name = { "tanh": nn.Tanh, "relu": nn.ReLU, "leakyrelu": nn.LeakyReLU, "gelu": nn.GELU } self.hparams = SimpleNamespace(num_classes=num_classes, num_layers=num_layers, bn_size=bn_size, growth_rate=growth_rate, act_fn_name=act_fn_name, act_fn=act_fn_by_name[act_fn_name]) self._create_network() self._init_params() def _create_network(self): # The start number of hidden channels c_hidden = self.hparams.growth_rate * self.hparams.bn_size # A first convolution on the original image to scale up the channel size self.input_net = nn.Sequential( # No batch norm or activation function as done inside the Dense layers nn.Conv2d(3, c_hidden, kernel_size=3, padding=1) ) # Creating the dense blocks, eventually including transition layers blocks = [] for block_idx, num_layers in enumerate(self.hparams.num_layers): blocks.append( DenseBlock(c_in=c_hidden, num_layers=num_layers, bn_size=self.hparams.bn_size, growth_rate=self.hparams.growth_rate, act_fn=self.hparams.act_fn) ) # Overall output of the dense block c_hidden = c_hidden + num_layers * self.hparams.growth_rate # Don't apply transition layer on last block if block_idx < len(self.hparams.num_layers) - 1: blocks.append( TransitionLayer(c_in=c_hidden, c_out=c_hidden // 2, act_fn=self.hparams.act_fn)) c_hidden = c_hidden // 2 self.blocks = nn.Sequential(*blocks) # Mapping to classification output self.output_net = nn.Sequential( # The features have not passed a non-linearity until here. nn.BatchNorm2d(c_hidden), self.hparams.act_fn(), nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(), nn.Linear(c_hidden, self.hparams.num_classes) ) def _init_params(self): # Based on our discussion in Tutorial 4, we should initialize the convolutions according to the activation function for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_( m.weight, nonlinearity=self.hparams.act_fn_name) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) def forward(self, x): x = self.input_net(x) x = self.blocks(x) x = self.output_net(x) return x class Model(BenchmarkModel): task = COMPUTER_VISION.CLASSIFICATION # Source: https://github.com/phlippe/uvadlc_notebooks_benchmarking/blob/main/PyTorch/Tutorial5_Inception_ResNet_DenseNet.py DEFAULT_TRAIN_BSIZE = 128 DEFAULT_EVAL_BSIZE = 128 def __init__(self, test, device, batch_size=None, extra_args=[]): super().__init__(test=test, device=device, batch_size=batch_size, extra_args=extra_args) self.model = DenseNet() self.model.to(device) self.example_inputs = ( torch.randn((self.batch_size, 3, 32, 32), device=self.device), ) self.example_target = torch.randint(0, 10, (self.batch_size,), device=self.device) dataset = data.TensorDataset(self.example_inputs[0], self.example_target) dummy_loader = data.DataLoader(dataset, batch_size=self.batch_size) self.optimizer = torch.optim.AdamW(self.model.parameters(), lr=1e-3, weight_decay=1e-4) self.criterion = nn.CrossEntropyLoss() def get_module(self): return self.model, self.example_inputs def train(self): model = self.model (images, ) = self.example_inputs model.train() targets = self.example_target output = model(images) loss = self.criterion(output, targets) loss.backward() self.optimizer.step() self.optimizer.zero_grad() def eval(self): model = self.model (images, ) = self.example_inputs model.eval() with torch.no_grad(): out = model(images) return (out,)
from torchbenchmark.util.framework.timm.model_factory import TimmModel from torchbenchmark.tasks import COMPUTER_VISION class Model(TimmModel): task = COMPUTER_VISION.DETECTION DEFAULT_TRAIN_BSIZE = 32 DEFAULT_EVAL_BSIZE = 32 def __init__(self, test, device, batch_size=None, extra_args=[]): super().__init__(test=test, model_name='vovnet39a', device=device, batch_size=batch_size, extra_args=extra_args)
from torchbenchmark.tasks import NLP from torchbenchmark.util.framework.huggingface.model_factory import HuggingFaceModel class Model(HuggingFaceModel): task = NLP.LANGUAGE_MODELING DEFAULT_TRAIN_BSIZE = 2 DEFAULT_EVAL_BSIZE = 1 def __init__(self, test, device, batch_size=None, extra_args=[]): super().__init__(name="hf_Longformer", test=test, device=device, batch_size=batch_size, extra_args=extra_args)
import subprocess import sys import os from torchbenchmark.util.framework.huggingface.patch_hf import patch_transformers, cache_model def pip_install_requirements(): subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-q', '-r', 'requirements.txt']) if __name__ == '__main__': pip_install_requirements() patch_transformers() model_name = os.path.basename(os.path.dirname(os.path.abspath(__file__))) cache_model(model_name)
""" HuggingFace Stable Diffusion model. It requires users to specify "HUGGINGFACE_AUTH_TOKEN" in environment variable to authorize login and agree HuggingFace terms and conditions. """ from torchbenchmark.tasks import COMPUTER_VISION from torchbenchmark.util.model import BenchmarkModel from torchbenchmark.util.framework.huggingface.model_factory import HuggingFaceAuthMixin import torch from diffusers import StableDiffusionPipeline, EulerDiscreteScheduler class Model(BenchmarkModel, HuggingFaceAuthMixin): task = COMPUTER_VISION.GENERATION DEFAULT_TRAIN_BSIZE = 1 DEFAULT_EVAL_BSIZE = 1 ALLOW_CUSTOMIZE_BSIZE = False # Skip deepcopy because it will oom on A100 40GB DEEPCOPY = False # Default eval precision on CUDA device is fp16 DEFAULT_EVAL_CUDA_PRECISION = "fp16" def __init__(self, test, device, batch_size=None, extra_args=[]): HuggingFaceAuthMixin.__init__(self) super().__init__(test=test, device=device, batch_size=batch_size, extra_args=extra_args) model_id = "stabilityai/stable-diffusion-2" scheduler = EulerDiscreteScheduler.from_pretrained(model_id, subfolder="scheduler") self.pipe = StableDiffusionPipeline.from_pretrained(model_id, scheduler=scheduler) self.example_inputs = "a photo of an astronaut riding a horse on mars" self.pipe.to(self.device) def enable_fp16_half(self): pass def get_module(self): random_input = torch.randn(1, 4, 128, 128).to(self.device) timestep = torch.tensor([1.0]).to(self.device) encoder_hidden_states = torch.randn(1, 1, 1024).to(self.device) return self.pipe.unet, [random_input, timestep, encoder_hidden_states] def train(self): raise NotImplementedError("Train test is not implemented for the stable diffusion model.") def eval(self): image = self.pipe(self.example_inputs) return (image, )
from torchbenchmark.util.framework.diffusers import install_diffusers from torchbenchmark.util.framework.huggingface.model_factory import HuggingFaceAuthMixin import torch import os import warnings MODEL_NAME = "stabilityai/stable-diffusion-2" def load_model_checkpoint(): from diffusers import StableDiffusionPipeline StableDiffusionPipeline.from_pretrained(MODEL_NAME, torch_dtype=torch.float16, safety_checker=None) if __name__ == "__main__": if not 'HUGGING_FACE_HUB_TOKEN' in os.environ: warnings.warn("Make sure to set `HUGGINGFACE_HUB_TOKEN` so you can download weights") else: install_diffusers() load_model_checkpoint()
import os from torchbenchmark.tasks import COMPUTER_VISION from torchbenchmark.util.framework.detectron2.model_factory import Detectron2Model MODEL_NAME = os.path.basename(os.path.dirname(os.path.abspath(__file__))) MODEL_DIR = os.path.abspath(os.path.dirname(__file__)) class Model(Detectron2Model): task = COMPUTER_VISION.DETECTION model_file = os.path.join(MODEL_DIR, ".data", f"{MODEL_NAME}.pkl") def __init__(self, test, device, batch_size=None, extra_args=[]): super().__init__(variant="COCO-Detection/faster_rcnn_R_101_C4_3x.yaml", test=test, device=device, batch_size=batch_size, extra_args=extra_args)
import os from torchbenchmark.util.framework.detectron2 import install_detectron2 MODEL_NAME = os.path.basename(os.path.dirname(os.path.abspath(__file__))) MODEL_DIR = os.path.abspath(os.path.dirname(__file__)) if __name__ == '__main__': install_detectron2(MODEL_NAME, MODEL_DIR)
import matplotlib matplotlib.use("Agg") import matplotlib.pylab as plt import numpy as np def save_figure_to_numpy(fig): # save it to a numpy array. data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) return data def plot_alignment_to_numpy(alignment, info=None): fig, ax = plt.subplots(figsize=(6, 4)) im = ax.imshow(alignment, aspect='auto', origin='lower', interpolation='none') fig.colorbar(im, ax=ax) xlabel = 'Decoder timestep' if info is not None: xlabel += '\n\n' + info plt.xlabel(xlabel) plt.ylabel('Encoder timestep') plt.tight_layout() fig.canvas.draw() data = save_figure_to_numpy(fig) plt.close() return data def plot_spectrogram_to_numpy(spectrogram): fig, ax = plt.subplots(figsize=(12, 3)) im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation='none') plt.colorbar(im, ax=ax) plt.xlabel("Frames") plt.ylabel("Channels") plt.tight_layout() fig.canvas.draw() data = save_figure_to_numpy(fig) plt.close() return data def plot_gate_outputs_to_numpy(gate_targets, gate_outputs): fig, ax = plt.subplots(figsize=(12, 3)) ax.scatter(range(len(gate_targets)), gate_targets, alpha=0.5, color='green', marker='+', s=1, label='target') ax.scatter(range(len(gate_outputs)), gate_outputs, alpha=0.5, color='red', marker='.', s=1, label='predicted') plt.xlabel("Frames (Green target, Red predicted)") plt.ylabel("Gate State") plt.tight_layout() fig.canvas.draw() data = save_figure_to_numpy(fig) plt.close() return data
import os import time import argparse import math from numpy import finfo import torch from .distributed import apply_gradient_allreduce import torch.distributed as dist from torch.utils.data.distributed import DistributedSampler from torch.utils.data import DataLoader from .model import Tacotron2 from .data_utils import TextMelLoader, TextMelCollate from .loss_function import Tacotron2Loss # from hparams import create_hparams def reduce_tensor(tensor, n_gpus): rt = tensor.clone() dist.all_reduce(rt, op=dist.reduce_op.SUM) rt /= n_gpus return rt def init_distributed(hparams, n_gpus, rank, group_name): assert torch.cuda.is_available(), "Distributed mode requires CUDA." print("Initializing Distributed") # Set cuda device so everything is done on the right GPU. torch.cuda.set_device(rank % torch.cuda.device_count()) # Initialize distributed communication dist.init_process_group( backend=hparams.dist_backend, init_method=hparams.dist_url, world_size=n_gpus, rank=rank, group_name=group_name) print("Done initializing distributed") def prepare_dataloaders(hparams): # Get data, data loaders and collate function ready trainset = TextMelLoader(hparams.training_files, hparams) valset = TextMelLoader(hparams.validation_files, hparams) collate_fn = TextMelCollate(hparams.n_frames_per_step) if hparams.distributed_run: train_sampler = DistributedSampler(trainset) shuffle = False else: train_sampler = None shuffle = True train_loader = DataLoader(trainset, num_workers=0, shuffle=shuffle, sampler=train_sampler, batch_size=hparams.batch_size, pin_memory=False, drop_last=True, collate_fn=collate_fn) return train_loader, valset, collate_fn def prepare_directories_and_logger(output_directory, log_directory, rank): if rank == 0: if not os.path.isdir(output_directory): os.makedirs(output_directory) os.chmod(output_directory, 0o775) # logger = Tacotron2Logger(os.path.join(output_directory, log_directory)) logger = None else: logger = None return logger def load_model(hparams): model = Tacotron2(hparams).cuda() if hparams.fp16_run: model.decoder.attention_layer.score_mask_value = finfo('float16').min if hparams.distributed_run: model = apply_gradient_allreduce(model) return model def warm_start_model(checkpoint_path, model, ignore_layers): assert os.path.isfile(checkpoint_path) print("Warm starting model from checkpoint '{}'".format(checkpoint_path)) checkpoint_dict = torch.load(checkpoint_path, map_location='cpu') model_dict = checkpoint_dict['state_dict'] if len(ignore_layers) > 0: model_dict = {k: v for k, v in model_dict.items() if k not in ignore_layers} dummy_dict = model.state_dict() dummy_dict.update(model_dict) model_dict = dummy_dict model.load_state_dict(model_dict) return model def load_checkpoint(checkpoint_path, model, optimizer): assert os.path.isfile(checkpoint_path) print("Loading checkpoint '{}'".format(checkpoint_path)) checkpoint_dict = torch.load(checkpoint_path, map_location='cpu') model.load_state_dict(checkpoint_dict['state_dict']) optimizer.load_state_dict(checkpoint_dict['optimizer']) learning_rate = checkpoint_dict['learning_rate'] iteration = checkpoint_dict['iteration'] print("Loaded checkpoint '{}' from iteration {}" .format( checkpoint_path, iteration)) return model, optimizer, learning_rate, iteration def save_checkpoint(model, optimizer, learning_rate, iteration, filepath): print("Saving model and optimizer state at iteration {} to {}".format( iteration, filepath)) torch.save({'iteration': iteration, 'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict(), 'learning_rate': learning_rate}, filepath) def validate(model, criterion, valset, iteration, batch_size, n_gpus, collate_fn, logger, distributed_run, rank): """Handles all the validation scoring and printing""" model.eval() with torch.no_grad(): val_sampler = DistributedSampler(valset) if distributed_run else None val_loader = DataLoader(valset, sampler=val_sampler, num_workers=1, shuffle=False, batch_size=batch_size, pin_memory=False, collate_fn=collate_fn) val_loss = 0.0 for i, batch in enumerate(val_loader): x, y = model.parse_batch(batch) y_pred = model(x) loss = criterion(y_pred, y) if distributed_run: reduced_val_loss = reduce_tensor(loss.data, n_gpus).item() else: reduced_val_loss = loss.item() val_loss += reduced_val_loss val_loss = val_loss / (i + 1) model.train() if rank == 0: print("Validation loss {}: {:9f} ".format(iteration, val_loss)) logger.log_validation(val_loss, model, y, y_pred, iteration) def train(output_directory, log_directory, checkpoint_path, warm_start, n_gpus, rank, group_name, hparams): """Training and validation logging results to tensorboard and stdout Params ------ output_directory (string): directory to save checkpoints log_directory (string) directory to save tensorboard logs checkpoint_path(string): checkpoint path n_gpus (int): number of gpus rank (int): rank of current gpu hparams (object): comma separated list of "name=value" pairs. """ if hparams.distributed_run: init_distributed(hparams, n_gpus, rank, group_name) model = load_model(hparams) learning_rate = hparams.learning_rate optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=hparams.weight_decay) if hparams.fp16_run: from apex import amp model, optimizer = amp.initialize( model, optimizer, opt_level='O2') if hparams.distributed_run: model = apply_gradient_allreduce(model) criterion = Tacotron2Loss() logger = prepare_directories_and_logger( output_directory, log_directory, rank) train_loader, valset, collate_fn = prepare_dataloaders(hparams) # Load checkpoint if one exists iteration = 0 epoch_offset = 0 if checkpoint_path is not None: if warm_start: model = warm_start_model( checkpoint_path, model, hparams.ignore_layers) else: model, optimizer, _learning_rate, iteration = load_checkpoint( checkpoint_path, model, optimizer) if hparams.use_saved_learning_rate: learning_rate = _learning_rate iteration += 1 # next iteration is iteration + 1 epoch_offset = max(0, int(iteration / len(train_loader))) model.train() is_overflow = False # ================ MAIN TRAINNIG LOOP! =================== for epoch in range(epoch_offset, hparams.epochs): print("Epoch: {}".format(epoch)) for i, batch in enumerate(train_loader): start = time.perf_counter() for param_group in optimizer.param_groups: param_group['lr'] = learning_rate model.zero_grad() x, y = model.parse_batch(batch) y_pred = model(x) loss = criterion(y_pred, y) if hparams.distributed_run: reduced_loss = reduce_tensor(loss.data, n_gpus).item() else: reduced_loss = loss.item() if hparams.fp16_run: with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() else: loss.backward() if hparams.fp16_run: grad_norm = torch.nn.utils.clip_grad_norm_( amp.master_params(optimizer), hparams.grad_clip_thresh) is_overflow = math.isnan(grad_norm) else: grad_norm = torch.nn.utils.clip_grad_norm_( model.parameters(), hparams.grad_clip_thresh) optimizer.step() if not is_overflow and rank == 0: duration = time.perf_counter() - start print("Train loss {} {:.6f} Grad Norm {:.6f} {:.2f}s/it".format( iteration, reduced_loss, grad_norm, duration)) logger.log_training( reduced_loss, grad_norm, learning_rate, duration, iteration) if not is_overflow and (iteration % hparams.iters_per_checkpoint == 0): validate(model, criterion, valset, iteration, hparams.batch_size, n_gpus, collate_fn, logger, hparams.distributed_run, rank) if rank == 0: checkpoint_path = os.path.join( output_directory, "checkpoint_{}".format(iteration)) save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path) iteration += 1 if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-o', '--output_directory', type=str, help='directory to save checkpoints') parser.add_argument('-l', '--log_directory', type=str, help='directory to save tensorboard logs') parser.add_argument('-c', '--checkpoint_path', type=str, default=None, required=False, help='checkpoint path') parser.add_argument('--warm_start', action='store_true', help='load model weights only, ignore specified layers') parser.add_argument('--n_gpus', type=int, default=1, required=False, help='number of gpus') parser.add_argument('--rank', type=int, default=0, required=False, help='rank of current gpu') parser.add_argument('--group_name', type=str, default='group_name', required=False, help='Distributed group name') parser.add_argument('--hparams', type=str, required=False, help='comma separated name=value pairs') args = parser.parse_args() hparams = create_hparams(args.hparams) torch.backends.cudnn.enabled = hparams.cudnn_enabled torch.backends.cudnn.benchmark = hparams.cudnn_benchmark print("FP16 Run:", hparams.fp16_run) print("Dynamic Loss Scaling:", hparams.dynamic_loss_scaling) print("Distributed Run:", hparams.distributed_run) print("cuDNN Enabled:", hparams.cudnn_enabled) print("cuDNN Benchmark:", hparams.cudnn_benchmark) train(args.output_directory, args.log_directory, args.checkpoint_path, args.warm_start, args.n_gpus, args.rank, args.group_name, hparams)
import tensorflow as tf from text import symbols def create_hparams(hparams_string=None, verbose=False): """Create model hyperparameters. Parse nondefault from given string.""" hparams = tf.contrib.training.HParams( ################################ # Experiment Parameters # ################################ epochs=500, iters_per_checkpoint=1000, seed=1234, dynamic_loss_scaling=True, fp16_run=False, distributed_run=False, dist_backend="nccl", dist_url="tcp://localhost:54321", cudnn_enabled=True, cudnn_benchmark=False, ignore_layers=['embedding.weight'], ################################ # Data Parameters # ################################ load_mel_from_disk=False, training_files='filelists/ljs_audio_text_train_filelist.txt', validation_files='filelists/ljs_audio_text_val_filelist.txt', text_cleaners=['english_cleaners'], ################################ # Audio Parameters # ################################ max_wav_value=32768.0, sampling_rate=22050, filter_length=1024, hop_length=256, win_length=1024, n_mel_channels=80, mel_fmin=0.0, mel_fmax=8000.0, ################################ # Model Parameters # ################################ n_symbols=len(symbols), symbols_embedding_dim=512, # Encoder parameters encoder_kernel_size=5, encoder_n_convolutions=3, encoder_embedding_dim=512, # Decoder parameters n_frames_per_step=1, # currently only 1 is supported decoder_rnn_dim=1024, prenet_dim=256, max_decoder_steps=1000, gate_threshold=0.5, p_attention_dropout=0.1, p_decoder_dropout=0.1, # Attention parameters attention_rnn_dim=1024, attention_dim=128, # Location Layer parameters attention_location_n_filters=32, attention_location_kernel_size=31, # Mel-post processing network parameters postnet_embedding_dim=512, postnet_kernel_size=5, postnet_n_convolutions=5, ################################ # Optimization Hyperparameters # ################################ use_saved_learning_rate=False, learning_rate=1e-3, weight_decay=1e-6, grad_clip_thresh=1.0, batch_size=64, mask_padding=True # set model's padded outputs to padded values ) if hparams_string: tf.logging.info('Parsing command line hparams: %s', hparams_string) hparams.parse(hparams_string) if verbose: tf.logging.info('Final parsed hparams: %s', hparams.values()) return hparams
from .train_tacotron2 import load_model, prepare_dataloaders import torch from .loss_function import Tacotron2Loss from argparse import Namespace from .text import symbols from pathlib import Path from ...util.model import BenchmarkModel from typing import Tuple from contextlib import nullcontext from torchbenchmark.tasks import SPEECH class Model(BenchmarkModel): task = SPEECH.SYNTHESIS # Training batch size comes from the source code: # Source: https://github.com/NVIDIA/tacotron2/blob/bb6761349354ee914909a42208e4820929612069/hparams.py#L84 DEFAULT_TRAIN_BSIZE = 64 DEFAULT_EVAL_BSIZE = 64 # Tacotron2 CUDA inference test uses amp precision DEFAULT_EVAL_CUDA_PRECISION = "amp" def __init__(self, test, device, batch_size=None, extra_args=[]): super().__init__(test=test, device=device, batch_size=batch_size, extra_args=extra_args) if device == 'cpu': # TODO - currently load_model assumes cuda raise NotImplementedError("Tacotron2 doesn't support CPU because load_model assumes CUDA.") self.hparams = self.create_hparams(batch_size=self.batch_size) self.model = load_model(self.hparams).to(device=device) self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.hparams.learning_rate, weight_decay=self.hparams.weight_decay) self.criterion = Tacotron2Loss().to(device=device) loader, valset, collate_fn = prepare_dataloaders(self.hparams) self.example_inputs, self.target = self.model.parse_batch(next(iter(loader)), device=self.device) self.amp_context = nullcontext # Parameters were obtained from the source code. # Source: https://github.com/NVIDIA/tacotron2/blob/bb6761349354ee914909a42208e4820929612069/hparams.py#L5 def create_hparams(hparams_string=None, verbose=False, batch_size=64): """Create model hyperparameters. Parse nondefault from given string.""" root = str(Path(__file__).parent.parent.parent) hparams = Namespace(**{ ################################ # Experiment Parameters # ################################ 'epochs': 2, # Reduced in TorchBench to shorten number of train iterations. 'iters_per_checkpoint': 1000, 'dynamic_loss_scaling': True, 'fp16_run': False, 'distributed_run': False, 'dist_backend': "nccl", 'dist_url': "tcp://localhost:54321", 'cudnn_enabled': True, 'cudnn_benchmark': False, 'ignore_layers': ['embedding.weight'], ################################ # Data Parameters # ################################ 'load_mel_from_disk': False, 'training_files': f'{root}/data/.data/tacotron2-minimal/filelists/ljs_audio_text_train_filelist.txt', 'validation_files': f'{root}/data/.data/tacotron2-minimal/filelists/ljs_audio_text_val_filelist.txt', 'text_cleaners': ['english_cleaners'], ################################ # Audio Parameters # ################################ 'max_wav_value': 32768.0, 'sampling_rate': 22050, 'filter_length': 1024, 'hop_length': 256, 'win_length': 1024, 'n_mel_channels': 80, 'mel_fmin': 0.0, 'mel_fmax': 8000.0, ################################ # Model Parameters # ################################ 'n_symbols': len(symbols), 'symbols_embedding_dim': 512, # Encoder parameters 'encoder_kernel_size': 5, 'encoder_n_convolutions': 3, 'encoder_embedding_dim': 512, # Decoder parameters 'n_frames_per_step': 1, # currently only 1 is supported 'decoder_rnn_dim': 1024, 'prenet_dim': 256, 'max_decoder_steps': 1000, 'gate_threshold': 0.5, 'p_attention_dropout': 0.1, 'p_decoder_dropout': 0.1, # Attention parameters 'attention_rnn_dim': 1024, 'attention_dim': 128, # Location Layer parameters 'attention_location_n_filters': 32, 'attention_location_kernel_size': 31, # Mel-post processing network parameters 'postnet_embedding_dim': 512, 'postnet_kernel_size': 5, 'postnet_n_convolutions': 5, ################################ # Optimization Hyperparameters # ################################ 'use_saved_learning_rate': False, 'learning_rate': 1e-3, 'weight_decay': 1e-6, 'grad_clip_thresh': 1.0, 'batch_size': batch_size, 'mask_padding': True # set model's padded outputs to padded values }) return hparams def get_module(self): return self.model, (self.example_inputs,) def train(self): self.model.train() self.model.zero_grad() y_pred = self.model(self.example_inputs) loss = self.criterion(y_pred, self.target) loss.backward() self.optimizer.step() def eval(self) -> Tuple[torch.Tensor]: self.model.eval() with self.amp_context(): out = self.model(self.example_inputs) return out
import torch import numpy as np from scipy.signal import get_window import librosa.util as librosa_util def window_sumsquare(window, n_frames, hop_length=200, win_length=800, n_fft=800, dtype=np.float32, norm=None): """ # from librosa 0.6 Compute the sum-square envelope of a window function at a given hop length. This is used to estimate modulation effects induced by windowing observations in short-time fourier transforms. Parameters ---------- window : string, tuple, number, callable, or list-like Window specification, as in `get_window` n_frames : int > 0 The number of analysis frames hop_length : int > 0 The number of samples to advance between frames win_length : [optional] The length of the window function. By default, this matches `n_fft`. n_fft : int > 0 The length of each analysis frame. dtype : np.dtype The data type of the output Returns ------- wss : np.ndarray, shape=`(n_fft + hop_length * (n_frames - 1))` The sum-squared envelope of the window function """ if win_length is None: win_length = n_fft n = n_fft + hop_length * (n_frames - 1) x = np.zeros(n, dtype=dtype) # Compute the squared window at the desired length win_sq = get_window(window, win_length, fftbins=True) win_sq = librosa_util.normalize(win_sq, norm=norm)**2 win_sq = librosa_util.pad_center(win_sq, n_fft) # Fill the envelope for i in range(n_frames): sample = i * hop_length x[sample:min(n, sample + n_fft)] += win_sq[:max(0, min(n_fft, n - sample))] return x def griffin_lim(magnitudes, stft_fn, n_iters=30): """ PARAMS ------ magnitudes: spectrogram magnitudes stft_fn: STFT class with transform (STFT) and inverse (ISTFT) methods """ angles = np.angle(np.exp(2j * np.pi * np.random.rand(*magnitudes.size()))) angles = angles.astype(np.float32) angles = torch.autograd.Variable(torch.from_numpy(angles)) signal = stft_fn.inverse(magnitudes, angles).squeeze(1) for i in range(n_iters): _, angles = stft_fn.transform(signal) signal = stft_fn.inverse(magnitudes, angles).squeeze(1) return signal def dynamic_range_compression(x, C=1, clip_val=1e-5): """ PARAMS ------ C: compression factor """ return torch.log(torch.clamp(x, min=clip_val) * C) def dynamic_range_decompression(x, C=1): """ PARAMS ------ C: compression factor used to compress """ return torch.exp(x) / C
import random import torch from torch.utils.tensorboard import SummaryWriter from plotting_utils import plot_alignment_to_numpy, plot_spectrogram_to_numpy from plotting_utils import plot_gate_outputs_to_numpy class Tacotron2Logger(SummaryWriter): def __init__(self, logdir): super(Tacotron2Logger, self).__init__(logdir) def log_training(self, reduced_loss, grad_norm, learning_rate, duration, iteration): self.add_scalar("training.loss", reduced_loss, iteration) self.add_scalar("grad.norm", grad_norm, iteration) self.add_scalar("learning.rate", learning_rate, iteration) self.add_scalar("duration", duration, iteration) def log_validation(self, reduced_loss, model, y, y_pred, iteration): self.add_scalar("validation.loss", reduced_loss, iteration) _, mel_outputs, gate_outputs, alignments = y_pred mel_targets, gate_targets = y # plot distribution of parameters for tag, value in model.named_parameters(): tag = tag.replace('.', '/') self.add_histogram(tag, value.data.cpu().numpy(), iteration) # plot alignment, mel target and predicted, gate target and predicted idx = random.randint(0, alignments.size(0) - 1) self.add_image( "alignment", plot_alignment_to_numpy(alignments[idx].data.cpu().numpy().T), iteration, dataformats='HWC') self.add_image( "mel_target", plot_spectrogram_to_numpy(mel_targets[idx].data.cpu().numpy()), iteration, dataformats='HWC') self.add_image( "mel_predicted", plot_spectrogram_to_numpy(mel_outputs[idx].data.cpu().numpy()), iteration, dataformats='HWC') self.add_image( "gate", plot_gate_outputs_to_numpy( gate_targets[idx].data.cpu().numpy(), torch.sigmoid(gate_outputs[idx]).data.cpu().numpy()), iteration, dataformats='HWC')
from math import sqrt import torch from torch.autograd import Variable from torch import nn from torch.nn import functional as F from .layers import ConvNorm, LinearNorm from .tacotron2_utils import to_gpu, get_mask_from_lengths class LocationLayer(nn.Module): def __init__(self, attention_n_filters, attention_kernel_size, attention_dim): super(LocationLayer, self).__init__() padding = int((attention_kernel_size - 1) / 2) self.location_conv = ConvNorm(2, attention_n_filters, kernel_size=attention_kernel_size, padding=padding, bias=False, stride=1, dilation=1) self.location_dense = LinearNorm(attention_n_filters, attention_dim, bias=False, w_init_gain='tanh') def forward(self, attention_weights_cat): processed_attention = self.location_conv(attention_weights_cat) processed_attention = processed_attention.transpose(1, 2) processed_attention = self.location_dense(processed_attention) return processed_attention class Attention(nn.Module): def __init__(self, attention_rnn_dim, embedding_dim, attention_dim, attention_location_n_filters, attention_location_kernel_size): super(Attention, self).__init__() self.query_layer = LinearNorm(attention_rnn_dim, attention_dim, bias=False, w_init_gain='tanh') self.memory_layer = LinearNorm(embedding_dim, attention_dim, bias=False, w_init_gain='tanh') self.v = LinearNorm(attention_dim, 1, bias=False) self.location_layer = LocationLayer(attention_location_n_filters, attention_location_kernel_size, attention_dim) self.score_mask_value = -float("inf") def get_alignment_energies(self, query, processed_memory, attention_weights_cat): """ PARAMS ------ query: decoder output (batch, n_mel_channels * n_frames_per_step) processed_memory: processed encoder outputs (B, T_in, attention_dim) attention_weights_cat: cumulative and prev. att weights (B, 2, max_time) RETURNS ------- alignment (batch, max_time) """ processed_query = self.query_layer(query.unsqueeze(1)) processed_attention_weights = self.location_layer(attention_weights_cat) energies = self.v(torch.tanh( processed_query + processed_attention_weights + processed_memory)) energies = energies.squeeze(-1) return energies def forward(self, attention_hidden_state, memory, processed_memory, attention_weights_cat, mask): """ PARAMS ------ attention_hidden_state: attention rnn last output memory: encoder outputs processed_memory: processed encoder outputs attention_weights_cat: previous and cummulative attention weights mask: binary mask for padded data """ alignment = self.get_alignment_energies( attention_hidden_state, processed_memory, attention_weights_cat) if mask is not None: alignment.data.masked_fill_(mask, self.score_mask_value) attention_weights = F.softmax(alignment, dim=1) attention_context = torch.bmm(attention_weights.unsqueeze(1), memory) attention_context = attention_context.squeeze(1) return attention_context, attention_weights class Prenet(nn.Module): def __init__(self, in_dim, sizes): super(Prenet, self).__init__() in_sizes = [in_dim] + sizes[:-1] self.layers = nn.ModuleList( [LinearNorm(in_size, out_size, bias=False) for (in_size, out_size) in zip(in_sizes, sizes)]) def forward(self, x): for linear in self.layers: x = F.dropout(F.relu(linear(x)), p=0.5, training=True) return x class Postnet(nn.Module): """Postnet - Five 1-d convolution with 512 channels and kernel size 5 """ def __init__(self, hparams): super(Postnet, self).__init__() self.convolutions = nn.ModuleList() self.convolutions.append( nn.Sequential( ConvNorm(hparams.n_mel_channels, hparams.postnet_embedding_dim, kernel_size=hparams.postnet_kernel_size, stride=1, padding=int((hparams.postnet_kernel_size - 1) / 2), dilation=1, w_init_gain='tanh'), nn.BatchNorm1d(hparams.postnet_embedding_dim)) ) for i in range(1, hparams.postnet_n_convolutions - 1): self.convolutions.append( nn.Sequential( ConvNorm(hparams.postnet_embedding_dim, hparams.postnet_embedding_dim, kernel_size=hparams.postnet_kernel_size, stride=1, padding=int((hparams.postnet_kernel_size - 1) / 2), dilation=1, w_init_gain='tanh'), nn.BatchNorm1d(hparams.postnet_embedding_dim)) ) self.convolutions.append( nn.Sequential( ConvNorm(hparams.postnet_embedding_dim, hparams.n_mel_channels, kernel_size=hparams.postnet_kernel_size, stride=1, padding=int((hparams.postnet_kernel_size - 1) / 2), dilation=1, w_init_gain='linear'), nn.BatchNorm1d(hparams.n_mel_channels)) ) def forward(self, x): for i in range(len(self.convolutions) - 1): x = F.dropout(torch.tanh(self.convolutions[i](x)), 0.5, self.training) x = F.dropout(self.convolutions[-1](x), 0.5, self.training) return x class Encoder(nn.Module): """Encoder module: - Three 1-d convolution banks - Bidirectional LSTM """ def __init__(self, hparams): super(Encoder, self).__init__() convolutions = [] for _ in range(hparams.encoder_n_convolutions): conv_layer = nn.Sequential( ConvNorm(hparams.encoder_embedding_dim, hparams.encoder_embedding_dim, kernel_size=hparams.encoder_kernel_size, stride=1, padding=int((hparams.encoder_kernel_size - 1) / 2), dilation=1, w_init_gain='relu'), nn.BatchNorm1d(hparams.encoder_embedding_dim)) convolutions.append(conv_layer) self.convolutions = nn.ModuleList(convolutions) self.lstm = nn.LSTM(hparams.encoder_embedding_dim, int(hparams.encoder_embedding_dim / 2), 1, batch_first=True, bidirectional=True) def forward(self, x, input_lengths): for conv in self.convolutions: x = F.dropout(F.relu(conv(x)), 0.5, self.training) x = x.transpose(1, 2) # pytorch tensor are not reversible, hence the conversion input_lengths = input_lengths.cpu().numpy() x = nn.utils.rnn.pack_padded_sequence( x, input_lengths, batch_first=True) self.lstm.flatten_parameters() outputs, _ = self.lstm(x) outputs, _ = nn.utils.rnn.pad_packed_sequence( outputs, batch_first=True) return outputs def inference(self, x): for conv in self.convolutions: x = F.dropout(F.relu(conv(x)), 0.5, self.training) x = x.transpose(1, 2) self.lstm.flatten_parameters() outputs, _ = self.lstm(x) return outputs class Decoder(nn.Module): def __init__(self, hparams): super(Decoder, self).__init__() self.n_mel_channels = hparams.n_mel_channels self.n_frames_per_step = hparams.n_frames_per_step self.encoder_embedding_dim = hparams.encoder_embedding_dim self.attention_rnn_dim = hparams.attention_rnn_dim self.decoder_rnn_dim = hparams.decoder_rnn_dim self.prenet_dim = hparams.prenet_dim self.max_decoder_steps = hparams.max_decoder_steps self.gate_threshold = hparams.gate_threshold self.p_attention_dropout = hparams.p_attention_dropout self.p_decoder_dropout = hparams.p_decoder_dropout self.prenet = Prenet( hparams.n_mel_channels * hparams.n_frames_per_step, [hparams.prenet_dim, hparams.prenet_dim]) self.attention_rnn = nn.LSTMCell( hparams.prenet_dim + hparams.encoder_embedding_dim, hparams.attention_rnn_dim) self.attention_layer = Attention( hparams.attention_rnn_dim, hparams.encoder_embedding_dim, hparams.attention_dim, hparams.attention_location_n_filters, hparams.attention_location_kernel_size) self.decoder_rnn = nn.LSTMCell( hparams.attention_rnn_dim + hparams.encoder_embedding_dim, hparams.decoder_rnn_dim, 1) self.linear_projection = LinearNorm( hparams.decoder_rnn_dim + hparams.encoder_embedding_dim, hparams.n_mel_channels * hparams.n_frames_per_step) self.gate_layer = LinearNorm( hparams.decoder_rnn_dim + hparams.encoder_embedding_dim, 1, bias=True, w_init_gain='sigmoid') def get_go_frame(self, memory): """ Gets all zeros frames to use as first decoder input PARAMS ------ memory: decoder outputs RETURNS ------- decoder_input: all zeros frames """ B = memory.size(0) decoder_input = Variable(memory.data.new( B, self.n_mel_channels * self.n_frames_per_step).zero_()) return decoder_input def initialize_decoder_states(self, memory, mask): """ Initializes attention rnn states, decoder rnn states, attention weights, attention cumulative weights, attention context, stores memory and stores processed memory PARAMS ------ memory: Encoder outputs mask: Mask for padded data if training, expects None for inference """ B = memory.size(0) MAX_TIME = memory.size(1) self.attention_hidden = Variable(memory.data.new( B, self.attention_rnn_dim).zero_()) self.attention_cell = Variable(memory.data.new( B, self.attention_rnn_dim).zero_()) self.decoder_hidden = Variable(memory.data.new( B, self.decoder_rnn_dim).zero_()) self.decoder_cell = Variable(memory.data.new( B, self.decoder_rnn_dim).zero_()) self.attention_weights = Variable(memory.data.new( B, MAX_TIME).zero_()) self.attention_weights_cum = Variable(memory.data.new( B, MAX_TIME).zero_()) self.attention_context = Variable(memory.data.new( B, self.encoder_embedding_dim).zero_()) self.memory = memory self.processed_memory = self.attention_layer.memory_layer(memory) self.mask = mask def parse_decoder_inputs(self, decoder_inputs): """ Prepares decoder inputs, i.e. mel outputs PARAMS ------ decoder_inputs: inputs used for teacher-forced training, i.e. mel-specs RETURNS ------- inputs: processed decoder inputs """ # (B, n_mel_channels, T_out) -> (B, T_out, n_mel_channels) decoder_inputs = decoder_inputs.transpose(1, 2) decoder_inputs = decoder_inputs.view( decoder_inputs.size(0), int(decoder_inputs.size(1)/self.n_frames_per_step), -1) # (B, T_out, n_mel_channels) -> (T_out, B, n_mel_channels) decoder_inputs = decoder_inputs.transpose(0, 1) return decoder_inputs def parse_decoder_outputs(self, mel_outputs, gate_outputs, alignments): """ Prepares decoder outputs for output PARAMS ------ mel_outputs: gate_outputs: gate output energies alignments: RETURNS ------- mel_outputs: gate_outpust: gate output energies alignments: """ # (T_out, B) -> (B, T_out) alignments = torch.stack(alignments).transpose(0, 1) # (T_out, B) -> (B, T_out) gate_outputs = torch.stack(gate_outputs).transpose(0, 1) gate_outputs = gate_outputs.contiguous() # (T_out, B, n_mel_channels) -> (B, T_out, n_mel_channels) mel_outputs = torch.stack(mel_outputs).transpose(0, 1).contiguous() # decouple frames per step mel_outputs = mel_outputs.view( mel_outputs.size(0), -1, self.n_mel_channels) # (B, T_out, n_mel_channels) -> (B, n_mel_channels, T_out) mel_outputs = mel_outputs.transpose(1, 2) return mel_outputs, gate_outputs, alignments def decode(self, decoder_input): """ Decoder step using stored states, attention and memory PARAMS ------ decoder_input: previous mel output RETURNS ------- mel_output: gate_output: gate output energies attention_weights: """ cell_input = torch.cat((decoder_input, self.attention_context), -1) self.attention_hidden, self.attention_cell = self.attention_rnn( cell_input, (self.attention_hidden, self.attention_cell)) self.attention_hidden = F.dropout( self.attention_hidden, self.p_attention_dropout, self.training) attention_weights_cat = torch.cat( (self.attention_weights.unsqueeze(1), self.attention_weights_cum.unsqueeze(1)), dim=1) self.attention_context, self.attention_weights = self.attention_layer( self.attention_hidden, self.memory, self.processed_memory, attention_weights_cat, self.mask) self.attention_weights_cum += self.attention_weights decoder_input = torch.cat( (self.attention_hidden, self.attention_context), -1) self.decoder_hidden, self.decoder_cell = self.decoder_rnn( decoder_input, (self.decoder_hidden, self.decoder_cell)) self.decoder_hidden = F.dropout( self.decoder_hidden, self.p_decoder_dropout, self.training) decoder_hidden_attention_context = torch.cat( (self.decoder_hidden, self.attention_context), dim=1) decoder_output = self.linear_projection( decoder_hidden_attention_context) gate_prediction = self.gate_layer(decoder_hidden_attention_context) return decoder_output, gate_prediction, self.attention_weights def forward(self, memory, decoder_inputs, memory_lengths): """ Decoder forward pass for training PARAMS ------ memory: Encoder outputs decoder_inputs: Decoder inputs for teacher forcing. i.e. mel-specs memory_lengths: Encoder output lengths for attention masking. RETURNS ------- mel_outputs: mel outputs from the decoder gate_outputs: gate outputs from the decoder alignments: sequence of attention weights from the decoder """ decoder_input = self.get_go_frame(memory).unsqueeze(0) decoder_inputs = self.parse_decoder_inputs(decoder_inputs) decoder_inputs = torch.cat((decoder_input, decoder_inputs), dim=0) decoder_inputs = self.prenet(decoder_inputs) self.initialize_decoder_states( memory, mask=~get_mask_from_lengths(memory_lengths)) mel_outputs, gate_outputs, alignments = [], [], [] while len(mel_outputs) < decoder_inputs.size(0) - 1: decoder_input = decoder_inputs[len(mel_outputs)] mel_output, gate_output, attention_weights = self.decode( decoder_input) mel_outputs += [mel_output.squeeze(1)] gate_outputs += [gate_output.squeeze(1)] alignments += [attention_weights] mel_outputs, gate_outputs, alignments = self.parse_decoder_outputs( mel_outputs, gate_outputs, alignments) return mel_outputs, gate_outputs, alignments def inference(self, memory): """ Decoder inference PARAMS ------ memory: Encoder outputs RETURNS ------- mel_outputs: mel outputs from the decoder gate_outputs: gate outputs from the decoder alignments: sequence of attention weights from the decoder """ decoder_input = self.get_go_frame(memory) self.initialize_decoder_states(memory, mask=None) mel_outputs, gate_outputs, alignments = [], [], [] while True: decoder_input = self.prenet(decoder_input) mel_output, gate_output, alignment = self.decode(decoder_input) mel_outputs += [mel_output.squeeze(1)] gate_outputs += [gate_output] alignments += [alignment] if torch.sigmoid(gate_output.data) > self.gate_threshold: break elif len(mel_outputs) == self.max_decoder_steps: print("Warning! Reached max decoder steps") break decoder_input = mel_output mel_outputs, gate_outputs, alignments = self.parse_decoder_outputs( mel_outputs, gate_outputs, alignments) return mel_outputs, gate_outputs, alignments class Tacotron2(nn.Module): def __init__(self, hparams): super(Tacotron2, self).__init__() self.mask_padding = hparams.mask_padding self.fp16_run = hparams.fp16_run self.n_mel_channels = hparams.n_mel_channels self.n_frames_per_step = hparams.n_frames_per_step self.embedding = nn.Embedding( hparams.n_symbols, hparams.symbols_embedding_dim) std = sqrt(2.0 / (hparams.n_symbols + hparams.symbols_embedding_dim)) val = sqrt(3.0) * std # uniform bounds for std self.embedding.weight.data.uniform_(-val, val) self.encoder = Encoder(hparams) self.decoder = Decoder(hparams) self.postnet = Postnet(hparams) def parse_batch(self, batch, device='cuda'): text_padded, input_lengths, mel_padded, gate_padded, \ output_lengths = batch text_padded = text_padded.to(device).long() input_lengths = input_lengths.to(device).long() max_len = torch.max(input_lengths.data).item() mel_padded = mel_padded.to(device).float() gate_padded = gate_padded.to(device).float() output_lengths = output_lengths.to(device).long() return ( (text_padded, input_lengths, mel_padded, max_len, output_lengths), (mel_padded, gate_padded)) def parse_output(self, outputs, output_lengths=None): if self.mask_padding and output_lengths is not None: mask = ~get_mask_from_lengths(output_lengths) mask = mask.expand(self.n_mel_channels, mask.size(0), mask.size(1)) mask = mask.permute(1, 0, 2) outputs[0].data.masked_fill_(mask, 0.0) outputs[1].data.masked_fill_(mask, 0.0) outputs[2].data.masked_fill_(mask[:, 0, :], 1e3) # gate energies return outputs def forward(self, inputs): text_inputs, text_lengths, mels, max_len, output_lengths = inputs text_lengths, output_lengths = text_lengths.data, output_lengths.data embedded_inputs = self.embedding(text_inputs).transpose(1, 2) encoder_outputs = self.encoder(embedded_inputs, text_lengths) mel_outputs, gate_outputs, alignments = self.decoder( encoder_outputs, mels, memory_lengths=text_lengths) mel_outputs_postnet = self.postnet(mel_outputs) mel_outputs_postnet = mel_outputs + mel_outputs_postnet return self.parse_output( [mel_outputs, mel_outputs_postnet, gate_outputs, alignments], output_lengths) def inference(self, inputs): embedded_inputs = self.embedding(inputs).transpose(1, 2) encoder_outputs = self.encoder.inference(embedded_inputs) mel_outputs, gate_outputs, alignments = self.decoder.inference( encoder_outputs) mel_outputs_postnet = self.postnet(mel_outputs) mel_outputs_postnet = mel_outputs + mel_outputs_postnet outputs = self.parse_output( [mel_outputs, mel_outputs_postnet, gate_outputs, alignments]) return outputs
""" BSD 3-Clause License Copyright (c) 2017, Prem Seetharaman All rights reserved. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import torch import numpy as np import torch.nn.functional as F from torch.autograd import Variable from scipy.signal import get_window from librosa.util import pad_center, tiny from .audio_processing import window_sumsquare class STFT(torch.nn.Module): """adapted from Prem Seetharaman's https://github.com/pseeth/pytorch-stft""" def __init__(self, filter_length=800, hop_length=200, win_length=800, window='hann'): super(STFT, self).__init__() self.filter_length = filter_length self.hop_length = hop_length self.win_length = win_length self.window = window self.forward_transform = None scale = self.filter_length / self.hop_length fourier_basis = np.fft.fft(np.eye(self.filter_length)) cutoff = int((self.filter_length / 2 + 1)) fourier_basis = np.vstack([np.real(fourier_basis[:cutoff, :]), np.imag(fourier_basis[:cutoff, :])]) forward_basis = torch.FloatTensor(fourier_basis[:, None, :]) inverse_basis = torch.FloatTensor( np.linalg.pinv(scale * fourier_basis).T[:, None, :]) if window is not None: assert(filter_length >= win_length) # get window and zero center pad it to filter_length fft_window = get_window(window, win_length, fftbins=True) fft_window = pad_center(fft_window, filter_length) fft_window = torch.from_numpy(fft_window).float() # window the bases forward_basis *= fft_window inverse_basis *= fft_window self.register_buffer('forward_basis', forward_basis.float()) self.register_buffer('inverse_basis', inverse_basis.float()) def transform(self, input_data): num_batches = input_data.size(0) num_samples = input_data.size(1) self.num_samples = num_samples # similar to librosa, reflect-pad the input input_data = input_data.view(num_batches, 1, num_samples) input_data = F.pad( input_data.unsqueeze(1), (int(self.filter_length / 2), int(self.filter_length / 2), 0, 0), mode='reflect') input_data = input_data.squeeze(1) forward_transform = F.conv1d( input_data, Variable(self.forward_basis, requires_grad=False), stride=self.hop_length, padding=0) cutoff = int((self.filter_length / 2) + 1) real_part = forward_transform[:, :cutoff, :] imag_part = forward_transform[:, cutoff:, :] magnitude = torch.sqrt(real_part**2 + imag_part**2) phase = torch.autograd.Variable( torch.atan2(imag_part.data, real_part.data)) return magnitude, phase def inverse(self, magnitude, phase): recombine_magnitude_phase = torch.cat( [magnitude*torch.cos(phase), magnitude*torch.sin(phase)], dim=1) inverse_transform = F.conv_transpose1d( recombine_magnitude_phase, Variable(self.inverse_basis, requires_grad=False), stride=self.hop_length, padding=0) if self.window is not None: window_sum = window_sumsquare( self.window, magnitude.size(-1), hop_length=self.hop_length, win_length=self.win_length, n_fft=self.filter_length, dtype=np.float32) # remove modulation effects approx_nonzero_indices = torch.from_numpy( np.where(window_sum > tiny(window_sum))[0]) window_sum = torch.autograd.Variable( torch.from_numpy(window_sum), requires_grad=False) window_sum = window_sum.cuda() if magnitude.is_cuda else window_sum inverse_transform[:, :, approx_nonzero_indices] /= window_sum[approx_nonzero_indices] # scale by hop ratio inverse_transform *= float(self.filter_length) / self.hop_length inverse_transform = inverse_transform[:, :, int(self.filter_length/2):] inverse_transform = inverse_transform[:, :, :-int(self.filter_length/2):] return inverse_transform def forward(self, input_data): self.magnitude, self.phase = self.transform(input_data) reconstruction = self.inverse(self.magnitude, self.phase) return reconstruction
import torch import torch.distributed as dist from torch.nn.modules import Module from torch.autograd import Variable def _flatten_dense_tensors(tensors): """Flatten dense tensors into a contiguous 1D buffer. Assume tensors are of same dense type. Since inputs are dense, the resulting tensor will be a concatenated 1D buffer. Element-wise operation on this buffer will be equivalent to operating individually. Arguments: tensors (Iterable[Tensor]): dense tensors to flatten. Returns: A contiguous 1D buffer containing input tensors. """ if len(tensors) == 1: return tensors[0].contiguous().view(-1) flat = torch.cat([t.contiguous().view(-1) for t in tensors], dim=0) return flat def _unflatten_dense_tensors(flat, tensors): """View a flat buffer using the sizes of tensors. Assume that tensors are of same dense type, and that flat is given by _flatten_dense_tensors. Arguments: flat (Tensor): flattened dense tensors to unflatten. tensors (Iterable[Tensor]): dense tensors whose sizes will be used to unflatten flat. Returns: Unflattened dense tensors with sizes same as tensors and values from flat. """ outputs = [] offset = 0 for tensor in tensors: numel = tensor.numel() outputs.append(flat.narrow(0, offset, numel).view_as(tensor)) offset += numel return tuple(outputs) ''' This version of DistributedDataParallel is designed to be used in conjunction with the multiproc.py launcher included with this example. It assumes that your run is using multiprocess with 1 GPU/process, that the model is on the correct device, and that torch.set_device has been used to set the device. Parameters are broadcasted to the other processes on initialization of DistributedDataParallel, and will be allreduced at the finish of the backward pass. ''' class DistributedDataParallel(Module): def __init__(self, module): super(DistributedDataParallel, self).__init__() #fallback for PyTorch 0.3 if not hasattr(dist, '_backend'): self.warn_on_half = True else: self.warn_on_half = True if dist._backend == dist.dist_backend.GLOO else False self.module = module for p in self.module.state_dict().values(): if not torch.is_tensor(p): continue dist.broadcast(p, 0) def allreduce_params(): if(self.needs_reduction): self.needs_reduction = False buckets = {} for param in self.module.parameters(): if param.requires_grad and param.grad is not None: tp = type(param.data) if tp not in buckets: buckets[tp] = [] buckets[tp].append(param) if self.warn_on_half: if torch.cuda.HalfTensor in buckets: print("WARNING: gloo dist backend for half parameters may be extremely slow." + " It is recommended to use the NCCL backend in this case. This currently requires" + "PyTorch built from top of tree master.") self.warn_on_half = False for tp in buckets: bucket = buckets[tp] grads = [param.grad.data for param in bucket] coalesced = _flatten_dense_tensors(grads) dist.all_reduce(coalesced) coalesced /= dist.get_world_size() for buf, synced in zip(grads, _unflatten_dense_tensors(coalesced, grads)): buf.copy_(synced) for param in list(self.module.parameters()): def allreduce_hook(*unused): param._execution_engine.queue_callback(allreduce_params) if param.requires_grad: param.register_hook(allreduce_hook) def forward(self, *inputs, **kwargs): self.needs_reduction = True return self.module(*inputs, **kwargs) ''' def _sync_buffers(self): buffers = list(self.module._all_buffers()) if len(buffers) > 0: # cross-node buffer sync flat_buffers = _flatten_dense_tensors(buffers) dist.broadcast(flat_buffers, 0) for buf, synced in zip(buffers, _unflatten_dense_tensors(flat_buffers, buffers)): buf.copy_(synced) def train(self, mode=True): # Clear NCCL communicator and CUDA event cache of the default group ID, # These cache will be recreated at the later call. This is currently a # work-around for a potential NCCL deadlock. if dist._backend == dist.dist_backend.NCCL: dist._clear_group_cache() super(DistributedDataParallel, self).train(mode) self.module.train(mode) ''' ''' Modifies existing model to do gradient allreduce, but doesn't change class so you don't need "module" ''' def apply_gradient_allreduce(module): if not hasattr(dist, '_backend'): module.warn_on_half = True else: module.warn_on_half = True if dist._backend == dist.dist_backend.GLOO else False for p in module.state_dict().values(): if not torch.is_tensor(p): continue dist.broadcast(p, 0) def allreduce_params(): if(module.needs_reduction): module.needs_reduction = False buckets = {} for param in module.parameters(): if param.requires_grad and param.grad is not None: tp = param.data.dtype if tp not in buckets: buckets[tp] = [] buckets[tp].append(param) if module.warn_on_half: if torch.cuda.HalfTensor in buckets: print("WARNING: gloo dist backend for half parameters may be extremely slow." + " It is recommended to use the NCCL backend in this case. This currently requires" + "PyTorch built from top of tree master.") module.warn_on_half = False for tp in buckets: bucket = buckets[tp] grads = [param.grad.data for param in bucket] coalesced = _flatten_dense_tensors(grads) dist.all_reduce(coalesced) coalesced /= dist.get_world_size() for buf, synced in zip(grads, _unflatten_dense_tensors(coalesced, grads)): buf.copy_(synced) for param in list(module.parameters()): def allreduce_hook(*unused): Variable._execution_engine.queue_callback(allreduce_params) if param.requires_grad: param.register_hook(allreduce_hook) def set_needs_reduction(self, input, output): self.needs_reduction = True module.register_forward_hook(set_needs_reduction) return module
import random import numpy as np import torch import torch.utils.data from .layers import TacotronSTFT from .tacotron2_utils import load_wav_to_torch, load_filepaths_and_text from .text import text_to_sequence class TextMelLoader(torch.utils.data.Dataset): """ 1) loads audio,text pairs 2) normalizes text and converts them to sequences of one-hot vectors 3) computes mel-spectrograms from audio files. """ def __init__(self, audiopaths_and_text, hparams): self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text) self.text_cleaners = hparams.text_cleaners self.max_wav_value = hparams.max_wav_value self.sampling_rate = hparams.sampling_rate self.load_mel_from_disk = hparams.load_mel_from_disk self.stft = TacotronSTFT( hparams.filter_length, hparams.hop_length, hparams.win_length, hparams.n_mel_channels, hparams.sampling_rate, hparams.mel_fmin, hparams.mel_fmax) random.shuffle(self.audiopaths_and_text) def get_mel_text_pair(self, audiopath_and_text): # separate filename and text audiopath, text = audiopath_and_text[0], audiopath_and_text[1] text = self.get_text(text) mel = self.get_mel(audiopath) return (text, mel) def get_mel(self, filename): if not self.load_mel_from_disk: audio, sampling_rate = load_wav_to_torch(filename) if sampling_rate != self.stft.sampling_rate: raise ValueError("{} {} SR doesn't match target {} SR".format( sampling_rate, self.stft.sampling_rate)) audio_norm = audio / self.max_wav_value audio_norm = audio_norm.unsqueeze(0) audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False) melspec = self.stft.mel_spectrogram(audio_norm) melspec = torch.squeeze(melspec, 0) else: melspec = torch.from_numpy(np.load(filename)) assert melspec.size(0) == self.stft.n_mel_channels, ( 'Mel dimension mismatch: given {}, expected {}'.format( melspec.size(0), self.stft.n_mel_channels)) return melspec def get_text(self, text): text_norm = torch.IntTensor(text_to_sequence(text, self.text_cleaners)) return text_norm def __getitem__(self, index): return self.get_mel_text_pair(self.audiopaths_and_text[index]) def __len__(self): return len(self.audiopaths_and_text) class TextMelCollate(): """ Zero-pads model inputs and targets based on number of frames per setep """ def __init__(self, n_frames_per_step): self.n_frames_per_step = n_frames_per_step def __call__(self, batch): """Collate's training batch from normalized text and mel-spectrogram PARAMS ------ batch: [text_normalized, mel_normalized] """ # Right zero-pad all one-hot text sequences to max input length input_lengths, ids_sorted_decreasing = torch.sort( torch.LongTensor([len(x[0]) for x in batch]), dim=0, descending=True) max_input_len = input_lengths[0] text_padded = torch.LongTensor(len(batch), max_input_len) text_padded.zero_() for i in range(len(ids_sorted_decreasing)): text = batch[ids_sorted_decreasing[i]][0] text_padded[i, :text.size(0)] = text # Right zero-pad mel-spec num_mels = batch[0][1].size(0) max_target_len = max([x[1].size(1) for x in batch]) if max_target_len % self.n_frames_per_step != 0: max_target_len += self.n_frames_per_step - max_target_len % self.n_frames_per_step assert max_target_len % self.n_frames_per_step == 0 # include mel padded and gate padded mel_padded = torch.FloatTensor(len(batch), num_mels, max_target_len) mel_padded.zero_() gate_padded = torch.FloatTensor(len(batch), max_target_len) gate_padded.zero_() output_lengths = torch.LongTensor(len(batch)) for i in range(len(ids_sorted_decreasing)): mel = batch[ids_sorted_decreasing[i]][1] mel_padded[i, :, :mel.size(1)] = mel gate_padded[i, mel.size(1)-1:] = 1 output_lengths[i] = mel.size(1) return text_padded, input_lengths, mel_padded, gate_padded, \ output_lengths
from torch import nn class Tacotron2Loss(nn.Module): def __init__(self): super(Tacotron2Loss, self).__init__() def forward(self, model_output, targets): mel_target, gate_target = targets[0], targets[1] mel_target.requires_grad = False gate_target.requires_grad = False gate_target = gate_target.view(-1, 1) mel_out, mel_out_postnet, gate_out, _ = model_output gate_out = gate_out.view(-1, 1) mel_loss = nn.MSELoss()(mel_out, mel_target) + \ nn.MSELoss()(mel_out_postnet, mel_target) gate_loss = nn.BCEWithLogitsLoss()(gate_out, gate_target) return mel_loss + gate_loss
import os from pathlib import Path import subprocess import sys from utils import s3_utils def check_data_dir(): current_dir = Path(os.path.dirname(os.path.realpath(__file__))) tacotron2_data_dir = os.path.join(current_dir.parent.parent, "data", ".data", "tacotron2-minimal") assert os.path.exists(tacotron2_data_dir), "Couldn't find tacotron2 minimal data dir, please run install.py again." def pip_install_requirements(): subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-q', '-r', 'requirements.txt']) if __name__ == '__main__': pip_install_requirements() s3_utils.checkout_s3_data("INPUT_TARBALLS", "tacotron2-minimal.tar.gz", decompress=True)
import torch from librosa.filters import mel as librosa_mel_fn from .audio_processing import dynamic_range_compression from .audio_processing import dynamic_range_decompression from .stft import STFT class LinearNorm(torch.nn.Module): def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'): super(LinearNorm, self).__init__() self.linear_layer = torch.nn.Linear(in_dim, out_dim, bias=bias) torch.nn.init.xavier_uniform_( self.linear_layer.weight, gain=torch.nn.init.calculate_gain(w_init_gain)) def forward(self, x): return self.linear_layer(x) class ConvNorm(torch.nn.Module): def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=None, dilation=1, bias=True, w_init_gain='linear'): super(ConvNorm, self).__init__() if padding is None: assert(kernel_size % 2 == 1) padding = int(dilation * (kernel_size - 1) / 2) self.conv = torch.nn.Conv1d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, bias=bias) torch.nn.init.xavier_uniform_( self.conv.weight, gain=torch.nn.init.calculate_gain(w_init_gain)) def forward(self, signal): conv_signal = self.conv(signal) return conv_signal class TacotronSTFT(torch.nn.Module): def __init__(self, filter_length=1024, hop_length=256, win_length=1024, n_mel_channels=80, sampling_rate=22050, mel_fmin=0.0, mel_fmax=8000.0): super(TacotronSTFT, self).__init__() self.n_mel_channels = n_mel_channels self.sampling_rate = sampling_rate self.stft_fn = STFT(filter_length, hop_length, win_length) mel_basis = librosa_mel_fn( sampling_rate, filter_length, n_mel_channels, mel_fmin, mel_fmax) mel_basis = torch.from_numpy(mel_basis).float() self.register_buffer('mel_basis', mel_basis) def spectral_normalize(self, magnitudes): output = dynamic_range_compression(magnitudes) return output def spectral_de_normalize(self, magnitudes): output = dynamic_range_decompression(magnitudes) return output def mel_spectrogram(self, y): """Computes mel-spectrograms from a batch of waves PARAMS ------ y: Variable(torch.FloatTensor) with shape (B, T) in range [-1, 1] RETURNS ------- mel_output: torch.FloatTensor of shape (B, n_mel_channels, T) """ assert(torch.min(y.data) >= -1) assert(torch.max(y.data) <= 1) magnitudes, phases = self.stft_fn.transform(y) magnitudes = magnitudes.data mel_output = torch.matmul(self.mel_basis, magnitudes) mel_output = self.spectral_normalize(mel_output) return mel_output
import time import torch import sys import subprocess argslist = list(sys.argv)[1:] num_gpus = torch.cuda.device_count() argslist.append('--n_gpus={}'.format(num_gpus)) workers = [] job_id = time.strftime("%Y_%m_%d-%H%M%S") argslist.append("--group_name=group_{}".format(job_id)) for i in range(num_gpus): argslist.append('--rank={}'.format(i)) stdout = None if i == 0 else open("logs/{}_GPU_{}.log".format(job_id, i), "w") print(argslist) p = subprocess.Popen([str(sys.executable)]+argslist, stdout=stdout) workers.append(p) argslist = argslist[:-1] for p in workers: p.wait()
import numpy as np from scipy.io.wavfile import read import torch from pathlib import Path def get_mask_from_lengths(lengths): max_len = torch.max(lengths).item() ids = torch.arange(0, max_len, device=lengths.device) mask = (ids < lengths.unsqueeze(1)).bool() return mask def load_wav_to_torch(full_path): sampling_rate, data = read(full_path) return torch.FloatTensor(data.astype(np.float32)), sampling_rate def load_filepaths_and_text(filename, split="|"): root = str(Path(__file__).parent) with open(filename, encoding='utf-8') as f: filepaths_and_text = [] for line in f: filename, *text = line.strip().split(split) filename = f'{root}/{filename}' filepaths_and_text.append((filename, *text)) return filepaths_and_text def to_gpu(x): x = x.contiguous() if torch.cuda.is_available(): x = x.cuda(non_blocking=True) return torch.autograd.Variable(x)
import torch class LossScaler: def __init__(self, scale=1): self.cur_scale = scale # `params` is a list / generator of torch.Variable def has_overflow(self, params): return False # `x` is a torch.Tensor def _has_inf_or_nan(x): return False # `overflow` is boolean indicating whether we overflowed in gradient def update_scale(self, overflow): pass @property def loss_scale(self): return self.cur_scale def scale_gradient(self, module, grad_in, grad_out): return tuple(self.loss_scale * g for g in grad_in) def backward(self, loss): scaled_loss = loss*self.loss_scale scaled_loss.backward() class DynamicLossScaler: def __init__(self, init_scale=2**32, scale_factor=2., scale_window=1000): self.cur_scale = init_scale self.cur_iter = 0 self.last_overflow_iter = -1 self.scale_factor = scale_factor self.scale_window = scale_window # `params` is a list / generator of torch.Variable def has_overflow(self, params): # return False for p in params: if p.grad is not None and DynamicLossScaler._has_inf_or_nan(p.grad.data): return True return False # `x` is a torch.Tensor def _has_inf_or_nan(x): cpu_sum = float(x.float().sum()) if cpu_sum == float('inf') or cpu_sum == -float('inf') or cpu_sum != cpu_sum: return True return False # `overflow` is boolean indicating whether we overflowed in gradient def update_scale(self, overflow): if overflow: #self.cur_scale /= self.scale_factor self.cur_scale = max(self.cur_scale/self.scale_factor, 1) self.last_overflow_iter = self.cur_iter else: if (self.cur_iter - self.last_overflow_iter) % self.scale_window == 0: self.cur_scale *= self.scale_factor # self.cur_scale = 1 self.cur_iter += 1 @property def loss_scale(self): return self.cur_scale def scale_gradient(self, module, grad_in, grad_out): return tuple(self.loss_scale * g for g in grad_in) def backward(self, loss): scaled_loss = loss*self.loss_scale scaled_loss.backward() ############################################################## # Example usage below here -- assuming it's in a separate file ############################################################## if __name__ == "__main__": import torch from torch.autograd import Variable from dynamic_loss_scaler import DynamicLossScaler # N is batch size; D_in is input dimension; # H is hidden dimension; D_out is output dimension. N, D_in, H, D_out = 64, 1000, 100, 10 # Create random Tensors to hold inputs and outputs, and wrap them in Variables. x = Variable(torch.randn(N, D_in), requires_grad=False) y = Variable(torch.randn(N, D_out), requires_grad=False) w1 = Variable(torch.randn(D_in, H), requires_grad=True) w2 = Variable(torch.randn(H, D_out), requires_grad=True) parameters = [w1, w2] learning_rate = 1e-6 optimizer = torch.optim.SGD(parameters, lr=learning_rate) loss_scaler = DynamicLossScaler() for t in range(500): y_pred = x.mm(w1).clamp(min=0).mm(w2) loss = (y_pred - y).pow(2).sum() * loss_scaler.loss_scale print('Iter {} loss scale: {}'.format(t, loss_scaler.loss_scale)) print('Iter {} scaled loss: {}'.format(t, loss.data[0])) print('Iter {} unscaled loss: {}'.format(t, loss.data[0] / loss_scaler.loss_scale)) # Run backprop optimizer.zero_grad() loss.backward() # Check for overflow has_overflow = DynamicLossScaler.has_overflow(parameters) # If no overflow, unscale grad and update as usual if not has_overflow: for param in parameters: param.grad.data.mul_(1. / loss_scaler.loss_scale) optimizer.step() # Otherwise, don't do anything -- ie, skip iteration else: print('OVERFLOW!') # Update loss scale for next iteration loss_scaler.update_scale(has_overflow)
# ***************************************************************************** # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the NVIDIA CORPORATION nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ***************************************************************************** import copy import torch from torch.autograd import Variable import torch.nn.functional as F @torch.jit.script def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels): n_channels_int = n_channels[0] in_act = input_a+input_b t_act = torch.tanh(in_act[:, :n_channels_int, :]) s_act = torch.sigmoid(in_act[:, n_channels_int:, :]) acts = t_act * s_act return acts class WaveGlowLoss(torch.nn.Module): def __init__(self, sigma=1.0): super(WaveGlowLoss, self).__init__() self.sigma = sigma def forward(self, model_output): z, log_s_list, log_det_W_list = model_output for i, log_s in enumerate(log_s_list): if i == 0: log_s_total = torch.sum(log_s) log_det_W_total = log_det_W_list[i] else: log_s_total = log_s_total + torch.sum(log_s) log_det_W_total += log_det_W_list[i] loss = torch.sum(z*z)/(2*self.sigma*self.sigma) - log_s_total - log_det_W_total return loss/(z.size(0)*z.size(1)*z.size(2)) class Invertible1x1Conv(torch.nn.Module): """ The layer outputs both the convolution, and the log determinant of its weight matrix. If reverse=True it does convolution with inverse """ def __init__(self, c): super(Invertible1x1Conv, self).__init__() self.conv = torch.nn.Conv1d(c, c, kernel_size=1, stride=1, padding=0, bias=False) # Sample a random orthonormal matrix to initialize weights W = torch.qr(torch.FloatTensor(c, c).normal_())[0] # Ensure determinant is 1.0 not -1.0 if torch.det(W) < 0: W[:,0] = -1*W[:,0] W = W.view(c, c, 1) self.conv.weight.data = W def forward(self, z, reverse=False): # shape batch_size, group_size, n_of_groups = z.size() W = self.conv.weight.squeeze() if reverse: if not hasattr(self, 'W_inverse'): # Reverse computation W_inverse = W.float().inverse() W_inverse = Variable(W_inverse[..., None]) if z.type() == 'torch.cuda.HalfTensor': W_inverse = W_inverse.half() self.W_inverse = W_inverse z = F.conv1d(z, self.W_inverse, bias=None, stride=1, padding=0) return z else: # Forward computation log_det_W = batch_size * n_of_groups * torch.logdet(W) z = self.conv(z) return z, log_det_W class WN(torch.nn.Module): """ This is the WaveNet like layer for the affine coupling. The primary difference from WaveNet is the convolutions need not be causal. There is also no dilation size reset. The dilation only doubles on each layer """ def __init__(self, n_in_channels, n_mel_channels, n_layers, n_channels, kernel_size): super(WN, self).__init__() assert(kernel_size % 2 == 1) assert(n_channels % 2 == 0) self.n_layers = n_layers self.n_channels = n_channels self.in_layers = torch.nn.ModuleList() self.res_skip_layers = torch.nn.ModuleList() start = torch.nn.Conv1d(n_in_channels, n_channels, 1) start = torch.nn.utils.weight_norm(start, name='weight') self.start = start # Initializing last layer to 0 makes the affine coupling layers # do nothing at first. This helps with training stability end = torch.nn.Conv1d(n_channels, 2*n_in_channels, 1) end.weight.data.zero_() end.bias.data.zero_() self.end = end cond_layer = torch.nn.Conv1d(n_mel_channels, 2*n_channels*n_layers, 1) self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight') for i in range(n_layers): dilation = 2 ** i padding = int((kernel_size*dilation - dilation)/2) in_layer = torch.nn.Conv1d(n_channels, 2*n_channels, kernel_size, dilation=dilation, padding=padding) in_layer = torch.nn.utils.weight_norm(in_layer, name='weight') self.in_layers.append(in_layer) # last one is not necessary if i < n_layers - 1: res_skip_channels = 2*n_channels else: res_skip_channels = n_channels res_skip_layer = torch.nn.Conv1d(n_channels, res_skip_channels, 1) res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight') self.res_skip_layers.append(res_skip_layer) def forward(self, forward_input): audio, spect = forward_input audio = self.start(audio) output = torch.zeros_like(audio) n_channels_tensor = torch.IntTensor([self.n_channels]) spect = self.cond_layer(spect) for i in range(self.n_layers): spect_offset = i*2*self.n_channels acts = fused_add_tanh_sigmoid_multiply( self.in_layers[i](audio), spect[:,spect_offset:spect_offset+2*self.n_channels,:], n_channels_tensor) res_skip_acts = self.res_skip_layers[i](acts) if i < self.n_layers - 1: audio = audio + res_skip_acts[:,:self.n_channels,:] output = output + res_skip_acts[:,self.n_channels:,:] else: output = output + res_skip_acts return self.end(output) class WaveGlow(torch.nn.Module): def __init__(self, n_mel_channels, n_flows, n_group, n_early_every, n_early_size, WN_config): super(WaveGlow, self).__init__() self.upsample = torch.nn.ConvTranspose1d(n_mel_channels, n_mel_channels, 1024, stride=256) assert(n_group % 2 == 0) self.n_flows = n_flows self.n_group = n_group self.n_early_every = n_early_every self.n_early_size = n_early_size self.WN = torch.nn.ModuleList() self.convinv = torch.nn.ModuleList() n_half = int(n_group/2) # Set up layers with the right sizes based on how many dimensions # have been output already n_remaining_channels = n_group for k in range(n_flows): if k % self.n_early_every == 0 and k > 0: n_half = n_half - int(self.n_early_size/2) n_remaining_channels = n_remaining_channels - self.n_early_size self.convinv.append(Invertible1x1Conv(n_remaining_channels)) self.WN.append(WN(n_half, n_mel_channels*n_group, **WN_config)) self.n_remaining_channels = n_remaining_channels # Useful during inference def forward(self, forward_input): """ forward_input[0] = mel_spectrogram: batch x n_mel_channels x frames forward_input[1] = audio: batch x time """ spect, audio = forward_input # Upsample spectrogram to size of audio spect = self.upsample(spect) assert(spect.size(2) >= audio.size(1)) if spect.size(2) > audio.size(1): spect = spect[:, :, :audio.size(1)] spect = spect.unfold(2, self.n_group, self.n_group).permute(0, 2, 1, 3) spect = spect.contiguous().view(spect.size(0), spect.size(1), -1).permute(0, 2, 1) audio = audio.unfold(1, self.n_group, self.n_group).permute(0, 2, 1) output_audio = [] log_s_list = [] log_det_W_list = [] for k in range(self.n_flows): if k % self.n_early_every == 0 and k > 0: output_audio.append(audio[:,:self.n_early_size,:]) audio = audio[:,self.n_early_size:,:] audio, log_det_W = self.convinv[k](audio) log_det_W_list.append(log_det_W) n_half = int(audio.size(1)/2) audio_0 = audio[:,:n_half,:] audio_1 = audio[:,n_half:,:] output = self.WN[k]((audio_0, spect)) log_s = output[:, n_half:, :] b = output[:, :n_half, :] audio_1 = torch.exp(log_s)*audio_1 + b log_s_list.append(log_s) audio = torch.cat([audio_0, audio_1],1) output_audio.append(audio) return torch.cat(output_audio,1), log_s_list, log_det_W_list def infer(self, spect, sigma=1.0): spect = self.upsample(spect) # trim conv artifacts. maybe pad spec to kernel multiple time_cutoff = self.upsample.kernel_size[0] - self.upsample.stride[0] spect = spect[:, :, :-time_cutoff] spect = spect.unfold(2, self.n_group, self.n_group).permute(0, 2, 1, 3) spect = spect.contiguous().view(spect.size(0), spect.size(1), -1).permute(0, 2, 1) if spect.type() == 'torch.cuda.HalfTensor': audio = torch.cuda.HalfTensor(spect.size(0), self.n_remaining_channels, spect.size(2)).normal_() else: audio = torch.cuda.FloatTensor(spect.size(0), self.n_remaining_channels, spect.size(2)).normal_() audio = torch.autograd.Variable(sigma*audio) for k in reversed(range(self.n_flows)): n_half = int(audio.size(1)/2) audio_0 = audio[:,:n_half,:] audio_1 = audio[:,n_half:,:] output = self.WN[k]((audio_0, spect)) s = output[:, n_half:, :] b = output[:, :n_half, :] audio_1 = (audio_1 - b)/torch.exp(s) audio = torch.cat([audio_0, audio_1],1) audio = self.convinv[k](audio, reverse=True) if k % self.n_early_every == 0 and k > 0: if spect.type() == 'torch.cuda.HalfTensor': z = torch.cuda.HalfTensor(spect.size(0), self.n_early_size, spect.size(2)).normal_() else: z = torch.cuda.FloatTensor(spect.size(0), self.n_early_size, spect.size(2)).normal_() audio = torch.cat((sigma*z, audio),1) audio = audio.permute(0,2,1).contiguous().view(audio.size(0), -1).data return audio @staticmethod def remove_weightnorm(model): waveglow = model for WN in waveglow.WN: WN.start = torch.nn.utils.remove_weight_norm(WN.start) WN.in_layers = remove(WN.in_layers) WN.cond_layer = torch.nn.utils.remove_weight_norm(WN.cond_layer) WN.res_skip_layers = remove(WN.res_skip_layers) return waveglow def remove(conv_list): new_conv_list = torch.nn.ModuleList() for old_conv in conv_list: old_conv = torch.nn.utils.remove_weight_norm(old_conv) new_conv_list.append(old_conv) return new_conv_list
import copy import torch from glow import Invertible1x1Conv, remove @torch.jit.script def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels): n_channels_int = n_channels[0] in_act = input_a+input_b t_act = torch.tanh(in_act[:, :n_channels_int, :]) s_act = torch.sigmoid(in_act[:, n_channels_int:, :]) acts = t_act * s_act return acts class WN(torch.nn.Module): """ This is the WaveNet like layer for the affine coupling. The primary difference from WaveNet is the convolutions need not be causal. There is also no dilation size reset. The dilation only doubles on each layer """ def __init__(self, n_in_channels, n_mel_channels, n_layers, n_channels, kernel_size): super(WN, self).__init__() assert(kernel_size % 2 == 1) assert(n_channels % 2 == 0) self.n_layers = n_layers self.n_channels = n_channels self.in_layers = torch.nn.ModuleList() self.res_skip_layers = torch.nn.ModuleList() self.cond_layers = torch.nn.ModuleList() start = torch.nn.Conv1d(n_in_channels, n_channels, 1) start = torch.nn.utils.weight_norm(start, name='weight') self.start = start # Initializing last layer to 0 makes the affine coupling layers # do nothing at first. This helps with training stability end = torch.nn.Conv1d(n_channels, 2*n_in_channels, 1) end.weight.data.zero_() end.bias.data.zero_() self.end = end for i in range(n_layers): dilation = 2 ** i padding = int((kernel_size*dilation - dilation)/2) in_layer = torch.nn.Conv1d(n_channels, 2*n_channels, kernel_size, dilation=dilation, padding=padding) in_layer = torch.nn.utils.weight_norm(in_layer, name='weight') self.in_layers.append(in_layer) cond_layer = torch.nn.Conv1d(n_mel_channels, 2*n_channels, 1) cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight') self.cond_layers.append(cond_layer) # last one is not necessary if i < n_layers - 1: res_skip_channels = 2*n_channels else: res_skip_channels = n_channels res_skip_layer = torch.nn.Conv1d(n_channels, res_skip_channels, 1) res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight') self.res_skip_layers.append(res_skip_layer) def forward(self, forward_input): audio, spect = forward_input audio = self.start(audio) for i in range(self.n_layers): acts = fused_add_tanh_sigmoid_multiply( self.in_layers[i](audio), self.cond_layers[i](spect), torch.IntTensor([self.n_channels])) res_skip_acts = self.res_skip_layers[i](acts) if i < self.n_layers - 1: audio = res_skip_acts[:,:self.n_channels,:] + audio skip_acts = res_skip_acts[:,self.n_channels:,:] else: skip_acts = res_skip_acts if i == 0: output = skip_acts else: output = skip_acts + output return self.end(output) class WaveGlow(torch.nn.Module): def __init__(self, n_mel_channels, n_flows, n_group, n_early_every, n_early_size, WN_config): super(WaveGlow, self).__init__() self.upsample = torch.nn.ConvTranspose1d(n_mel_channels, n_mel_channels, 1024, stride=256) assert(n_group % 2 == 0) self.n_flows = n_flows self.n_group = n_group self.n_early_every = n_early_every self.n_early_size = n_early_size self.WN = torch.nn.ModuleList() self.convinv = torch.nn.ModuleList() n_half = int(n_group/2) # Set up layers with the right sizes based on how many dimensions # have been output already n_remaining_channels = n_group for k in range(n_flows): if k % self.n_early_every == 0 and k > 0: n_half = n_half - int(self.n_early_size/2) n_remaining_channels = n_remaining_channels - self.n_early_size self.convinv.append(Invertible1x1Conv(n_remaining_channels)) self.WN.append(WN(n_half, n_mel_channels*n_group, **WN_config)) self.n_remaining_channels = n_remaining_channels # Useful during inference def forward(self, forward_input): return None """ forward_input[0] = audio: batch x time forward_input[1] = upsamp_spectrogram: batch x n_cond_channels x time """ """ spect, audio = forward_input # Upsample spectrogram to size of audio spect = self.upsample(spect) assert(spect.size(2) >= audio.size(1)) if spect.size(2) > audio.size(1): spect = spect[:, :, :audio.size(1)] spect = spect.unfold(2, self.n_group, self.n_group).permute(0, 2, 1, 3) spect = spect.contiguous().view(spect.size(0), spect.size(1), -1).permute(0, 2, 1) audio = audio.unfold(1, self.n_group, self.n_group).permute(0, 2, 1) output_audio = [] s_list = [] s_conv_list = [] for k in range(self.n_flows): if k%4 == 0 and k > 0: output_audio.append(audio[:,:self.n_multi,:]) audio = audio[:,self.n_multi:,:] # project to new basis audio, s = self.convinv[k](audio) s_conv_list.append(s) n_half = int(audio.size(1)/2) if k%2 == 0: audio_0 = audio[:,:n_half,:] audio_1 = audio[:,n_half:,:] else: audio_1 = audio[:,:n_half,:] audio_0 = audio[:,n_half:,:] output = self.nn[k]((audio_0, spect)) s = output[:, n_half:, :] b = output[:, :n_half, :] audio_1 = torch.exp(s)*audio_1 + b s_list.append(s) if k%2 == 0: audio = torch.cat([audio[:,:n_half,:], audio_1],1) else: audio = torch.cat([audio_1, audio[:,n_half:,:]], 1) output_audio.append(audio) return torch.cat(output_audio,1), s_list, s_conv_list """ def infer(self, spect, sigma=1.0): spect = self.upsample(spect) # trim conv artifacts. maybe pad spec to kernel multiple time_cutoff = self.upsample.kernel_size[0] - self.upsample.stride[0] spect = spect[:, :, :-time_cutoff] spect = spect.unfold(2, self.n_group, self.n_group).permute(0, 2, 1, 3) spect = spect.contiguous().view(spect.size(0), spect.size(1), -1).permute(0, 2, 1) if spect.type() == 'torch.cuda.HalfTensor': audio = torch.cuda.HalfTensor(spect.size(0), self.n_remaining_channels, spect.size(2)).normal_() else: audio = torch.cuda.FloatTensor(spect.size(0), self.n_remaining_channels, spect.size(2)).normal_() audio = torch.autograd.Variable(sigma*audio) for k in reversed(range(self.n_flows)): n_half = int(audio.size(1)/2) if k%2 == 0: audio_0 = audio[:,:n_half,:] audio_1 = audio[:,n_half:,:] else: audio_1 = audio[:,:n_half,:] audio_0 = audio[:,n_half:,:] output = self.WN[k]((audio_0, spect)) s = output[:, n_half:, :] b = output[:, :n_half, :] audio_1 = (audio_1 - b)/torch.exp(s) if k%2 == 0: audio = torch.cat([audio[:,:n_half,:], audio_1],1) else: audio = torch.cat([audio_1, audio[:,n_half:,:]], 1) audio = self.convinv[k](audio, reverse=True) if k%4 == 0 and k > 0: if spect.type() == 'torch.cuda.HalfTensor': z = torch.cuda.HalfTensor(spect.size(0), self.n_early_size, spect.size(2)).normal_() else: z = torch.cuda.FloatTensor(spect.size(0), self.n_early_size, spect.size(2)).normal_() audio = torch.cat((sigma*z, audio),1) return audio.permute(0,2,1).contiguous().view(audio.size(0), -1).data @staticmethod def remove_weightnorm(model): waveglow = model for WN in waveglow.WN: WN.start = torch.nn.utils.remove_weight_norm(WN.start) WN.in_layers = remove(WN.in_layers) WN.cond_layers = remove(WN.cond_layers) WN.res_skip_layers = remove(WN.res_skip_layers) return waveglow
import sys sys.path.append('tacotron2') import torch from layers import STFT class Denoiser(torch.nn.Module): """ Removes model bias from audio produced with waveglow """ def __init__(self, waveglow, filter_length=1024, n_overlap=4, win_length=1024, mode='zeros'): super(Denoiser, self).__init__() self.stft = STFT(filter_length=filter_length, hop_length=int(filter_length/n_overlap), win_length=win_length).cuda() if mode == 'zeros': mel_input = torch.zeros( (1, 80, 88), dtype=waveglow.upsample.weight.dtype, device=waveglow.upsample.weight.device) elif mode == 'normal': mel_input = torch.randn( (1, 80, 88), dtype=waveglow.upsample.weight.dtype, device=waveglow.upsample.weight.device) else: raise Exception("Mode {} if not supported".format(mode)) with torch.no_grad(): bias_audio = waveglow.infer(mel_input, sigma=0.0).float() bias_spec, _ = self.stft.transform(bias_audio) self.register_buffer('bias_spec', bias_spec[:, :, 0][:, :, None]) def forward(self, audio, strength=0.1): audio_spec, audio_angles = self.stft.transform(audio.cuda().float()) audio_spec_denoised = audio_spec - self.bias_spec * strength audio_spec_denoised = torch.clamp(audio_spec_denoised, 0.0) audio_denoised = self.stft.inverse(audio_spec_denoised, audio_angles) return audio_denoised
# ***************************************************************************** # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the NVIDIA CORPORATION nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ***************************************************************************** import os import sys import time import subprocess import argparse import torch import torch.distributed as dist from torch.autograd import Variable def reduce_tensor(tensor, num_gpus): rt = tensor.clone() dist.all_reduce(rt, op=dist.reduce_op.SUM) rt /= num_gpus return rt def init_distributed(rank, num_gpus, group_name, dist_backend, dist_url): assert torch.cuda.is_available(), "Distributed mode requires CUDA." print("Initializing Distributed") # Set cuda device so everything is done on the right GPU. torch.cuda.set_device(rank % torch.cuda.device_count()) # Initialize distributed communication dist.init_process_group(dist_backend, init_method=dist_url, world_size=num_gpus, rank=rank, group_name=group_name) def _flatten_dense_tensors(tensors): """Flatten dense tensors into a contiguous 1D buffer. Assume tensors are of same dense type. Since inputs are dense, the resulting tensor will be a concatenated 1D buffer. Element-wise operation on this buffer will be equivalent to operating individually. Arguments: tensors (Iterable[Tensor]): dense tensors to flatten. Returns: A contiguous 1D buffer containing input tensors. """ if len(tensors) == 1: return tensors[0].contiguous().view(-1) flat = torch.cat([t.contiguous().view(-1) for t in tensors], dim=0) return flat def _unflatten_dense_tensors(flat, tensors): """View a flat buffer using the sizes of tensors. Assume that tensors are of same dense type, and that flat is given by _flatten_dense_tensors. Arguments: flat (Tensor): flattened dense tensors to unflatten. tensors (Iterable[Tensor]): dense tensors whose sizes will be used to unflatten flat. Returns: Unflattened dense tensors with sizes same as tensors and values from flat. """ outputs = [] offset = 0 for tensor in tensors: numel = tensor.numel() outputs.append(flat.narrow(0, offset, numel).view_as(tensor)) offset += numel return tuple(outputs) def apply_gradient_allreduce(module): """ Modifies existing model to do gradient allreduce, but doesn't change class so you don't need "module" """ if not hasattr(dist, '_backend'): module.warn_on_half = True else: module.warn_on_half = True if dist._backend == dist.dist_backend.GLOO else False for p in module.state_dict().values(): if not torch.is_tensor(p): continue dist.broadcast(p, 0) def allreduce_params(): if(module.needs_reduction): module.needs_reduction = False buckets = {} for param in module.parameters(): if param.requires_grad and param.grad is not None: tp = type(param.data) if tp not in buckets: buckets[tp] = [] buckets[tp].append(param) if module.warn_on_half: if torch.cuda.HalfTensor in buckets: print("WARNING: gloo dist backend for half parameters may be extremely slow." + " It is recommended to use the NCCL backend in this case. This currently requires" + "PyTorch built from top of tree master.") module.warn_on_half = False for tp in buckets: bucket = buckets[tp] grads = [param.grad.data for param in bucket] coalesced = _flatten_dense_tensors(grads) dist.all_reduce(coalesced) coalesced /= dist.get_world_size() for buf, synced in zip(grads, _unflatten_dense_tensors(coalesced, grads)): buf.copy_(synced) for param in list(module.parameters()): def allreduce_hook(*unused): Variable._execution_engine.queue_callback(allreduce_params) if param.requires_grad: param.register_hook(allreduce_hook) dir(param) def set_needs_reduction(self, input, output): self.needs_reduction = True module.register_forward_hook(set_needs_reduction) return module def main(config, stdout_dir, args_str): args_list = ['train.py'] args_list += args_str.split(' ') if len(args_str) > 0 else [] args_list.append('--config={}'.format(config)) num_gpus = torch.cuda.device_count() args_list.append('--num_gpus={}'.format(num_gpus)) args_list.append("--group_name=group_{}".format(time.strftime("%Y_%m_%d-%H%M%S"))) if not os.path.isdir(stdout_dir): os.makedirs(stdout_dir) os.chmod(stdout_dir, 0o775) workers = [] for i in range(num_gpus): args_list[-2] = '--rank={}'.format(i) stdout = None if i == 0 else open( os.path.join(stdout_dir, "GPU_{}.log".format(i)), "w") print(args_list) p = subprocess.Popen([str(sys.executable)]+args_list, stdout=stdout) workers.append(p) for p in workers: p.wait() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', type=str, required=True, help='JSON file for configuration') parser.add_argument('-s', '--stdout_dir', type=str, default=".", help='directory to save stoud logs') parser.add_argument( '-a', '--args_str', type=str, default='', help='double quoted string with space separated key value pairs') args = parser.parse_args() main(args.config, args.stdout_dir, args.args_str)
# ***************************************************************************** # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the NVIDIA CORPORATION nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ***************************************************************************** import argparse import json import os import torch #=====START: ADDED FOR DISTRIBUTED====== from distributed import init_distributed, apply_gradient_allreduce, reduce_tensor from torch.utils.data.distributed import DistributedSampler #=====END: ADDED FOR DISTRIBUTED====== from torch.utils.data import DataLoader from glow import WaveGlow, WaveGlowLoss from mel2samp import Mel2Samp def load_checkpoint(checkpoint_path, model, optimizer): assert os.path.isfile(checkpoint_path) checkpoint_dict = torch.load(checkpoint_path, map_location='cpu') iteration = checkpoint_dict['iteration'] optimizer.load_state_dict(checkpoint_dict['optimizer']) model_for_loading = checkpoint_dict['model'] model.load_state_dict(model_for_loading.state_dict()) print("Loaded checkpoint '{}' (iteration {})" .format( checkpoint_path, iteration)) return model, optimizer, iteration def save_checkpoint(model, optimizer, learning_rate, iteration, filepath): print("Saving model and optimizer state at iteration {} to {}".format( iteration, filepath)) model_for_saving = WaveGlow(**waveglow_config).cuda() model_for_saving.load_state_dict(model.state_dict()) torch.save({'model': model_for_saving, 'iteration': iteration, 'optimizer': optimizer.state_dict(), 'learning_rate': learning_rate}, filepath) def train(num_gpus, rank, group_name, output_directory, epochs, learning_rate, sigma, iters_per_checkpoint, batch_size, seed, fp16_run, checkpoint_path, with_tensorboard): torch.manual_seed(seed) torch.cuda.manual_seed(seed) #=====START: ADDED FOR DISTRIBUTED====== if num_gpus > 1: init_distributed(rank, num_gpus, group_name, **dist_config) #=====END: ADDED FOR DISTRIBUTED====== criterion = WaveGlowLoss(sigma) model = WaveGlow(**waveglow_config).cuda() #=====START: ADDED FOR DISTRIBUTED====== if num_gpus > 1: model = apply_gradient_allreduce(model) #=====END: ADDED FOR DISTRIBUTED====== optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) if fp16_run: from apex import amp model, optimizer = amp.initialize(model, optimizer, opt_level='O1') # Load checkpoint if one exists iteration = 0 if checkpoint_path != "": model, optimizer, iteration = load_checkpoint(checkpoint_path, model, optimizer) iteration += 1 # next iteration is iteration + 1 trainset = Mel2Samp(**data_config) # =====START: ADDED FOR DISTRIBUTED====== train_sampler = DistributedSampler(trainset) if num_gpus > 1 else None # =====END: ADDED FOR DISTRIBUTED====== train_loader = DataLoader(trainset, num_workers=1, shuffle=False, sampler=train_sampler, batch_size=batch_size, pin_memory=False, drop_last=True) # Get shared output_directory ready if rank == 0: if not os.path.isdir(output_directory): os.makedirs(output_directory) os.chmod(output_directory, 0o775) print("output directory", output_directory) if with_tensorboard and rank == 0: from tensorboardX import SummaryWriter logger = SummaryWriter(os.path.join(output_directory, 'logs')) model.train() epoch_offset = max(0, int(iteration / len(train_loader))) # ================ MAIN TRAINNIG LOOP! =================== for epoch in range(epoch_offset, epochs): print("Epoch: {}".format(epoch)) for i, batch in enumerate(train_loader): model.zero_grad() mel, audio = batch mel = torch.autograd.Variable(mel.cuda()) audio = torch.autograd.Variable(audio.cuda()) outputs = model((mel, audio)) loss = criterion(outputs) if num_gpus > 1: reduced_loss = reduce_tensor(loss.data, num_gpus).item() else: reduced_loss = loss.item() if fp16_run: with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() else: loss.backward() optimizer.step() print("{}:\t{:.9f}".format(iteration, reduced_loss)) if with_tensorboard and rank == 0: logger.add_scalar('training_loss', reduced_loss, i + len(train_loader) * epoch) if (iteration % iters_per_checkpoint == 0): if rank == 0: checkpoint_path = "{}/waveglow_{}".format( output_directory, iteration) save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path) iteration += 1 if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', type=str, help='JSON file for configuration') parser.add_argument('-r', '--rank', type=int, default=0, help='rank of process for distributed') parser.add_argument('-g', '--group_name', type=str, default='', help='name of group for distributed') args = parser.parse_args() # Parse configs. Globals nicer in this case with open(args.config) as f: data = f.read() config = json.loads(data) train_config = config["train_config"] global data_config data_config = config["data_config"] global dist_config dist_config = config["dist_config"] global waveglow_config waveglow_config = config["waveglow_config"] num_gpus = torch.cuda.device_count() if num_gpus > 1: if args.group_name == '': print("WARNING: Multiple GPUs detected but no distributed group set") print("Only running 1 GPU. Use distributed.py for multiple GPUs") num_gpus = 1 if num_gpus == 1 and args.rank != 0: raise Exception("Doing single GPU training on rank > 0") torch.backends.cudnn.enabled = True torch.backends.cudnn.benchmark = False train(num_gpus, args.rank, args.group_name, **train_config)
# ***************************************************************************** # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the NVIDIA CORPORATION nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ***************************************************************************** import os from scipy.io.wavfile import write import torch from mel2samp import files_to_list, MAX_WAV_VALUE from denoiser import Denoiser def main(mel_files, waveglow_path, sigma, output_dir, sampling_rate, is_fp16, denoiser_strength): mel_files = files_to_list(mel_files) waveglow = torch.load(waveglow_path)['model'] waveglow = waveglow.remove_weightnorm(waveglow) waveglow.cuda().eval() if is_fp16: from apex import amp waveglow, _ = amp.initialize(waveglow, [], opt_level="O3") if denoiser_strength > 0: denoiser = Denoiser(waveglow).cuda() for i, file_path in enumerate(mel_files): file_name = os.path.splitext(os.path.basename(file_path))[0] mel = torch.load(file_path) mel = torch.autograd.Variable(mel.cuda()) mel = torch.unsqueeze(mel, 0) mel = mel.half() if is_fp16 else mel with torch.no_grad(): audio = waveglow.infer(mel, sigma=sigma) if denoiser_strength > 0: audio = denoiser(audio, denoiser_strength) audio = audio * MAX_WAV_VALUE audio = audio.squeeze() audio = audio.cpu().numpy() audio = audio.astype('int16') audio_path = os.path.join( output_dir, "{}_synthesis.wav".format(file_name)) write(audio_path, sampling_rate, audio) print(audio_path) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument('-f', "--filelist_path", required=True) parser.add_argument('-w', '--waveglow_path', help='Path to waveglow decoder checkpoint with model') parser.add_argument('-o', "--output_dir", required=True) parser.add_argument("-s", "--sigma", default=1.0, type=float) parser.add_argument("--sampling_rate", default=22050, type=int) parser.add_argument("--is_fp16", action="store_true") parser.add_argument("-d", "--denoiser_strength", default=0.0, type=float, help='Removes model bias. Start with 0.1 and adjust') args = parser.parse_args() main(args.filelist_path, args.waveglow_path, args.sigma, args.output_dir, args.sampling_rate, args.is_fp16, args.denoiser_strength)
# ***************************************************************************** # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the NVIDIA CORPORATION nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # *****************************************************************************\ import os import random import argparse import json import torch import torch.utils.data import sys from scipy.io.wavfile import read # We're using the audio processing from TacoTron2 to make sure it matches sys.path.insert(0, 'tacotron2') from tacotron2.layers import TacotronSTFT MAX_WAV_VALUE = 32768.0 def files_to_list(filename): """ Takes a text file of filenames and makes a list of filenames """ with open(filename, encoding='utf-8') as f: files = f.readlines() files = [f.rstrip() for f in files] return files def load_wav_to_torch(full_path): """ Loads wavdata into torch array """ sampling_rate, data = read(full_path) return torch.from_numpy(data).float(), sampling_rate class Mel2Samp(torch.utils.data.Dataset): """ This is the main class that calculates the spectrogram and returns the spectrogram, audio pair. """ def __init__(self, training_files, segment_length, filter_length, hop_length, win_length, sampling_rate, mel_fmin, mel_fmax): self.audio_files = files_to_list(training_files) random.seed(1234) random.shuffle(self.audio_files) self.stft = TacotronSTFT(filter_length=filter_length, hop_length=hop_length, win_length=win_length, sampling_rate=sampling_rate, mel_fmin=mel_fmin, mel_fmax=mel_fmax) self.segment_length = segment_length self.sampling_rate = sampling_rate def get_mel(self, audio): audio_norm = audio / MAX_WAV_VALUE audio_norm = audio_norm.unsqueeze(0) audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False) melspec = self.stft.mel_spectrogram(audio_norm) melspec = torch.squeeze(melspec, 0) return melspec def __getitem__(self, index): # Read audio filename = self.audio_files[index] audio, sampling_rate = load_wav_to_torch(filename) if sampling_rate != self.sampling_rate: raise ValueError("{} SR doesn't match target {} SR".format( sampling_rate, self.sampling_rate)) # Take segment if audio.size(0) >= self.segment_length: max_audio_start = audio.size(0) - self.segment_length audio_start = random.randint(0, max_audio_start) audio = audio[audio_start:audio_start+self.segment_length] else: audio = torch.nn.functional.pad(audio, (0, self.segment_length - audio.size(0)), 'constant').data mel = self.get_mel(audio) audio = audio / MAX_WAV_VALUE return (mel, audio) def __len__(self): return len(self.audio_files) # =================================================================== # Takes directory of clean audio and makes directory of spectrograms # Useful for making test sets # =================================================================== if __name__ == "__main__": # Get defaults so it can work with no Sacred parser = argparse.ArgumentParser() parser.add_argument('-f', "--filelist_path", required=True) parser.add_argument('-c', '--config', type=str, help='JSON file for configuration') parser.add_argument('-o', '--output_dir', type=str, help='Output directory') args = parser.parse_args() with open(args.config) as f: data = f.read() data_config = json.loads(data)["data_config"] mel2samp = Mel2Samp(**data_config) filepaths = files_to_list(args.filelist_path) # Make directory if it doesn't exist if not os.path.isdir(args.output_dir): os.makedirs(args.output_dir) os.chmod(args.output_dir, 0o775) for filepath in filepaths: audio, sr = load_wav_to_torch(filepath) melspectrogram = mel2samp.get_mel(audio) filename = os.path.basename(filepath) new_filepath = args.output_dir + '/' + filename + '.pt' print(new_filepath) torch.save(melspectrogram, new_filepath)
import sys import copy import torch def _check_model_old_version(model): if hasattr(model.WN[0], 'res_layers') or hasattr(model.WN[0], 'cond_layers'): return True else: return False def _update_model_res_skip(old_model, new_model): for idx in range(0, len(new_model.WN)): wavenet = new_model.WN[idx] n_channels = wavenet.n_channels n_layers = wavenet.n_layers wavenet.res_skip_layers = torch.nn.ModuleList() for i in range(0, n_layers): if i < n_layers - 1: res_skip_channels = 2*n_channels else: res_skip_channels = n_channels res_skip_layer = torch.nn.Conv1d(n_channels, res_skip_channels, 1) skip_layer = torch.nn.utils.remove_weight_norm(wavenet.skip_layers[i]) if i < n_layers - 1: res_layer = torch.nn.utils.remove_weight_norm(wavenet.res_layers[i]) res_skip_layer.weight = torch.nn.Parameter(torch.cat([res_layer.weight, skip_layer.weight])) res_skip_layer.bias = torch.nn.Parameter(torch.cat([res_layer.bias, skip_layer.bias])) else: res_skip_layer.weight = torch.nn.Parameter(skip_layer.weight) res_skip_layer.bias = torch.nn.Parameter(skip_layer.bias) res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight') wavenet.res_skip_layers.append(res_skip_layer) del wavenet.res_layers del wavenet.skip_layers def _update_model_cond(old_model, new_model): for idx in range(0, len(new_model.WN)): wavenet = new_model.WN[idx] n_channels = wavenet.n_channels n_layers = wavenet.n_layers n_mel_channels = wavenet.cond_layers[0].weight.shape[1] cond_layer = torch.nn.Conv1d(n_mel_channels, 2*n_channels*n_layers, 1) cond_layer_weight = [] cond_layer_bias = [] for i in range(0, n_layers): _cond_layer = torch.nn.utils.remove_weight_norm(wavenet.cond_layers[i]) cond_layer_weight.append(_cond_layer.weight) cond_layer_bias.append(_cond_layer.bias) cond_layer.weight = torch.nn.Parameter(torch.cat(cond_layer_weight)) cond_layer.bias = torch.nn.Parameter(torch.cat(cond_layer_bias)) cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight') wavenet.cond_layer = cond_layer del wavenet.cond_layers def update_model(old_model): if not _check_model_old_version(old_model): return old_model new_model = copy.deepcopy(old_model) if hasattr(old_model.WN[0], 'res_layers'): _update_model_res_skip(old_model, new_model) if hasattr(old_model.WN[0], 'cond_layers'): _update_model_cond(old_model, new_model) return new_model if __name__ == '__main__': old_model_path = sys.argv[1] new_model_path = sys.argv[2] model = torch.load(old_model_path, map_location='cpu') model['model'] = update_model(model['model']) torch.save(model, new_model_path)
import matplotlib matplotlib.use("Agg") import matplotlib.pylab as plt import numpy as np def save_figure_to_numpy(fig): # save it to a numpy array. data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) return data def plot_alignment_to_numpy(alignment, info=None): fig, ax = plt.subplots(figsize=(6, 4)) im = ax.imshow(alignment, aspect='auto', origin='lower', interpolation='none') fig.colorbar(im, ax=ax) xlabel = 'Decoder timestep' if info is not None: xlabel += '\n\n' + info plt.xlabel(xlabel) plt.ylabel('Encoder timestep') plt.tight_layout() fig.canvas.draw() data = save_figure_to_numpy(fig) plt.close() return data def plot_spectrogram_to_numpy(spectrogram): fig, ax = plt.subplots(figsize=(12, 3)) im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation='none') plt.colorbar(im, ax=ax) plt.xlabel("Frames") plt.ylabel("Channels") plt.tight_layout() fig.canvas.draw() data = save_figure_to_numpy(fig) plt.close() return data def plot_gate_outputs_to_numpy(gate_targets, gate_outputs): fig, ax = plt.subplots(figsize=(12, 3)) ax.scatter(range(len(gate_targets)), gate_targets, alpha=0.5, color='green', marker='+', s=1, label='target') ax.scatter(range(len(gate_outputs)), gate_outputs, alpha=0.5, color='red', marker='.', s=1, label='predicted') plt.xlabel("Frames (Green target, Red predicted)") plt.ylabel("Gate State") plt.tight_layout() fig.canvas.draw() data = save_figure_to_numpy(fig) plt.close() return data
import tensorflow as tf from text import symbols def create_hparams(hparams_string=None, verbose=False): """Create model hyperparameters. Parse nondefault from given string.""" hparams = tf.contrib.training.HParams( ################################ # Experiment Parameters # ################################ epochs=500, iters_per_checkpoint=500, seed=1234, dynamic_loss_scaling=True, fp16_run=False, distributed_run=False, dist_backend="nccl", dist_url="file://distributed.dpt", cudnn_enabled=True, cudnn_benchmark=False, ################################ # Data Parameters # ################################ load_mel_from_disk=False, training_files='filelists/ljs_audio_text_train_filelist.txt', validation_files='filelists/ljs_audio_text_val_filelist.txt', text_cleaners=['english_cleaners'], sort_by_length=False, ################################ # Audio Parameters # ################################ max_wav_value=32768.0, sampling_rate=22050, filter_length=1024, hop_length=256, win_length=1024, n_mel_channels=80, mel_fmin=0.0, mel_fmax=None, # if None, half the sampling rate ################################ # Model Parameters # ################################ n_symbols=len(symbols), symbols_embedding_dim=512, # Encoder parameters encoder_kernel_size=5, encoder_n_convolutions=3, encoder_embedding_dim=512, # Decoder parameters n_frames_per_step=1, # currently only 1 is supported decoder_rnn_dim=1024, prenet_dim=256, max_decoder_steps=1000, gate_threshold=0.6, # Attention parameters attention_rnn_dim=1024, attention_dim=128, # Location Layer parameters attention_location_n_filters=32, attention_location_kernel_size=31, # Mel-post processing network parameters postnet_embedding_dim=512, postnet_kernel_size=5, postnet_n_convolutions=5, ################################ # Optimization Hyperparameters # ################################ use_saved_learning_rate=False, learning_rate=1e-3, weight_decay=1e-6, grad_clip_thresh=1, batch_size=48, mask_padding=False # set model's padded outputs to padded values ) if hparams_string: tf.logging.info('Parsing command line hparams: %s', hparams_string) hparams.parse(hparams_string) if verbose: tf.logging.info('Final parsed hparams: %s', hparams.values()) return hparams
import torch import numpy as np from scipy.signal import get_window import librosa.util as librosa_util def window_sumsquare(window, n_frames, hop_length=200, win_length=800, n_fft=800, dtype=np.float32, norm=None): """ # from librosa 0.6 Compute the sum-square envelope of a window function at a given hop length. This is used to estimate modulation effects induced by windowing observations in short-time fourier transforms. Parameters ---------- window : string, tuple, number, callable, or list-like Window specification, as in `get_window` n_frames : int > 0 The number of analysis frames hop_length : int > 0 The number of samples to advance between frames win_length : [optional] The length of the window function. By default, this matches `n_fft`. n_fft : int > 0 The length of each analysis frame. dtype : np.dtype The data type of the output Returns ------- wss : np.ndarray, shape=`(n_fft + hop_length * (n_frames - 1))` The sum-squared envelope of the window function """ if win_length is None: win_length = n_fft n = n_fft + hop_length * (n_frames - 1) x = np.zeros(n, dtype=dtype) # Compute the squared window at the desired length win_sq = get_window(window, win_length, fftbins=True) win_sq = librosa_util.normalize(win_sq, norm=norm)**2 win_sq = librosa_util.pad_center(win_sq, n_fft) # Fill the envelope for i in range(n_frames): sample = i * hop_length x[sample:min(n, sample + n_fft)] += win_sq[:max(0, min(n_fft, n - sample))] return x def griffin_lim(magnitudes, stft_fn, n_iters=30): """ PARAMS ------ magnitudes: spectrogram magnitudes stft_fn: STFT class with transform (STFT) and inverse (ISTFT) methods """ angles = np.angle(np.exp(2j * np.pi * np.random.rand(*magnitudes.size()))) angles = angles.astype(np.float32) angles = torch.autograd.Variable(torch.from_numpy(angles)) signal = stft_fn.inverse(magnitudes, angles).squeeze(1) for i in range(n_iters): _, angles = stft_fn.transform(signal) signal = stft_fn.inverse(magnitudes, angles).squeeze(1) return signal def dynamic_range_compression(x, C=1, clip_val=1e-5): """ PARAMS ------ C: compression factor """ return torch.log(torch.clamp(x, min=clip_val) * C) def dynamic_range_decompression(x, C=1): """ PARAMS ------ C: compression factor used to compress """ return torch.exp(x) / C
import random import torch.nn.functional as F from tensorboardX import SummaryWriter from plotting_utils import plot_alignment_to_numpy, plot_spectrogram_to_numpy from plotting_utils import plot_gate_outputs_to_numpy class Tacotron2Logger(SummaryWriter): def __init__(self, logdir): super(Tacotron2Logger, self).__init__(logdir) def log_training(self, reduced_loss, grad_norm, learning_rate, duration, iteration): self.add_scalar("training.loss", reduced_loss, iteration) self.add_scalar("grad.norm", grad_norm, iteration) self.add_scalar("learning.rate", learning_rate, iteration) self.add_scalar("duration", duration, iteration) def log_validation(self, reduced_loss, model, y, y_pred, iteration): self.add_scalar("validation.loss", reduced_loss, iteration) _, mel_outputs, gate_outputs, alignments = y_pred mel_targets, gate_targets = y # plot distribution of parameters for tag, value in model.named_parameters(): tag = tag.replace('.', '/') self.add_histogram(tag, value.data.cpu().numpy(), iteration) # plot alignment, mel target and predicted, gate target and predicted idx = random.randint(0, alignments.size(0) - 1) self.add_image( "alignment", plot_alignment_to_numpy(alignments[idx].data.cpu().numpy().T), iteration) self.add_image( "mel_target", plot_spectrogram_to_numpy(mel_targets[idx].data.cpu().numpy()), iteration) self.add_image( "mel_predicted", plot_spectrogram_to_numpy(mel_outputs[idx].data.cpu().numpy()), iteration) self.add_image( "gate", plot_gate_outputs_to_numpy( gate_targets[idx].data.cpu().numpy(), F.sigmoid(gate_outputs[idx]).data.cpu().numpy()), iteration)
import torch from torch import nn from torch.autograd import Variable from torch.nn.parameter import Parameter from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors from loss_scaler import DynamicLossScaler, LossScaler FLOAT_TYPES = (torch.FloatTensor, torch.cuda.FloatTensor) HALF_TYPES = (torch.HalfTensor, torch.cuda.HalfTensor) def conversion_helper(val, conversion): """Apply conversion to val. Recursively apply conversion if `val` is a nested tuple/list structure.""" if not isinstance(val, (tuple, list)): return conversion(val) rtn = [conversion_helper(v, conversion) for v in val] if isinstance(val, tuple): rtn = tuple(rtn) return rtn def fp32_to_fp16(val): """Convert fp32 `val` to fp16""" def half_conversion(val): val_typecheck = val if isinstance(val_typecheck, (Parameter, Variable)): val_typecheck = val.data if isinstance(val_typecheck, FLOAT_TYPES): val = val.half() return val return conversion_helper(val, half_conversion) def fp16_to_fp32(val): """Convert fp16 `val` to fp32""" def float_conversion(val): val_typecheck = val if isinstance(val_typecheck, (Parameter, Variable)): val_typecheck = val.data if isinstance(val_typecheck, HALF_TYPES): val = val.float() return val return conversion_helper(val, float_conversion) class FP16_Module(nn.Module): def __init__(self, module): super(FP16_Module, self).__init__() self.add_module('module', module.half()) def forward(self, *inputs, **kwargs): return fp16_to_fp32(self.module(*(fp32_to_fp16(inputs)), **kwargs)) class FP16_Optimizer: """ FP16_Optimizer is designed to wrap an existing PyTorch optimizer, and enable an fp16 model to be trained using a master copy of fp32 weights. Args: optimizer (torch.optim.optimizer): Existing optimizer containing initialized fp16 parameters. Internally, FP16_Optimizer replaces the passed optimizer's fp16 parameters with new fp32 parameters copied from the original ones. FP16_Optimizer also stores references to the original fp16 parameters, and updates these fp16 parameters from the master fp32 copy after each step. static_loss_scale (float, optional, default=1.0): Loss scale used internally to scale fp16 gradients computed by the model. Scaled gradients will be copied to fp32, then downscaled before being applied to the fp32 master params, so static_loss_scale should not affect learning rate. dynamic_loss_scale (bool, optional, default=False): Use dynamic loss scaling. If True, this will override any static_loss_scale option. """ def __init__(self, optimizer, static_loss_scale=1.0, dynamic_loss_scale=False): if not torch.cuda.is_available: raise SystemError('Cannot use fp16 without CUDA') self.fp16_param_groups = [] self.fp32_param_groups = [] self.fp32_flattened_groups = [] for i, param_group in enumerate(optimizer.param_groups): print("FP16_Optimizer processing param group {}:".format(i)) fp16_params_this_group = [] fp32_params_this_group = [] for param in param_group['params']: if param.requires_grad: if param.type() == 'torch.cuda.HalfTensor': print("FP16_Optimizer received torch.cuda.HalfTensor with {}" .format(param.size())) fp16_params_this_group.append(param) elif param.type() == 'torch.cuda.FloatTensor': print("FP16_Optimizer received torch.cuda.FloatTensor with {}" .format(param.size())) fp32_params_this_group.append(param) else: raise TypeError("Wrapped parameters must be either " "torch.cuda.FloatTensor or torch.cuda.HalfTensor. " "Received {}".format(param.type())) fp32_flattened_this_group = None if len(fp16_params_this_group) > 0: fp32_flattened_this_group = _flatten_dense_tensors( [param.detach().data.clone().float() for param in fp16_params_this_group]) fp32_flattened_this_group = Variable(fp32_flattened_this_group, requires_grad = True) fp32_flattened_this_group.grad = fp32_flattened_this_group.new( *fp32_flattened_this_group.size()) # python's lovely list concatenation via + if fp32_flattened_this_group is not None: param_group['params'] = [fp32_flattened_this_group] + fp32_params_this_group else: param_group['params'] = fp32_params_this_group self.fp16_param_groups.append(fp16_params_this_group) self.fp32_param_groups.append(fp32_params_this_group) self.fp32_flattened_groups.append(fp32_flattened_this_group) # print("self.fp32_flattened_groups = ", self.fp32_flattened_groups) # print("self.fp16_param_groups = ", self.fp16_param_groups) self.optimizer = optimizer.__class__(optimizer.param_groups) # self.optimizer.load_state_dict(optimizer.state_dict()) self.param_groups = self.optimizer.param_groups if dynamic_loss_scale: self.dynamic_loss_scale = True self.loss_scaler = DynamicLossScaler() else: self.dynamic_loss_scale = False self.loss_scaler = LossScaler(static_loss_scale) self.overflow = False self.first_closure_call_this_step = True def zero_grad(self): """ Zero fp32 and fp16 parameter grads. """ self.optimizer.zero_grad() for fp16_group in self.fp16_param_groups: for param in fp16_group: if param.grad is not None: param.grad.detach_() # This does appear in torch.optim.optimizer.zero_grad(), # but I'm not sure why it's needed. param.grad.zero_() def _check_overflow(self): params = [] for group in self.fp16_param_groups: for param in group: params.append(param) for group in self.fp32_param_groups: for param in group: params.append(param) self.overflow = self.loss_scaler.has_overflow(params) def _update_scale(self, has_overflow=False): self.loss_scaler.update_scale(has_overflow) def _copy_grads_fp16_to_fp32(self): for fp32_group, fp16_group in zip(self.fp32_flattened_groups, self.fp16_param_groups): if len(fp16_group) > 0: # This might incur one more deep copy than is necessary. fp32_group.grad.data.copy_( _flatten_dense_tensors([fp16_param.grad.data for fp16_param in fp16_group])) def _downscale_fp32(self): if self.loss_scale != 1.0: for param_group in self.optimizer.param_groups: for param in param_group['params']: param.grad.data.mul_(1./self.loss_scale) def clip_fp32_grads(self, clip=-1): if not self.overflow: fp32_params = [] for param_group in self.optimizer.param_groups: for param in param_group['params']: fp32_params.append(param) if clip > 0: return torch.nn.utils.clip_grad_norm(fp32_params, clip) def _copy_params_fp32_to_fp16(self): for fp16_group, fp32_group in zip(self.fp16_param_groups, self.fp32_flattened_groups): if len(fp16_group) > 0: for fp16_param, fp32_data in zip(fp16_group, _unflatten_dense_tensors(fp32_group.data, fp16_group)): fp16_param.data.copy_(fp32_data) def state_dict(self): """ Returns a dict containing the current state of this FP16_Optimizer instance. This dict contains attributes of FP16_Optimizer, as well as the state_dict of the contained Pytorch optimizer. Untested. """ state_dict = {} state_dict['loss_scaler'] = self.loss_scaler state_dict['dynamic_loss_scale'] = self.dynamic_loss_scale state_dict['overflow'] = self.overflow state_dict['first_closure_call_this_step'] = self.first_closure_call_this_step state_dict['optimizer_state_dict'] = self.optimizer.state_dict() return state_dict def load_state_dict(self, state_dict): """ Loads a state_dict created by an earlier call to state_dict. Untested. """ self.loss_scaler = state_dict['loss_scaler'] self.dynamic_loss_scale = state_dict['dynamic_loss_scale'] self.overflow = state_dict['overflow'] self.first_closure_call_this_step = state_dict['first_closure_call_this_step'] self.optimizer.load_state_dict(state_dict['optimizer_state_dict']) def step(self, closure=None): # could add clip option. """ If no closure is supplied, step should be called after fp16_optimizer_obj.backward(loss). step updates the fp32 master copy of parameters using the optimizer supplied to FP16_Optimizer's constructor, then copies the updated fp32 params into the fp16 params originally referenced by Fp16_Optimizer's constructor, so the user may immediately run another forward pass using their model. If a closure is supplied, step may be called without a prior call to self.backward(loss). However, the user should take care that any loss.backward() call within the closure has been replaced by fp16_optimizer_obj.backward(loss). Args: closure (optional): Closure that will be supplied to the underlying optimizer originally passed to FP16_Optimizer's constructor. closure should call zero_grad on the FP16_Optimizer object, compute the loss, call .backward(loss), and return the loss. Closure example:: # optimizer is assumed to be an FP16_Optimizer object, previously constructed from an # existing pytorch optimizer. for input, target in dataset: def closure(): optimizer.zero_grad() output = model(input) loss = loss_fn(output, target) optimizer.backward(loss) return loss optimizer.step(closure) .. note:: The only changes that need to be made compared to `ordinary optimizer closures`_ are that "optimizer" itself should be an instance of FP16_Optimizer, and that the call to loss.backward should be replaced by optimizer.backward(loss). .. warning:: Currently, calling step with a closure is not compatible with dynamic loss scaling. .. _`ordinary optimizer closures`: http://pytorch.org/docs/master/optim.html#optimizer-step-closure """ if closure is not None and isinstance(self.loss_scaler, DynamicLossScaler): raise TypeError("Using step with a closure is currently not " "compatible with dynamic loss scaling.") scale = self.loss_scaler.loss_scale self._update_scale(self.overflow) if self.overflow: print("OVERFLOW! Skipping step. Attempted loss scale: {}".format(scale)) return if closure is not None: self._step_with_closure(closure) else: self.optimizer.step() self._copy_params_fp32_to_fp16() return def _step_with_closure(self, closure): def wrapped_closure(): if self.first_closure_call_this_step: """ We expect that the fp16 params are initially fresh on entering self.step(), so _copy_params_fp32_to_fp16() is unnecessary the first time wrapped_closure() is called within self.optimizer.step(). """ self.first_closure_call_this_step = False else: """ If self.optimizer.step() internally calls wrapped_closure more than once, it may update the fp32 params after each call. However, self.optimizer doesn't know about the fp16 params at all. If the fp32 params get updated, we can't rely on self.optimizer to refresh the fp16 params. We need to handle that manually: """ self._copy_params_fp32_to_fp16() """ Our API expects the user to give us ownership of the backward() call by replacing all calls to loss.backward() with optimizer.backward(loss). This requirement holds whether or not the call to backward() is made within a closure. If the user is properly calling optimizer.backward(loss) within "closure," calling closure() here will give the fp32 master params fresh gradients for the optimizer to play with, so all wrapped_closure needs to do is call closure() and return the loss. """ temp_loss = closure() return temp_loss self.optimizer.step(wrapped_closure) self.first_closure_call_this_step = True def backward(self, loss, update_fp32_grads=True): """ fp16_optimizer_obj.backward performs the following conceptual operations: fp32_loss = loss.float() (see first Note below) scaled_loss = fp32_loss*loss_scale scaled_loss.backward(), which accumulates scaled gradients into the .grad attributes of the fp16 model's leaves. fp16 grads are then copied to the stored fp32 params' .grad attributes (see second Note). Finally, fp32 grads are divided by loss_scale. In this way, after fp16_optimizer_obj.backward, the fp32 parameters have fresh gradients, and fp16_optimizer_obj.step may be called. .. note:: Converting the loss to fp32 before applying the loss scale provides some additional safety against overflow if the user has supplied an fp16 value. However, for maximum overflow safety, the user should compute the loss criterion (MSE, cross entropy, etc) in fp32 before supplying it to fp16_optimizer_obj.backward. .. note:: The gradients found in an fp16 model's leaves after a call to fp16_optimizer_obj.backward should not be regarded as valid in general, because it's possible they have been scaled (and in the case of dynamic loss scaling, the scale factor may silently change over time). If the user wants to inspect gradients after a call to fp16_optimizer_obj.backward, he/she should query the .grad attribute of FP16_Optimizer's stored fp32 parameters. Args: loss: The loss output by the user's model. loss may be either float or half (but see first Note above). update_fp32_grads (bool, optional, default=True): Option to copy fp16 grads to fp32 grads on this call. By setting this to False, the user can delay this copy, which is useful to eliminate redundant fp16->fp32 grad copies if fp16_optimizer_obj.backward is being called on multiple losses in one iteration. If set to False, the user becomes responsible for calling fp16_optimizer_obj.update_fp32_grads before calling fp16_optimizer_obj.step. Example:: # Ordinary operation: optimizer.backward(loss) # Naive operation with multiple losses (technically valid, but less efficient): # fp32 grads will be correct after the second call, but # the first call incurs an unnecessary fp16->fp32 grad copy. optimizer.backward(loss1) optimizer.backward(loss2) # More efficient way to handle multiple losses: # The fp16->fp32 grad copy is delayed until fp16 grads from all # losses have been accumulated. optimizer.backward(loss1, update_fp32_grads=False) optimizer.backward(loss2, update_fp32_grads=False) optimizer.update_fp32_grads() """ self.loss_scaler.backward(loss.float()) if update_fp32_grads: self.update_fp32_grads() def update_fp32_grads(self): """ Copy the .grad attribute from stored references to fp16 parameters to the .grad attribute of the master fp32 parameters that are directly updated by the optimizer. :attr:`update_fp32_grads` only needs to be called if fp16_optimizer_obj.backward was called with update_fp32_grads=False. """ if self.dynamic_loss_scale: self._check_overflow() if self.overflow: return self._copy_grads_fp16_to_fp32() self._downscale_fp32() @property def loss_scale(self): return self.loss_scaler.loss_scale
import torch from torch.autograd import Variable from torch import nn from torch.nn import functional as F from layers import ConvNorm, LinearNorm from utils import to_gpu, get_mask_from_lengths from fp16_optimizer import fp32_to_fp16, fp16_to_fp32 class LocationLayer(nn.Module): def __init__(self, attention_n_filters, attention_kernel_size, attention_dim): super(LocationLayer, self).__init__() padding = int((attention_kernel_size - 1) / 2) self.location_conv = ConvNorm(2, attention_n_filters, kernel_size=attention_kernel_size, padding=padding, bias=False, stride=1, dilation=1) self.location_dense = LinearNorm(attention_n_filters, attention_dim, bias=False, w_init_gain='tanh') def forward(self, attention_weights_cat): processed_attention = self.location_conv(attention_weights_cat) processed_attention = processed_attention.transpose(1, 2) processed_attention = self.location_dense(processed_attention) return processed_attention class Attention(nn.Module): def __init__(self, attention_rnn_dim, embedding_dim, attention_dim, attention_location_n_filters, attention_location_kernel_size): super(Attention, self).__init__() self.query_layer = LinearNorm(attention_rnn_dim, attention_dim, bias=False, w_init_gain='tanh') self.memory_layer = LinearNorm(embedding_dim, attention_dim, bias=False, w_init_gain='tanh') self.v = LinearNorm(attention_dim, 1, bias=False) self.location_layer = LocationLayer(attention_location_n_filters, attention_location_kernel_size, attention_dim) self.score_mask_value = -float("inf") def get_alignment_energies(self, query, processed_memory, attention_weights_cat): """ PARAMS ------ query: decoder output (batch, n_mel_channels * n_frames_per_step) processed_memory: processed encoder outputs (B, T_in, attention_dim) attention_weights_cat: cumulative and prev. att weights (B, 2, max_time) RETURNS ------- alignment (batch, max_time) """ processed_query = self.query_layer(query.unsqueeze(1)) processed_attention_weights = self.location_layer(attention_weights_cat) energies = self.v(F.tanh( processed_query + processed_attention_weights + processed_memory)) energies = energies.squeeze(-1) return energies def forward(self, attention_hidden_state, memory, processed_memory, attention_weights_cat, mask): """ PARAMS ------ attention_hidden_state: attention rnn last output memory: encoder outputs processed_memory: processed encoder outputs attention_weights_cat: previous and cummulative attention weights mask: binary mask for padded data """ alignment = self.get_alignment_energies( attention_hidden_state, processed_memory, attention_weights_cat) if mask is not None: alignment.data.masked_fill_(mask, self.score_mask_value) attention_weights = F.softmax(alignment, dim=1) attention_context = torch.bmm(attention_weights.unsqueeze(1), memory) attention_context = attention_context.squeeze(1) return attention_context, attention_weights class Prenet(nn.Module): def __init__(self, in_dim, sizes): super(Prenet, self).__init__() in_sizes = [in_dim] + sizes[:-1] self.layers = nn.ModuleList( [LinearNorm(in_size, out_size, bias=False) for (in_size, out_size) in zip(in_sizes, sizes)]) def forward(self, x): for linear in self.layers: x = F.dropout(F.relu(linear(x)), p=0.5, training=True) return x class Postnet(nn.Module): """Postnet - Five 1-d convolution with 512 channels and kernel size 5 """ def __init__(self, hparams): super(Postnet, self).__init__() self.dropout = nn.Dropout(0.5) self.convolutions = nn.ModuleList() self.convolutions.append( nn.Sequential( ConvNorm(hparams.n_mel_channels, hparams.postnet_embedding_dim, kernel_size=hparams.postnet_kernel_size, stride=1, padding=int((hparams.postnet_kernel_size - 1) / 2), dilation=1, w_init_gain='tanh'), nn.BatchNorm1d(hparams.postnet_embedding_dim)) ) for i in range(1, hparams.postnet_n_convolutions - 1): self.convolutions.append( nn.Sequential( ConvNorm(hparams.postnet_embedding_dim, hparams.postnet_embedding_dim, kernel_size=hparams.postnet_kernel_size, stride=1, padding=int((hparams.postnet_kernel_size - 1) / 2), dilation=1, w_init_gain='tanh'), nn.BatchNorm1d(hparams.postnet_embedding_dim)) ) self.convolutions.append( nn.Sequential( ConvNorm(hparams.postnet_embedding_dim, hparams.n_mel_channels, kernel_size=hparams.postnet_kernel_size, stride=1, padding=int((hparams.postnet_kernel_size - 1) / 2), dilation=1, w_init_gain='linear'), nn.BatchNorm1d(hparams.n_mel_channels)) ) def forward(self, x): for i in range(len(self.convolutions) - 1): x = self.dropout(F.tanh(self.convolutions[i](x))) x = self.dropout(self.convolutions[-1](x)) return x class Encoder(nn.Module): """Encoder module: - Three 1-d convolution banks - Bidirectional LSTM """ def __init__(self, hparams): super(Encoder, self).__init__() self.dropout = nn.Dropout(0.5) convolutions = [] for _ in range(hparams.encoder_n_convolutions): conv_layer = nn.Sequential( ConvNorm(hparams.encoder_embedding_dim, hparams.encoder_embedding_dim, kernel_size=hparams.encoder_kernel_size, stride=1, padding=int((hparams.encoder_kernel_size - 1) / 2), dilation=1, w_init_gain='relu'), nn.BatchNorm1d(hparams.encoder_embedding_dim)) convolutions.append(conv_layer) self.convolutions = nn.ModuleList(convolutions) self.lstm = nn.LSTM(hparams.encoder_embedding_dim, int(hparams.encoder_embedding_dim / 2), 1, batch_first=True, bidirectional=True) def forward(self, x, input_lengths): for conv in self.convolutions: x = self.dropout(F.relu(conv(x))) x = x.transpose(1, 2) # pytorch tensor are not reversible, hence the conversion input_lengths = input_lengths.cpu().numpy() x = nn.utils.rnn.pack_padded_sequence( x, input_lengths, batch_first=True) self.lstm.flatten_parameters() outputs, _ = self.lstm(x) outputs, _ = nn.utils.rnn.pad_packed_sequence( outputs, batch_first=True) return outputs def inference(self, x): for conv in self.convolutions: x = self.dropout(F.relu(conv(x))) x = x.transpose(1, 2) self.lstm.flatten_parameters() outputs, _ = self.lstm(x) return outputs class Decoder(nn.Module): def __init__(self, hparams): super(Decoder, self).__init__() self.n_mel_channels = hparams.n_mel_channels self.n_frames_per_step = hparams.n_frames_per_step self.encoder_embedding_dim = hparams.encoder_embedding_dim self.attention_rnn_dim = hparams.attention_rnn_dim self.decoder_rnn_dim = hparams.decoder_rnn_dim self.prenet_dim = hparams.prenet_dim self.max_decoder_steps = hparams.max_decoder_steps self.gate_threshold = hparams.gate_threshold self.prenet = Prenet( hparams.n_mel_channels * hparams.n_frames_per_step, [hparams.prenet_dim, hparams.prenet_dim]) self.attention_rnn = nn.LSTMCell( hparams.decoder_rnn_dim + hparams.encoder_embedding_dim, hparams.attention_rnn_dim) self.attention_layer = Attention( hparams.attention_rnn_dim, hparams.encoder_embedding_dim, hparams.attention_dim, hparams.attention_location_n_filters, hparams.attention_location_kernel_size) self.decoder_rnn = nn.LSTMCell( hparams.prenet_dim + hparams.encoder_embedding_dim, hparams.decoder_rnn_dim, 1) self.linear_projection = LinearNorm( hparams.decoder_rnn_dim + hparams.encoder_embedding_dim, hparams.n_mel_channels*hparams.n_frames_per_step) self.gate_layer = LinearNorm( hparams.decoder_rnn_dim + hparams.encoder_embedding_dim, 1, bias=True, w_init_gain='sigmoid') def get_go_frame(self, memory): """ Gets all zeros frames to use as first decoder input PARAMS ------ memory: decoder outputs RETURNS ------- decoder_input: all zeros frames """ B = memory.size(0) decoder_input = Variable(memory.data.new( B, self.n_mel_channels * self.n_frames_per_step).zero_()) return decoder_input def initialize_decoder_states(self, memory, mask): """ Initializes attention rnn states, decoder rnn states, attention weights, attention cumulative weights, attention context, stores memory and stores processed memory PARAMS ------ memory: Encoder outputs mask: Mask for padded data if training, expects None for inference """ B = memory.size(0) MAX_TIME = memory.size(1) self.attention_hidden = Variable(memory.data.new( B, self.attention_rnn_dim).zero_()) self.attention_cell = Variable(memory.data.new( B, self.attention_rnn_dim).zero_()) self.decoder_hidden = Variable(memory.data.new( B, self.decoder_rnn_dim).zero_()) self.decoder_cell = Variable(memory.data.new( B, self.decoder_rnn_dim).zero_()) self.attention_weights = Variable(memory.data.new( B, MAX_TIME).zero_()) self.attention_weights_cum = Variable(memory.data.new( B, MAX_TIME).zero_()) self.attention_context = Variable(memory.data.new( B, self.encoder_embedding_dim).zero_()) self.memory = memory self.processed_memory = self.attention_layer.memory_layer(memory) self.mask = mask def parse_decoder_inputs(self, decoder_inputs): """ Prepares decoder inputs, i.e. mel outputs PARAMS ------ decoder_inputs: inputs used for teacher-forced training, i.e. mel-specs RETURNS ------- inputs: processed decoder inputs """ # (B, n_mel_channels, T_out) -> (B, T_out, n_mel_channels) decoder_inputs = decoder_inputs.transpose(1, 2) decoder_inputs = decoder_inputs.view( decoder_inputs.size(0), int(decoder_inputs.size(1)/self.n_frames_per_step), -1) # (B, T_out, n_mel_channels) -> (T_out, B, n_mel_channels) decoder_inputs = decoder_inputs.transpose(0, 1) return decoder_inputs def parse_decoder_outputs(self, mel_outputs, gate_outputs, alignments): """ Prepares decoder outputs for output PARAMS ------ mel_outputs: gate_outputs: gate output energies alignments: RETURNS ------- mel_outputs: gate_outpust: gate output energies alignments: """ # (T_out, B) -> (B, T_out) alignments = torch.stack(alignments).transpose(0, 1) # (T_out, B) -> (B, T_out) gate_outputs = torch.stack(gate_outputs).transpose(0, 1) gate_outputs = gate_outputs.contiguous() # (T_out, B, n_mel_channels) -> (B, T_out, n_mel_channels) mel_outputs = torch.stack(mel_outputs).transpose(0, 1).contiguous() # decouple frames per step mel_outputs = mel_outputs.view( mel_outputs.size(0), -1, self.n_mel_channels) # (B, T_out, n_mel_channels) -> (B, n_mel_channels, T_out) mel_outputs = mel_outputs.transpose(1, 2) return mel_outputs, gate_outputs, alignments def decode(self, decoder_input): """ Decoder step using stored states, attention and memory PARAMS ------ decoder_input: previous mel output RETURNS ------- mel_output: gate_output: gate output energies attention_weights: """ cell_input = torch.cat((self.decoder_hidden, self.attention_context), -1) self.attention_hidden, self.attention_cell = self.attention_rnn( cell_input, (self.attention_hidden, self.attention_cell)) attention_weights_cat = torch.cat( (self.attention_weights.unsqueeze(1), self.attention_weights_cum.unsqueeze(1)), dim=1) self.attention_context, self.attention_weights = self.attention_layer( self.attention_hidden, self.memory, self.processed_memory, attention_weights_cat, self.mask) self.attention_weights_cum += self.attention_weights prenet_output = self.prenet(decoder_input) decoder_input = torch.cat((prenet_output, self.attention_context), -1) self.decoder_hidden, self.decoder_cell = self.decoder_rnn( decoder_input, (self.decoder_hidden, self.decoder_cell)) decoder_hidden_attention_context = torch.cat( (self.decoder_hidden, self.attention_context), dim=1) decoder_output = self.linear_projection( decoder_hidden_attention_context) gate_prediction = self.gate_layer(decoder_hidden_attention_context) return decoder_output, gate_prediction, self.attention_weights def forward(self, memory, decoder_inputs, memory_lengths): """ Decoder forward pass for training PARAMS ------ memory: Encoder outputs decoder_inputs: Decoder inputs for teacher forcing. i.e. mel-specs memory_lengths: Encoder output lengths for attention masking. RETURNS ------- mel_outputs: mel outputs from the decoder gate_outputs: gate outputs from the decoder alignments: sequence of attention weights from the decoder """ decoder_input = self.get_go_frame(memory) decoder_inputs = self.parse_decoder_inputs(decoder_inputs) self.initialize_decoder_states( memory, mask=~get_mask_from_lengths(memory_lengths)) mel_outputs, gate_outputs, alignments = [], [], [] while len(mel_outputs) < decoder_inputs.size(0): mel_output, gate_output, attention_weights = self.decode( decoder_input) mel_outputs += [mel_output] gate_outputs += [gate_output.squeeze(1)] alignments += [attention_weights] decoder_input = decoder_inputs[len(mel_outputs) - 1] mel_outputs, gate_outputs, alignments = self.parse_decoder_outputs( mel_outputs, gate_outputs, alignments) return mel_outputs, gate_outputs, alignments def inference(self, memory): """ Decoder inference PARAMS ------ memory: Encoder outputs RETURNS ------- mel_outputs: mel outputs from the decoder gate_outputs: gate outputs from the decoder alignments: sequence of attention weights from the decoder """ decoder_input = self.get_go_frame(memory) self.initialize_decoder_states(memory, mask=None) mel_outputs, gate_outputs, alignments = [], [], [] while True: mel_output, gate_output, alignment = self.decode(decoder_input) mel_outputs += [mel_output] gate_outputs += [gate_output.squeeze(1)] alignments += [alignment] if F.sigmoid(gate_output.data) > self.gate_threshold: break elif len(mel_outputs) == self.max_decoder_steps: print("Warning! Reached max decoder steps") break decoder_input = mel_output mel_outputs, gate_outputs, alignments = self.parse_decoder_outputs( mel_outputs, gate_outputs, alignments) return mel_outputs, gate_outputs, alignments class Tacotron2(nn.Module): def __init__(self, hparams): super(Tacotron2, self).__init__() self.mask_padding = hparams.mask_padding self.fp16_run = hparams.fp16_run self.n_mel_channels = hparams.n_mel_channels self.n_frames_per_step = hparams.n_frames_per_step self.embedding = nn.Embedding( hparams.n_symbols, hparams.symbols_embedding_dim) torch.nn.init.xavier_uniform_(self.embedding.weight.data) self.encoder = Encoder(hparams) self.decoder = Decoder(hparams) self.postnet = Postnet(hparams) def parse_batch(self, batch): text_padded, input_lengths, mel_padded, gate_padded, \ output_lengths = batch text_padded = to_gpu(text_padded).long() max_len = int(torch.max(input_lengths.data).numpy()) input_lengths = to_gpu(input_lengths).long() mel_padded = to_gpu(mel_padded).float() gate_padded = to_gpu(gate_padded).float() output_lengths = to_gpu(output_lengths).long() return ( (text_padded, input_lengths, mel_padded, max_len, output_lengths), (mel_padded, gate_padded)) def parse_input(self, inputs): inputs = fp32_to_fp16(inputs) if self.fp16_run else inputs return inputs def parse_output(self, outputs, output_lengths=None): if self.mask_padding and output_lengths is not None: mask = ~get_mask_from_lengths(output_lengths+1) # +1 <stop> token mask = mask.expand(self.n_mel_channels, mask.size(0), mask.size(1)) mask = mask.permute(1, 0, 2) outputs[0].data.masked_fill_(mask, 0.0) outputs[1].data.masked_fill_(mask, 0.0) outputs[2].data.masked_fill_(mask[:, 0, :], 1e3) # gate energies outputs = fp16_to_fp32(outputs) if self.fp16_run else outputs return outputs def forward(self, inputs): inputs, input_lengths, targets, max_len, \ output_lengths = self.parse_input(inputs) input_lengths, output_lengths = input_lengths.data, output_lengths.data embedded_inputs = self.embedding(inputs).transpose(1, 2) encoder_outputs = self.encoder(embedded_inputs, input_lengths) mel_outputs, gate_outputs, alignments = self.decoder( encoder_outputs, targets, memory_lengths=input_lengths) mel_outputs_postnet = self.postnet(mel_outputs) mel_outputs_postnet = mel_outputs + mel_outputs_postnet # DataParallel expects equal sized inputs/outputs, hence padding if input_lengths is not None: alignments = alignments.unsqueeze(0) alignments = nn.functional.pad( alignments, (0, max_len - alignments.size(3), 0, 0), "constant", 0) alignments = alignments.squeeze() return self.parse_output( [mel_outputs, mel_outputs_postnet, gate_outputs, alignments], output_lengths) def inference(self, inputs): inputs = self.parse_input(inputs) embedded_inputs = self.embedding(inputs).transpose(1, 2) encoder_outputs = self.encoder.inference(embedded_inputs) mel_outputs, gate_outputs, alignments = self.decoder.inference( encoder_outputs) mel_outputs_postnet = self.postnet(mel_outputs) mel_outputs_postnet = mel_outputs + mel_outputs_postnet outputs = self.parse_output( [mel_outputs, mel_outputs_postnet, gate_outputs, alignments]) return outputs
""" BSD 3-Clause License Copyright (c) 2017, Prem Seetharaman All rights reserved. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import torch import numpy as np import torch.nn.functional as F from torch.autograd import Variable from scipy.signal import get_window from librosa.util import pad_center, tiny from audio_processing import window_sumsquare class STFT(torch.nn.Module): """adapted from Prem Seetharaman's https://github.com/pseeth/pytorch-stft""" def __init__(self, filter_length=800, hop_length=200, win_length=800, window='hann'): super(STFT, self).__init__() self.filter_length = filter_length self.hop_length = hop_length self.win_length = win_length self.window = window self.forward_transform = None scale = self.filter_length / self.hop_length fourier_basis = np.fft.fft(np.eye(self.filter_length)) cutoff = int((self.filter_length / 2 + 1)) fourier_basis = np.vstack([np.real(fourier_basis[:cutoff, :]), np.imag(fourier_basis[:cutoff, :])]) forward_basis = torch.FloatTensor(fourier_basis[:, None, :]) inverse_basis = torch.FloatTensor( np.linalg.pinv(scale * fourier_basis).T[:, None, :]) if window is not None: assert(win_length >= filter_length) # get window and zero center pad it to filter_length fft_window = get_window(window, win_length, fftbins=True) fft_window = pad_center(fft_window, filter_length) fft_window = torch.from_numpy(fft_window).float() # window the bases forward_basis *= fft_window inverse_basis *= fft_window self.register_buffer('forward_basis', forward_basis.float()) self.register_buffer('inverse_basis', inverse_basis.float()) def transform(self, input_data): num_batches = input_data.size(0) num_samples = input_data.size(1) self.num_samples = num_samples # similar to librosa, reflect-pad the input input_data = input_data.view(num_batches, 1, num_samples) input_data = F.pad( input_data.unsqueeze(1), (int(self.filter_length / 2), int(self.filter_length / 2), 0, 0), mode='reflect') input_data = input_data.squeeze(1) forward_transform = F.conv1d( input_data, Variable(self.forward_basis, requires_grad=False), stride=self.hop_length, padding=0) cutoff = int((self.filter_length / 2) + 1) real_part = forward_transform[:, :cutoff, :] imag_part = forward_transform[:, cutoff:, :] magnitude = torch.sqrt(real_part**2 + imag_part**2) phase = torch.autograd.Variable( torch.atan2(imag_part.data, real_part.data)) return magnitude, phase def inverse(self, magnitude, phase): recombine_magnitude_phase = torch.cat( [magnitude*torch.cos(phase), magnitude*torch.sin(phase)], dim=1) inverse_transform = F.conv_transpose1d( recombine_magnitude_phase, Variable(self.inverse_basis, requires_grad=False), stride=self.hop_length, padding=0) if self.window is not None: window_sum = window_sumsquare( self.window, magnitude.size(-1), hop_length=self.hop_length, win_length=self.win_length, n_fft=self.filter_length, dtype=np.float32) # remove modulation effects approx_nonzero_indices = torch.from_numpy( np.where(window_sum > tiny(window_sum))[0]) window_sum = torch.autograd.Variable( torch.from_numpy(window_sum), requires_grad=False) inverse_transform[:, :, approx_nonzero_indices] /= window_sum[approx_nonzero_indices] # scale by hop ratio inverse_transform *= float(self.filter_length) / self.hop_length inverse_transform = inverse_transform[:, :, int(self.filter_length/2):] inverse_transform = inverse_transform[:, :, :-int(self.filter_length/2):] return inverse_transform def forward(self, input_data): self.magnitude, self.phase = self.transform(input_data) reconstruction = self.inverse(self.magnitude, self.phase) return reconstruction
import torch import torch.distributed as dist from torch.nn.modules import Module def _flatten_dense_tensors(tensors): """Flatten dense tensors into a contiguous 1D buffer. Assume tensors are of same dense type. Since inputs are dense, the resulting tensor will be a concatenated 1D buffer. Element-wise operation on this buffer will be equivalent to operating individually. Arguments: tensors (Iterable[Tensor]): dense tensors to flatten. Returns: A contiguous 1D buffer containing input tensors. """ if len(tensors) == 1: return tensors[0].contiguous().view(-1) flat = torch.cat([t.contiguous().view(-1) for t in tensors], dim=0) return flat def _unflatten_dense_tensors(flat, tensors): """View a flat buffer using the sizes of tensors. Assume that tensors are of same dense type, and that flat is given by _flatten_dense_tensors. Arguments: flat (Tensor): flattened dense tensors to unflatten. tensors (Iterable[Tensor]): dense tensors whose sizes will be used to unflatten flat. Returns: Unflattened dense tensors with sizes same as tensors and values from flat. """ outputs = [] offset = 0 for tensor in tensors: numel = tensor.numel() outputs.append(flat.narrow(0, offset, numel).view_as(tensor)) offset += numel return tuple(outputs) ''' This version of DistributedDataParallel is designed to be used in conjunction with the multiproc.py launcher included with this example. It assumes that your run is using multiprocess with 1 GPU/process, that the model is on the correct device, and that torch.set_device has been used to set the device. Parameters are broadcasted to the other processes on initialization of DistributedDataParallel, and will be allreduced at the finish of the backward pass. ''' class DistributedDataParallel(Module): def __init__(self, module): super(DistributedDataParallel, self).__init__() #fallback for PyTorch 0.3 if not hasattr(dist, '_backend'): self.warn_on_half = True else: self.warn_on_half = True if dist._backend == dist.dist_backend.GLOO else False self.module = module for p in self.module.state_dict().values(): if not torch.is_tensor(p): continue dist.broadcast(p, 0) def allreduce_params(): if(self.needs_reduction): self.needs_reduction = False buckets = {} for param in self.module.parameters(): if param.requires_grad and param.grad is not None: tp = type(param.data) if tp not in buckets: buckets[tp] = [] buckets[tp].append(param) if self.warn_on_half: if torch.cuda.HalfTensor in buckets: print("WARNING: gloo dist backend for half parameters may be extremely slow." + " It is recommended to use the NCCL backend in this case. This currently requires" + "PyTorch built from top of tree master.") self.warn_on_half = False for tp in buckets: bucket = buckets[tp] grads = [param.grad.data for param in bucket] coalesced = _flatten_dense_tensors(grads) dist.all_reduce(coalesced) coalesced /= dist.get_world_size() for buf, synced in zip(grads, _unflatten_dense_tensors(coalesced, grads)): buf.copy_(synced) for param in list(self.module.parameters()): def allreduce_hook(*unused): param._execution_engine.queue_callback(allreduce_params) if param.requires_grad: param.register_hook(allreduce_hook) def forward(self, *inputs, **kwargs): self.needs_reduction = True return self.module(*inputs, **kwargs) ''' def _sync_buffers(self): buffers = list(self.module._all_buffers()) if len(buffers) > 0: # cross-node buffer sync flat_buffers = _flatten_dense_tensors(buffers) dist.broadcast(flat_buffers, 0) for buf, synced in zip(buffers, _unflatten_dense_tensors(flat_buffers, buffers)): buf.copy_(synced) def train(self, mode=True): # Clear NCCL communicator and CUDA event cache of the default group ID, # These cache will be recreated at the later call. This is currently a # work-around for a potential NCCL deadlock. if dist._backend == dist.dist_backend.NCCL: dist._clear_group_cache() super(DistributedDataParallel, self).train(mode) self.module.train(mode) '''
import random import numpy as np import torch import torch.utils.data import layers from utils import load_wav_to_torch, load_filepaths_and_text from text import text_to_sequence class TextMelLoader(torch.utils.data.Dataset): """ 1) loads audio,text pairs 2) normalizes text and converts them to sequences of one-hot vectors 3) computes mel-spectrograms from audio files. """ def __init__(self, audiopaths_and_text, hparams, shuffle=True): self.audiopaths_and_text = load_filepaths_and_text( audiopaths_and_text, hparams.sort_by_length) self.text_cleaners = hparams.text_cleaners self.max_wav_value = hparams.max_wav_value self.sampling_rate = hparams.sampling_rate self.load_mel_from_disk = hparams.load_mel_from_disk self.stft = layers.TacotronSTFT( hparams.filter_length, hparams.hop_length, hparams.win_length, hparams.n_mel_channels, hparams.sampling_rate, hparams.mel_fmin, hparams.mel_fmax) random.seed(1234) if shuffle: random.shuffle(self.audiopaths_and_text) def get_mel_text_pair(self, audiopath_and_text): # separate filename and text audiopath, text = audiopath_and_text[0], audiopath_and_text[1] text = self.get_text(text) mel = self.get_mel(audiopath) return (text, mel) def get_mel(self, filename): if not self.load_mel_from_disk: audio = load_wav_to_torch(filename, self.sampling_rate) audio_norm = audio / self.max_wav_value audio_norm = audio_norm.unsqueeze(0) audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False) melspec = self.stft.mel_spectrogram(audio_norm) melspec = torch.squeeze(melspec, 0) else: melspec = torch.from_numpy(np.load(filename)) assert melspec.size(0) == self.stft.n_mel_channels, ( 'Mel dimension mismatch: given {}, expected {}'.format( melspec.size(0), self.stft.n_mel_channels)) return melspec def get_text(self, text): text_norm = torch.IntTensor(text_to_sequence(text, self.text_cleaners)) return text_norm def __getitem__(self, index): return self.get_mel_text_pair(self.audiopaths_and_text[index]) def __len__(self): return len(self.audiopaths_and_text) class TextMelCollate(): """ Zero-pads model inputs and targets based on number of frames per setep """ def __init__(self, n_frames_per_step): self.n_frames_per_step = n_frames_per_step def __call__(self, batch): """Collate's training batch from normalized text and mel-spectrogram PARAMS ------ batch: [text_normalized, mel_normalized] """ # Right zero-pad all one-hot text sequences to max input length input_lengths, ids_sorted_decreasing = torch.sort( torch.LongTensor([len(x[0]) for x in batch]), dim=0, descending=True) max_input_len = input_lengths[0] text_padded = torch.LongTensor(len(batch), max_input_len) text_padded.zero_() for i in range(len(ids_sorted_decreasing)): text = batch[ids_sorted_decreasing[i]][0] text_padded[i, :text.size(0)] = text # Right zero-pad mel-spec with extra single zero vector to mark the end num_mels = batch[0][1].size(0) max_target_len = max([x[1].size(1) for x in batch]) + 1 if max_target_len % self.n_frames_per_step != 0: max_target_len += self.n_frames_per_step - max_target_len % self.n_frames_per_step assert max_target_len % self.n_frames_per_step == 0 # include mel padded and gate padded mel_padded = torch.FloatTensor(len(batch), num_mels, max_target_len) mel_padded.zero_() gate_padded = torch.FloatTensor(len(batch), max_target_len) gate_padded.zero_() output_lengths = torch.LongTensor(len(batch)) for i in range(len(ids_sorted_decreasing)): mel = batch[ids_sorted_decreasing[i]][1] mel_padded[i, :, :mel.size(1)] = mel gate_padded[i, mel.size(1):] = 1 output_lengths[i] = mel.size(1) return text_padded, input_lengths, mel_padded, gate_padded, \ output_lengths
from torch import nn class Tacotron2Loss(nn.Module): def __init__(self): super(Tacotron2Loss, self).__init__() def forward(self, model_output, targets): mel_target, gate_target = targets[0], targets[1] mel_target.requires_grad = False gate_target.requires_grad = False gate_target = gate_target.view(-1, 1) mel_out, mel_out_postnet, gate_out, _ = model_output gate_out = gate_out.view(-1, 1) mel_loss = nn.MSELoss()(mel_out, mel_target) + \ nn.MSELoss()(mel_out_postnet, mel_target) gate_loss = nn.BCEWithLogitsLoss()(gate_out, gate_target) return mel_loss + gate_loss
import numpy as np from scipy.io.wavfile import read import torch def get_mask_from_lengths(lengths): max_len = torch.max(lengths) ids = torch.arange(0, max_len).long().cuda() mask = (ids < lengths.unsqueeze(1)).byte() return mask def load_wav_to_torch(full_path, sr): sampling_rate, data = read(full_path) assert sr == sampling_rate, "{} SR doesn't match {} on path {}".format( sr, sampling_rate, full_path) return torch.FloatTensor(data.astype(np.float32)) def load_filepaths_and_text(filename, sort_by_length, split="|"): with open(filename, encoding='utf-8') as f: filepaths_and_text = [line.strip().split(split) for line in f] if sort_by_length: filepaths_and_text.sort(key=lambda x: len(x[1])) return filepaths_and_text def to_gpu(x): x = x.contiguous().cuda(async=True) return torch.autograd.Variable(x)
import os import time import argparse import math from numpy import finfo import torch from distributed import DistributedDataParallel from torch.utils.data.distributed import DistributedSampler from torch.nn import DataParallel from torch.utils.data import DataLoader from fp16_optimizer import FP16_Optimizer from model import Tacotron2 from data_utils import TextMelLoader, TextMelCollate from loss_function import Tacotron2Loss from logger import Tacotron2Logger from hparams import create_hparams def batchnorm_to_float(module): """Converts batch norm modules to FP32""" if isinstance(module, torch.nn.modules.batchnorm._BatchNorm): module.float() for child in module.children(): batchnorm_to_float(child) return module def reduce_tensor(tensor, num_gpus): rt = tensor.clone() torch.distributed.all_reduce(rt, op=torch.distributed.reduce_op.SUM) rt /= num_gpus return rt def init_distributed(hparams, n_gpus, rank, group_name): assert torch.cuda.is_available(), "Distributed mode requires CUDA." print("Initializing distributed") # Set cuda device so everything is done on the right GPU. torch.cuda.set_device(rank % torch.cuda.device_count()) # Initialize distributed communication torch.distributed.init_process_group( backend=hparams.dist_backend, init_method=hparams.dist_url, world_size=n_gpus, rank=rank, group_name=group_name) print("Done initializing distributed") def prepare_dataloaders(hparams): # Get data, data loaders and collate function ready trainset = TextMelLoader(hparams.training_files, hparams) valset = TextMelLoader(hparams.validation_files, hparams) collate_fn = TextMelCollate(hparams.n_frames_per_step) train_sampler = DistributedSampler(trainset) \ if hparams.distributed_run else None train_loader = DataLoader(trainset, num_workers=1, shuffle=False, sampler=train_sampler, batch_size=hparams.batch_size, pin_memory=False, drop_last=True, collate_fn=collate_fn) return train_loader, valset, collate_fn def prepare_directories_and_logger(output_directory, log_directory, rank): if rank == 0: if not os.path.isdir(output_directory): os.makedirs(output_directory) os.chmod(output_directory, 0o775) logger = Tacotron2Logger(os.path.join(output_directory, log_directory)) else: logger = None return logger def load_model(hparams): model = Tacotron2(hparams).cuda() if hparams.fp16_run: model = batchnorm_to_float(model.half()) model.decoder.attention_layer.score_mask_value = float(finfo('float16').min) if hparams.distributed_run: model = DistributedDataParallel(model) elif torch.cuda.device_count() > 1: model = DataParallel(model) return model def warm_start_model(checkpoint_path, model): assert os.path.isfile(checkpoint_path) print("Warm starting model from checkpoint '{}'".format(checkpoint_path)) checkpoint_dict = torch.load(checkpoint_path, map_location='cpu') model.load_state_dict(checkpoint_dict['state_dict']) return model def load_checkpoint(checkpoint_path, model, optimizer): assert os.path.isfile(checkpoint_path) print("Loading checkpoint '{}'".format(checkpoint_path)) checkpoint_dict = torch.load(checkpoint_path, map_location='cpu') model.load_state_dict(checkpoint_dict['state_dict']) optimizer.load_state_dict(checkpoint_dict['optimizer']) learning_rate = checkpoint_dict['learning_rate'] iteration = checkpoint_dict['iteration'] print("Loaded checkpoint '{}' from iteration {}" .format( checkpoint_path, iteration)) return model, optimizer, learning_rate, iteration def save_checkpoint(model, optimizer, learning_rate, iteration, filepath): print("Saving model and optimizer state at iteration {} to {}".format( iteration, filepath)) torch.save({'iteration': iteration, 'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict(), 'learning_rate': learning_rate}, filepath) def validate(model, criterion, valset, iteration, batch_size, n_gpus, collate_fn, logger, distributed_run, rank): """Handles all the validation scoring and printing""" model.eval() with torch.no_grad(): val_sampler = DistributedSampler(valset) if distributed_run else None val_loader = DataLoader(valset, sampler=val_sampler, num_workers=1, shuffle=False, batch_size=batch_size, pin_memory=False, collate_fn=collate_fn) val_loss = 0.0 if distributed_run or torch.cuda.device_count() > 1: batch_parser = model.module.parse_batch else: batch_parser = model.parse_batch for i, batch in enumerate(val_loader): x, y = batch_parser(batch) y_pred = model(x) loss = criterion(y_pred, y) reduced_val_loss = reduce_tensor(loss.data, n_gpus)[0] \ if distributed_run else loss.data[0] val_loss += reduced_val_loss val_loss = val_loss / (i + 1) model.train() return val_loss def train(output_directory, log_directory, checkpoint_path, warm_start, n_gpus, rank, group_name, hparams): """Training and validation logging results to tensorboard and stdout Params ------ output_directory (string): directory to save checkpoints log_directory (string) directory to save tensorboard logs checkpoint_path(string): checkpoint path n_gpus (int): number of gpus rank (int): rank of current gpu hparams (object): comma separated list of "name=value" pairs. """ if hparams.distributed_run: init_distributed(hparams, n_gpus, rank, group_name) torch.manual_seed(hparams.seed) torch.cuda.manual_seed(hparams.seed) model = load_model(hparams) learning_rate = hparams.learning_rate optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=hparams.weight_decay) if hparams.fp16_run: optimizer = FP16_Optimizer( optimizer, dynamic_loss_scale=hparams.dynamic_loss_scaling) criterion = Tacotron2Loss() logger = prepare_directories_and_logger( output_directory, log_directory, rank) train_loader, valset, collate_fn = prepare_dataloaders(hparams) # Load checkpoint if one exists iteration = 0 epoch_offset = 0 if checkpoint_path is not None: if warm_start: model = warm_start_model(checkpoint_path, model) else: model, optimizer, _learning_rate, iteration = load_checkpoint( checkpoint_path, model, optimizer) if hparams.use_saved_learning_rate: learning_rate = _learning_rate iteration += 1 # next iteration is iteration + 1 epoch_offset = max(0, int(iteration / len(train_loader))) model.train() if hparams.distributed_run or torch.cuda.device_count() > 1: batch_parser = model.module.parse_batch else: batch_parser = model.parse_batch # ================ MAIN TRAINNIG LOOP! =================== for epoch in range(epoch_offset, hparams.epochs): print("Epoch: {}".format(epoch)) for i, batch in enumerate(train_loader): start = time.perf_counter() for param_group in optimizer.param_groups: param_group['lr'] = learning_rate model.zero_grad() x, y = batch_parser(batch) y_pred = model(x) loss = criterion(y_pred, y) reduced_loss = reduce_tensor(loss.data, n_gpus)[0] \ if hparams.distributed_run else loss.data[0] if hparams.fp16_run: optimizer.backward(loss) grad_norm = optimizer.clip_fp32_grads(hparams.grad_clip_thresh) else: loss.backward() grad_norm = torch.nn.utils.clip_grad_norm( model.parameters(), hparams.grad_clip_thresh) optimizer.step() overflow = optimizer.overflow if hparams.fp16_run else False if not overflow and not math.isnan(reduced_loss) and rank == 0: duration = time.perf_counter() - start print("Train loss {} {:.6f} Grad Norm {:.6f} {:.2f}s/it".format( iteration, reduced_loss, grad_norm, duration)) logger.log_training( reduced_loss, grad_norm, learning_rate, duration, iteration) if not overflow and (iteration % hparams.iters_per_checkpoint == 0): reduced_val_loss = validate( model, criterion, valset, iteration, hparams.batch_size, n_gpus, collate_fn, logger, hparams.distributed_run, rank) if rank == 0: print("Validation loss {}: {:9f} ".format( iteration, reduced_val_loss)) logger.log_validation( reduced_val_loss, model, y, y_pred, iteration) checkpoint_path = os.path.join( output_directory, "checkpoint_{}".format(iteration)) save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path) iteration += 1 if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-o', '--output_directory', type=str, help='directory to save checkpoints') parser.add_argument('-l', '--log_directory', type=str, help='directory to save tensorboard logs') parser.add_argument('-c', '--checkpoint_path', type=str, default=None, required=False, help='checkpoint path') parser.add_argument('--warm_start', action='store_true', help='load the model only (warm start)') parser.add_argument('--n_gpus', type=int, default=1, required=False, help='number of gpus') parser.add_argument('--rank', type=int, default=0, required=False, help='rank of current gpu') parser.add_argument('--group_name', type=str, default='group_name', required=False, help='Distributed group name') parser.add_argument('--hparams', type=str, required=False, help='comma separated name=value pairs') args = parser.parse_args() hparams = create_hparams(args.hparams) torch.backends.cudnn.enabled = hparams.cudnn_enabled torch.backends.cudnn.benchmark = hparams.cudnn_benchmark print("FP16 Run:", hparams.fp16_run) print("Dynamic Loss Scaling:", hparams.dynamic_loss_scaling) print("Distributed Run:", hparams.distributed_run) print("cuDNN Enabled:", hparams.cudnn_enabled) print("cuDNN Benchmark:", hparams.cudnn_benchmark) train(args.output_directory, args.log_directory, args.checkpoint_path, args.warm_start, args.n_gpus, args.rank, args.group_name, hparams)
import torch from librosa.filters import mel as librosa_mel_fn from audio_processing import dynamic_range_compression from audio_processing import dynamic_range_decompression from stft import STFT class LinearNorm(torch.nn.Module): def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'): super(LinearNorm, self).__init__() self.linear_layer = torch.nn.Linear(in_dim, out_dim, bias=bias) torch.nn.init.xavier_uniform( self.linear_layer.weight, gain=torch.nn.init.calculate_gain(w_init_gain)) def forward(self, x): return self.linear_layer(x) class ConvNorm(torch.nn.Module): def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=None, dilation=1, bias=True, w_init_gain='linear'): super(ConvNorm, self).__init__() if padding is None: assert(kernel_size % 2 == 1) padding = int(dilation * (kernel_size - 1) / 2) self.conv = torch.nn.Conv1d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, bias=bias) torch.nn.init.xavier_uniform( self.conv.weight, gain=torch.nn.init.calculate_gain(w_init_gain)) def forward(self, signal): conv_signal = self.conv(signal) return conv_signal class TacotronSTFT(torch.nn.Module): def __init__(self, filter_length=1024, hop_length=256, win_length=1024, n_mel_channels=80, sampling_rate=22050, mel_fmin=0.0, mel_fmax=None): super(TacotronSTFT, self).__init__() self.n_mel_channels = n_mel_channels self.sampling_rate = sampling_rate self.stft_fn = STFT(filter_length, hop_length, win_length) mel_basis = librosa_mel_fn( sampling_rate, filter_length, n_mel_channels, mel_fmin, mel_fmax) mel_basis = torch.from_numpy(mel_basis).float() self.register_buffer('mel_basis', mel_basis) def spectral_normalize(self, magnitudes): output = dynamic_range_compression(magnitudes) return output def spectral_de_normalize(self, magnitudes): output = dynamic_range_decompression(magnitudes) return output def mel_spectrogram(self, y): """Computes mel-spectrograms from a batch of waves PARAMS ------ y: Variable(torch.FloatTensor) with shape (B, T) in range [-1, 1] RETURNS ------- mel_output: torch.FloatTensor of shape (B, n_mel_channels, T) """ assert(torch.min(y.data) >= -1) assert(torch.max(y.data) <= 1) magnitudes, phases = self.stft_fn.transform(y) magnitudes = magnitudes.data mel_output = torch.matmul(self.mel_basis, magnitudes) mel_output = self.spectral_normalize(mel_output) return mel_output
import time import torch import sys import subprocess argslist = list(sys.argv)[1:] num_gpus = torch.cuda.device_count() argslist.append('--n_gpus={}'.format(num_gpus)) workers = [] job_id = time.strftime("%Y_%m_%d-%H%M%S") argslist.append("--group_name=group_{}".format(job_id)) for i in range(num_gpus): argslist.append('--rank={}'.format(i)) stdout = None if i == 0 else open("logs/{}_GPU_{}.log".format(job_id, i), "w") print(argslist) p = subprocess.Popen([str(sys.executable)]+argslist, stdout=stdout) workers.append(p) argslist = argslist[:-1] for p in workers: p.wait()
import torch class LossScaler: def __init__(self, scale=1): self.cur_scale = scale # `params` is a list / generator of torch.Variable def has_overflow(self, params): return False # `x` is a torch.Tensor def _has_inf_or_nan(x): return False # `overflow` is boolean indicating whether we overflowed in gradient def update_scale(self, overflow): pass @property def loss_scale(self): return self.cur_scale def scale_gradient(self, module, grad_in, grad_out): return tuple(self.loss_scale * g for g in grad_in) def backward(self, loss): scaled_loss = loss*self.loss_scale scaled_loss.backward() class DynamicLossScaler: def __init__(self, init_scale=2**32, scale_factor=2., scale_window=1000): self.cur_scale = init_scale self.cur_iter = 0 self.last_overflow_iter = -1 self.scale_factor = scale_factor self.scale_window = scale_window # `params` is a list / generator of torch.Variable def has_overflow(self, params): # return False for p in params: if p.grad is not None and DynamicLossScaler._has_inf_or_nan(p.grad.data): return True return False # `x` is a torch.Tensor def _has_inf_or_nan(x): cpu_sum = float(x.float().sum()) if cpu_sum == float('inf') or cpu_sum == -float('inf') or cpu_sum != cpu_sum: return True return False # `overflow` is boolean indicating whether we overflowed in gradient def update_scale(self, overflow): if overflow: #self.cur_scale /= self.scale_factor self.cur_scale = max(self.cur_scale/self.scale_factor, 1) self.last_overflow_iter = self.cur_iter else: if (self.cur_iter - self.last_overflow_iter) % self.scale_window == 0: self.cur_scale *= self.scale_factor # self.cur_scale = 1 self.cur_iter += 1 @property def loss_scale(self): return self.cur_scale def scale_gradient(self, module, grad_in, grad_out): return tuple(self.loss_scale * g for g in grad_in) def backward(self, loss): scaled_loss = loss*self.loss_scale scaled_loss.backward() ############################################################## # Example usage below here -- assuming it's in a separate file ############################################################## if __name__ == "__main__": import torch from torch.autograd import Variable from dynamic_loss_scaler import DynamicLossScaler # N is batch size; D_in is input dimension; # H is hidden dimension; D_out is output dimension. N, D_in, H, D_out = 64, 1000, 100, 10 # Create random Tensors to hold inputs and outputs, and wrap them in Variables. x = Variable(torch.randn(N, D_in), requires_grad=False) y = Variable(torch.randn(N, D_out), requires_grad=False) w1 = Variable(torch.randn(D_in, H), requires_grad=True) w2 = Variable(torch.randn(H, D_out), requires_grad=True) parameters = [w1, w2] learning_rate = 1e-6 optimizer = torch.optim.SGD(parameters, lr=learning_rate) loss_scaler = DynamicLossScaler() for t in range(500): y_pred = x.mm(w1).clamp(min=0).mm(w2) loss = (y_pred - y).pow(2).sum() * loss_scaler.loss_scale print('Iter {} loss scale: {}'.format(t, loss_scaler.loss_scale)) print('Iter {} scaled loss: {}'.format(t, loss.data[0])) print('Iter {} unscaled loss: {}'.format(t, loss.data[0] / loss_scaler.loss_scale)) # Run backprop optimizer.zero_grad() loss.backward() # Check for overflow has_overflow = DynamicLossScaler.has_overflow(parameters) # If no overflow, unscale grad and update as usual if not has_overflow: for param in parameters: param.grad.data.mul_(1. / loss_scaler.loss_scale) optimizer.step() # Otherwise, don't do anything -- ie, skip iteration else: print('OVERFLOW!') # Update loss scale for next iteration loss_scaler.update_scale(has_overflow)
""" from https://github.com/keithito/tacotron """ import re valid_symbols = [ 'AA', 'AA0', 'AA1', 'AA2', 'AE', 'AE0', 'AE1', 'AE2', 'AH', 'AH0', 'AH1', 'AH2', 'AO', 'AO0', 'AO1', 'AO2', 'AW', 'AW0', 'AW1', 'AW2', 'AY', 'AY0', 'AY1', 'AY2', 'B', 'CH', 'D', 'DH', 'EH', 'EH0', 'EH1', 'EH2', 'ER', 'ER0', 'ER1', 'ER2', 'EY', 'EY0', 'EY1', 'EY2', 'F', 'G', 'HH', 'IH', 'IH0', 'IH1', 'IH2', 'IY', 'IY0', 'IY1', 'IY2', 'JH', 'K', 'L', 'M', 'N', 'NG', 'OW', 'OW0', 'OW1', 'OW2', 'OY', 'OY0', 'OY1', 'OY2', 'P', 'R', 'S', 'SH', 'T', 'TH', 'UH', 'UH0', 'UH1', 'UH2', 'UW', 'UW0', 'UW1', 'UW2', 'V', 'W', 'Y', 'Z', 'ZH' ] _valid_symbol_set = set(valid_symbols) class CMUDict: '''Thin wrapper around CMUDict data. http://www.speech.cs.cmu.edu/cgi-bin/cmudict''' def __init__(self, file_or_path, keep_ambiguous=True): if isinstance(file_or_path, str): with open(file_or_path, encoding='latin-1') as f: entries = _parse_cmudict(f) else: entries = _parse_cmudict(file_or_path) if not keep_ambiguous: entries = {word: pron for word, pron in entries.items() if len(pron) == 1} self._entries = entries def __len__(self): return len(self._entries) def lookup(self, word): '''Returns list of ARPAbet pronunciations of the given word.''' return self._entries.get(word.upper()) _alt_re = re.compile(r'\([0-9]+\)') def _parse_cmudict(file): cmudict = {} for line in file: if len(line) and (line[0] >= 'A' and line[0] <= 'Z' or line[0] == "'"): parts = line.split(' ') word = re.sub(_alt_re, '', parts[0]) pronunciation = _get_pronunciation(parts[1]) if pronunciation: if word in cmudict: cmudict[word].append(pronunciation) else: cmudict[word] = [pronunciation] return cmudict def _get_pronunciation(s): parts = s.strip().split(' ') for part in parts: if part not in _valid_symbol_set: return None return ' '.join(parts)
""" from https://github.com/keithito/tacotron """ import re from text import cleaners from text.symbols import symbols # Mappings from symbol to numeric ID and vice versa: _symbol_to_id = {s: i for i, s in enumerate(symbols)} _id_to_symbol = {i: s for i, s in enumerate(symbols)} # Regular expression matching text enclosed in curly braces: _curly_re = re.compile(r'(.*?)\{(.+?)\}(.*)') def text_to_sequence(text, cleaner_names): '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text. The text can optionally have ARPAbet sequences enclosed in curly braces embedded in it. For example, "Turn left on {HH AW1 S S T AH0 N} Street." Args: text: string to convert to a sequence cleaner_names: names of the cleaner functions to run the text through Returns: List of integers corresponding to the symbols in the text ''' sequence = [] # Check for curly braces and treat their contents as ARPAbet: while len(text): m = _curly_re.match(text) if not m: sequence += _symbols_to_sequence(_clean_text(text, cleaner_names)) break sequence += _symbols_to_sequence(_clean_text(m.group(1), cleaner_names)) sequence += _arpabet_to_sequence(m.group(2)) text = m.group(3) # Append EOS token sequence.append(_symbol_to_id['~']) return sequence def sequence_to_text(sequence): '''Converts a sequence of IDs back to a string''' result = '' for symbol_id in sequence: if symbol_id in _id_to_symbol: s = _id_to_symbol[symbol_id] # Enclose ARPAbet back in curly braces: if len(s) > 1 and s[0] == '@': s = '{%s}' % s[1:] result += s return result.replace('}{', ' ') def _clean_text(text, cleaner_names): for name in cleaner_names: cleaner = getattr(cleaners, name) if not cleaner: raise Exception('Unknown cleaner: %s' % name) text = cleaner(text) return text def _symbols_to_sequence(symbols): return [_symbol_to_id[s] for s in symbols if _should_keep_symbol(s)] def _arpabet_to_sequence(text): return _symbols_to_sequence(['@' + s for s in text.split()]) def _should_keep_symbol(s): return s in _symbol_to_id and s != '_' and s != '~'
""" from https://github.com/keithito/tacotron """ import inflect import re _inflect = inflect.engine() _comma_number_re = re.compile(r'([0-9][0-9\,]+[0-9])') _decimal_number_re = re.compile(r'([0-9]+\.[0-9]+)') _pounds_re = re.compile(r'£([0-9\,]*[0-9]+)') _dollars_re = re.compile(r'\$([0-9\.\,]*[0-9]+)') _ordinal_re = re.compile(r'[0-9]+(st|nd|rd|th)') _number_re = re.compile(r'[0-9]+') def _remove_commas(m): return m.group(1).replace(',', '') def _expand_decimal_point(m): return m.group(1).replace('.', ' point ') def _expand_dollars(m): match = m.group(1) parts = match.split('.') if len(parts) > 2: return match + ' dollars' # Unexpected format dollars = int(parts[0]) if parts[0] else 0 cents = int(parts[1]) if len(parts) > 1 and parts[1] else 0 if dollars and cents: dollar_unit = 'dollar' if dollars == 1 else 'dollars' cent_unit = 'cent' if cents == 1 else 'cents' return '%s %s, %s %s' % (dollars, dollar_unit, cents, cent_unit) elif dollars: dollar_unit = 'dollar' if dollars == 1 else 'dollars' return '%s %s' % (dollars, dollar_unit) elif cents: cent_unit = 'cent' if cents == 1 else 'cents' return '%s %s' % (cents, cent_unit) else: return 'zero dollars' def _expand_ordinal(m): return _inflect.number_to_words(m.group(0)) def _expand_number(m): num = int(m.group(0)) if num > 1000 and num < 3000: if num == 2000: return 'two thousand' elif num > 2000 and num < 2010: return 'two thousand ' + _inflect.number_to_words(num % 100) elif num % 100 == 0: return _inflect.number_to_words(num // 100) + ' hundred' else: return _inflect.number_to_words(num, andword='', zero='oh', group=2).replace(', ', ' ') else: return _inflect.number_to_words(num, andword='') def normalize_numbers(text): text = re.sub(_comma_number_re, _remove_commas, text) text = re.sub(_pounds_re, r'\1 pounds', text) text = re.sub(_dollars_re, _expand_dollars, text) text = re.sub(_decimal_number_re, _expand_decimal_point, text) text = re.sub(_ordinal_re, _expand_ordinal, text) text = re.sub(_number_re, _expand_number, text) return text
""" from https://github.com/keithito/tacotron """ ''' Defines the set of symbols used in text input to the model. The default is a set of ASCII characters that works well for English or text that has been run through Unidecode. For other data, you can modify _characters. See TRAINING_DATA.md for details. ''' from text import cmudict _pad = '_' _eos = '~' _characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!\'(),-.:;? ' # Prepend "@" to ARPAbet symbols to ensure uniqueness (some are the same as uppercase letters): _arpabet = ['@' + s for s in cmudict.valid_symbols] # Export all symbols: symbols = [_pad, _eos] + list(_characters) + _arpabet
""" from https://github.com/keithito/tacotron """ ''' Cleaners are transformations that run over the input text at both training and eval time. Cleaners can be selected by passing a comma-delimited list of cleaner names as the "cleaners" hyperparameter. Some cleaners are English-specific. You'll typically want to use: 1. "english_cleaners" for English text 2. "transliteration_cleaners" for non-English text that can be transliterated to ASCII using the Unidecode library (https://pypi.python.org/pypi/Unidecode) 3. "basic_cleaners" if you do not want to transliterate (in this case, you should also update the symbols in symbols.py to match your data). ''' import re from unidecode import unidecode from .numbers import normalize_numbers # Regular expression matching whitespace: _whitespace_re = re.compile(r'\s+') # List of (regular expression, replacement) pairs for abbreviations: _abbreviations = [(re.compile('\\b%s\\.' % x[0], re.IGNORECASE), x[1]) for x in [ ('mrs', 'misess'), ('mr', 'mister'), ('dr', 'doctor'), ('st', 'saint'), ('co', 'company'), ('jr', 'junior'), ('maj', 'major'), ('gen', 'general'), ('drs', 'doctors'), ('rev', 'reverend'), ('lt', 'lieutenant'), ('hon', 'honorable'), ('sgt', 'sergeant'), ('capt', 'captain'), ('esq', 'esquire'), ('ltd', 'limited'), ('col', 'colonel'), ('ft', 'fort'), ]] def expand_abbreviations(text): for regex, replacement in _abbreviations: text = re.sub(regex, replacement, text) return text def expand_numbers(text): return normalize_numbers(text) def lowercase(text): return text.lower() def collapse_whitespace(text): return re.sub(_whitespace_re, ' ', text) def convert_to_ascii(text): return unidecode(text) def basic_cleaners(text): '''Basic pipeline that lowercases and collapses whitespace without transliteration.''' text = lowercase(text) text = collapse_whitespace(text) return text def transliteration_cleaners(text): '''Pipeline for non-English text that transliterates to ASCII.''' text = convert_to_ascii(text) text = lowercase(text) text = collapse_whitespace(text) return text def english_cleaners(text): '''Pipeline for English text, including number and abbreviation expansion.''' text = convert_to_ascii(text) text = lowercase(text) text = expand_numbers(text) text = expand_abbreviations(text) text = collapse_whitespace(text) return text
""" from https://github.com/keithito/tacotron """ import re valid_symbols = [ 'AA', 'AA0', 'AA1', 'AA2', 'AE', 'AE0', 'AE1', 'AE2', 'AH', 'AH0', 'AH1', 'AH2', 'AO', 'AO0', 'AO1', 'AO2', 'AW', 'AW0', 'AW1', 'AW2', 'AY', 'AY0', 'AY1', 'AY2', 'B', 'CH', 'D', 'DH', 'EH', 'EH0', 'EH1', 'EH2', 'ER', 'ER0', 'ER1', 'ER2', 'EY', 'EY0', 'EY1', 'EY2', 'F', 'G', 'HH', 'IH', 'IH0', 'IH1', 'IH2', 'IY', 'IY0', 'IY1', 'IY2', 'JH', 'K', 'L', 'M', 'N', 'NG', 'OW', 'OW0', 'OW1', 'OW2', 'OY', 'OY0', 'OY1', 'OY2', 'P', 'R', 'S', 'SH', 'T', 'TH', 'UH', 'UH0', 'UH1', 'UH2', 'UW', 'UW0', 'UW1', 'UW2', 'V', 'W', 'Y', 'Z', 'ZH' ] _valid_symbol_set = set(valid_symbols) class CMUDict: '''Thin wrapper around CMUDict data. http://www.speech.cs.cmu.edu/cgi-bin/cmudict''' def __init__(self, file_or_path, keep_ambiguous=True): if isinstance(file_or_path, str): with open(file_or_path, encoding='latin-1') as f: entries = _parse_cmudict(f) else: entries = _parse_cmudict(file_or_path) if not keep_ambiguous: entries = {word: pron for word, pron in entries.items() if len(pron) == 1} self._entries = entries def __len__(self): return len(self._entries) def lookup(self, word): '''Returns list of ARPAbet pronunciations of the given word.''' return self._entries.get(word.upper()) _alt_re = re.compile(r'\([0-9]+\)') def _parse_cmudict(file): cmudict = {} for line in file: if len(line) and (line[0] >= 'A' and line[0] <= 'Z' or line[0] == "'"): parts = line.split(' ') word = re.sub(_alt_re, '', parts[0]) pronunciation = _get_pronunciation(parts[1]) if pronunciation: if word in cmudict: cmudict[word].append(pronunciation) else: cmudict[word] = [pronunciation] return cmudict def _get_pronunciation(s): parts = s.strip().split(' ') for part in parts: if part not in _valid_symbol_set: return None return ' '.join(parts)
""" from https://github.com/keithito/tacotron """ import re from . import cleaners from .symbols import symbols # Mappings from symbol to numeric ID and vice versa: _symbol_to_id = {s: i for i, s in enumerate(symbols)} _id_to_symbol = {i: s for i, s in enumerate(symbols)} # Regular expression matching text enclosed in curly braces: _curly_re = re.compile(r'(.*?)\{(.+?)\}(.*)') def text_to_sequence(text, cleaner_names): '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text. The text can optionally have ARPAbet sequences enclosed in curly braces embedded in it. For example, "Turn left on {HH AW1 S S T AH0 N} Street." Args: text: string to convert to a sequence cleaner_names: names of the cleaner functions to run the text through Returns: List of integers corresponding to the symbols in the text ''' sequence = [] # Check for curly braces and treat their contents as ARPAbet: while len(text): m = _curly_re.match(text) if not m: sequence += _symbols_to_sequence(_clean_text(text, cleaner_names)) break sequence += _symbols_to_sequence(_clean_text(m.group(1), cleaner_names)) sequence += _arpabet_to_sequence(m.group(2)) text = m.group(3) return sequence def sequence_to_text(sequence): '''Converts a sequence of IDs back to a string''' result = '' for symbol_id in sequence: if symbol_id in _id_to_symbol: s = _id_to_symbol[symbol_id] # Enclose ARPAbet back in curly braces: if len(s) > 1 and s[0] == '@': s = '{%s}' % s[1:] result += s return result.replace('}{', ' ') def _clean_text(text, cleaner_names): for name in cleaner_names: cleaner = getattr(cleaners, name) if not cleaner: raise Exception('Unknown cleaner: %s' % name) text = cleaner(text) return text def _symbols_to_sequence(symbols): return [_symbol_to_id[s] for s in symbols if _should_keep_symbol(s)] def _arpabet_to_sequence(text): return _symbols_to_sequence(['@' + s for s in text.split()]) def _should_keep_symbol(s): return s in _symbol_to_id and s != '_' and s != '~'
""" from https://github.com/keithito/tacotron """ import inflect import re _inflect = inflect.engine() _comma_number_re = re.compile(r'([0-9][0-9\,]+[0-9])') _decimal_number_re = re.compile(r'([0-9]+\.[0-9]+)') _pounds_re = re.compile(r'£([0-9\,]*[0-9]+)') _dollars_re = re.compile(r'\$([0-9\.\,]*[0-9]+)') _ordinal_re = re.compile(r'[0-9]+(st|nd|rd|th)') _number_re = re.compile(r'[0-9]+') def _remove_commas(m): return m.group(1).replace(',', '') def _expand_decimal_point(m): return m.group(1).replace('.', ' point ') def _expand_dollars(m): match = m.group(1) parts = match.split('.') if len(parts) > 2: return match + ' dollars' # Unexpected format dollars = int(parts[0]) if parts[0] else 0 cents = int(parts[1]) if len(parts) > 1 and parts[1] else 0 if dollars and cents: dollar_unit = 'dollar' if dollars == 1 else 'dollars' cent_unit = 'cent' if cents == 1 else 'cents' return '%s %s, %s %s' % (dollars, dollar_unit, cents, cent_unit) elif dollars: dollar_unit = 'dollar' if dollars == 1 else 'dollars' return '%s %s' % (dollars, dollar_unit) elif cents: cent_unit = 'cent' if cents == 1 else 'cents' return '%s %s' % (cents, cent_unit) else: return 'zero dollars' def _expand_ordinal(m): return _inflect.number_to_words(m.group(0)) def _expand_number(m): num = int(m.group(0)) if num > 1000 and num < 3000: if num == 2000: return 'two thousand' elif num > 2000 and num < 2010: return 'two thousand ' + _inflect.number_to_words(num % 100) elif num % 100 == 0: return _inflect.number_to_words(num // 100) + ' hundred' else: return _inflect.number_to_words(num, andword='', zero='oh', group=2).replace(', ', ' ') else: return _inflect.number_to_words(num, andword='') def normalize_numbers(text): text = re.sub(_comma_number_re, _remove_commas, text) text = re.sub(_pounds_re, r'\1 pounds', text) text = re.sub(_dollars_re, _expand_dollars, text) text = re.sub(_decimal_number_re, _expand_decimal_point, text) text = re.sub(_ordinal_re, _expand_ordinal, text) text = re.sub(_number_re, _expand_number, text) return text
""" from https://github.com/keithito/tacotron """ ''' Defines the set of symbols used in text input to the model. The default is a set of ASCII characters that works well for English or text that has been run through Unidecode. For other data, you can modify _characters. See TRAINING_DATA.md for details. ''' from . import cmudict _pad = '_' _punctuation = '!\'(),.:;? ' _special = '-' _letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' # Prepend "@" to ARPAbet symbols to ensure uniqueness (some are the same as uppercase letters): _arpabet = ['@' + s for s in cmudict.valid_symbols] # Export all symbols: symbols = [_pad] + list(_special) + list(_punctuation) + list(_letters) + _arpabet
""" from https://github.com/keithito/tacotron """ ''' Cleaners are transformations that run over the input text at both training and eval time. Cleaners can be selected by passing a comma-delimited list of cleaner names as the "cleaners" hyperparameter. Some cleaners are English-specific. You'll typically want to use: 1. "english_cleaners" for English text 2. "transliteration_cleaners" for non-English text that can be transliterated to ASCII using the Unidecode library (https://pypi.python.org/pypi/Unidecode) 3. "basic_cleaners" if you do not want to transliterate (in this case, you should also update the symbols in symbols.py to match your data). ''' import re from unidecode import unidecode from .numbers import normalize_numbers # Regular expression matching whitespace: _whitespace_re = re.compile(r'\s+') # List of (regular expression, replacement) pairs for abbreviations: _abbreviations = [(re.compile('\\b%s\\.' % x[0], re.IGNORECASE), x[1]) for x in [ ('mrs', 'misess'), ('mr', 'mister'), ('dr', 'doctor'), ('st', 'saint'), ('co', 'company'), ('jr', 'junior'), ('maj', 'major'), ('gen', 'general'), ('drs', 'doctors'), ('rev', 'reverend'), ('lt', 'lieutenant'), ('hon', 'honorable'), ('sgt', 'sergeant'), ('capt', 'captain'), ('esq', 'esquire'), ('ltd', 'limited'), ('col', 'colonel'), ('ft', 'fort'), ]] def expand_abbreviations(text): for regex, replacement in _abbreviations: text = re.sub(regex, replacement, text) return text def expand_numbers(text): return normalize_numbers(text) def lowercase(text): return text.lower() def collapse_whitespace(text): return re.sub(_whitespace_re, ' ', text) def convert_to_ascii(text): return unidecode(text) def basic_cleaners(text): '''Basic pipeline that lowercases and collapses whitespace without transliteration.''' text = lowercase(text) text = collapse_whitespace(text) return text def transliteration_cleaners(text): '''Pipeline for non-English text that transliterates to ASCII.''' text = convert_to_ascii(text) text = lowercase(text) text = collapse_whitespace(text) return text def english_cleaners(text): '''Pipeline for English text, including number and abbreviation expansion.''' text = convert_to_ascii(text) text = lowercase(text) text = expand_numbers(text) text = expand_abbreviations(text) text = collapse_whitespace(text) return text
import os import json import torch import kaldi_io import dataclasses from .speech_transformer.transformer.decoder import Decoder from .speech_transformer.transformer.encoder import Encoder from .speech_transformer.transformer import Transformer from .speech_transformer.transformer.optimizer import TransformerOptimizer from .speech_transformer.transformer.loss import cal_performance from .speech_transformer.utils import add_results_to_json, process_dict, IGNORE_ID from .speech_transformer.data import build_LFR_features from .speech_transformer.data import AudioDataLoader, AudioDataset from torchbenchmark import DATA_PATH @dataclasses.dataclass class SpeechTransformerTrainConfig: # Low Frame Rate LFR_m = 4 LFR_n = 3 # Network Architecture - Encoder d_input = 80 n_layers_enc = 6 n_head = 8 d_k = 64 d_v = 64 d_model = 512 d_inner = 2048 dropout = 0.1 pe_maxlen = 5000 d_word_vec = 512 n_layers_dec = 6 tgt_emb_prj_weight_sharing = 1 label_smoothing = 0.1 # minibatch shuffle = 1 batch_frames = 15000 maxlen_in = 800 maxlen_out = 150 # don't use subprocess in dataloader # because TorchBench is only running 1 batch num_workers = 0 # original value # num_workers = 4 # optimizer k = 0.2 warmup_steps = 1 # solver configs epochs = 5 save_folder = "output_data" checkpoint = False continue_from = False model_path = 'final.pth.tar' print_freq = 10 visdom = 0 visdom_lr = 0 visdom_epoch = 0 visdom_id = 0 cross_valid = False # The input files. Their paths are relative to the directory of __file__ train_json = "input_data/train/data.json" valid_json = "input_data/dev/data.json" dict_txt = "input_data/lang_1char/train_chars.txt" def __init__(self, prefetch=True, train_bs=32, num_train_batch=1, device='cuda'): dir_path = os.path.join(DATA_PATH, "speech_transformer_inputs") self.device = device self.train_json = os.path.join(dir_path, self.train_json) self.valid_json = os.path.join(dir_path, self.valid_json) self.dict_txt = os.path.join(dir_path, self.dict_txt) self.char_list, self.sos_id, self.eos_id = process_dict(self.dict_txt) self.vocab_size = len(self.char_list) self.tr_dataset = AudioDataset(self.train_json, train_bs, self.maxlen_in, self.maxlen_out, batch_frames=self.batch_frames) self.cv_dataset = AudioDataset(self.valid_json, train_bs, self.maxlen_in, self.maxlen_out, batch_frames=self.batch_frames) self.tr_loader = AudioDataLoader(self.tr_dataset, batch_size=train_bs, num_workers=self.num_workers, shuffle=self.shuffle, LFR_m=self.LFR_m, LFR_n=self.LFR_n) self.cv_loader = AudioDataLoader(self.cv_dataset, batch_size=train_bs, num_workers=self.num_workers, LFR_m=self.LFR_m, LFR_n=self.LFR_n) self.data = {'tr_loader': self.tr_loader, 'cv_loader': self.cv_loader} self.encoder = Encoder(self.d_input * self.LFR_m, self.n_layers_enc, self.n_head, self.d_k, self.d_v, self.d_model, self.d_inner, dropout=self.dropout, pe_maxlen=self.pe_maxlen) self.decoder = Decoder(self.sos_id, self.eos_id, self.vocab_size, self.d_word_vec, self.n_layers_dec, self.n_head, self.d_k, self.d_v, self.d_model, self.d_inner, dropout=self.dropout, tgt_emb_prj_weight_sharing=self.tgt_emb_prj_weight_sharing, pe_maxlen=self.pe_maxlen) self.tr_loss = torch.Tensor(self.epochs) self.cv_loss = torch.Tensor(self.epochs) self.model = Transformer(self.encoder, self.decoder) self.optimizer = TransformerOptimizer(torch.optim.Adam(self.model.parameters(), betas=(0.9, 0.98), eps=1e-09), self.k, self.d_model, self.warmup_steps) self._reset() self.data_loader = self.tr_loader if not SpeechTransformerTrainConfig.cross_valid else self.cv_loader if prefetch: result = [] for _batch_num, data in zip(range(num_train_batch), self.data_loader): padded_input, input_lengths, padded_target = data padded_input = padded_input.to(self.device) input_lengths = input_lengths.to(self.device) padded_target = padded_target.to(self.device) result.append((padded_input, input_lengths, padded_target)) self.data_loader = result def _reset(self): self.prev_val_loss = float("inf") self.best_val_loss = float("inf") self.halving = False def _run_one_epoch(self, cross_valid=False): total_loss = 0 data_loader = self.data_loader for i, (data) in enumerate(data_loader): padded_input, input_lengths, padded_target = data padded_input = padded_input.to(self.device) input_lengths = input_lengths.to(self.device) padded_target = padded_target.to(self.device) pred, gold = self.model(padded_input, input_lengths, padded_target) loss, n_correct = cal_performance(pred, gold, smoothing=self.label_smoothing) if not cross_valid: self.optimizer.zero_grad() loss.backward() self.optimizer.step() total_loss += loss.item() non_pad_mask = gold.ne(IGNORE_ID) n_word = non_pad_mask.sum().item() return total_loss / (i + 1) def train(self, epoch = 1): self.model.train() tr_avg_loss = self._run_one_epoch() # Cross validation self.model.eval() val_loss = self._run_one_epoch(cross_valid=SpeechTransformerTrainConfig.cross_valid) self.tr_loss[epoch] = tr_avg_loss self.cv_loss[epoch] = val_loss if val_loss < self.best_val_loss: self.best_val_loss = val_loss # speech transformer has a TransformerOptimizer wrapping an inner Adam optimizer. This returns the TransformerOptimizer. def get_optimizer(self): return self.optimizer def set_optimizer(self, optimizer) -> None: self.optimizer = optimizer # Takes in an inner optimizer and wraps it in a TransformerOptimizer def set_inner_optimizer(self, optimizer) -> None: self.optimizer = TransformerOptimizer(optimizer, self.k, self.d_model, self.warmup_steps) @dataclasses.dataclass class SpeechTransformerEvalConfig: beam_size = 5 nbest = 1 decode_max_len = 100 recog_word = 1 # The input files. Their paths are relative to the directory of __file__ recog_json = "input_data/test/data.json" dict_txt = "input_data/lang_1char/train_chars.txt" def __init__(self, traincfg, num_eval_batch=1, device='cuda'): dir_path = os.path.join(DATA_PATH, "speech_transformer_inputs") self.device = device self.base_path = dir_path self.recog_json = os.path.join(dir_path, self.recog_json) self.dict_txt = os.path.join(dir_path, self.dict_txt) # Construct the model self.model, self.LFR_m, self.LFR_n = Transformer(traincfg.encoder, traincfg.decoder), traincfg.LFR_m, traincfg.LFR_n self.char_list, self.sos_id, self.eos_id = process_dict(self.dict_txt) assert self.model.decoder.sos_id == self.sos_id and self.model.decoder.eos_id == self.eos_id # Read json data with open(self.recog_json, "rb") as f: self.js = json.load(f)['utts'] self.example_inputs = [] for idx, name in enumerate(list(self.js.keys())[:self.recog_word], 1): feat_path = os.path.join(self.base_path, self.js[name]['input'][0]['feat']) input = kaldi_io.read_mat(feat_path) input = build_LFR_features(input, self.LFR_m, self.LFR_n) input = torch.from_numpy(input).float() input_length = torch.tensor([input.size(0)], dtype=torch.int) input = input.to(self.device) input_length = input_length.to(self.device) self.example_inputs.append((input, input_length)) if len(self.example_inputs) == num_eval_batch: break def eval(self): with torch.no_grad(): for input, input_length in self.example_inputs: nbest_hyps = self.model.recognize(input, input_length, self.char_list, self) return nbest_hyps
#!/usr/bin/env python # # The SpeechTransformer model copied from https://github.com/kaituoxu/Speech-Transformer, commit e684777. # The model only supports CUDA and eager mode. # The input data files in the input_data/ directory are generated with a minimized aishell data # containing the following files in the original dataset: # S0002.tar.gz, S0757.tar.gz, S0915.tar.gz # import os import itertools import torch # set KALDI_ROOT to avoid spam message os.environ["KALDI_ROOT"] = "/tmp" from .config import SpeechTransformerTrainConfig, SpeechTransformerEvalConfig from ...util.model import BenchmarkModel from torchbenchmark.tasks import SPEECH from typing import Tuple NUM_TRAIN_BATCH = 1 NUM_EVAL_BATCH = 1 class Model(BenchmarkModel): task = SPEECH.RECOGNITION # Original batch size: 32 # Source: https://github.com/kaituoxu/Speech-Transformer/blob/e6847772d6a786336e117a03c48c62ecbf3016f6/src/bin/train.py#L68 # This model does not support batch size customization DEFAULT_TRAIN_BSIZE = 32 DEFAULT_EVAL_BSIZE = 1 ALLOW_CUSTOMIZE_BSIZE = False def __init__(self, test, device, batch_size=None, extra_args=[]): super().__init__(test=test, device=device, batch_size=batch_size, extra_args=extra_args) self.traincfg = SpeechTransformerTrainConfig(prefetch=True, train_bs=self.batch_size, num_train_batch=NUM_TRAIN_BATCH, device=self.device) if test == "train": self.traincfg.model.to(self.device) self.traincfg.model.train() elif test == "eval": self.evalcfg = SpeechTransformerEvalConfig(self.traincfg, num_eval_batch=NUM_EVAL_BATCH, device=self.device) self.evalcfg.model.to(self.device) self.evalcfg.model.eval() def get_module(self): for data in self.traincfg.tr_loader: padded_input, input_lengths, padded_target = data if self.test == "train": return self.traincfg.model, (padded_input.to(self.device), input_lengths.to(self.device), padded_target.to(self.device)) elif self.test == "eval": return self.evalcfg.model, (padded_input.to(self.device), input_lengths.to(self.device), padded_target.to(self.device)) def set_module(self, new_model): if self.test == "train": self.traincfg.model = new_model elif self.test == "eval": self.evalcfg.model = new_model def train(self): self.traincfg.train(epoch=1) def eval(self) -> Tuple[torch.Tensor]: out = self.evalcfg.eval() # only the first element of model output is a tensor out = tuple(itertools.chain(*list(map(lambda x: x.values(), out)))) return (out[0], ) def get_optimizer(self): return self.traincfg.get_optimizer() def set_optimizer(self, optimizer) -> None: return self.traincfg.set_optimizer(optimizer) def set_raw_optimizer(self, optimizer) -> None: return self.traincfg.set_raw_optimizer(optimizer)
import sys import subprocess from utils import s3_utils def pip_install_requirements(): subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-q', '-r', 'requirements.txt']) if __name__ == '__main__': s3_utils.checkout_s3_data("INPUT_TARBALLS", "speech_transformer_inputs.tar.gz", decompress=True) pip_install_requirements()
import torch import torch.nn as nn import torch.nn.functional as F from .attention import MultiHeadAttention from .module import PositionalEncoding, PositionwiseFeedForward from ..utils import (IGNORE_ID, get_attn_key_pad_mask, get_attn_pad_mask, get_non_pad_mask, get_subsequent_mask, pad_list) class Decoder(nn.Module): ''' A decoder model with self attention mechanism. ''' def __init__( self, sos_id, eos_id, n_tgt_vocab, d_word_vec, n_layers, n_head, d_k, d_v, d_model, d_inner, dropout=0.1, tgt_emb_prj_weight_sharing=True, pe_maxlen=5000): super(Decoder, self).__init__() # parameters self.sos_id = sos_id # Start of Sentence self.eos_id = eos_id # End of Sentence self.n_tgt_vocab = n_tgt_vocab self.d_word_vec = d_word_vec self.n_layers = n_layers self.n_head = n_head self.d_k = d_k self.d_v = d_v self.d_model = d_model self.d_inner = d_inner self.dropout = dropout self.tgt_emb_prj_weight_sharing = tgt_emb_prj_weight_sharing self.pe_maxlen = pe_maxlen self.tgt_word_emb = nn.Embedding(n_tgt_vocab, d_word_vec) self.positional_encoding = PositionalEncoding(d_model, max_len=pe_maxlen) self.dropout = nn.Dropout(dropout) self.layer_stack = nn.ModuleList([ DecoderLayer(d_model, d_inner, n_head, d_k, d_v, dropout=dropout) for _ in range(n_layers)]) self.tgt_word_prj = nn.Linear(d_model, n_tgt_vocab, bias=False) nn.init.xavier_normal_(self.tgt_word_prj.weight) if tgt_emb_prj_weight_sharing: # Share the weight matrix between target word embedding & the final logit dense layer self.tgt_word_prj.weight = self.tgt_word_emb.weight self.x_logit_scale = (d_model ** 0.5) else: self.x_logit_scale = 1. def preprocess(self, padded_input): """Generate decoder input and output label from padded_input Add <sos> to decoder input, and add <eos> to decoder output label """ ys = [y[y != IGNORE_ID] for y in padded_input] # parse padded ys # prepare input and output word sequences with sos/eos IDs eos = ys[0].new([self.eos_id]) sos = ys[0].new([self.sos_id]) ys_in = [torch.cat([sos, y], dim=0) for y in ys] ys_out = [torch.cat([y, eos], dim=0) for y in ys] # padding for ys with -1 # pys: utt x olen ys_in_pad = pad_list(ys_in, self.eos_id) ys_out_pad = pad_list(ys_out, IGNORE_ID) assert ys_in_pad.size() == ys_out_pad.size() return ys_in_pad, ys_out_pad def forward(self, padded_input, encoder_padded_outputs, encoder_input_lengths, return_attns=False): """ Args: padded_input: N x To encoder_padded_outputs: N x Ti x H Returns: """ dec_slf_attn_list, dec_enc_attn_list = [], [] # Get Deocder Input and Output ys_in_pad, ys_out_pad = self.preprocess(padded_input) # Prepare masks non_pad_mask = get_non_pad_mask(ys_in_pad, pad_idx=self.eos_id) slf_attn_mask_subseq = get_subsequent_mask(ys_in_pad) slf_attn_mask_keypad = get_attn_key_pad_mask(seq_k=ys_in_pad, seq_q=ys_in_pad, pad_idx=self.eos_id) slf_attn_mask = (slf_attn_mask_keypad + slf_attn_mask_subseq).gt(0) output_length = ys_in_pad.size(1) dec_enc_attn_mask = get_attn_pad_mask(encoder_padded_outputs, encoder_input_lengths, output_length) # Forward dec_output = self.dropout(self.tgt_word_emb(ys_in_pad) * self.x_logit_scale + self.positional_encoding(ys_in_pad)) for dec_layer in self.layer_stack: dec_output, dec_slf_attn, dec_enc_attn = dec_layer( dec_output, encoder_padded_outputs, non_pad_mask=non_pad_mask, slf_attn_mask=slf_attn_mask, dec_enc_attn_mask=dec_enc_attn_mask) if return_attns: dec_slf_attn_list += [dec_slf_attn] dec_enc_attn_list += [dec_enc_attn] # before softmax seq_logit = self.tgt_word_prj(dec_output) # Return pred, gold = seq_logit, ys_out_pad if return_attns: return pred, gold, dec_slf_attn_list, dec_enc_attn_list return pred, gold def recognize_beam(self, encoder_outputs, char_list, args): """Beam search, decode one utterence now. Args: encoder_outputs: T x H char_list: list of character args: args.beam Returns: nbest_hyps: """ # search params beam = args.beam_size nbest = args.nbest if args.decode_max_len == 0: maxlen = encoder_outputs.size(0) else: maxlen = args.decode_max_len encoder_outputs = encoder_outputs.unsqueeze(0) # prepare sos ys = torch.ones(1, 1).fill_(self.sos_id).type_as(encoder_outputs).long() # yseq: 1xT hyp = {'score': 0.0, 'yseq': ys} hyps = [hyp] ended_hyps = [] for i in range(maxlen): hyps_best_kept = [] for hyp in hyps: ys = hyp['yseq'] # 1 x i # -- Prepare masks non_pad_mask = torch.ones_like(ys).float().unsqueeze(-1) # 1xix1 slf_attn_mask = get_subsequent_mask(ys) # -- Forward dec_output = self.dropout( self.tgt_word_emb(ys) * self.x_logit_scale + self.positional_encoding(ys)) for dec_layer in self.layer_stack: dec_output, _, _ = dec_layer( dec_output, encoder_outputs, non_pad_mask=non_pad_mask, slf_attn_mask=slf_attn_mask, dec_enc_attn_mask=None) seq_logit = self.tgt_word_prj(dec_output[:, -1]) local_scores = F.log_softmax(seq_logit, dim=1) # topk scores local_best_scores, local_best_ids = torch.topk( local_scores, beam, dim=1) for j in range(beam): new_hyp = {} new_hyp['score'] = hyp['score'] + local_best_scores[0, j] new_hyp['yseq'] = torch.ones(1, (1+ys.size(1))).type_as(encoder_outputs).long() new_hyp['yseq'][:, :ys.size(1)] = hyp['yseq'] new_hyp['yseq'][:, ys.size(1)] = int(local_best_ids[0, j]) # will be (2 x beam) hyps at most hyps_best_kept.append(new_hyp) hyps_best_kept = sorted(hyps_best_kept, key=lambda x: x['score'], reverse=True)[:beam] # end for hyp in hyps hyps = hyps_best_kept # add eos in the final loop to avoid that there are no ended hyps if i == maxlen - 1: for hyp in hyps: hyp['yseq'] = torch.cat([hyp['yseq'], torch.ones(1, 1).fill_(self.eos_id).type_as(encoder_outputs).long()], dim=1) # add ended hypothes to a final list, and removed them from current hypothes # (this will be a probmlem, number of hyps < beam) remained_hyps = [] for hyp in hyps: if hyp['yseq'][0, -1] == self.eos_id: ended_hyps.append(hyp) else: remained_hyps.append(hyp) hyps = remained_hyps if len(hyps) > 0: # print('remeined hypothes: ' + str(len(hyps))) pass else: print('no hypothesis. Finish decoding.') break # for hyp in hyps: # print('hypo: ' + ''.join([char_list[int(x)] # for x in hyp['yseq'][0, 1:]])) # end for i in range(maxlen) nbest_hyps = sorted(ended_hyps, key=lambda x: x['score'], reverse=True)[ :min(len(ended_hyps), nbest)] # compitable with LAS implementation for hyp in nbest_hyps: hyp['yseq'] = hyp['yseq'][0].cpu().numpy().tolist() return nbest_hyps class DecoderLayer(nn.Module): ''' Compose with three layers ''' def __init__(self, d_model, d_inner, n_head, d_k, d_v, dropout=0.1): super(DecoderLayer, self).__init__() self.slf_attn = MultiHeadAttention(n_head, d_model, d_k, d_v, dropout=dropout) self.enc_attn = MultiHeadAttention(n_head, d_model, d_k, d_v, dropout=dropout) self.pos_ffn = PositionwiseFeedForward(d_model, d_inner, dropout=dropout) def forward(self, dec_input, enc_output, non_pad_mask=None, slf_attn_mask=None, dec_enc_attn_mask=None): dec_output, dec_slf_attn = self.slf_attn( dec_input, dec_input, dec_input, mask=slf_attn_mask) dec_output *= non_pad_mask dec_output, dec_enc_attn = self.enc_attn( dec_output, enc_output, enc_output, mask=dec_enc_attn_mask) dec_output *= non_pad_mask dec_output = self.pos_ffn(dec_output) dec_output *= non_pad_mask return dec_output, dec_slf_attn, dec_enc_attn
import numpy as np import torch import torch.nn as nn class MultiHeadAttention(nn.Module): ''' Multi-Head Attention module ''' def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1): super().__init__() self.n_head = n_head self.d_k = d_k self.d_v = d_v self.w_qs = nn.Linear(d_model, n_head * d_k) self.w_ks = nn.Linear(d_model, n_head * d_k) self.w_vs = nn.Linear(d_model, n_head * d_v) nn.init.normal_(self.w_qs.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_k))) nn.init.normal_(self.w_ks.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_k))) nn.init.normal_(self.w_vs.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_v))) self.attention = ScaledDotProductAttention(temperature=np.power(d_k, 0.5), attn_dropout=dropout) self.layer_norm = nn.LayerNorm(d_model) self.fc = nn.Linear(n_head * d_v, d_model) nn.init.xavier_normal_(self.fc.weight) self.dropout = nn.Dropout(dropout) def forward(self, q, k, v, mask=None): d_k, d_v, n_head = self.d_k, self.d_v, self.n_head sz_b, len_q, _ = q.size() sz_b, len_k, _ = k.size() sz_b, len_v, _ = v.size() residual = q q = self.w_qs(q).view(sz_b, len_q, n_head, d_k) k = self.w_ks(k).view(sz_b, len_k, n_head, d_k) v = self.w_vs(v).view(sz_b, len_v, n_head, d_v) q = q.permute(2, 0, 1, 3).contiguous().view(-1, len_q, d_k) # (n*b) x lq x dk k = k.permute(2, 0, 1, 3).contiguous().view(-1, len_k, d_k) # (n*b) x lk x dk v = v.permute(2, 0, 1, 3).contiguous().view(-1, len_v, d_v) # (n*b) x lv x dv if mask is not None: mask = mask.repeat(n_head, 1, 1) # (n*b) x .. x .. output, attn = self.attention(q, k, v, mask=mask) output = output.view(n_head, sz_b, len_q, d_v) output = output.permute(1, 2, 0, 3).contiguous().view(sz_b, len_q, -1) # b x lq x (n*dv) output = self.dropout(self.fc(output)) output = self.layer_norm(output + residual) return output, attn class ScaledDotProductAttention(nn.Module): ''' Scaled Dot-Product Attention ''' def __init__(self, temperature, attn_dropout=0.1): super().__init__() self.temperature = temperature self.dropout = nn.Dropout(attn_dropout) self.softmax = nn.Softmax(dim=2) def forward(self, q, k, v, mask=None): attn = torch.bmm(q, k.transpose(1, 2)) attn = attn / self.temperature if mask is not None: attn = attn.masked_fill(mask.bool(), -np.inf) attn = self.softmax(attn) attn = self.dropout(attn) output = torch.bmm(attn, v) return output, attn
from .transformer import *
import torch.nn as nn from .attention import MultiHeadAttention from .module import PositionalEncoding, PositionwiseFeedForward from ..utils import get_non_pad_mask, get_attn_pad_mask class Encoder(nn.Module): """Encoder of Transformer including self-attention and feed forward. """ def __init__(self, d_input, n_layers, n_head, d_k, d_v, d_model, d_inner, dropout=0.1, pe_maxlen=5000): super(Encoder, self).__init__() # parameters self.d_input = d_input self.n_layers = n_layers self.n_head = n_head self.d_k = d_k self.d_v = d_v self.d_model = d_model self.d_inner = d_inner self.dropout_rate = dropout self.pe_maxlen = pe_maxlen # use linear transformation with layer norm to replace input embedding self.linear_in = nn.Linear(d_input, d_model) self.layer_norm_in = nn.LayerNorm(d_model) self.positional_encoding = PositionalEncoding(d_model, max_len=pe_maxlen) self.dropout = nn.Dropout(dropout) self.layer_stack = nn.ModuleList([ EncoderLayer(d_model, d_inner, n_head, d_k, d_v, dropout=dropout) for _ in range(n_layers)]) def forward(self, padded_input, input_lengths, return_attns=False): """ Args: padded_input: N x T x D input_lengths: N Returns: enc_output: N x T x H """ enc_slf_attn_list = [] # Prepare masks non_pad_mask = get_non_pad_mask(padded_input, input_lengths=input_lengths) length = padded_input.size(1) slf_attn_mask = get_attn_pad_mask(padded_input, input_lengths, length) # Forward enc_output = self.dropout( self.layer_norm_in(self.linear_in(padded_input)) + self.positional_encoding(padded_input)) for enc_layer in self.layer_stack: enc_output, enc_slf_attn = enc_layer( enc_output, non_pad_mask=non_pad_mask, slf_attn_mask=slf_attn_mask) if return_attns: enc_slf_attn_list += [enc_slf_attn] if return_attns: return enc_output, enc_slf_attn_list return enc_output, class EncoderLayer(nn.Module): """Compose with two sub-layers. 1. A multi-head self-attention mechanism 2. A simple, position-wise fully connected feed-forward network. """ def __init__(self, d_model, d_inner, n_head, d_k, d_v, dropout=0.1): super(EncoderLayer, self).__init__() self.slf_attn = MultiHeadAttention( n_head, d_model, d_k, d_v, dropout=dropout) self.pos_ffn = PositionwiseFeedForward( d_model, d_inner, dropout=dropout) def forward(self, enc_input, non_pad_mask=None, slf_attn_mask=None): enc_output, enc_slf_attn = self.slf_attn( enc_input, enc_input, enc_input, mask=slf_attn_mask) enc_output *= non_pad_mask enc_output = self.pos_ffn(enc_output) enc_output *= non_pad_mask return enc_output, enc_slf_attn
import torch import torch.nn.functional as F from ..utils import IGNORE_ID def cal_performance(pred, gold, smoothing=0.0): """Calculate cross entropy loss, apply label smoothing if needed. Args: pred: N x T x C, score before softmax gold: N x T """ pred = pred.view(-1, pred.size(2)) gold = gold.contiguous().view(-1) loss = cal_loss(pred, gold, smoothing) pred = pred.max(1)[1] non_pad_mask = gold.ne(IGNORE_ID) n_correct = pred.eq(gold) n_correct = n_correct.masked_select(non_pad_mask).sum().item() return loss, n_correct def cal_loss(pred, gold, smoothing=0.0): """Calculate cross entropy loss, apply label smoothing if needed. """ if smoothing > 0.0: eps = smoothing n_class = pred.size(1) # Generate one-hot matrix: N x C. # Only label position is 1 and all other positions are 0 # gold include -1 value (IGNORE_ID) and this will lead to assert error gold_for_scatter = gold.ne(IGNORE_ID).long() * gold one_hot = torch.zeros_like(pred).scatter(1, gold_for_scatter.view(-1, 1), 1) one_hot = one_hot * (1 - eps) + (1 - one_hot) * eps / n_class log_prb = F.log_softmax(pred, dim=1) non_pad_mask = gold.ne(IGNORE_ID) n_word = non_pad_mask.sum().item() loss = -(one_hot * log_prb).sum(dim=1) loss = loss.masked_select(non_pad_mask).sum() / n_word else: loss = F.cross_entropy(pred, gold, ignore_index=IGNORE_ID, reduction='elementwise_mean') return loss
import torch import torch.nn as nn from .decoder import Decoder from .encoder import Encoder class Transformer(nn.Module): """An encoder-decoder framework only includes attention. """ def __init__(self, encoder, decoder): super(Transformer, self).__init__() self.encoder = encoder self.decoder = decoder for p in self.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) def forward(self, padded_input, input_lengths, padded_target): """ Args: padded_input: N x Ti x D input_lengths: N padded_targets: N x To """ encoder_padded_outputs, *_ = self.encoder(padded_input, input_lengths) # pred is score before softmax pred, gold, *_ = self.decoder(padded_target, encoder_padded_outputs, input_lengths) return pred, gold def recognize(self, input, input_length, char_list, args): """Sequence-to-Sequence beam search, decode one utterence now. Args: input: T x D char_list: list of characters args: args.beam Returns: nbest_hyps: """ encoder_outputs, *_ = self.encoder(input.unsqueeze(0), input_length) nbest_hyps = self.decoder.recognize_beam(encoder_outputs[0], char_list, args) return nbest_hyps @classmethod def load_model(cls, path): # Load to CPU package = torch.load(path, map_location=lambda storage, loc: storage) model, LFR_m, LFR_n = cls.load_model_from_package(package) return model, LFR_m, LFR_n @classmethod def load_model_from_package(cls, package): encoder = Encoder(package['d_input'], package['n_layers_enc'], package['n_head'], package['d_k'], package['d_v'], package['d_model'], package['d_inner'], dropout=package['dropout'], pe_maxlen=package['pe_maxlen']) decoder = Decoder(package['sos_id'], package['eos_id'], package['vocab_size'], package['d_word_vec'], package['n_layers_dec'], package['n_head'], package['d_k'], package['d_v'], package['d_model'], package['d_inner'], dropout=package['dropout'], tgt_emb_prj_weight_sharing=package['tgt_emb_prj_weight_sharing'], pe_maxlen=package['pe_maxlen'], ) model = cls(encoder, decoder) model.load_state_dict(package['state_dict']) LFR_m, LFR_n = package['LFR_m'], package['LFR_n'] return model, LFR_m, LFR_n @staticmethod def serialize(model, optimizer, epoch, LFR_m, LFR_n, tr_loss=None, cv_loss=None): package = { # Low Frame Rate Feature 'LFR_m': LFR_m, 'LFR_n': LFR_n, # encoder 'd_input': model.encoder.d_input, 'n_layers_enc': model.encoder.n_layers, 'n_head': model.encoder.n_head, 'd_k': model.encoder.d_k, 'd_v': model.encoder.d_v, 'd_model': model.encoder.d_model, 'd_inner': model.encoder.d_inner, 'dropout': model.encoder.dropout_rate, 'pe_maxlen': model.encoder.pe_maxlen, # decoder 'sos_id': model.decoder.sos_id, 'eos_id': model.decoder.eos_id, 'vocab_size': model.decoder.n_tgt_vocab, 'd_word_vec': model.decoder.d_word_vec, 'n_layers_dec': model.decoder.n_layers, 'tgt_emb_prj_weight_sharing': model.decoder.tgt_emb_prj_weight_sharing, # state 'state_dict': model.state_dict(), 'optim_dict': optimizer.state_dict(), 'epoch': epoch } if tr_loss is not None: package['tr_loss'] = tr_loss package['cv_loss'] = cv_loss return package
"""A wrapper class for optimizer""" import torch class TransformerOptimizer: """A simple wrapper class for learning rate scheduling""" def __init__(self, optimizer, k, d_model, warmup_steps=4000): self.optimizer = optimizer self.k = k self.init_lr = d_model ** (-0.5) self.warmup_steps = warmup_steps self.step_num = 0 self.visdom_lr = None def zero_grad(self): self.optimizer.zero_grad() def step(self): self._update_lr() self._visdom() self.optimizer.step() def _update_lr(self): self.step_num += 1 lr = self.k * self.init_lr * min(self.step_num ** (-0.5), self.step_num * (self.warmup_steps ** (-1.5))) for param_group in self.optimizer.param_groups: param_group['lr'] = lr def load_state_dict(self, state_dict): self.optimizer.load_state_dict(state_dict) def state_dict(self): return self.optimizer.state_dict() def set_k(self, k): self.k = k def set_visdom(self, visdom_lr, vis): self.visdom_lr = visdom_lr # Turn on/off visdom of learning rate self.vis = vis # visdom enviroment self.vis_opts = dict(title='Learning Rate', ylabel='Leanring Rate', xlabel='step') self.vis_window = None self.x_axis = torch.LongTensor() self.y_axis = torch.FloatTensor() def _visdom(self): if self.visdom_lr is not None: self.x_axis = torch.cat( [self.x_axis, torch.LongTensor([self.step_num])]) self.y_axis = torch.cat( [self.y_axis, torch.FloatTensor([self.optimizer.param_groups[0]['lr']])]) if self.vis_window is None: self.vis_window = self.vis.line(X=self.x_axis, Y=self.y_axis, opts=self.vis_opts) else: self.vis.line(X=self.x_axis, Y=self.y_axis, win=self.vis_window, update='replace')
import math import torch import torch.nn as nn import torch.nn.functional as F class PositionalEncoding(nn.Module): """Implement the positional encoding (PE) function. PE(pos, 2i) = sin(pos/(10000^(2i/dmodel))) PE(pos, 2i+1) = cos(pos/(10000^(2i/dmodel))) """ def __init__(self, d_model, max_len=5000): super(PositionalEncoding, self).__init__() # Compute the positional encodings once in log space. pe = torch.zeros(max_len, d_model, requires_grad=False) position = torch.arange(0, max_len).unsqueeze(1).float() div_term = torch.exp(torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) pe = pe.unsqueeze(0) self.register_buffer('pe', pe) def forward(self, input): """ Args: input: N x T x D """ length = input.size(1) return self.pe[:, :length] class PositionwiseFeedForward(nn.Module): """Implements position-wise feedforward sublayer. FFN(x) = max(0, xW1 + b1)W2 + b2 """ def __init__(self, d_model, d_ff, dropout=0.1): super(PositionwiseFeedForward, self).__init__() self.w_1 = nn.Linear(d_model, d_ff) self.w_2 = nn.Linear(d_ff, d_model) self.dropout = nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model) def forward(self, x): residual = x output = self.w_2(F.relu(self.w_1(x))) output = self.dropout(output) output = self.layer_norm(output + residual) return output # Another implementation class PositionwiseFeedForwardUseConv(nn.Module): """A two-feed-forward-layer module""" def __init__(self, d_in, d_hid, dropout=0.1): super(PositionwiseFeedForwardUseConv, self).__init__() self.w_1 = nn.Conv1d(d_in, d_hid, 1) # position-wise self.w_2 = nn.Conv1d(d_hid, d_in, 1) # position-wise self.layer_norm = nn.LayerNorm(d_in) self.dropout = nn.Dropout(dropout) def forward(self, x): residual = x output = x.transpose(1, 2) output = self.w_2(F.relu(self.w_1(output))) output = output.transpose(1, 2) output = self.dropout(output) output = self.layer_norm(output + residual) return output
#!/usr/bin/env python # encoding: utf-8 # Copyright 2017 Johns Hopkins University (Shinji Watanabe) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) import json import argparse import logging from utils import process_dict if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('json', type=str, help='json files') parser.add_argument('dict', type=str, help='dict') parser.add_argument('ref', type=str, help='ref') parser.add_argument('hyp', type=str, help='hyp') args = parser.parse_args() # logging info logging.basicConfig( level=logging.INFO, format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s") logging.info("reading %s", args.json) with open(args.json, 'r') as f: j = json.load(f) logging.info("reading %s", args.dict) char_list, sos_id, eos_id = process_dict(args.dict) # with open(args.dict, 'r') as f: # dictionary = f.readlines() # char_list = [unicode(entry.split(' ')[0], 'utf_8') for entry in dictionary] # char_list.insert(0, '<blank>') # char_list.append('<eos>') # print([x.encode('utf-8') for x in char_list]) logging.info("writing hyp trn to %s", args.hyp) logging.info("writing ref trn to %s", args.ref) h = open(args.hyp, 'w') r = open(args.ref, 'w') for x in j['utts']: seq = [char_list[int(i)] for i in j['utts'][x] ['output'][0]['rec_tokenid'].split()] h.write(" ".join(seq).replace('<eos>', '')), h.write( " (" + j['utts'][x]['utt2spk'].replace('-', '_') + "-" + x + ")\n") seq = [char_list[int(i)] for i in j['utts'][x] ['output'][0]['tokenid'].split()] r.write(" ".join(seq).replace('<eos>', '')), r.write( " (" + j['utts'][x]['utt2spk'].replace('-', '_') + "-" + x + ")\n")
#!/usr/bin/env python2 # encoding: utf-8 # Copyright 2017 Johns Hopkins University (Shinji Watanabe) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) import sys import json import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--key', '-k', type=str, help='key') args = parser.parse_args() l = {} line = sys.stdin.readline() while line: x = unicode(line, 'utf_8').rstrip().split() v = {args.key: ' '.join(x[1:]).encode('utf_8')} l[x[0].encode('utf_8')] = v line = sys.stdin.readline() all_l = {'utts': l} # ensure "ensure_ascii=False", which is a bug jsonstring = json.dumps(all_l, indent=4, ensure_ascii=False) print(jsonstring)
#!/usr/bin/env python # Apache 2.0 import sys import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--exclude', '-v', dest='exclude', action='store_true', help='exclude filter words') parser.add_argument('filt', type=str, help='filter list') parser.add_argument('infile', type=str, help='input file') args = parser.parse_args() vocab = set() with open(args.filt) as vocabfile: for line in vocabfile: vocab.add(line.strip()) with open(args.infile) as textfile: for line in textfile: if args.exclude: print(" ".join( map(lambda word: word if not word in vocab else '', line.strip().split()))) # else: # print(" ".join(map(lambda word: word if word in vocab else '<UNK>', unicode(line, 'utf_8').strip().split())).encode('utf_8'))
#!/usr/bin/env python2 # encoding: utf-8 # Copyright 2017 Johns Hopkins University (Shinji Watanabe) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) import argparse import json import logging if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('jsons', type=str, nargs='+', help='json files') parser.add_argument('--multi', '-m', type=int, help='Test the json file for multiple input/output', default=0) parser.add_argument('--verbose', '-V', default=0, type=int, help='Verbose option') args = parser.parse_args() # logging info if args.verbose > 0: logging.basicConfig( level=logging.INFO, format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s") else: logging.basicConfig( level=logging.WARN, format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s") # make intersection set for utterance keys js = [] intersec_ks = [] for x in args.jsons: with open(x, 'r') as f: j = json.load(f) ks = j['utts'].keys() logging.info(x + ': has ' + str(len(ks)) + ' utterances') if len(intersec_ks) > 0: intersec_ks = intersec_ks.intersection(set(ks)) else: intersec_ks = set(ks) js.append(j) logging.info('new json has ' + str(len(intersec_ks)) + ' utterances') old_dic = dict() for k in intersec_ks: v = js[0]['utts'][k] for j in js[1:]: v.update(j['utts'][k]) old_dic[k] = v new_dic = dict() for id in old_dic: dic = old_dic[id] in_dic = {} if dic.has_key(unicode('idim', 'utf-8')): in_dic[unicode('shape', 'utf-8')] = (int(dic[unicode('ilen', 'utf-8')]), int(dic[unicode('idim', 'utf-8')])) in_dic[unicode('name', 'utf-8')] = unicode('input1', 'utf-8') in_dic[unicode('feat', 'utf-8')] = dic[unicode('feat', 'utf-8')] out_dic = {} out_dic[unicode('name', 'utf-8')] = unicode('target1', 'utf-8') out_dic[unicode('shape', 'utf-8')] = (int(dic[unicode('olen', 'utf-8')]), int(dic[unicode('odim', 'utf-8')])) out_dic[unicode('text', 'utf-8')] = dic[unicode('text', 'utf-8')] out_dic[unicode('token', 'utf-8')] = dic[unicode('token', 'utf-8')] out_dic[unicode('tokenid', 'utf-8')] = dic[unicode('tokenid', 'utf-8')] new_dic[id] = {unicode('input', 'utf-8'):[in_dic], unicode('output', 'utf-8'):[out_dic], unicode('utt2spk', 'utf-8'):dic[unicode('utt2spk', 'utf-8')]} # ensure "ensure_ascii=False", which is a bug jsonstring = json.dumps({'utts': new_dic}, indent=4, ensure_ascii=False, sort_keys=True).encode('utf_8') print(jsonstring)