1 /* Copyright 2021 The TensorFlow Authors. All Rights Reserved. 2 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 7 http://www.apache.org/licenses/LICENSE-2.0 8 9 Unless required by applicable law or agreed to in writing, software 10 distributed under the License is distributed on an "AS IS" BASIS, 11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 See the License for the specific language governing permissions and 13 limitations under the License. 14 ==============================================================================*/ 15 16 #include "tensorflow/core/util/determinism.h" 17 18 #include "absl/strings/string_view.h" 19 #include "tensorflow/core/platform/mutex.h" 20 #include "tensorflow/core/util/env_var.h" 21 22 namespace tensorflow { 23 24 namespace { 25 26 class DeterminismState { 27 public: DeterminismState(absl::string_view env_var)28 explicit DeterminismState(absl::string_view env_var) : env_var_(env_var) {} Required()29 bool Required() { 30 mutex_lock l(*mutex_); 31 32 if (state_ == Value::NOT_SET) { 33 bool env_var_set = false; 34 TF_CHECK_OK(tensorflow::ReadBoolFromEnvVar(env_var_, 35 /*default_val=*/false, 36 &env_var_set)); 37 state_ = env_var_set ? Value::ENABLED : Value::DISABLED; 38 } 39 40 return state_ == Value::ENABLED; 41 } Enable(bool enabled)42 void Enable(bool enabled) { 43 mutex_lock l(*mutex_); 44 state_ = enabled ? Value::ENABLED : Value::DISABLED; 45 } 46 47 private: 48 absl::string_view env_var_; 49 enum class Value { DISABLED, ENABLED, NOT_SET }; 50 mutex* mutex_ = new mutex; 51 Value state_ = Value::NOT_SET; 52 }; 53 54 } // namespace 55 56 DeterminismState OpDeterminismState = DeterminismState("TF_DETERMINISTIC_OPS"); 57 DeterminismState OpOrderDeterminismState = 58 DeterminismState("TF_DETERMINISTIC_ORDER"); 59 OpDeterminismRequired()60bool OpDeterminismRequired() { return OpDeterminismState.Required(); } EnableOpDeterminism(bool enabled)61void EnableOpDeterminism(bool enabled) { OpDeterminismState.Enable(enabled); } OpOrderDeterminismRequired()62bool OpOrderDeterminismRequired() { return OpOrderDeterminismState.Required(); } 63 64 } // namespace tensorflow 65