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.

test_gpu_lstm.py 5.5 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. # Copyright 2019 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. import numpy as np
  16. import pytest
  17. import mindspore.context as context
  18. import mindspore.nn as nn
  19. from mindspore import Tensor
  20. from mindspore.common.initializer import initializer
  21. from mindspore.common.parameter import Parameter
  22. from mindspore.nn import Dense
  23. from mindspore.nn import TrainOneStepCell, WithLossCell
  24. from mindspore.nn.optim import Momentum
  25. from mindspore.ops import operations as P
  26. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  27. def InitialLstmWeight(input_size, hidden_size, num_layers, bidirectional, has_bias=False):
  28. num_directions = 1
  29. if bidirectional:
  30. num_directions = 2
  31. weight_size = 0
  32. gate_size = 4 * hidden_size
  33. for layer in range(num_layers):
  34. for d in range(num_directions):
  35. input_layer_size = input_size if layer == 0 else hidden_size * num_directions
  36. weight_size += gate_size * input_layer_size
  37. weight_size += gate_size * hidden_size
  38. if has_bias:
  39. weight_size += 2 * gate_size
  40. w_np = np.ones([weight_size, 1, 1]).astype(np.float32) * 0.01
  41. w = Parameter(initializer(Tensor(w_np), w_np.shape), name='w')
  42. h = Parameter(initializer(
  43. Tensor(np.ones((num_layers * num_directions, batch_size, hidden_size)).astype(np.float32)),
  44. [num_layers * num_directions, batch_size, hidden_size]), name='h')
  45. c = Parameter(initializer(
  46. Tensor(np.ones((num_layers * num_directions, batch_size, hidden_size)).astype(np.float32)),
  47. [num_layers * num_directions, batch_size, hidden_size]), name='c')
  48. return h, c, w
  49. class SentimentNet(nn.Cell):
  50. def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,
  51. bidirectional, weight, labels, batch_size):
  52. super(SentimentNet, self).__init__()
  53. self.num_hiddens = num_hiddens
  54. self.num_layers = num_layers
  55. self.bidirectional = bidirectional
  56. self.batch_size = batch_size
  57. self.embedding = nn.Embedding(vocab_size, embed_size, use_one_hot=False, embedding_table=Tensor(weight))
  58. self.embedding.embedding_table.requires_grad = False
  59. self.trans = P.Transpose()
  60. self.perm = (1, 0, 2)
  61. self.h, self.c, self.w = InitialLstmWeight(embed_size, num_hiddens, num_layers, bidirectional)
  62. self.encoder = P.LSTM(input_size=embed_size, hidden_size=self.num_hiddens,
  63. num_layers=num_layers, has_bias=False,
  64. bidirectional=self.bidirectional, dropout=0.0)
  65. self.concat = P.Concat(2)
  66. if self.bidirectional:
  67. self.decoder = nn.Dense(num_hiddens * 4, labels)
  68. else:
  69. self.decoder = nn.Dense(num_hiddens * 2, labels)
  70. self.slice1 = P.Slice()
  71. self.slice2 = P.Slice()
  72. self.reshape = P.Reshape()
  73. self.num_direction = 1
  74. if bidirectional:
  75. self.num_direction = 2
  76. def construct(self, inputs):
  77. embeddings = self.embedding(inputs)
  78. embeddings = self.trans(embeddings, self.perm)
  79. output, hidden = self.encoder(embeddings, self.h, self.c, self.w)
  80. output0 = self.slice1(output, (0, 0, 0), (1, 64, 200))
  81. output1 = self.slice2(output, (499, 0, 0), (1, 64, 200))
  82. encoding = self.concat((output0, output1))
  83. encoding = self.reshape(encoding, (self.batch_size, self.num_hiddens * self.num_direction * 2))
  84. outputs = self.decoder(encoding)
  85. return outputs
  86. batch_size = 64
  87. @pytest.mark.level0
  88. @pytest.mark.platform_x86_gpu_training
  89. @pytest.mark.env_onecard
  90. def test_LSTM():
  91. num_epochs = 5
  92. embed_size = 100
  93. num_hiddens = 100
  94. num_layers = 2
  95. bidirectional = True
  96. labels = 2
  97. vocab_size = 252193
  98. max_len = 500
  99. weight = np.ones((vocab_size + 1, embed_size)).astype(np.float32)
  100. net = SentimentNet(vocab_size=(vocab_size + 1), embed_size=embed_size,
  101. num_hiddens=num_hiddens, num_layers=num_layers,
  102. bidirectional=bidirectional, weight=weight,
  103. labels=labels, batch_size=batch_size)
  104. learning_rate = 0.1
  105. momentum = 0.9
  106. optimizer = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), learning_rate, momentum)
  107. criterion = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True)
  108. net_with_criterion = WithLossCell(net, criterion)
  109. train_network = TrainOneStepCell(net_with_criterion, optimizer) # optimizer
  110. train_network.set_train()
  111. train_features = Tensor(np.ones([64, max_len]).astype(np.int32))
  112. train_labels = Tensor(np.ones([64,]).astype(np.int32)[0:64])
  113. losses = []
  114. for epoch in range(num_epochs):
  115. loss = train_network(train_features, train_labels)
  116. losses.append(loss)
  117. print("loss:", loss.asnumpy())
  118. assert (losses[-1].asnumpy() < 0.01)