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/tsl/util/determinism.h" |
17 | |
18 | #include "absl/strings/string_view.h" |
19 | #include "tensorflow/tsl/platform/mutex.h" |
20 | #include "tensorflow/tsl/util/env_var.h" |
21 | |
22 | namespace tsl { |
23 | |
24 | namespace { |
25 | |
26 | class DeterminismState { |
27 | public: |
28 | explicit DeterminismState(absl::string_view env_var) : env_var_(env_var) {} |
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(tsl::ReadBoolFromEnvVar(env_var_, |
35 | /*default_val=*/false, &env_var_set)); |
36 | state_ = env_var_set ? Value::ENABLED : Value::DISABLED; |
37 | } |
38 | |
39 | return state_ == Value::ENABLED; |
40 | } |
41 | void Enable(bool enabled) { |
42 | mutex_lock l(*mutex_); |
43 | state_ = enabled ? Value::ENABLED : Value::DISABLED; |
44 | } |
45 | |
46 | private: |
47 | absl::string_view env_var_; |
48 | enum class Value { DISABLED, ENABLED, NOT_SET }; |
49 | mutex* mutex_ = new mutex; |
50 | Value state_ = Value::NOT_SET; |
51 | }; |
52 | |
53 | } // namespace |
54 | |
55 | DeterminismState OpDeterminismState = DeterminismState("TF_DETERMINISTIC_OPS"); |
56 | DeterminismState OpOrderDeterminismState = |
57 | DeterminismState("TF_DETERMINISTIC_ORDER"); |
58 | |
59 | bool OpDeterminismRequired() { return OpDeterminismState.Required(); } |
60 | void EnableOpDeterminism(bool enabled) { OpDeterminismState.Enable(enabled); } |
61 | bool OpOrderDeterminismRequired() { return OpOrderDeterminismState.Required(); } |
62 | |
63 | } // namespace tsl |
64 |