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.

reshape.py 2.6 kB

5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python3
  2. # coding: utf-8
  3. # Copyright 2019 Huawei Technologies Co., Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """operator dsl function: reshape"""
  17. from functools import reduce
  18. import akg
  19. import akg.topi
  20. from akg.utils.validation_check import ops_dtype_check, check_shape, DtypeForDavinci, check_input_type
  21. from akg.utils.format_transform import get_shape
  22. from akg.utils import dynamic_shape as ds
  23. @check_input_type(akg.tvm.tensor.Tensor, (list, tuple))
  24. def reshape(data, out_shape):
  25. """
  26. Rearranges input tensor data to new shape out_shape.
  27. Args:
  28. data (tvm.tensor.Tensor): The tensor to be reshaped.
  29. out_shape (list, tuple): The new shape applied on the input tensor data,
  30. should be compatible with the original shape of data.
  31. Returns:
  32. The reshaped akg.tvm.tensor of same type as input tensor data.
  33. """
  34. ops_dtype_check(data.dtype, DtypeForDavinci.INT32.value + DtypeForDavinci.ALL_FLOAT.value)
  35. data_shape = data.shape
  36. check_shape(data_shape)
  37. in_shape = get_shape(data)
  38. out_shape = list(out_shape)
  39. is_dynamic = ds.shape_is_dynamic(data)
  40. if -1 in out_shape:
  41. access_size = 1
  42. for i, o_shape in enumerate(out_shape):
  43. if -1 != o_shape:
  44. access_size *= o_shape
  45. else:
  46. hit_idx = i
  47. ori_size = reduce(lambda x, y: x * y, in_shape)
  48. if ori_size % access_size != 0:
  49. raise ValueError(("Invalid out_shape ({})".format(out_shape)))
  50. out_shape[hit_idx] = int(ori_size / access_size)
  51. else:
  52. if not is_dynamic:
  53. if reduce(lambda x, y: x * y, in_shape) != reduce(lambda x, y: x * y, out_shape):
  54. raise ValueError("the total length of out_shape is not equal to the in_shape")
  55. inputs = akg.tvm.compute(in_shape, lambda *indice: data(*indice), name="inputs")
  56. res = akg.topi.reshape(inputs, out_shape)
  57. output = akg.tvm.compute(out_shape, lambda *indice: res(*indice), name="reshape")
  58. attr_map = {}
  59. return output, attr_map