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.

inference.py 2.2 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright 2020 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. """
  16. TopK for text generation
  17. """
  18. import numpy as np
  19. import mindspore.common.dtype as mstype
  20. from mindspore.common.tensor import Tensor
  21. def generate(model, origin_inputs, seq_length, end_token=50256):
  22. """
  23. TopK for text generation
  24. Inputs:
  25. model: the model for inferencing
  26. origin_inputs: the original inputs based on which the model will continue writing
  27. seq_length: seq_length for the model
  28. end_token: end of sentence token id
  29. Returns:
  30. outputs: the ids for the generated text
  31. """
  32. TOPK = 5
  33. seq_length = seq_length
  34. bs, valid_length = origin_inputs.shape
  35. pad_length = seq_length - origin_inputs.shape[-1]
  36. input_ids = np.pad(origin_inputs, ((0, 0), (0, pad_length)), 'constant', constant_values=(0, 0))
  37. print("input_ids is ", input_ids)
  38. while valid_length < seq_length:
  39. inputs = Tensor(input_ids, mstype.int32)
  40. logits = model(inputs).asnumpy()
  41. logits = logits.reshape(bs, seq_length, -1)
  42. probs = logits[0, valid_length-1, :]
  43. p_args = probs.argsort()[::-1][:TOPK]
  44. p = probs[p_args]
  45. p = p / sum(p)
  46. target_index = np.random.choice(len(p), p=p)
  47. if p_args[target_index] == end_token or valid_length == seq_length-1:
  48. outputs = input_ids
  49. break
  50. input_ids[0][valid_length] = p_args[target_index]
  51. valid_length += 1
  52. length = np.sum(outputs != 0)
  53. outputs = outputs[0][:length]
  54. return outputs