You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

simple_pipeline_mlp.py 2.7 kB

4 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import hetu as ht
  2. import os
  3. import time
  4. import argparse
  5. import numpy as np
  6. def fc(x, shape, name, with_relu=True):
  7. weight = ht.init.random_normal(shape, stddev=0.04, name=name+'_weight')
  8. bias = ht.init.random_normal(shape[-1:], stddev=0.04, name=name+'_bias')
  9. x = ht.matmul_op(x, weight)
  10. x = x + ht.broadcastto_op(bias, x)
  11. if with_relu:
  12. x = ht.relu_op(x)
  13. return x
  14. if __name__ == "__main__":
  15. # argument parser
  16. parser = argparse.ArgumentParser()
  17. parser.add_argument('--epochs', type=int, default=8,
  18. help='training epochs')
  19. parser.add_argument('--warmup', type=int, default=1,
  20. help='warm up steps excluded from timing')
  21. parser.add_argument('--batch-size', type=int,
  22. default=10000, help='batch size')
  23. parser.add_argument('--learning-rate', type=float,
  24. default=0.01, help='learning rate')
  25. args = parser.parse_args()
  26. datasets = ht.data.mnist()
  27. train_set_x, train_set_y = datasets[0]
  28. valid_set_x, valid_set_y = datasets[1]
  29. test_set_x, test_set_y = datasets[2]
  30. # pipeline parallel
  31. with ht.context(ht.gpu(0)):
  32. x = ht.Variable(name="dataloader_x", trainable=False)
  33. activation = fc(x, (784, 1024), 'mlp_fc1', with_relu=True)
  34. for i in range(1, 7):
  35. with ht.context(ht.gpu(i)):
  36. activation = fc(activation, (1024, 1024), 'mlp_fc%d' %
  37. (i + 1), with_relu=True)
  38. with ht.context(ht.gpu(7)):
  39. y_pred = fc(activation, (1024, 10), 'mlp_fc8', with_relu=True)
  40. y_ = ht.Variable(name="dataloader_y", trainable=False)
  41. loss = ht.softmaxcrossentropy_op(y_pred, y_)
  42. loss = ht.reduce_mean_op(loss, [0])
  43. opt = ht.optim.SGDOptimizer(learning_rate=args.learning_rate)
  44. train_op = opt.minimize(loss)
  45. executor = ht.Executor([loss, train_op])
  46. # training
  47. steps = train_set_x.shape[0] // args.batch_size
  48. for epoch in range(args.epochs):
  49. loss_vals = []
  50. if epoch == args.warmup:
  51. start_time = time.time()
  52. for step in range(steps):
  53. start = step * args.batch_size
  54. end = start + args.batch_size
  55. loss_val, _ = executor.run(feed_dict={
  56. x: train_set_x[start:end], y_: train_set_y[start:end]}, convert_to_numpy_ret_vals=True)
  57. loss_vals.append(loss_val)
  58. if executor.rank == 7:
  59. print('epoch: {}, loss: {}'.format(epoch, np.mean(loss_vals)))
  60. if executor.rank == 0:
  61. end_time = time.time()
  62. print("time elapsed for {} epochs: {}s".format(
  63. args.epochs-args.warmup, round(end_time-start_time, 3)))