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.

mindspore_backend.py 34 kB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321
  1. #! /usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import, division, print_function
  4. from .mindspore_nn import nchw_to_nhwc, nhwc_to_nchw
  5. from mindspore._c_expression.typing import Type
  6. from mindspore.common import dtype as mstype
  7. from mindspore.common.parameter import Parameter
  8. from mindspore.common.initializer import (
  9. initializer, Constant, Normal, TruncatedNormal, Initializer, _assignment, _calculate_in_and_out, One, Zero
  10. )
  11. from mindspore.common.tensor import Tensor
  12. from mindspore.ops import operations as P
  13. from mindspore.ops import functional as F
  14. from mindspore.ops import composite as C
  15. import mindspore.context as context
  16. from mindspore.nn import Cell
  17. from mindspore.ops import count_nonzero
  18. import mindspore.numpy as msnp
  19. import numpy as np
  20. from scipy.stats import truncnorm
  21. import random
  22. _dtypeDict = {
  23. 'DType': Type,
  24. 'float16': mstype.float16,
  25. 'float32': mstype.float32,
  26. 'float64': mstype.float64,
  27. 'int8': mstype.int8,
  28. 'int16': mstype.int16,
  29. 'int32': mstype.int32,
  30. 'int64': mstype.int64,
  31. 'uint8': mstype.uint8,
  32. 'uint16': mstype.uint16,
  33. 'uint32': mstype.uint32,
  34. 'uint64': mstype.uint64
  35. }
  36. DType = Type
  37. float16 = mstype.float16
  38. float32 = mstype.float32
  39. float64 = mstype.float64
  40. int8 = mstype.int8
  41. int16 = mstype.int16
  42. int32 = mstype.int32
  43. int64 = mstype.int64
  44. uint8 = mstype.uint8
  45. uint16 = mstype.uint16
  46. uint32 = mstype.uint32
  47. uint64 = mstype.uint64
  48. # isinstance input output
  49. # TensorLike = Tensor_
  50. def set_context(**kwargs):
  51. return context.set_context(**kwargs)
  52. def get_tensor_shape(x):
  53. return list(P.Shape()(x))
  54. # initializers
  55. def zeros(shape, dtype=mstype.float32):
  56. """
  57. Creates a tensor with all elements set to zero.
  58. Parameters
  59. ----------
  60. shape : A list of integers
  61. a tuple of integers, or a 1-D Tensor of type int32.
  62. dtype : tensor
  63. The DType of an element in the resulting Tensor
  64. Returns
  65. -------
  66. A Tensor with all elements set to zero.
  67. """
  68. # shape = shape[::-1]
  69. arr = np.ndarray(shape)
  70. init_obj = Zero()
  71. init_obj(arr)
  72. return Tensor(arr, dtype=dtype)
  73. def ones(shape, dtype=mstype.float32):
  74. """
  75. Creates a tensor with all elements set to ones.
  76. Parameters
  77. ----------
  78. shape : A list of integers
  79. a tuple of integers, or a 1-D Tensor of type int32.
  80. dtype : tensor
  81. The DType of an element in the resulting Tensor
  82. Returns
  83. -------
  84. A Tensor with all elements set to zero.
  85. """
  86. # shape = shape[::-1]
  87. arr = np.ndarray(shape)
  88. init_obj = One()
  89. init_obj(arr)
  90. return Tensor(arr, dtype=dtype)
  91. def constant(value, dtype=mstype.float32, shape=None):
  92. """
  93. Creates a constant tensor from a tensor-like object.
  94. Parameters
  95. ----------
  96. value : list
  97. A constant value (or list) of output type dtype.
  98. dtype : tensor
  99. The type of the elements of the resulting tensor.
  100. shape : tuple
  101. Optional dimensions of resulting tensor.
  102. Returns
  103. -------
  104. A Constant Tensor.
  105. """
  106. # shape = shape[::-1]
  107. arr = np.ndarray(shape)
  108. Constant(value)(arr=arr)
  109. return Tensor(arr, dtype=dtype)
  110. class Uniform(Initializer):
  111. """
  112. Initialize a uniform array, and obtain values U(-scale, scale) from the uniform distribution
  113. to fill the input tensor.
  114. Args:
  115. minval : int
  116. The lower bound on the range of random values to generate (inclusive). Defaults to 0.
  117. maxval : int
  118. The upper bound on the range of random values to generate (exclusive). Defaults to 1 if dtype is floating point.
  119. seed : int
  120. Used in combination with tf.random.set_seed to create a reproducible sequence of tensors across multiple calls.
  121. Returns:
  122. Array, uniform array.
  123. """
  124. def __init__(self, minval=0, maxval=None, seed=None):
  125. super(Uniform, self).__init__(minval=minval, maxval=maxval, seed=seed)
  126. self.minval = minval
  127. self.maxval = maxval
  128. self.seed = seed
  129. def _initialize(self, arr):
  130. random.seed(self.seed)
  131. tmp = np.random.uniform(self.minval, self.maxval, arr.shape)
  132. _assignment(arr, tmp)
  133. def random_uniform(shape, minval=0, maxval=None, dtype=mstype.float32, seed=None):
  134. """
  135. Outputs random values from a uniform distribution.
  136. Parameters
  137. ----------
  138. shape : tuple
  139. A 1-D integer Tensor or Python array. The shape of the output tensor.
  140. minval : int
  141. The lower bound on the range of random values to generate (inclusive). Defaults to 0.
  142. maxval : int
  143. The upper bound on the range of random values to generate (exclusive). Defaults to 1 if dtype is floating point.
  144. dtype : tensor
  145. The type of the output: float16, float32, float64, int32, or int64.
  146. seed : int
  147. Used in combination with tf.random.set_seed to create a reproducible sequence of tensors across multiple calls.
  148. Returns
  149. -------
  150. A tensor of the specified shape filled with random uniform values.
  151. """
  152. # shape = shape[::-1]
  153. arr = np.ndarray(shape)
  154. init_obj = Uniform(minval=minval, maxval=maxval, seed=seed)
  155. init_obj(arr)
  156. return Tensor(arr, dtype=dtype)
  157. class Normal(Initializer):
  158. """
  159. Initialize a normal array, and obtain values N(0, sigma) from the uniform distribution
  160. to fill the input tensor.
  161. Parameters
  162. ----------
  163. mean : float
  164. The mean of the normal distribution
  165. stddev : float
  166. The standard deviation of the normal distribution.
  167. seed : A Python integer
  168. Used to create a random seed for the distribution
  169. Returns:
  170. Array, normal array.
  171. """
  172. def __init__(self, mean=0.0, stddev=0.01, seed=None):
  173. super(Normal, self).__init__(mean=mean, stddev=stddev)
  174. self.mean = mean
  175. self.stddev = stddev
  176. self.seed = seed
  177. def _initialize(self, arr):
  178. random.seed(self.seed)
  179. tmp = np.random.normal(self.mean, self.stddev, arr.shape)
  180. _assignment(arr, tmp)
  181. class RandomNormal(Cell):
  182. def __init__(self, mean=0.0, stddev=0.01, seed=None):
  183. super(RandomNormal, self).__init__()
  184. self.normal = Normal(mean=mean, stddev=stddev, seed=seed)
  185. def construct(self, shape):
  186. arr = np.ndarray(shape)
  187. outputs = self.normal(arr)
  188. return outputs
  189. def random_normal(shape, mean=0.0, stddev=1.0, dtype=mstype.float32, seed=None):
  190. """
  191. Outputs random values from a normal distribution.
  192. Parameters
  193. ----------
  194. shape : tuple
  195. A 1-D integer Tensor or Python array. The shape of the output tensor.
  196. mean : float
  197. The mean of the normal distribution
  198. stddev : float
  199. The standard deviation of the normal distribution.
  200. dtype : tensor
  201. The type of the output.
  202. seed : A Python integer
  203. Used to create a random seed for the distribution
  204. Returns
  205. -------
  206. A tensor of the specified shape filled with random normal values.
  207. """
  208. # shape = shape[::-1]
  209. arr = np.ndarray(shape)
  210. init_obj = Normal(mean=mean, stddev=stddev, seed=seed)
  211. init_obj(arr)
  212. return Tensor(arr, dtype=dtype)
  213. class TruncatedNormal(Initializer):
  214. """
  215. Initialize a truncated normal distribution which is a bounded normal distribution within N(low, high).
  216. Args:
  217. sigma (float): The sigma of the array. Default: 0.01.
  218. Returns:
  219. Array, truncated normal array.
  220. """
  221. def __init__(self, mean=0.0, stddev=0.01, seed=None):
  222. super(TruncatedNormal, self).__init__(mean=mean, stddev=stddev, seed=seed)
  223. self.mean = mean
  224. self.stddev = stddev
  225. self.seed = seed
  226. def _initialize(self, arr):
  227. tmp = truncnorm.rvs(-2, 2, loc=self.mean, scale=self.stddev, size=arr.shape, random_state=None)
  228. _assignment(arr, tmp)
  229. def truncated_normal(shape, mean=0.0, stddev=1.0, dtype=mstype.float32, seed=None):
  230. """
  231. Outputs random values from a truncated normal distribution.
  232. Parameters
  233. ----------
  234. shape : tuple
  235. A 1-D integer Tensor or Python array. The shape of the output tensor.
  236. mean : float
  237. The mean of the normal distribution
  238. stddev : float
  239. The standard deviation of the normal distribution.
  240. dtype : tensor
  241. The type of the output.
  242. seed : A Python integer
  243. Used to create a random seed for the distribution
  244. Returns
  245. -------
  246. A tensor of the specified shape filled with random truncated normal values.
  247. """
  248. # shape = shape[::-1]
  249. arr = np.ndarray(shape)
  250. init_obj = TruncatedNormal(mean=mean, stddev=stddev, seed=seed)
  251. init_obj(arr)
  252. return Tensor(arr, dtype=dtype)
  253. class HeNormal(Initializer):
  254. r"""
  255. he_normal: It draws samples from a truncated normal distribution centered on 0 with
  256. stddev = sqrt(2 / fan_in) where fan_in is the number of input units in the weight tensor.
  257. Args:
  258. arr (Array): The array to be assigned.
  259. Returns:
  260. Array, assigned array.
  261. """
  262. def __init__(self, seed=None):
  263. super(HeNormal, self).__init__(seed=seed)
  264. self.seed = seed
  265. def _initialize(self, arr):
  266. n_in, _ = _calculate_in_and_out(arr)
  267. boundary = np.sqrt(2.0 / n_in)
  268. random.seed(self.seed)
  269. data = np.random.normal(-boundary, boundary, arr.shape)
  270. _assignment(arr, data)
  271. def he_normal(shape, dtype, seed=None):
  272. """
  273. He normal initializer.
  274. Parameters
  275. ----------
  276. seed : A Python integer.
  277. Used to seed the random generator.
  278. shape : tuple
  279. A 1-D integer Tensor or Python array. The shape of the output tensor.
  280. dtype : tensor
  281. The type of the output.
  282. Returns
  283. -------
  284. A tensor of the specified shape filled with he normal values.
  285. """
  286. # shape = shape[::-1]
  287. arr = np.ndarray(shape)
  288. init_obj = HeNormal(seed)
  289. init_obj(arr)
  290. return Tensor(arr, dtype=dtype)
  291. def Variable(initial_value, name, trainable=True):
  292. """
  293. Creates a new variable with value initial_value.
  294. Parameters
  295. ----------
  296. initial_value : tensor
  297. A Tensor, or Python object convertible to a Tensor
  298. name : str
  299. Optional name for the variable. Defaults to 'Variable' and gets uniquified automatically.
  300. Returns
  301. -------
  302. Variable
  303. """
  304. var = Parameter(initial_value, name=name, requires_grad=trainable)
  305. return var
  306. class MatMul(Cell):
  307. def __init__(self):
  308. super(MatMul, self).__init__()
  309. self.matmul = P.MatMul()
  310. def construct(self, a, b):
  311. return self.matmul(a, b)
  312. def matmul(a, b):
  313. """
  314. Multiplies matrix a by matrix b, producing a * b.
  315. Parameters
  316. ----------
  317. a : tensor
  318. type float16, float32, float64, int32, complex64, complex128 and rank > 1.
  319. b : tensor
  320. with same type and rank as a.
  321. Returns
  322. -------
  323. A Tensor of the same type as a and b
  324. """
  325. matmul_obj = P.MatMul()
  326. outputs = matmul_obj(a, b)
  327. return outputs
  328. def add(value, bias):
  329. """
  330. Returns x + y element-wise.
  331. Parameters
  332. ----------
  333. value : tensor.
  334. Must be one of the following types: bfloat16, half, float32, float64,
  335. uint8, int8, int16, int32, int64, complex64, complex128, string.
  336. bias : tensor
  337. Must have the same type as a
  338. name : str
  339. A name for the operation
  340. Returns
  341. -------
  342. A Tensor. Has the same type as a.
  343. """
  344. add_obj = P.TensorAdd()
  345. outputs = add_obj(value, bias)
  346. return outputs
  347. def dtypes(dt):
  348. """
  349. Data dtypes.
  350. Parameters
  351. ----------
  352. dt : string
  353. It could be 'uint8', 'uint16', 'uint32', 'uint64', 'int8', 'int16',
  354. 'int32', 'int64', 'float16', 'float32', 'float64', 'DType'.
  355. Returns
  356. -------
  357. Data dtypes
  358. """
  359. if dt not in _dtypeDict.keys():
  360. raise Exception("Unsupported dtype: {}".format(dt))
  361. return _dtypeDict[dt]
  362. class Maximum(Cell):
  363. def __init__(self):
  364. super(Maximum, self).__init__()
  365. self.maximum = P.Maximum()
  366. def construct(self, x, y):
  367. return self.maximum(x, y)
  368. class Minimum(Cell):
  369. def __init__(self):
  370. super(Minimum, self).__init__()
  371. self.minimum = P.Minimum()
  372. def construct(self, x, y):
  373. return self.minimum(x, y)
  374. def minimum(x, y):
  375. """
  376. Returns the min of x and y (i.e. x < y ? x : y) element-wise.
  377. Parameters
  378. ----------
  379. x : tensor.
  380. Must be one of the following types: bfloat16, half, float32, float64, int32, int64.
  381. y : A Tensor.
  382. Must have the same type as x.
  383. name : str
  384. A name for the operation (optional).
  385. Returns
  386. -------
  387. A Tensor. Has the same type as x
  388. """
  389. minimum_obj = P.Minimum()
  390. outputs = minimum_obj(x, y)
  391. return outputs
  392. class FlattenReshape(Cell):
  393. def __init__(self):
  394. super(FlattenReshape, self).__init__()
  395. self.shape = P.Shape()
  396. self.reshape = P.Reshape()
  397. def construct(self, inputs):
  398. dim = 1
  399. for d in self.shape(inputs)[1:]:
  400. dim *= d
  401. return self.reshape(inputs, (-1, dim))
  402. class Reshape(Cell):
  403. def __init__(self, shape):
  404. super(Reshape, self).__init__()
  405. self.reshape = P.Reshape()
  406. self.shape = tuple(shape)
  407. def construct(self, tensor):
  408. return self.reshape(tensor, self.shape)
  409. def reshape(tensor, shape):
  410. """
  411. Reshapes a tensor.
  412. Parameters
  413. ----------
  414. tensor : tensor
  415. A Tensor.
  416. shape : tensor
  417. Defines the shape of the output tensor.
  418. Returns
  419. -------
  420. A Tensor. Has the same type as tensor
  421. """
  422. reshape_obj = P.Reshape()
  423. outputs = reshape_obj(tensor, tuple(shape))
  424. return outputs
  425. class Concat(Cell):
  426. def __init__(self, axis):
  427. super(Concat, self).__init__()
  428. self.concat = P.Concat(axis)
  429. def construct(self, values):
  430. return self.concat(values)
  431. def concat(values, axis):
  432. """
  433. Concatenates tensors along one dimension.
  434. Parameters
  435. ----------
  436. values : list
  437. A list of Tensor objects or a single Tensor
  438. axis : int
  439. 0-D int32 Tensor. Dimension along which to concatenate
  440. Returns
  441. -------
  442. A Tensor resulting from concatenation of the input tensors.
  443. """
  444. # TODO testing axis
  445. concat_obj = P.Concat(axis)
  446. outputs = concat_obj(values)
  447. return outputs
  448. def convert_to_tensor(value, dtype=None):
  449. """
  450. Converts the given value to a Tensor.
  451. Parameters
  452. ----------
  453. value : object
  454. An object whose type has a registered Tensor conversion function.
  455. dtype : optional
  456. Optional element type for the returned tensor. If missing, the type is inferred from the type of value.
  457. Returns
  458. -------
  459. A Tensor based on value.
  460. """
  461. #todo testing value
  462. return Tensor(value, dtype=dtype)
  463. def convert_to_numpy(value):
  464. return value.asnumpy()
  465. def sqrt(x):
  466. """
  467. Computes square root of x element-wise.
  468. Parameters
  469. ----------
  470. x : tensor
  471. Must be one of the following types: bfloat16, half, float32, float64, complex64, complex128.
  472. Returns
  473. -------
  474. A Tensor. Has the same type as x.
  475. """
  476. sqrt_obj = P.Sqrt()
  477. outputs = sqrt_obj(x)
  478. return outputs
  479. class ReduceSum(Cell):
  480. def __init__(self, axis):
  481. super(ReduceSum, self).__init__()
  482. self.axis = axis
  483. self.reduce_sum = P.ReduceSum(keep_dims=False)
  484. def construct(self, input):
  485. return self.reduce_sum(input, self.axis)
  486. class ReduceMean(Cell):
  487. def __init__(self, axis):
  488. super(ReduceMean, self).__init__()
  489. self.axis = axis
  490. self.reducemean = P.ReduceMean(keep_dims=False)
  491. def construct(self, inputs):
  492. output = self.reducemean(inputs, self.axis)
  493. return output
  494. def reduce_mean(input_tensor, axis=None):
  495. """
  496. Computes the mean of elements across dimensions of a tensor.
  497. Parameters
  498. ----------
  499. input_tensor : tensor
  500. The tensor to reduce. Should have numeric type.
  501. axis : int
  502. The dimensions to reduce. If None (the default), reduces all dimensions.
  503. Must be in the range [-rank(input_tensor), rank(input_tensor)).
  504. name : str
  505. A name for the operation (optional).
  506. Returns
  507. -------
  508. The reduced tensor.
  509. """
  510. Rmean_obj = P.ReduceMean(keep_dims=False)
  511. outputs = Rmean_obj(input_tensor, axis)
  512. return outputs
  513. class ReduceMax(Cell):
  514. def __init__(self, axis):
  515. super(ReduceMax, self).__init__()
  516. self.axis = axis
  517. self.reducemax = P.ReduceMax(keep_dims=False)
  518. def construct(self, inputs):
  519. output = self.reducemax(inputs, self.axis)
  520. return output
  521. def reduce_max(input_tensor, axis=None):
  522. """
  523. Computes the maximum of elements across dimensions of a tensor.
  524. Parameters
  525. ----------
  526. input_tensor : tensor
  527. The tensor to reduce. Should have real numeric type.
  528. axis : int
  529. The dimensions to reduce. If None (the default), reduces all dimensions.
  530. Must be in the range [-rank(input_tensor), rank(input_tensor)).
  531. name : str
  532. A name for the operation (optional).
  533. Returns
  534. -------
  535. The reduced tensor.
  536. """
  537. Rmax_obj = P.ReduceMax(keep_dims=False)
  538. outputs = Rmax_obj(input_tensor, axis)
  539. return outputs
  540. def reduce_min(input_tensor, axis=None):
  541. """
  542. Computes the minimum of elements across dimensions of a tensor.
  543. Parameters
  544. ----------
  545. input_tensor : tensor
  546. The tensor to reduce. Should have real numeric type.
  547. axis : int
  548. The dimensions to reduce. If None (the default), reduces all dimensions.
  549. Must be in the range [-rank(input_tensor), rank(input_tensor)).
  550. name : str
  551. A name for the operation (optional).
  552. Returns
  553. -------
  554. The reduced tensor.
  555. """
  556. Rmin_obj = P.ReduceMin(keep_dims=False)
  557. outputs = Rmin_obj(input_tensor, axis)
  558. return outputs
  559. class Pad(Cell):
  560. def __init__(self, paddings, mode="REFLECT", constant_values=0):
  561. super(Pad, self).__init__()
  562. if mode not in ['CONSTANT', 'REFLECT', 'SYMMETRIC']:
  563. raise Exception("Unsupported mode: {}".format(mode))
  564. if mode == 'CONSTANT':
  565. self.pad = P.Pad(paddings)
  566. if constant_values-0 == 0:
  567. pass
  568. else:
  569. raise NotImplementedError("constant_values can only be equal to 0.")
  570. else:
  571. self.pad = P.MirrorPad(mode=mode)
  572. self.paddings = Tensor(np.array(self.paddings))
  573. self.mode = mode
  574. def construct(self, x):
  575. if self.mode == 'CONSTANT':
  576. return self.pad(x)
  577. else:
  578. return self.pad(x, self.paddings)
  579. def pad(tensor, paddings, mode='CONSTANT', constant_values=0):
  580. """
  581. Pads a tensor.
  582. Parameters
  583. ----------
  584. tensor : tensor
  585. A Tensor.
  586. paddings : tuple
  587. A tuple of type int32.
  588. mode : str
  589. One of "CONSTANT", "REFLECT", or "SYMMETRIC" (case-insensitive)
  590. constant_values : int
  591. In "CONSTANT" mode, the scalar pad value to use. Must be same type as tensor.
  592. Returns
  593. -------
  594. A Tensor. Has the same type as tensor.
  595. """
  596. raise NotImplementedError
  597. class Unstack(Cell):
  598. def __init__(self, axis, num=None):
  599. super(Unstack, self).__init__()
  600. if num is not None:
  601. raise ("The num Parameters do not need to be set.")
  602. self.unstack = P.Unpack(axis=axis)
  603. def construct(self, values):
  604. return self.unstack(values)
  605. class Stack(Cell):
  606. def __init__(self, axis=0):
  607. super(Stack, self).__init__()
  608. self.stack = P.Pack(axis=axis)
  609. def construct(self, values):
  610. return self.stack(values)
  611. def stack(values, axis=0):
  612. """
  613. Stacks a list of rank-R tensors into one rank-(R+1) tensor.
  614. Parameters
  615. ----------
  616. values : list
  617. A list of Tensor objects with the same shape and type.
  618. axis : int
  619. An int. The axis to stack along. Defaults to the first dimension.
  620. Negative values wrap around, so the valid range is [-(R+1), R+1).
  621. Returns
  622. -------
  623. A stacked Tensor with the same type as values.
  624. """
  625. _stack = P.Pack(axis=axis)
  626. return _stack(values)
  627. class Meshgrid(Cell):
  628. def __init__(self, indexing='xy'):
  629. super(Meshgrid, self).__init__()
  630. self._meshgrid = P.Meshgrid(indexing=indexing)
  631. def construct(self, *args):
  632. inputs = tuple(*args)
  633. return self._meshgrid(inputs)
  634. def meshgrid(*args, **kwargs):
  635. """
  636. Broadcasts parameters for evaluation on an N-D grid.
  637. Parameters
  638. ----------
  639. x : tensor
  640. Tensors with rank 1.
  641. y : tensor
  642. Tensors with rank 1.
  643. Returns
  644. -------
  645. A list of N Tensors with rank N.
  646. """
  647. _meshgrid = P.Meshgrid(**kwargs)
  648. return _meshgrid(*args)
  649. def range(start, limit=None, delta=1, dtype=None):
  650. """
  651. Creates a sequence of numbers.
  652. Parameters
  653. ----------
  654. start : tensor
  655. A 0-D Tensor (scalar). Acts as first entry in the range if limit is not None;
  656. otherwise, acts as range limit and first entry defaults to 0.
  657. limit : tensor
  658. A 0-D Tensor (scalar). Upper limit of sequence, exclusive. If None,
  659. defaults to the value of start while the first entry of the range defaults to 0.
  660. delta : tensor
  661. A 0-D Tensor (scalar). Number that increments start. Defaults to 1.
  662. dtype : type
  663. The type of the elements of the resulting tensor.
  664. Returns
  665. -------
  666. An 1-D Tensor of type dtype.
  667. """
  668. pass
  669. class ExpandDims(Cell):
  670. def __init__(self, axis):
  671. super(ExpandDims, self).__init__()
  672. self.axis = axis
  673. self.expand_dims = P.ExpandDims()
  674. def construct(self, input):
  675. output = self.expand_dims(input, self.axis)
  676. return output
  677. def expand_dims(input, axis):
  678. """
  679. Inserts a dimension of 1 into a tensor's shape.
  680. Parameters
  681. ----------
  682. input : tensor
  683. A Tensor.
  684. axis : int
  685. 0-D (scalar). Specifies the dimension index at which to expand the shape of input.
  686. Must be in the range [-rank(input) - 1, rank(input)].
  687. Returns
  688. -------
  689. A Tensor with the same data as input, but its shape has an additional dimension of size 1 added.
  690. """
  691. expand_obj = P.ExpandDims()
  692. outputs = expand_obj(input, axis)
  693. return outputs
  694. class Tile(Cell):
  695. def __init__(self):
  696. super(Tile, self).__init__()
  697. self.tile = P.Tile()
  698. def construct(self, input, multiples):
  699. return self.tile(input, tuple(multiples))
  700. def tile(input, multiples):
  701. """
  702. Constructs a tensor by tiling a given tensor.
  703. Parameters
  704. ----------
  705. input : tensor
  706. A Tensor. 1-D or higher.
  707. multiples : tensor
  708. Must be one of the following types: int32, int64. 1-D.
  709. Length must be the same as the number of dimensions in input
  710. Returns
  711. -------
  712. A Tensor. Has the same type as input.
  713. """
  714. tile_obj = P.Tile()
  715. outputs = tile_obj(input, multiples)
  716. return outputs
  717. class Cast(Cell):
  718. def __init__(self, dtype):
  719. super(Cast, self).__init__()
  720. self.dtype = dtype
  721. self.cast = P.Cast()
  722. def construct(self, input):
  723. return self.cast(input, self.dtype)
  724. def cast(x, dtype):
  725. """
  726. Casts a tensor to a new type.
  727. Parameters
  728. ----------
  729. x : tensor
  730. A Tensor or SparseTensor or IndexedSlices of numeric type.
  731. It could be uint8, uint16, uint32, uint64, int8, int16, int32, int64, float16, float32, float64.
  732. dtype : dtpye
  733. The destination type. The list of supported dtypes is the same as x
  734. Returns
  735. -------
  736. A Tensor or SparseTensor or IndexedSlices with same shape as x and same type as dtype.
  737. """
  738. cast_obj = P.Cast()
  739. outputs = cast_obj(x, dtype)
  740. return outputs
  741. class Transpose(Cell):
  742. def __init__(self, perm, conjugate=False):
  743. super(Transpose, self).__init__()
  744. self.perm = tuple(perm)
  745. self.conjugate = conjugate
  746. self.transpose = P.Transpose()
  747. if self.conjugate:
  748. raise NotImplementedError("conjugate not implemented")
  749. def construct(self, a):
  750. return self.transpose(a, self.perm)
  751. def transpose(a, perm=None, conjugate=False):
  752. """
  753. Transposes a.
  754. Parameters
  755. ----------
  756. a : tensor
  757. A Tensor.
  758. perm : int
  759. A permutation of the dimensions of a.
  760. conjugate : bool
  761. Setting it to True is mathematically equivalent to ms.math.conj(ms.transpose(input)).
  762. Returns
  763. -------
  764. A transposed Tensor.
  765. """
  766. # TODO conjugate
  767. trans_obj = P.Transpose()
  768. outputs = trans_obj(a, perm)
  769. print(outputs)
  770. def gather_nd(params, indices, batch_dims=0):
  771. """
  772. Gather slices from params into a Tensor with shape specified by indices.
  773. Parameters
  774. ----------
  775. params : tensor
  776. The tensor from which to gather values.
  777. indices : tensor
  778. Must be one of the following types: int32, int64. Index tensor.
  779. batch_dims : int
  780. An integer or a scalar 'Tensor'. The number of batch dimensions.
  781. Returns
  782. -------
  783. A Tensor. Has the same type as params.
  784. """
  785. pass
  786. def clip_by_value(t, clip_value_min, clip_value_max):
  787. """
  788. Clips tensor values to a specified min and max.
  789. Parameters
  790. ----------
  791. t : tensor
  792. A Tensor or IndexedSlices
  793. clip_value_min : tensor
  794. A 0-D (scalar) Tensor, or a Tensor with the same shape as t. The minimum value to clip by
  795. clip_value_max : tensor
  796. A 0-D (scalar) Tensor, or a Tensor with the same shape as t. The minimum value to clip by
  797. Returns
  798. -------
  799. A clipped Tensor or IndexedSlices.
  800. """
  801. min_value = Tensor(clip_value_min, mstype.float32)
  802. max_value = Tensor(clip_value_max, mstype.float32)
  803. output = C.clip_by_value(t, min_value, max_value)
  804. return output
  805. def split(value, num_or_size_splits, axis=0, num=None):
  806. """
  807. Splits a tensor into sub tensors.
  808. Parameters
  809. ----------
  810. value : tensor
  811. The Tensor to split.
  812. num_or_size_splits : list
  813. Either an integer indicating the number of splits along split_dim or a 1-D integer Tensor or
  814. Python list containing the sizes of each output tensor along split_dim.
  815. axis : int
  816. The dimension along which to split. Must be in the range [-rank(value), rank(value)). Defaults to 0.
  817. num : int
  818. used to specify the number of outputs when it cannot be inferred from the shape of size_splits.
  819. Returns
  820. -------
  821. Tensor objects resulting from splitting value.
  822. """
  823. pass
  824. class Floor(Cell):
  825. def __call__(self, *args, **kwargs):
  826. raise NotImplementedError
  827. def floor(x):
  828. return NotImplementedError
  829. def gather(params, indices):
  830. return NotImplementedError
  831. def linspace(start, stop, num):
  832. return NotImplementedError
  833. def slice(inputs, starts, sizes):
  834. return NotImplementedError
  835. def add_n(inputs):
  836. return NotImplementedError
  837. class OneHot(Cell):
  838. def __init__(self, axis=-1, depth=1, on_value=1.0, off_value=0.0, dtype=mstype.float32):
  839. super(OneHot, self).__init__()
  840. self.onehot = P.OneHot(axis)
  841. self.depth = depth
  842. self.dtype = dtype
  843. self.on_value = F.cast(on_value, self.dtype)
  844. self.off_value = F.cast(off_value, self.dtype)
  845. def construct(self, indices):
  846. return self.onehot(indices, self.depth, self.on_value, self.off_value)
  847. class L2Normalize(Cell):
  848. def __init__(self, axis=None, epsilon=1e-12):
  849. super(L2Normalize, self).__init__()
  850. pass
  851. def construct(self, input, *args, **kwargs):
  852. pass
  853. class EmbeddingLookup(Cell):
  854. def __init__(self, max_norm=0):
  855. super(EmbeddingLookup, self).__init__()
  856. self.max_norm = max_norm
  857. self.embedding_lookup = P.EmbeddingLookup()
  858. def construct(self, params, ids, *args, **kwargs):
  859. return self.embedding_lookup(params, ids, self.max_norm)
  860. class NCELoss(Cell):
  861. def __init__(self, num_true=1, sampled_values=None, remove_accidental_hits=False):
  862. super(NCELoss, self).__init__()
  863. pass
  864. def construct(self, weights, biases, labels, inputs, num_sampled, num_classes):
  865. raise NotImplementedError
  866. class NotEqual(Cell):
  867. def __init__(self):
  868. super(NotEqual, self).__init__()
  869. self.not_equal = P.NotEqual()
  870. def construct(self, x, y):
  871. outputs = self.not_equal(x, y)
  872. return outputs
  873. class CountNonzero(object):
  874. def __init__(self, keepdims=None, dtype=int64):
  875. self.keepdims = keepdims
  876. self.dtype = dtype
  877. def __call__(self, input, axis=None):
  878. input = self.convert_dtype(input)
  879. return count_nonzero(x=input, axis=axis, keep_dims=self.keepdims, dtype=self.dtype)
  880. def bool_convert_to_tensor(self, x):
  881. x = x.asnumpy()
  882. shapes = x.shape
  883. b = np.ones(shapes)
  884. if len(shapes) == 1:
  885. for i in range(shapes - 1):
  886. if x[i] ==True:
  887. b[i] = 1
  888. else:
  889. b[i] = 0
  890. if len(shapes) == 2:
  891. for i in range(shapes[0] - 1):
  892. for j in range(shapes[1] - 1):
  893. if x[i][j] ==True:
  894. b[i][j] = 1
  895. else:
  896. b[i][j] = 0
  897. return Tensor(b, dtype=float32)
  898. def convert_dtype(self, input):
  899. if input.shape == 1 and type(input[0]) is bool:
  900. output = self.bool_convert_to_tensor(input)
  901. elif input.shape == 2 and type(input[0][0]) is bool:
  902. output = self.bool_convert_to_tensor(input)
  903. else:
  904. output = input
  905. return output
  906. class Resize(Cell):
  907. def __init__(self, scale, method, antialias=False, data_format='channels_last', ksize=None):
  908. super(Resize, self).__init__()
  909. self.data_format = data_format
  910. if method not in ['nearest', 'bilinear']:
  911. raise ('The method must be "nearest" or "bilinear".')
  912. self.method = method
  913. if ksize is None:
  914. raise ('The "bilinear" and "nearest" method must enter ksize. The dimension of size must be 2 (H, W).')
  915. out_seize = (int(ksize[0] * scale[0]), int(ksize[1] * scale[1]))
  916. if self.method == 'nearest':
  917. self.resize = P.ResizeNearestNeighbor(size=out_seize, align_corners=antialias)
  918. elif self.method == 'bilinear':
  919. self.resize = P.ResizeBilinear(size=out_seize)
  920. def construct(self, inputs):
  921. if self.data_format == 'channels_last':
  922. inputs = nhwc_to_nchw(inputs)
  923. outputs = self.resize(inputs)
  924. if self.data_format == 'channels_last':
  925. outputs = nchw_to_nhwc(outputs)
  926. return outputs
  927. def resize(inputs, output_size, method, antialias):
  928. raise NotImplementedError
  929. class ZeroPadding1D(Cell):
  930. def __init__(self, padding):
  931. super(ZeroPadding1D, self).__init__()
  932. if np.size(padding) == 2:
  933. self.pad = P.Pad(paddings=padding)
  934. else:
  935. raise ("The shape of parameter paddings is (N, 2). N is the rank of input data.")
  936. def construct(self, inputs):
  937. return self.pad(inputs)
  938. class ZeroPadding2D(Cell):
  939. def __init__(self, padding):
  940. super(ZeroPadding2D, self).__init__()
  941. if np.size(padding) == 4:
  942. self.pad = P.Pad(paddings=padding)
  943. else:
  944. raise ("The shape of parameter paddings is (N, 2). N is the rank of input data.")
  945. def construct(self, inputs):
  946. return self.pad(inputs)
  947. class ZeroPadding3D(Cell):
  948. def __init__(self, padding):
  949. super(ZeroPadding3D, self).__init__()
  950. if np.size(padding) == 6:
  951. self.pad = P.Pad(paddings=padding)
  952. else:
  953. raise ("The shape of parameter paddings is (N, 2). N is the rank of input data.")
  954. def construct(self, inputs):
  955. return self.pad(inputs)
  956. class Sign(Cell):
  957. def __init__(self):
  958. super(Sign, self).__init__()
  959. self.sign = P.Sign()
  960. def construct(self, x):
  961. return self.sign(x)
  962. class Ceil(Cell):
  963. def __init__(self):
  964. super(Ceil, self).__init__()
  965. self.ceil = P.Ceil()
  966. def construct(self, x):
  967. return self.ceil(x)
  968. def ceil(x):
  969. _ceil = P.Ceil()
  970. return _ceil(x)
  971. def multiply(x, y):
  972. raise NotImplementedError
  973. def divide(x, y):
  974. return msnp.divide(x, y)
  975. def identity(x):
  976. raise NotImplementedError
  977. class BatchToSpace(Cell):
  978. def __init__(self, block_size, crops):
  979. super(BatchToSpace, self).__init__()
  980. self.batch_to_space = P.BatchToSpace(block_size=block_size, crops=crops)
  981. def __call__(self, input_x):
  982. return self.batch_to_space(input_x)
  983. class DepthToSpace(Cell):
  984. def __init__(self, block_size, data_format='NHWC'):
  985. super(DepthToSpace, self).__init__()
  986. self.data_format = data_format
  987. self.depth_to_space = P.DepthToSpace(block_size=block_size)
  988. def __call__(self, input):
  989. if self.data_format == 'NHWC':
  990. input = nhwc_to_nchw(input)
  991. output = self.depth_to_space(input)
  992. if self.data_format == 'NHWC':
  993. output = nchw_to_nhwc(output)
  994. return output

TensorLayer3.0 是一款兼容多种深度学习框架为计算后端的深度学习库。计划兼容TensorFlow, Pytorch, MindSpore, Paddle.