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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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 TrainOneStepCell, WithLossCell
  23. from mindspore.nn.optim import Momentum
  24. from mindspore.ops import operations as P
  25. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  26. def InitialLstmWeight(input_size, hidden_size, num_layers, bidirectional, has_bias=False):
  27. num_directions = 1
  28. if bidirectional:
  29. num_directions = 2
  30. weight_size = 0
  31. gate_size = 4 * hidden_size
  32. for layer in range(num_layers):
  33. for d in range(num_directions):
  34. input_layer_size = input_size if layer == 0 else hidden_size * num_directions
  35. weight_size += gate_size * input_layer_size
  36. weight_size += gate_size * hidden_size
  37. if has_bias:
  38. weight_size += 2 * gate_size
  39. w_np = np.ones([weight_size, 1, 1]).astype(np.float32) * 0.01
  40. w = Parameter(initializer(Tensor(w_np), w_np.shape), name='w')
  41. h = Parameter(initializer(
  42. Tensor(np.ones((num_layers * num_directions, batch_size, hidden_size)).astype(np.float32)),
  43. [num_layers * num_directions, batch_size, hidden_size]), name='h')
  44. c = Parameter(initializer(
  45. Tensor(np.ones((num_layers * num_directions, batch_size, hidden_size)).astype(np.float32)),
  46. [num_layers * num_directions, batch_size, hidden_size]), name='c')
  47. return h, c, w
  48. class SentimentNet(nn.Cell):
  49. def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,
  50. bidirectional, weight, labels, batch_size):
  51. super(SentimentNet, self).__init__()
  52. self.num_hiddens = num_hiddens
  53. self.num_layers = num_layers
  54. self.bidirectional = bidirectional
  55. self.batch_size = batch_size
  56. self.embedding = nn.Embedding(vocab_size, embed_size, use_one_hot=False, embedding_table=Tensor(weight))
  57. self.embedding.embedding_table.requires_grad = False
  58. self.trans = P.Transpose()
  59. self.perm = (1, 0, 2)
  60. self.h, self.c, self.w = InitialLstmWeight(embed_size, num_hiddens, num_layers, bidirectional)
  61. self.encoder = P.LSTM(input_size=embed_size, hidden_size=self.num_hiddens,
  62. num_layers=num_layers, has_bias=False,
  63. bidirectional=self.bidirectional, dropout=0.0)
  64. self.concat = P.Concat(2)
  65. if self.bidirectional:
  66. self.decoder = nn.Dense(num_hiddens * 4, labels)
  67. else:
  68. self.decoder = nn.Dense(num_hiddens * 2, labels)
  69. self.slice1 = P.Slice()
  70. self.slice2 = P.Slice()
  71. self.reshape = P.Reshape()
  72. self.num_direction = 1
  73. if bidirectional:
  74. self.num_direction = 2
  75. def construct(self, inputs):
  76. embeddings = self.embedding(inputs)
  77. embeddings = self.trans(embeddings, self.perm)
  78. output, hidden = self.encoder(embeddings, self.h, self.c, self.w)
  79. output0 = self.slice1(output, (0, 0, 0), (1, 64, 200))
  80. output1 = self.slice2(output, (499, 0, 0), (1, 64, 200))
  81. encoding = self.concat((output0, output1))
  82. encoding = self.reshape(encoding, (self.batch_size, self.num_hiddens * self.num_direction * 2))
  83. outputs = self.decoder(encoding)
  84. return outputs
  85. batch_size = 64
  86. @pytest.mark.level0
  87. @pytest.mark.platform_x86_gpu_training
  88. @pytest.mark.env_onecard
  89. def test_LSTM():
  90. num_epochs = 5
  91. embed_size = 100
  92. num_hiddens = 100
  93. num_layers = 2
  94. bidirectional = True
  95. labels = 2
  96. vocab_size = 252193
  97. max_len = 500
  98. weight = np.ones((vocab_size + 1, embed_size)).astype(np.float32)
  99. net = SentimentNet(vocab_size=(vocab_size + 1), embed_size=embed_size,
  100. num_hiddens=num_hiddens, num_layers=num_layers,
  101. bidirectional=bidirectional, weight=weight,
  102. labels=labels, batch_size=batch_size)
  103. learning_rate = 0.1
  104. momentum = 0.9
  105. optimizer = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), learning_rate, momentum)
  106. criterion = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  107. net_with_criterion = WithLossCell(net, criterion)
  108. train_network = TrainOneStepCell(net_with_criterion, optimizer) # optimizer
  109. train_network.set_train()
  110. train_features = Tensor(np.ones([64, max_len]).astype(np.int32))
  111. train_labels = Tensor(np.ones([64,]).astype(np.int32)[0:64])
  112. losses = []
  113. for epoch in range(num_epochs):
  114. loss = train_network(train_features, train_labels)
  115. losses.append(loss)
  116. print("loss:", loss.asnumpy())
  117. assert (losses[-1].asnumpy() < 0.01)