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.

Sequential.cs 7.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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.Linq;
  15. using System.Collections.Generic;
  16. using Tensorflow.Keras.ArgsDefinition;
  17. using Tensorflow.Keras.Layers;
  18. using Tensorflow.Keras.Utils;
  19. using static Tensorflow.KerasApi;
  20. namespace Tensorflow.Keras.Engine
  21. {
  22. /// <summary>
  23. /// `Sequential` groups a linear stack of layers into a `tf.keras.Model`.
  24. /// `Sequential` provides training and inference features on this model.
  25. /// </summary>
  26. public class Sequential : Functional
  27. {
  28. SequentialArgs args;
  29. bool _compute_output_and_mask_jointly;
  30. bool _auto_track_sub_layers;
  31. Shape _inferred_input_shape;
  32. bool _has_explicit_input_shape;
  33. bool _graph_initialized;
  34. public Shape output_shape => outputs[0].shape;
  35. List<INode> _created_nodes;
  36. public Sequential(SequentialArgs args)
  37. : base(args.Inputs, args.Outputs, name: args.Name)
  38. {
  39. this.args = args;
  40. // SupportsMasking = true;
  41. _compute_output_and_mask_jointly = true;
  42. _auto_track_sub_layers = false;
  43. _has_explicit_input_shape = false;
  44. _is_graph_network = false;
  45. _created_nodes = new List<INode>();
  46. // Add to the model any layers passed to the constructor.
  47. if (args.Layers is not null)
  48. {
  49. InitLayers(args.Layers);
  50. }
  51. }
  52. public void InitLayers(IEnumerable<ILayer> layers)
  53. {
  54. foreach(var layer in layers)
  55. {
  56. add(layer);
  57. }
  58. }
  59. public void add(Tensor tensor)
  60. {
  61. var layer = tensor.KerasHistory.Layer;
  62. add(layer);
  63. }
  64. /// <summary>
  65. /// Adds a layer instance on top of the layer stack.
  66. /// </summary>
  67. /// <param name="layer"></param>
  68. public void add(ILayer layer)
  69. {
  70. built = false;
  71. var set_inputs = false;
  72. if (_self_tracked_trackables.Count == 0)
  73. {
  74. if (layer is InputLayer)
  75. {
  76. set_inputs = true;
  77. }
  78. else
  79. {
  80. if (layer.BatchInputShape != null)
  81. {
  82. // Instantiate an input layer.
  83. var x = keras.Input(
  84. batch_input_shape: layer.BatchInputShape,
  85. dtype: layer.DType,
  86. name: layer.Name + "_input");
  87. // This will build the current layer
  88. // and create the node connecting the current layer
  89. // to the input layer we just created.
  90. layer.Apply(x);
  91. set_inputs = true;
  92. }
  93. }
  94. if (set_inputs)
  95. {
  96. // If an input layer (placeholder) is available.
  97. outputs = layer.InboundNodes.Last().Outputs;
  98. inputs = layer_utils.get_source_inputs(outputs[0]);
  99. built = true;
  100. _has_explicit_input_shape = true;
  101. }
  102. }
  103. else if (outputs != null)
  104. {
  105. // If the model is being built continuously on top of an input layer:
  106. // refresh its output.
  107. outputs = layer.Apply(outputs);
  108. built = true;
  109. }
  110. if (set_inputs || _is_graph_network)
  111. {
  112. _init_graph_network(inputs, outputs);
  113. _is_graph_network = true;
  114. }
  115. else
  116. {
  117. _self_tracked_trackables.add(layer);
  118. }
  119. }
  120. protected override Tensors Call(Tensors inputs, Tensor state = null, bool? training = null)
  121. {
  122. if (!_has_explicit_input_shape)
  123. {
  124. _build_graph_network_for_inferred_shape(inputs.shape, inputs.dtype);
  125. }
  126. if(_graph_initialized)
  127. {
  128. if (!built)
  129. _init_graph_network(this.inputs, outputs);
  130. return base.Call(inputs, state, training);
  131. }
  132. return base.Call(inputs, state, training);
  133. }
  134. void _build_graph_network_for_inferred_shape(Shape input_shape, TF_DataType input_dtype)
  135. {
  136. if (_inferred_input_shape == input_shape)
  137. return;
  138. ops.init_scope();
  139. var inputs = keras.Input(batch_input_shape: input_shape,
  140. dtype: input_dtype,
  141. name: _self_tracked_trackables[0].Name.EndsWith("_input") ? _self_tracked_trackables[0].Name : $"{_self_tracked_trackables[0].Name}_input");
  142. Tensors layer_input = inputs;
  143. Tensors layer_output = null;
  144. Tensors outputs = null;
  145. List<INode> created_nodes = new List<INode>();
  146. foreach (var layer in args.Layers)
  147. {
  148. clear_previously_created_nodes(layer, _created_nodes);
  149. layer_output = layer.Apply(layer_input);
  150. // Keep track of nodes just created above
  151. track_nodes_created_by_last_call(layer, created_nodes);
  152. layer_input = layer_output;
  153. outputs = layer_output;
  154. }
  155. _created_nodes = created_nodes;
  156. _init_graph_network(inputs, outputs);
  157. _graph_initialized = true;
  158. _inferred_input_shape = input_shape;
  159. }
  160. void clear_previously_created_nodes(ILayer layer, List<INode> created_nodes)
  161. {
  162. foreach(var node in layer.InboundNodes)
  163. {
  164. foreach(var prev_layer in node.InboundLayers)
  165. {
  166. var outNodes = prev_layer.OutboundNodes.Where(x => !created_nodes.Contains(x)).ToArray();
  167. prev_layer.OutboundNodes.Clear();
  168. prev_layer.OutboundNodes.AddRange(outNodes);
  169. }
  170. }
  171. var inNodes = layer.InboundNodes.Where(x => !created_nodes.Contains(x)).ToArray();
  172. layer.InboundNodes.Clear();
  173. layer.InboundNodes.AddRange(inNodes);
  174. }
  175. void track_nodes_created_by_last_call(ILayer layer, List<INode> created_nodes)
  176. {
  177. var node = layer.InboundNodes.Last();
  178. created_nodes.Add(node);
  179. foreach(var prev_layer in node.InboundLayers)
  180. {
  181. created_nodes.add(prev_layer.OutboundNodes.Last());
  182. }
  183. }
  184. public override List<ILayer> Layers
  185. => base.Layers.Where(x => x is not InputLayer).ToList();
  186. }
  187. }