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

4 years ago
4 years ago
6 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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 Newtonsoft.Json.Linq;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Linq;
  17. using System.Threading;
  18. using Tensorflow.Eager;
  19. using Tensorflow.Keras.ArgsDefinition;
  20. using Tensorflow.Keras.Metrics;
  21. using Tensorflow.Keras.Saving;
  22. using Tensorflow.Keras.Utils;
  23. using Tensorflow.NumPy;
  24. using Tensorflow.Train;
  25. using Tensorflow.Training;
  26. using Tensorflow.Training.Saving.SavedModel;
  27. using Tensorflow.Util;
  28. using static Tensorflow.Binding;
  29. using Tensorflow.Framework;
  30. using Tensorflow.Sessions;
  31. using Tensorflow.Common.Types;
  32. namespace Tensorflow.Keras.Engine
  33. {
  34. /// <summary>
  35. /// Base layer class.
  36. /// A layer is a class implementing common neural networks operations, such
  37. /// as convolution, batch norm, etc. These operations require managing weights,
  38. /// losses, updates, and inter-layer connectivity.
  39. /// </summary>
  40. public abstract partial class Layer : AutoTrackable, ILayer
  41. {
  42. /// <summary>
  43. /// Arguments initialize layer.
  44. /// </summary>
  45. internal LayerArgs args;
  46. /// <summary>
  47. /// Indicates whether `build` needs to be called upon layer call, to create
  48. /// the layer's weights.
  49. /// </summary>
  50. protected bool built;
  51. public bool Built
  52. {
  53. get
  54. {
  55. return built;
  56. }
  57. internal set
  58. {
  59. built = value;
  60. }
  61. }
  62. public bool Trainable => args.Trainable;
  63. public TF_DataType DType => args.DType;
  64. public bool AutoCast => args.Autocast;
  65. public IRegularizer ActivityRegularizer => args.ActivityRegularizer;
  66. /// <summary>
  67. /// A stateful layer is a layer whose updates are run during inference too,
  68. /// for instance stateful RNNs.
  69. /// </summary>
  70. protected bool stateful;
  71. /// <summary>
  72. /// Provides information about which inputs are compatible with the layer.
  73. /// </summary>
  74. protected InputSpec inputSpec;
  75. public InputSpec InputSpec => inputSpec;
  76. bool dynamic = true;
  77. public bool SupportsMasking { get; set; }
  78. protected List<IVariableV1> _trainable_weights;
  79. public virtual List<IVariableV1> TrainableVariables => TrainableWeights;
  80. protected List<IVariableV1> _non_trainable_weights;
  81. public List<IVariableV1> NonTrainableVariables => NonTrainableWeights;
  82. public List<IVariableV1> Variables => Weights;
  83. public virtual List<IVariableV1> TrainableWeights
  84. {
  85. get
  86. {
  87. if (!this.Trainable)
  88. {
  89. return new List<IVariableV1>();
  90. }
  91. var children_weights = _gather_children_variables(true);
  92. return children_weights.Concat(_trainable_weights).Distinct().ToList();
  93. }
  94. }
  95. public virtual List<IVariableV1> NonTrainableWeights
  96. {
  97. get
  98. {
  99. if (!this.Trainable)
  100. {
  101. var children_weights = _gather_children_variables(true, true);
  102. return children_weights.Concat(_trainable_weights).Concat(_non_trainable_weights).Distinct().ToList();
  103. }
  104. else
  105. {
  106. var children_weights = _gather_children_variables(include_non_trainable: true);
  107. return children_weights.Concat(_non_trainable_weights).Distinct().ToList();
  108. }
  109. }
  110. }
  111. public virtual List<IVariableV1> Weights
  112. {
  113. get
  114. {
  115. return TrainableWeights.Concat(NonTrainableWeights).ToList();
  116. }
  117. set
  118. {
  119. if (Weights.Count() != value.Count()) throw new ValueError(
  120. $"You called `set_weights` on layer \"{this.name}\"" +
  121. $"with a weight list of length {len(value)}, but the layer was " +
  122. $"expecting {len(Weights)} weights.");
  123. foreach (var (this_w, v_w) in zip(Weights, value))
  124. this_w.assign(v_w, read_value: true);
  125. }
  126. }
  127. public virtual void set_weights(IEnumerable<NDArray> weights)
  128. {
  129. if (Weights.Count() != weights.Count()) throw new ValueError(
  130. $"You called `set_weights` on layer \"{this.name}\"" +
  131. $"with a weight list of length {len(weights)}, but the layer was " +
  132. $"expecting {len(Weights)} weights.");
  133. // check if the shapes are compatible
  134. var weight_index = 0;
  135. foreach(var w in weights)
  136. {
  137. if (!Weights[weight_index].AsTensor().is_compatible_with(w))
  138. {
  139. throw new ValueError($"Layer weight shape {w.shape} not compatible with provided weight shape {Weights[weight_index].shape}");
  140. }
  141. weight_index++;
  142. }
  143. if (tf.executing_eagerly())
  144. {
  145. foreach (var (this_w, v_w) in zip(Weights, weights))
  146. this_w.assign(v_w, read_value: true);
  147. }
  148. else
  149. {
  150. // TODO(Wanglongzhi2001):seems like there exist some bug in graph mode when define model, so uncomment the following when it fixed.
  151. //Tensors assign_ops = new Tensors();
  152. //var feed_dict = new FeedDict();
  153. //Graph g = tf.Graph().as_default();
  154. //foreach (var (this_w, v_w) in zip(Weights, weights))
  155. //{
  156. // var tf_dtype = this_w.dtype;
  157. // var placeholder_shape = v_w.shape;
  158. // var assign_placeholder = tf.placeholder(tf_dtype, placeholder_shape);
  159. // var assign_op = this_w.assign(assign_placeholder);
  160. // assign_ops.Add(assign_op);
  161. // feed_dict.Add(assign_placeholder, v_w);
  162. //}
  163. //var sess = tf.Session().as_default();
  164. //sess.run(assign_ops, feed_dict);
  165. //g.Exit();
  166. }
  167. }
  168. public List<NDArray> get_weights()
  169. {
  170. List<NDArray > weights = new List<NDArray>();
  171. weights.AddRange(Weights.ConvertAll(x => x.numpy()));
  172. return weights;
  173. }
  174. protected int id;
  175. public int Id => id;
  176. protected string name;
  177. protected string base_name;
  178. public string Name
  179. {
  180. get
  181. {
  182. return name;
  183. }
  184. set
  185. {
  186. name = value;
  187. }
  188. }
  189. protected bool computePreviousMask;
  190. protected List<Operation> updates;
  191. public KerasShapesWrapper BatchInputShape => args.BatchInputShape;
  192. protected KerasShapesWrapper _buildInputShape = null;
  193. public KerasShapesWrapper BuildInputShape => _buildInputShape;
  194. List<INode> inboundNodes;
  195. public List<INode> InboundNodes => inboundNodes;
  196. List<INode> outboundNodes;
  197. public List<INode> OutboundNodes => outboundNodes;
  198. public Dictionary<string, object> SerializedAttributes { get; set; }
  199. ThreadLocal<CallContext> callContext = new ThreadLocal<CallContext>();
  200. public CallContext CallContext => callContext.Value;
  201. public Tensor[] input
  202. {
  203. get
  204. {
  205. if(inboundNodes is not null && inboundNodes.Count > 0)
  206. {
  207. return inboundNodes[0].input_tensors;
  208. }
  209. return null;
  210. }
  211. }
  212. public Dictionary<int, List<INode>> NodesByDepth { get; set; }
  213. public Shape OutputShape
  214. {
  215. get
  216. {
  217. if(inboundNodes is not null && inboundNodes.Count > 0)
  218. {
  219. return inboundNodes[0].Outputs.shape;
  220. }
  221. return null;
  222. }
  223. }
  224. protected List<ILayer> _self_tracked_trackables;
  225. /// <summary>
  226. /// If this value is set, the behavior of layer call will be changed to directly calling this function.
  227. /// </summary>
  228. public Func<Tensors, Tensors>? ReplacedCall { get; set; } = null;
  229. public StateSizeWrapper state_size => throw new NotImplementedException();
  230. public int output_size => throw new NotImplementedException();
  231. public Layer(LayerArgs args)
  232. {
  233. Initialize(args);
  234. }
  235. internal virtual void Initialize(LayerArgs args)
  236. {
  237. this.args = args;
  238. // A stateful layer is a layer whose updates are run during inference too,
  239. // for instance stateful RNNs.
  240. stateful = false;
  241. // Indicates whether `build` needs to be called upon layer call, to create
  242. // the layer's weights.
  243. built = false;
  244. SupportsMasking = false;
  245. id = ops.uid_layer();
  246. _init_set_name(args.Name);
  247. _trainable_weights = new List<IVariableV1>();
  248. _non_trainable_weights = new List<IVariableV1>();
  249. computePreviousMask = false;
  250. updates = new List<Operation>();
  251. _self_tracked_trackables = new List<ILayer>();
  252. inboundNodes = new List<INode>();
  253. outboundNodes = new List<INode>();
  254. // Manage input shape information if passed.
  255. if (args.BatchInputShape == null && args.InputShape != null)
  256. {
  257. args.BatchInputShape = new KerasShapesWrapper(new long[] { args.BatchSize }.Concat(args.InputShape.dims).ToArray());
  258. }
  259. }
  260. bool _in_functional_construction_mode(Tensors inputs)
  261. {
  262. return tf.Context.executing_eagerly()
  263. && inputs.Count(x => x is not EagerTensor && x is not NDArray) == inputs.Count() || _enforce_layer_construction;
  264. }
  265. public void SetConnectivityMetadata(Tensors inputs, Tensors outputs)
  266. => _set_connectivity_metadata_(inputs, outputs);
  267. private void _set_connectivity_metadata_(Tensors inputs, Tensors outputs)
  268. {
  269. var node = new Node(new NodeArgs
  270. {
  271. InputTensors = inputs,
  272. Outputs = outputs
  273. });
  274. node.Connect(this);
  275. }
  276. private void _handle_activity_regularization(Tensors inputs, Tensors outputs)
  277. {
  278. //if(_activity_regularizer != null)
  279. {
  280. }
  281. }
  282. private void _set_mask_metadata(Tensors inputs, Tensors outputs, Tensors previous_mask)
  283. {
  284. }
  285. private Tensor compute_mask(Tensor inputs, Tensor mask = null)
  286. {
  287. return null;
  288. }
  289. /// <summary>
  290. /// Subclass has to override this method.
  291. /// </summary>
  292. /// <param name="inputs"></param>
  293. /// <param name="state"></param>
  294. /// <param name="training"></param>
  295. /// <returns></returns>
  296. <<<<<<< HEAD
  297. <<<<<<< HEAD
  298. protected virtual Tensors Call(Tensors inputs, Tensors state = null, bool? training = null, IOptionalArgs? optional_args = null)
  299. =======
  300. protected virtual Tensors Call(Tensors inputs, Tensor mask = null, bool? training = null, Tensors initial_state = null, Tensors constants = null)
  301. >>>>>>> master
  302. =======
  303. protected virtual Tensors Call(Tensors inputs, Tensors state = null, bool? training = null, IOptionalArgs? optional_args = null)
  304. >>>>>>> 90a65d7d98b92f26574ac32392ed802a57d4d2c8
  305. {
  306. if (ReplacedCall is not null)
  307. {
  308. return ReplacedCall(inputs);
  309. }
  310. return inputs;
  311. }
  312. protected virtual string _name_scope()
  313. {
  314. return Name;
  315. }
  316. protected void MaybeBuild(Tensors inputs)
  317. {
  318. // Check input assumptions set before layer building, e.g. input rank.
  319. if (built)
  320. return;
  321. if (DType == TF_DataType.DtInvalid)
  322. args.DType = inputs.dtype;
  323. tf.init_scope();
  324. bool need_restore_mode = false;
  325. if (inputs.Any(x => x is EagerTensor) || tf.Context.is_build_function())
  326. {
  327. need_restore_mode = true;
  328. tf.Context.eager_mode(isFunc: tf.Context.is_build_function());
  329. }
  330. build(new KerasShapesWrapper(inputs.shape));
  331. if (need_restore_mode)
  332. tf.Context.restore_mode();
  333. built = true;
  334. }
  335. public virtual void build(KerasShapesWrapper input_shape)
  336. {
  337. _buildInputShape = input_shape;
  338. built = true;
  339. }
  340. protected virtual void add_loss(Func<Tensor> losses)
  341. {
  342. }
  343. /// <summary>
  344. /// Create lambdas which compute regularization losses.
  345. /// </summary>
  346. /// <param name="name"></param>
  347. /// <param name="variable"></param>
  348. /// <param name="regularizer"></param>
  349. void _handle_weight_regularization(string name, IVariableV1 variable, IRegularizer regularizer)
  350. {
  351. add_loss(() => tf_with(ops.name_scope(name + "/Regularizer"), scope =>
  352. regularizer.Apply(new RegularizerArgs(variable.AsTensor())
  353. {
  354. })
  355. ));
  356. }
  357. /*protected virtual void add_update(Tensor[] updates, bool inputs = false)
  358. {
  359. var updates_op = updates.Select(x => x.op).ToArray();
  360. this.updates.AddRange(updates_op);
  361. }*/
  362. // Determine layer name (non-unique).
  363. protected virtual void _init_set_name(string name, bool zero_based = true)
  364. {
  365. base_name = name;
  366. this.name = name;
  367. if (name == null)
  368. {
  369. base_name = generic_utils.to_snake_case(this.GetType().Name);
  370. this.name = base_layer_utils.unique_layer_name(base_name, zero_based: zero_based);
  371. }
  372. }
  373. public int count_params()
  374. {
  375. if (Trainable)
  376. return layer_utils.count_params(this, Weights);
  377. return 0;
  378. }
  379. public virtual IKerasConfig get_config()
  380. => args;
  381. public virtual void adapt(Tensor data, int? batch_size = null, int? steps = null)
  382. {
  383. }
  384. public override void SetAttr(string name, object value)
  385. {
  386. //// TODO(Rinne): deal with "_self_setattr_tracking".
  387. //value = TrackableDataStructure.sticky_attribute_assignment(this, name, value);
  388. //foreach(var val in nest.flatten(value))
  389. //{
  390. // if(val is Metric)
  391. // {
  392. // // TODO(Rinne): deal with metrics.
  393. // }
  394. //}
  395. //// TODO(Rinne): deal with "_auto_track_sub_layers".
  396. //foreach(var val in nest.flatten(value))
  397. //{
  398. // if(val is not IVariableV1 variable)
  399. // {
  400. // continue;
  401. // }
  402. // if (variable.Trainable)
  403. // {
  404. // if (_trainable_weights.Contains(variable))
  405. // {
  406. // continue;
  407. // }
  408. // _trainable_weights.Add(variable);
  409. // }
  410. // else
  411. // {
  412. // if (_non_trainable_weights.Contains(variable))
  413. // {
  414. // continue;
  415. // }
  416. // _non_trainable_weights.Add(variable);
  417. // }
  418. // keras.backend.track_variable(variable);
  419. //}
  420. //// Directly use the implementation of `Trackable`.
  421. //var t = this.GetType();
  422. //var field_info = t.GetField(name);
  423. //if (field_info is not null)
  424. //{
  425. // field_info.SetValue(this, value);
  426. //}
  427. //else
  428. //{
  429. // CustomizedFields[name] = value;
  430. //}
  431. }
  432. Tensors ILayer.Call(Tensors inputs, Tensor mask, bool? training, Tensors initial_state, Tensors constants)
  433. {
  434. throw new NotImplementedException();
  435. }
  436. }
  437. }