1 /* Copyright 2016 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 #ifndef TENSORFLOW_CORE_LIB_MONITORING_SAMPLER_H_
17 #define TENSORFLOW_CORE_LIB_MONITORING_SAMPLER_H_
18
19 // We replace this implementation with a null implementation for mobile
20 // platforms.
21 #include "tensorflow/core/platform/platform.h"
22 #ifdef IS_MOBILE_PLATFORM
23 #include "tensorflow/core/lib/monitoring/mobile_sampler.h"
24 #else
25
26 #include <float.h>
27 #include <map>
28
29 #include "tensorflow/core/framework/summary.pb.h"
30 #include "tensorflow/core/lib/histogram/histogram.h"
31 #include "tensorflow/core/lib/monitoring/collection_registry.h"
32 #include "tensorflow/core/lib/monitoring/metric_def.h"
33 #include "tensorflow/core/platform/macros.h"
34 #include "tensorflow/core/platform/mutex.h"
35 #include "tensorflow/core/platform/thread_annotations.h"
36
37 namespace tensorflow {
38 namespace monitoring {
39
40 // SamplerCell stores each value of an Sampler.
41 //
42 // A cell can be passed off to a module which may repeatedly update it without
43 // needing further map-indexing computations. This improves both encapsulation
44 // (separate modules can own a cell each, without needing to know about the map
45 // to which both cells belong) and performance (since map indexing and
46 // associated locking are both avoided).
47 //
48 // This class is thread-safe.
49 class SamplerCell {
50 public:
SamplerCell(const std::vector<double> & bucket_limits)51 SamplerCell(const std::vector<double>& bucket_limits)
52 : histogram_(bucket_limits) {}
53
~SamplerCell()54 ~SamplerCell() {}
55
56 // Atomically adds a sample.
57 void Add(double sample);
58
59 // Returns the current histogram value as a proto.
60 HistogramProto value() const;
61
62 private:
63 histogram::ThreadSafeHistogram histogram_;
64
65 TF_DISALLOW_COPY_AND_ASSIGN(SamplerCell);
66 };
67
68 // Bucketing strategies for the samplers.
69 //
70 // We automatically add -DBL_MAX and DBL_MAX to the ranges, so that no sample
71 // goes out of bounds.
72 //
73 // WARNING: If you are changing the interface here, please do change the same in
74 // mobile_sampler.h.
75 class Buckets {
76 public:
77 virtual ~Buckets() = default;
78
79 // Sets up buckets of the form:
80 // [-DBL_MAX, ..., scale * growth^i,
81 // scale * growth_factor^(i + 1), ..., DBL_MAX].
82 //
83 // So for powers of 2 with a bucket count of 10, you would say (1, 2, 10)
84 static std::unique_ptr<Buckets> Exponential(double scale,
85 double growth_factor,
86 int bucket_count);
87
88 // Sets up buckets of the form:
89 // [-DBL_MAX, ..., bucket_limits[i], bucket_limits[i + 1], ..., DBL_MAX].
90 static std::unique_ptr<Buckets> Explicit(
91 std::initializer_list<double> bucket_limits);
92
93 virtual const std::vector<double>& explicit_bounds() const = 0;
94 };
95
96 // A stateful class for updating a cumulative histogram metric.
97 //
98 // This class encapsulates a set of histograms (or a single histogram for a
99 // label-less metric) configured with a list of increasing bucket boundaries.
100 // Each histogram is identified by a tuple of labels. The class allows the
101 // user to add a sample to each histogram value.
102 //
103 // Sampler allocates storage and maintains a cell for each value. You can
104 // retrieve an individual cell using a label-tuple and update it separately.
105 // This improves performance since operations related to retrieval, like
106 // map-indexing and locking, are avoided.
107 //
108 // This class is thread-safe.
109 template <int NumLabels>
110 class Sampler {
111 public:
~Sampler()112 ~Sampler() {
113 // Deleted here, before the metric_def is destroyed.
114 registration_handle_.reset();
115 }
116
117 // Creates the metric based on the metric-definition arguments and buckets.
118 //
119 // Example;
120 // auto* sampler_with_label = Sampler<1>::New({"/tensorflow/sampler",
121 // "Tensorflow sampler", "MyLabelName"}, {10.0, 20.0, 30.0});
122 static Sampler* New(const MetricDef<MetricKind::kCumulative, HistogramProto,
123 NumLabels>& metric_def,
124 std::unique_ptr<Buckets> buckets);
125
126 // Retrieves the cell for the specified labels, creating it on demand if
127 // not already present.
128 template <typename... Labels>
129 SamplerCell* GetCell(const Labels&... labels) LOCKS_EXCLUDED(mu_);
130
131 private:
132 friend class SamplerCell;
133
Sampler(const MetricDef<MetricKind::kCumulative,HistogramProto,NumLabels> & metric_def,std::unique_ptr<Buckets> buckets)134 Sampler(const MetricDef<MetricKind::kCumulative, HistogramProto, NumLabels>&
135 metric_def,
136 std::unique_ptr<Buckets> buckets)
137 : metric_def_(metric_def),
138 buckets_(std::move(buckets)),
139 registration_handle_(CollectionRegistry::Default()->Register(
140 &metric_def_, [&](MetricCollectorGetter getter) {
141 auto metric_collector = getter.Get(&metric_def_);
142
143 mutex_lock l(mu_);
144 for (const auto& cell : cells_) {
145 metric_collector.CollectValue(cell.first, cell.second.value());
146 }
147 })) {}
148
149 mutable mutex mu_;
150
151 // The metric definition. This will be used to identify the metric when we
152 // register it for collection.
153 const MetricDef<MetricKind::kCumulative, HistogramProto, NumLabels>
154 metric_def_;
155
156 // Bucket limits for the histograms in the cells.
157 std::unique_ptr<Buckets> buckets_;
158
159 // Registration handle with the CollectionRegistry.
160 std::unique_ptr<CollectionRegistry::RegistrationHandle> registration_handle_;
161
162 using LabelArray = std::array<string, NumLabels>;
163 // we need a container here that guarantees pointer stability of the value,
164 // namely, the pointer of the value should remain valid even after more cells
165 // are inserted.
166 std::map<LabelArray, SamplerCell> cells_ GUARDED_BY(mu_);
167
168 TF_DISALLOW_COPY_AND_ASSIGN(Sampler);
169 };
170
171 ////
172 // Implementation details follow. API readers may skip.
173 ////
174
Add(const double sample)175 inline void SamplerCell::Add(const double sample) { histogram_.Add(sample); }
176
value()177 inline HistogramProto SamplerCell::value() const {
178 HistogramProto pb;
179 histogram_.EncodeToProto(&pb, true /* preserve_zero_buckets */);
180 return pb;
181 }
182
183 template <int NumLabels>
New(const MetricDef<MetricKind::kCumulative,HistogramProto,NumLabels> & metric_def,std::unique_ptr<Buckets> buckets)184 Sampler<NumLabels>* Sampler<NumLabels>::New(
185 const MetricDef<MetricKind::kCumulative, HistogramProto, NumLabels>&
186 metric_def,
187 std::unique_ptr<Buckets> buckets) {
188 return new Sampler<NumLabels>(metric_def, std::move(buckets));
189 }
190
191 template <int NumLabels>
192 template <typename... Labels>
GetCell(const Labels &...labels)193 SamplerCell* Sampler<NumLabels>::GetCell(const Labels&... labels)
194 LOCKS_EXCLUDED(mu_) {
195 // Provides a more informative error message than the one during array
196 // construction below.
197 static_assert(sizeof...(Labels) == NumLabels,
198 "Mismatch between Sampler<NumLabels> and number of labels "
199 "provided in GetCell(...).");
200
201 const LabelArray& label_array = {{labels...}};
202 mutex_lock l(mu_);
203 const auto found_it = cells_.find(label_array);
204 if (found_it != cells_.end()) {
205 return &(found_it->second);
206 }
207 return &(cells_
208 .emplace(std::piecewise_construct,
209 std::forward_as_tuple(label_array),
210 std::forward_as_tuple(buckets_->explicit_bounds()))
211 .first->second);
212 }
213
214 } // namespace monitoring
215 } // namespace tensorflow
216
217 #endif // IS_MOBILE_PLATFORM
218 #endif // TENSORFLOW_CORE_LIB_MONITORING_SAMPLER_H_
219