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.

_embedding_cache_ops.py 12 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. """cache_ops"""
  16. from ..._checkparam import Validator as validator
  17. from ...common import dtype as mstype
  18. from ..primitive import prim_attr_register, PrimitiveWithCheck
  19. from .. import signature as sig
  20. class UpdateCache(PrimitiveWithCheck):
  21. """
  22. Update the value fo input_x, similar to ScatterNdUpdate.
  23. The difference is that UpdateCache will not update when indices < 0 or indices >= max_num.
  24. Inputs:
  25. - **input_x** (Parameter) - Parameter which is going to be updated.
  26. - **indices** (Tensor) - Update indices of input_x.
  27. - **updates** (Tensor) - The update values.
  28. Outputs:
  29. - **out** (Tensor) - Returns a [1] Tensor, which is not useful.
  30. """
  31. __mindspore_signature__ = (
  32. sig.make_sig('input_x', sig.sig_rw.RW_WRITE,
  33. dtype=sig.sig_dtype.T),
  34. sig.make_sig('indices', dtype=sig.sig_dtype.T1),
  35. sig.make_sig('updates', dtype=sig.sig_dtype.T),
  36. sig.make_sig('max_num', dtype=sig.sig_dtype.T1)
  37. )
  38. @prim_attr_register
  39. def __init__(self):
  40. """init UpdateCache"""
  41. self.init_prim_io_names(inputs=['input_x', 'indices', 'update', 'max_num'],
  42. outputs=['out'])
  43. def check_shape(self, input_x_shape, indices_shape, update_shape, max_num_shape):
  44. return [1]
  45. def check_dtype(self, input_x_dtype, indices_dtype, update_dtype, max_num_dtype):
  46. validator.check_tensor_dtype_valid(
  47. "indices", indices_dtype, mstype.int_type, self.name)
  48. return input_x_dtype
  49. class SubAndFilter(PrimitiveWithCheck):
  50. """
  51. Dynamic kernel, sub an offset and
  52. return the elements which in range [0, max_num).
  53. Inputs:
  54. - **input_x** (Tensor) - Input tensor.
  55. - **max_num** (Int) - The max value of element that after sub `offset`.
  56. - **offset** (int) - Specifies the offset value of this `input_x`.
  57. Outputs:
  58. tuple(Tensor), tuple of 2 tensors, filter_res and filter_idx.
  59. - **filter_res** (Tensor) - The result that `input_x` minus `offset`,
  60. and return which in the range [0, max_num).
  61. - **filter_idx** (Tensor) - A tensor containing indices of elements in the input
  62. coressponding to the output tensor.
  63. Supported Platforms:
  64. `CPU`
  65. Examples:
  66. >>> x = Tensor(np.array([1, 3, 5, 8, 9, 16]), mindspore.int32)
  67. >>> max_num = 10
  68. >>> offset = 5
  69. >>> output = ops.SubAndFilter()(x, max_num, offset)
  70. >>> print(output)
  71. (Tensor(shape=[3], dtype=Int32, value= [0, 3, 4]),
  72. Tensor(shape=[3], dtype=Int32, value= [2, 3, 4]))
  73. """
  74. @prim_attr_register
  75. def __init__(self):
  76. """init SubAndFilter"""
  77. self.init_prim_io_names(inputs=['input_x', 'max_num', 'offset'],
  78. outputs=['sub_res', 'sub_idx'])
  79. def check_shape(self, input_x_shape, max_num_shape, offset_shape):
  80. return ((-1,), (-1,))
  81. def check_dtype(self, input_x_dtype, max_num_dtype, offset_dtype):
  82. validator.check_tensor_dtype_valid(
  83. "input_x", input_x_dtype, mstype.int_type, self.name)
  84. return input_x_dtype
  85. class MapUniform(PrimitiveWithCheck):
  86. """
  87. Map a tensor by using fomula : value = key % `group_num` * `per_group_size` + key // `group_num`.
  88. Inputs:
  89. - **input** (Tensor) - Input Tensor.
  90. - **per_group_size** (int) - The size of each group.
  91. - **group_num** (int) - The number of group.
  92. Outputs:
  93. Tensor, has the same dtype and shape as the `input`.
  94. Supported Platforms:
  95. `CPU`
  96. Examples:
  97. >>> input_x = Tensor(np.array([0, 1, 2, 3, 4, 5, 6, 7]))
  98. >>> per_group_size = 4
  99. >>> group_num = 2
  100. >>> map_uniform = ops.MapUniform()
  101. >>> output = map_uniform(input_x, per_group_size, group_num)
  102. >>> print(output)
  103. [0, 4, 1, 5, 2, 6, 3, 7]
  104. """
  105. @prim_attr_register
  106. def __init__(self):
  107. """init MapUniform"""
  108. self.init_prim_io_names(inputs=['input', 'per_group_size', 'group_num'],
  109. outputs=['output'])
  110. def check_dtype(self, input_dtype, per_group_size_dtype, group_num_dtype):
  111. validator.check_tensor_dtype_valid(
  112. "input", input_dtype, mstype.int_type, self.name)
  113. validator.check_value_type(
  114. 'per_group_size', per_group_size_dtype, [mstype.Int], self.name)
  115. validator.check_value_type(
  116. 'group_num', group_num_dtype, [mstype.Int], self.name)
  117. class CacheSwapTable(PrimitiveWithCheck):
  118. """
  119. Delete a hashmap entry,and insert a new key to hashmap, return the key and value of delete entry.
  120. Inputs:
  121. - **cache_table** (Parameter) - The cache table which is on device.
  122. - **swap_cache_idx** (Tensor) - The index of table which need to swap. -1 is skipped.
  123. - **miss_value** (int) - The values which arg going to swap into cache table.
  124. Outputs:
  125. - **old_value** (Tensor) - The values which are swapped out.
  126. """
  127. __mindspore_signature__ = (
  128. sig.make_sig('cache_table', sig.sig_rw.RW_WRITE,
  129. dtype=sig.sig_dtype.T),
  130. sig.make_sig('swap_cache_idx', dtype=sig.sig_dtype.T1),
  131. sig.make_sig('miss_value', dtype=sig.sig_dtype.T)
  132. )
  133. @prim_attr_register
  134. def __init__(self):
  135. """init CacheSwapTable"""
  136. self.init_prim_io_names(inputs=['cache_table', 'swap_cache_idx', 'miss_value'],
  137. outputs=['old_value'])
  138. def check_shape(self, cache_table_shape, swap_cache_idx_shape, miss_value_shape):
  139. if len(cache_table_shape) != 2:
  140. raise ValueError(
  141. "cache table shape must be 2, but got %d" % len(cache_table_shape))
  142. return miss_value_shape
  143. def check_dtype(self, cache_table_dtype, swap_cache_idx_dtype, miss_value_dtype):
  144. validator.check_tensor_dtype_valid(
  145. "swap_cache_idx", swap_cache_idx_dtype, mstype.int_type, self.name)
  146. return miss_value_dtype
  147. class MapCacheIdx(PrimitiveWithCheck):
  148. """
  149. MapCacheIdx merge SearchCacheIdx, CacheSwapHashmap, UpdateCache together.
  150. When input an indices tensor, it will output the cache indices which search in hashmap.
  151. """
  152. __mindspore_signature__ = (
  153. sig.make_sig('hashmap', sig.sig_rw.RW_WRITE,
  154. dtype=sig.sig_dtype.T),
  155. sig.make_sig('indices', dtype=sig.sig_dtype.T),
  156. sig.make_sig('step', dtype=sig.sig_dtype.T),
  157. sig.make_sig('emb_max_num', dtype=sig.sig_dtype.T),
  158. sig.make_sig('cache_max_num', dtype=sig.sig_dtype.T)
  159. )
  160. @prim_attr_register
  161. def __init__(self):
  162. """init MapCacheIdx"""
  163. self.init_prim_io_names(inputs=['hashmap', 'indices', 'step', 'emb_max_num', 'offset'],
  164. outputs=['cache_idx', 'old_emb_idx', 'miss_emb_idx', 'swap_cache_idx'])
  165. def __check__(self, hashmap, indices, step, emb_max_num, offset):
  166. hashmap_shape = hashmap['shape']
  167. if len(hashmap_shape) != 2:
  168. raise ValueError("The dimension of 'hashmap' in SearchCacheIdx must be 2, "
  169. "but got %d." % len(hashmap_shape))
  170. out_shape = (indices['shape'], -1, -1, -1)
  171. hashmap_dtype = hashmap['dtype']
  172. indices_dtype = indices['dtype']
  173. args = {"hashmap": hashmap_dtype, "indices": indices_dtype}
  174. validator.check_tensors_dtypes_same_and_valid(
  175. args, mstype.int_type, self.name)
  176. out_dtype = (hashmap_dtype, hashmap_dtype,
  177. hashmap_dtype, hashmap_dtype)
  178. out = {'shape': out_shape,
  179. 'dtype': out_dtype,
  180. 'value': None}
  181. if 'max_shape' in indices:
  182. out['max_shape'] = (indices['max_shape'], indices['max_shape'],
  183. indices['max_shape'], indices['max_shape'])
  184. else:
  185. out['max_shape'] = (indices['shape'], indices['shape'],
  186. indices['shape'], indices['shape'])
  187. if 'min_shape' in indices:
  188. out['min_shape'] = (indices['min_shape'], 0, 0, 0)
  189. else:
  190. out['min_shape'] = (0, 0, 0, 0)
  191. return out
  192. class DynamicAssign(PrimitiveWithCheck):
  193. """
  194. Assigns `Parameter` with a value, the `value` can have a dynamic shape.
  195. Inputs:
  196. - **variable** (Parameter) - The `Parameter`.
  197. - **value** (Tensor) - The value to be assigned.
  198. Outputs:
  199. Tensor, has the same type as original `variable`.
  200. Supported Platforms:
  201. `CPU`
  202. """
  203. __mindspore_signature__ = (
  204. sig.make_sig('variable', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T),
  205. sig.make_sig('value', dtype=sig.sig_dtype.T)
  206. )
  207. @prim_attr_register
  208. def __init__(self):
  209. self.init_prim_io_names(inputs=['ref', 'value'], outputs=['output'])
  210. def check_dtype(self, variable, value):
  211. if variable != mstype.type_refkey:
  212. validator.check_tensor_dtype_valid(
  213. "variable", variable, mstype.number_type, self.name)
  214. validator.check_scalar_or_tensor_types_same(
  215. {"value": value}, mstype.number_type, self.name)
  216. class PadAndShift(PrimitiveWithCheck):
  217. """
  218. Pad a tensor with -1, and shift with a length.
  219. Inputs:
  220. - **input_x** (Tensor) - The input Tensor, which will be copied
  221. to `output`.
  222. - **cum_sum_arr** (Tensor) - The last value of cum_sum_arr is
  223. the pad length of output tensor, cum_sum_arr[shift_idx] is
  224. the start to shift, and cum_sum_arr[shift_idx+1] is the end.
  225. - **shift_idx** (Int) - The idx of cum_sum_arr.
  226. if use python, PadAndShift is:
  227. output = [-1] * cum_sum_arr[-1]
  228. start = cum_sum_arr[shift_idx]
  229. end = cum_sum_arr[shift_idx + 1]
  230. output[start:end] = input_x[:(end-start)]
  231. Outputs:
  232. Tensor, has the same type as original `variable`.
  233. Supported Platforms:
  234. `CPU`
  235. Examples:
  236. >>> input_x = Tensor(np.array([9, 13, -1, -1, -1, -1, -1, -1]), mstype.int32)
  237. >>> cum_sum_arr = Tensor(np.array([0, 3, 5]), mstype.int32)
  238. >>> shift_idx = 1
  239. >>> pad_and_shift = ops.PadAndShift()
  240. >>> output = pad_and_shift(input_x, cum_sum_arr, shift_idx)
  241. >>> print(output)
  242. [-1, -1, -1, 9, 13]
  243. """
  244. @prim_attr_register
  245. def __init__(self):
  246. self.init_prim_io_names(
  247. inputs=['input_x', 'cum_sum_arr', 'shift_idx'], outputs=['output'])
  248. def check_shape(self, input_x_shape, cum_sum_arr_shape, shift_idx_shape):
  249. return input_x_shape
  250. def check_dtype(self, input_x_dtype, cum_sum_arr_dtype, shift_idx_dtype):
  251. return input_x_dtype