test.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import paddle
  2. import paddle.nn as nn
  3. from paddle.vision.transforms import Compose, Normalize
  4. from paddle.utils.cpp_extension import load
  5. from paddle.inference import Config
  6. from paddle.inference import create_predictor
  7. import numpy as np
  8. EPOCH_NUM = 4
  9. BATCH_SIZE = 64
  10. # jit compile custom op
  11. custom_ops = load(
  12. name="custom_jit_ops", sources=["custom_relu_op.cc", "custom_relu_op.cu"])
  13. class LeNet(nn.Layer):
  14. def __init__(self):
  15. super(LeNet, self).__init__()
  16. self.conv1 = nn.Conv2D(
  17. in_channels=1, out_channels=6, kernel_size=5, stride=1, padding=2)
  18. self.max_pool1 = nn.MaxPool2D(kernel_size=2, stride=2)
  19. self.conv2 = nn.Conv2D(
  20. in_channels=6, out_channels=16, kernel_size=5, stride=1)
  21. self.max_pool2 = nn.MaxPool2D(kernel_size=2, stride=2)
  22. self.linear1 = nn.Linear(in_features=16 * 5 * 5, out_features=120)
  23. self.linear2 = nn.Linear(in_features=120, out_features=84)
  24. self.linear3 = nn.Linear(in_features=84, out_features=10)
  25. def forward(self, x):
  26. x = self.conv1(x)
  27. x = custom_ops.custom_relu(x)
  28. x = self.max_pool1(x)
  29. x = custom_ops.custom_relu(x)
  30. x = self.conv2(x)
  31. x = self.max_pool2(x)
  32. x = paddle.flatten(x, start_axis=1, stop_axis=-1)
  33. x = self.linear1(x)
  34. x = custom_ops.custom_relu(x)
  35. x = self.linear2(x)
  36. x = custom_ops.custom_relu(x)
  37. x = self.linear3(x)
  38. return x
  39. # set device
  40. paddle.set_device("gpu")
  41. # model
  42. net = LeNet()
  43. loss_fn = nn.CrossEntropyLoss()
  44. opt = paddle.optimizer.Adam(learning_rate=0.001, parameters=net.parameters())
  45. # data loader
  46. transform = Compose([Normalize(mean=[127.5], std=[127.5], data_format='CHW')])
  47. train_dataset = paddle.vision.datasets.MNIST(mode='train', transform=transform)
  48. train_loader = paddle.io.DataLoader(
  49. train_dataset,
  50. batch_size=BATCH_SIZE,
  51. shuffle=True,
  52. drop_last=True,
  53. num_workers=2)
  54. # train
  55. for epoch_id in range(EPOCH_NUM):
  56. for batch_id, (image, label) in enumerate(train_loader()):
  57. out = net(image)
  58. loss = loss_fn(out, label)
  59. loss.backward()
  60. if batch_id % 300 == 0:
  61. print("Epoch {} batch {}: loss = {}".format(epoch_id, batch_id,
  62. np.mean(loss.numpy())))
  63. opt.step()
  64. opt.clear_grad()