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 8.9 kB

4 years ago
4 years ago
6 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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.Keras.ArgsDefinition;
  18. using Tensorflow.Keras.Saving;
  19. using Tensorflow.Keras.Utils;
  20. using Tensorflow.Train;
  21. using static Tensorflow.Binding;
  22. namespace Tensorflow.Keras.Engine
  23. {
  24. /// <summary>
  25. /// Base layer class.
  26. /// A layer is a class implementing common neural networks operations, such
  27. /// as convolution, batch norm, etc. These operations require managing weights,
  28. /// losses, updates, and inter-layer connectivity.
  29. /// </summary>
  30. public abstract partial class Layer : AutoTrackable, ILayer
  31. {
  32. /// <summary>
  33. /// Arguments initialize layer.
  34. /// </summary>
  35. LayerArgs args;
  36. /// <summary>
  37. /// Indicates whether `build` needs to be called upon layer call, to create
  38. /// the layer's weights.
  39. /// </summary>
  40. protected bool built;
  41. public bool Built => built;
  42. public bool Trainable => args.Trainable;
  43. public TF_DataType DType => args.DType;
  44. /// <summary>
  45. /// A stateful layer is a layer whose updates are run during inference too,
  46. /// for instance stateful RNNs.
  47. /// </summary>
  48. protected bool stateful;
  49. /// <summary>
  50. /// Provides information about which inputs are compatible with the layer.
  51. /// </summary>
  52. protected InputSpec inputSpec;
  53. bool dynamic = true;
  54. public bool SupportsMasking { get; set; }
  55. protected List<IVariableV1> trainable_weights;
  56. public virtual List<IVariableV1> trainable_variables => trainable_weights;
  57. protected List<IVariableV1> non_trainable_weights;
  58. public List<IVariableV1> non_trainable_variables => non_trainable_weights;
  59. protected string name;
  60. protected string base_name;
  61. public string Name => name;
  62. protected bool computePreviousMask;
  63. protected List<Operation> updates;
  64. public TensorShape BatchInputShape => args.BatchInputShape;
  65. List<INode> inboundNodes;
  66. public List<INode> InboundNodes => inboundNodes;
  67. List<INode> outboundNodes;
  68. public List<INode> OutboundNodes => outboundNodes;
  69. ThreadLocal<CallContext> callContext;
  70. public CallContext CallContext => callContext.Value;
  71. public Tensor[] input => inboundNodes[0].input_tensors;
  72. public Dictionary<int, List<INode>> NodesByDepth { get; set; }
  73. public TensorShape output_shape => inboundNodes[0].Outputs.shape;
  74. public Layer(LayerArgs args)
  75. {
  76. this.args = args;
  77. // A stateful layer is a layer whose updates are run during inference too,
  78. // for instance stateful RNNs.
  79. stateful = false;
  80. // Indicates whether `build` needs to be called upon layer call, to create
  81. // the layer's weights.
  82. built = false;
  83. SupportsMasking = false;
  84. _init_set_name(args.Name);
  85. trainable_weights = new List<IVariableV1>();
  86. non_trainable_weights = new List<IVariableV1>();
  87. computePreviousMask = false;
  88. updates = new List<Operation>();
  89. inboundNodes = new List<INode>();
  90. outboundNodes = new List<INode>();
  91. // Manage input shape information if passed.
  92. if (args.BatchInputShape == null && args.InputShape != null)
  93. {
  94. args.BatchInputShape = new long[] { args.BatchSize }.Concat(args.InputShape.dims).ToArray();
  95. }
  96. }
  97. bool _in_functional_construction_mode(Tensors inputs)
  98. {
  99. return tf.Context.executing_eagerly()
  100. && inputs.Count(x => x.IsCreatedInGraphMode) == inputs.Count();
  101. }
  102. public void SetConnectivityMetadata(Tensors inputs, Tensors outputs)
  103. => _set_connectivity_metadata_(inputs, outputs);
  104. private void _set_connectivity_metadata_(Tensors inputs, Tensors outputs)
  105. {
  106. var node = new Node(new NodeArgs
  107. {
  108. InputTensors = inputs,
  109. Outputs = outputs
  110. });
  111. node.Connect(this);
  112. }
  113. private void _handle_activity_regularization(Tensors inputs, Tensors outputs)
  114. {
  115. //if(_activity_regularizer != null)
  116. {
  117. }
  118. }
  119. private void _set_mask_metadata(Tensors inputs, Tensors outputs, Tensors previous_mask)
  120. {
  121. }
  122. private Tensor compute_mask(Tensor inputs, Tensor mask = null)
  123. {
  124. return null;
  125. }
  126. /// <summary>
  127. /// Subclass has to override this method.
  128. /// </summary>
  129. /// <param name="inputs"></param>
  130. /// <param name="state"></param>
  131. /// <param name="is_training"></param>
  132. /// <returns></returns>
  133. protected virtual Tensors Call(Tensors inputs, Tensor state = null, bool? training = null)
  134. {
  135. return inputs;
  136. }
  137. protected virtual string _name_scope()
  138. {
  139. return Name;
  140. }
  141. protected void MaybeBuild(Tensors inputs)
  142. {
  143. // Check input assumptions set before layer building, e.g. input rank.
  144. if (built)
  145. return;
  146. if (DType == TF_DataType.DtInvalid)
  147. args.DType = inputs.dtype;
  148. tf.init_scope();
  149. bool need_restore_mode = false;
  150. if (!inputs.IsCreatedInGraphMode || tf.Context.is_build_function())
  151. {
  152. need_restore_mode = true;
  153. tf.Context.eager_mode(isFunc: tf.Context.is_build_function());
  154. }
  155. build(inputs);
  156. if (need_restore_mode)
  157. tf.Context.restore_mode();
  158. built = true;
  159. }
  160. protected virtual void build(Tensors inputs)
  161. {
  162. built = true;
  163. }
  164. protected virtual void add_loss(Func<Tensor> losses)
  165. {
  166. }
  167. /// <summary>
  168. /// Create lambdas which compute regularization losses.
  169. /// </summary>
  170. /// <param name="name"></param>
  171. /// <param name="variable"></param>
  172. /// <param name="regularizer"></param>
  173. void _handle_weight_regularization(string name, IVariableV1 variable, IRegularizer regularizer)
  174. {
  175. add_loss(() => regularizer.Apply(new RegularizerArgs
  176. {
  177. }));
  178. }
  179. /*protected virtual void add_update(Tensor[] updates, bool inputs = false)
  180. {
  181. var updates_op = updates.Select(x => x.op).ToArray();
  182. this.updates.AddRange(updates_op);
  183. }*/
  184. // Determine layer name (non-unique).
  185. protected virtual void _init_set_name(string name, bool zero_based = true)
  186. {
  187. base_name = name;
  188. this.name = name;
  189. if (name == null)
  190. {
  191. base_name = generic_utils.to_snake_case(this.GetType().Name);
  192. this.name = base_layer_utils.unique_layer_name(base_name, zero_based: zero_based);
  193. }
  194. }
  195. public int count_params()
  196. {
  197. if (Trainable)
  198. return layer_utils.count_params(this, weights);
  199. return 0;
  200. }
  201. List<IVariableV1> ILayer.trainable_weights
  202. {
  203. get
  204. {
  205. return trainable_weights;
  206. }
  207. }
  208. List<IVariableV1> ILayer.non_trainable_weights
  209. {
  210. get
  211. {
  212. return non_trainable_weights;
  213. }
  214. }
  215. public List<IVariableV1> weights
  216. {
  217. get
  218. {
  219. var weights = new List<IVariableV1>();
  220. weights.AddRange(trainable_weights);
  221. weights.AddRange(non_trainable_weights);
  222. return weights;
  223. }
  224. }
  225. public virtual LayerArgs get_config()
  226. => args;
  227. }
  228. }