1/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15
16#include "tensorflow/core/util/guarded_philox_random.h"
17
18#include "tensorflow/core/lib/random/random.h"
19#include "tensorflow/core/util/determinism.h"
20
21namespace tensorflow {
22
23Status GuardedPhiloxRandom::Init(OpKernelConstruction* context) {
24 // Grab seed Attrs.
25 int64_t seed, seed2;
26 auto status = context->GetAttr("seed", &seed);
27 if (!status.ok()) return status;
28 status = context->GetAttr("seed2", &seed2);
29 if (!status.ok()) return status;
30 if (seed == 0 && seed2 == 0 && OpDeterminismRequired()) {
31 return errors::InvalidArgument(
32 "When determinism is enabled, random ops "
33 "must have a seed specified.");
34 }
35
36 // Initialize with the given seeds
37 Init(seed, seed2);
38 return OkStatus();
39}
40
41void GuardedPhiloxRandom::Init(int64_t seed, int64_t seed2) {
42 CHECK(!initialized_);
43 if (seed == 0 && seed2 == 0) {
44 // If both seeds are unspecified, use completely random seeds.
45 seed = random::New64();
46 seed2 = random::New64();
47 }
48 mutex_lock lock(mu_);
49 generator_ = random::PhiloxRandom(seed, seed2);
50 initialized_ = true;
51}
52
53void GuardedPhiloxRandom::Init(random::PhiloxRandom::ResultType counter,
54 random::PhiloxRandom::Key key) {
55 CHECK(!initialized_);
56 mutex_lock lock(mu_);
57 generator_ = random::PhiloxRandom(counter, key);
58 initialized_ = true;
59}
60
61random::PhiloxRandom GuardedPhiloxRandom::ReserveSamples128(int64_t samples) {
62 CHECK(initialized_);
63 mutex_lock lock(mu_);
64 auto local = generator_;
65 generator_.Skip(samples);
66 return local;
67}
68
69} // namespace tensorflow
70