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.

Context.cs 5.9 kB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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.Diagnostics;
  15. using System.Linq;
  16. using Tensorflow.Eager;
  17. using static Tensorflow.Binding;
  18. using Google.Protobuf;
  19. using Tensorflow.Util;
  20. namespace Tensorflow.Contexts
  21. {
  22. /// <summary>
  23. /// Environment in which eager operations execute.
  24. /// </summary>
  25. public sealed partial class Context : IDisposable
  26. {
  27. public const int GRAPH_MODE = 0;
  28. public const int EAGER_MODE = 1;
  29. int defaultExecutionMode = EAGER_MODE;
  30. public string DeviceName { get; set; } = "";
  31. public string ScopeName { get; set; } = "";
  32. bool initialized = false;
  33. ContextSwitchStack context_switches;
  34. public FunctionCallOptions FunctionCallOptions { get; }
  35. SafeContextHandle _handle;
  36. public SafeContextHandle Handle => _handle;
  37. int? _seed;
  38. Random _rng;
  39. public Context()
  40. {
  41. _device_policy = ContextDevicePlacementPolicy.DEVICE_PLACEMENT_SILENT;
  42. context_switches = new ContextSwitchStack(defaultExecutionMode == EAGER_MODE, false);
  43. initialized = false;
  44. FunctionCallOptions = new FunctionCallOptions();
  45. }
  46. /// <summary>
  47. /// Initialize handle and devices if not already done so.
  48. /// </summary>
  49. public void ensure_initialized()
  50. {
  51. if (initialized)
  52. return;
  53. Config = MergeConfig();
  54. FunctionCallOptions.Config = Config;
  55. var config_str = Config.ToByteArray();
  56. using var opts = new ContextOptions();
  57. using var status = new Status();
  58. c_api.TFE_ContextOptionsSetConfig(opts.Handle, config_str, (ulong)config_str.Length, status.Handle);
  59. status.Check(true);
  60. c_api.TFE_ContextOptionsSetDevicePlacementPolicy(opts.Handle, _device_policy);
  61. _handle = c_api.TFE_NewContext(opts.Handle, status.Handle);
  62. status.Check(true);
  63. initialized = true;
  64. }
  65. public void set_global_seed(int? seed)
  66. {
  67. _seed = seed;
  68. if (seed.HasValue)
  69. _rng = new Random(seed.Value);
  70. else
  71. _rng = null;
  72. // Also clear the kernel cache, to reset any existing seeds
  73. if (_handle != null)
  74. c_api.TFE_ContextClearCaches(_handle);
  75. }
  76. public int? global_seed()
  77. => _seed;
  78. public int? internal_operation_seed()
  79. => _rng?.Next(0, int.MaxValue);
  80. public void start_step()
  81. => c_api.TFE_ContextStartStep(_handle);
  82. public void end_step()
  83. => c_api.TFE_ContextEndStep(_handle);
  84. /// <summary>
  85. /// Checks whether the current thread has eager execution enabled.
  86. /// </summary>
  87. /// <returns></returns>
  88. [DebuggerStepThrough]
  89. public bool executing_eagerly()
  90. {
  91. if(context_switches.Count() == 0)
  92. tf.enable_eager_execution();
  93. return context_switches.Current().EagerMode;
  94. }
  95. public bool is_build_function()
  96. => context_switches.Current().IsBuildingFunction;
  97. public string shared_name(string name = null)
  98. => !string.IsNullOrEmpty(name) || !executing_eagerly() ?
  99. name :
  100. "cd2c89b7-88b7-44c8-ad83-06c2a9158347";
  101. public void graph_mode(bool isFunc = false)
  102. => context_switches.Push(false, isFunc);
  103. public void eager_mode(bool isFunc = false)
  104. => context_switches.Push(true, isFunc);
  105. public bool switched_to_graph(params object[] args)
  106. {
  107. var switching_to_graph = has_graph_arg(args) && tf.Context.executing_eagerly();
  108. if (switching_to_graph)
  109. tf.Context.graph_mode(tf.Context.is_build_function());
  110. return switching_to_graph;
  111. }
  112. public bool has_graph_arg(params object[] args)
  113. {
  114. var flatten_args = nest.flatten<object>(args);
  115. /*if (flatten_args.Count(x => x.GetType().IsValueType) == flatten_args.Count())
  116. return tf.Context.executing_eagerly() == false*/
  117. bool has_graph_arg = !tf.Context.executing_eagerly();
  118. foreach (var el in flatten_args)
  119. {
  120. if (el is Tensor tensor && !tensor.IsEagerTensor)
  121. {
  122. has_graph_arg = true;
  123. break;
  124. }
  125. }
  126. return has_graph_arg;
  127. }
  128. public void restore_mode()
  129. {
  130. context_switches.Pop();
  131. tf.get_default_graph();
  132. }
  133. public void reset_context()
  134. {
  135. ops.reset_uid();
  136. // tf.defaultSession = null;
  137. ops.reset_default_graph();
  138. context_switches.Clear();
  139. tf.Context.ensure_initialized();
  140. if (_handle != null)
  141. c_api.TFE_ContextClearCaches(_handle);
  142. }
  143. public void Dispose()
  144. => _handle.Dispose();
  145. }
  146. }