|
| 1 | +from __future__ import print_function |
| 2 | + |
| 3 | +import torch |
| 4 | +import numpy as np |
| 5 | +import torch.nn as nn |
| 6 | +import torch.nn.functional as F |
| 7 | +from config import cfg |
| 8 | +from tensorboardX import SummaryWriter |
| 9 | +from torch.autograd import Variable |
| 10 | +import time |
| 11 | +from retrieval import read_data |
| 12 | +from util import Checkpointer |
| 13 | + |
| 14 | +ar_data = read_data() |
| 15 | + |
| 16 | +STEP_NUM = 11 |
| 17 | +ELEM_NUM = 26 + 10 + 1 |
| 18 | +HIDDEN_NUM = 20 |
| 19 | + |
| 20 | +def softmax_cross_entropy_with_logits(logits, labels): |
| 21 | + loss = torch.sum(-labels * F.log_softmax(logits, -1), -1) |
| 22 | + return loss |
| 23 | + |
| 24 | +class fast_weights_model(nn.Module): |
| 25 | + """docstring for fast_weights_model""" |
| 26 | + def __init__(self, batch_size, step_num, elem_num, hidden_num): |
| 27 | + super(fast_weights_model, self).__init__() |
| 28 | + self.x = Variable(torch.randn(batch_size, step_num, elem_num).type(torch.float32)) |
| 29 | + self.y = Variable(torch.randn(batch_size, elem_num).type(torch.float32)) |
| 30 | + self.l = torch.zeros(1, dtype=torch.float32) |
| 31 | + self.e = torch.zeros(1, dtype=torch.float32) |
| 32 | + |
| 33 | + self.w1 = Variable(torch.empty(elem_num, 50).uniform_(-np.sqrt(0.02), np.sqrt(0.02))) |
| 34 | + self.b1 = Variable(torch.zeros([1, 50]).type(torch.float32)) |
| 35 | + self.w2 = Variable(torch.empty(500, 100).uniform_(-np.sqrt(0.01), np.sqrt(0.01))) |
| 36 | + self.b2 = Variable(torch.zeros([1, 100]).type(torch.float32)) |
| 37 | + self.w3 = Variable(torch.empty(hidden_num, 100).uniform_(-np.sqrt(0.01), np.sqrt(0.01))) |
| 38 | + self.b3 = Variable(torch.zeros([1, 100]).type(torch.float32)) |
| 39 | + self.w4 = Variable(torch.empty(100, elem_num).uniform_(-np.sqrt(1.0 / elem_num), np.sqrt(1.0 / elem_num))) |
| 40 | + self.b4 = Variable(torch.zeros([1, elem_num]).type(torch.float32)) |
| 41 | + |
| 42 | + self.w = Variable(torch.tensor(0.05 * np.identity(hidden_num)).type(torch.float32)) |
| 43 | + |
| 44 | + self.c = Variable(torch.empty(100, hidden_num).uniform_(-np.sqrt(hidden_num), np.sqrt(hidden_num))) |
| 45 | + |
| 46 | + self.g = Variable(torch.ones([1, hidden_num]).type(torch.float32)) |
| 47 | + self.b = Variable(torch.ones([1, hidden_num]).type(torch.float32)) |
| 48 | + |
| 49 | + def forward(self, bx, by) |
| 50 | + a = torch.zeros([batch_size, hidden_num, hidden_num]).type(torch.float32) |
| 51 | + h = torch.zeros([batch_size, hidden_num]).type(torch.float32) |
| 52 | + |
| 53 | + la = [] |
| 54 | + |
| 55 | + for i in range(0, step_num): |
| 56 | + s1 = torch.relu(torch.matmul(self.x[:, t, :], self.w1) + self.b1) |
| 57 | + z = torch.relu(torch.matmul(s1, self.w2) + self.b2) |
| 58 | + |
| 59 | + h = torch.relu(torch.matmul(h, self.w) + torch.matmul(z, self.c)) |
| 60 | + |
| 61 | + hs = torch.reshape(h, [batch_size, 1, hidden_num]) |
| 62 | + |
| 63 | + hh = hs |
| 64 | + |
| 65 | + a = self.l * a + self.e * torch.matmul(hs.transpose(1,2), hs) |
| 66 | + |
| 67 | + la.append(torch.mean(torch.pow(a,2))) |
| 68 | + |
| 69 | + for s in range(1): |
| 70 | + hs = torch.reshape(torch.matmul(h, self.w), hh.shape) + \ |
| 71 | + torch.reshape(torch.matmul(z, self.c), hh.shape) + torch.matmul(hs, a) |
| 72 | + mu = torch.mean(hs, 0) |
| 73 | + sig = torch.sqrt(torch.mean(torch.pow((hs - mu), 2), 0)) |
| 74 | + hs = torch.relu(torch.div(torch.mul(self.g, (hs - mu)), sig) + self.b) |
| 75 | + |
| 76 | + h = torch.reshape(hs, [batch_size, hidden_num]) |
| 77 | + |
| 78 | + h = torch.relu(torch.matmul(h, self.w3) + self.b3) |
| 79 | + logits = torch.matmul(h, self.w4) + self.b4 |
| 80 | + correct = torch.argmax(logits, dim=1).eq(torch.argmax(self.y, dim=1)) |
| 81 | + self.loss = softmax_cross_entropy_with_logits(logits, self.y).mean() |
| 82 | + self.acc = torch.mean(correct.type(torch.float32)) |
| 83 | + |
| 84 | + return self.loss, self.acc |
| 85 | + |
| 86 | +def train(self, save = 0, verbose = 0): |
| 87 | + model = fast_weights_model(STEP_NUM, ELEM_NUM, HIDDEN_NUM) |
| 88 | + model.train() |
| 89 | + batch_size = cfg.train.batch_size |
| 90 | + start_time = time.time() |
| 91 | + optimizer = torch.optim.Adam(model.paramters(), lr=cfg.train.model_lr) |
| 92 | + writer = SummaryWriter(logdir=os.path.join(cfg.logdir, cfg.exp_name), flush_secs=30) |
| 93 | + checkpointer = Checkpointer(os.path.join(cfg.checkpointdir, cfg.exp_name)) |
| 94 | + start_epoch = 0 |
| 95 | + batch_idxs = 600 |
| 96 | + for epoch in range(start_epoch, cfg.train.max_epochs): |
| 97 | + for idx in range(batch_idxs): |
| 98 | + gloabl_step = epoch * cfg.num_train + idx + 1 |
| 99 | + bx, by = ar_data.train.next_batch(batch_size=cfg.batch_size) |
| 100 | + loss, acc = model(bx, by) |
| 101 | + optimizer.zero_grad() |
| 102 | + loss.backward() |
| 103 | + optimizer.step() |
| 104 | + writer.add_scalar('loss/loss', loss, gloabl_step) |
| 105 | + writer.add_scalar('acc/acc', acc, gloabl_step) |
| 106 | + if verbose > 0 and idx % verbose == 0: |
| 107 | + print('Epoch: [{:4d}] [{:4d}/{:4d}] time: {:.4f}, loss: {:.8f}, acc: {:.2f}'.format( |
| 108 | + epoch, idx, batch_idxs, time.time() - start_time, loss, acc |
| 109 | + )) |
| 110 | + checkpointer.save(model, optimizer, epoch+1) |
| 111 | + |
| 112 | + |
| 113 | +if __name__ == "__main__": |
| 114 | + train(verbose = 10) |
| 115 | + |
| 116 | + |
| 117 | + |
| 118 | + |
| 119 | + |
0 commit comments