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.

utils.py 13 kB

4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. #! /usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import tensorflow as tf
  4. from tensorflow.python.ops.rnn_cell import LSTMStateTuple
  5. import tensorlayer as tl
  6. from tensorlayer import logging
  7. from tensorlayer.decorators import deprecated, deprecated_alias
  8. from tensorlayer.backend.ops.load_backend import BACKEND
  9. __all__ = [
  10. 'cabs',
  11. 'compute_alpha',
  12. 'flatten_reshape',
  13. 'get_collection_trainable',
  14. 'get_layers_with_name',
  15. 'get_variables_with_name',
  16. 'initialize_global_variables',
  17. 'initialize_rnn_state',
  18. 'list_remove_repeat',
  19. 'merge_networks',
  20. 'print_all_variables',
  21. 'quantize',
  22. 'quantize_active',
  23. 'quantize_weight',
  24. 'quantize_active_overflow',
  25. 'quantize_weight_overflow',
  26. 'set_name_reuse',
  27. 'ternary_operation',
  28. ]
  29. ########## Module Public Functions ##########
  30. def cabs(x):
  31. return tf.minimum(1.0, tf.abs(x), name='cabs')
  32. def compute_alpha(x):
  33. """Computing the scale parameter."""
  34. threshold = _compute_threshold(x)
  35. alpha1_temp1 = tf.where(tf.greater(x, threshold), x, tf.zeros_like(x, tf.float32))
  36. alpha1_temp2 = tf.where(tf.less(x, -threshold), x, tf.zeros_like(x, tf.float32))
  37. alpha_array = tf.add(alpha1_temp1, alpha1_temp2, name=None)
  38. alpha_array_abs = tf.abs(alpha_array)
  39. alpha_array_abs1 = tf.where(
  40. tf.greater(alpha_array_abs, 0), tf.ones_like(alpha_array_abs, tf.float32),
  41. tf.zeros_like(alpha_array_abs, tf.float32)
  42. )
  43. alpha_sum = tf.reduce_sum(input_tensor=alpha_array_abs)
  44. n = tf.reduce_sum(input_tensor=alpha_array_abs1)
  45. # alpha = tf.compat.v1.div(alpha_sum, n)
  46. alpha = tf.math.divide(alpha_sum, n)
  47. return alpha
  48. def flatten_reshape(variable, name='flatten'):
  49. """Reshapes a high-dimension vector input.
  50. [batch_size, mask_row, mask_col, n_mask] ---> [batch_size, mask_row x mask_col x n_mask]
  51. Parameters
  52. ----------
  53. variable : TensorFlow variable or tensor
  54. The variable or tensor to be flatten.
  55. name : str
  56. A unique layer name.
  57. Returns
  58. -------
  59. Tensor
  60. Flatten Tensor
  61. """
  62. dim = 1
  63. for d in tl.get_tensor_shape(variable)[1:]: # variable.get_shape()[1:].as_list():
  64. dim *= d
  65. return tl.reshape(variable, shape=[-1, dim])
  66. def get_collection_trainable(name=''):
  67. variables = []
  68. for p in tf.compat.v1.trainable_variables():
  69. # print(p.name.rpartition('/')[0], self.name)
  70. if p.name.rpartition('/')[0] == name:
  71. variables.append(p)
  72. return variables
  73. @deprecated_alias(printable='verbose', end_support_version=1.9) # TODO remove this line for the 1.9 release
  74. def get_layers_with_name(net, name="", verbose=False):
  75. """Get a list of layers' output in a network by a given name scope.
  76. Parameters
  77. -----------
  78. net : :class:`Layer`
  79. The last layer of the network.
  80. name : str
  81. Get the layers' output that contain this name.
  82. verbose : boolean
  83. If True, print information of all the layers' output
  84. Returns
  85. --------
  86. list of Tensor
  87. A list of layers' output (TensorFlow tensor)
  88. Examples
  89. ---------
  90. >>> import tensorlayer as tl
  91. >>> layers = tl.layers.get_layers_with_name(net, "CNN", True)
  92. """
  93. logging.info(" [*] geting layers with %s" % name)
  94. layers = []
  95. i = 0
  96. for layer in net.all_layers:
  97. # logging.info(type(layer.name))
  98. if name in layer.name:
  99. layers.append(layer)
  100. if verbose:
  101. logging.info(" got {:3}: {:15} {}".format(i, layer.name, str(layer.get_shape())))
  102. i = i + 1
  103. return layers
  104. def get_variable_with_initializer(scope_name, var_name, shape, init=tl.initializers.random_normal(), trainable=True):
  105. # FIXME: documentation needed
  106. var_name = scope_name + "/" + var_name
  107. # FIXME: not sure whether this is correct?
  108. # TODO mindspore weights shape : [out_channel, in_channel, kernel_h, kernel_w]
  109. if BACKEND == 'mindspore':
  110. if len(shape) == 2:
  111. pass
  112. else:
  113. shape = shape[::-1]
  114. initial_value = init(shape=shape)
  115. if BACKEND == 'dragon':
  116. return initial_value
  117. var = tl.Variable(initial_value=initial_value, name=var_name, trainable=trainable)
  118. return var
  119. @deprecated_alias(printable='verbose', end_support_version=1.9) # TODO remove this line for the 1.9 release
  120. def get_variables_with_name(name=None, train_only=True, verbose=False):
  121. """Get a list of TensorFlow variables by a given name scope.
  122. Parameters
  123. ----------
  124. name : str
  125. Get the variables that contain this name.
  126. train_only : boolean
  127. If Ture, only get the trainable variables.
  128. verbose : boolean
  129. If True, print the information of all variables.
  130. Returns
  131. -------
  132. list of Tensor
  133. A list of TensorFlow variables
  134. Examples
  135. --------
  136. >>> import tensorlayer as tl
  137. >>> dense_vars = tl.layers.get_variables_with_name('dense', True, True)
  138. """
  139. if name is None:
  140. raise Exception("please input a name")
  141. logging.info(" [*] geting variables with %s" % name)
  142. # tvar = tf.trainable_variables() if train_only else tf.all_variables()
  143. if train_only:
  144. t_vars = tf.compat.v1.trainable_variables()
  145. else:
  146. t_vars = tf.compat.v1.global_variables()
  147. d_vars = [var for var in t_vars if name in var.name]
  148. if verbose:
  149. for idx, v in enumerate(d_vars):
  150. logging.info(" got {:3}: {:15} {}".format(idx, v.name, str(v.get_shape())))
  151. return d_vars
  152. @deprecated(
  153. date="2018-09-30", instructions="This API is deprecated in favor of `sess.run(tf.global_variables_initializer())`"
  154. )
  155. def initialize_global_variables(sess):
  156. """Initialize the global variables of TensorFlow.
  157. Run ``sess.run(tf.global_variables_initializer())`` for TF 0.12+ or
  158. ``sess.run(tf.initialize_all_variables())`` for TF 0.11.
  159. Parameters
  160. ----------
  161. sess : Session
  162. TensorFlow session.
  163. """
  164. if sess is None:
  165. raise AssertionError('The session must be defined')
  166. sess.run(tf.compat.v1.global_variables_initializer())
  167. def initialize_rnn_state(state, feed_dict=None):
  168. """Returns the initialized RNN state.
  169. The inputs are `LSTMStateTuple` or `State` of `RNNCells`, and an optional `feed_dict`.
  170. Parameters
  171. ----------
  172. state : RNN state.
  173. The TensorFlow's RNN state.
  174. feed_dict : dictionary
  175. Initial RNN state; if None, returns zero state.
  176. Returns
  177. -------
  178. RNN state
  179. The TensorFlow's RNN state.
  180. """
  181. if isinstance(state, LSTMStateTuple):
  182. c = state.c.eval(feed_dict=feed_dict)
  183. h = state.h.eval(feed_dict=feed_dict)
  184. return c, h
  185. else:
  186. new_state = state.eval(feed_dict=feed_dict)
  187. return new_state
  188. def list_remove_repeat(x):
  189. """Remove the repeated items in a list, and return the processed list.
  190. You may need it to create merged layer like Concat, Elementwise and etc.
  191. Parameters
  192. ----------
  193. x : list
  194. Input
  195. Returns
  196. -------
  197. list
  198. A list that after removing it's repeated items
  199. Examples
  200. -------
  201. >>> l = [2, 3, 4, 2, 3]
  202. >>> l = list_remove_repeat(l)
  203. [2, 3, 4]
  204. """
  205. y = []
  206. for i in x:
  207. if i not in y:
  208. y.append(i)
  209. return y
  210. def merge_networks(layers=None):
  211. """Merge all parameters, layers and dropout probabilities to a :class:`Layer`.
  212. The output of return network is the first network in the list.
  213. Parameters
  214. ----------
  215. layers : list of :class:`Layer`
  216. Merge all parameters, layers and dropout probabilities to the first layer in the list.
  217. Returns
  218. --------
  219. :class:`Layer`
  220. The network after merging all parameters, layers and dropout probabilities to the first network in the list.
  221. Examples
  222. ---------
  223. >>> import tensorlayer as tl
  224. >>> n1 = ...
  225. >>> n2 = ...
  226. >>> n1 = tl.layers.merge_networks([n1, n2])
  227. """
  228. if layers is None:
  229. raise Exception("layers should be a list of TensorLayer's Layers.")
  230. layer = layers[0]
  231. all_params = []
  232. all_layers = []
  233. all_drop = {}
  234. for l in layers:
  235. all_params.extend(l.all_params)
  236. all_layers.extend(l.all_layers)
  237. all_drop.update(l.all_drop)
  238. layer.all_params = list(all_params)
  239. layer.all_layers = list(all_layers)
  240. layer.all_drop = dict(all_drop)
  241. layer.all_layers = list_remove_repeat(layer.all_layers)
  242. layer.all_params = list_remove_repeat(layer.all_params)
  243. return layer
  244. def print_all_variables(train_only=False):
  245. """Print information of trainable or all variables,
  246. without ``tl.layers.initialize_global_variables(sess)``.
  247. Parameters
  248. ----------
  249. train_only : boolean
  250. Whether print trainable variables only.
  251. - If True, print the trainable variables.
  252. - If False, print all variables.
  253. """
  254. # tvar = tf.trainable_variables() if train_only else tf.all_variables()
  255. if train_only:
  256. t_vars = tf.compat.v1.trainable_variables()
  257. logging.info(" [*] printing trainable variables")
  258. else:
  259. t_vars = tf.compat.v1.global_variables()
  260. logging.info(" [*] printing global variables")
  261. for idx, v in enumerate(t_vars):
  262. logging.info(" var {:3}: {:15} {}".format(idx, str(v.get_shape()), v.name))
  263. def quantize(x):
  264. # ref: https://github.com/AngusG/tensorflow-xnor-bnn/blob/master/models/binary_net.py#L70
  265. # https://github.com/itayhubara/BinaryNet.tf/blob/master/nnUtils.py
  266. with tf.compat.v1.get_default_graph().gradient_override_map({"Sign": "TL_Sign_QuantizeGrad"}):
  267. return tf.sign(x)
  268. def quantize_active(x, bitA):
  269. if bitA == 32:
  270. return x
  271. return _quantize_dorefa(x, bitA)
  272. def quantize_weight(x, bitW, force_quantization=False):
  273. G = tf.compat.v1.get_default_graph()
  274. if bitW == 32 and not force_quantization:
  275. return x
  276. if bitW == 1: # BWN
  277. with G.gradient_override_map({"Sign": "Identity"}):
  278. E = tf.stop_gradient(tf.reduce_mean(input_tensor=tf.abs(x)))
  279. return tf.sign(x / E) * E
  280. x = tf.clip_by_value(x * 0.5 + 0.5, 0.0, 1.0) # it seems as though most weights are within -1 to 1 region anyways
  281. return 2 * _quantize_dorefa(x, bitW) - 1
  282. def quantize_active_overflow(x, bitA):
  283. if bitA == 32:
  284. return x
  285. return _quantize_overflow(x, bitA)
  286. def quantize_weight_overflow(x, bitW):
  287. if bitW == 32:
  288. return x
  289. return _quantize_overflow(x, bitW)
  290. @deprecated(date="2018-06-30", instructions="TensorLayer relies on TensorFlow to check name reusing")
  291. def set_name_reuse(enable=True):
  292. logging.warning('this method is DEPRECATED and has no effect, please remove it from your code.')
  293. def ternary_operation(x):
  294. """Ternary operation use threshold computed with weights."""
  295. g = tf.compat.v1.get_default_graph()
  296. with g.gradient_override_map({"Sign": "Identity"}):
  297. threshold = _compute_threshold(x)
  298. x = tf.sign(tf.add(tf.sign(tf.add(x, threshold)), tf.sign(tf.add(x, -threshold))))
  299. return x
  300. ########## Module Private Functions ##########
  301. @tf.RegisterGradient("TL_Sign_QuantizeGrad")
  302. def _quantize_grad(op, grad):
  303. """Clip and binarize tensor using the straight through estimator (STE) for the gradient."""
  304. return tf.clip_by_value(grad, -1, 1)
  305. def _quantize_dorefa(x, k):
  306. G = tf.compat.v1.get_default_graph()
  307. n = float(2**k - 1)
  308. with G.gradient_override_map({"Round": "Identity"}):
  309. return tf.round(x * n) / n
  310. def _quantize_overflow(x, k):
  311. G = tf.compat.v1.get_default_graph()
  312. n = float(2**k - 1)
  313. max_value = tf.reduce_max(input_tensor=x)
  314. min_value = tf.reduce_min(input_tensor=x)
  315. with G.gradient_override_map({"Round": "Identity"}):
  316. step = tf.stop_gradient((max_value - min_value) / n)
  317. return tf.round((tf.maximum(tf.minimum(x, max_value), min_value) - min_value) / step) * step + min_value
  318. def _compute_threshold(x):
  319. """
  320. ref: https://github.com/XJTUWYD/TWN
  321. Computing the threshold.
  322. """
  323. x_sum = tf.reduce_sum(input_tensor=tf.abs(x), axis=None, keepdims=False, name=None)
  324. # threshold = tf.compat.v1.div(x_sum, tf.cast(tf.size(input=x), tf.float32), name=None)
  325. threshold = tf.math.divide(x_sum, tf.cast(tf.size(input=x), tf.float32), name=None)
  326. threshold = tf.multiply(0.7, threshold, name=None)
  327. return threshold
  328. def mean_var_with_update(update_moving_mean, update_moving_variance, mean, variance):
  329. with tf.control_dependencies([update_moving_mean, update_moving_variance]):
  330. return tf.identity(mean), tf.identity(variance)
  331. def w_fold(w, gama, var, epsilon):
  332. return tf.compat.v1.div(tf.multiply(gama, w), tf.sqrt(var + epsilon))
  333. def bias_fold(beta, gama, mean, var, epsilon):
  334. return tf.subtract(beta, tf.compat.v1.div(tf.multiply(gama, mean), tf.sqrt(var + epsilon)))

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