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.

Layer.cs 10 kB

5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. /*****************************************************************************
  2. Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ******************************************************************************/
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Linq;
  16. using System.Threading;
  17. using Tensorflow.Eager;
  18. using Tensorflow.Keras.ArgsDefinition;
  19. using Tensorflow.Keras.Saving;
  20. using Tensorflow.Keras.Utils;
  21. using Tensorflow.NumPy;
  22. using Tensorflow.Train;
  23. using static Tensorflow.Binding;
  24. namespace Tensorflow.Keras.Engine
  25. {
  26. /// <summary>
  27. /// Base layer class.
  28. /// A layer is a class implementing common neural networks operations, such
  29. /// as convolution, batch norm, etc. These operations require managing weights,
  30. /// losses, updates, and inter-layer connectivity.
  31. /// </summary>
  32. public abstract partial class Layer : AutoTrackable, ILayer
  33. {
  34. /// <summary>
  35. /// Arguments initialize layer.
  36. /// </summary>
  37. LayerArgs args;
  38. /// <summary>
  39. /// Indicates whether `build` needs to be called upon layer call, to create
  40. /// the layer's weights.
  41. /// </summary>
  42. protected bool built;
  43. public bool Built => built;
  44. public bool Trainable => args.Trainable;
  45. public TF_DataType DType => args.DType;
  46. public bool AutoCast => args.Autocast;
  47. public IRegularizer ActivityRegularizer => args.ActivityRegularizer;
  48. /// <summary>
  49. /// A stateful layer is a layer whose updates are run during inference too,
  50. /// for instance stateful RNNs.
  51. /// </summary>
  52. protected bool stateful;
  53. /// <summary>
  54. /// Provides information about which inputs are compatible with the layer.
  55. /// </summary>
  56. protected InputSpec inputSpec;
  57. bool dynamic = true;
  58. public bool SupportsMasking { get; set; }
  59. protected List<IVariableV1> _trainable_weights;
  60. public virtual List<IVariableV1> TrainableVariables => _trainable_weights;
  61. protected List<IVariableV1> _non_trainable_weights;
  62. public List<IVariableV1> non_trainable_variables => _non_trainable_weights;
  63. protected int id;
  64. public int Id => id;
  65. protected string name;
  66. protected string base_name;
  67. public string Name => name;
  68. protected bool computePreviousMask;
  69. protected List<Operation> updates;
  70. public Shape BatchInputShape => args.BatchInputShape;
  71. List<INode> inboundNodes;
  72. public List<INode> InboundNodes => inboundNodes;
  73. List<INode> outboundNodes;
  74. public List<INode> OutboundNodes => outboundNodes;
  75. ThreadLocal<CallContext> callContext = new ThreadLocal<CallContext>();
  76. public CallContext CallContext => callContext.Value;
  77. public Tensor[] input => inboundNodes[0].input_tensors;
  78. public Dictionary<int, List<INode>> NodesByDepth { get; set; }
  79. public Shape OutputShape => inboundNodes[0].Outputs.shape;
  80. protected List<ILayer> _self_tracked_trackables;
  81. public Layer(LayerArgs args)
  82. {
  83. this.args = args;
  84. // A stateful layer is a layer whose updates are run during inference too,
  85. // for instance stateful RNNs.
  86. stateful = false;
  87. // Indicates whether `build` needs to be called upon layer call, to create
  88. // the layer's weights.
  89. built = false;
  90. SupportsMasking = false;
  91. id = ops.uid_layer();
  92. _init_set_name(args.Name);
  93. _trainable_weights = new List<IVariableV1>();
  94. _non_trainable_weights = new List<IVariableV1>();
  95. computePreviousMask = false;
  96. updates = new List<Operation>();
  97. _self_tracked_trackables = new List<ILayer>();
  98. inboundNodes = new List<INode>();
  99. outboundNodes = new List<INode>();
  100. // Manage input shape information if passed.
  101. if (args.BatchInputShape == null && args.InputShape != null)
  102. {
  103. args.BatchInputShape = new long[] { args.BatchSize }.Concat(args.InputShape.dims).ToArray();
  104. }
  105. }
  106. bool _in_functional_construction_mode(Tensors inputs)
  107. {
  108. return tf.Context.executing_eagerly()
  109. && inputs.Count(x => x is not EagerTensor && x is not NDArray) == inputs.Count();
  110. }
  111. public void SetConnectivityMetadata(Tensors inputs, Tensors outputs)
  112. => _set_connectivity_metadata_(inputs, outputs);
  113. private void _set_connectivity_metadata_(Tensors inputs, Tensors outputs)
  114. {
  115. var node = new Node(new NodeArgs
  116. {
  117. InputTensors = inputs,
  118. Outputs = outputs
  119. });
  120. node.Connect(this);
  121. }
  122. private void _handle_activity_regularization(Tensors inputs, Tensors outputs)
  123. {
  124. //if(_activity_regularizer != null)
  125. {
  126. }
  127. }
  128. private void _set_mask_metadata(Tensors inputs, Tensors outputs, Tensors previous_mask)
  129. {
  130. }
  131. private Tensor compute_mask(Tensor inputs, Tensor mask = null)
  132. {
  133. return null;
  134. }
  135. /// <summary>
  136. /// Subclass has to override this method.
  137. /// </summary>
  138. /// <param name="inputs"></param>
  139. /// <param name="state"></param>
  140. /// <param name="training"></param>
  141. /// <returns></returns>
  142. protected virtual Tensors Call(Tensors inputs, Tensor state = null, bool? training = null)
  143. {
  144. return inputs;
  145. }
  146. protected virtual string _name_scope()
  147. {
  148. return Name;
  149. }
  150. protected void MaybeBuild(Tensors inputs)
  151. {
  152. // Check input assumptions set before layer building, e.g. input rank.
  153. if (built)
  154. return;
  155. if (DType == TF_DataType.DtInvalid)
  156. args.DType = inputs.dtype;
  157. tf.init_scope();
  158. bool need_restore_mode = false;
  159. if (inputs.Any(x => x is EagerTensor) || tf.Context.is_build_function())
  160. {
  161. need_restore_mode = true;
  162. tf.Context.eager_mode(isFunc: tf.Context.is_build_function());
  163. }
  164. build(inputs.shape);
  165. if (need_restore_mode)
  166. tf.Context.restore_mode();
  167. built = true;
  168. }
  169. public virtual void build(Shape input_shape)
  170. {
  171. built = true;
  172. }
  173. protected virtual void add_loss(Func<Tensor> losses)
  174. {
  175. }
  176. /// <summary>
  177. /// Create lambdas which compute regularization losses.
  178. /// </summary>
  179. /// <param name="name"></param>
  180. /// <param name="variable"></param>
  181. /// <param name="regularizer"></param>
  182. void _handle_weight_regularization(string name, IVariableV1 variable, IRegularizer regularizer)
  183. {
  184. add_loss(() => tf_with(ops.name_scope(name + "/Regularizer"), scope =>
  185. regularizer.Apply(new RegularizerArgs(variable.AsTensor())
  186. {
  187. })
  188. ));
  189. }
  190. /*protected virtual void add_update(Tensor[] updates, bool inputs = false)
  191. {
  192. var updates_op = updates.Select(x => x.op).ToArray();
  193. this.updates.AddRange(updates_op);
  194. }*/
  195. // Determine layer name (non-unique).
  196. protected virtual void _init_set_name(string name, bool zero_based = true)
  197. {
  198. base_name = name;
  199. this.name = name;
  200. if (name == null)
  201. {
  202. base_name = generic_utils.to_snake_case(this.GetType().Name);
  203. this.name = base_layer_utils.unique_layer_name(base_name, zero_based: zero_based);
  204. }
  205. }
  206. public int count_params()
  207. {
  208. if (Trainable)
  209. return layer_utils.count_params(this, weights);
  210. return 0;
  211. }
  212. List<IVariableV1> ILayer.TrainableWeights
  213. {
  214. get
  215. {
  216. return _trainable_weights;
  217. }
  218. }
  219. List<IVariableV1> ILayer.NonTrainableWeights
  220. {
  221. get
  222. {
  223. return _non_trainable_weights;
  224. }
  225. }
  226. public List<IVariableV1> weights
  227. {
  228. get
  229. {
  230. var weights = new List<IVariableV1>();
  231. weights.AddRange(_trainable_weights);
  232. weights.AddRange(_non_trainable_weights);
  233. return weights;
  234. }
  235. set
  236. {
  237. if (weights.Count() != value.Count()) throw new ValueError(
  238. $"You called `set_weights` on layer \"{this.name}\"" +
  239. $"with a weight list of length {len(value)}, but the layer was " +
  240. $"expecting {len(weights)} weights.");
  241. foreach (var (this_w, v_w) in zip(weights, value))
  242. this_w.assign(v_w, read_value: true);
  243. }
  244. }
  245. public List<IVariableV1> Variables => weights;
  246. public virtual LayerArgs get_config()
  247. => args;
  248. }
  249. }