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.

data_pipeline_mlp.py 2.5 kB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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('--warmup', type=int, default=1,
  18. help='warm up steps excluded from timing')
  19. parser.add_argument('--batch-size', type=int,
  20. default=10000, help='batch size')
  21. parser.add_argument('--learning-rate', type=float,
  22. default=0.01, help='learning rate')
  23. args = parser.parse_args()
  24. datasets = ht.data.mnist()
  25. train_set_x, train_set_y = datasets[0]
  26. valid_set_x, valid_set_y = datasets[1]
  27. test_set_x, test_set_y = datasets[2]
  28. with ht.context("gpu:0,gpu:4"):
  29. x = ht.Variable(name="dataloader_x", trainable=False)
  30. activation = fc(x, (784, 1024), 'mlp_fc0', with_relu=True)
  31. with ht.context("gpu:1,gpu:5"):
  32. activation = fc(activation, (1024, 1024), 'mlp_fc1', with_relu=True)
  33. activation = fc(activation, (1024, 1024), 'mlp_fc11', with_relu=True)
  34. with ht.context("gpu:2,gpu:6"):
  35. activation = fc(activation, (1024, 1024), 'mlp_fc2', with_relu=True)
  36. activation = fc(activation, (1024, 1024), 'mlp_fc22', with_relu=True)
  37. with ht.context("gpu:3,gpu:7"):
  38. y_pred = fc(activation, (1024, 10), 'mlp_fc3', with_relu=True)
  39. y_ = ht.Variable(name="dataloader_y", trainable=False)
  40. loss = ht.softmaxcrossentropy_op(y_pred, y_)
  41. loss = ht.reduce_mean_op(loss, [0])
  42. opt = ht.optim.SGDOptimizer(learning_rate=args.learning_rate)
  43. train_op = opt.minimize(loss)
  44. executor = ht.Executor([loss, train_op])
  45. print_devices = [3, 7]
  46. # training
  47. steps = train_set_x.shape[0] // args.batch_size
  48. for step in range(steps):
  49. start = step * args.batch_size
  50. end = start + args.batch_size
  51. loss_val, _ = executor.run(feed_dict={
  52. x: train_set_x[start:end], y_: train_set_y[start:end]}, convert_to_numpy_ret_vals=True)
  53. if executor.local_rank in print_devices:
  54. print('[step {}]: loss: {}'.format(step, loss_val[0]))