This commit is contained in:
Kevin Darby committed 2019-01-02 17:04:10 -05:00
1 parent eb1b42a5e8
commit 458eb2aef1
1283 files changed
+323373

No files matched your search

@@ -0,0 +1,46 @@
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_ACTIVATION_MODE_H_
#define TENSORFLOW_CORE_UTIL_ACTIVATION_MODE_H_
// This file contains helper routines to deal with activation mode in various
// ops and kernels.
#include <string>
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/lib/core/status.h"
namespace tensorflow {
// ActivationMode: the activation function we apply to the input tensor:
enum ActivationMode {
NONE = 0,
SIGMOID = 1,
RELU = 2,
RELU6 = 3,
RELUX = 4,
TANH = 5,
BANDPASS = 6,
};
// Specialization to parse an attribute directly into a ActivationMode enum.
Status GetActivationModeFromString(const string& str_value,
ActivationMode* value);
} // end namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_ACTIVATION_MODE_H_
@@ -0,0 +1,54 @@
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_BATCH_UTIL_H_
#define TENSORFLOW_CORE_UTIL_BATCH_UTIL_H_
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/core/status.h"
namespace tensorflow {
namespace batch_util {
// Copies element into the index^th slice of parent (in the 0th dimension).
//
// NOTE(mrry): The `element` argument is taken by value. Use `std::move()`
// to move the `element` argument into this function, and the implementation
// may be able to optimize the copy to a move. This is particularly important
// for DT_STRING tensors.
Status CopyElementToSlice(Tensor element, Tensor* parent, int64 index);
// Copies the index^th slice of parent (in the 0th dimension) into element.
Status CopySliceToElement(const Tensor& parent, Tensor* element, int64 index);
// Copies the index^th slice of parent (in the 0th dimension) into element.
//
// NOTE(mrry): The implementation may be able to optimize the copy to a move.
// This is particularly important for DT_STRING tensors.
Status MaybeMoveSliceToElement(Tensor* parent, Tensor* element, int64 index);
// Zero-initializes the tensor `element` using the scalar stored in `padding`.
// Both `element` and `padding` must have matching `dtype`.
Status SetElementZero(Tensor* element, const Tensor& padding);
// Copies `element` into a (0th dimension) slice of `parent`, assuming
// the shape of `element` is strictly not larger along any axis than a
// slice.
Status CopyElementToLargerSlice(const Tensor& element, Tensor* parent,
int index);
} // namespace batch_util
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_BATCH_UTIL_H_
+135
View File
@@ -0,0 +1,135 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_BCAST_H_
#define TENSORFLOW_CORE_UTIL_BCAST_H_
#include <algorithm>
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
// BCast is a helper for broadcasting binary tensor operation.
// TensorFlow's broadcasting rule follows that of numpy (See
// http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html).
//
// The rule has the following properties:
//
// 1. suffix matching: the rule starts with the right-most
// dimension, and works towards the left-most dimension. Since
// TensorFlow is row-major, the right-most dimension (the last
// element in the shape of a tensor) is the inner-most, a.k.a.
// the fastest changing, dimension.
//
// 2. Two dimensions are compatible for broadcasting if both are the
// same or either is 1.
//
// BCast takes the shape of two tensors and computes a few vectors of
// int32 that are useful for the caller to reshape the tensors, apply
// the right broadcasts to them, compute the broadcasted operation,
// and possibly the gradients. In a nutshell, the caller is expected
// to compute the broadcasted operation as following:
//
// BCast b(x.shape(), y.shape());
// output = x.reshape(b.x_reshape()).broadcast(b.x_bcast())
// _op_
// y.reshape(b.y_reshape()).broadcast(b.y_bcast())
//
// For the gradient computation,
// grad_x = sum(grad * backprop_x(x, y), grad_x_reduce_idx)
// .reshape(x.shape())
// grad_y = sum(grad * backprop_y(x, y), grad_y_reduce_idx)
// .reshape(y.shape())
// backprop_x and backprop_y are functionals of the binary function "op",
// e.g.,
// for +, backprop_x(x, y) = backprop_y(x, y) = 1;
// for *, backprop_x(x, y) = y, backprop_y(x, y) = x;
// for /, backprop_x(x, y) = 1/y, backprop_y(x, y) = -x/y^2;
//
// The multiplication in the grad * backprop_x itself is also
// broadcasting following the same rule.
//
// TODO(zhifengc): Adds support for n-ary (n >= 2).
class BCast {
public:
// A vector of int64 representing the shape of tensor. The 0-th
// element is the outer-most dimension and the last element is the
// inner-most dimension. Note that we do not use TensorShape since
// it's more convenient to manipulate Vec directly for this module.
typedef gtl::InlinedVector<int64, 4> Vec;
// Constructs all helper shapes, following the aforementioned rules.
//
// If "fewer_dims_optimization" is set to true (the default), the
// implementation tries to reduce intermediate dimensions needed to be more
// efficient. This is transparent to the caller.
//
// If false, all intermediate shapes (except for grad_{x,y}_reduce_idx()) have
// the same number of dimensions as the larger of the two inputs.
BCast(const Vec& x, const Vec& y, const bool fewer_dims_optimization = true);
~BCast() {}
// Returns true iff two operands are compatible according to the
// broadcasting rule.
bool IsValid() const { return valid_; }
// If and only if IsValid(), the following fields can be used in
// implementing a broadcasted binary tensor operation according to
// the broadcasting rule.
const Vec& x_reshape() const { return x_reshape_; }
const Vec& x_bcast() const { return x_bcast_; }
const Vec& y_reshape() const { return y_reshape_; }
const Vec& y_bcast() const { return y_bcast_; }
const Vec& result_shape() const { return result_; }
const Vec& output_shape() const { return output_; }
const Vec& grad_x_reduce_idx() const { return grad_x_reduce_idx_; }
const Vec& grad_y_reduce_idx() const { return grad_y_reduce_idx_; }
// Static helpers.
static Vec FromShape(const TensorShape& shape);
static TensorShape ToShape(const BCast::Vec& vec);
template <int NDIMS>
static Eigen::array<Eigen::DenseIndex, NDIMS> ToIndexArray(
const BCast::Vec& vec) {
CHECK_EQ(vec.size(), NDIMS);
Eigen::array<Eigen::DenseIndex, NDIMS> ret;
for (int i = 0; i < NDIMS; ++i) ret[i] = vec[i];
return ret;
}
private:
bool valid_ = true;
Vec x_reshape_;
Vec x_bcast_;
Vec y_reshape_;
Vec y_bcast_;
Vec result_;
Vec output_;
Vec grad_x_reduce_idx_;
Vec grad_y_reduce_idx_;
static void Reverse(Vec* shape);
TF_DISALLOW_COPY_AND_ASSIGN(BCast);
};
} // end namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_BCAST_H_
@@ -0,0 +1,137 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_COMMAND_LINE_FLAGS_H
#define TENSORFLOW_CORE_UTIL_COMMAND_LINE_FLAGS_H
#include <functional>
#include <string>
#include <vector>
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
// N.B. This library is for INTERNAL use only.
//
// This is a simple command-line argument parsing module to help us handle
// parameters for C++ binaries. The recommended way of using it is with local
// variables and an initializer list of Flag objects, for example:
//
// int some_int = 10;
// bool some_switch = false;
// string some_name = "something";
// std::vector<tensorFlow::Flag> flag_list = {
// Flag("some_int", &some_int, "an integer that affects X"),
// Flag("some_switch", &some_switch, "a bool that affects Y"),
// Flag("some_name", &some_name, "a string that affects Z")
// };
// // Get usage message before ParseFlags() to capture default values.
// string usage = Flag::Usage(argv[0], flag_list);
// bool parsed_values_ok = Flags::Parse(&argc, argv, flag_list);
//
// tensorflow::port::InitMain(usage.c_str(), &argc, &argv);
// if (argc != 1 || !parsed_values_ok) {
// ...output usage and error message...
// }
//
// The argc and argv values are adjusted by the Parse function so all that
// remains is the program name (at argv[0]) and any unknown arguments fill the
// rest of the array. This means you can check for flags that weren't understood
// by seeing if argv is greater than 1.
// The result indicates if there were any errors parsing the values that were
// passed to the command-line switches. For example, --some_int=foo would return
// false because the argument is expected to be an integer.
//
// NOTE: Unlike gflags-style libraries, this library is intended to be
// used in the `main()` function of your binary. It does not handle
// flag definitions that are scattered around the source code.
// A description of a single command line flag, holding its name, type, usage
// text, and a pointer to the corresponding variable.
class Flag {
public:
Flag(const char* name, int32* dst, const string& usage_text);
Flag(const char* name, int64* dst, const string& usage_text);
Flag(const char* name, bool* dst, const string& usage_text);
Flag(const char* name, string* dst, const string& usage_text);
Flag(const char* name, float* dst, const string& usage_text);
// These constructors invoke a hook on a match instead of writing to a
// specific memory location. The hook may return false to signal a malformed
// or illegal value, which will then fail the command line parse.
//
// "default_value_for_display" is shown as the default value of this flag in
// Flags::Usage().
Flag(const char* name, std::function<bool(int32)> int32_hook,
int32 default_value_for_display, const string& usage_text);
Flag(const char* name, std::function<bool(int64)> int64_hook,
int64 default_value_for_display, const string& usage_text);
Flag(const char* name, std::function<bool(float)> float_hook,
float default_value_for_display, const string& usage_text);
Flag(const char* name, std::function<bool(bool)> bool_hook,
bool default_value_for_display, const string& usage_text);
Flag(const char* name, std::function<bool(string)> string_hook,
string default_value_for_display, const string& usage_text);
private:
friend class Flags;
bool Parse(string arg, bool* value_parsing_ok) const;
string name_;
enum {
TYPE_INT32,
TYPE_INT64,
TYPE_BOOL,
TYPE_STRING,
TYPE_FLOAT,
} type_;
std::function<bool(int32)> int32_hook_;
int32 int32_default_for_display_;
std::function<bool(int64)> int64_hook_;
int64 int64_default_for_display_;
std::function<bool(float)> float_hook_;
float float_default_for_display_;
std::function<bool(bool)> bool_hook_;
bool bool_default_for_display_;
std::function<bool(string)> string_hook_;
string string_default_for_display_;
string usage_text_;
};
class Flags {
public:
// Parse the command line represented by argv[0, ..., (*argc)-1] to find flag
// instances matching flags in flaglist[]. Update the variables associated
// with matching flags, and remove the matching arguments from (*argc, argv).
// Return true iff all recognized flag values were parsed correctly, and the
// first remaining argument is not "--help".
static bool Parse(int* argc, char** argv, const std::vector<Flag>& flag_list);
// Return a usage message with command line cmdline, and the
// usage_text strings in flag_list[].
static string Usage(const string& cmdline,
const std::vector<Flag>& flag_list);
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_COMMAND_LINE_FLAGS_H
@@ -0,0 +1,149 @@
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// LINT.IfChange
#ifndef TENSORFLOW_CORE_UTIL_CTC_CTC_BEAM_ENTRY_H_
#define TENSORFLOW_CORE_UTIL_CTC_CTC_BEAM_ENTRY_H_
#include <algorithm>
#include <memory>
#include <vector>
#include "third_party/eigen3/Eigen/Core"
#include "tensorflow/core/lib/gtl/flatmap.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/ctc/ctc_loss_util.h"
namespace tensorflow {
namespace ctc {
// The ctc_beam_search namespace holds several classes meant to be accessed only
// in case of extending the CTCBeamSearch decoder to allow custom scoring
// functions.
//
// BeamEntry is exposed through template arguments BeamScorer and BeamComparer
// of CTCBeamSearch (ctc_beam_search.h).
namespace ctc_beam_search {
struct EmptyBeamState {};
struct BeamProbability {
BeamProbability() : total(kLogZero), blank(kLogZero), label(kLogZero) {}
void Reset() {
total = kLogZero;
blank = kLogZero;
label = kLogZero;
}
float total;
float blank;
float label;
};
template <class CTCBeamState>
class BeamRoot;
template <class CTCBeamState = EmptyBeamState>
struct BeamEntry {
// BeamRoot<CTCBeamState>::AddEntry() serves as the factory method.
friend BeamEntry<CTCBeamState>* BeamRoot<CTCBeamState>::AddEntry(
BeamEntry<CTCBeamState>* p, int l);
inline bool Active() const { return newp.total != kLogZero; }
// Return the child at the given index, or construct a new one in-place if
// none was found.
BeamEntry& GetChild(int ind) {
auto entry = children.emplace(ind, nullptr);
auto& child_entry = entry.first->second;
// If this is a new child, populate the BeamEntry<CTCBeamState>*.
if (entry.second) {
child_entry = beam_root->AddEntry(this, ind);
}
return *child_entry;
}
std::vector<int> LabelSeq(bool merge_repeated) const {
std::vector<int> labels;
int prev_label = -1;
const BeamEntry* c = this;
while (c->parent != nullptr) { // Checking c->parent to skip root leaf.
if (!merge_repeated || c->label != prev_label) {
labels.push_back(c->label);
}
prev_label = c->label;
c = c->parent;
}
std::reverse(labels.begin(), labels.end());
return labels;
}
BeamEntry<CTCBeamState>* parent;
int label;
// All instances of child BeamEntry are owned by *beam_root.
gtl::FlatMap<int, BeamEntry<CTCBeamState>*> children;
BeamProbability oldp;
BeamProbability newp;
CTCBeamState state;
private:
// Constructor giving parent, label, and the beam_root.
// The object pointed to by p cannot be copied and should not be moved,
// otherwise parent will become invalid.
// This private constructor is only called through the factory method
// BeamRoot<CTCBeamState>::AddEntry().
BeamEntry(BeamEntry* p, int l, BeamRoot<CTCBeamState>* beam_root)
: parent(p), label(l), beam_root(beam_root) {}
BeamRoot<CTCBeamState>* beam_root;
TF_DISALLOW_COPY_AND_ASSIGN(BeamEntry);
};
// This class owns all instances of BeamEntry. This is used to avoid recursive
// destructor call during destruction.
template <class CTCBeamState = EmptyBeamState>
class BeamRoot {
public:
BeamRoot(BeamEntry<CTCBeamState>* p, int l) { root_entry_ = AddEntry(p, l); }
BeamRoot(const BeamRoot&) = delete;
BeamRoot& operator=(const BeamRoot&) = delete;
BeamEntry<CTCBeamState>* AddEntry(BeamEntry<CTCBeamState>* p, int l) {
auto* new_entry = new BeamEntry<CTCBeamState>(p, l, this);
beam_entries_.emplace_back(new_entry);
return new_entry;
}
BeamEntry<CTCBeamState>* RootEntry() const { return root_entry_; }
private:
BeamEntry<CTCBeamState>* root_entry_ = nullptr;
std::vector<std::unique_ptr<BeamEntry<CTCBeamState>>> beam_entries_;
};
// BeamComparer is the default beam comparer provided in CTCBeamSearch.
template <class CTCBeamState = EmptyBeamState>
class BeamComparer {
public:
virtual ~BeamComparer() {}
virtual bool inline operator()(const BeamEntry<CTCBeamState>* a,
const BeamEntry<CTCBeamState>* b) const {
return a->newp.total > b->newp.total;
}
};
} // namespace ctc_beam_search
} // namespace ctc
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_CTC_CTC_BEAM_ENTRY_H_
// LINT.ThenChange(//tensorflow/contrib/lite/experimental/kernels/ctc_beam_entry.h)
@@ -0,0 +1,77 @@
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// LINT.IfChange
// Collection of scoring classes that can be extended and provided to the
// CTCBeamSearchDecoder to incorporate additional scoring logic (such as a
// language model).
//
// To build a custom scorer extend and implement the pure virtual methods from
// BeamScorerInterface. The default CTC decoding behavior is implemented
// through BaseBeamScorer.
#ifndef TENSORFLOW_CORE_UTIL_CTC_CTC_BEAM_SCORER_H_
#define TENSORFLOW_CORE_UTIL_CTC_CTC_BEAM_SCORER_H_
#include "tensorflow/core/util/ctc/ctc_beam_entry.h"
namespace tensorflow {
namespace ctc {
// Base implementation of a beam scorer used by default by the decoder that can
// be subclassed and provided as an argument to CTCBeamSearchDecoder, if complex
// scoring is required. Its main purpose is to provide a thin layer for
// integrating language model scoring easily.
template <typename CTCBeamState>
class BaseBeamScorer {
public:
virtual ~BaseBeamScorer() {}
// State initialization.
virtual void InitializeState(CTCBeamState* root) const {}
// ExpandState is called when expanding a beam to one of its children.
// Called at most once per child beam. In the simplest case, no state
// expansion is done.
virtual void ExpandState(const CTCBeamState& from_state, int from_label,
CTCBeamState* to_state, int to_label) const {}
// ExpandStateEnd is called after decoding has finished. Its purpose is to
// allow a final scoring of the beam in its current state, before resorting
// and retrieving the TopN requested candidates. Called at most once per beam.
virtual void ExpandStateEnd(CTCBeamState* state) const {}
// GetStateExpansionScore should be an inexpensive method to retrieve the
// (cached) expansion score computed within ExpandState. The score is
// multiplied (log-addition) with the input score at the current step from
// the network.
//
// The score returned should be a log-probability. In the simplest case, as
// there's no state expansion logic, the expansion score is zero.
virtual float GetStateExpansionScore(const CTCBeamState& state,
float previous_score) const {
return previous_score;
}
// GetStateEndExpansionScore should be an inexpensive method to retrieve the
// (cached) expansion score computed within ExpandStateEnd. The score is
// multiplied (log-addition) with the final probability of the beam.
//
// The score returned should be a log-probability.
virtual float GetStateEndExpansionScore(const CTCBeamState& state) const {
return 0;
}
};
} // namespace ctc
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_CTC_CTC_BEAM_SCORER_H_
// LINT.ThenChange(//tensorflow/contrib/lite/experimental/kernels/ctc_beam_scorer.h)
@@ -0,0 +1,434 @@
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// LINT.IfChange
#ifndef TENSORFLOW_CORE_UTIL_CTC_CTC_BEAM_SEARCH_H_
#define TENSORFLOW_CORE_UTIL_CTC_CTC_BEAM_SEARCH_H_
#include <algorithm>
#include <cmath>
#include <limits>
#include <memory>
#include <vector>
#include "third_party/eigen3/Eigen/Core"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/gtl/top_n.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/ctc/ctc_beam_entry.h"
#include "tensorflow/core/util/ctc/ctc_beam_scorer.h"
#include "tensorflow/core/util/ctc/ctc_decoder.h"
#include "tensorflow/core/util/ctc/ctc_loss_util.h"
namespace tensorflow {
namespace ctc {
template <typename CTCBeamState = ctc_beam_search::EmptyBeamState,
typename CTCBeamComparer =
ctc_beam_search::BeamComparer<CTCBeamState>>
class CTCBeamSearchDecoder : public CTCDecoder {
// Beam Search
//
// Example (GravesTh Fig. 7.5):
// a -
// P = [ 0.3 0.7 ] t = 0
// [ 0.4 0.6 ] t = 1
//
// Then P(l = -) = P(--) = 0.7 * 0.6 = 0.42
// P(l = a) = P(a-) + P(aa) + P(-a) = 0.3*0.4 + ... = 0.58
//
// In this case, Best Path decoding is suboptimal.
//
// For Beam Search, we use the following main recurrence relations:
//
// Relation 1:
// ---------------------------------------------------------- Eq. 1
// P(l=abcd @ t=7) = P(l=abc @ t=6) * P(d @ 7)
// + P(l=abcd @ t=6) * (P(d @ 7) + P(- @ 7))
// where P(l=? @ t=7), ? = a, ab, abc, abcd are all stored and
// updated recursively in the beam entry.
//
// Relation 2:
// ---------------------------------------------------------- Eq. 2
// P(l=abc? @ t=3) = P(l=abc @ t=2) * P(? @ 3)
// for ? in a, b, d, ..., (not including c or the blank index),
// and the recurrence starts from the beam entry for P(l=abc @ t=2).
//
// For this case, the length of the new sequence equals t+1 (t
// starts at 0). This special case can be calculated as:
// P(l=abc? @ t=3) = P(a @ 0)*P(b @ 1)*P(c @ 2)*P(? @ 3)
// but we calculate it recursively for speed purposes.
typedef ctc_beam_search::BeamEntry<CTCBeamState> BeamEntry;
typedef ctc_beam_search::BeamRoot<CTCBeamState> BeamRoot;
typedef ctc_beam_search::BeamProbability BeamProbability;
public:
typedef BaseBeamScorer<CTCBeamState> DefaultBeamScorer;
// The beam search decoder is constructed specifying the beam_width (number of
// candidates to keep at each decoding timestep) and a beam scorer (used for
// custom scoring, for example enabling the use of a language model).
// The ownership of the scorer remains with the caller. The default
// implementation, CTCBeamSearchDecoder<>::DefaultBeamScorer, generates the
// standard beam search.
CTCBeamSearchDecoder(int num_classes, int beam_width,
BaseBeamScorer<CTCBeamState>* scorer, int batch_size = 1,
bool merge_repeated = false)
: CTCDecoder(num_classes, batch_size, merge_repeated),
beam_width_(beam_width),
leaves_(beam_width),
beam_scorer_(CHECK_NOTNULL(scorer)) {
Reset();
}
~CTCBeamSearchDecoder() override {}
// Run the hibernating beam search algorithm on the given input.
Status Decode(const CTCDecoder::SequenceLength& seq_len,
const std::vector<CTCDecoder::Input>& input,
std::vector<CTCDecoder::Output>* output,
CTCDecoder::ScoreOutput* scores) override;
// Calculate the next step of the beam search and update the internal state.
template <typename Vector>
void Step(const Vector& log_input_t);
template <typename Vector>
float GetTopK(const int K, const Vector& input,
std::vector<float>* top_k_logits,
std::vector<int>* top_k_indices);
// Retrieve the beam scorer instance used during decoding.
BaseBeamScorer<CTCBeamState>* GetBeamScorer() const { return beam_scorer_; }
// Set label selection parameters for faster decoding.
// See comments for label_selection_size_ and label_selection_margin_.
void SetLabelSelectionParameters(int label_selection_size,
float label_selection_margin) {
label_selection_size_ = label_selection_size;
label_selection_margin_ = label_selection_margin;
}
// Reset the beam search
void Reset();
// Extract the top n paths at current time step
Status TopPaths(int n, std::vector<std::vector<int>>* paths,
std::vector<float>* log_probs, bool merge_repeated) const;
private:
int beam_width_;
// Label selection is designed to avoid possibly very expensive scorer calls,
// by pruning the hypotheses based on the input alone.
// Label selection size controls how many items in each beam are passed
// through to the beam scorer. Only items with top N input scores are
// considered.
// Label selection margin controls the difference between minimal input score
// (versus the best scoring label) for an item to be passed to the beam
// scorer. This margin is expressed in terms of log-probability.
// Default is to do no label selection.
// For more detail: https://research.google.com/pubs/pub44823.html
int label_selection_size_ = 0; // zero means unlimited
float label_selection_margin_ = -1; // -1 means unlimited.
gtl::TopN<BeamEntry*, CTCBeamComparer> leaves_;
std::unique_ptr<BeamRoot> beam_root_;
BaseBeamScorer<CTCBeamState>* beam_scorer_;
TF_DISALLOW_COPY_AND_ASSIGN(CTCBeamSearchDecoder);
};
template <typename CTCBeamState, typename CTCBeamComparer>
Status CTCBeamSearchDecoder<CTCBeamState, CTCBeamComparer>::Decode(
const CTCDecoder::SequenceLength& seq_len,
const std::vector<CTCDecoder::Input>& input,
std::vector<CTCDecoder::Output>* output, ScoreOutput* scores) {
// Storage for top paths.
std::vector<std::vector<int>> beams;
std::vector<float> beam_log_probabilities;
int top_n = output->size();
if (std::any_of(output->begin(), output->end(),
[this](const CTCDecoder::Output& output) -> bool {
return output.size() < this->batch_size_;
})) {
return errors::InvalidArgument(
"output needs to be of size at least (top_n, batch_size).");
}
if (scores->rows() < batch_size_ || scores->cols() < top_n) {
return errors::InvalidArgument(
"scores needs to be of size at least (batch_size, top_n).");
}
for (int b = 0; b < batch_size_; ++b) {
int seq_len_b = seq_len[b];
Reset();
for (int t = 0; t < seq_len_b; ++t) {
// Pass log-probabilities for this example + time.
Step(input[t].row(b));
} // for (int t...
// O(n * log(n))
std::unique_ptr<std::vector<BeamEntry*>> branches(leaves_.Extract());
leaves_.Reset();
for (int i = 0; i < branches->size(); ++i) {
BeamEntry* entry = (*branches)[i];
beam_scorer_->ExpandStateEnd(&entry->state);
entry->newp.total +=
beam_scorer_->GetStateEndExpansionScore(entry->state);
leaves_.push(entry);
}
Status status =
TopPaths(top_n, &beams, &beam_log_probabilities, merge_repeated_);
if (!status.ok()) {
return status;
}
CHECK_EQ(top_n, beam_log_probabilities.size());
CHECK_EQ(beams.size(), beam_log_probabilities.size());
for (int i = 0; i < top_n; ++i) {
// Copy output to the correct beam + batch
(*output)[i][b].swap(beams[i]);
(*scores)(b, i) = -beam_log_probabilities[i];
}
} // for (int b...
return Status::OK();
}
template <typename CTCBeamState, typename CTCBeamComparer>
template <typename Vector>
float CTCBeamSearchDecoder<CTCBeamState, CTCBeamComparer>::GetTopK(
const int K, const Vector& input, std::vector<float>* top_k_logits,
std::vector<int>* top_k_indices) {
// Find Top K choices, complexity nk in worst case. The array input is read
// just once.
CHECK_EQ(num_classes_, input.size());
top_k_logits->clear();
top_k_indices->clear();
top_k_logits->resize(K, -INFINITY);
top_k_indices->resize(K, -1);
for (int j = 0; j < num_classes_ - 1; ++j) {
const float logit = input(j);
if (logit > (*top_k_logits)[K - 1]) {
int k = K - 1;
while (k > 0 && logit > (*top_k_logits)[k - 1]) {
(*top_k_logits)[k] = (*top_k_logits)[k - 1];
(*top_k_indices)[k] = (*top_k_indices)[k - 1];
k--;
}
(*top_k_logits)[k] = logit;
(*top_k_indices)[k] = j;
}
}
// Return max value which is in 0th index or blank character logit
return std::max((*top_k_logits)[0], input(num_classes_ - 1));
}
template <typename CTCBeamState, typename CTCBeamComparer>
template <typename Vector>
void CTCBeamSearchDecoder<CTCBeamState, CTCBeamComparer>::Step(
const Vector& raw_input) {
std::vector<float> top_k_logits;
std::vector<int> top_k_indices;
const bool top_k =
(label_selection_size_ > 0 && label_selection_size_ < raw_input.size());
// Number of character classes to consider in each step.
const int max_classes = top_k ? label_selection_size_ : (num_classes_ - 1);
// Get max coefficient and remove it from raw_input later.
float max_coeff;
if (top_k) {
max_coeff = GetTopK(label_selection_size_, raw_input, &top_k_logits,
&top_k_indices);
} else {
max_coeff = raw_input.maxCoeff();
}
// Get normalization term of softmax: log(sum(exp(logit[j]-max_coeff))).
float logsumexp = 0.0;
for (int j = 0; j < raw_input.size(); ++j) {
logsumexp += Eigen::numext::exp(raw_input(j) - max_coeff);
}
logsumexp = Eigen::numext::log(logsumexp);
// Final normalization offset to get correct log probabilities.
float norm_offset = max_coeff + logsumexp;
const float label_selection_input_min =
(label_selection_margin_ >= 0) ? (max_coeff - label_selection_margin_)
: -std::numeric_limits<float>::infinity();
// Extract the beams sorted in decreasing new probability
CHECK_EQ(num_classes_, raw_input.size());
std::unique_ptr<std::vector<BeamEntry*>> branches(leaves_.Extract());
leaves_.Reset();
for (BeamEntry* b : *branches) {
// P(.. @ t) becomes the new P(.. @ t-1)
b->oldp = b->newp;
}
for (BeamEntry* b : *branches) {
if (b->parent != nullptr) { // if not the root
if (b->parent->Active()) {
// If last two sequence characters are identical:
// Plabel(l=acc @ t=6) = (Plabel(l=acc @ t=5)
// + Pblank(l=ac @ t=5))
// else:
// Plabel(l=abc @ t=6) = (Plabel(l=abc @ t=5)
// + P(l=ab @ t=5))
float previous = (b->label == b->parent->label) ? b->parent->oldp.blank
: b->parent->oldp.total;
b->newp.label =
LogSumExp(b->newp.label,
beam_scorer_->GetStateExpansionScore(b->state, previous));
}
// Plabel(l=abc @ t=6) *= P(c @ 6)
b->newp.label += raw_input(b->label) - norm_offset;
}
// Pblank(l=abc @ t=6) = P(l=abc @ t=5) * P(- @ 6)
b->newp.blank = b->oldp.total + raw_input(blank_index_) - norm_offset;
// P(l=abc @ t=6) = Plabel(l=abc @ t=6) + Pblank(l=abc @ t=6)
b->newp.total = LogSumExp(b->newp.blank, b->newp.label);
// Push the entry back to the top paths list.
// Note, this will always fill leaves back up in sorted order.
leaves_.push(b);
}
// we need to resort branches in descending oldp order.
// branches is in descending oldp order because it was
// originally in descending newp order and we copied newp to oldp.
// Grow new leaves
for (BeamEntry* b : *branches) {
// A new leaf (represented by its BeamProbability) is a candidate
// iff its total probability is nonzero and either the beam list
// isn't full, or the lowest probability entry in the beam has a
// lower probability than the leaf.
auto is_candidate = [this](const BeamProbability& prob) {
return (prob.total > kLogZero &&
(leaves_.size() < beam_width_ ||
prob.total > leaves_.peek_bottom()->newp.total));
};
if (!is_candidate(b->oldp)) {
continue;
}
for (int ind = 0; ind < max_classes; ind++) {
const int label = top_k ? top_k_indices[ind] : ind;
const float logit = top_k ? top_k_logits[ind] : raw_input(ind);
// Perform label selection: if input for this label looks very
// unpromising, never evaluate it with a scorer.
// We may compare logits instead of log probabilities,
// since the difference is the same in both cases.
if (logit < label_selection_input_min) {
continue;
}
BeamEntry& c = b->GetChild(label);
if (!c.Active()) {
// Pblank(l=abcd @ t=6) = 0
c.newp.blank = kLogZero;
// If new child label is identical to beam label:
// Plabel(l=abcc @ t=6) = Pblank(l=abc @ t=5) * P(c @ 6)
// Otherwise:
// Plabel(l=abcd @ t=6) = P(l=abc @ t=5) * P(d @ 6)
beam_scorer_->ExpandState(b->state, b->label, &c.state, c.label);
float previous = (c.label == b->label) ? b->oldp.blank : b->oldp.total;
c.newp.label = logit - norm_offset +
beam_scorer_->GetStateExpansionScore(c.state, previous);
// P(l=abcd @ t=6) = Plabel(l=abcd @ t=6)
c.newp.total = c.newp.label;
if (is_candidate(c.newp)) {
// Before adding the new node to the beam, check if the beam
// is already at maximum width.
if (leaves_.size() == beam_width_) {
// Bottom is no longer in the beam search. Reset
// its probability; signal it's no longer in the beam search.
BeamEntry* bottom = leaves_.peek_bottom();
bottom->newp.Reset();
}
leaves_.push(&c);
} else {
// Deactivate child.
c.oldp.Reset();
c.newp.Reset();
}
}
}
} // for (BeamEntry* b...
}
template <typename CTCBeamState, typename CTCBeamComparer>
void CTCBeamSearchDecoder<CTCBeamState, CTCBeamComparer>::Reset() {
leaves_.Reset();
// This beam root, and all of its children, will be in memory until
// the next reset.
beam_root_.reset(new BeamRoot(nullptr, -1));
beam_root_->RootEntry()->newp.total = 0.0; // ln(1)
beam_root_->RootEntry()->newp.blank = 0.0; // ln(1)
// Add the root as the initial leaf.
leaves_.push(beam_root_->RootEntry());
// Call initialize state on the root object.
beam_scorer_->InitializeState(&beam_root_->RootEntry()->state);
}
template <typename CTCBeamState, typename CTCBeamComparer>
Status CTCBeamSearchDecoder<CTCBeamState, CTCBeamComparer>::TopPaths(
int n, std::vector<std::vector<int>>* paths, std::vector<float>* log_probs,
bool merge_repeated) const {
CHECK_NOTNULL(paths)->clear();
CHECK_NOTNULL(log_probs)->clear();
if (n > beam_width_) {
return errors::InvalidArgument("requested more paths than the beam width.");
}
if (n > leaves_.size()) {
return errors::InvalidArgument(
"Less leaves in the beam search than requested.");
}
gtl::TopN<BeamEntry*, CTCBeamComparer> top_branches(n);
// O(beam_width_ * log(n)), space complexity is O(n)
for (auto it = leaves_.unsorted_begin(); it != leaves_.unsorted_end(); ++it) {
top_branches.push(*it);
}
// O(n * log(n))
std::unique_ptr<std::vector<BeamEntry*>> branches(top_branches.Extract());
for (int i = 0; i < n; ++i) {
BeamEntry* e((*branches)[i]);
paths->push_back(e->LabelSeq(merge_repeated));
log_probs->push_back(e->newp.total);
}
return Status::OK();
}
} // namespace ctc
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_CTC_CTC_BEAM_SEARCH_H_
// LINT.ThenChange(//tensorflow/contrib/lite/experimental/kernels/ctc_beam_search.h)
@@ -0,0 +1,116 @@
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// LINT.IfChange
#ifndef TENSORFLOW_CORE_UTIL_CTC_CTC_DECODER_H_
#define TENSORFLOW_CORE_UTIL_CTC_CTC_DECODER_H_
#include <memory>
#include <vector>
#include "third_party/eigen3/Eigen/Core"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
namespace tensorflow {
namespace ctc {
// The CTCDecoder is an abstract interface to be implemented when providing a
// decoding method on the timestep output of a RNN trained with CTC loss.
//
// The two types of decoding available are:
// - greedy path, through the CTCGreedyDecoder
// - beam search, through the CTCBeamSearchDecoder
class CTCDecoder {
public:
typedef Eigen::Map<const Eigen::ArrayXi> SequenceLength;
typedef Eigen::Map<const Eigen::MatrixXf> Input;
typedef std::vector<std::vector<int>> Output;
typedef Eigen::Map<Eigen::MatrixXf> ScoreOutput;
CTCDecoder(int num_classes, int batch_size, bool merge_repeated)
: num_classes_(num_classes),
blank_index_(num_classes - 1),
batch_size_(batch_size),
merge_repeated_(merge_repeated) {}
virtual ~CTCDecoder() {}
// Dimensionality of the input/output is expected to be:
// - seq_len[b] - b = 0 to batch_size_
// - input[t].rows(b) - t = 0 to timesteps; b = 0 t batch_size_
// - output.size() specifies the number of beams to be returned.
// - scores(b, i) - b = 0 to batch_size; i = 0 to output.size()
virtual Status Decode(const SequenceLength& seq_len,
const std::vector<Input>& input,
std::vector<Output>* output, ScoreOutput* scores) = 0;
int batch_size() { return batch_size_; }
int num_classes() { return num_classes_; }
protected:
int num_classes_;
int blank_index_;
int batch_size_;
bool merge_repeated_;
};
// CTCGreedyDecoder is an implementation of the simple best path decoding
// algorithm, selecting at each timestep the most likely class at each timestep.
class CTCGreedyDecoder : public CTCDecoder {
public:
CTCGreedyDecoder(int num_classes, int batch_size, bool merge_repeated)
: CTCDecoder(num_classes, batch_size, merge_repeated) {}
Status Decode(const CTCDecoder::SequenceLength& seq_len,
const std::vector<CTCDecoder::Input>& input,
std::vector<CTCDecoder::Output>* output,
CTCDecoder::ScoreOutput* scores) override {
if (output->empty() || (*output)[0].size() < batch_size_) {
return errors::InvalidArgument(
"output needs to be of size at least (1, batch_size).");
}
if (scores->rows() < batch_size_ || scores->cols() == 0) {
return errors::InvalidArgument(
"scores needs to be of size at least (batch_size, 1).");
}
// For each batch entry, identify the transitions
for (int b = 0; b < batch_size_; ++b) {
int seq_len_b = seq_len[b];
// Only writing to beam 0
std::vector<int>& output_b = (*output)[0][b];
int prev_class_ix = -1;
(*scores)(b, 0) = 0;
for (int t = 0; t < seq_len_b; ++t) {
auto row = input[t].row(b);
int max_class_ix;
(*scores)(b, 0) += -row.maxCoeff(&max_class_ix);
if (max_class_ix != blank_index_ &&
!(merge_repeated_ && max_class_ix == prev_class_ix)) {
output_b.push_back(max_class_ix);
}
prev_class_ix = max_class_ix;
}
}
return Status::OK();
}
};
} // namespace ctc
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_CTC_CTC_DECODER_H_
// LINT.ThenChange(//tensorflow/contrib/lite/experimental/kernels/ctc_decoder.h)
@@ -0,0 +1,362 @@
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_CTC_CTC_LOSS_CALCULATOR_H_
#define TENSORFLOW_CORE_UTIL_CTC_CTC_LOSS_CALCULATOR_H_
#include <vector>
#include "third_party/eigen3/Eigen/Core"
#include "tensorflow/core/framework/device_base.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/util/ctc/ctc_loss_util.h"
#include "tensorflow/core/util/work_sharder.h"
namespace tensorflow {
namespace ctc {
class CTCLossCalculator {
// Connectionist Temporal Classification Loss
//
// Implementation by kanishkarao@, posenhuang@, and ebrevdo@.
//
// The CTC Loss layer learns a *transition* probability value for each
// input time step. The transitions are on the class alphabet
// {0, 1, ..., N-2}
// where N is the depth of the input layer (the size of the alphabet is N-1).
// Note: The token N-1 is reserved for the "no transition" output, so
// make sure that your input layer has a depth that's one larger than
// the set of classes you're training on. Also make sure that your
// training labels do not have a class value of N-1, as training will skip
// these examples.
//
// Reference materials:
// GravesTh: Alex Graves, "Supervised Sequence Labeling with Recurrent
// Neural Networks" (PhD Thesis), Technische Universit¨at M¨unchen.
public:
typedef std::vector<std::vector<int>> LabelSequences;
typedef Eigen::MatrixXf Matrix;
typedef Eigen::ArrayXf Array;
typedef Eigen::Map<const Eigen::MatrixXf> InputMap;
typedef Eigen::Map<Eigen::MatrixXf> OutputMap;
CTCLossCalculator(int blank_index, int output_delay)
: blank_index_(blank_index), output_delay_(output_delay) {}
template <typename VectorIn, typename VectorOut, typename MatrixIn,
typename MatrixOut>
Status CalculateLoss(const VectorIn& seq_len, const LabelSequences& labels,
const std::vector<MatrixIn>& inputs,
bool preprocess_collapse_repeated,
bool ctc_merge_repeated,
bool ignore_longer_outputs_than_inputs, VectorOut* loss,
std::vector<MatrixOut>* gradients,
DeviceBase::CpuWorkerThreads* workers = nullptr) const;
private:
void CalculateForwardVariables(const std::vector<int>& l_prime,
const Matrix& y, bool ctc_merge_repeated,
Matrix* log_alpha) const;
void CalculateBackwardVariables(const std::vector<int>& l_prime,
const Matrix& y, bool ctc_merge_repeated,
Matrix* log_beta) const;
void CalculateGradient(const std::vector<int>& l_prime, const Matrix& y,
const Matrix& log_alpha, const Matrix& log_beta,
float log_p_z_x, Matrix* dy) const;
void GetLPrimeIndices(const std::vector<int>& l,
std::vector<int>* l_prime) const;
// Helper function that calculates the l_prime indices for all
// batches at the same time, and identifies errors for any given
// batch. Return value:
// max_{b in batch_size} l_primes[b].size()
template <typename Vector>
Status PopulateLPrimes(bool preprocess_collapse_repeated,
bool ignore_longer_outputs_than_inputs, int batch_size,
int num_classes, const Vector& seq_len,
const LabelSequences& labels, size_t* max_u_prime,
LabelSequences* l_primes) const;
// Utility indices for the CTC algorithm.
int blank_index_;
// Delay for target labels in time steps.
// The delay in time steps before the output sequence.
const int output_delay_;
};
template <typename VectorIn, typename VectorOut, typename MatrixIn,
typename MatrixOut>
Status CTCLossCalculator::CalculateLoss(
const VectorIn& seq_len, const LabelSequences& labels,
const std::vector<MatrixIn>& inputs, bool preprocess_collapse_repeated,
bool ctc_merge_repeated, bool ignore_longer_outputs_than_inputs,
VectorOut* loss, std::vector<MatrixOut>* gradients,
DeviceBase::CpuWorkerThreads* workers) const {
auto num_time_steps = inputs.size();
if (loss == nullptr) {
return errors::InvalidArgument("loss == nullptr");
}
bool requires_backprop = (gradients != nullptr);
auto batch_size = inputs[0].rows();
auto num_classes = inputs[0].cols();
if (loss->size() != batch_size) {
return errors::InvalidArgument("loss.size() != batch_size");
}
loss->setZero();
for (int t = 1; t < num_time_steps; ++t) {
if (inputs[t].rows() != batch_size) {
return errors::InvalidArgument("Expected batch size at t: ", t,
" to be: ", batch_size,
" but got: ", inputs[t].rows());
}
if (inputs[t].cols() != num_classes) {
return errors::InvalidArgument("Expected class count at t: ", t,
" to be: ", num_classes,
" but got: ", inputs[t].cols());
}
}
// Check validity of sequence_length array values.
auto max_seq_len = seq_len(0);
for (int b = 0; b < batch_size; b++) {
if (seq_len(b) < 0) {
return errors::InvalidArgument("seq_len(", b, ") < 0");
}
if (seq_len(b) > num_time_steps) {
return errors::InvalidArgument("seq_len(", b, ") > num_time_steps");
}
max_seq_len = std::max(seq_len(b), max_seq_len);
}
// Calculate the modified label sequence l' for each batch element,
// and calculate the maximum necessary allocation size.
LabelSequences l_primes(batch_size);
size_t max_u_prime = 0;
Status l_p_ret = PopulateLPrimes(
preprocess_collapse_repeated, ignore_longer_outputs_than_inputs,
batch_size, num_classes, seq_len, labels, &max_u_prime, &l_primes);
if (!l_p_ret.ok()) {
return l_p_ret;
}
// Process each item in a batch in parallel, using at most kMaxThreads.
auto ComputeLossAndGradients = [this, num_classes, &labels, &l_primes,
&seq_len, &inputs, requires_backprop,
ctc_merge_repeated,
ignore_longer_outputs_than_inputs, &loss,
&gradients](int64 start_row,
int64 limit_row) {
for (int b = start_row; b < limit_row; b++) {
// Return zero gradient for empty sequences or sequences with labels
// longer than input, which is not supported by CTC.
if (seq_len(b) == 0 ||
(ignore_longer_outputs_than_inputs &&
labels[b].size() > seq_len(b) - this->output_delay_)) {
VLOG(1) << "The sequence length is either zero or shorter than the "
"target output (CTC works only with shorter target sequence "
"than input sequence). You can turn this into a warning by "
"using the flag ignore_longer_outputs_than_inputs - "
<< b << ": " << str_util::Join(labels[b], " ");
continue;
}
// For each batch element, log(alpha) and log(beta).
// row size is: u_prime == l_prime.size()
// col size is: seq_len[b] - output_delay_
const std::vector<int>& l_prime = l_primes[b];
Matrix log_alpha_b(l_prime.size(), seq_len(b) - this->output_delay_);
Matrix log_beta_b(l_prime.size(), seq_len(b) - this->output_delay_);
// Work matrices, pre-allocated to the size required by this batch item.
Matrix y(num_classes, seq_len(b));
Matrix dy;
if (requires_backprop) {
dy = Matrix::Zero(y.rows(), y.cols());
}
// For this batch, we'll only work with this shortened sequence_length.
Matrix y_b = y.leftCols(seq_len(b));
// Convert label from DistBelief
// y, prob are in num_classes x seq_len(b)
// Output activations.
Eigen::ArrayXf y_b_col;
for (int t = 0; t < seq_len(b); t++) {
// Calculate the softmax of y_b. Use double precision
// arithmetic for the sum.
float max_coeff = inputs[t].row(b).maxCoeff();
y_b_col = (inputs[t].row(b).array() - max_coeff).exp();
y_b.col(t) = y_b_col / y_b_col.sum();
}
// Compute forward, backward.
// Forward variables.
CalculateForwardVariables(l_prime, y_b, ctc_merge_repeated, &log_alpha_b);
// Backward variables.
CalculateBackwardVariables(l_prime, y_b, ctc_merge_repeated, &log_beta_b);
// The loss is computed as the log(p(z|x)) between the target and
// prediction. Do lazy evaluation of log_prob here.
float log_p_z_x = kLogZero;
for (int u = 0; u < l_prime.size(); ++u) {
// (GravesTh) Eq 7.26, sum over all paths for t = 0.
log_p_z_x = LogSumExp(log_p_z_x, log_alpha_b(u, 0) + log_beta_b(u, 0));
}
(*loss)(b) = -log_p_z_x; // Use negative log loss for display.
// We compute the derivative if needed.
if (requires_backprop) {
// Gradients with respect to input activations.
// Calculate gradient.
dy.setZero();
CalculateGradient(l_prime, y_b, log_alpha_b, log_beta_b, log_p_z_x,
&dy);
// Convert gradient for current sample to DistBelief.
for (int t = 0; t < seq_len(b); t++) {
(*gradients)[t].row(b).array() = dy.col(t);
}
}
} // for (int b = ...
};
if (workers) {
// *Rough* estimate of the cost for one item in the batch.
// Forward, Backward: O(T * U (= 2L + 1)), Gradients: O(T * (U + L)).
//
// softmax: T * L * (Cost(Exp) + Cost(Div))softmax +
// fwd,bwd: T * 2 * (2*L + 1) * (Cost(LogSumExp) + Cost(Log)) +
// grad: T * ((2L + 1) * Cost(LogSumExp) + L * (Cost(Expf) + Cost(Add)).
const int64 cost_exp = Eigen::internal::functor_traits<
Eigen::internal::scalar_exp_op<float>>::Cost;
const int64 cost_log = Eigen::internal::functor_traits<
Eigen::internal::scalar_log_op<float>>::Cost;
const int64 cost_log_sum_exp =
Eigen::TensorOpCost::AddCost<float>() + cost_exp + cost_log;
const int64 cost =
max_seq_len * num_classes *
(cost_exp + Eigen::TensorOpCost::DivCost<float>()) +
max_seq_len * 2 * (2 * num_classes + 1) *
(cost_log_sum_exp + cost_log) +
max_seq_len *
((2 * num_classes + 1) * cost_log_sum_exp +
num_classes * (cost_exp + Eigen::TensorOpCost::AddCost<float>()));
Shard(workers->num_threads, workers->workers, batch_size, cost,
ComputeLossAndGradients);
} else {
ComputeLossAndGradients(0, batch_size);
}
return Status::OK();
}
template <typename Vector>
Status CTCLossCalculator::PopulateLPrimes(
bool preprocess_collapse_repeated, bool ignore_longer_outputs_than_inputs,
int batch_size, int num_classes, const Vector& seq_len,
const LabelSequences& labels, size_t* max_u_prime,
LabelSequences* l_primes) const {
// labels is a Label array of size batch_size
if (labels.size() != batch_size) {
return errors::InvalidArgument(
"labels.size() != batch_size: ", labels.size(), " vs. ", batch_size);
}
*max_u_prime = 0; // keep track of longest l' modified label sequence.
for (int b = 0; b < batch_size; b++) {
// Assume label is in Label proto
const std::vector<int>& label = labels[b];
if (label.size() == 0) {
return errors::InvalidArgument("Labels length is zero in batch ", b);
}
// If debugging: output the labels coming into training.
//
VLOG(2) << "label for batch: " << b << ": " << str_util::Join(label, " ");
// Target indices, length = U.
std::vector<int> l;
// Convert label from DistBelief
bool finished_sequence = false;
for (int i = 0; i < label.size(); ++i) {
if (i == 0 || !preprocess_collapse_repeated || label[i] != label[i - 1]) {
if (label[i] >= num_classes - 1) {
finished_sequence = true;
} else {
if (finished_sequence) {
// Saw an invalid sequence with non-null following null
// labels.
return errors::InvalidArgument(
"Saw a non-null label (index >= num_classes - 1) "
"following a ",
"null label, batch: ", b, " num_classes: ", num_classes,
" labels: ", str_util::Join(l, ","));
}
l.push_back(label[i]);
}
}
}
for (int l_i : l) {
if (l_i < 0) {
return errors::InvalidArgument(
"All labels must be nonnegative integers, batch: ", b,
" labels: ", str_util::Join(l, ","));
} else if (l_i >= num_classes) {
return errors::InvalidArgument(
"No label may be greater than num_classes. ",
"num_classes: ", num_classes, ", batch: ", b,
" labels: ", str_util::Join(l, ","));
}
}
if (!ignore_longer_outputs_than_inputs) {
// Make sure there is enough time to output the target indices.
int time = seq_len(b) - output_delay_;
int required_time = label.size();
if (required_time > time) {
return errors::InvalidArgument(
"Not enough time for target transition sequence ("
"required: ",
required_time, ", available: ", time, ")", b,
"You can turn this error into a warning by using the flag "
"ignore_longer_outputs_than_inputs");
}
}
// Target indices with blanks before each index and a blank at the end.
// Length U' = 2U + 1.
// Convert l to l_prime
GetLPrimeIndices(l, &l_primes->at(b));
*max_u_prime = std::max(*max_u_prime, l_primes->at(b).size());
}
return Status::OK();
}
} // namespace ctc
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_CTC_CTC_LOSS_CALCULATOR_H_
@@ -0,0 +1,50 @@
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// LINT.IfChange
#ifndef TENSORFLOW_CORE_UTIL_CTC_CTC_LOSS_UTIL_H_
#define TENSORFLOW_CORE_UTIL_CTC_CTC_LOSS_UTIL_H_
#include <cmath>
#include <limits>
namespace tensorflow {
namespace ctc {
const float kLogZero = -std::numeric_limits<float>::infinity();
// Add logarithmic probabilities using:
// ln(a + b) = ln(a) + ln(1 + exp(ln(b) - ln(a)))
// The two inputs are assumed to be log probabilities.
// (GravesTh) Eq. 7.18
inline float LogSumExp(float log_prob_1, float log_prob_2) {
// Always have 'b' be the smaller number to avoid the exponential from
// blowing up.
if (log_prob_1 == kLogZero) {
return log_prob_2;
} else if (log_prob_2 == kLogZero) {
return log_prob_1;
} else {
return (log_prob_1 > log_prob_2)
? log_prob_1 + log1pf(expf(log_prob_2 - log_prob_1))
: log_prob_2 + log1pf(expf(log_prob_1 - log_prob_2));
}
}
} // namespace ctc
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_CTC_CTC_LOSS_UTIL_H_
// LINT.ThenChange(//tensorflow/contrib/lite/experimental/kernels/ctc_loss_util.h)
@@ -0,0 +1,635 @@
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_CUDA_DEVICE_FUNCTIONS_H_
#define TENSORFLOW_CORE_UTIL_CUDA_DEVICE_FUNCTIONS_H_
/**
* Wrappers and helpers for CUDA device code.
*
* Wraps the warp-cooperative intrinsics introduced in CUDA 9 to provide
* backwards compatibility, see go/volta-porting for details.
* Provides atomic operations on types that aren't natively supported.
*/
#if GOOGLE_CUDA
#include <algorithm>
#include <complex>
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "cuda/include/cuda.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace detail {
// Helper for range-based for loop using 'delta' increments.
// Usage: see CudaGridRange?() functions below.
template <typename T>
class CudaGridRange {
struct Iterator {
__device__ Iterator(T index, T delta) : index_(index), delta_(delta) {}
__device__ T operator*() const { return index_; }
__device__ Iterator& operator++() {
index_ += delta_;
return *this;
}
__device__ bool operator!=(const Iterator& other) const {
bool greater = index_ > other.index_;
bool less = index_ < other.index_;
// Anything past an end iterator (delta_ == 0) is equal.
// In range-based for loops, this optimizes to 'return less'.
if (!other.delta_) {
return less;
}
if (!delta_) {
return greater;
}
return less || greater;
}
private:
T index_;
const T delta_;
};
public:
__device__ CudaGridRange(T begin, T delta, T end)
: begin_(begin), delta_(delta), end_(end) {}
__device__ Iterator begin() const { return Iterator{begin_, delta_}; }
__device__ Iterator end() const { return Iterator{end_, 0}; }
private:
T begin_;
T delta_;
T end_;
};
} // namespace detail
// Helper to visit indices in the range 0 <= i < count, using the x-coordinate
// of the global thread index. That is, each index i is visited by all threads
// with the same x-coordinate.
// Usage: for(int i : CudaGridRangeX(count)) { visit(i); }
template <typename T>
__device__ detail::CudaGridRange<T> CudaGridRangeX(T count) {
return detail::CudaGridRange<T>(blockIdx.x * blockDim.x + threadIdx.x,
gridDim.x * blockDim.x, count);
}
// Helper to visit indices in the range 0 <= i < count using the y-coordinate.
// Usage: for(int i : CudaGridRangeY(count)) { visit(i); }
template <typename T>
__device__ detail::CudaGridRange<T> CudaGridRangeY(T count) {
return detail::CudaGridRange<T>(blockIdx.y * blockDim.y + threadIdx.y,
gridDim.y * blockDim.y, count);
}
// Helper to visit indices in the range 0 <= i < count using the z-coordinate.
// Usage: for(int i : CudaGridRangeZ(count)) { visit(i); }
template <typename T>
__device__ detail::CudaGridRange<T> CudaGridRangeZ(T count) {
return detail::CudaGridRange<T>(blockIdx.z * blockDim.z + threadIdx.z,
gridDim.z * blockDim.z, count);
}
// Mask for all 32 threads in a warp.
const unsigned kCudaWarpAll = 0xffffffff;
// Returns the warp lane ID of the calling thread
__device__ inline unsigned CudaLaneId() {
unsigned int lane_id;
asm("mov.u32 %0, %%laneid;" : "=r"(lane_id));
return lane_id;
}
namespace detail {
// Returns true if mask is a valid parameter for __shfl*sync to return a well
// defined value, assuming the calling lane will read from src_lane as part of
// the shuffle operation.
//
// Specifically, returns true iff mask has the calling lane bit and the src_lane
// bit set, and the src_lane calls this function with the same mask value
// (required for the two threads to wait for each other).
//
// On Volta, for some invalid masks, this function hangs or returns false
// positives, because the implementation shuffles with the same mask that
// we are validating. Run on Pascal if you suspect that the mask is incorrect.
__device__ inline bool CudaValidateShuffleSyncMask(unsigned mask,
unsigned src_lane) {
unsigned src_dst_mask = 1u << CudaLaneId() | 1u << src_lane;
#if CUDA_VERSION >= 9000
unsigned src_lane_mask = __shfl_sync(mask, mask, src_lane);
#else
unsigned src_lane_mask = __shfl(mask, src_lane);
#endif
return (src_dst_mask & ~mask) == 0 && src_lane_mask == mask;
}
// Returns the actual source lane for shuffle.
__device__ inline unsigned CudaShuffleGetSrcLane(int src_lane, int width) {
int lane_id = CudaLaneId();
int lane_base = lane_id & ~width + 1;
int lane_offset = src_lane & width - 1;
return lane_base + lane_offset;
}
// Returns the source lane for shuffle up.
__device__ inline unsigned CudaShuffleUpGetSrcLane(unsigned delta, int width) {
unsigned lane_id = CudaLaneId();
if ((lane_id & width - 1) < delta) {
return lane_id;
}
return lane_id - delta;
}
// Returns the source lane for shuffle down.
__device__ inline unsigned CudaShuffleDownGetSrcLane(unsigned delta,
int width) {
unsigned lane_id = CudaLaneId();
if ((lane_id & width - 1) + delta >= width) {
return lane_id;
}
return lane_id + delta;
}
// Returns the source lane for shuffle xor.
__device__ inline unsigned CudaShuffleXorGetSrcLane(int lane_mask, int width) {
int lane_id = CudaLaneId();
int src_lane = lane_id ^ lane_mask;
if (src_lane > (lane_id | width - 1)) {
return lane_id;
}
return src_lane;
}
} // namespace detail
// For all *_sync wrappers below, it is illegal to synchronize threads from
// different program locations, because that is not supported before sm_70.
// In other words, all threads in 'mask' must call the functions in convergence.
// Code that requires sm_70 (and CUDA 9) may use the intrinsic directly.
//
// It is also illegal to shuffle with a mask that produces an undefined result
// for any of the threads. Specifically, all source threads of the shuffle
// must have their corresponding bit in 'mask' set.
// Wrapper for __syncwarp. No-op for CUDA 8 and earlier.
__device__ inline void CudaSyncWarp(unsigned mask = kCudaWarpAll) {
assert(mask & 1u << CudaLaneId());
#if CUDA_VERSION >= 9000
__syncwarp(mask);
#endif
}
// Wrapper for __ballot_sync. All threads in 'mask' must call this function in
// convergence, see comment above for details.
__device__ inline unsigned CudaBallotSync(unsigned mask, int pred) {
assert(mask & 1u << CudaLaneId());
#if CUDA_VERSION >= 9000
return __ballot_sync(mask, pred);
#else
return __ballot(pred) & mask; // Apply mask to match __ballot_sync's spec.
#endif
}
// Wrapper for __any_sync. All threads in 'mask' must call this function in
// convergence, see comment above for details.
__device__ inline int CudaAnySync(unsigned mask, int pred) {
assert(mask & 1u << CudaLaneId());
#if CUDA_VERSION >= 9000
return __any_sync(mask, pred);
#else
return __any(pred);
#endif
}
// Wrapper for __all_sync. All threads in 'mask' must call this function in
// convergence, see comment above for details.
__device__ inline int CudaAllSync(unsigned mask, int pred) {
assert(mask & 1u << CudaLaneId());
#if CUDA_VERSION >= 9000
return __all_sync(mask, pred);
#else
return __all(pred);
#endif
}
// Wrapper for __shfl_sync. All threads in 'mask' must call this function in
// convergence, see comment above for details.
template <typename T>
__device__ T CudaShuffleSync(unsigned mask, T value, int src_lane,
int width = warpSize) {
assert(!(width & width - 1));
assert(detail::CudaValidateShuffleSyncMask(
mask, detail::CudaShuffleGetSrcLane(src_lane, width)));
#if CUDA_VERSION >= 9000
return __shfl_sync(mask, value, src_lane, width);
#else
return __shfl(value, src_lane, width);
#endif
}
// Variant of the (undocumented) version from the CUDA SDK, but using unsigned
// instead of float for lo and hi (which is incorrect with ftz, for example).
// See b/69446944.
__device__ inline double CudaShuffleSync(unsigned mask, double value,
int src_lane, int width = warpSize) {
unsigned lo, hi;
asm volatile("mov.b64 {%0,%1}, %2;" : "=r"(lo), "=r"(hi) : "d"(value));
hi = CudaShuffleSync(mask, hi, src_lane, width);
lo = CudaShuffleSync(mask, lo, src_lane, width);
asm volatile("mov.b64 %0, {%1,%2};" : "=d"(value) : "r"(lo), "r"(hi));
return value;
}
// Wrapper for __shfl_up_sync. All threads in 'mask' must call this function in
// convergence, see comment above for details.
template <typename T>
__device__ inline T CudaShuffleUpSync(unsigned mask, T value, unsigned delta,
int width = warpSize) {
assert(!(width & width - 1));
assert(detail::CudaValidateShuffleSyncMask(
mask, detail::CudaShuffleUpGetSrcLane(delta, width)));
#if CUDA_VERSION >= 9000
return __shfl_up_sync(mask, value, delta, width);
#else
return __shfl_up(value, delta, width);
#endif
}
// Variant of the (undocumented) version from the CUDA SDK, but using unsigned
// instead of float for lo and hi (which is incorrect with ftz, for example).
// See b/69446944.
__device__ inline double CudaShuffleUpSync(unsigned mask, double value,
unsigned delta,
int width = warpSize) {
unsigned lo, hi;
asm volatile("mov.b64 {%0,%1}, %2;" : "=r"(lo), "=r"(hi) : "d"(value));
hi = CudaShuffleUpSync(mask, hi, delta, width);
lo = CudaShuffleUpSync(mask, lo, delta, width);
asm volatile("mov.b64 %0, {%1,%2};" : "=d"(value) : "r"(lo), "r"(hi));
return value;
}
// Wrapper for __shfl_down_sync. All threads in 'mask' must call this function
// in convergence, see comment above for details.
template <typename T>
__device__ inline T CudaShuffleDownSync(unsigned mask, T value, unsigned delta,
int width = warpSize) {
assert(!(width & width - 1));
assert(detail::CudaValidateShuffleSyncMask(
mask, detail::CudaShuffleDownGetSrcLane(delta, width)));
#if CUDA_VERSION >= 9000
return __shfl_down_sync(mask, value, delta, width);
#else
return __shfl_down(value, delta, width);
#endif
}
// Variant of the (undocumented) version from the CUDA SDK, but using unsigned
// instead of float for lo and hi (which is incorrect with ftz, for example).
// See b/69446944.
__device__ inline double CudaShuffleDownSync(unsigned mask, double value,
unsigned delta,
int width = warpSize) {
unsigned lo, hi;
asm volatile("mov.b64 {%0,%1}, %2;" : "=r"(lo), "=r"(hi) : "d"(value));
hi = CudaShuffleDownSync(mask, hi, delta, width);
lo = CudaShuffleDownSync(mask, lo, delta, width);
asm volatile("mov.b64 %0, {%1,%2};" : "=d"(value) : "r"(lo), "r"(hi));
return value;
}
// Wrapper for __shfl_xor_sync. All threads in 'mask' must call this function in
// convergence, see comment above for details.
template <typename T>
__device__ T CudaShuffleXorSync(unsigned mask, T value, int lane_mask,
int width = warpSize) {
assert(!(width & width - 1));
assert(detail::CudaValidateShuffleSyncMask(
mask, detail::CudaShuffleXorGetSrcLane(lane_mask, width)));
#if CUDA_VERSION >= 9000
return __shfl_xor_sync(mask, value, lane_mask, width);
#else
return __shfl_xor(value, lane_mask, width);
#endif
}
// Variant of the (undocumented) version from the CUDA SDK, but using unsigned
// instead of float for lo and hi (which is incorrect with ftz, for example).
// See b/69446944.
__device__ inline double CudaShuffleXorSync(unsigned mask, double value,
int lane_mask,
int width = warpSize) {
unsigned lo, hi;
asm volatile("mov.b64 {%0,%1}, %2;" : "=r"(lo), "=r"(hi) : "d"(value));
hi = CudaShuffleXorSync(mask, hi, lane_mask, width);
lo = CudaShuffleXorSync(mask, lo, lane_mask, width);
asm volatile("mov.b64 %0, {%1,%2};" : "=d"(value) : "r"(lo), "r"(hi));
return value;
}
// Wrapper for __ldg.
template <typename T>
__host__ __device__ T CudaLdg(const T* address) {
#if __CUDA_ARCH__ >= 350
return __ldg(address);
#else
return *address;
#endif
}
__host__ __device__ inline bool CudaLdg(const bool* address) {
return CudaLdg(reinterpret_cast<const char*>(address)) != 0;
}
__host__ __device__ inline std::complex<float> CudaLdg(
const std::complex<float>* address) {
#if __CUDA_ARCH__ >= 350
float2 mem = __ldg(reinterpret_cast<const float2*>(address));
return std::complex<float>(mem.x, mem.y);
#else
return *address;
#endif
}
__host__ __device__ inline std::complex<double> CudaLdg(
const std::complex<double>* address) {
#if __CUDA_ARCH__ >= 350
double2 mem = __ldg(reinterpret_cast<const double2*>(address));
return std::complex<double>(mem.x, mem.y);
#else
return *address;
#endif
}
// Zeroes count elements starting at ptr using all threads of a 1-D grid.
// Note: this function does not synchronize, and therefore the memory range is
// not guaranteed to be zero until the next kernel launch.
template <typename T>
__global__ void SetZero(const int count, T* ptr) {
// Check that the grid is one dimensional and index doesn't overflow.
assert(blockDim.y == 1 && blockDim.z == 1);
assert(blockDim.x * gridDim.x / blockDim.x == gridDim.x);
for (int i : CudaGridRangeX(count)) {
ptr[i] = T(0);
}
}
// Helper to set all tensor entries to a specific value.
template <typename T>
__global__ void SetToValue(const int count, T* ptr, T value) {
// Check that the grid is one dimensional and index doesn't overflow.
assert(blockDim.y == 1 && blockDim.z == 1);
assert(blockDim.x * gridDim.x / blockDim.x == gridDim.x);
for (int i : CudaGridRangeX(count)) {
ptr[i] = value;
}
}
namespace detail {
// Helper function for atomic accumulation implemented as CAS.
template <typename T, typename F>
__device__ T CudaAtomicCasHelper(T* ptr, F accumulate) {
T old = *ptr;
T assumed;
do {
assumed = old;
old = atomicCAS(ptr, assumed, accumulate(assumed));
} while (assumed != old);
return old;
}
// Overload for floating point (using integer comparison to handle NaN
// correctly).
template <typename F>
__device__ float CudaAtomicCasHelper(float* ptr, F accumulate) {
return __float_as_int(
CudaAtomicCasHelper(reinterpret_cast<int32*>(ptr), [accumulate](int32 a) {
return __float_as_int(accumulate(__int_as_float(a)));
}));
}
template <typename F>
__device__ double CudaAtomicCasHelper(double* ptr, F accumulate) {
return __longlong_as_double(CudaAtomicCasHelper(
reinterpret_cast<tensorflow::uint64*>(ptr),
[accumulate](tensorflow::uint64 a) {
return __double_as_longlong(accumulate(__longlong_as_double(a)));
}));
}
// Overload of above function for half. Note that we don't have
// atomicCAS() for anything less than 32 bits, so we need to include the
// other 16 bits in the operation.
//
// This version is going to be very slow
// under high concurrency, since most threads will be spinning on failing
// their compare-and-swap tests. (The fact that we get false sharing on the
// neighboring fp16 makes this even worse.) If you are doing a large reduction,
// you are much better off with doing the intermediate steps in fp32 and then
// switching to fp16 as late as you can in the calculations.
//
// Note: Assumes little endian.
template <typename F>
__device__ Eigen::half CudaAtomicCasHelper(Eigen::half* ptr, F accumulate) {
#if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__)
static_assert(__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__, "Not little endian");
#endif
namespace half_impl = Eigen::half_impl;
intptr_t intptr = reinterpret_cast<intptr_t>(ptr);
assert(!(intptr & 0x1)); // should be 2-aligned.
if (intptr & 0x2) {
// The half is in the second part of the uint32 (upper 16 bits).
uint32* address = reinterpret_cast<uint32*>(intptr - 2);
uint32 result = CudaAtomicCasHelper(address, [accumulate](uint32 arg) {
unsigned short high = static_cast<unsigned short>(arg >> 16);
Eigen::half acc = accumulate(half_impl::raw_uint16_to_half(high));
return (static_cast<uint32>(acc.x) << 16) | (arg & 0xffff);
});
return half_impl::raw_uint16_to_half(static_cast<uint16>(result >> 16));
} else {
// The half is in the first part of the uint32 (lower 16 bits).
uint32* address = reinterpret_cast<uint32*>(intptr);
uint32 result = CudaAtomicCasHelper(address, [accumulate](uint32 arg) {
unsigned short low = static_cast<unsigned short>(arg & 0xffff);
Eigen::half acc = accumulate(half_impl::raw_uint16_to_half(low));
return (arg & 0xffff0000) | static_cast<uint32>(acc.x);
});
return half_impl::raw_uint16_to_half(static_cast<uint16>(result & 0xffff));
}
}
template <typename From, typename To>
using ToTypeIfConvertible =
typename std::enable_if<std::is_convertible<From, To>::value, To>::type;
} // namespace detail
// CUDA provides atomic ops, but not for all types. We provide wrappers
// for some ops and provide implementation for all reasonable types.
template <typename T, typename U>
__device__ detail::ToTypeIfConvertible<U, T> CudaAtomicAdd(T* ptr, U value) {
return atomicAdd(ptr, value);
}
__device__ inline Eigen::half CudaAtomicAdd(Eigen::half* ptr,
Eigen::half value) {
return detail::CudaAtomicCasHelper(
ptr, [value](Eigen::half a) { return a + value; });
}
#if __CUDA_ARCH__ < 600
__device__ inline double CudaAtomicAdd(double* ptr, double value) {
return detail::CudaAtomicCasHelper(ptr,
[value](double a) { return a + value; });
}
#elif __clang__
// Clang cannot compile __nvvm_atom_add_gen_d builtin yet, use inline PTX.
// see https://reviews.llvm.org/D39638
__device__ inline double CudaAtomicAdd(double* ptr, double value) {
double result;
asm volatile("atom.add.f64 %0, [%1], %2;"
: "=d"(result)
: "l"(ptr), "d"(value)
: "memory");
return result;
}
#endif
// CudaAtomicAdd
// Specializations of CudaAtomicAdd for complex types, which CudaAtomicAdd does
// not support. We treat a std::complex<T>* as a T* (the C++ standard section
// 26.4.4 allows this explicitly) and atomic add the real and imaginary
// components individually. The operation as a whole is not atomic, but we can
// safely treat the components independently for the purpose of accumulating.
__device__ inline std::complex<float> CudaAtomicAdd(std::complex<float>* ptr,
std::complex<float> value) {
auto ptr_scalar = reinterpret_cast<float*>(ptr);
return std::complex<float>(CudaAtomicAdd(ptr_scalar, value.real()),
CudaAtomicAdd(ptr_scalar + 1, value.imag()));
}
__device__ inline std::complex<double> CudaAtomicAdd(
std::complex<double>* ptr, std::complex<double> value) {
auto ptr_scalar = reinterpret_cast<double*>(ptr);
return std::complex<double>(CudaAtomicAdd(ptr_scalar, value.real()),
CudaAtomicAdd(ptr_scalar + 1, value.imag()));
}
// CudaAtomicSub
template <typename T, typename U>
__device__ detail::ToTypeIfConvertible<U, T> CudaAtomicSub(T* ptr, U value) {
return atomicSub(ptr, value);
}
// Specializations of subtraction which add the negative value.
__device__ inline float CudaAtomicSub(float* ptr, float value) {
return CudaAtomicAdd(ptr, -value);
}
__device__ inline double CudaAtomicSub(double* ptr, double value) {
return CudaAtomicAdd(ptr, -value);
}
__device__ inline tensorflow::uint64 CudaAtomicSub(tensorflow::uint64* ptr,
tensorflow::uint64 value) {
return CudaAtomicAdd(ptr, -value);
}
__device__ inline Eigen::half CudaAtomicSub(Eigen::half* ptr,
Eigen::half value) {
return detail::CudaAtomicCasHelper(
ptr, [value](Eigen::half a) { return a - value; });
}
// CudaAtomicMax
template <typename T, typename U>
__device__ detail::ToTypeIfConvertible<U, T> CudaAtomicMax(T* ptr, U value) {
return atomicMax(ptr, value);
}
__device__ inline float CudaAtomicMax(float* ptr, float value) {
return detail::CudaAtomicCasHelper(
ptr, [value](float a) { return max(a, value); });
}
__device__ inline double CudaAtomicMax(double* ptr, double value) {
return detail::CudaAtomicCasHelper(
ptr, [value](double a) { return max(a, value); });
}
__device__ inline Eigen::half CudaAtomicMax(Eigen::half* ptr,
Eigen::half value) {
return detail::CudaAtomicCasHelper(
ptr, [value](Eigen::half a) { return max(a, value); });
}
#if __CUDA_ARCH__ < 320
__device__ inline tensorflow::uint64 CudaAtomicMax(tensorflow::uint64* ptr,
tensorflow::uint64 value) {
return detail::CudaAtomicCasHelper(
ptr, [value](tensorflow::uint64 a) { return max(a, value); });
}
#endif
// CudaAtomicMin
template <typename T, typename U>
__device__ detail::ToTypeIfConvertible<U, T> CudaAtomicMin(T* ptr, U value) {
return atomicMin(ptr, value);
}
__device__ inline float CudaAtomicMin(float* ptr, float value) {
return detail::CudaAtomicCasHelper(
ptr, [value](float a) { return min(a, value); });
}
__device__ inline double CudaAtomicMin(double* ptr, double value) {
return detail::CudaAtomicCasHelper(
ptr, [value](double a) { return min(a, value); });
}
__device__ inline Eigen::half CudaAtomicMin(Eigen::half* ptr,
Eigen::half value) {
return detail::CudaAtomicCasHelper(
ptr, [value](Eigen::half a) { return min(a, value); });
}
#if __CUDA_ARCH__ < 320
__device__ inline tensorflow::uint64 CudaAtomicMin(tensorflow::uint64* ptr,
tensorflow::uint64 value) {
return detail::CudaAtomicCasHelper(
ptr, [value](tensorflow::uint64 a) { return min(a, value); });
}
#endif
// CudaAtomicMul
template <typename T, typename U>
__device__ detail::ToTypeIfConvertible<U, T> CudaAtomicMul(T* ptr, U value) {
return detail::CudaAtomicCasHelper(ptr, [value](T a) { return a * value; });
}
// CudaAtomicDiv
template <typename T, typename U>
__device__ detail::ToTypeIfConvertible<U, T> CudaAtomicDiv(T* ptr, U value) {
return detail::CudaAtomicCasHelper(ptr, [value](T a) { return a / value; });
}
} // namespace tensorflow
#endif // GOOGLE_CUDA
#endif // TENSORFLOW_CORE_UTIL_CUDA_KERNEL_HELPER_H_
@@ -0,0 +1,140 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_CUDA_KERNEL_HELPER_H_
#define TENSORFLOW_CORE_UTIL_CUDA_KERNEL_HELPER_H_
#if GOOGLE_CUDA
#include "tensorflow/core/util/cuda_device_functions.h"
#include "tensorflow/core/util/cuda_launch_config.h"
#include "cuda/include/cuda_fp16.h"
// Deprecated, use 'for(int i : CudaGridRangeX(n))' instead.
#define CUDA_1D_KERNEL_LOOP(i, n) \
for (int i : ::tensorflow::CudaGridRangeX<int>(n))
// Deprecated, use 'for(int i : CudaGridRange?(n))' instead.
#define CUDA_AXIS_KERNEL_LOOP(i, n, axis) \
for (int i : ::tensorflow::CudaGridRange##axis<int>(n))
namespace tensorflow {
__host__ __device__ inline tensorflow::bfloat16 CudaLdg(
const tensorflow::bfloat16* address) {
tensorflow::bfloat16 return_value;
return_value.value = CudaLdg(reinterpret_cast<const uint16_t*>(address));
return return_value;
}
template <typename T>
__host__ __device__ inline T ldg(const T* ptr) {
return CudaLdg(ptr);
}
template <typename T>
__host__ __device__ inline const T& tf_min(const T& x, const T& y) {
return x < y ? x : y;
}
template <typename T>
__host__ __device__ inline const T& tf_max(const T& x, const T& y) {
return x < y ? y : x;
}
// Overloads of the above functions for float and double.
__host__ __device__ inline float tf_min(float x, float y) {
return fminf(x, y);
}
__host__ __device__ inline double tf_min(double x, double y) {
return fmin(x, y);
}
__host__ __device__ inline float tf_max(float x, float y) {
return fmaxf(x, y);
}
__host__ __device__ inline double tf_max(double x, double y) {
return fmax(x, y);
}
__device__ inline Eigen::half CudaShuffleSync(unsigned mask, Eigen::half value,
int src_lane,
int width = warpSize) {
return Eigen::half(
CudaShuffleSync(mask, static_cast<uint16>(value), src_lane, width));
}
__device__ EIGEN_ALWAYS_INLINE Eigen::half CudaShuffleUpSync(
unsigned mask, Eigen::half value, int delta, int width = warpSize) {
return Eigen::half(
CudaShuffleUpSync(mask, static_cast<uint16>(value), delta, width));
}
__device__ EIGEN_ALWAYS_INLINE Eigen::half CudaShuffleDownSync(
unsigned mask, Eigen::half value, int delta, int width = warpSize) {
return Eigen::half(
CudaShuffleDownSync(mask, static_cast<uint16>(value), delta, width));
}
__device__ EIGEN_ALWAYS_INLINE Eigen::half CudaShuffleXorSync(
unsigned mask, Eigen::half value, int lane_mask, int width = warpSize) {
return Eigen::half(
CudaShuffleXorSync(mask, static_cast<uint16>(value), lane_mask, width));
}
namespace cuda_helper {
template <typename T, typename OutType = int32>
__device__ OutType upper_bound(const T* first, OutType count, T val) {
const T* orig = first;
const T* it = nullptr;
OutType step = 0;
while (count > 0) {
it = first;
step = count / 2;
it += step;
if (!(val < *it)) {
first = ++it;
count -= step + 1;
} else {
count = step;
}
}
return first - orig;
}
template <typename T, typename OutType = int32>
__device__ OutType lower_bound(const T* first, OutType count, T val) {
const T* orig = first;
const T* it = nullptr;
OutType step = 0;
while (count > 0) {
it = first;
step = count / 2;
it += step;
if (*it < val) {
first = ++it;
count -= step + 1;
} else {
count = step;
}
}
return first - orig;
}
} // namespace cuda_helper
} // namespace tensorflow
#endif // GOOGLE_CUDA
#endif // TENSORFLOW_CORE_UTIL_CUDA_KERNEL_HELPER_H_
@@ -0,0 +1,306 @@
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_CUDA_LAUNCH_CONFIG_H_
#define TENSORFLOW_CORE_UTIL_CUDA_LAUNCH_CONFIG_H_
#if GOOGLE_CUDA
#include <algorithm>
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "cuda/include/cuda.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/stream_executor.h"
#include "tensorflow/core/platform/types.h"
// Usage of GetCudaLaunchConfig, GetCuda2DLaunchConfig, and
// GetCuda3DLaunchConfig:
//
// There are two versions of GetCudaLaunchConfig and GetCuda2DLaunchConfig, one
// version uses heuristics without any knowledge of the device kernel, the other
// version uses cudaOccupancyMaxPotentialBlockSize to determine the theoretical
// launch parameters that maximize occupancy. Currently, only the maximum
// occupancy version of GetCuda3DLaunchConfig is available.
//
// For large number of work elements, the convention is that each kernel would
// iterate through its assigned range. The return value of GetCudaLaunchConfig
// is struct CudaLaunchConfig, which contains all the information needed for the
// kernel launch, including: virtual number of threads, the number of threads
// per block and number of threads per block used inside <<< >>> of a kernel
// launch. GetCuda2DLaunchConfig and GetCuda3DLaunchConfig does the same thing
// as CudaLaunchConfig. The only difference is the dimension. The macros
// CUDA_1D_KERNEL_LOOP and CUDA_AXIS_KERNEL_LOOP might be used to do inner loop.
//
/* Sample code:
__global__ void MyKernel1D(CudaLaunchConfig config, other_args...) {
CUDA_1D_KERNEL_LOOP(x, config.virtual_thread_count) {
do_your_job_here;
}
}
__global__ void MyKernel2D(Cuda2DLaunchConfig config, other_args...) {
CUDA_AXIS_KERNEL_LOOP(x, config.virtual_thread_count, x) {
CUDA_AXIS_KERNEL_LOOP(y, config.virtual_thread_count, y) {
do_your_job_here;
}
}
}
__global__ void MyKernel3D(Cuda3DLaunchConfig config, other_args...) {
CUDA_AXIS_KERNEL_LOOP(x, config.virtual_thread_count, x) {
CUDA_AXIS_KERNEL_LOOP(y, config.virtual_thread_count, y) {
CUDA_AXIS_KERNEL_LOOP(z, config.virtual_thread_count, z) {
do_your_job_here;
}
}
}
}
void MyDriverFunc(const Eigen::GpuDevice &d) {
// use heuristics
CudaLaunchConfig cfg1 = GetCudaLaunchConfig(10240, d);
MyKernel1D <<<config.block_count,
config.thread_per_block, 0, d.stream()>>> (cfg1, other_args...);
Cuda2DLaunchConfig cfg2 = GetCuda2DLaunchConfig(10240, 10240, d);
MyKernel2D <<<config.block_count,
config.thread_per_block, 0, d.stream()>>> (cfg2, other_args...);
Cuda3DLaunchConfig cfg3 = GetCuda3DLaunchConfig(4096, 4096, 100, d);
MyKernel3D <<<config.block_count,
config.thread_per_block, 0, d.stream()>>> (cfg3, other_args...);
// maximize occupancy
CudaLaunchConfig cfg4 = GetCudaLaunchConfig(10240, d, MyKernel1D, 0, 0 );
MyKernel1D <<<config.block_count,
config.thread_per_block, 0, d.stream()>>> (cfg4, other_args...);
Cuda2DLaunchConfig cfg5 = GetCuda2DLaunchConfig(10240, 10240, d,
MyKernel1D, 0, 0);
MyKernel2D <<<config.block_count,
config.thread_per_block, 0, d.stream()>>> (cfg5, other_args...);
Cuda3DLaunchConfig cfg6 = GetCuda3DLaunchConfig(4096, 4096, 100, d,
MyKernel1D, 0, 0);
MyKernel3D <<<config.block_count,
config.thread_per_block, 0, d.stream()>>> (cfg6, other_args...);
}
// See the test for this for more example:
//
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/util/cuda_kernel_helper_test.cu.cc
*/
namespace tensorflow {
inline int DivUp(int a, int b) { return (a + b - 1) / b; }
struct CudaLaunchConfig {
// Logical number of thread that works on the elements. If each logical
// thread works on exactly a single element, this is the same as the working
// element count.
int virtual_thread_count = -1;
// Number of threads per block.
int thread_per_block = -1;
// Number of blocks for Cuda kernel launch.
int block_count = -1;
};
// Calculate the Cuda launch config we should use for a kernel launch.
// This is assuming the kernel is quite simple and will largely be
// memory-limited.
// REQUIRES: work_element_count > 0.
inline CudaLaunchConfig GetCudaLaunchConfig(int work_element_count,
const Eigen::GpuDevice& d) {
CHECK_GT(work_element_count, 0);
CudaLaunchConfig config;
const int virtual_thread_count = work_element_count;
const int physical_thread_count = std::min(
d.getNumCudaMultiProcessors() * d.maxCudaThreadsPerMultiProcessor(),
virtual_thread_count);
const int thread_per_block = std::min(1024, d.maxCudaThreadsPerBlock());
const int block_count =
std::min(DivUp(physical_thread_count, thread_per_block),
d.getNumCudaMultiProcessors());
config.virtual_thread_count = virtual_thread_count;
config.thread_per_block = thread_per_block;
config.block_count = block_count;
return config;
}
// Calculate the Cuda launch config we should use for a kernel launch. This
// variant takes the resource limits of func into account to maximize occupancy.
// REQUIRES: work_element_count > 0.
template <typename DeviceFunc>
inline CudaLaunchConfig GetCudaLaunchConfig(int work_element_count,
const Eigen::GpuDevice& d,
DeviceFunc func,
size_t dynamic_shared_memory_size,
int block_size_limit) {
CHECK_GT(work_element_count, 0);
CudaLaunchConfig config;
int block_count = 0;
int thread_per_block = 0;
cudaError_t err = cudaOccupancyMaxPotentialBlockSize(
&block_count, &thread_per_block, func, dynamic_shared_memory_size,
block_size_limit);
CHECK_EQ(err, cudaSuccess);
block_count =
std::min(block_count, DivUp(work_element_count, thread_per_block));
config.virtual_thread_count = work_element_count;
config.thread_per_block = thread_per_block;
config.block_count = block_count;
return config;
}
// Calculate the Cuda launch config we should use for a kernel launch. This
// variant takes the resource limits of func into account to maximize occupancy.
// The returned launch config has thread_per_block set to fixed_block_size.
// REQUIRES: work_element_count > 0.
template <typename DeviceFunc>
inline CudaLaunchConfig GetCudaLaunchConfigFixedBlockSize(
int work_element_count, const Eigen::GpuDevice& d, DeviceFunc func,
size_t dynamic_shared_memory_size, int fixed_block_size) {
CHECK_GT(work_element_count, 0);
CudaLaunchConfig config;
int block_count = 0;
cudaError_t err = cudaOccupancyMaxActiveBlocksPerMultiprocessor(
&block_count, func, fixed_block_size, dynamic_shared_memory_size);
CHECK_EQ(err, cudaSuccess);
block_count = std::min(block_count * d.getNumCudaMultiProcessors(),
DivUp(work_element_count, fixed_block_size));
config.virtual_thread_count = work_element_count;
config.thread_per_block = fixed_block_size;
config.block_count = block_count;
return config;
}
struct Cuda2DLaunchConfig {
dim3 virtual_thread_count = dim3(0, 0, 0);
dim3 thread_per_block = dim3(0, 0, 0);
dim3 block_count = dim3(0, 0, 0);
};
inline Cuda2DLaunchConfig GetCuda2DLaunchConfig(int xdim, int ydim,
const Eigen::GpuDevice& d) {
Cuda2DLaunchConfig config;
if (xdim <= 0 || ydim <= 0) {
return config;
}
const int kThreadsPerBlock = 256;
int block_cols = std::min(xdim, kThreadsPerBlock);
// ok to round down here and just do more loops in the kernel
int block_rows = std::max(kThreadsPerBlock / block_cols, 1);
const int physical_thread_count =
d.getNumCudaMultiProcessors() * d.maxCudaThreadsPerMultiProcessor();
const int max_blocks = std::max(physical_thread_count / kThreadsPerBlock, 1);
config.virtual_thread_count = dim3(xdim, ydim, 1);
config.thread_per_block = dim3(block_cols, block_rows, 1);
int grid_x = std::min(DivUp(xdim, block_cols), max_blocks);
config.block_count = dim3(
grid_x, std::min(max_blocks / grid_x, std::max(ydim / block_rows, 1)), 1);
return config;
}
// Calculate the Cuda 2D and 3D launch config we should use for a kernel launch.
// This variant takes the resource limits of func into account to maximize
// occupancy.
using Cuda3DLaunchConfig = Cuda2DLaunchConfig;
template <typename DeviceFunc>
inline Cuda3DLaunchConfig GetCuda3DLaunchConfig(
int xdim, int ydim, int zdim, const Eigen::GpuDevice& d, DeviceFunc func,
size_t dynamic_shared_memory_size, int block_size_limit) {
Cuda3DLaunchConfig config;
if (xdim <= 0 || ydim <= 0 || zdim <= 0) {
return config;
}
int dev;
cudaGetDevice(&dev);
cudaDeviceProp deviceProp;
cudaGetDeviceProperties(&deviceProp, dev);
int xthreadlimit = deviceProp.maxThreadsDim[0];
int ythreadlimit = deviceProp.maxThreadsDim[1];
int zthreadlimit = deviceProp.maxThreadsDim[2];
int xgridlimit = deviceProp.maxGridSize[0];
int ygridlimit = deviceProp.maxGridSize[1];
int zgridlimit = deviceProp.maxGridSize[2];
int block_count = 0;
int thread_per_block = 0;
cudaError_t err = cudaOccupancyMaxPotentialBlockSize(
&block_count, &thread_per_block, func, dynamic_shared_memory_size,
block_size_limit);
CHECK_EQ(err, cudaSuccess);
int threadsx = std::min({xdim, thread_per_block, xthreadlimit});
int threadsy =
std::min({ydim, std::max(thread_per_block / threadsx, 1), ythreadlimit});
int threadsz =
std::min({zdim, std::max(thread_per_block / (threadsx * threadsy), 1),
zthreadlimit});
int blocksx = std::min({block_count, DivUp(xdim, threadsx), xgridlimit});
int blocksy = std::min(
{DivUp(block_count, blocksx), DivUp(ydim, threadsy), ygridlimit});
int blocksz = std::min({DivUp(block_count, (blocksx * blocksy)),
DivUp(zdim, threadsz), zgridlimit});
config.virtual_thread_count = dim3(xdim, ydim, zdim);
config.thread_per_block = dim3(threadsx, threadsy, threadsz);
config.block_count = dim3(blocksx, blocksy, blocksz);
return config;
}
template <typename DeviceFunc>
inline Cuda2DLaunchConfig GetCuda2DLaunchConfig(
int xdim, int ydim, const Eigen::GpuDevice& d, DeviceFunc func,
size_t dynamic_shared_memory_size, int block_size_limit) {
return GetCuda3DLaunchConfig(xdim, ydim, 1, d, func,
dynamic_shared_memory_size, block_size_limit);
}
// Returns a raw reference to the current cuda stream. Required by a
// number of kernel calls (for which StreamInterface* does not work), i.e.
// CUB and certain cublas primitives.
inline const cudaStream_t& GetCudaStream(OpKernelContext* context) {
const cudaStream_t* ptr = CHECK_NOTNULL(
reinterpret_cast<const cudaStream_t*>(context->op_device_context()
->stream()
->implementation()
->GpuStreamMemberHack()));
return *ptr;
}
} // namespace tensorflow
#endif // GOOGLE_CUDA
#endif // TENSORFLOW_CORE_UTIL_CUDA_KERNEL_HELPER_H_
@@ -0,0 +1,176 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_DEVICE_NAME_UTILS_H_
#define TENSORFLOW_CORE_UTIL_DEVICE_NAME_UTILS_H_
#include <string>
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/stringpiece.h"
namespace tensorflow {
// In TensorFlow a device name is a string of the following form:
// /job:<name>/replica:<replica>/task:<task>/device:<type>:<device_num>
//
// <name> is a short identifier conforming to the regexp
// [a-zA-Z][_a-zA-Z]*
// <type> is a supported device type (e.g. 'cpu' or 'gpu')
// <replica>, <task>, <device_num> are small non-negative integers and are
// densely allocated (except in tests).
//
// For some purposes, we also allow device patterns, which can specify
// some or none of the specific fields above, with missing components,
// or "<component>:*" indicating "any value allowed for that component.
//
// For example:
// "/job:param_server" - Consider any devices in the "param_server" job
// "/device:cpu:*" - Consider any cpu devices in any job/task/replica
// "/job:*/replica:*/task:*/device:cpu:*" - Consider any cpu devices in any
// job/task/replica
// "/job:w/replica:0/task:0/device:gpu:*" - Consider any gpu devices in
// replica 0, task 0, of job "w"
class DeviceNameUtils {
public:
// Returns a fully qualified device name given the parameters.
static string FullName(const string& job, int replica, int task,
const string& type, int id);
struct ParsedName {
void Clear() {
has_job = false;
has_replica = false;
has_task = false;
has_type = false;
has_id = false;
job.clear();
replica = 0;
task = 0;
type.clear();
id = 0;
}
bool operator==(const ParsedName& other) const {
return (has_job ? (other.has_job && job == other.job) : !other.has_job) &&
(has_replica ? (other.has_replica && replica == other.replica)
: !other.has_replica) &&
(has_task ? (other.has_task && task == other.task)
: !other.has_task) &&
(has_type ? (other.has_type && type == other.type)
: !other.has_type) &&
(has_id ? (other.has_id && id == other.id) : !other.has_id);
}
bool has_job = false;
string job;
bool has_replica = false;
int replica = 0;
bool has_task = false;
int task = 0;
bool has_type = false;
string type;
bool has_id = false;
int id = 0;
};
// Parses "fullname" into "*parsed". Returns true iff succeeds.
static bool ParseFullName(StringPiece fullname, ParsedName* parsed);
// Canonicalizes "fullname" into "*canonical_name". Uses a fully specified
// basename to fill in fields that are missing. Accepts both legacy, newer
// and local versions of the device spec. Returns the newer version of the
// device spec. If we were unable to interpret / parse "fullname" returns
// an error and *canonical_name is set to "".
static Status CanonicalizeDeviceName(StringPiece fullname,
StringPiece basename,
string* canonical_name);
// Returns true if "name" specifies any non-trivial constraint on the device.
static bool HasSomeDetails(const ParsedName& name) {
return name.has_job || name.has_replica || name.has_task || name.has_type ||
name.has_id;
}
// Returns true if more_specific is a specification of
// less_specific, i.e. everywhere that less-specific has a
// non-wildcard component value, more_specific has the same value
// for that component.
static bool IsSpecification(const ParsedName& less_specific,
const ParsedName& more_specific);
// Like IsSpecification, but the second argument "name" must have a
// non-wildcard value for all of its components.
static bool IsCompleteSpecification(const ParsedName& pattern,
const ParsedName& name);
// True iff there exists any possible complete device name that is
// a specification of both "a" and "b".
static inline bool AreCompatibleDevNames(const ParsedName& a,
const ParsedName& b) {
return IsSpecification(a, b) || IsSpecification(b, a);
}
// Merges the device specifications in "*target" and "other", and
// stores the result in "*target". Returns OK if "*target" and
// "other" are compatible, otherwise returns an error.
static Status MergeDevNames(ParsedName* target, const ParsedName& other) {
return MergeDevNames(target, other, false);
}
static Status MergeDevNames(ParsedName* target, const ParsedName& other,
bool allow_soft_placement);
// Returns true iff devices identified by 'src' and 'dst' are in the
// same address space.
static bool IsSameAddressSpace(StringPiece src, StringPiece dst);
static bool IsSameAddressSpace(const ParsedName& src, const ParsedName& dst);
// Returns the local device given its "type" and "id".
static string LocalName(StringPiece type, int id);
// Returns a short local device name (cpu:0, gpu:1, etc) based on
// the given fullname.
static string LocalName(StringPiece fullname);
// If "name" is a valid local device name (cpu:0, gpu:1, etc.),
// fills in parsed.type and parsed.id accordingly. Returns true iff
// succeeds.
static bool ParseLocalName(StringPiece name, ParsedName* parsed);
// Splits a fully-qualified device name into a task identifier and a
// relative device identifier. It first parses "name" using
// ParseFullName(), then assigns *task with everything except for
// the local device component, and assigns the relative device
// component into *device. This function will still return true if
// the task component is empty, but it requires the relative device
// component to be fully specified.
static bool SplitDeviceName(StringPiece name, string* task, string* device);
static string ParsedNameToString(const ParsedName& pn);
// Returns canonical and legacy full names for the given parsed
// device name 'pn'. The returned string names are often useful to
// look up devices from a mapping.
static std::vector<string> GetNamesForDeviceMappings(const ParsedName& pn);
// Returns canonical and legacy local names for the given parsed device name
// 'pn'. The returned string names are often useful to look up devices from a
// mapping.
static std::vector<string> GetLocalNamesForDeviceMappings(
const ParsedName& pn);
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_DEVICE_NAME_UTILS_H_
@@ -0,0 +1,46 @@
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_ENV_VAR_H_
#define TENSORFLOW_CORE_UTIL_ENV_VAR_H_
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
// Returns a boolean into "value" from the environmental variable
// "env_var_name". If it is unset, the default value is used. A string "0" or a
// case insensitive "false" is interpreted as false. A string "1" or a case
// insensitive "true" is interpreted as true. Otherwise, an error status is
// returned.
Status ReadBoolFromEnvVar(StringPiece env_var_name, bool default_val,
bool* value);
// Returns an int64 into "value" from the environmental variable "env_var_name".
// If it is unset, the default value is used.
// If the string cannot be parsed into int64, an error status is returned.
Status ReadInt64FromEnvVar(StringPiece env_var_name, int64 default_val,
int64* value);
// Returns a string into "value" from the environmental variable "env_var_name".
// If it is unset, the default value is used.
Status ReadStringFromEnvVar(StringPiece env_var_name, StringPiece default_val,
string* value);
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_ENV_VAR_H_
@@ -0,0 +1,100 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_GRAPH_EQUAL_GRAPH_DEF_H_
#define TENSORFLOW_GRAPH_EQUAL_GRAPH_DEF_H_
#include "tensorflow/core/framework/graph_def_util.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
class GraphDef;
class NodeDef;
struct EqualGraphDefOptions {
// Should internal attributes (attribute names that start with '_') be
// ignored?
bool ignore_internal_attrs = true;
};
// Determines if actual and expected are equal, ignoring versions and ordering
// of nodes, attrs, and control inputs. If the GraphDefs are different and
// diff != nullptr, *diff is set to an explanation of the difference. Note that
// we use node names to match up nodes between the graphs, and so the naming of
// nodes must be consistent.
bool EqualGraphDef(const GraphDef& actual, const GraphDef& expected,
string* diff, const EqualGraphDefOptions& options = {});
// Returns a hash of `gdef` that is consistent with EqualGraphDef. In other
// words, if two graph defs compare equal according to EqualGraphDef,
// GraphDefHash will return the same value for both of them when called
// with the same `options` that was used in the call to EqualGraphDef.
// Similarly to protobuf deterministic serialization, hash value is
// guaranteed to be stable only for a given binary. In particular, one should
// probably not persist the returned value.
uint64 GraphDefHash(const GraphDef& gdef,
const EqualGraphDefOptions& options = {});
// Determines if actual and expected are equal, ignoring: ordering of
// attrs, internal attributes (if set in `options`), and control inputs.
//
// If the NodeDefs are different and
// diff != nullptr, *diff is set to an explanation of the difference.
bool EqualNodeDef(const NodeDef& actual, const NodeDef& expected, string* diff,
const EqualGraphDefOptions& options = {});
// Returns a hash of `ndef` that is consistent with EqualNodeDef. In other
// words, if two node defs compare equal according to EqualNodeDef, NodeDefHash
// will return the same value for both of them when called with the same
// `options` that was used in the call to EqualNodeDef.
// Similarly to protobuf deterministic serialization, hash value is
// guaranteed to be stable only for a given binary. In particular, one should
// probably not persist the returned value.
uint64 NodeDefHash(const NodeDef& ndef,
const EqualGraphDefOptions& options = {});
// Determines if actual and expected are equal, ignoring ordering. If they're
// different and diff != nullptr, *diff is set to an explanation of the
// difference.
bool EqualRepeatedNodeDef(const protobuf::RepeatedPtrField<NodeDef>& actual,
const protobuf::RepeatedPtrField<NodeDef>& expected,
string* diff,
const EqualGraphDefOptions& options = {});
// Returns a hash of `ndefs` that is consistent with EqualRepeatedNodeDef.
// In other words, if two ndefs compare equal according to
// EqualRepeatedNodeDef, RepeatedNodeDefHash will return the same value for
// both of them when called with the same `options` that was used in
// the call to EqualRepeatedNodeDef.
// Similarly to protobuf deterministic serialization, hash value is
// guaranteed to be stable only for a given binary. In particular, one should
// probably not persist the returned value.
uint64 RepeatedNodeDefHash(const protobuf::RepeatedPtrField<NodeDef>& ndefs,
const EqualGraphDefOptions& options = {});
#define TF_EXPECT_GRAPH_EQ(expected, actual) \
do { \
string diff; \
EXPECT_TRUE(EqualGraphDef(actual, expected, &diff)) \
<< diff << "\nExpected:\n" \
<< SummarizeGraphDef(expected) << "\nActual:\n" \
<< SummarizeGraphDef(actual); \
} while (false)
} // namespace tensorflow
#endif // TENSORFLOW_GRAPH_EQUAL_GRAPH_DEF_H_
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,77 @@
// GENERATED FILE - DO NOT MODIFY
#ifndef tensorflow_core_util_event_proto_IMPL_H_
#define tensorflow_core_util_event_proto_IMPL_H_
#include "tensorflow/core/framework/resource_handle.pb.h"
#include "tensorflow/core/framework/resource_handle.pb_text-impl.h"
#include "tensorflow/core/framework/summary.pb.h"
#include "tensorflow/core/framework/summary.pb_text-impl.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/tensor.pb_text-impl.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/framework/tensor_shape.pb_text-impl.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/framework/types.pb_text-impl.h"
#include "tensorflow/core/lib/strings/proto_text_util.h"
#include "tensorflow/core/lib/strings/scanner.h"
#include "tensorflow/core/util/event.pb.h"
#include "tensorflow/core/util/event.pb_text.h"
namespace tensorflow {
namespace internal {
void AppendProtoDebugString(
::tensorflow::strings::ProtoTextOutput* o,
const ::tensorflow::Event& msg);
bool ProtoParseFromScanner(
::tensorflow::strings::Scanner* scanner, bool nested, bool close_curly,
::tensorflow::Event* msg);
void AppendProtoDebugString(
::tensorflow::strings::ProtoTextOutput* o,
const ::tensorflow::LogMessage& msg);
bool ProtoParseFromScanner(
::tensorflow::strings::Scanner* scanner, bool nested, bool close_curly,
::tensorflow::LogMessage* msg);
void AppendProtoDebugString(
::tensorflow::strings::ProtoTextOutput* o,
const ::tensorflow::SessionLog& msg);
bool ProtoParseFromScanner(
::tensorflow::strings::Scanner* scanner, bool nested, bool close_curly,
::tensorflow::SessionLog* msg);
void AppendProtoDebugString(
::tensorflow::strings::ProtoTextOutput* o,
const ::tensorflow::TaggedRunMetadata& msg);
bool ProtoParseFromScanner(
::tensorflow::strings::Scanner* scanner, bool nested, bool close_curly,
::tensorflow::TaggedRunMetadata* msg);
void AppendProtoDebugString(
::tensorflow::strings::ProtoTextOutput* o,
const ::tensorflow::WatchdogConfig& msg);
bool ProtoParseFromScanner(
::tensorflow::strings::Scanner* scanner, bool nested, bool close_curly,
::tensorflow::WatchdogConfig* msg);
void AppendProtoDebugString(
::tensorflow::strings::ProtoTextOutput* o,
const ::tensorflow::WorkerHeartbeatRequest& msg);
bool ProtoParseFromScanner(
::tensorflow::strings::Scanner* scanner, bool nested, bool close_curly,
::tensorflow::WorkerHeartbeatRequest* msg);
void AppendProtoDebugString(
::tensorflow::strings::ProtoTextOutput* o,
const ::tensorflow::WorkerHeartbeatResponse& msg);
bool ProtoParseFromScanner(
::tensorflow::strings::Scanner* scanner, bool nested, bool close_curly,
::tensorflow::WorkerHeartbeatResponse* msg);
} // namespace internal
} // namespace tensorflow
#endif // tensorflow_core_util_event_proto_IMPL_H_
@@ -0,0 +1,100 @@
// GENERATED FILE - DO NOT MODIFY
#ifndef tensorflow_core_util_event_proto_H_
#define tensorflow_core_util_event_proto_H_
#include "tensorflow/core/util/event.pb.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
// Enum text output for tensorflow.WorkerHealth
const char* EnumName_WorkerHealth(
::tensorflow::WorkerHealth value);
// Enum text output for tensorflow.WorkerShutdownMode
const char* EnumName_WorkerShutdownMode(
::tensorflow::WorkerShutdownMode value);
// Message-text conversion for tensorflow.Event
string ProtoDebugString(
const ::tensorflow::Event& msg);
string ProtoShortDebugString(
const ::tensorflow::Event& msg);
bool ProtoParseFromString(
const string& s,
::tensorflow::Event* msg)
TF_MUST_USE_RESULT;
// Enum text output for tensorflow.LogMessage.Level
const char* EnumName_LogMessage_Level(
::tensorflow::LogMessage_Level value);
// Message-text conversion for tensorflow.LogMessage
string ProtoDebugString(
const ::tensorflow::LogMessage& msg);
string ProtoShortDebugString(
const ::tensorflow::LogMessage& msg);
bool ProtoParseFromString(
const string& s,
::tensorflow::LogMessage* msg)
TF_MUST_USE_RESULT;
// Enum text output for tensorflow.SessionLog.SessionStatus
const char* EnumName_SessionLog_SessionStatus(
::tensorflow::SessionLog_SessionStatus value);
// Message-text conversion for tensorflow.SessionLog
string ProtoDebugString(
const ::tensorflow::SessionLog& msg);
string ProtoShortDebugString(
const ::tensorflow::SessionLog& msg);
bool ProtoParseFromString(
const string& s,
::tensorflow::SessionLog* msg)
TF_MUST_USE_RESULT;
// Message-text conversion for tensorflow.TaggedRunMetadata
string ProtoDebugString(
const ::tensorflow::TaggedRunMetadata& msg);
string ProtoShortDebugString(
const ::tensorflow::TaggedRunMetadata& msg);
bool ProtoParseFromString(
const string& s,
::tensorflow::TaggedRunMetadata* msg)
TF_MUST_USE_RESULT;
// Message-text conversion for tensorflow.WatchdogConfig
string ProtoDebugString(
const ::tensorflow::WatchdogConfig& msg);
string ProtoShortDebugString(
const ::tensorflow::WatchdogConfig& msg);
bool ProtoParseFromString(
const string& s,
::tensorflow::WatchdogConfig* msg)
TF_MUST_USE_RESULT;
// Message-text conversion for tensorflow.WorkerHeartbeatRequest
string ProtoDebugString(
const ::tensorflow::WorkerHeartbeatRequest& msg);
string ProtoShortDebugString(
const ::tensorflow::WorkerHeartbeatRequest& msg);
bool ProtoParseFromString(
const string& s,
::tensorflow::WorkerHeartbeatRequest* msg)
TF_MUST_USE_RESULT;
// Message-text conversion for tensorflow.WorkerHeartbeatResponse
string ProtoDebugString(
const ::tensorflow::WorkerHeartbeatResponse& msg);
string ProtoShortDebugString(
const ::tensorflow::WorkerHeartbeatResponse& msg);
bool ProtoParseFromString(
const string& s,
::tensorflow::WorkerHeartbeatResponse* msg)
TF_MUST_USE_RESULT;
} // namespace tensorflow
#endif // tensorflow_core_util_event_proto_H_
@@ -0,0 +1,98 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_EVENTS_WRITER_H_
#define TENSORFLOW_CORE_UTIL_EVENTS_WRITER_H_
#include <memory>
#include <string>
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/io/record_writer.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/event.pb.h"
namespace tensorflow {
class EventsWriter {
public:
#ifndef SWIG
// Prefix of version string present in the first entry of every event file.
static constexpr const char* kVersionPrefix = "brain.Event:";
static constexpr const int kCurrentVersion = 2;
#endif
// Events files typically have a name of the form
// '/some/file/path/my.file.out.events.[timestamp].[hostname][suffix]'
// To create and EventWriter, the user should provide file_prefix =
// '/some/file/path/my.file'
// The EventsWriter will append '.out.events.[timestamp].[hostname][suffix]'
// to the ultimate filename once Init() is called.
// Note that it is not recommended to simultaneously have two
// EventWriters writing to the same file_prefix.
explicit EventsWriter(const string& file_prefix);
~EventsWriter();
// Sets the event file filename and opens file for writing. If not called by
// user, will be invoked automatically by a call to FileName() or Write*().
// Returns false if the file could not be opened. Idempotent: if file exists
// and is open this is a no-op. If on the other hand the file was opened,
// but has since disappeared (e.g. deleted by another process), this will open
// a new file with a new timestamp in its filename.
Status Init();
Status InitWithSuffix(const string& suffix);
// Returns the filename for the current events file:
// filename_ = [file_prefix_].out.events.[timestamp].[hostname][suffix]
string FileName();
// Append "event" to the file. The "tensorflow::" part is for swig happiness.
void WriteEvent(const tensorflow::Event& event);
// Append "event_str", a serialized Event, to the file.
// Note that this function does NOT check that de-serializing event_str
// results in a valid Event proto. The tensorflow:: bit makes SWIG happy.
void WriteSerializedEvent(tensorflow::StringPiece event_str);
// EventWriter automatically flushes and closes on destruction, but
// these two methods are provided for users who want to write to disk sooner
// and/or check for success.
// Flush() pushes outstanding events to disk. Returns false if the
// events file could not be created, or if the file exists but could not
// be written too.
// Close() calls Flush() and then closes the current events file.
// Returns true only if both the flush and the closure were successful.
Status Flush();
Status Close();
private:
Status FileStillExists(); // OK if event_file_path_ exists.
Status InitIfNeeded();
Env* env_;
const string file_prefix_;
string file_suffix_;
string filename_;
std::unique_ptr<WritableFile> recordio_file_;
std::unique_ptr<io::RecordWriter> recordio_writer_;
int num_outstanding_events_;
TF_DISALLOW_COPY_AND_ASSIGN(EventsWriter);
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_EVENTS_WRITER_H_
@@ -0,0 +1,133 @@
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_EXAMPLE_PROTO_FAST_PARSING_H_
#define TENSORFLOW_CORE_UTIL_EXAMPLE_PROTO_FAST_PARSING_H_
#include <string>
#include <unordered_map>
#include <vector>
#include "tensorflow/core/example/example.pb.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/sparse/sparse_tensor.h"
namespace tensorflow {
namespace example {
// FastParseExampleConfig defines how to parse features in Example.
// Each sub-config is responsible for one feature identified with feautre_name.
// FastParseExampleConfig can't have two sub-configs with the same feature_name.
// dtype identifies the type of output vector and the kind of Feature expected
// in Example.
struct FastParseExampleConfig {
struct Dense {
string feature_name;
DataType dtype;
// These 2 fields correspond exactly to dense_shapes and dense_defaults in
// ParseExample op.
// Documentation is available in: tensorflow/core/ops/parsing_ops.cc
PartialTensorShape shape;
Tensor default_value;
bool variable_length;
std::size_t elements_per_stride;
};
struct Sparse {
string feature_name;
DataType dtype;
};
std::vector<Dense> dense;
std::vector<Sparse> sparse;
// If `true`, `Result::feature_stats` will contain one
// `PerExampleFeatureStats` for each serialized example in the input.
bool collect_feature_stats = false;
};
// Statistics about the features in each example passed to
// `FastParse[Single]Example()`.
//
// TODO(b/111553342): The gathered statistics currently have two limitations:
// * Feature names that appear more than once will be counted multiple times.
// * The feature values count only represents the counts for features that were
// requested in the `FastParseExampleConfig`.
// These could be addressed with additional work at runtime.
struct PerExampleFeatureStats {
// The number of feature names in an example.
size_t features_count = 0;
// The sum of the number of values in each feature that is parsed.
size_t feature_values_count = 0;
};
// This is exactly the output of TF's ParseExample Op.
// Documentation is available in: tensorflow/core/ops/parsing_ops.cc
struct Result {
std::vector<Tensor> sparse_indices;
std::vector<Tensor> sparse_values;
std::vector<Tensor> sparse_shapes;
std::vector<Tensor> dense_values;
// This vector will be populated with one element per example if
// `FastParseExampleConfig::collect_feature_stats` is set to `true`.
std::vector<PerExampleFeatureStats> feature_stats;
};
// Parses a batch of serialized Example protos and converts them into result
// according to given config.
// Given example names have to either be empty or the same size as serialized.
// example_names are used only for error messages.
Status FastParseExample(const FastParseExampleConfig& config,
gtl::ArraySlice<string> serialized,
gtl::ArraySlice<string> example_names,
thread::ThreadPool* thread_pool, Result* result);
// TODO(mrry): Move the hash table construction into the config object.
typedef FastParseExampleConfig FastParseSingleExampleConfig;
Status FastParseSingleExample(const FastParseSingleExampleConfig& config,
const string& serialized, Result* result);
// Parses a batch of serialized SequenceExample protos and converts them into
// result according to given config.
// Given example names have to either be empty or the same size as serialized.
// example_names are used only for error messages.
Status FastParseSequenceExample(
const example::FastParseExampleConfig& context_config,
const example::FastParseExampleConfig& feature_list_config,
gtl::ArraySlice<string> serialized, gtl::ArraySlice<string> example_names,
thread::ThreadPool* thread_pool, example::Result* context_result,
example::Result* feature_list_result,
std::vector<Tensor>* dense_feature_lengths);
// This function parses serialized Example and populates given example.
// It uses the same specialized parser as FastParseExample which is efficient.
// But then constructs Example which is relatively slow.
// It is exported here as a convenient API to test parser part separately.
bool TestFastParse(const string& serialized, Example* example);
} // namespace example
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_EXAMPLE_PROTO_FAST_PARSING_H_
@@ -0,0 +1,378 @@
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_EXAMPLE_PROTO_HELPER_H_
#define TENSORFLOW_CORE_UTIL_EXAMPLE_PROTO_HELPER_H_
#include <string>
#include <vector>
#include "tensorflow/core/example/example.pb.h"
#include "tensorflow/core/example/feature.pb.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/sparse/sparse_tensor.h"
// This is a set of helper methods that will make it possible to share
// tensorflow::Example proto Tensor conversion code inside the ExampleParserOp
// OpKernel as well as in external code.
namespace tensorflow {
// "Dense" feature configuration.
struct FixedLenFeature {
string key;
DataType dtype;
TensorShape shape;
Tensor default_value;
string values_output_tensor_name;
};
// "Sparse" feature configuration.
struct VarLenFeature {
string key;
DataType dtype;
string values_output_tensor_name;
string indices_output_tensor_name;
string shapes_output_tensor_name;
};
// Given a single tensorflow::Example, with an optional example name
// at a particular index within a batch, and dense and sparse feature
// configurations from fixed_len_features, var_len_features, this method
// updates the dense value tensor and the sparse values temporary vector
// of tensors. The indexing of the output vectors correspond 1:1 to the
// indexing of the feature configuration vectors.
//
// The fixed_len_features and var_len_features maps are assume to be
// have disjoint key fields from the Feature map in the tensorflow.Example
// proto.
//
// For each sparse feature, the sparse values temporary vector holds a
// tensor for each Example. Each tensor is either empty or filled, depending
// on if the sparse feature value is set for the Example. This
// temporary structure is needed because we need to know the total number
// of filled elements in the batch to get the proper final sparse tensor
// shapes allocated. After the entire batch is processed,
// GetSparseTensorShape can be used to calculate the final shapes and
// CopyIntoSparseTensor can be used to copy from the temporary vector
// into the final allocated tensors.
Status SingleExampleProtoToTensors(
const Example& example, const string& name, const int batch_index,
const std::vector<FixedLenFeature>& fixed_len_features,
const std::vector<VarLenFeature>& var_len_features,
std::vector<Tensor*>* dense_values,
std::vector<std::vector<Tensor>>* sparse_values_temporary_vector);
// The shape of the indices and values tensors associated with a SparseTensor
// are dependent on the contents of the batch.
struct VarLenFeatureBatchShapes {
TensorShape indices_shape;
TensorShape values_shape;
int max_num_features;
};
// Get the shape of the sparse values and indices tensors for the batch,
// given how many of the tensors in the temporary sparse values vector
// are actually filled.
Status GetSparseTensorShapes(const VarLenFeature& var_len_feature,
const std::vector<Tensor>& sparse_values_tmp,
const int batch_size,
VarLenFeatureBatchShapes* output_shapes);
// A method to convert a batch of tensorflow::Example protos into output
// tensors. This method is useful if there already is a batch of deserialized
// Example protos in memory (such as a serving use-case) and we do not wish
// to incur an extraneous serialize/deserialize. It is intended
// as an outside of OpKernel compatible replacement for the functionality of
// ExampleParserOp. In a serving setting, this method could be used to produce
// a feed_dict of Tensors that could bypass the ExampleParserOp.
//
// Note that unlike SingleExampleProtoToTensors, output tensors are
// allocated using a provided Allocator within this method.
Status BatchExampleProtoToTensors(
const std::vector<const Example*>& examples,
const std::vector<string>& names,
const std::vector<FixedLenFeature>& fixed_len_features,
const std::vector<VarLenFeature>& var_len_features, Allocator* allocator,
std::vector<Tensor>* output_dense_values_tensor,
std::vector<Tensor>* output_sparse_indices_tensor,
std::vector<Tensor>* output_sparse_values_tensor,
std::vector<Tensor>* output_sparse_shapes_tensor);
// Check that the given dtype is one that is compatible with
// tensorflow::Example protocol buffer feature values.
Status CheckValidType(const DataType& dtype);
// Check that the provided Feature proto message's oneof value
// matches that of the provided dtype.
Status CheckTypesMatch(const Feature& feature, const DataType& dtype,
bool* match);
// For a single Example, copy a dense feature value into an output
// dense value tensor Out at the provided out_index offset.
Status FeatureDenseCopy(const std::size_t out_index, const string& name,
const string& key, const DataType& dtype,
const TensorShape& shape, const Feature& feature,
Tensor* out);
// Copy the value a provided Tensor into an output dense_value tensor Out
// at the provided out_index offset.
void RowDenseCopy(const std::size_t& out_index, const DataType& dtype,
const Tensor& in, Tensor* out);
// For a single Example, and given sparse feature return a temporary output
// Tensor suitable for being collected in the temporary sparse value vector.
Tensor FeatureSparseCopy(const std::size_t batch, const string& key,
const DataType& dtype, const Feature& feature);
// Copy a temporary Tensor into the final sparse indices and values
// tensor at a given batch index and element offset. This method
// assumes that the indices/values Tensors have been properly allocated
// for the batch.
int64 CopyIntoSparseTensor(const Tensor& in, const int batch,
const int64 offset, Tensor* indices, Tensor* values);
// Parses the attributes passed to ParseExample.
// REQUIRES: Init must be called after construction.
class ParseExampleAttrs {
public:
template <typename ContextType>
Status Init(ContextType* ctx) {
TF_RETURN_IF_ERROR(ctx->GetAttr("sparse_types", &sparse_types));
TF_RETURN_IF_ERROR(ctx->GetAttr("Ndense", &num_dense));
TF_RETURN_IF_ERROR(ctx->GetAttr("Nsparse", &num_sparse));
TF_RETURN_IF_ERROR(ctx->GetAttr("Tdense", &dense_types));
TF_RETURN_IF_ERROR(ctx->GetAttr("dense_shapes", &dense_shapes));
// Temporary check until we start allowing a variable length outer
// dimension.
for (int i = 0; i < dense_shapes.size(); ++i) {
bool shape_ok = true;
if (dense_shapes[i].dims() == -1) {
shape_ok = false;
} else {
for (int d = 1; d < dense_shapes[i].dims(); ++d) {
if (dense_shapes[i].dim_size(d) == -1) {
shape_ok = false;
}
}
}
if (!shape_ok) {
return errors::InvalidArgument(
"dense_shapes[", i,
"] has unknown rank or unknown inner dimensions: ",
dense_shapes[i].DebugString());
}
TensorShape dense_shape;
if (dense_shapes[i].dims() > 0 && dense_shapes[i].dim_size(0) == -1) {
variable_length.push_back(true);
for (int d = 1; d < dense_shapes[i].dims(); ++d) {
dense_shape.AddDim(dense_shapes[i].dim_size(d));
}
} else {
variable_length.push_back(false);
dense_shapes[i].AsTensorShape(&dense_shape);
}
elements_per_stride.push_back(dense_shape.num_elements());
}
return FinishInit();
}
int64 num_sparse;
int64 num_dense;
std::vector<DataType> sparse_types;
std::vector<DataType> dense_types;
std::vector<PartialTensorShape> dense_shapes;
std::vector<bool> variable_length;
std::vector<std::size_t> elements_per_stride;
private:
Status FinishInit(); // for context-independent parts of Init.
};
// Parses the attributes passed to ParseSingleExample.
// REQUIRES: Init must be called after construction.
class ParseSingleExampleAttrs {
public:
template <typename ContextType>
Status Init(ContextType* ctx) {
TF_RETURN_IF_ERROR(ctx->GetAttr("sparse_keys", &sparse_keys));
TF_RETURN_IF_ERROR(ctx->GetAttr("sparse_types", &sparse_types));
TF_RETURN_IF_ERROR(ctx->GetAttr("dense_keys", &dense_keys));
TF_RETURN_IF_ERROR(ctx->GetAttr("Tdense", &dense_types));
TF_RETURN_IF_ERROR(ctx->GetAttr("dense_shapes", &dense_shapes));
int num_sparse;
TF_RETURN_IF_ERROR(ctx->GetAttr("num_sparse", &num_sparse));
if (num_sparse != sparse_keys.size() || num_sparse != sparse_types.size()) {
return errors::InvalidArgument(
"num_sparse (", num_sparse, ") must match the size of sparse_keys (",
sparse_keys.size(), ") and sparse_types (", sparse_types.size(), ")");
}
// Temporary check until we start allowing a variable length outer
// dimension.
for (int i = 0; i < dense_shapes.size(); ++i) {
bool shape_ok = true;
if (dense_shapes[i].dims() == -1) {
shape_ok = false;
} else {
for (int d = 1; d < dense_shapes[i].dims(); ++d) {
if (dense_shapes[i].dim_size(d) == -1) {
shape_ok = false;
}
}
}
if (!shape_ok) {
return errors::InvalidArgument(
"dense_shapes[", i,
"] has unknown rank or unknown inner dimensions: ",
dense_shapes[i].DebugString());
}
TensorShape dense_shape;
if (dense_shapes[i].dims() > 0 && dense_shapes[i].dim_size(0) == -1) {
variable_length.push_back(true);
for (int d = 1; d < dense_shapes[i].dims(); ++d) {
dense_shape.AddDim(dense_shapes[i].dim_size(d));
}
} else {
variable_length.push_back(false);
dense_shapes[i].AsTensorShape(&dense_shape);
}
elements_per_stride.push_back(dense_shape.num_elements());
}
return FinishInit();
}
std::vector<string> sparse_keys;
std::vector<DataType> sparse_types;
std::vector<string> dense_keys;
std::vector<DataType> dense_types;
std::vector<PartialTensorShape> dense_shapes;
std::vector<bool> variable_length;
std::vector<std::size_t> elements_per_stride;
private:
Status FinishInit(); // for context-independent parts of Init.
};
// Parses the attributes passed to ParseSequenceExample.
// REQUIRES: Init must be called after construction.
class ParseSequenceExampleAttrs {
public:
template <typename ContextType>
Status Init(ContextType* ctx) {
std::vector<string> feature_list_dense_missing_assumed_empty_tmp;
TF_RETURN_IF_ERROR(
ctx->GetAttr("feature_list_dense_missing_assumed_empty",
&feature_list_dense_missing_assumed_empty_tmp));
for (const string& feature : feature_list_dense_missing_assumed_empty_tmp) {
feature_list_dense_missing_assumed_empty.insert(feature);
}
TF_RETURN_IF_ERROR(
ctx->GetAttr("context_sparse_keys", &context_sparse_keys));
TF_RETURN_IF_ERROR(ctx->GetAttr("context_dense_keys", &context_dense_keys));
TF_RETURN_IF_ERROR(
ctx->GetAttr("feature_list_sparse_keys", &feature_list_sparse_keys));
TF_RETURN_IF_ERROR(
ctx->GetAttr("feature_list_dense_keys", &feature_list_dense_keys));
TF_RETURN_IF_ERROR(
ctx->GetAttr("context_sparse_types", &context_sparse_types));
TF_RETURN_IF_ERROR(ctx->GetAttr("Ncontext_dense", &num_context_dense));
TF_RETURN_IF_ERROR(
ctx->GetAttr("Nfeature_list_dense", &num_feature_list_dense));
TF_RETURN_IF_ERROR(ctx->GetAttr("Ncontext_sparse", &num_context_sparse));
TF_RETURN_IF_ERROR(ctx->GetAttr("Tcontext_dense", &context_dense_types));
TF_RETURN_IF_ERROR(
ctx->GetAttr("feature_list_sparse_types", &feature_list_sparse_types));
TF_RETURN_IF_ERROR(
ctx->GetAttr("feature_list_dense_types", &feature_list_dense_types));
TF_RETURN_IF_ERROR(
ctx->GetAttr("Nfeature_list_sparse", &num_feature_list_sparse));
TF_RETURN_IF_ERROR(
ctx->GetAttr("context_dense_shapes", &context_dense_shapes));
TF_RETURN_IF_ERROR(
ctx->GetAttr("feature_list_dense_shapes", &feature_list_dense_shapes));
return FinishInit();
}
std::unordered_set<string> feature_list_dense_missing_assumed_empty;
int64 num_context_sparse;
int64 num_context_dense;
int64 num_feature_list_sparse;
int64 num_feature_list_dense;
std::vector<string> context_sparse_keys;
std::vector<string> context_dense_keys;
std::vector<string> feature_list_sparse_keys;
std::vector<string> feature_list_dense_keys;
std::vector<DataType> context_sparse_types;
std::vector<DataType> context_dense_types;
std::vector<TensorShape> context_dense_shapes;
std::vector<DataType> feature_list_sparse_types;
std::vector<DataType> feature_list_dense_types;
std::vector<TensorShape> feature_list_dense_shapes;
private:
Status FinishInit(); // for context-independent parts of Init.
};
// Parses the attributes passed to ParseSingleSequenceExample.
// REQUIRES: Init must be called after construction.
class ParseSingleSequenceExampleAttrs {
public:
template <typename ContextType>
Status Init(ContextType* ctx) {
TF_RETURN_IF_ERROR(
ctx->GetAttr("context_sparse_types", &context_sparse_types));
TF_RETURN_IF_ERROR(ctx->GetAttr("Ncontext_dense", &num_context_dense));
TF_RETURN_IF_ERROR(
ctx->GetAttr("Nfeature_list_dense", &num_feature_list_dense));
TF_RETURN_IF_ERROR(ctx->GetAttr("Ncontext_sparse", &num_context_sparse));
TF_RETURN_IF_ERROR(ctx->GetAttr("Tcontext_dense", &context_dense_types));
TF_RETURN_IF_ERROR(
ctx->GetAttr("feature_list_sparse_types", &feature_list_sparse_types));
TF_RETURN_IF_ERROR(
ctx->GetAttr("feature_list_dense_types", &feature_list_dense_types));
TF_RETURN_IF_ERROR(
ctx->GetAttr("Nfeature_list_sparse", &num_feature_list_sparse));
TF_RETURN_IF_ERROR(
ctx->GetAttr("context_dense_shapes", &context_dense_shapes));
TF_RETURN_IF_ERROR(
ctx->GetAttr("feature_list_dense_shapes", &feature_list_dense_shapes));
return FinishInit();
}
int64 num_context_sparse;
int64 num_context_dense;
int64 num_feature_list_sparse;
int64 num_feature_list_dense;
std::vector<DataType> context_sparse_types;
std::vector<DataType> context_dense_types;
std::vector<TensorShape> context_dense_shapes;
std::vector<DataType> feature_list_sparse_types;
std::vector<DataType> feature_list_dense_types;
std::vector<TensorShape> feature_list_dense_shapes;
private:
Status FinishInit(); // for context-independent parts of Init.
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_EXAMPLE_PROTO_HELPER_H_
@@ -0,0 +1,89 @@
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_EXEC_ON_STALL_H_
#define TENSORFLOW_CORE_UTIL_EXEC_ON_STALL_H_
#include <functional>
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/mutex.h"
namespace tensorflow {
// An object that executes a particular function only if it
// is not deleted within the allotted number of seconds.
//
// This can be useful in diagnosing deadlocks, stalls and memory leaks
// without logging too agressively.
class ExecuteOnStall {
public:
// delay_secs: If the object still exists after this many seconds,
// execute f.
// f: The function to be executed, for example a detailed log of the
// the state of an object to which this is attached.
// poll_microseconds: The spawned thread will wake and test whether
// the destructor has been invoked this frequently.
ExecuteOnStall(int delay_secs, std::function<void()> f,
int32 poll_microseconds = 100)
: disabled_(false),
joined_(false),
env_(Env::Default()),
f_(f),
poll_microseconds_(poll_microseconds) {
deadline_ = env_->NowMicros() + 1000000 * delay_secs;
env_->SchedClosure([this]() {
while (env_->NowMicros() < deadline_) {
{
mutex_lock l(mu_);
if (disabled_) {
break;
}
}
env_->SleepForMicroseconds(poll_microseconds_);
}
{
mutex_lock l(mu_);
if (!disabled_) {
f_();
}
joined_ = true;
cond_var_.notify_all();
}
});
}
~ExecuteOnStall() {
// Wait for spawned thread to terminate.
mutex_lock l(mu_);
disabled_ = true;
if (!joined_) {
cond_var_.wait(l);
}
}
private:
mutex mu_;
condition_variable cond_var_;
bool disabled_ GUARDED_BY(mu_);
bool joined_ GUARDED_BY(mu_);
Env* env_;
std::function<void()> f_;
int64 deadline_;
int32 poll_microseconds_;
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_EXEC_ON_STALL_H_
@@ -0,0 +1,82 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_GUARDED_PHILOX_RANDOM_H_
#define TENSORFLOW_CORE_UTIL_GUARDED_PHILOX_RANDOM_H_
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/lib/random/philox_random.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
// A thread safe wrapper around a Philox generator. Example usage:
//
// GuardedRandomPhilox generator;
// generator.Init(context);
//
// // In thread safe code
// const int samples = ...;
// auto local_generator = generator.ReserveSamples128(samples);
// for (int i = 0; i < samples; i++)
// Array<uint32, 4> sample = local_generator();
// // Use sample
// }
//
class GuardedPhiloxRandom {
public:
// Must call Init to finish initialization
GuardedPhiloxRandom() : initialized_(false) {}
// Initialize the generator from attributes "seed" and "seed2".
// If both seeds are unspecified, use random seeds.
// Must be called exactly once.
Status Init(OpKernelConstruction* context);
// Initialize with given seeds.
void Init(int64 seed, int64 seed2);
void Init(random::PhiloxRandom::ResultType counter,
random::PhiloxRandom::Key key);
// Reserve a certain number of 128-bit samples.
// This function is thread safe. The returned generator is valid for the
// given number of samples, and can be used without a lock.
random::PhiloxRandom ReserveSamples128(int64 samples);
// Reserve a certain number of 32-bit samples.
random::PhiloxRandom ReserveSamples32(int64 samples) {
return ReserveSamples128((samples + 3) / 4);
}
// Reserve enough random samples in the generator for the given output count.
random::PhiloxRandom ReserveRandomOutputs(int64 output_count,
int multiplier) {
int64 conservative_sample_count = output_count * multiplier;
return ReserveSamples128(conservative_sample_count);
}
private:
mutex mu_;
random::PhiloxRandom generator_ GUARDED_BY(mu_);
bool initialized_;
TF_DISALLOW_COPY_AND_ASSIGN(GuardedPhiloxRandom);
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_GUARDED_PHILOX_RANDOM_H_
@@ -0,0 +1,28 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// The utility to check matmul autotune related flags.
#ifndef TENSORFLOW_CORE_UTIL_MATMUL_AUTOTUNE_H_
#define TENSORFLOW_CORE_UTIL_MATMUL_AUTOTUNE_H_
namespace tensorflow {
bool MatmulAutotuneEnable();
bool MatmulDoFP32ComputationFP16Input();
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_MATMUL_AUTOTUNE_H_
@@ -0,0 +1,141 @@
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_MEMMAPPED_FILE_SYSTEM_H_
#define TENSORFLOW_CORE_UTIL_MEMMAPPED_FILE_SYSTEM_H_
#include <memory>
#include <string>
#include <unordered_map>
#include "tensorflow/core/platform/env.h"
namespace tensorflow {
// A file system that uses a graph saved in memmapped format by
// MemmappedEnvWriter as a file system.
//
// The format supports saved tensors and protos. Tensors are saved at aligned
// offsets.
//
// Format specification:
// - last 8 bytes of a package is encoded offset to the directory. The encoding
// is always little endian, independently from the platform, done by functions
// EncodeUint64LittleEndian/DecodeUint64LittleEndian
// - the directory starts from the encoded offset and is saved proto
// MemmappedFileSystemDirectory with names and offsets to the regions.
// - at the offsets in the directory the file regions are stored. Tensor regions
// are aligned such way that when the package mapped to RAM they have the right
// offset to be used by ImmutableConst operator.
//
// Region naming:
// Region naming is up to the application, all of them starts from
// kMemmappedPackagePrefix. The default graph usually has name
// kMemmappedPackageDefaultGraphDef; for more details see the conversion
// utility
// third_party/tensorflow/contrib/util/convert_graphdef_memmapped_format.cc
//
// A "frozen" GraphDef can be converted into this format using
// tensorflow/contrib/util/convert_graphdef_memmapped_format
class MemmappedFileSystem : public FileSystem {
public:
// Memmapped regions use this prefix to distinguish from
// the filesystem.
#if defined(_MSC_VER)
static constexpr char* kMemmappedPackagePrefix =
#else
static constexpr char kMemmappedPackagePrefix[] =
#endif
"memmapped_package://";
// The default graphdef in the package.
#if defined(_MSC_VER)
static constexpr char* kMemmappedPackageDefaultGraphDef =
#else
static constexpr char kMemmappedPackageDefaultGraphDef[] =
#endif
"memmapped_package://.";
MemmappedFileSystem();
~MemmappedFileSystem() override = default;
Status FileExists(const string& fname) override;
Status NewRandomAccessFile(
const string& filename,
std::unique_ptr<RandomAccessFile>* result) override;
Status NewReadOnlyMemoryRegionFromFile(
const string& filename,
std::unique_ptr<ReadOnlyMemoryRegion>* result) override;
// All these functions return Unimplemented error, the memmapped storage is
// read only.
Status NewWritableFile(const string& fname,
std::unique_ptr<WritableFile>* result) override;
Status NewAppendableFile(const string& fname,
std::unique_ptr<WritableFile>* result) override;
Status GetChildren(const string& dir, std::vector<string>* r) override;
Status GetMatchingPaths(const string& pattern,
std::vector<string>* results) override;
Status DeleteFile(const string& f) override;
Status CreateDir(const string& d) override;
Status DeleteDir(const string& d) override;
Status RenameFile(const string& s, const string& t) override;
// These functions are implemented.
Status GetFileSize(const string& f, uint64* s) override;
// Currently just returns size.
Status Stat(const string& fname, FileStatistics* stat) override;
// Initializes filesystem from a file in memmapped format.
Status InitializeFromFile(Env* env, const string& filename);
// Checks if the filename has a correct prefix.
static bool IsMemmappedPackageFilename(const string& filename);
static bool IsWellFormedMemmappedPackageFilename(const string& filename);
private:
struct FileRegion {
FileRegion(uint64 o, uint64 l) : offset(o), length(l) {}
uint64 offset; // Offset from the beginning of the file.
uint64 length; // Length of the region.
};
using DirectoryType = std::unordered_map<string, FileRegion>;
const void* GetMemoryWithOffset(uint64 offset) const;
std::unique_ptr<ReadOnlyMemoryRegion> mapped_memory_;
DirectoryType directory_;
TF_DISALLOW_COPY_AND_ASSIGN(MemmappedFileSystem);
};
class MemmappedEnv : public EnvWrapper {
public:
explicit MemmappedEnv(Env* env);
~MemmappedEnv() override = default;
Status GetFileSystemForFile(const string& fname,
FileSystem** result) override;
Status GetRegisteredFileSystemSchemes(std::vector<string>* schemes) override;
Status InitializeFromFile(const string& filename);
protected:
std::unique_ptr<MemmappedFileSystem> memmapped_file_system_;
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_MEMMAPPED_FILE_SYSTEM_H_
@@ -0,0 +1,476 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: tensorflow/core/util/memmapped_file_system.proto
#ifndef PROTOBUF_INCLUDED_tensorflow_2fcore_2futil_2fmemmapped_5ffile_5fsystem_2eproto
#define PROTOBUF_INCLUDED_tensorflow_2fcore_2futil_2fmemmapped_5ffile_5fsystem_2eproto
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 3006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3006000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
#define PROTOBUF_INTERNAL_EXPORT_protobuf_tensorflow_2fcore_2futil_2fmemmapped_5ffile_5fsystem_2eproto
namespace protobuf_tensorflow_2fcore_2futil_2fmemmapped_5ffile_5fsystem_2eproto {
// Internal implementation detail -- do not use these members.
struct TableStruct {
static const ::google::protobuf::internal::ParseTableField entries[];
static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
static const ::google::protobuf::internal::ParseTable schema[2];
static const ::google::protobuf::internal::FieldMetadata field_metadata[];
static const ::google::protobuf::internal::SerializationTable serialization_table[];
static const ::google::protobuf::uint32 offsets[];
};
void AddDescriptors();
} // namespace protobuf_tensorflow_2fcore_2futil_2fmemmapped_5ffile_5fsystem_2eproto
namespace tensorflow {
class MemmappedFileSystemDirectory;
class MemmappedFileSystemDirectoryDefaultTypeInternal;
extern MemmappedFileSystemDirectoryDefaultTypeInternal _MemmappedFileSystemDirectory_default_instance_;
class MemmappedFileSystemDirectoryElement;
class MemmappedFileSystemDirectoryElementDefaultTypeInternal;
extern MemmappedFileSystemDirectoryElementDefaultTypeInternal _MemmappedFileSystemDirectoryElement_default_instance_;
} // namespace tensorflow
namespace google {
namespace protobuf {
template<> ::tensorflow::MemmappedFileSystemDirectory* Arena::CreateMaybeMessage<::tensorflow::MemmappedFileSystemDirectory>(Arena*);
template<> ::tensorflow::MemmappedFileSystemDirectoryElement* Arena::CreateMaybeMessage<::tensorflow::MemmappedFileSystemDirectoryElement>(Arena*);
} // namespace protobuf
} // namespace google
namespace tensorflow {
// ===================================================================
class MemmappedFileSystemDirectoryElement : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:tensorflow.MemmappedFileSystemDirectoryElement) */ {
public:
MemmappedFileSystemDirectoryElement();
virtual ~MemmappedFileSystemDirectoryElement();
MemmappedFileSystemDirectoryElement(const MemmappedFileSystemDirectoryElement& from);
inline MemmappedFileSystemDirectoryElement& operator=(const MemmappedFileSystemDirectoryElement& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
MemmappedFileSystemDirectoryElement(MemmappedFileSystemDirectoryElement&& from) noexcept
: MemmappedFileSystemDirectoryElement() {
*this = ::std::move(from);
}
inline MemmappedFileSystemDirectoryElement& operator=(MemmappedFileSystemDirectoryElement&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
static const MemmappedFileSystemDirectoryElement& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const MemmappedFileSystemDirectoryElement* internal_default_instance() {
return reinterpret_cast<const MemmappedFileSystemDirectoryElement*>(
&_MemmappedFileSystemDirectoryElement_default_instance_);
}
static constexpr int kIndexInFileMessages =
0;
void UnsafeArenaSwap(MemmappedFileSystemDirectoryElement* other);
void Swap(MemmappedFileSystemDirectoryElement* other);
friend void swap(MemmappedFileSystemDirectoryElement& a, MemmappedFileSystemDirectoryElement& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
inline MemmappedFileSystemDirectoryElement* New() const final {
return CreateMaybeMessage<MemmappedFileSystemDirectoryElement>(NULL);
}
MemmappedFileSystemDirectoryElement* New(::google::protobuf::Arena* arena) const final {
return CreateMaybeMessage<MemmappedFileSystemDirectoryElement>(arena);
}
void CopyFrom(const ::google::protobuf::Message& from) final;
void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const MemmappedFileSystemDirectoryElement& from);
void MergeFrom(const MemmappedFileSystemDirectoryElement& from);
void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(MemmappedFileSystemDirectoryElement* other);
protected:
explicit MemmappedFileSystemDirectoryElement(::google::protobuf::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
return _internal_metadata_.raw_arena_ptr();
}
public:
::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// string name = 2;
void clear_name();
static const int kNameFieldNumber = 2;
const ::std::string& name() const;
void set_name(const ::std::string& value);
#if LANG_CXX11
void set_name(::std::string&& value);
#endif
void set_name(const char* value);
void set_name(const char* value, size_t size);
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
" string fields are deprecated and will be removed in a"
" future release.")
::std::string* unsafe_arena_release_name();
PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
" string fields are deprecated and will be removed in a"
" future release.")
void unsafe_arena_set_allocated_name(
::std::string* name);
// uint64 offset = 1;
void clear_offset();
static const int kOffsetFieldNumber = 1;
::google::protobuf::uint64 offset() const;
void set_offset(::google::protobuf::uint64 value);
// @@protoc_insertion_point(class_scope:tensorflow.MemmappedFileSystemDirectoryElement)
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::uint64 offset_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_tensorflow_2fcore_2futil_2fmemmapped_5ffile_5fsystem_2eproto::TableStruct;
};
// -------------------------------------------------------------------
class MemmappedFileSystemDirectory : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:tensorflow.MemmappedFileSystemDirectory) */ {
public:
MemmappedFileSystemDirectory();
virtual ~MemmappedFileSystemDirectory();
MemmappedFileSystemDirectory(const MemmappedFileSystemDirectory& from);
inline MemmappedFileSystemDirectory& operator=(const MemmappedFileSystemDirectory& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
MemmappedFileSystemDirectory(MemmappedFileSystemDirectory&& from) noexcept
: MemmappedFileSystemDirectory() {
*this = ::std::move(from);
}
inline MemmappedFileSystemDirectory& operator=(MemmappedFileSystemDirectory&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
static const MemmappedFileSystemDirectory& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const MemmappedFileSystemDirectory* internal_default_instance() {
return reinterpret_cast<const MemmappedFileSystemDirectory*>(
&_MemmappedFileSystemDirectory_default_instance_);
}
static constexpr int kIndexInFileMessages =
1;
void UnsafeArenaSwap(MemmappedFileSystemDirectory* other);
void Swap(MemmappedFileSystemDirectory* other);
friend void swap(MemmappedFileSystemDirectory& a, MemmappedFileSystemDirectory& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
inline MemmappedFileSystemDirectory* New() const final {
return CreateMaybeMessage<MemmappedFileSystemDirectory>(NULL);
}
MemmappedFileSystemDirectory* New(::google::protobuf::Arena* arena) const final {
return CreateMaybeMessage<MemmappedFileSystemDirectory>(arena);
}
void CopyFrom(const ::google::protobuf::Message& from) final;
void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const MemmappedFileSystemDirectory& from);
void MergeFrom(const MemmappedFileSystemDirectory& from);
void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(MemmappedFileSystemDirectory* other);
protected:
explicit MemmappedFileSystemDirectory(::google::protobuf::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
return _internal_metadata_.raw_arena_ptr();
}
public:
::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// repeated .tensorflow.MemmappedFileSystemDirectoryElement element = 1;
int element_size() const;
void clear_element();
static const int kElementFieldNumber = 1;
::tensorflow::MemmappedFileSystemDirectoryElement* mutable_element(int index);
::google::protobuf::RepeatedPtrField< ::tensorflow::MemmappedFileSystemDirectoryElement >*
mutable_element();
const ::tensorflow::MemmappedFileSystemDirectoryElement& element(int index) const;
::tensorflow::MemmappedFileSystemDirectoryElement* add_element();
const ::google::protobuf::RepeatedPtrField< ::tensorflow::MemmappedFileSystemDirectoryElement >&
element() const;
// @@protoc_insertion_point(class_scope:tensorflow.MemmappedFileSystemDirectory)
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::RepeatedPtrField< ::tensorflow::MemmappedFileSystemDirectoryElement > element_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_tensorflow_2fcore_2futil_2fmemmapped_5ffile_5fsystem_2eproto::TableStruct;
};
// ===================================================================
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// MemmappedFileSystemDirectoryElement
// uint64 offset = 1;
inline void MemmappedFileSystemDirectoryElement::clear_offset() {
offset_ = GOOGLE_ULONGLONG(0);
}
inline ::google::protobuf::uint64 MemmappedFileSystemDirectoryElement::offset() const {
// @@protoc_insertion_point(field_get:tensorflow.MemmappedFileSystemDirectoryElement.offset)
return offset_;
}
inline void MemmappedFileSystemDirectoryElement::set_offset(::google::protobuf::uint64 value) {
offset_ = value;
// @@protoc_insertion_point(field_set:tensorflow.MemmappedFileSystemDirectoryElement.offset)
}
// string name = 2;
inline void MemmappedFileSystemDirectoryElement::clear_name() {
name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline const ::std::string& MemmappedFileSystemDirectoryElement::name() const {
// @@protoc_insertion_point(field_get:tensorflow.MemmappedFileSystemDirectoryElement.name)
return name_.Get();
}
inline void MemmappedFileSystemDirectoryElement::set_name(const ::std::string& value) {
name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:tensorflow.MemmappedFileSystemDirectoryElement.name)
}
#if LANG_CXX11
inline void MemmappedFileSystemDirectoryElement::set_name(::std::string&& value) {
name_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:tensorflow.MemmappedFileSystemDirectoryElement.name)
}
#endif
inline void MemmappedFileSystemDirectoryElement::set_name(const char* value) {
GOOGLE_DCHECK(value != NULL);
name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:tensorflow.MemmappedFileSystemDirectoryElement.name)
}
inline void MemmappedFileSystemDirectoryElement::set_name(const char* value,
size_t size) {
name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:tensorflow.MemmappedFileSystemDirectoryElement.name)
}
inline ::std::string* MemmappedFileSystemDirectoryElement::mutable_name() {
// @@protoc_insertion_point(field_mutable:tensorflow.MemmappedFileSystemDirectoryElement.name)
return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* MemmappedFileSystemDirectoryElement::release_name() {
// @@protoc_insertion_point(field_release:tensorflow.MemmappedFileSystemDirectoryElement.name)
return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void MemmappedFileSystemDirectoryElement::set_allocated_name(::std::string* name) {
if (name != NULL) {
} else {
}
name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:tensorflow.MemmappedFileSystemDirectoryElement.name)
}
inline ::std::string* MemmappedFileSystemDirectoryElement::unsafe_arena_release_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.MemmappedFileSystemDirectoryElement.name)
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
inline void MemmappedFileSystemDirectoryElement::unsafe_arena_set_allocated_name(
::std::string* name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (name != NULL) {
} else {
}
name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
name, GetArenaNoVirtual());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.MemmappedFileSystemDirectoryElement.name)
}
// -------------------------------------------------------------------
// MemmappedFileSystemDirectory
// repeated .tensorflow.MemmappedFileSystemDirectoryElement element = 1;
inline int MemmappedFileSystemDirectory::element_size() const {
return element_.size();
}
inline void MemmappedFileSystemDirectory::clear_element() {
element_.Clear();
}
inline ::tensorflow::MemmappedFileSystemDirectoryElement* MemmappedFileSystemDirectory::mutable_element(int index) {
// @@protoc_insertion_point(field_mutable:tensorflow.MemmappedFileSystemDirectory.element)
return element_.Mutable(index);
}
inline ::google::protobuf::RepeatedPtrField< ::tensorflow::MemmappedFileSystemDirectoryElement >*
MemmappedFileSystemDirectory::mutable_element() {
// @@protoc_insertion_point(field_mutable_list:tensorflow.MemmappedFileSystemDirectory.element)
return &element_;
}
inline const ::tensorflow::MemmappedFileSystemDirectoryElement& MemmappedFileSystemDirectory::element(int index) const {
// @@protoc_insertion_point(field_get:tensorflow.MemmappedFileSystemDirectory.element)
return element_.Get(index);
}
inline ::tensorflow::MemmappedFileSystemDirectoryElement* MemmappedFileSystemDirectory::add_element() {
// @@protoc_insertion_point(field_add:tensorflow.MemmappedFileSystemDirectory.element)
return element_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::tensorflow::MemmappedFileSystemDirectoryElement >&
MemmappedFileSystemDirectory::element() const {
// @@protoc_insertion_point(field_list:tensorflow.MemmappedFileSystemDirectory.element)
return element_;
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// -------------------------------------------------------------------
// @@protoc_insertion_point(namespace_scope)
} // namespace tensorflow
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_INCLUDED_tensorflow_2fcore_2futil_2fmemmapped_5ffile_5fsystem_2eproto
@@ -0,0 +1,32 @@
// GENERATED FILE - DO NOT MODIFY
#ifndef tensorflow_core_util_memmapped_file_system_proto_IMPL_H_
#define tensorflow_core_util_memmapped_file_system_proto_IMPL_H_
#include "tensorflow/core/lib/strings/proto_text_util.h"
#include "tensorflow/core/lib/strings/scanner.h"
#include "tensorflow/core/util/memmapped_file_system.pb.h"
#include "tensorflow/core/util/memmapped_file_system.pb_text.h"
namespace tensorflow {
namespace internal {
void AppendProtoDebugString(
::tensorflow::strings::ProtoTextOutput* o,
const ::tensorflow::MemmappedFileSystemDirectoryElement& msg);
bool ProtoParseFromScanner(
::tensorflow::strings::Scanner* scanner, bool nested, bool close_curly,
::tensorflow::MemmappedFileSystemDirectoryElement* msg);
void AppendProtoDebugString(
::tensorflow::strings::ProtoTextOutput* o,
const ::tensorflow::MemmappedFileSystemDirectory& msg);
bool ProtoParseFromScanner(
::tensorflow::strings::Scanner* scanner, bool nested, bool close_curly,
::tensorflow::MemmappedFileSystemDirectory* msg);
} // namespace internal
} // namespace tensorflow
#endif // tensorflow_core_util_memmapped_file_system_proto_IMPL_H_
@@ -0,0 +1,34 @@
// GENERATED FILE - DO NOT MODIFY
#ifndef tensorflow_core_util_memmapped_file_system_proto_H_
#define tensorflow_core_util_memmapped_file_system_proto_H_
#include "tensorflow/core/util/memmapped_file_system.pb.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
// Message-text conversion for tensorflow.MemmappedFileSystemDirectoryElement
string ProtoDebugString(
const ::tensorflow::MemmappedFileSystemDirectoryElement& msg);
string ProtoShortDebugString(
const ::tensorflow::MemmappedFileSystemDirectoryElement& msg);
bool ProtoParseFromString(
const string& s,
::tensorflow::MemmappedFileSystemDirectoryElement* msg)
TF_MUST_USE_RESULT;
// Message-text conversion for tensorflow.MemmappedFileSystemDirectory
string ProtoDebugString(
const ::tensorflow::MemmappedFileSystemDirectory& msg);
string ProtoShortDebugString(
const ::tensorflow::MemmappedFileSystemDirectory& msg);
bool ProtoParseFromString(
const string& s,
::tensorflow::MemmappedFileSystemDirectory* msg)
TF_MUST_USE_RESULT;
} // namespace tensorflow
#endif // tensorflow_core_util_memmapped_file_system_proto_H_
@@ -0,0 +1,53 @@
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_MEMMAPPED_FILE_SYSTEM_WRITER_H_
#define TENSORFLOW_CORE_UTIL_MEMMAPPED_FILE_SYSTEM_WRITER_H_
#include <memory>
#include <vector>
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/util/memmapped_file_system.h"
#include "tensorflow/core/util/memmapped_file_system.pb.h"
namespace tensorflow {
// A class for saving into the memmapped format that can be read by
// MemmappedFileSystem.
class MemmappedFileSystemWriter {
public:
MemmappedFileSystemWriter() = default;
~MemmappedFileSystemWriter() = default;
Status InitializeToFile(Env* env, const string& filename);
Status SaveTensor(const Tensor& tensor, const string& element_name);
Status SaveProtobuf(const protobuf::MessageLite& message,
const string& element_name);
// Writes out the directory of regions and closes the output file.
Status FlushAndClose();
private:
Status AdjustAlignment(uint64 alignment);
void AddToDirectoryElement(const string& element_name);
MemmappedFileSystemDirectory directory_;
// The current offset in the file, to support alignment.
uint64 output_file_offset_ = 0;
std::unique_ptr<WritableFile> output_file_;
TF_DISALLOW_COPY_AND_ASSIGN(MemmappedFileSystemWriter);
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_MEMMAPPED_FILE_SYSTEM_WRITER_H_
@@ -0,0 +1,52 @@
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_MIRROR_PAD_MODE_H_
#define TENSORFLOW_CORE_UTIL_MIRROR_PAD_MODE_H_
// This file contains helper routines to deal with padding in various ops and
// kernels.
#include <string>
#include "tensorflow/core/lib/core/status.h"
namespace tensorflow {
// REFLECT: Border elements are not mirrored to padded regions.
// SYMMETRIC: Border elements are mirrored to padded regions.
//
// For example, if two elements are padded to the right of an array [1, 2, 3],
// then the result is [1, 2, 3, 2, 1] for REFLECT mode, and is [1, 2, 3, 3, 2]
// for SYMMETRIC mode.
enum class MirrorPadMode {
REFLECT = 1,
SYMMETRIC = 2,
};
// Return the string containing the list of valid padding modes, that can be
// used as an Attr() in REGISTER_OP.
string GetMirrorPadModeAttrString();
// Forward declaration to avoid including core/framework/graph.proto.
class NodeDef;
// Specialization to parse an attribute directly into a MirrorPadMode enum.
Status GetNodeAttr(const NodeDef& node_def, StringPiece attr_name,
MirrorPadMode* value);
} // end namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_MIRROR_PAD_MODE_H_
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,50 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_OVERFLOW_H_
#define TENSORFLOW_CORE_UTIL_OVERFLOW_H_
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
// Multiply two nonnegative int64's, returning negative for overflow
inline int64 MultiplyWithoutOverflow(const int64 x, const int64 y) {
// Multiply in uint64 rather than int64 since signed overflow is undefined.
// Negative values will wrap around to large unsigned values in the casts
// (see section 4.7 [conv.integral] of the C++14 standard).
const uint64 ux = x;
const uint64 uy = y;
const uint64 uxy = ux * uy;
// Check if we overflow uint64, using a cheap check if both inputs are small
if (TF_PREDICT_FALSE((ux | uy) >> 32 != 0)) {
// Ensure nonnegativity. Note that negative numbers will appear "large"
// to the unsigned comparisons above.
CHECK(x >= 0 && y >= 0);
// Otherwise, detect overflow using a division
if (ux != 0 && uxy / ux != uy) return -1;
}
// Cast back to signed. Any negative value will signal an error.
return static_cast<int64>(uxy);
}
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_OVERFLOW_H_
@@ -0,0 +1,53 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_PADDING_H_
#define TENSORFLOW_CORE_UTIL_PADDING_H_
// This file contains helper routines to deal with padding in various ops and
// kernels.
#include <string>
#include "tensorflow/core/lib/core/status.h"
namespace tensorflow {
class NodeDef;
// Padding: the padding we apply to the input tensor along the rows and columns
// dimensions. This is usually used to make sure that the spatial dimensions do
// not shrink when we progress with convolutions. Two types of padding are
// supported:
// VALID: No padding is carried out.
// SAME: The pad value is computed so that the output will have the same
// dimensions as the input.
// The padded area is zero-filled.
enum Padding {
VALID = 1, // No padding.
SAME = 2, // Input and output layers have the same size.
};
// Return the string containing the list of valid padding types, that can be
// used as an Attr() in REGISTER_OP.
string GetPaddingAttrString();
// Specialization to parse an attribute directly into a Padding enum.
Status GetNodeAttr(const NodeDef& node_def, StringPiece attr_name,
Padding* value);
} // end namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_PADDING_H_
@@ -0,0 +1,134 @@
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_UTIL_PERMUTATION_INPUT_ITERATOR_H_
#define TENSORFLOW_UTIL_PERMUTATION_INPUT_ITERATOR_H_
#include <iostream>
#include <iterator>
namespace tensorflow {
template <typename ValueType, typename InputIteratorT, typename IndexIteratorT,
typename OffsetT = ptrdiff_t>
class PermutationInputIterator {
public:
// Required iterator traits
typedef PermutationInputIterator self_type; ///< My own type
typedef OffsetT difference_type; ///< Type to express the result of
///< subtracting one iterator from another
typedef ValueType
value_type; ///< The type of the element the iterator can point to
typedef ValueType* pointer; ///< The type of a pointer to an element the
///< iterator can point to
typedef ValueType reference; ///< The type of a reference to an element the
///< iterator can point to
typedef std::random_access_iterator_tag
iterator_category; ///< The iterator category
private:
InputIteratorT input_itr;
IndexIteratorT index_itr;
public:
/// Constructor
__host__ __device__ __forceinline__ PermutationInputIterator(
InputIteratorT input_itr, ///< Input iterator to wrap
IndexIteratorT index_itr) ///< Conversion functor to wrap
: input_itr(input_itr), index_itr(index_itr) {}
/// Postfix increment
__host__ __device__ __forceinline__ self_type operator++(int) {
self_type retval = *this;
index_itr++;
return retval;
}
/// Prefix increment
__host__ __device__ __forceinline__ self_type operator++() {
index_itr++;
return *this;
}
/// Indirection
__host__ __device__ __forceinline__ reference operator*() const {
return input_itr[*index_itr];
}
/// Addition
template <typename Distance>
__host__ __device__ __forceinline__ self_type operator+(Distance n) const {
self_type retval(input_itr, index_itr + n);
return retval;
}
/// Addition assignment
template <typename Distance>
__host__ __device__ __forceinline__ self_type& operator+=(Distance n) {
index_itr += n;
return *this;
}
/// Subtraction
template <typename Distance>
__host__ __device__ __forceinline__ self_type operator-(Distance n) const {
self_type retval(input_itr, index_itr - n);
return retval;
}
/// Subtraction assignment
template <typename Distance>
__host__ __device__ __forceinline__ self_type& operator-=(Distance n) {
index_itr -= n;
return *this;
}
/// Distance
__host__ __device__ __forceinline__ difference_type
operator-(self_type other) const {
return index_itr - other.index_itr;
}
/// Array subscript
template <typename Distance>
__host__ __device__ __forceinline__ reference operator[](Distance n) const {
return input_itr[index_itr[n]];
}
/// Structure dereference
__host__ __device__ __forceinline__ pointer operator->() {
return input_itr + *index_itr;
}
/// Equal to
__host__ __device__ __forceinline__ bool operator==(const self_type& rhs) {
return (index_itr == rhs.index_itr && input_itr == rhs.input_itr);
}
/// Not equal to
__host__ __device__ __forceinline__ bool operator!=(const self_type& rhs) {
return !(*this == rhs);
}
/// ostream operator
friend std::ostream& operator<<(std::ostream& os, const self_type& itr) {
return os;
}
};
} // end namespace tensorflow
#endif // TENSORFLOW_UTIL_PERMUTATION_INPUT_ITERATOR_H_
+33
View File
@@ -0,0 +1,33 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_PORT_H_
#define TENSORFLOW_CORE_UTIL_PORT_H_
namespace tensorflow {
// Returns true if GOOGLE_CUDA is defined.
bool IsGoogleCudaEnabled();
// Returns true if GOOGLE_CUDA is defined, and the given CUDA version supports
// half-precision matrix multiplications and convolution operations.
bool CudaSupportsHalfMatMulAndConv();
// Returns true if INTEL_MKL is defined
bool IsMklEnabled();
} // end namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_PORT_H_
@@ -0,0 +1,354 @@
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_UTIL_PRESIZED_CUCKOO_MAP_H_
#define TENSORFLOW_UTIL_PRESIZED_CUCKOO_MAP_H_
#include <algorithm>
#include <vector>
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/platform/macros.h"
namespace tensorflow {
// Class for efficiently storing key->value mappings when the size is
// known in advance and the keys are pre-hashed into uint64s.
// Keys should have "good enough" randomness (be spread across the
// entire 64 bit space).
//
// Important: Clients wishing to use deterministic keys must
// ensure that their keys fall in the range 0 .. (uint64max-1);
// the table uses 2^64-1 as the "not occupied" flag.
//
// Inserted keys must be unique, and there are no update
// or delete functions (until some subsequent use of this table
// requires them).
//
// Threads must synchronize their access to a PresizedCuckooMap.
//
// The cuckoo hash table is 4-way associative (each "bucket" has 4
// "slots" for key/value entries). Uses breadth-first-search to find
// a good cuckoo path with less data movement (see
// http://www.cs.cmu.edu/~dga/papers/cuckoo-eurosys14.pdf )
namespace presized_cuckoo_map {
// Utility function to compute (x * y) >> 64, or "multiply high".
// On x86-64, this is a single instruction, but not all platforms
// support the __uint128_t type, so we provide a generic
// implementation as well.
inline uint64 multiply_high_u64(uint64 x, uint64 y) {
#if defined(__SIZEOF_INT128__)
return (uint64)(((__uint128_t)x * (__uint128_t)y) >> 64);
#else
// For platforms without int128 support, do it the long way.
uint64 x_lo = x & 0xffffffff;
uint64 x_hi = x >> 32;
uint64 buckets_lo = y & 0xffffffff;
uint64 buckets_hi = y >> 32;
uint64 prod_hi = x_hi * buckets_hi;
uint64 prod_lo = x_lo * buckets_lo;
uint64 prod_mid1 = x_hi * buckets_lo;
uint64 prod_mid2 = x_lo * buckets_hi;
uint64 carry =
((prod_mid1 & 0xffffffff) + (prod_mid2 & 0xffffffff) + (prod_lo >> 32)) >>
32;
return prod_hi + (prod_mid1 >> 32) + (prod_mid2 >> 32) + carry;
#endif
}
} // namespace presized_cuckoo_map
template <class value>
class PresizedCuckooMap {
public:
// The key type is fixed as a pre-hashed key for this specialized use.
typedef uint64 key_type;
explicit PresizedCuckooMap(uint64 num_entries) { Clear(num_entries); }
void Clear(uint64 num_entries) {
cpq_.reset(new CuckooPathQueue());
double n(num_entries);
n /= kLoadFactor;
num_buckets_ = (static_cast<uint64>(n) / kSlotsPerBucket);
// Very small cuckoo tables don't work, because the probability
// of having same-bucket hashes is large. We compromise for those
// uses by having a larger static starting size.
num_buckets_ += 32;
Bucket empty_bucket;
for (int i = 0; i < kSlotsPerBucket; i++) {
empty_bucket.keys[i] = kUnusedSlot;
}
buckets_.clear();
buckets_.resize(num_buckets_, empty_bucket);
}
// Returns false if k is already in table or if the table
// is full; true otherwise.
bool InsertUnique(const key_type k, const value& v) {
uint64 tk = key_transform(k);
uint64 b1 = fast_map_to_buckets(tk);
uint64 b2 = fast_map_to_buckets(h2(tk));
// Merged find and duplicate checking.
uint64 target_bucket = 0;
int target_slot = kNoSpace;
for (auto bucket : {b1, b2}) {
Bucket* bptr = &buckets_[bucket];
for (int slot = 0; slot < kSlotsPerBucket; slot++) {
if (bptr->keys[slot] == k) { // Duplicates are not allowed.
return false;
} else if (target_slot == kNoSpace && bptr->keys[slot] == kUnusedSlot) {
target_bucket = bucket;
target_slot = slot;
}
}
}
if (target_slot != kNoSpace) {
InsertInternal(tk, v, target_bucket, target_slot);
return true;
}
return CuckooInsert(tk, v, b1, b2);
}
// Returns true if found. Sets *out = value.
bool Find(const key_type k, value* out) const {
uint64 tk = key_transform(k);
return FindInBucket(k, fast_map_to_buckets(tk), out) ||
FindInBucket(k, fast_map_to_buckets(h2(tk)), out);
}
int64 MemoryUsed() const {
return sizeof(PresizedCuckooMap<value>) + sizeof(CuckooPathQueue);
}
private:
static constexpr int kSlotsPerBucket = 4;
// The load factor is chosen slightly conservatively for speed and
// to avoid the need for a table rebuild on insertion failure.
// 0.94 is achievable, but 0.85 is faster and keeps the code simple
// at the cost of a small amount of memory.
// NOTE: 0 < kLoadFactor <= 1.0
static constexpr double kLoadFactor = 0.85;
// Cuckoo insert: The maximum number of entries to scan should be ~400
// (Source: Personal communication with Michael Mitzenmacher; empirical
// experiments validate.). After trying 400 candidate locations, declare
// the table full - it's probably full of unresolvable cycles. Less than
// 400 reduces max occupancy; much more results in very poor performance
// around the full point. For (2,4) a max BFS path len of 5 results in ~682
// nodes to visit, calculated below, and is a good value.
static constexpr uint8 kMaxBFSPathLen = 5;
// Constants for BFS cuckoo path search:
// The visited list must be maintained for all but the last level of search
// in order to trace back the path. The BFS search has two roots
// and each can go to a total depth (including the root) of 5.
// The queue must be sized for 2 * \sum_{k=0...4}{kSlotsPerBucket^k} = 682.
// The visited queue, however, does not need to hold the deepest level,
// and so it is sized 2 * \sum{k=0...3}{kSlotsPerBucket^k} = 170
static constexpr int kMaxQueueSize = 682;
static constexpr int kVisitedListSize = 170;
static constexpr int kNoSpace = -1; // SpaceAvailable return
static constexpr uint64 kUnusedSlot = ~(0ULL);
// Buckets are organized with key_types clustered for access speed
// and for compactness while remaining aligned.
struct Bucket {
key_type keys[kSlotsPerBucket];
value values[kSlotsPerBucket];
};
// Insert uses the BFS optimization (search before moving) to reduce
// the number of cache lines dirtied during search.
struct CuckooPathEntry {
uint64 bucket;
int depth;
int parent; // To index in the visited array.
int parent_slot; // Which slot in our parent did we come from? -1 == root.
};
// CuckooPathQueue is a trivial circular queue for path entries.
// The caller is responsible for not inserting more than kMaxQueueSize
// entries. Each PresizedCuckooMap has one (heap-allocated) CuckooPathQueue
// that it reuses across inserts.
class CuckooPathQueue {
public:
CuckooPathQueue() : head_(0), tail_(0) {}
void push_back(CuckooPathEntry e) {
queue_[tail_] = e;
tail_ = (tail_ + 1) % kMaxQueueSize;
}
CuckooPathEntry pop_front() {
CuckooPathEntry& e = queue_[head_];
head_ = (head_ + 1) % kMaxQueueSize;
return e;
}
bool empty() const { return head_ == tail_; }
bool full() const { return ((tail_ + 1) % kMaxQueueSize) == head_; }
void reset() { head_ = tail_ = 0; }
private:
CuckooPathEntry queue_[kMaxQueueSize];
int head_;
int tail_;
};
typedef std::array<CuckooPathEntry, kMaxBFSPathLen> CuckooPath;
// Callers are expected to have pre-hashed the keys into a uint64
// and are expected to be able to handle (a very low rate) of
// collisions, OR must ensure that their keys are always in
// the range 0 - (uint64max - 1). This transforms 'not found flag'
// keys into something else.
inline uint64 key_transform(const key_type k) const {
return k + (k == kUnusedSlot);
}
// h2 performs a very quick mix of h to generate the second bucket hash.
// Assumes there is plenty of remaining entropy in the initial h.
inline uint64 h2(uint64 h) const {
const uint64 m = 0xc6a4a7935bd1e995;
return m * ((h >> 32) | (h << 32));
}
// alt_bucket identifies the "other" bucket for key k, where
// other is "the one that isn't bucket b"
inline uint64 alt_bucket(key_type k, uint64 b) const {
if (fast_map_to_buckets(k) != b) {
return fast_map_to_buckets(k);
}
return fast_map_to_buckets(h2(k));
}
inline void InsertInternal(key_type k, const value& v, uint64 b, int slot) {
Bucket* bptr = &buckets_[b];
bptr->keys[slot] = k;
bptr->values[slot] = v;
}
// For the associative cuckoo table, check all of the slots in
// the bucket to see if the key is present.
bool FindInBucket(key_type k, uint64 b, value* out) const {
const Bucket& bref = buckets_[b];
for (int i = 0; i < kSlotsPerBucket; i++) {
if (bref.keys[i] == k) {
*out = bref.values[i];
return true;
}
}
return false;
}
// returns either kNoSpace or the index of an
// available slot (0 <= slot < kSlotsPerBucket)
inline int SpaceAvailable(uint64 bucket) const {
const Bucket& bref = buckets_[bucket];
for (int i = 0; i < kSlotsPerBucket; i++) {
if (bref.keys[i] == kUnusedSlot) {
return i;
}
}
return kNoSpace;
}
inline void CopyItem(uint64 src_bucket, int src_slot, uint64 dst_bucket,
int dst_slot) {
Bucket& src_ref = buckets_[src_bucket];
Bucket& dst_ref = buckets_[dst_bucket];
dst_ref.keys[dst_slot] = src_ref.keys[src_slot];
dst_ref.values[dst_slot] = src_ref.values[src_slot];
}
bool CuckooInsert(key_type k, const value& v, uint64 b1, uint64 b2) {
int visited_end = 0;
cpq_->reset();
cpq_->push_back({b1, 1, 0, 0}); // Note depth starts at 1.
cpq_->push_back({b2, 1, 0, 0});
while (!cpq_->empty()) {
CuckooPathEntry e = cpq_->pop_front();
int free_slot;
free_slot = SpaceAvailable(e.bucket);
if (free_slot != kNoSpace) {
while (e.depth > 1) {
// "copy" instead of "swap" because one entry is always zero.
// After, write target key/value over top of last copied entry.
CuckooPathEntry parent = visited_[e.parent];
CopyItem(parent.bucket, e.parent_slot, e.bucket, free_slot);
free_slot = e.parent_slot;
e = parent;
}
InsertInternal(k, v, e.bucket, free_slot);
return true;
} else {
if (e.depth < (kMaxBFSPathLen)) {
auto parent_index = visited_end;
visited_[visited_end] = e;
visited_end++;
// Don't always start with the same slot, to even out the path depth.
int start_slot = (k + e.bucket) % kSlotsPerBucket;
const Bucket& bref = buckets_[e.bucket];
for (int i = 0; i < kSlotsPerBucket; i++) {
int slot = (start_slot + i) % kSlotsPerBucket;
uint64 next_bucket = alt_bucket(bref.keys[slot], e.bucket);
// Optimization: Avoid single-step cycles (from e, don't
// add a child node that is actually e's parent).
uint64 e_parent_bucket = visited_[e.parent].bucket;
if (next_bucket != e_parent_bucket) {
cpq_->push_back({next_bucket, e.depth + 1, parent_index, slot});
}
}
}
}
}
LOG(WARNING) << "Cuckoo path finding failed: Table too small?";
return false;
}
inline uint64 fast_map_to_buckets(uint64 x) const {
// Map x (uniform in 2^64) to the range [0, num_buckets_ -1]
// using Lemire's alternative to modulo reduction:
// http://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
// Instead of x % N, use (x * N) >> 64.
return presized_cuckoo_map::multiply_high_u64(x, num_buckets_);
}
// Set upon initialization: num_entries / kLoadFactor / kSlotsPerBucket.
uint64 num_buckets_;
std::vector<Bucket> buckets_;
std::unique_ptr<CuckooPathQueue> cpq_;
CuckooPathEntry visited_[kVisitedListSize];
TF_DISALLOW_COPY_AND_ASSIGN(PresizedCuckooMap);
};
} // namespace tensorflow
#endif // TENSORFLOW_UTIL_PRESIZED_CUCKOO_MAP_H_
@@ -0,0 +1,692 @@
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Inline functions for parsing the protocol buffers wire format.
//
// These functions have been optimized at the expense of safety.
// They are broken out into a separate file for readability but are
// not intended for use by clients other than the decode_proto op.
//
// The calling code in the decode_proto op does some fairly
// complicated things to ensure that this code is called
// safely. Changes to this code should be thoroughly fuzz tested.
#ifndef TENSORFLOW_CORE_UTIL_PROTO_DECODE_H_
#define TENSORFLOW_CORE_UTIL_PROTO_DECODE_H_
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace internal {
using tensorflow::protobuf::internal::WireFormatLite;
using tensorflow::protobuf::io::CodedInputStream;
using tensorflow::protobuf::io::CodedOutputStream;
using tensorflow::protobuf::io::StringOutputStream;
// Converts an uint64 to an int64 without loss of information.
// Unsigned values greater than INT64_MAX are represented as
// negative numbers by wrapping (same as twos-complement bit equivalence).
inline int64 WrapUnsignedAsSigned64(uint64 unsigned_value) {
// For a detailed explanation of why this works to wrap unsigned ints, see
// http://stackoverflow.com/questions/13150449/efficient-unsigned-to-signed-cast-avoiding-implementation-defined-behavior
// Both if tests should be optimized out.
if (unsigned_value <= INT64_MAX) {
return static_cast<int64>(unsigned_value);
}
// The C++ spec allows an architecture where this test is required.
if (unsigned_value >= INT64_MIN) {
return static_cast<int64>(unsigned_value - INT64_MIN) + INT64_MIN;
}
return 0; // This should never occur.
}
// Converts an uint32 to an int32 without loss of information.
// Unsigned values greater than INT_MAX are represented as
// negative numbers by wrapping (same as twos-complement bit equivalence).
inline int32 WrapUnsignedAsSigned32(uint32 unsigned_value) {
// For a detailed explanation of why this works to wrap unsigned ints, see
// http://stackoverflow.com/questions/13150449/efficient-unsigned-to-signed-cast-avoiding-implementation-defined-behavior
// Both if tests should be optimized out.
if (unsigned_value <= INT_MAX) {
return static_cast<int32>(unsigned_value);
}
// The C++ spec allows an architecture where this test is required.
if (unsigned_value >= INT_MIN) {
return static_cast<int32>(unsigned_value - INT_MIN) + INT_MIN;
}
return 0; // This should never occur.
}
// Reads a single varint32 from a byte array.
// It is the caller's responsibility to ensure that there is enough
// space in the buffer.
// The ok value will be set to false if the buffer does not contain
// a valid varint.
inline const uint8* ReadVarint64FromArray(const uint8* buffer, bool* ok,
uint64* value);
// Reads a single varint32 from a byte array.
// It is the caller's responsibility to ensure that there is enough
// space in the buffer.
// The ok value will be set to false if the buffer does not contain
// a valid varint.
// This is slightly less efficient than the private version in
// coded_stream.cc but we duplicate less code by calling
// the 64 bit version instead of copying the code.
inline const uint8* ReadVarint32FromArray(const uint8* buffer, bool* ok,
uint32* value) {
uint64 tmp;
const uint8* buf = ReadVarint64FromArray(buffer, ok, &tmp);
*value = tmp & 0xffffffff;
return buf;
}
// Reads a single proto field value from a byte array into an array.
// The array is part of a Tensor that was allocated by the caller
// with type TensorType, while DeclaredType is the proto field type.
template <class TensorType, enum WireFormatLite::FieldType DeclaredType>
const uint8* ReadFromArray(const uint8* buf, TensorType* value);
template <>
inline const uint8* ReadFromArray<int64, WireFormatLite::TYPE_INT32>(
const uint8* buf, int64* value) {
uint32 temp;
bool unused_ok; // The Counting pass would have failed if this were corrupt.
buf = ReadVarint32FromArray(buf, &unused_ok, &temp);
*value = static_cast<int64>(temp);
return buf;
}
template <>
inline const uint8* ReadFromArray<int32, WireFormatLite::TYPE_INT32>(
const uint8* buf, int32* value) {
uint32 temp;
bool unused_ok; // The Counting pass would have failed if this were corrupt.
buf = ReadVarint32FromArray(buf, &unused_ok, &temp);
*value = static_cast<int32>(temp);
return buf;
}
template <>
inline const uint8* ReadFromArray<int64, WireFormatLite::TYPE_INT64>(
const uint8* buf, int64* value) {
uint64 temp;
bool unused_ok; // The Counting pass would have failed if this were corrupt.
buf = ReadVarint64FromArray(buf, &unused_ok, &temp);
*value = WrapUnsignedAsSigned64(temp);
return buf;
}
template <>
inline const uint8* ReadFromArray<uint64, WireFormatLite::TYPE_UINT32>(
const uint8* buf, uint64* value) {
uint32 temp;
bool unused_ok; // The Counting pass would have failed if this were corrupt.
buf = ReadVarint32FromArray(buf, &unused_ok, &temp);
*value = temp;
return buf;
}
template <>
inline const uint8* ReadFromArray<uint32, WireFormatLite::TYPE_UINT32>(
const uint8* buf, uint32* value) {
bool unused_ok; // The Counting pass would have failed if this were corrupt.
return ReadVarint32FromArray(buf, &unused_ok, value);
}
template <>
inline const uint8* ReadFromArray<uint64, WireFormatLite::TYPE_UINT64>(
const uint8* buf, uint64* value) {
bool unused_ok; // The Counting pass would have failed if this were corrupt.
return ReadVarint64FromArray(buf, &unused_ok, value);
}
template <>
inline const uint8* ReadFromArray<int64, WireFormatLite::TYPE_SINT32>(
const uint8* buf, int64* value) {
uint64 temp;
bool unused_ok; // The Counting pass would have failed if this were corrupt.
buf = ReadVarint64FromArray(buf, &unused_ok, &temp);
*value = WireFormatLite::ZigZagDecode32(temp);
return buf;
}
template <>
inline const uint8* ReadFromArray<int32, WireFormatLite::TYPE_SINT32>(
const uint8* buf, int32* value) {
uint32 temp;
bool unused_ok; // The Counting pass would have failed if this were corrupt.
buf = ReadVarint32FromArray(buf, &unused_ok, &temp);
*value = WireFormatLite::ZigZagDecode32(temp);
return buf;
}
template <>
inline const uint8* ReadFromArray<int64, WireFormatLite::TYPE_SINT64>(
const uint8* buf, int64* value) {
uint64 temp;
bool unused_ok; // The Counting pass would have failed if this were corrupt.
buf = ReadVarint64FromArray(buf, &unused_ok, &temp);
*value = WireFormatLite::ZigZagDecode64(temp);
return buf;
}
template <>
inline const uint8* ReadFromArray<uint64, WireFormatLite::TYPE_FIXED32>(
const uint8* buf, uint64* value) {
uint32 temp;
buf = WireFormatLite::ReadPrimitiveFromArray<uint32,
WireFormatLite::TYPE_FIXED32>(
buf, &temp);
*value = temp;
return buf;
}
template <>
inline const uint8* ReadFromArray<uint32, WireFormatLite::TYPE_FIXED32>(
const uint8* buf, uint32* value) {
uint32 temp;
buf = WireFormatLite::ReadPrimitiveFromArray<uint32,
WireFormatLite::TYPE_FIXED32>(
buf, &temp);
*value = WrapUnsignedAsSigned32(temp);
return buf;
}
template <>
inline const uint8* ReadFromArray<uint64, WireFormatLite::TYPE_FIXED64>(
const uint8* buf, uint64* value) {
protobuf_uint64 temp;
buf = WireFormatLite::ReadPrimitiveFromArray<protobuf_uint64,
WireFormatLite::TYPE_FIXED64>(
buf, &temp);
*value = WrapUnsignedAsSigned64(temp);
return buf;
}
template <>
inline const uint8* ReadFromArray<int64, WireFormatLite::TYPE_SFIXED32>(
const uint8* buf, int64* value) {
int32 temp;
buf = WireFormatLite::ReadPrimitiveFromArray<int32,
WireFormatLite::TYPE_SFIXED32>(
buf, &temp);
*value = temp;
return buf;
}
template <>
inline const uint8* ReadFromArray<int32, WireFormatLite::TYPE_SFIXED32>(
const uint8* buf, int32* value) {
return WireFormatLite::ReadPrimitiveFromArray<int32,
WireFormatLite::TYPE_SFIXED32>(
buf, value);
}
template <>
inline const uint8* ReadFromArray<int64, WireFormatLite::TYPE_SFIXED64>(
const uint8* buf, int64* value) {
protobuf_int64 temp;
buf = WireFormatLite::ReadPrimitiveFromArray<protobuf_int64,
WireFormatLite::TYPE_SFIXED64>(
buf, &temp);
*value = temp;
return buf;
}
template <>
inline const uint8* ReadFromArray<float, WireFormatLite::TYPE_FLOAT>(
const uint8* buf, float* value) {
return WireFormatLite::ReadPrimitiveFromArray<float,
WireFormatLite::TYPE_FLOAT>(
buf, value);
}
template <>
inline const uint8* ReadFromArray<double, WireFormatLite::TYPE_FLOAT>(
const uint8* buf, double* value) {
float temp;
buf =
WireFormatLite::ReadPrimitiveFromArray<float, WireFormatLite::TYPE_FLOAT>(
buf, &temp);
*value = temp;
return buf;
}
template <>
inline const uint8* ReadFromArray<double, WireFormatLite::TYPE_DOUBLE>(
const uint8* buf, double* value) {
return WireFormatLite::ReadPrimitiveFromArray<double,
WireFormatLite::TYPE_DOUBLE>(
buf, value);
}
template <>
inline const uint8* ReadFromArray<bool, WireFormatLite::TYPE_BOOL>(
const uint8* buf, bool* value) {
uint64 temp;
bool unused_ok; // The Counting pass would have failed if this were corrupt.
buf = ReadVarint64FromArray(buf, &unused_ok, &temp);
*value = temp != 0;
return buf;
}
template <>
inline const uint8* ReadFromArray<int, WireFormatLite::TYPE_ENUM>(
const uint8* buf, int* value) {
uint32 temp;
bool unused_ok; // The Counting pass would have failed if this were corrupt.
buf = ReadVarint32FromArray(buf, &unused_ok, &temp);
*value = static_cast<int>(temp);
return buf;
}
// Reads packed values from an array.
// Stride is set to 1 for repeated fields, and 0 for non-repeated fields
// (where any value overwrites previous values).
template <class TensorType, enum WireFormatLite::FieldType DeclaredType>
inline int ReadPackedPrimitives(const void* bufp, const size_t len,
const int index, const int stride,
void* datap) {
const uint8* buf = reinterpret_cast<const uint8*>(bufp);
const uint8* bound = buf + len;
TensorType* data = reinterpret_cast<TensorType*>(datap) + index;
int count;
// This could overrun the bound by stride-1. This is defended
// against in the caller, where it ensures that the input buffer
// contains complete values.
for (count = 0; buf < bound; count += stride) {
buf = ReadFromArray<TensorType, DeclaredType>(buf, data + count);
}
return count;
}
// Reads a primitive value field from a serialized proto.
// The value is parsed from the serialized format, then static_cast
// to the desired type for TensorFlow and stored.
template <class ValueType, class TensorType,
enum WireFormatLite::FieldType DeclaredType>
inline Status ReadPrimitive(CodedInputStream* input, int index, void* data) {
ValueType v;
if (!WireFormatLite::ReadPrimitive<ValueType, DeclaredType>(input, &v)) {
return errors::DataLoss("Failed reading primitive");
}
reinterpret_cast<TensorType*>(data)[index] = v;
return Status::OK();
}
// Reads a string, submessage, or other variable-length field from a
// serialized proto.
// May read all or part of a repeated field.
inline Status ReadBytes(CodedInputStream* input, int index, void* datap) {
string* data = reinterpret_cast<string*>(datap) + index;
if (!WireFormatLite::ReadBytes(input, data)) {
return errors::DataLoss("Failed reading bytes");
}
return Status::OK();
}
// Reads a tag-delimited field (TYPE_GROUP) from a serialized proto,
// as a bytestring.
inline Status ReadGroupBytes(CodedInputStream* input, int field_number,
int index, void* datap) {
// WireFormatLite::SkipField has an option to emit the
// skipped bytes to an output stream. We could do better by implementing our
// own scanner but this is simpler for now.
// TODO(nix): there is a faster way to grab TYPE_GROUP bytes by relying
// on input->IsFlat() == true and using input->GetDirectBufferPointer()
// with input->CurrentPosition().
string* data = reinterpret_cast<string*>(datap) + index;
StringOutputStream string_stream(data);
CodedOutputStream out(&string_stream);
if (!WireFormatLite::SkipField(
input,
WireFormatLite::MakeTag(field_number,
WireFormatLite::WIRETYPE_START_GROUP),
&out)) {
return errors::DataLoss("Failed reading group");
}
return Status::OK();
}
// Reads a single field value from a CodedInputStream into a tensor.
inline Status ReadValue(CodedInputStream* input,
WireFormatLite::FieldType field_type, int field_number,
DataType dtype, int index, void* datap) {
// Dispatch to the appropriately typed field reader based on the schema type.
switch (field_type) {
case WireFormatLite::TYPE_DOUBLE:
return ReadPrimitive<double, double, WireFormatLite::TYPE_DOUBLE>(
input, index, datap);
case WireFormatLite::TYPE_FLOAT:
switch (dtype) {
case DataType::DT_DOUBLE:
return ReadPrimitive<float, double, WireFormatLite::TYPE_FLOAT>(
input, index, datap);
case DataType::DT_FLOAT:
return ReadPrimitive<float, float, WireFormatLite::TYPE_FLOAT>(
input, index, datap);
default:
return errors::DataLoss("Failed reading TYPE_FLOAT for ",
DataTypeString(dtype));
}
case WireFormatLite::TYPE_INT64:
return ReadPrimitive<protobuf_int64, int64, WireFormatLite::TYPE_INT64>(
input, index, datap);
case WireFormatLite::TYPE_UINT64:
return ReadPrimitive<protobuf_uint64, uint64,
WireFormatLite::TYPE_UINT64>(input, index, datap);
case WireFormatLite::TYPE_INT32:
switch (dtype) {
case DataType::DT_INT64:
return ReadPrimitive<int32, int64, WireFormatLite::TYPE_INT32>(
input, index, datap);
case DataType::DT_INT32:
return ReadPrimitive<int32, int32, WireFormatLite::TYPE_INT32>(
input, index, datap);
default:
return errors::DataLoss("Failed reading TYPE_INT32 for ",
DataTypeString(dtype));
}
case WireFormatLite::TYPE_FIXED64:
return ReadPrimitive<protobuf_uint64, uint64,
WireFormatLite::TYPE_FIXED64>(input, index, datap);
case WireFormatLite::TYPE_FIXED32:
switch (dtype) {
case DataType::DT_UINT64:
return ReadPrimitive<uint32, uint64, WireFormatLite::TYPE_FIXED32>(
input, index, datap);
case DataType::DT_UINT32:
return ReadPrimitive<uint32, uint32, WireFormatLite::TYPE_FIXED32>(
input, index, datap);
default:
return errors::DataLoss("Failed reading TYPE_FIXED32 for ",
DataTypeString(dtype));
}
case WireFormatLite::TYPE_BOOL:
return ReadPrimitive<bool, bool, WireFormatLite::TYPE_BOOL>(input, index,
datap);
case WireFormatLite::TYPE_STRING:
return ReadBytes(input, index, datap);
case WireFormatLite::TYPE_GROUP:
return ReadGroupBytes(input, field_number, index, datap);
case WireFormatLite::TYPE_MESSAGE:
return ReadBytes(input, index, datap);
case WireFormatLite::TYPE_BYTES:
return ReadBytes(input, index, datap);
case WireFormatLite::TYPE_UINT32:
switch (dtype) {
case DataType::DT_UINT64:
return ReadPrimitive<uint32, uint64, WireFormatLite::TYPE_UINT32>(
input, index, datap);
case DataType::DT_UINT32:
return ReadPrimitive<uint32, uint32, WireFormatLite::TYPE_UINT32>(
input, index, datap);
default:
return errors::DataLoss("Failed reading TYPE_UINT32 for ",
DataTypeString(dtype));
}
case WireFormatLite::TYPE_ENUM:
return ReadPrimitive<int32, int32, WireFormatLite::TYPE_ENUM>(
input, index, datap);
case WireFormatLite::TYPE_SFIXED32:
switch (dtype) {
case DataType::DT_INT64:
return ReadPrimitive<int32, int64, WireFormatLite::TYPE_SFIXED32>(
input, index, datap);
case DataType::DT_INT32:
return ReadPrimitive<int32, int32, WireFormatLite::TYPE_SFIXED32>(
input, index, datap);
default:
return errors::DataLoss("Failed reading TYPE_SFIXED32 for ",
DataTypeString(dtype));
}
case WireFormatLite::TYPE_SFIXED64:
return ReadPrimitive<protobuf_int64, int64,
WireFormatLite::TYPE_SFIXED64>(input, index, datap);
case WireFormatLite::TYPE_SINT32:
switch (dtype) {
case DataType::DT_INT64:
return ReadPrimitive<int32, int64, WireFormatLite::TYPE_SINT32>(
input, index, datap);
case DataType::DT_INT32:
return ReadPrimitive<int32, int32, WireFormatLite::TYPE_SINT32>(
input, index, datap);
default:
return errors::DataLoss("Failed reading TYPE_SINT32 for ",
DataTypeString(dtype));
}
case WireFormatLite::TYPE_SINT64:
return ReadPrimitive<protobuf_int64, int64, WireFormatLite::TYPE_SINT64>(
input, index, datap);
// default: intentionally omitted in order to enable static checking.
}
// Unreachable.
return errors::DataLoss("Failed reading unknown wire type");
}
// Reads and stores a length-delimited list of values.
inline Status ReadPackedFromArray(const void* buf, size_t buf_size,
const WireFormatLite::FieldType field_type,
const int field_number, const DataType dtype,
const int stride, int* index, void* data) {
// Dispatch to the appropriately typed field reader based on the schema type.
switch (field_type) {
case WireFormatLite::TYPE_DOUBLE:
*index += ReadPackedPrimitives<double, WireFormatLite::TYPE_DOUBLE>(
buf, buf_size, *index, stride, data);
return Status::OK();
case WireFormatLite::TYPE_FLOAT:
switch (dtype) {
case DataType::DT_DOUBLE:
*index += ReadPackedPrimitives<double, WireFormatLite::TYPE_FLOAT>(
buf, buf_size, *index, stride, data);
return Status::OK();
case DataType::DT_FLOAT:
*index += ReadPackedPrimitives<float, WireFormatLite::TYPE_FLOAT>(
buf, buf_size, *index, stride, data);
return Status::OK();
default:
return errors::DataLoss("Failed reading TYPE_FLOAT for ",
DataTypeString(dtype));
}
case WireFormatLite::TYPE_INT64:
*index += ReadPackedPrimitives<int64, WireFormatLite::TYPE_INT64>(
buf, buf_size, *index, stride, data);
return Status::OK();
case WireFormatLite::TYPE_UINT64:
*index += ReadPackedPrimitives<uint64, WireFormatLite::TYPE_UINT64>(
buf, buf_size, *index, stride, data);
return Status::OK();
case WireFormatLite::TYPE_INT32:
switch (dtype) {
case DataType::DT_INT64:
*index += ReadPackedPrimitives<int64, WireFormatLite::TYPE_INT32>(
buf, buf_size, *index, stride, data);
return Status::OK();
case DataType::DT_INT32:
*index += ReadPackedPrimitives<int32, WireFormatLite::TYPE_INT32>(
buf, buf_size, *index, stride, data);
return Status::OK();
default:
return errors::DataLoss("Failed reading TYPE_INT32 for ",
DataTypeString(dtype));
}
case WireFormatLite::TYPE_FIXED64:
*index += ReadPackedPrimitives<uint64, WireFormatLite::TYPE_FIXED64>(
buf, buf_size, *index, stride, data);
return Status::OK();
case WireFormatLite::TYPE_FIXED32:
switch (dtype) {
case DataType::DT_UINT64:
*index += ReadPackedPrimitives<uint64, WireFormatLite::TYPE_FIXED32>(
buf, buf_size, *index, stride, data);
return Status::OK();
case DataType::DT_UINT32:
*index += ReadPackedPrimitives<uint32, WireFormatLite::TYPE_FIXED32>(
buf, buf_size, *index, stride, data);
return Status::OK();
default:
return errors::DataLoss("Failed reading TYPE_FIXED32 for ",
DataTypeString(dtype));
}
case WireFormatLite::TYPE_BOOL:
*index += ReadPackedPrimitives<bool, WireFormatLite::TYPE_BOOL>(
buf, buf_size, *index, stride, data);
return Status::OK();
case WireFormatLite::TYPE_STRING:
case WireFormatLite::TYPE_GROUP:
case WireFormatLite::TYPE_MESSAGE:
case WireFormatLite::TYPE_BYTES:
return errors::DataLoss("Non-primitive type encountered as packed");
case WireFormatLite::TYPE_UINT32:
switch (dtype) {
case DataType::DT_UINT64:
*index += ReadPackedPrimitives<uint64, WireFormatLite::TYPE_UINT32>(
buf, buf_size, *index, stride, data);
return Status::OK();
case DataType::DT_UINT32:
*index += ReadPackedPrimitives<uint32, WireFormatLite::TYPE_UINT32>(
buf, buf_size, *index, stride, data);
return Status::OK();
default:
return errors::DataLoss("Failed reading TYPE_UINT32 for ",
DataTypeString(dtype));
}
case WireFormatLite::TYPE_ENUM:
*index += ReadPackedPrimitives<int32, WireFormatLite::TYPE_ENUM>(
buf, buf_size, *index, stride, data);
return Status::OK();
case WireFormatLite::TYPE_SFIXED32:
switch (dtype) {
case DataType::DT_INT64:
*index += ReadPackedPrimitives<int64, WireFormatLite::TYPE_SFIXED32>(
buf, buf_size, *index, stride, data);
return Status::OK();
case DataType::DT_INT32:
*index += ReadPackedPrimitives<int32, WireFormatLite::TYPE_SFIXED32>(
buf, buf_size, *index, stride, data);
return Status::OK();
default:
return errors::DataLoss("Failed reading TYPE_INT32 for ",
DataTypeString(dtype));
}
case WireFormatLite::TYPE_SFIXED64:
*index += ReadPackedPrimitives<int64, WireFormatLite::TYPE_SFIXED64>(
buf, buf_size, *index, stride, data);
return Status::OK();
case WireFormatLite::TYPE_SINT32:
switch (dtype) {
case DataType::DT_INT64:
*index += ReadPackedPrimitives<int64, WireFormatLite::TYPE_SINT32>(
buf, buf_size, *index, stride, data);
return Status::OK();
case DataType::DT_INT32:
*index += ReadPackedPrimitives<int32, WireFormatLite::TYPE_SINT32>(
buf, buf_size, *index, stride, data);
return Status::OK();
default:
return errors::DataLoss("Failed reading TYPE_SINT32 for ",
DataTypeString(dtype));
}
case WireFormatLite::TYPE_SINT64:
*index += ReadPackedPrimitives<int64, WireFormatLite::TYPE_SINT64>(
buf, buf_size, *index, stride, data);
return Status::OK();
// default: intentionally omitted in order to enable static checking.
}
// Unreachable.
return errors::DataLoss("Failed reading unknown wire type");
}
// Reads a varint from the given buffer, write it to *value, and return the
// new buffer pointer.
// This was copied from coded_stream.cc where it is private.
// Important: This routine may read as much as kMaxVarintBytes from
// the buffer. It is the caller's responsibility to make sure that there is
// enough space in the buffer.
inline const uint8* ReadVarint64FromArray(const uint8* buffer, bool* ok,
uint64* value) {
const uint8* ptr = buffer;
uint32 b;
// Splitting into 32-bit pieces gives better performance on 32-bit
// processors.
uint32 part0 = 0, part1 = 0, part2 = 0;
b = *(ptr++);
part0 = b;
if (!(b & 0x80)) goto done;
part0 -= 0x80;
b = *(ptr++);
part0 += b << 7;
if (!(b & 0x80)) goto done;
part0 -= 0x80 << 7;
b = *(ptr++);
part0 += b << 14;
if (!(b & 0x80)) goto done;
part0 -= 0x80 << 14;
b = *(ptr++);
part0 += b << 21;
if (!(b & 0x80)) goto done;
part0 -= 0x80 << 21;
b = *(ptr++);
part1 = b;
if (!(b & 0x80)) goto done;
part1 -= 0x80;
b = *(ptr++);
part1 += b << 7;
if (!(b & 0x80)) goto done;
part1 -= 0x80 << 7;
b = *(ptr++);
part1 += b << 14;
if (!(b & 0x80)) goto done;
part1 -= 0x80 << 14;
b = *(ptr++);
part1 += b << 21;
if (!(b & 0x80)) goto done;
part1 -= 0x80 << 21;
b = *(ptr++);
part2 = b;
if (!(b & 0x80)) goto done;
part2 -= 0x80;
b = *(ptr++);
part2 += b << 7;
if (!(b & 0x80)) goto done;
// "part2 -= 0x80 << 7" is irrelevant because (0x80 << 7) << 56 is 0.
// We have overrun the maximum size of a varint (10 bytes). Assume
// the data is corrupt.
*ok = false;
return ptr;
done:
*ok = true;
*value = (static_cast<uint64>(part0)) | (static_cast<uint64>(part1) << 28) |
(static_cast<uint64>(part2) << 56);
return ptr;
}
} // namespace internal
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_PROTO_DECODE_H_
@@ -0,0 +1,76 @@
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_PROTO_DESCRIPTOR_POOL_REGISTRY_H_
#define TENSORFLOW_CORE_UTIL_PROTO_DESCRIPTOR_POOL_REGISTRY_H_
#include <functional>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/hash/hash.h"
#include "tensorflow/core/platform/protobuf.h"
namespace tensorflow {
class DescriptorPoolRegistry {
public:
typedef std::function<Status(
tensorflow::protobuf::DescriptorPool const** desc_pool,
std::unique_ptr<tensorflow::protobuf::DescriptorPool>* owned_desc_pool)>
DescriptorPoolFn;
// Returns a pointer to a global DescriptorPoolRegistry object.
static DescriptorPoolRegistry* Global();
// Returns a pointer to a descriptor pool function for the given source.
DescriptorPoolFn* Get(const string& source);
// Registers a descriptor pool factory.
void Register(const string& source, const DescriptorPoolFn& pool_fn);
private:
std::map<string, DescriptorPoolFn> fns_;
};
namespace descriptor_pool_registration {
class DescriptorPoolRegistration {
public:
DescriptorPoolRegistration(
const string& source,
const DescriptorPoolRegistry::DescriptorPoolFn& pool_fn) {
DescriptorPoolRegistry::Global()->Register(source, pool_fn);
}
};
} // namespace descriptor_pool_registration
#define REGISTER_DESCRIPTOR_POOL(source, pool_fn) \
REGISTER_DESCRIPTOR_POOL_UNIQ_HELPER(__COUNTER__, source, pool_fn)
#define REGISTER_DESCRIPTOR_POOL_UNIQ_HELPER(ctr, source, pool_fn) \
REGISTER_DESCRIPTOR_POOL_UNIQ(ctr, source, pool_fn)
#define REGISTER_DESCRIPTOR_POOL_UNIQ(ctr, source, pool_fn) \
static descriptor_pool_registration::DescriptorPoolRegistration \
descriptor_pool_registration_fn_##ctr(source, pool_fn)
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_PROTO_DESCRIPTOR_POOL_REGISTRY_H_
@@ -0,0 +1,42 @@
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_PROTO_DESCRIPTORS_H_
#define TENSORFLOW_CORE_UTIL_PROTO_DESCRIPTORS_H_
#include <memory>
#include <string>
#include "tensorflow/core/platform/protobuf.h"
namespace tensorflow {
class Env;
class Status;
// Get a `DescriptorPool` object from the named `descriptor_source`.
// `descriptor_source` may be a path to a file accessible to TensorFlow, in
// which case it is parsed as a `FileDescriptorSet` and used to build the
// `DescriptorPool`.
//
// `owned_desc_pool` will be filled in with the same pointer as `desc_pool` if
// the caller should take ownership.
extern tensorflow::Status GetDescriptorPool(
tensorflow::Env* env, string const& descriptor_source,
tensorflow::protobuf::DescriptorPool const** desc_pool,
std::unique_ptr<tensorflow::protobuf::DescriptorPool>* owned_desc_pool);
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_PROTO_DESCRIPTORS_H_
@@ -0,0 +1,33 @@
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_PROTO_PROTO_UTILS_H_
#define TENSORFLOW_CORE_UTIL_PROTO_PROTO_UTILS_H_
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/platform/protobuf.h"
namespace tensorflow {
namespace proto_utils {
using tensorflow::protobuf::FieldDescriptor;
// Returns true if the proto field type can be converted to the tensor dtype.
bool IsCompatibleType(FieldDescriptor::Type field_type, DataType dtype);
} // namespace proto_utils
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_PROTO_PROTO_UTILS_H_
@@ -0,0 +1,80 @@
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_PTR_UTIL_H_
#define TENSORFLOW_CORE_UTIL_PTR_UTIL_H_
// Utility functions for pointers.
#include <stddef.h>
#include <memory>
#include <type_traits>
#include <utility>
namespace tensorflow {
namespace helper {
// Trait to select overloads and return types for MakeUnique.
template <typename T>
struct MakeUniqueResult {
using scalar = std::unique_ptr<T>;
};
template <typename T>
struct MakeUniqueResult<T[]> {
using array = std::unique_ptr<T[]>;
};
template <typename T, size_t N>
struct MakeUniqueResult<T[N]> {
using invalid = void;
};
} // namespace helper
// Transfers ownership of a raw pointer to a std::unique_ptr of deduced type.
// Example:
// X* NewX(int, int);
// auto x = WrapUnique(NewX(1, 2)); // 'x' is std::unique_ptr<X>.
//
// WrapUnique is useful for capturing the output of a raw pointer factory.
// However, prefer 'MakeUnique<T>(args...) over 'WrapUnique(new T(args...))'.
// auto x = WrapUnique(new X(1, 2)); // works, but nonideal.
// auto x = MakeUnique<X>(1, 2); // safer, standard, avoids raw 'new'.
//
// Note: Cannot wrap pointers to array of unknown bound (i.e. U(*)[]).
template <typename T>
std::unique_ptr<T> WrapUnique(T* ptr) {
static_assert(!std::is_array<T>::value || std::extent<T>::value != 0,
"types T[0] or T[] are unsupported");
return std::unique_ptr<T>(ptr);
}
template <typename T, typename... Args>
typename helper::MakeUniqueResult<T>::scalar MakeUnique(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
// Overload for array of unknown bound.
// The allocation of arrays needs to use the array form of new,
// and cannot take element constructor arguments.
template <typename T>
typename helper::MakeUniqueResult<T>::array MakeUnique(size_t n) {
return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
}
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_PTR_UTIL_H_
@@ -0,0 +1,62 @@
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_REFFED_STATUS_CALLBACK_H_
#define TENSORFLOW_CORE_UTIL_REFFED_STATUS_CALLBACK_H_
#include "tensorflow/core/lib/core/refcount.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/mutex.h"
namespace tensorflow {
// The ReffedStatusCallback is a refcounted object that accepts a
// StatusCallback. When it is destroyed (its refcount goes to 0), the
// StatusCallback is called with the first non-OK status passed to
// UpdateStatus(), or Status::OK() if no non-OK status was set.
class ReffedStatusCallback : public core::RefCounted {
public:
explicit ReffedStatusCallback(StatusCallback done)
: done_(std::move(done)), status_(Status::OK()) {}
void UpdateStatus(const Status& s) {
if (!s.ok()) {
mutex_lock lock(mu_);
if (status_.ok()) status_.Update(s);
}
}
bool ok() {
mutex_lock lock(mu_);
return status_.ok();
}
// Returns a copy of the current status.
Status status() {
mutex_lock lock(mu_);
return status_;
}
~ReffedStatusCallback() { done_(status_); }
private:
StatusCallback done_;
mutex mu_;
Status status_ GUARDED_BY(mu_);
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_REFFED_STATUS_CALLBACK_H_
@@ -0,0 +1,182 @@
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_RPC_CALL_CONTAINER_H_
#define TENSORFLOW_CORE_UTIL_RPC_CALL_CONTAINER_H_
#include <list>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/refcount.h"
#include "tensorflow/core/util/reffed_status_callback.h"
namespace tensorflow {
namespace internal {
// The following class is used for coordination between a `CallContainer`
// instance and a cancellation callback to make sure that the `CallContainer`
// instance waits for the cancellation callback to be destroyed (either because
// a cancellation occurred or because the callback was deregistered) before
// deleting itself. Without this coordination the cancellation callback could
// attempt to access a `CallContainer` instance that is no longer valid.
class NotifyWhenDestroyed {
public:
explicit NotifyWhenDestroyed(std::shared_ptr<Notification> notification)
: notification_(std::move(notification)) {}
~NotifyWhenDestroyed() { notification_->Notify(); }
private:
std::shared_ptr<Notification> notification_;
};
} // namespace internal
// The following class is responsible for the life cycle management of a set of
// RPC calls. The calls are started when an instance of the class is created and
// the class contract guarantees to invoke a "done" callback provided by the
// caller when all RPC calls have either completed or been cancelled.
//
// The caller should not make any assumptions about the validity of an instance
// of this class after the provided callback has been invoked, which may be
// immediately after the instance was created.
template <class Call>
class CallContainer {
public:
typedef std::function<void(CallContainer<Call>*, int)> CreateCallFn;
typedef std::function<void(Call*)> StartCallFn;
// Uses the provided `create_call_fn` and `start_call_fn` functions to create
// and start a set of RPC calls. When all RPC calls have either completed or
// been cancelled, the `done` callback is invoked. The caller should not make
// any assumptions about the validity of the created instance as the instance
// will delete itself after invoking the `done` callback.
explicit CallContainer(OpKernelContext* ctx, int num_calls, bool fail_fast,
bool try_rpc, AsyncOpKernel::DoneCallback done,
CreateCallFn create_call_fn,
StartCallFn start_call_fn);
// Registers a call with this container. This method expects its arguments to
// match those of a `Call` constructor as it forwards them to an underlying
// collection, which creates a `Call` instance in place.
template <class... Args>
void RegisterCall(Args&&... args);
// Starts the cancellation of all RPC calls managed by this container.
void StartCancel();
// Indicates that the `index`-th RPC call has finished.
void Done(const Status& s, int index);
private:
OpKernelContext* ctx_;
std::list<Call> calls_;
const AsyncOpKernel::DoneCallback done_;
const CancellationToken token_;
const bool fail_fast_;
const bool try_rpc_;
std::shared_ptr<Notification> callback_destroyed_;
// Performs its own reference counting.
ReffedStatusCallback* reffed_status_callback_;
};
template <class Call>
CallContainer<Call>::CallContainer(
OpKernelContext* ctx, int num_calls, bool fail_fast, bool try_rpc,
AsyncOpKernel::DoneCallback done,
typename CallContainer<Call>::CreateCallFn create_call_fn,
typename CallContainer<Call>::StartCallFn start_call_fn)
: ctx_(ctx),
done_(std::move(done)),
token_(ctx->cancellation_manager() != nullptr
? ctx->cancellation_manager()->get_cancellation_token()
: CancellationManager::kInvalidToken),
fail_fast_(fail_fast),
try_rpc_(try_rpc),
callback_destroyed_(new Notification) {
CHECK_GT(num_calls, 0);
// This will run when all RPCs are finished.
reffed_status_callback_ = new ReffedStatusCallback([this](const Status& s) {
if (token_ != CancellationManager::kInvalidToken) {
ctx_->cancellation_manager()->DeregisterCallback(token_);
}
ctx_->SetStatus(s);
done_();
callback_destroyed_->WaitForNotification();
delete this;
});
// The cancellation callback needs to be registered before the RPC calls are
// started to make sure that the callback is properly cleaned up by the
// `reffed_status_callback` when all calls complete. At the same time, the
// cancellation callback should wait for the RPC calls to be started for the
// cancellation to take effect.
std::shared_ptr<internal::NotifyWhenDestroyed> notify_when_destroyed(
new internal::NotifyWhenDestroyed(callback_destroyed_));
std::shared_ptr<Notification> calls_started(new Notification);
bool is_cancelled = false;
if (token_ != CancellationManager::kInvalidToken) {
is_cancelled = !ctx_->cancellation_manager()->RegisterCallback(
token_, [this, calls_started, notify_when_destroyed]() {
calls_started->WaitForNotification();
StartCancel();
});
}
for (int i = 0; i < num_calls; ++i) {
create_call_fn(this, i);
// Increase the reference on the callback for each new RPC.
reffed_status_callback_->Ref();
}
for (Call& call : calls_) {
start_call_fn(&call);
}
calls_started->Notify();
if (is_cancelled) {
ctx_->SetStatus(errors::Cancelled("Operation has been cancelled."));
StartCancel();
}
// Subtract reference count from the initial creation.
reffed_status_callback_->Unref();
}
template <class Call>
template <class... Args>
void CallContainer<Call>::RegisterCall(Args&&... args) {
calls_.emplace_back(std::forward<Args>(args)...);
}
template <class Call>
void CallContainer<Call>::StartCancel() {
for (auto& call : calls_) {
call.StartCancel();
}
}
template <class Call>
void CallContainer<Call>::Done(const Status& s, int index) {
if (!try_rpc_) {
reffed_status_callback_->UpdateStatus(s);
}
reffed_status_callback_->Unref();
}
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_RPC_CALL_CONTAINER_H_
@@ -0,0 +1,71 @@
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_RPC_RPC_FACTORY_H_
#define TENSORFLOW_CORE_UTIL_RPC_RPC_FACTORY_H_
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_types.h"
namespace tensorflow {
// Return the environment variable `key`. If the variable is not set,
// use the default value. If it is set but could not be parsed,
// return `false`. Otherwise set `value` and return `true`.
template <typename T>
bool GetEnvVar(const char* key, const T& default_value, T* value);
class RPCFactory {
public:
RPCFactory() {}
virtual ~RPCFactory() {}
// Asynchronously invokes methods `method_t` at addresses `address_t` with
// request strings from `request_t`. Any of these may be scalar
// Tensors, in which case the operands are broadcasted.
// Upon completion of all requests, `response_t` will be populated and the
// `done` callback will be invoked.
//
// If `try_rpc` is `true`, then `status_message_t` and
// `status_code_t` will be populated as well.
//
// If `try_rpc` is `false`, then `status_message_t` and
// `status_code_t` are ignored (and may be nullptr). Instead, the
// status of any failed call will be propagated to the op.
//
// REQUIRES:
// - `response_t` is not null, and is a string Tensor with the same shape as
// `request_t`.
//
// If `try_rpc` is `true`:
// - `status_code_t` and `status_message_t` are not null.
// - `status_code_t` is an int32 Tensor with the same shape as
// `request_t`.
// - `status_message_t` is a string Tensor with the same shape as
// `request_t`.
virtual void Call(OpKernelContext* ctx, int64 num_elements,
const Tensor& address_t, const Tensor& method_t,
const Tensor& request_t, const bool try_rpc,
Tensor* response_t, Tensor* status_code_t,
Tensor* status_message_t,
AsyncOpKernel::DoneCallback done) = 0;
private:
TF_DISALLOW_COPY_AND_ASSIGN(RPCFactory);
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_RPC_RPC_FACTORY_H_
@@ -0,0 +1,72 @@
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_RPC_RPC_FACTORY_REGISTRY_H_
#define TENSORFLOW_CORE_UTIL_RPC_RPC_FACTORY_REGISTRY_H_
#include <map>
#include <string>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/util/rpc/rpc_factory.h"
namespace tensorflow {
class RPCFactoryRegistry {
public:
typedef std::function<RPCFactory*(OpKernelConstruction* ctx, bool fail_fast,
int64 timeout_in_ms)>
RPCFactoryFn;
// Returns a pointer to a global RPCFactoryRegistry object.
static RPCFactoryRegistry* Global();
// Returns a pointer to an function that creates an RPC factory for the given
// protocol.
RPCFactoryFn* Get(const string& protocol);
// Registers a function that creates and RPC factory for the given protocol.
// The function should transfer the ownership of the factory to its caller.
void Register(const string& protocol, const RPCFactoryFn& factory_fn);
private:
std::map<string, RPCFactoryFn> fns_;
};
namespace rpc_factory_registration {
class RPCFactoryRegistration {
public:
RPCFactoryRegistration(const string& protocol,
const RPCFactoryRegistry::RPCFactoryFn& factory_fn) {
RPCFactoryRegistry::Global()->Register(protocol, factory_fn);
}
};
} // namespace rpc_factory_registration
#define REGISTER_RPC_FACTORY(protocol, factory_fn) \
REGISTER_RPC_FACTORY_UNIQ_HELPER(__COUNTER__, protocol, factory_fn)
#define REGISTER_RPC_FACTORY_UNIQ_HELPER(ctr, protocol, factory_fn) \
REGISTER_RPC_FACTORY_UNIQ(ctr, protocol, factory_fn)
#define REGISTER_RPC_FACTORY_UNIQ(ctr, protocol, factory_fn) \
static rpc_factory_registration::RPCFactoryRegistration \
rpc_factory_registration_fn_##ctr(protocol, factory_fn)
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_RPC_RPC_FACTORY_REGISTRY_H_
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,58 @@
// GENERATED FILE - DO NOT MODIFY
#ifndef tensorflow_core_util_saved_tensor_slice_proto_IMPL_H_
#define tensorflow_core_util_saved_tensor_slice_proto_IMPL_H_
#include "tensorflow/core/framework/resource_handle.pb.h"
#include "tensorflow/core/framework/resource_handle.pb_text-impl.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/tensor.pb_text-impl.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/framework/tensor_shape.pb_text-impl.h"
#include "tensorflow/core/framework/tensor_slice.pb.h"
#include "tensorflow/core/framework/tensor_slice.pb_text-impl.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/framework/types.pb_text-impl.h"
#include "tensorflow/core/framework/versions.pb.h"
#include "tensorflow/core/framework/versions.pb_text-impl.h"
#include "tensorflow/core/lib/strings/proto_text_util.h"
#include "tensorflow/core/lib/strings/scanner.h"
#include "tensorflow/core/util/saved_tensor_slice.pb.h"
#include "tensorflow/core/util/saved_tensor_slice.pb_text.h"
namespace tensorflow {
namespace internal {
void AppendProtoDebugString(
::tensorflow::strings::ProtoTextOutput* o,
const ::tensorflow::SavedSliceMeta& msg);
bool ProtoParseFromScanner(
::tensorflow::strings::Scanner* scanner, bool nested, bool close_curly,
::tensorflow::SavedSliceMeta* msg);
void AppendProtoDebugString(
::tensorflow::strings::ProtoTextOutput* o,
const ::tensorflow::SavedTensorSliceMeta& msg);
bool ProtoParseFromScanner(
::tensorflow::strings::Scanner* scanner, bool nested, bool close_curly,
::tensorflow::SavedTensorSliceMeta* msg);
void AppendProtoDebugString(
::tensorflow::strings::ProtoTextOutput* o,
const ::tensorflow::SavedSlice& msg);
bool ProtoParseFromScanner(
::tensorflow::strings::Scanner* scanner, bool nested, bool close_curly,
::tensorflow::SavedSlice* msg);
void AppendProtoDebugString(
::tensorflow::strings::ProtoTextOutput* o,
const ::tensorflow::SavedTensorSlices& msg);
bool ProtoParseFromScanner(
::tensorflow::strings::Scanner* scanner, bool nested, bool close_curly,
::tensorflow::SavedTensorSlices* msg);
} // namespace internal
} // namespace tensorflow
#endif // tensorflow_core_util_saved_tensor_slice_proto_IMPL_H_
@@ -0,0 +1,54 @@
// GENERATED FILE - DO NOT MODIFY
#ifndef tensorflow_core_util_saved_tensor_slice_proto_H_
#define tensorflow_core_util_saved_tensor_slice_proto_H_
#include "tensorflow/core/util/saved_tensor_slice.pb.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
// Message-text conversion for tensorflow.SavedSliceMeta
string ProtoDebugString(
const ::tensorflow::SavedSliceMeta& msg);
string ProtoShortDebugString(
const ::tensorflow::SavedSliceMeta& msg);
bool ProtoParseFromString(
const string& s,
::tensorflow::SavedSliceMeta* msg)
TF_MUST_USE_RESULT;
// Message-text conversion for tensorflow.SavedTensorSliceMeta
string ProtoDebugString(
const ::tensorflow::SavedTensorSliceMeta& msg);
string ProtoShortDebugString(
const ::tensorflow::SavedTensorSliceMeta& msg);
bool ProtoParseFromString(
const string& s,
::tensorflow::SavedTensorSliceMeta* msg)
TF_MUST_USE_RESULT;
// Message-text conversion for tensorflow.SavedSlice
string ProtoDebugString(
const ::tensorflow::SavedSlice& msg);
string ProtoShortDebugString(
const ::tensorflow::SavedSlice& msg);
bool ProtoParseFromString(
const string& s,
::tensorflow::SavedSlice* msg)
TF_MUST_USE_RESULT;
// Message-text conversion for tensorflow.SavedTensorSlices
string ProtoDebugString(
const ::tensorflow::SavedTensorSlices& msg);
string ProtoShortDebugString(
const ::tensorflow::SavedTensorSlices& msg);
bool ProtoParseFromString(
const string& s,
::tensorflow::SavedTensorSlices* msg)
TF_MUST_USE_RESULT;
} // namespace tensorflow
#endif // tensorflow_core_util_saved_tensor_slice_proto_H_
@@ -0,0 +1,213 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Utilities for saving/restoring tensor slice checkpoints.
#ifndef TENSORFLOW_CORE_UTIL_SAVED_TENSOR_SLICE_UTIL_H_
#define TENSORFLOW_CORE_UTIL_SAVED_TENSOR_SLICE_UTIL_H_
#include <string> // for string
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/tensor_slice.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/status.h" // for Status
#include "tensorflow/core/platform/protobuf.h"
namespace tensorflow {
namespace checkpoint {
// The key for the metadata in the tensor slice checkpoint files. It is "" so
// that the metadata is always at the beginning of a checkpoint file.
extern const char kSavedTensorSlicesKey[];
// Encode a tensor name + a tensor slice into an ordered code and outputs it as
// a string.
// The format is
// <0>
// <tensor_name>
// <rank>
// <dim-0-start><dim-0-length>
// <dim-1-start><dim-1-length>
// ...
string EncodeTensorNameSlice(const string& name,
const tensorflow::TensorSlice& slice);
// Parse out the name and the slice from string encoded as an ordered code.
Status DecodeTensorNameSlice(const string& code, string* name,
tensorflow::TensorSlice* slice);
// Extracts the full shape, slice spec, and shape of the slice from
// "shape_and_slice". On non-OK return, caller must clear the out-arguments
// before reusing.
Status ParseShapeAndSlice(const string& shape_and_slice, TensorShape* shape,
TensorSlice* slice, TensorShape* shape_slice);
template <typename T>
struct SaveTypeTraits;
template <typename T>
const typename SaveTypeTraits<T>::SavedType* TensorProtoData(
const TensorProto& t);
template <typename T>
typename SaveTypeTraits<T>::RepeatedField* MutableTensorProtoData(
TensorProto* t);
template <typename T>
void Fill(T* data, size_t n, TensorProto* t);
#define TENSOR_PROTO_EXTRACT_TYPE_HELPER(TYPE, FIELD, FTYPE, STYPE) \
template <> \
struct SaveTypeTraits<TYPE> { \
static constexpr bool supported = true; \
typedef STYPE SavedType; \
typedef protobuf::RepeatedField<FTYPE> RepeatedField; \
}; \
template <> \
inline const STYPE* TensorProtoData<TYPE>(const TensorProto& t) { \
static_assert(SaveTypeTraits<TYPE>::supported, \
"Specified type " #TYPE " not supported for Restore"); \
return reinterpret_cast<const STYPE*>(t.FIELD##_val().data()); \
} \
template <> \
inline protobuf::RepeatedField<FTYPE>* MutableTensorProtoData<TYPE>( \
TensorProto * t) { \
static_assert(SaveTypeTraits<TYPE>::supported, \
"Specified type " #TYPE " not supported for Save"); \
return reinterpret_cast<protobuf::RepeatedField<FTYPE>*>( \
t->mutable_##FIELD##_val()); \
}
#define TENSOR_PROTO_EXTRACT_TYPE(TYPE, FIELD, FTYPE) \
TENSOR_PROTO_EXTRACT_TYPE_HELPER(TYPE, FIELD, FTYPE, FTYPE) \
template <> \
inline void Fill(const TYPE* data, size_t n, TensorProto* t) { \
typename protobuf::RepeatedField<FTYPE> copy(data, data + n); \
t->mutable_##FIELD##_val()->Swap(&copy); \
}
// Complex needs special treatment since proto doesn't have native complex
#define TENSOR_PROTO_EXTRACT_TYPE_COMPLEX(TYPE, FIELD, FTYPE) \
TENSOR_PROTO_EXTRACT_TYPE_HELPER(TYPE, FIELD, FTYPE, TYPE) \
template <> \
inline void Fill(const TYPE* data, size_t n, TensorProto* t) { \
const FTYPE* sub = reinterpret_cast<const FTYPE*>(data); \
typename protobuf::RepeatedField<FTYPE> copy(sub, sub + 2 * n); \
t->mutable_##FIELD##_val()->Swap(&copy); \
}
TENSOR_PROTO_EXTRACT_TYPE(bool, bool, bool);
TENSOR_PROTO_EXTRACT_TYPE(float, float, float);
TENSOR_PROTO_EXTRACT_TYPE(double, double, double);
TENSOR_PROTO_EXTRACT_TYPE_COMPLEX(complex64, scomplex, float);
TENSOR_PROTO_EXTRACT_TYPE_COMPLEX(complex128, dcomplex, double);
TENSOR_PROTO_EXTRACT_TYPE(int32, int, int32);
TENSOR_PROTO_EXTRACT_TYPE(int64, int64, protobuf_int64);
TENSOR_PROTO_EXTRACT_TYPE(uint16, int, int32);
TENSOR_PROTO_EXTRACT_TYPE(uint8, int, int32);
TENSOR_PROTO_EXTRACT_TYPE(int8, int, int32);
TENSOR_PROTO_EXTRACT_TYPE(int16, int, int32);
TENSOR_PROTO_EXTRACT_TYPE(qint8, int, int32);
TENSOR_PROTO_EXTRACT_TYPE(quint8, int, int32);
TENSOR_PROTO_EXTRACT_TYPE(quint16, int, int32);
#undef TENSOR_PROTO_EXTRACT_TYPE_COMPLEX
#undef TENSOR_PROTO_EXTRACT_TYPE_HELPER
#undef TENSOR_PROTO_EXTRACT_TYPE
// Custom implementation for qint32, based on the one for int32.
template <>
struct SaveTypeTraits<qint32> : SaveTypeTraits<int32> {};
template <>
inline const int32* TensorProtoData<qint32>(const TensorProto& t) {
static_assert(SaveTypeTraits<qint32>::supported,
"Specified type qint32 not supported for Restore");
return reinterpret_cast<const int32*>(t.int_val().data());
}
inline void Fill(const qint32* data, size_t n, TensorProto* t) {
const int32* p = reinterpret_cast<const int32*>(data);
typename protobuf::RepeatedField<int32> copy(p, p + n);
t->mutable_int_val()->Swap(&copy);
}
// Custom implementation for Eigen::half.
template <>
struct SaveTypeTraits<Eigen::half> {
static constexpr bool supported = true;
typedef int SavedType;
typedef protobuf::RepeatedField<int32> RepeatedField;
};
template <>
inline const int* TensorProtoData<Eigen::half>(const TensorProto& t) {
return t.half_val().data();
}
template <>
inline protobuf::RepeatedField<int32>* MutableTensorProtoData<Eigen::half>(
TensorProto* t) {
return t->mutable_half_val();
}
template <>
inline void Fill(const Eigen::half* data, size_t n, TensorProto* t) {
typename protobuf::RepeatedField<int32>* val = t->mutable_half_val();
val->Resize(n, 0);
for (size_t i = 0; i < n; ++i) {
val->Set(i, data[i].x);
}
}
// Custom implementation for string.
template <>
struct SaveTypeTraits<string> {
static constexpr bool supported = true;
typedef const string* SavedType;
typedef protobuf::RepeatedPtrField<string> RepeatedField;
};
template <>
inline const string* const* TensorProtoData<string>(const TensorProto& t) {
static_assert(SaveTypeTraits<string>::supported,
"Specified type string not supported for Restore");
return t.string_val().data();
}
template <>
inline protobuf::RepeatedPtrField<string>* MutableTensorProtoData<string>(
TensorProto* t) {
static_assert(SaveTypeTraits<string>::supported,
"Specified type string not supported for Save");
return t->mutable_string_val();
}
template <>
inline void Fill(const string* data, size_t n, TensorProto* t) {
typename protobuf::RepeatedPtrField<string> copy(data, data + n);
t->mutable_string_val()->Swap(&copy);
}
} // namespace checkpoint
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_SAVED_TENSOR_SLICE_UTIL_H_
@@ -0,0 +1,119 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_SPARSE_DIM_COMPARATOR_H_
#define TENSORFLOW_CORE_UTIL_SPARSE_DIM_COMPARATOR_H_
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/kernels/bounds_check.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace sparse {
/////////////////
// DimComparator
/////////////////
//
// Helper class, mainly used by the IndexSortOrder. This comparator
// can be passed to e.g. std::sort, or any other sorter, to sort two
// rows of an index matrix according to the dimension(s) of interest.
// The dimensions to sort by are passed to the constructor as "order".
//
// Example: if given index matrix IX, two rows ai and bi, and order = {2,1}.
// operator() compares
// IX(ai,2) < IX(bi,2).
// If IX(ai,2) == IX(bi,2), it compares
// IX(ai,1) < IX(bi,1).
//
// This can be used to sort a vector of row indices into IX according to
// the values in IX in particular columns (dimensions) of interest.
class DimComparator {
public:
typedef typename gtl::ArraySlice<int64> VarDimArray;
DimComparator(const TTypes<int64>::Matrix& ix, const VarDimArray& order,
const VarDimArray& shape)
: ix_(ix), order_(order), dims_(shape.size()) {
DCHECK_GT(order.size(), size_t{0}) << "Must order using at least one index";
DCHECK_LE(order.size(), shape.size()) << "Can only sort up to dims";
for (size_t d = 0; d < order.size(); ++d) {
DCHECK_GE(order[d], 0);
DCHECK_LT(order[d], shape.size());
}
}
inline bool operator()(const int64 i, const int64 j) const {
for (int di = 0; di < dims_; ++di) {
const int64 d = order_[di];
if (ix_(i, d) < ix_(j, d)) return true;
if (ix_(i, d) > ix_(j, d)) return false;
}
return false;
}
// Compares two indices taken from corresponding index matrices, using the
// standard, row-major (or lexicographic) order. Useful for cases that need
// to distinguish between all three orderings (<, ==, >).
inline static int cmp(const TTypes<int64>::ConstMatrix& a_idx,
const TTypes<int64>::ConstMatrix& b_idx,
const int64 a_row, const int64 b_row, const int dims) {
for (int d = 0; d < dims; ++d) {
const int64 a = a_idx(a_row, d);
const int64 b = b_idx(b_row, d);
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
}
return 0;
}
protected:
const TTypes<int64>::Matrix ix_;
const VarDimArray order_;
const int dims_;
const std::vector<int64>* ix_order_;
};
template <int ORDER_DIM>
class FixedDimComparator : DimComparator {
public:
FixedDimComparator(const TTypes<int64>::Matrix& ix, const VarDimArray& order,
const VarDimArray& shape)
: DimComparator(ix, order, shape) {
DCHECK_EQ(order.size(), ORDER_DIM);
}
inline bool operator()(const int64 i, const int64 j) const {
bool value = false;
for (int di = 0; di < ORDER_DIM; ++di) {
const int64 d = order_[di];
if (ix_(i, d) < ix_(j, d)) {
value = true;
break;
}
if (ix_(i, d) > ix_(j, d)) break;
}
return value;
}
};
} // namespace sparse
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_SPARSE_DIM_COMPARATOR_H_
@@ -0,0 +1,148 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_SPARSE_GROUP_ITERATOR_H_
#define TENSORFLOW_CORE_UTIL_SPARSE_GROUP_ITERATOR_H_
#include <vector>
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace sparse {
class GroupIterable; // Predeclare GroupIterable for Group.
// This class is returned when dereferencing a GroupIterable iterator.
// It provides the methods group(), indices(), and values(), which
// provide access into the underlying SparseTensor.
class Group {
public:
Group(GroupIterable* iter, int64 loc, int64 next_loc)
: iter_(iter), loc_(loc), next_loc_(next_loc) {}
std::vector<int64> group() const;
TTypes<int64>::UnalignedConstMatrix indices() const;
template <typename T>
typename TTypes<T>::UnalignedVec values() const;
private:
GroupIterable* iter_;
int64 loc_;
int64 next_loc_;
};
/////////////////
// GroupIterable
/////////////////
//
// Returned when calling sparse_tensor.group({dim0, dim1, ...}).
//
// Please note: the sparse_tensor should already be ordered according
// to {dim0, dim1, ...}. Otherwise this iteration will return invalid groups.
//
// Allows grouping and iteration of the SparseTensor according to the
// subset of dimensions provided to the group call.
//
// The actual grouping dimensions are stored in the
// internal vector group_dims_. Iterators inside the iterable provide
// the three methods:
//
// * group(): returns a vector with the current group dimension values.
// * indices(): a map of index, providing the indices in
// this group.
// * values(): a map of values, providing the values in
// this group.
//
// To iterate across GroupIterable, see examples in README.md.
//
// Forward declaration of SparseTensor
class GroupIterable {
public:
typedef gtl::ArraySlice<int64> VarDimArray;
GroupIterable(Tensor ix, Tensor vals, int dims, const VarDimArray& group_dims)
: ix_(ix),
ix_matrix_(ix_.matrix<int64>()),
vals_(vals),
dims_(dims),
group_dims_(group_dims.begin(), group_dims.end()) {}
class IteratorStep;
IteratorStep begin() { return IteratorStep(this, 0); }
IteratorStep at(int64 loc) {
CHECK(loc >= 0 && loc <= ix_.dim_size(0))
<< "loc provided must lie between 0 and " << ix_.dim_size(0);
return IteratorStep(this, loc);
}
IteratorStep end() { return IteratorStep(this, ix_.dim_size(0)); }
template <typename TIX>
inline bool GroupMatches(const TIX& ix, int64 loc_a, int64 loc_b) const {
bool matches = true;
for (int d : group_dims_) {
if (ix(loc_a, d) != ix(loc_b, d)) {
matches = false;
}
}
return matches;
}
class IteratorStep {
public:
IteratorStep(GroupIterable* iter, int64 loc)
: iter_(iter), loc_(loc), next_loc_(loc_) {
UpdateEndOfGroup();
}
void UpdateEndOfGroup();
bool operator!=(const IteratorStep& rhs) const;
bool operator==(const IteratorStep& rhs) const;
IteratorStep& operator++(); // prefix ++
IteratorStep operator++(int); // postfix ++
Group operator*() const { return Group(iter_, loc_, next_loc_); }
int64 loc() const { return loc_; }
private:
GroupIterable* iter_;
int64 loc_;
int64 next_loc_;
};
private:
friend class Group;
const Tensor ix_;
const TTypes<int64>::ConstMatrix ix_matrix_;
Tensor vals_;
const int dims_;
const gtl::InlinedVector<int64, 8> group_dims_;
};
// Implementation of Group::values<T>()
template <typename T>
typename TTypes<T>::UnalignedVec Group::values() const {
return typename TTypes<T>::UnalignedVec(&(iter_->vals_.vec<T>()(loc_)),
next_loc_ - loc_);
}
} // namespace sparse
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_SPARSE_GROUP_ITERATOR_H_
@@ -0,0 +1,754 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_SPARSE_SPARSE_TENSOR_H_
#define TENSORFLOW_CORE_UTIL_SPARSE_SPARSE_TENSOR_H_
#include <limits>
#include <numeric>
#include <vector>
#include "absl/base/macros.h"
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/kernels/bounds_check.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/sparse/dim_comparator.h"
#include "tensorflow/core/util/sparse/group_iterator.h"
namespace tensorflow {
namespace sparse {
class SparseTensor {
public:
typedef typename gtl::ArraySlice<int64> VarDimArray;
typedef typename gtl::InlinedVector<int64, 8> ShapeArray;
static Status Create(Tensor ix, Tensor vals, const VarDimArray shape,
const VarDimArray order, SparseTensor* result) {
if (ix.dtype() != DT_INT64) {
return Status(
error::INVALID_ARGUMENT,
strings::StrCat("indices must be type int64 but got: ", ix.dtype()));
}
if (!TensorShapeUtils::IsVector(vals.shape())) {
return Status(error::INVALID_ARGUMENT,
strings::StrCat("vals must be a vec, but got: ",
vals.shape().DebugString()));
}
if (ix.shape().dim_size(0) != vals.shape().dim_size(0)) {
return Status(error::INVALID_ARGUMENT,
strings::StrCat("indices and values rows (indexing "
"dimension) must match. (indices = ",
ix.shape().dim_size(0), ", values = ",
vals.shape().dim_size(0), ")"));
}
int dims;
TF_RETURN_IF_ERROR(GetDimsFromIx(ix, &dims));
if (order.size() != dims) {
return Status(error::INVALID_ARGUMENT,
"Order length must be SparseTensor rank.");
}
if (shape.size() != dims) {
return Status(error::INVALID_ARGUMENT,
"Shape rank must be SparseTensor rank.");
}
*result = SparseTensor(ix, vals, shape, order);
return Status();
}
static Status Create(Tensor ix, Tensor vals, const TensorShape& shape,
SparseTensor* result) {
return Create(ix, vals, TensorShapeToVector(shape),
UndefinedOrder(TensorShapeToVector(shape)), result);
}
static Status Create(Tensor ix, Tensor vals, const VarDimArray shape,
SparseTensor* result) {
return Create(ix, vals, shape, UndefinedOrder(shape), result);
}
static Status Create(Tensor ix, Tensor vals, const TensorShape& shape,
const VarDimArray order, SparseTensor* result) {
return Create(ix, vals, TensorShapeToVector(shape), order, result);
}
SparseTensor() : dims_(0) {}
ABSL_DEPRECATED("Use Create() functions instead of constructors directly.")
SparseTensor(Tensor ix, Tensor vals, const TensorShape& shape)
: SparseTensor(ix, vals, TensorShapeToVector(shape),
UndefinedOrder(TensorShapeToVector(shape))) {}
ABSL_DEPRECATED("Use Create() functions instead of constructors directly.")
SparseTensor(Tensor ix, Tensor vals, const VarDimArray shape)
: SparseTensor(ix, vals, shape, UndefinedOrder(shape)) {}
ABSL_DEPRECATED("use Create() functions instead of constructors directly.")
SparseTensor(Tensor ix, Tensor vals, const TensorShape& shape,
const VarDimArray order)
: SparseTensor(ix, vals, TensorShapeToVector(shape), order) {}
ABSL_DEPRECATED("Use Create() functions instead of constructors directly.")
SparseTensor(Tensor ix, Tensor vals, const VarDimArray shape,
const VarDimArray order)
: ix_(ix),
vals_(vals),
shape_(shape.begin(), shape.end()),
order_(order.begin(), order.end()),
dims_(UnsafeGetDimsFromIx(ix)) {
DCHECK_EQ(ix.dtype(), DT_INT64)
<< "indices must be type int64 but got: " << ix.dtype();
DCHECK(TensorShapeUtils::IsVector(vals.shape()))
<< "vals must be a vec, but got: " << vals.shape().DebugString();
DCHECK_EQ(ix.shape().dim_size(0), vals.shape().dim_size(0))
<< "indices and values rows (indexing dimension) must match.";
DCHECK_EQ(order.size(), dims_) << "Order length must be SparseTensor rank.";
DCHECK_EQ(shape.size(), dims_) << "Shape rank must be SparseTensor rank.";
}
SparseTensor(const SparseTensor& other)
: SparseTensor(other.ix_, other.vals_, other.shape_, other.order_) {}
SparseTensor(SparseTensor&& other)
: SparseTensor(std::move(other.ix_), std::move(other.vals_),
std::move(other.shape_), std::move(other.order_)) {}
SparseTensor& operator=(const SparseTensor& other) {
ix_ = other.ix_;
vals_ = other.vals_;
shape_ = other.shape_;
order_ = other.order_;
dims_ = other.dims_;
return *this;
}
SparseTensor& operator=(SparseTensor&& other) {
ix_ = std::move(other.ix_);
vals_ = std::move(other.vals_);
shape_ = std::move(other.shape_);
order_ = std::move(other.order_);
dims_ = std::move(other.dims_);
return *this;
}
std::size_t num_entries() const { return ix_.dim_size(0); }
int dims() const { return shape_.size(); }
const Tensor& indices() const { return ix_; }
const Tensor& values() const { return vals_; }
DataType dtype() const { return vals_.dtype(); }
Status IndicesValid() const {
const auto ix_t = ix_.matrix<int64>();
for (int64 ord : order_) {
if (ord < 0) {
return errors::FailedPrecondition(
"Order was not provided. Provide an order at "
"construction time or run ReorderInPlace");
}
}
for (std::size_t n = 0; n < num_entries(); ++n) {
TF_RETURN_IF_ERROR(IndexValid(ix_t, n));
}
return Status::OK();
}
VarDimArray shape() const { return shape_; }
VarDimArray order() const { return order_; }
// Resorts the indices and values according to the dimensions in order.
template <typename T>
void Reorder(const VarDimArray& order);
// Returns a group iterable that can be used for clumping indices
// and values according to the group indices of interest.
//
// Precondition: order()[0..group_ix.size()] == group_ix.
//
// See the README.md in this directory for more usage information.
GroupIterable group(const VarDimArray& group_ix) const {
DCHECK_LE(group_ix.size(), dims_);
for (std::size_t di = 0; di < group_ix.size(); ++di) {
DCHECK_GE(group_ix[di], 0) << "Group dimension out of range";
DCHECK_LT(group_ix[di], dims_) << "Group dimension out of range";
DCHECK_EQ(group_ix[di], order_[di])
<< "Group dimension does not match sorted order";
}
return GroupIterable(ix_, vals_, dims_, group_ix);
}
// Stores the sparse indices into the dense tensor out.
// Preconditions:
// out->shape().dims() == shape().dims()
// out->shape().dim_size(d) >= shape(d) for all d
//
// Returns true on success. False on failure (mismatched dimensions
// or out-of-bounds indices).
//
// If initialize==True, ToDense first overwrites all coefficients in out to 0.
//
template <typename T>
bool ToDense(Tensor* out, bool initialize = true);
// Concat() will concatenate all the tensors according to their first order
// dimension. All tensors must have identical shape except for
// the first order dimension. All tensors orders' first dimension
// must match.
//
// If all of the tensors have identical ordering, then the output
// will have this ordering. Otherwise the output is set as not
// having any order and a Reorder<T>() should be called on it before
// performing any subsequent operations.
template <typename T>
static SparseTensor Concat(const gtl::ArraySlice<SparseTensor>& tensors);
// Split() will split the input SparseTensor into a list of num_split
// SparseTensor given a splitting dimension. If the input dimension range
// isn't an integer multiple of split_dim, we add one extra dimension for
// each slice.
template <typename T>
static Status Split(const SparseTensor& tensor, const int split_dim,
const int num_split, std::vector<SparseTensor>* result);
template <typename T>
ABSL_DEPRECATED(
"Use the form of Split() that takes an output pointer and returns a "
"status instead.")
static std::vector<SparseTensor> Split(const SparseTensor& tensor,
const int split_dim,
const int num_split,
Status* status = nullptr);
// Slice() will slice the input SparseTensor into a SparseTensor based on
// specified start and size. Both start and size are 1-D array with each
// element of the array representing one dimension. The start is the start
// index at each dimension and the size is the size at each dimension.
template <typename T>
static SparseTensor Slice(const SparseTensor& tensor,
const gtl::ArraySlice<int64>& start,
const gtl::ArraySlice<int64>& size);
// Picks out the dimensions according to `dim_indices`.
std::vector<int64> PickDims(gtl::ArraySlice<int64> dim_indices) const {
std::vector<int64> res(dim_indices.size());
for (size_t i = 0; i < dim_indices.size(); ++i) {
res[i] = shape_[dim_indices[i]];
}
return res;
}
private:
static Status GetDimsFromIx(const Tensor& ix, int* result) {
if (!TensorShapeUtils::IsMatrix(ix.shape())) {
return Status(error::INVALID_ARGUMENT,
strings::StrCat("indices must be a matrix, but got: ",
ix.shape().DebugString()));
}
*result = UnsafeGetDimsFromIx(ix);
return Status();
}
static int UnsafeGetDimsFromIx(const Tensor& ix) {
DCHECK(TensorShapeUtils::IsMatrix(ix.shape()));
return ix.dim_size(1);
}
static inline ShapeArray UndefinedOrder(const VarDimArray shape) {
return ShapeArray(shape.size(), -1);
}
static inline ShapeArray TensorShapeToVector(const TensorShape& shape) {
ShapeArray vec(shape.dims());
for (int i = 0; i < shape.dims(); ++i) vec[i] = shape.dim_size(i);
return vec;
}
// Helper for IndicesValid()
inline Status IndexValid(const TTypes<int64>::ConstMatrix& ix_t,
int n) const {
bool valid = true;
bool different = false;
bool increasing = true;
if (n == 0) {
for (int di = 0; di < dims_; ++di) {
if (ix_t(n, di) < 0 || ix_t(n, di) >= shape_[di]) valid = false;
}
different = true;
} else {
for (int di = 0; di < dims_; ++di) {
if (ix_t(n, di) < 0 || ix_t(n, di) >= shape_[di]) valid = false;
int64 diff = ix_t(n, order_[di]) - ix_t(n - 1, order_[di]);
if (diff > 0) different = true;
if (!different && diff < 0) increasing = false;
}
}
if (TF_PREDICT_FALSE(!valid || !increasing || !different)) {
string index = strings::StrCat("indices[", n, "] = [");
for (int di = 0; di < dims_; ++di) {
strings::StrAppend(&index, ix_t(n, di), di < dims_ - 1 ? "," : "]");
}
if (!valid) {
return errors::InvalidArgument(index,
" is out of bounds: need 0 <= index < [",
str_util::Join(shape_, ","), "]");
}
if (!increasing) {
return errors::InvalidArgument(index, " is out of order");
}
if (!different) {
return errors::InvalidArgument(index, " is repeated");
}
}
return Status::OK();
}
// Helper for ToDense<T>()
template <typename T>
bool ValidateAndInitializeToDense(Tensor* out, bool initialize);
// Helper for Split() that returns the slice index.
static inline int GetSliceIndex(const int dim, const int split_size,
const int residual) {
DCHECK_GT(split_size, 0);
DCHECK_GE(dim, 0);
if (residual == 0) return dim / split_size;
const int offset = residual * (split_size + 1);
if (dim < offset) {
return dim / (split_size + 1);
} else {
return residual + ((dim - offset) / split_size);
}
}
// Helper for Split() that returns the dimension in the slice.
static inline int GetDimensionInSlice(const int dim, const int split_size,
const int residual) {
DCHECK_GT(split_size, 0);
DCHECK_GE(dim, 0);
if (residual == 0) return dim % split_size;
const int offset = residual * (split_size + 1);
if (dim < offset) {
return dim % (split_size + 1);
} else {
return (dim - offset) % split_size;
}
}
// Helper for Split() that returns the shape given a slice index.
static inline int GetSliceShape(const int slice_index, const int split_size,
const int residual) {
DCHECK_GT(split_size, 0);
DCHECK_GE(slice_index, 0);
if (residual == 0) return split_size;
if (slice_index < residual) {
return split_size + 1;
} else {
return split_size;
}
}
Tensor ix_;
Tensor vals_;
ShapeArray shape_;
ShapeArray order_;
int dims_;
};
// This operation updates the indices and values Tensor rows, so it is
// an in-place algorithm. It requires O(N log N) time and O(N)
// temporary space.
template <typename T>
void SparseTensor::Reorder(const VarDimArray& order) {
DCHECK_EQ(DataTypeToEnum<T>::v(), dtype())
<< "Reorder requested with the wrong datatype";
DCHECK_EQ(order.size(), dims_) << "Order length must be SparseTensor rank";
auto ix_t = ix_.matrix<int64>();
auto vals_t = vals_.vec<T>();
std::vector<int64> reorder(num_entries());
std::iota(reorder.begin(), reorder.end(), 0);
// Sort to get order of indices
switch (order.size()) {
#define CASE_SORT(ORDER_SIZE) \
case ORDER_SIZE: { \
FixedDimComparator<ORDER_SIZE> sorter(ix_t, order, shape()); \
std::sort(reorder.begin(), reorder.end(), sorter); \
break; \
}
CASE_SORT(0);
CASE_SORT(1);
CASE_SORT(2);
CASE_SORT(3);
CASE_SORT(4);
CASE_SORT(5);
#undef CASE_SORT
default: {
DimComparator sorter(ix_t, order, shape());
std::sort(reorder.begin(), reorder.end(), sorter);
}
}
// We have a forward reordering, but what we'll need is a
// permutation (the inverse). This can be calculated with O(1)
// additional
// and O(n) time (INVPERM) but we just do the simple thing here.
std::vector<size_t> permutation(reorder.size());
for (std::size_t n = 0; n < reorder.size(); ++n) {
permutation[reorder[n]] = n;
}
// Update indices & values by converting the permutations to
// a product of transpositions. Iterate over the cycles in the
// permutation, and convert each of those into a product of
// transpositions (swaps):
// https://en.wikipedia.org/wiki/Cyclic_permutation
// This is N swaps, 2*N comparisons.
for (std::size_t n = 0; n + 1 < permutation.size(); ++n) {
while (n != permutation[n]) {
std::size_t r = permutation[n];
std::swap_ranges(&(ix_t(n, 0)), &(ix_t(n + 1, 0)), &(ix_t(r, 0)));
std::swap(vals_t(n), vals_t(r));
std::swap(permutation[n], permutation[r]);
}
}
order_ = ShapeArray(order.begin(), order.end());
}
template <typename T>
bool SparseTensor::ValidateAndInitializeToDense(Tensor* out, bool initialize) {
DCHECK_EQ(DataTypeToEnum<T>::v(), dtype())
<< "ToDense requested with the wrong datatype";
DCHECK_EQ(out->shape().dims(), dims_)
<< "Incompatible dimensions between SparseTensor and output";
DCHECK_EQ(out->dtype(), DataTypeToEnum<T>::v())
<< "Output must be type: " << DataTypeToEnum<T>::v()
<< " but got: " << out->dtype();
// Make sure the dense output is the same rank and has room
// to hold the SparseTensor.
const auto& out_shape = out->shape();
if (shape_.size() != out_shape.dims()) return false;
for (int d = 0; d < shape_.size(); ++d) {
if (shape_[d] > out_shape.dim_size(d)) return false;
}
if (initialize) {
auto out_t = out->flat<T>();
out_t.setConstant(T());
}
return true;
}
template <typename T>
bool SparseTensor::ToDense(Tensor* out, bool initialize) {
if (!ValidateAndInitializeToDense<T>(out, initialize)) return false;
auto out_t = out->flat<T>();
auto ix_t = ix_.matrix<int64>();
auto vals_t = vals_.vec<T>();
std::vector<int64> strides(dims_);
const auto& out_shape = out->shape();
if (dims_ > 0) {
strides[dims_ - 1] = 1;
}
for (int d = dims_ - 2; d >= 0; --d) {
strides[d] = strides[d + 1] * out_shape.dim_size(d + 1);
}
for (int n = 0; n < vals_t.dimension(0); ++n) {
bool invalid_dims = false;
int64 ix = 0;
for (int d = 0; d < dims_; ++d) {
const int64 ix_n_d = internal::SubtleMustCopy(ix_t(n, d));
if (!FastBoundsCheck(ix_n_d, out_shape.dim_size(d))) {
invalid_dims = true;
}
ix += strides[d] * ix_n_d;
}
if (invalid_dims) return false;
out_t(ix) = vals_t(n);
}
return true;
}
template <typename T>
SparseTensor SparseTensor::Concat(
const gtl::ArraySlice<SparseTensor>& tensors) {
DCHECK_GE(tensors.size(), size_t{1}) << "Cannot concat 0 SparseTensors";
const int dims = tensors[0].dims_;
DCHECK_GE(dims, 1) << "Cannot concat 0-dimensional SparseTensors";
auto order_0 = tensors[0].order();
const int primary_dim = order_0[0];
ShapeArray final_order(order_0.begin(), order_0.end());
ShapeArray final_shape(tensors[0].shape().begin(), tensors[0].shape().end());
final_shape[primary_dim] = 0; // We'll build this up as we go along.
int num_entries = 0;
bool fully_ordered = true;
for (const SparseTensor& st : tensors) {
DCHECK_EQ(st.dims_, dims) << "All SparseTensors must have the same rank.";
DCHECK_EQ(DataTypeToEnum<T>::v(), st.dtype())
<< "Concat requested with the wrong data type";
DCHECK_GE(st.order()[0], 0) << "SparseTensor must be ordered";
DCHECK_EQ(st.order()[0], primary_dim)
<< "All SparseTensors' order[0] must match. This is the concat dim.";
if (st.order() != final_order) fully_ordered = false;
const VarDimArray& st_shape = st.shape();
for (int d = 0; d < dims - 1; ++d) {
const int cdim = (d < primary_dim) ? d : d + 1;
DCHECK_EQ(final_shape[cdim], st_shape[cdim])
<< "All SparseTensors' shapes must match except on the concat dim. "
<< "Concat dim: " << primary_dim
<< ", mismatched shape at dim: " << cdim
<< ". Expecting shape like: [" << str_util::Join(final_shape, ",")
<< "] but saw shape: [" << str_util::Join(st_shape, ",") << "]";
}
// Update dimension of final shape
final_shape[primary_dim] =
(final_shape[primary_dim] + st_shape[primary_dim]);
num_entries += st.num_entries(); // Update number of entries
}
// If nonconsistent ordering among inputs, set final order to -1s.
if (!fully_ordered) {
final_order = UndefinedOrder(final_shape);
}
Tensor output_ix(DT_INT64, TensorShape({num_entries, dims}));
Tensor output_vals(DataTypeToEnum<T>::v(), TensorShape({num_entries}));
TTypes<int64>::Matrix ix_t = output_ix.matrix<int64>();
typename TTypes<T>::Vec vals_t = output_vals.vec<T>();
Eigen::DenseIndex offset = 0;
int64 shape_offset = 0;
for (const SparseTensor& st : tensors) {
const int st_num_entries = st.num_entries();
// Fill in indices & values.
std::copy_n(&st.vals_.vec<T>()(0), st_num_entries, &vals_t(offset));
const auto* st_ix = &st.ix_.matrix<int64>()(0, 0);
auto* ix_out = &ix_t(offset, 0);
for (std::size_t i = 0; i < st_num_entries * dims; ++i) {
*ix_out++ = *st_ix++ + ((i % dims == primary_dim) ? shape_offset : 0);
}
offset += st_num_entries;
shape_offset += st.shape()[primary_dim];
}
return SparseTensor(output_ix, output_vals, final_shape, final_order);
}
template <typename T>
std::vector<SparseTensor> SparseTensor::Split(const SparseTensor& input_tensor,
const int split_dim,
const int num_split,
Status* status /* = nullptr */) {
std::vector<Tensor> output_indices;
std::vector<Tensor> output_values;
std::vector<TensorShape> output_shapes;
output_indices.reserve(num_split);
output_values.reserve(num_split);
output_shapes.reserve(num_split);
std::vector<typename TTypes<int64>::Matrix> output_indices_t;
std::vector<typename TTypes<T>::Vec> output_values_t;
output_indices_t.reserve(num_split);
output_values_t.reserve(num_split);
auto input_values_t = input_tensor.values().vec<T>();
auto input_indices_t = input_tensor.indices().matrix<int64>();
std::vector<int> num_values(num_split, 0);
const int num_dim = input_tensor.shape().size();
const int split_dim_size = input_tensor.shape()[split_dim];
const int split_size = split_dim_size / num_split;
if (!(num_split > 0 && num_split <= split_dim_size) && status != nullptr) {
*status = Status(error::INVALID_ARGUMENT,
strings::StrCat("num_split must be in the interval (0, ",
split_dim_size, "]"));
return {};
}
if (!(split_dim >= 0 && split_dim < num_dim)) {
*status = Status(
error::INVALID_ARGUMENT,
strings::StrCat("num_dim must be in the interval [0, ", num_dim, ")"));
return {};
}
const int residual = split_dim_size % num_split;
for (int i = 0; i < input_tensor.indices().dim_size(0); ++i) {
const int dim = input_tensor.indices().matrix<int64>()(i, split_dim);
int slice_index = GetSliceIndex(dim, split_size, residual);
num_values[slice_index]++;
}
for (int i = 0; i < num_split; ++i) {
// TODO(ataei): Pass an allocator to avoid allocating large memory buffer.
output_indices.emplace_back(DT_INT64,
TensorShape({num_values[i], num_dim}));
output_values.emplace_back(DataTypeToEnum<T>::v(),
TensorShape({num_values[i]}));
output_shapes.emplace_back(input_tensor.shape());
output_indices_t.emplace_back(output_indices[i].matrix<int64>());
output_values_t.emplace_back(output_values[i].vec<T>());
const int size = GetSliceShape(i, split_size, residual);
output_shapes[i].set_dim(split_dim, size);
}
std::vector<int> values_inserted_in_slice(num_split, 0);
for (int i = 0; i < input_tensor.indices().dim_size(0); ++i) {
const int dim = input_indices_t(i, split_dim);
const int slice_index = GetSliceIndex(dim, split_size, residual);
const int slice_dim = values_inserted_in_slice[slice_index]++;
output_values_t[slice_index](slice_dim) = input_values_t(i);
for (int j = 0; j < num_dim; ++j) {
const int64 original_dim = input_indices_t(i, j);
output_indices_t[slice_index](slice_dim, j) =
(j == split_dim)
? GetDimensionInSlice(original_dim, split_size, residual)
: original_dim;
}
}
std::vector<SparseTensor> output_tensors;
output_tensors.reserve(num_split);
for (int i = 0; i < num_split; ++i) {
SparseTensor tensor;
Status create_status =
Create(output_indices[i], output_values[i], output_shapes[i], &tensor);
if (!create_status.ok() && status != nullptr) {
*status = create_status;
return {};
}
output_tensors.push_back(std::move(tensor));
}
return output_tensors;
}
template <typename T>
Status SparseTensor::Split(const SparseTensor& input_tensor,
const int split_dim, const int num_split,
std::vector<SparseTensor>* result) {
Status status;
*result = Split<T>(input_tensor, split_dim, num_split, &status);
return status;
}
template <typename T>
SparseTensor SparseTensor::Slice(const SparseTensor& input_tensor,
const gtl::ArraySlice<int64>& start,
const gtl::ArraySlice<int64>& size) {
TensorShape output_shape(input_tensor.shape());
const int dims = input_tensor.dims();
for (int dim = 0; dim < dims; dim++) {
int64 dim_size = start[dim] + size[dim] < output_shape.dim_size(dim)
? size[dim]
: output_shape.dim_size(dim) - start[dim];
output_shape.set_dim(dim, dim_size);
}
auto input_indices_t = input_tensor.indices().matrix<int64>();
auto input_values_t = input_tensor.values().vec<T>();
// Find the number of indices that fall inside start and size.
int count = 0;
for (int i = 0; i < input_tensor.indices().dim_size(0); i++) {
// The following will check to see if an input is within the
// range specified by start and size.
// The for loop below iterates through all dimensions. In case
// the index falls outside of the start and size at any dimension,
// it will be considered as a "no hit" (hit = false). In this
// case, it will not be counted as the index that fall inside
// the range specified by start and size.
bool hit = true;
for (int dim = 0; dim < dims; dim++) {
if (!(start[dim] <= input_indices_t(i, dim) &&
input_indices_t(i, dim) < start[dim] + size[dim])) {
hit = false;
break;
}
}
if (!hit) {
continue;
}
count++;
}
Tensor output_values(DataTypeToEnum<T>::v(), TensorShape({count}));
Tensor output_indices(DT_INT64, TensorShape({count, dims}));
auto output_values_t = output_values.vec<T>();
auto output_indices_t = output_indices.matrix<int64>();
// Obtain the output indices that fall inside start and size.
int index = 0;
for (int i = 0; i < input_tensor.indices().dim_size(0) && index < count;
i++) {
// The logic here is similar as the above except that the above
// only count the number of indices while here we actually generate
// the output.
bool hit = true;
for (int dim = 0; dim < dims; dim++) {
if (!(start[dim] <= input_indices_t(i, dim) &&
input_indices_t(i, dim) < start[dim] + size[dim])) {
hit = false;
break;
}
}
if (!hit) {
continue;
}
output_values_t(index) = input_values_t(i);
for (int dim = 0; dim < dims; dim++) {
output_indices_t(index, dim) = input_indices_t(i, dim) - start[dim];
}
index++;
}
return SparseTensor(output_indices, output_values, output_shape);
}
} // namespace sparse
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_SPARSE_SPARSE_TENSOR_H_
@@ -0,0 +1,116 @@
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_STAT_SUMMARIZER_H_
#define TENSORFLOW_CORE_UTIL_STAT_SUMMARIZER_H_
#include <stdlib.h>
#include <cmath>
#include <limits>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/stat_summarizer_options.h"
#include "tensorflow/core/util/stats_calculator.h"
namespace tensorflow {
class GraphDef;
class StepStats;
class NodeExecStats;
// A StatSummarizer assists in performance analysis of Graph executions.
//
// It summarizes time spent executing (on GPU/CPU), memory used etc. across
// multiple executions of a single Graph from the StepStats collected during
// graph execution.
//
// See tensorflow/tools/benchmark/benchmark_model.cc for an example usage.
class StatSummarizer {
public:
explicit StatSummarizer(const StatSummarizerOptions& options);
// Deprecated: Use StatSummarizer(const StatSummarizerOptions&) instead. The
// GraphDef is not needed by the StatSummarizer.
explicit StatSummarizer(const tensorflow::GraphDef& tensorflow_graph);
~StatSummarizer();
// Adds another run's StepStats output to the aggregate counts.
void ProcessStepStats(const StepStats& step_stats);
// Returns a string detailing the accumulated runtime stats in a tab-separated
// format which can be pasted into a spreadsheet for further analysis.
std::string GetOutputString() const {
return stats_calculator_->GetOutputString();
}
std::string ShortSummary() const {
return stats_calculator_->GetShortSummary();
}
// Prints the string returned by GetOutputString().
void PrintStepStats() const;
// Prints the output tensor sizes and types for each node.
void PrintOutputs() const;
void ComputeStatsByType(
std::map<std::string, int64_t>* node_type_map_count,
std::map<std::string, int64_t>* node_type_map_time,
std::map<std::string, int64_t>* node_type_map_memory,
std::map<std::string, int64_t>* node_type_map_times_called,
int64_t* accumulated_us) const {
stats_calculator_->ComputeStatsByType(
node_type_map_count, node_type_map_time, node_type_map_memory,
node_type_map_times_called, accumulated_us);
}
std::string GetStatsByNodeType() const {
return stats_calculator_->GetStatsByNodeType();
}
std::string GetStatsByMetric(const string& title,
StatsCalculator::SortingMetric sorting_metric,
int num_stats) const {
return stats_calculator_->GetStatsByMetric(title, sorting_metric,
num_stats);
}
int num_runs() const { return stats_calculator_->num_runs(); }
// Returns stats of total microseconds spent by all nodes in each run.
const Stat<int64_t>& run_total_us() const {
return stats_calculator_->run_total_us();
}
private:
void Validate(const std::vector<TensorDescription>* outputs,
const NodeExecStats& ns) const;
std::map<std::string, std::vector<TensorDescription> > outputs_;
std::unique_ptr<StatsCalculator> stats_calculator_;
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_STAT_SUMMARIZER_H_
@@ -0,0 +1,43 @@
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_STAT_SUMMARIZER_OPTIONS_H_
#define TENSORFLOW_CORE_UTIL_STAT_SUMMARIZER_OPTIONS_H_
namespace tensorflow {
// Used to control the output of the statistics summarizer;
class StatSummarizerOptions {
public:
StatSummarizerOptions()
: show_run_order(true),
run_order_limit(0),
show_time(true),
time_limit(10),
show_memory(true),
memory_limit(10),
show_type(true),
show_summary(true) {}
bool show_run_order;
int run_order_limit;
bool show_time;
int time_limit;
bool show_memory;
int memory_limit;
bool show_type;
bool show_summary;
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_STAT_SUMMARIZER_OPTIONS_H_
@@ -0,0 +1,189 @@
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_STATS_CALCULATOR_H_
#define TENSORFLOW_CORE_UTIL_STATS_CALCULATOR_H_
#include <stdlib.h>
#include <cmath>
#include <limits>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include "tensorflow/core/util/stat_summarizer_options.h"
namespace tensorflow {
template <typename ValueType, typename HighPrecisionValueType = double>
class Stat {
public:
void UpdateStat(ValueType v) {
if (count_ == 0) {
first_ = v;
}
newest_ = v;
max_ = std::max(v, max_);
min_ = std::min(v, min_);
++count_;
sum_ += v;
squared_sum_ += static_cast<HighPrecisionValueType>(v) * v;
}
void Reset() { new (this) Stat<ValueType, HighPrecisionValueType>(); }
bool empty() const { return count_ == 0; }
ValueType first() const { return first_; }
ValueType newest() const { return newest_; }
ValueType max() const { return max_; }
ValueType min() const { return min_; }
int64_t count() const { return count_; }
ValueType sum() const { return sum_; }
HighPrecisionValueType squared_sum() const { return squared_sum_; }
bool all_same() const { return (count_ == 0 || min_ == max_); }
HighPrecisionValueType avg() const {
return empty() ? std::numeric_limits<ValueType>::quiet_NaN()
: static_cast<HighPrecisionValueType>(sum_) / count_;
}
ValueType std_deviation() const {
return all_same() ? 0 : sqrt(squared_sum_ / count_ - avg() * avg());
}
void OutputToStream(std::ostream* stream) const {
if (empty()) {
*stream << "count=0";
} else if (all_same()) {
*stream << "count=" << count_ << " curr=" << newest_;
if (count_ > 1) *stream << "(all same)";
} else {
*stream << "count=" << count_ << " first=" << first_
<< " curr=" << newest_ << " min=" << min_ << " max=" << max_
<< " avg=" << avg() << " std=" << std_deviation();
}
}
friend std::ostream& operator<<(std::ostream& stream,
const Stat<ValueType>& stat) {
stat.OutputToStream(&stream);
return stream;
}
private:
ValueType first_ = 0;
ValueType newest_ = 0;
ValueType max_ = std::numeric_limits<ValueType>::min();
ValueType min_ = std::numeric_limits<ValueType>::max();
int64_t count_ = 0;
ValueType sum_ = 0;
HighPrecisionValueType squared_sum_ = 0;
};
// A StatsCalculator assists in performance analysis of Graph executions.
//
// It summarizes time spent executing (on GPU/CPU), memory used etc for
// graph execution.
//
// For example usage see StatsSummarizer.
class StatsCalculator {
public:
enum SortingMetric {
BY_NAME,
BY_RUN_ORDER,
BY_TIME,
BY_MEMORY,
BY_TYPE,
};
explicit StatsCalculator(const StatSummarizerOptions& options);
// Returns a string detailing the accumulated runtime stats in a tab-separated
// format which can be pasted into a spreadsheet for further analysis.
std::string GetOutputString() const;
std::string GetShortSummary() const;
void ComputeStatsByType(
std::map<std::string, int64_t>* node_type_map_count,
std::map<std::string, int64_t>* node_type_map_time,
std::map<std::string, int64_t>* node_type_map_memory,
std::map<std::string, int64_t>* node_type_map_times_called,
int64_t* accumulated_us) const;
std::string GetStatsByNodeType() const;
std::string GetStatsByMetric(const std::string& title,
SortingMetric sorting_metric,
int num_stats) const;
// Returns number of runs.
int num_runs() const { return static_cast<int>(run_total_us_.count()); }
// Returns stats of total microseconds spent by all nodes in each run.
const Stat<int64_t>& run_total_us() const { return run_total_us_; }
void UpdateRunTotalUs(int64_t run_total_us) {
run_total_us_.UpdateStat(run_total_us);
}
void UpdateMemoryUsed(int64_t memory) { memory_.UpdateStat(memory); }
struct Detail {
std::string name;
std::string type;
int64_t run_order;
Stat<int64_t> start_us;
Stat<int64_t> rel_end_us;
Stat<int64_t> mem_used;
int64_t times_called;
};
const std::map<std::string, Detail>& GetDetails() const { return details_; }
void AddNodeStats(const std::string& name, const std::string& type,
int64_t run_order, int64_t start_us, int64_t rel_end_us,
int64_t mem_used);
private:
void OrderNodesByMetric(SortingMetric sorting_metric,
std::vector<const Detail*>* details) const;
std::string HeaderString(const std::string& title) const;
std::string ColumnString(const Detail& detail,
const int64_t cumulative_stat_on_node,
const Stat<int64_t>& stat) const;
Stat<int64_t> run_total_us_;
Stat<int64_t> memory_;
std::map<std::string, Detail> details_;
StatSummarizerOptions options_;
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_STATS_CALCULATOR_H_
@@ -0,0 +1,41 @@
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_STREAM_EXECUTOR_UTIL_H_
#define TENSORFLOW_CORE_UTIL_STREAM_EXECUTOR_UTIL_H_
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/stream_executor.h"
namespace tensorflow {
// StreamExecutorUtil contains functions useful for interfacing
// between StreamExecutor classes and TensorFlow.
class StreamExecutorUtil {
public:
// Map a Tensor as a DeviceMemory object wrapping the given typed
// buffer.
template <typename T>
static se::DeviceMemory<T> AsDeviceMemory(const Tensor& t) {
T* ptr = reinterpret_cast<T*>(const_cast<char*>(t.tensor_data().data()));
return se::DeviceMemory<T>(se::DeviceMemoryBase(ptr, t.TotalBytes()));
}
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_STREAM_EXECUTOR_UTIL_H_
@@ -0,0 +1,65 @@
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_STRIDED_SLICE_OP_H_
#define TENSORFLOW_CORE_UTIL_STRIDED_SLICE_OP_H_
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
namespace tensorflow {
// Runs validation on the strided slice op parameters.
//
// Is a separate translation unit from the kernel so that:
// 1. The op's shape function can use it.
// 2. The code size is reduced vs templating this on the kernel's type.
//
// Note that when input_shape is not fully specified, only <final_shape> and
// <processing_shape> are valid; <is_identity>, <is_simple_slice> and other
// output parameters will not be accurate.
//
// If <begin_tensor> or <end_tensor> are nullptr, <begin> and <end> will not be
// valid. In this case, <slice_dim0> and <is_identity> will be true only if a
// determination can be made based on the information given. A best effort is
// made to set <processing_shape> and <final_shape> based on <input_shape>, but
// some dimensions of <processing_shape> and/or <final_shape> may be unknown
// (-1). Any validation that can be done without complete information is
// performed.
Status ValidateStridedSliceOp(
const Tensor* begin_tensor, const Tensor* end_tensor,
const Tensor& strides_tensor, const PartialTensorShape& input_shape,
int32 begin_mask_spec, int32 end_mask_spec, const int32 ellipsis_mask,
int32 new_axis_mask, int32 shrink_axis_mask,
PartialTensorShape* processing_shape, PartialTensorShape* final_shape,
bool* is_identity, bool* is_simple_slice, bool* slice_dim0,
gtl::InlinedVector<int64, 4>* begin, gtl::InlinedVector<int64, 4>* end,
gtl::InlinedVector<int64, 4>* strides);
// Same as above, but the outputs are TensorShape, not PartialTensorShape
Status ValidateStridedSliceOp(
const Tensor* begin_tensor, const Tensor* end_tensor,
const Tensor& strides_tensor, const PartialTensorShape& input_shape,
int32 begin_mask_spec, int32 end_mask_spec, const int32 ellipsis_mask,
int32 new_axis_mask, int32 shrink_axis_mask, TensorShape* processing_shape,
TensorShape* final_shape, bool* is_identity, bool* is_simple_slice,
bool* slice_dim0, gtl::InlinedVector<int64, 4>* begin,
gtl::InlinedVector<int64, 4>* end, gtl::InlinedVector<int64, 4>* strides);
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_STRIDED_SLICE_OP_H_
@@ -0,0 +1,47 @@
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// A minimal library exposing the naming logic used in tensor_bundle.
//
// A tensor bundle contains a metadata file and sharded data files, which all
// share a common pathname prefix.
//
// Given the prefix, the actual pathnames of the files can be queried via:
//
// MetaFilename(prefix): pathname of the metadata file.
// DataFilename(prefix, shard_id, num_shards): pathname of a data file.
//
// Typical usage includes forming a filepattern to match files on disk:
//
// // To find the unique metadata file.
// const string metadata_file = MetaFilename("/fs/train/ckpt-step");
// Env::Default()->GetMatchingFiles(metadata_file, &path);
//
// Regexp can also be used: e.g. R"<prefix>.data-\d{5}-of-\d{5}" for data files.
#ifndef TENSORFLOW_CORE_UTIL_TENSOR_BUNDLE_NAMING_H_
#define TENSORFLOW_CORE_UTIL_TENSOR_BUNDLE_NAMING_H_
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
string MetaFilename(StringPiece prefix);
string DataFilename(StringPiece prefix, int32 shard_id, int32 num_shards);
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_TENSOR_BUNDLE_NAMING_H_
@@ -0,0 +1,349 @@
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// A tensor bundle is a set of immutable persistent files storing a set of named
// tensors. It is designed for checkpointing TensorFlow tensors.
//
// The paths of the managed files share a common prefix; e.g., with the prefix:
// /fs/model/train/ckpt-step/ckpt
//
// the bundle may contain a metadata file, and sharded data files:
// /fs/model/train/ckpt-step/
// ckpt.index
// ckpt.data-00000-of-00020
// ckpt.data-00001-of-00020
// ...
// ckpt.data-00019-of-00020
//
// The ".index" file is a string-string immutable table
// (tensorflow::table::Table). Each key is a name of a tensor and its value is
// a serialized BundleEntryProto. Each BundleEntryProto describes the metadata
// of a tensor: which of the "data" files contains the content of a tensor, the
// offset into that file, checksum, some auxiliary data, etc.
//
// A tensor bundle can be accessed randomly using a BundleReader. Usage:
//
// BundleReader reader(env, "/fs/model/train/ckpt-step/ckpt");
// reader.Lookup("name", &tensor);
//
// A tensor bundle can be built using BundleWriter. Each BundleWriter builds a
// single data file bundle. Multiple bundles can then be merged by
// MergeBundles() without reading and writing large chunk of data: it reads the
// metadata files and outputs a single merged metadata. Typical usage:
//
// worker 0:
// BundleWriter writer(env, "/fs/model/train/ckpt-step/tmp/worker0-step");
// writer.Add(...); // Adds the tensors on this worker.
// writer.Finish(); // Flushes.
// worker 1:
// BundleWriter writer(env, "/fs/model/train/ckpt-step/tmp/worker1-step");
// writer.Add(...);
// writer.Finish();
// worker 2:
// MergeBundles(env,
// {"/fs/model/train/ckpt-step/tmp/worker0-step",
// "/fs/model/train/ckpt-step/tmp/worker1-step"},
// "/fs/model/train/ckpt-step/ckpt" /* merged prefix */);
//
#ifndef TENSORFLOW_CORE_UTIL_TENSOR_BUNDLE_TENSOR_BUNDLE_H_
#define TENSORFLOW_CORE_UTIL_TENSOR_BUNDLE_TENSOR_BUNDLE_H_
#include "tensorflow/core/protobuf/tensor_bundle.pb.h"
#include <map>
#include <string>
#include <unordered_map>
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_slice.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/lib/io/inputbuffer.h"
#include "tensorflow/core/lib/io/table.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/file_system.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/tensor_bundle/naming.h"
#include "tensorflow/core/util/tensor_slice_set.h"
namespace tensorflow {
class FileOutputBuffer;
// Versioning of the tensor bundle format.
// Follows the same rules as 3p/tf/core/public/version.h.
//
// History:
// 0. Any tensor bundles produced before this field was added.
// 1. Added this field (2016-09-14).
extern const int kTensorBundleMinProducer;
extern const int kTensorBundleMinConsumer;
extern const int kTensorBundleVersion;
// The empty string, hence always the first key in the metadata table. Its
// corresponding value is a BundleHeaderProto.
extern const char* const kHeaderEntryKey;
// Builds a string-string table of tensor names to BundleEntryProto (metadata).
//
// On construction, attempts to create a directory given by the dirname of
// "prefix", so "status()" must be checked before calling any member functions.
//
// All threads accessing the same BundleWriter must synchronize.
class BundleWriter {
public:
struct Options {
Options() {}
// Alignment, in bytes, for tensor data.
// Must be >= 1. The default size of 1 densely packs tensors.
int data_alignment{1};
};
BundleWriter(Env* env, StringPiece prefix,
const Options& options = Options());
// Adds the tensor "val" under key "key".
// Across calls "key" must be unique but can be added in any order.
Status Add(StringPiece key, const Tensor& val);
// Partitioned variables support.
// A slice of a full tensor is stored in two entries in the metadata table:
//
// full_tensor_key -> BundleEntryProto, describing all stored slices
// of this full tensor. Does not append to the data
// file.
// encoded slice key -> BundleEntryProto, describing one particular slice.
// Appends values of this slice to the data file.
//
// Slices of a full tensor can be added in any order.
//
// If a full tensor has slices placed on N devices and N BundleWriter's are
// concurrently used, the caller must use MergeBundles() to ensure that a
// consistent entry for "full_tensor_key" is produced.
//
// Returns an error if the same slice is added the second time.
Status AddSlice(StringPiece full_tensor_key,
const TensorShape& full_tensor_shape,
const TensorSlice& slice_spec, const Tensor& slice_tensor);
// Finishes the writer and flushes.
Status Finish() TF_MUST_USE_RESULT;
Status status() const { return status_; }
private:
Env* const env_; // Not owned.
const Options options_;
const string prefix_;
const string tmp_metadata_path_;
const string tmp_data_path_;
std::unique_ptr<FileOutputBuffer> out_;
int64 size_; // Number of bytes written into out_.
std::map<string, BundleEntryProto> entries_;
Status status_;
TF_DISALLOW_COPY_AND_ASSIGN(BundleWriter);
};
// Merges a set of bundles (given their prefixes) into a single bundle with the
// given "merged_prefix". The merged metadata is guaranteed to be consistent.
//
// If there are N bundles in "prefixes", during the merge the data files will be
// renamed to contain a proper sharded file spec, with num_shards set to the sum
// of num_shards across the N input bundles.
//
// The caller should only rely on the metadata file of the merged bundle to
// query information about a tensor. In particular, this function does not
// guarantee not to re-order the input data files.
//
// Once merged, makes a best effort to delete the old metadata files.
// Returns OK iff all bundles are successfully merged.
Status MergeBundles(Env* env, gtl::ArraySlice<string> prefixes,
StringPiece merged_prefix);
// On construction, silently attempts to read the metadata associated with
// "prefix". If caller intends to call any function afterwards, "status()"
// must be checked.
// All threads accessing the same BundleReader must synchronize.
class BundleReader {
public:
BundleReader(Env* const env, StringPiece prefix);
~BundleReader();
// Is ok() iff the reader construction is successful (completed the read of
// the metadata).
Status status() const { return status_; }
// Queries whether the bundle contains an entry keyed by "key". Calls Seek()
// internally, so this call invalidates the reader's current position.
// REQUIRES: status().ok()
bool Contains(StringPiece key);
// Looks up the dtype and the shape of the tensor keyed by "key".
// REQUIRES: status().ok()
Status LookupDtypeAndShape(StringPiece key, DataType* dtype,
TensorShape* shape) TF_MUST_USE_RESULT;
// Looks up the shape of the tensor keyed by "key".
// Clears "shape" if not found.
// REQUIRES: status().ok()
Status LookupTensorShape(StringPiece key,
TensorShape* shape) TF_MUST_USE_RESULT;
// Looks up the tensor keyed by "key". If "key" refers to a partitioned
// tensor, attempts to look up the full contents using all stored slices.
//
// Caller must make sure "val" has the same shape and dtype as the
// corresponding contents, so that its buffer can be filled without needing
// extra allocation. These can be queried via "LookupDtypeAndShape()".
//
// On error, "val" may contain nonsense data. Returns a NotFound error if
// tensor keyed by "key" does not exist in this bundle.
//
// Validates the stored crc32c checksum against the restored bytes.
// REQUIRES: status().ok()
Status Lookup(StringPiece key, Tensor* val) TF_MUST_USE_RESULT;
// Looks up the tensor pointed to by the internal iterator.
//
// On error, "val" may contain nonsense data.
//
// Validates the stored crc32c checksum against the restored bytes.
// REQUIRES: status().ok() && Valid()
Status ReadCurrent(Tensor* val) TF_MUST_USE_RESULT;
// Looks up the slices of the tensor keyed by "key". On OK, "slices"
// is non-empty if and only if the tensor is a partitioned tensor.
//
// Warning - there is no guaranteed ordering for the returned slices, so
// a slice with a larger start index in some dimension could come before
// another slice with a smaller start index in the same dimension.
// REQUIRES: status().ok()
Status LookupTensorSlices(StringPiece key, std::vector<TensorSlice>* slices)
TF_MUST_USE_RESULT;
// Looks up a specific slice of a partitioned tensor.
// It is only required that the stored slices cover the requested slice,
// namely "slice_spec" is a subset of the union of the stored slices.
// REQUIRES: status().ok()
Status LookupSlice(StringPiece full_tensor_key, const TensorSlice& slice_spec,
Tensor* val) TF_MUST_USE_RESULT;
// Seeks to the first position in the bundle whose key is no less than "key".
// REQUIRES: status().ok()
void Seek(StringPiece key) { return iter_->Seek(key); }
// Moves to the next position in the bundle.
// REQUIRES: status().ok()
void Next() const { iter_->Next(); }
// Returns true iff the reader is positioned to a key/val pair.
// REQUIRES: status().ok()
bool Valid() const { return iter_->Valid(); }
// Returns the key at the current position.
// REQUIRES: status().ok() && Valid()
StringPiece key() const { return iter_->key(); }
// Returns the raw value at the current position.
// REQUIRES: status().ok() && Valid()
StringPiece value() const { return iter_->value(); }
string DebugString();
private:
// Seeks for "key" and reads the metadata proto.
// On non-OK return, clears "entry" for the caller.
// REQUIRES: status().ok()
Status GetBundleEntryProto(StringPiece key,
BundleEntryProto* entry) TF_MUST_USE_RESULT;
// Reads the tensor value described by the metadata proto "entry".
// Usage for "val" follows the comment of "Lookup()".
Status GetValue(const BundleEntryProto& entry,
Tensor* val) TF_MUST_USE_RESULT;
// Reads the slice described by "slice_spec". The corresponding full tensor
// has key "ful_tensor_key" and metadata proto "full_tensor_entry".
// REQUIRES: full_tensor_entry.slices_size() > 0
Status GetSliceValue(StringPiece full_tensor_key,
const BundleEntryProto& full_tensor_entry,
const TensorSlice& slice_spec,
Tensor* val) TF_MUST_USE_RESULT;
Env* env_; // Not owned.
const string prefix_;
Status status_;
RandomAccessFile* metadata_; // Owned.
table::Table* table_;
table::Iterator* iter_;
// Owned the InputBuffer objects and their underlying RandomAccessFile's.
std::unordered_map<int32, io::InputBuffer*> data_;
// Maps each partitioned tensor's key to its stored slices (represented in a
// TensorSliceSet). Populated on-demand.
std::unordered_map<string, checkpoint::TensorSliceSet*> tensor_slices_;
// Expected number of data file shards in the bundle. Extracted by reading
// the header entry in the metadata table.
int num_shards_;
friend class TensorBundleAlignmentTest; // For testing data alignment.
TF_DISALLOW_COPY_AND_ASSIGN(BundleReader);
};
// A buffering wrapper for a WritableFile. Useful if the caller wishes to issue
// small writes to a file (e.g. writing out a list of small varints).
// External synchronization must be used in the presence of concurrent callers.
class FileOutputBuffer {
public:
FileOutputBuffer(WritableFile* file, size_t buffer_size)
: file_(file), position_(0), buffer_size_(buffer_size) {
DCHECK_GT(buffer_size, 0);
buffer_.resize(buffer_size);
}
~FileOutputBuffer();
// Buffered append.
Status Append(StringPiece data);
// Returns the running crc32c checksum of all currently appended bytes.
uint32 crc32c() { return crc32c_; }
// Clears the running crc32c checksum.
void clear_crc32c() { crc32c_ = 0; }
// Appends the buffered data, then closes the underlying file.
Status Close();
private:
// Appends the buffered data to the underlying file. Does NOT flush the file.
Status FlushBuffer();
WritableFile* file_; // Owned.
// buffer_[0, position_) holds the buffered data not yet appended to the
// underlying file.
size_t position_;
const size_t buffer_size_;
std::vector<char> buffer_;
// Checksum of all appended bytes since construction or last clear_crc32c().
uint32 crc32c_ = 0;
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_TENSOR_BUNDLE_TENSOR_BUNDLE_H_
@@ -0,0 +1,617 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_TENSOR_FORMAT_H_
#define TENSORFLOW_CORE_UTIL_TENSOR_FORMAT_H_
#include <array>
#include <vector>
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
// Tensor format for input/output activations used in convolution operations.
// The mnemonics specify the meaning of each tensor dimension sorted from
// largest to smallest memory stride.
// N = Batch, H = Image Height, W = Image Width, C = Number of Channels.
// TODO(pauldonnelly): It would probably be better to switch to a registration
// process for tensor formats, so specialized formats could be defined more
// locally to where they are used.
enum TensorFormat {
// FORMAT_NHWC is the default format in TensorFlow.
FORMAT_NHWC = 0,
// FORMAT_NCHW often improves performance on GPUs.
FORMAT_NCHW = 1,
// NCHW_VECT_C is the most performant tensor format for cudnn6's quantized
// int8 convolution and fused convolution. It is laid out in the same order
// as NCHW, except that the size of the Channels dimension is divided by 4,
// and a new dimension of size 4 is appended, which packs 4 adjacent channel
// activations for the same pixel into an int32. Thus an NCHW format tensor
// with dimensions [N, C, H, W] would have dimensions [N, C/4, H, W, 4] in
// NCHW_VECT_C format.
// A pre-condition of this format is that C must be a multiple of 4.
FORMAT_NCHW_VECT_C = 2,
// Similar to NHWC, but the size of the W dimension is divided by 4, and a
// new dimension of size 4 is appended, which packs 4 adjacent activations
// in the width dimension.
FORMAT_NHWC_VECT_W = 3,
// Note: although the current code in this file assumes VECT_C and VECT_W
// enums imply int8x4 vectors, this should not be relied upon.
// In the future we may change the meaning of these enums to include vectors
// of other types such as int16x2, with op implementations automatically
// determining which format is implied based on the datatype.
// FORMAT_HWNC is for TPUs.
FORMAT_HWNC = 4,
// FORMAT_HWCN is for TPUs.
FORMAT_HWCN = 5,
};
// Tensor format for convolutional filters.
// The mnemonics specify the meaning of each tensor dimension sorted
// from largest to smallest memory stride.
// H = Kernel Height, W = Kernel Width, I = Input Channels, O = Output Channels.
// Note: In cudnnGetFilter4dDescriptor(), 'O' is called 'K', 'I' is called 'C'.
enum FilterTensorFormat {
// FORMAT_HWIO is the default filter format in TensorFlow.
// Ops that do not have a 'filter_format' attribute will assume this format.
FORMAT_HWIO = 0,
// FORMAT_OIHW often improves performance on GPUs.
FORMAT_OIHW = 1,
// OIHW_VECT_I is the most performant tensor format for cudnn6's quantized
// int8 convolution and fused convolution. It is analogous to the NCHW_VECT_C
// data format. It is laid out in the same order as OIHW, except that the size
// of the Input Channels dimension is divided by 4, and a new dimension of
// size 4 is appended, which packs 4 adjacent input channel weights into an
// int32. Thus an OIHW format filter with dimensions [O, I, H, W] would have
// dimensions [O, I/4, H, W, 4] in OIHW_VECT_I format.
// A pre-condition of this format is that I must be a multiple of 4.
FORMAT_OIHW_VECT_I = 2,
};
// Parse tensor format from the given string.
// Return true if the parsing succeeds, and false if it fails.
bool FormatFromString(const string& format_str, TensorFormat* format);
// Parse tensor format from the given string.
// Return true if the parsing succeeds, and false if it fails.
bool FilterFormatFromString(const string& format_str,
FilterTensorFormat* format);
// Convert a tensor format into string.
string ToString(TensorFormat format);
// Convert a filter tensor format into string.
string ToString(FilterTensorFormat format);
// Returns the number of spatial dims of a tensor of rank 'num_dims' and tensor
// format 'format'.
inline int GetTensorSpatialDims(int num_dims, TensorFormat format) {
switch (format) {
case FORMAT_NHWC:
case FORMAT_NCHW:
case FORMAT_HWNC:
case FORMAT_HWCN:
return num_dims - 2; // Exclude N,C.
case FORMAT_NCHW_VECT_C:
case FORMAT_NHWC_VECT_W:
// Note: the VECT_W is not counted as an independent spatial dim here,
// since it just a component of the width dimension.
return num_dims - 3; // Exclude N,C,VectDim.
}
}
inline int GetFilterTensorSpatialDims(int num_dims, FilterTensorFormat format) {
if (format == FORMAT_OIHW_VECT_I) {
return num_dims - 3; // Exclude O,I,InnerI.
} else {
return num_dims - 2; // Exclude O,I.
}
}
// Returns the rank of a tensor with 'num_spatial_dims' spatial dimensions and
// tensor format 'format'. This is the inverse of GetTensorSpatialDims.
inline int GetTensorDimsFromSpatialDims(int num_spatial_dims,
TensorFormat format) {
switch (format) {
case FORMAT_NHWC:
case FORMAT_NCHW:
case FORMAT_HWNC:
case FORMAT_HWCN:
return num_spatial_dims + 2; // Include N,C.
case FORMAT_NCHW_VECT_C:
case FORMAT_NHWC_VECT_W:
return num_spatial_dims + 3; // Include N,C,VectDim.
}
}
// Returns the rank of a tensor with 'num_spatial_dims' spatial dimensions and
// filter tensor format 'format'.
inline int GetFilterTensorDimsFromSpatialDims(int num_spatial_dims,
FilterTensorFormat format) {
if (format == FORMAT_OIHW_VECT_I) {
return num_spatial_dims + 3; // Include O,I,InnerI.
} else {
return num_spatial_dims + 2; // Include O,I.
}
}
// Returns the index of the batch dimension.
inline int GetTensorBatchDimIndex(int num_dims, TensorFormat format) {
switch (format) {
case FORMAT_NHWC:
case FORMAT_NCHW:
case FORMAT_NCHW_VECT_C:
case FORMAT_NHWC_VECT_W:
return 0;
case FORMAT_HWNC:
return num_dims - 2;
case FORMAT_HWCN:
return num_dims - 1;
default:
LOG(FATAL) << "Unknown format " << format;
return -1; // Avoid compiler warning about missing return value
}
}
// Returns the index of the feature dimension. If format is NCHW_VECT_C, returns
// the index of the outer feature dimension (i.e. dimension 1, whose size would
// be num_features / 4 in this case).
inline int GetTensorFeatureDimIndex(int num_dims, TensorFormat format) {
switch (format) {
case FORMAT_NHWC:
case FORMAT_HWNC:
return num_dims - 1;
case FORMAT_NHWC_VECT_W:
case FORMAT_HWCN:
return num_dims - 2;
case FORMAT_NCHW:
case FORMAT_NCHW_VECT_C:
return 1;
default:
LOG(FATAL) << "Unknown format " << format;
return -1; // Avoid compiler warning about missing return value
}
}
// Returns the index of the inner feature dimension.
inline int GetTensorInnerFeatureDimIndex(int num_dims, TensorFormat format) {
DCHECK_EQ(format, FORMAT_NCHW_VECT_C);
return num_dims - 1;
}
// Returns the index of the inner width dimension.
inline int GetTensorInnerWidthDimIndex(int num_dims, TensorFormat format) {
DCHECK_EQ(format, FORMAT_NHWC_VECT_W);
return num_dims - 1;
}
// Returns the dimension index of the specified 'spatial_dim' within an
// activation tensor. If format is NHWC_VECT_W and spatial_dim is 1, returns
// the index of the outer width dimension (i.e. dimension 2, whose size would
// be width / 4 in this case).
inline int GetTensorSpatialDimIndex(int num_dims, TensorFormat format,
int spatial_dim) {
CHECK(spatial_dim >= 0 &&
spatial_dim < GetTensorSpatialDims(num_dims, format))
<< spatial_dim << " " << num_dims << " " << ToString(format);
switch (format) {
case FORMAT_NHWC:
case FORMAT_NHWC_VECT_W:
return spatial_dim + 1;
case FORMAT_NCHW:
case FORMAT_NCHW_VECT_C:
return spatial_dim + 2;
case FORMAT_HWNC:
case FORMAT_HWCN:
return spatial_dim;
default:
LOG(FATAL) << "Unknown format " << format;
return -1; // Avoid compiler warning about missing return value
}
}
inline int GetFilterTensorSpatialDimIndex(int num_dims,
FilterTensorFormat format, int dim) {
CHECK(dim >= 0 && dim < GetFilterTensorSpatialDims(num_dims, format))
<< dim << " " << num_dims << " " << ToString(format);
switch (format) {
case FORMAT_HWIO:
return dim;
case FORMAT_OIHW:
case FORMAT_OIHW_VECT_I:
return dim + 2;
default:
LOG(FATAL) << "Unknown format " << format;
return -1; // Avoid compiler warning about missing return value
}
}
// Returns the index of the inner input channels dimension.
inline int GetFilterTensorInnerInputChannelsDimIndex(
int num_dims, FilterTensorFormat format) {
DCHECK_EQ(format, FORMAT_OIHW_VECT_I);
return num_dims - 1;
}
// Returns the index of the input channels dimension.
// If 'format' is FORMAT_OIHW_VECT_I, returns the dimension index of the
// outer input channel (i.e. 1), which holds num_input_channels / 4.
inline int GetFilterTensorInputChannelsDimIndex(int num_dims,
FilterTensorFormat format) {
switch (format) {
case FORMAT_HWIO:
return num_dims - 2;
case FORMAT_OIHW:
case FORMAT_OIHW_VECT_I:
return 1;
default:
LOG(FATAL) << "Unknown format " << format;
return -1; // Avoid compiler warning about missing return value
}
}
// Returns the index of the output channels dimension.
inline int GetFilterTensorOutputChannelsDimIndex(int num_dims,
FilterTensorFormat format) {
switch (format) {
case FORMAT_HWIO:
return num_dims - 1;
case FORMAT_OIHW:
case FORMAT_OIHW_VECT_I:
return 0;
default:
LOG(FATAL) << "Unknown format " << format;
return -1; // Avoid compiler warning about missing return value
}
}
// TODO(pauldonnelly): Replace these tensor dimension index functions with
// constant structs to improve performance and reduce code size in Compute()
// functions.
// Return the dimension index for the specified 'dimension' of the specified
// data 'tensor_format'. 'dimension' is a char that can be 'N' (batch size),
// 'C' (channels), 'H' (height), 'W' (width), or a numbered spatial dimension:
// '0', .. (NUM_SPATIAL_DIMS-1)..
// If 'format' is NCHW_VECT_C and 'dimension' is 'C', returns the index of
// the outer channel dimension (i.e. 1).
template <int NUM_SPATIAL_DIMS>
inline int32 GetTensorDimIndex(TensorFormat format, char dimension) {
if (format == FORMAT_NHWC || format == FORMAT_NHWC_VECT_W) {
// clang-format off
switch (dimension) {
case 'N': return 0;
case '0': return 1;
case '1': return 2;
case '2': return 3;
case 'H': return NUM_SPATIAL_DIMS - 1;
case 'W': return NUM_SPATIAL_DIMS;
case 'C': return NUM_SPATIAL_DIMS + 1;
default:
LOG(FATAL) << "Invalid dimension: " << dimension;
return -1; // Avoid compiler warning about missing return value
}
} else if (format == FORMAT_NCHW || format == FORMAT_NCHW_VECT_C) {
switch (dimension) {
case 'N': return 0;
case 'C': return 1;
case '0': return 2;
case '1': return 3;
case '2': return 4;
case 'H': return NUM_SPATIAL_DIMS;
case 'W': return NUM_SPATIAL_DIMS + 1;
default:
LOG(FATAL) << "Invalid dimension: " << dimension;
return -1; // Avoid compiler warning about missing return value
}
} else if (format == FORMAT_HWNC) {
switch (dimension) {
case '0': return 0;
case '1': return 1;
case '2': return 2;
case 'H': return NUM_SPATIAL_DIMS - 2;
case 'W': return NUM_SPATIAL_DIMS - 1;
case 'N': return NUM_SPATIAL_DIMS;
case 'C': return NUM_SPATIAL_DIMS + 1;
default:
LOG(FATAL) << "Invalid dimension: " << dimension;
return -1; // Avoid compiler warning about missing return value
}
} else if (format == FORMAT_HWCN) {
switch (dimension) {
case '0': return 0;
case '1': return 1;
case '2': return 2;
case 'H': return NUM_SPATIAL_DIMS - 2;
case 'W': return NUM_SPATIAL_DIMS - 1;
case 'C': return NUM_SPATIAL_DIMS;
case 'N': return NUM_SPATIAL_DIMS + 1;
default:
LOG(FATAL) << "Invalid dimension: " << dimension;
return -1; // Avoid compiler warning about missing return value
}
} else {
LOG(FATAL) << "Invalid format: " << static_cast<int>(format);
return -1; // Avoid compiler warning about missing return value
}
// clang-format on
}
// Return the dimension index for the specified 'dimension' of the specified
// 'filter_tensor_format'. 'dimension' is a char that can be 'O' (num output
// channels), 'I' (num input channels), 'H' (height), 'W' (width), or a
// numbered spatial dimension: '0', .. (NUM_SPATIAL_DIMS-1).
// If 'format' is OIHW_VECT_I and 'dimension' is 'I', returns the index of the
// outer input channels dimension (i.e. 1).
template <int NUM_SPATIAL_DIMS>
inline int GetFilterDimIndex(FilterTensorFormat filter_tensor_format,
char dimension) {
// clang-format off
if (filter_tensor_format == FORMAT_HWIO) {
switch (dimension) {
case '0': return 0;
case '1': return 1;
case '2': return 2;
case 'H': return NUM_SPATIAL_DIMS - 2;
case 'W': return NUM_SPATIAL_DIMS - 1;
case 'I': return NUM_SPATIAL_DIMS;
case 'O': return NUM_SPATIAL_DIMS + 1;
default:
LOG(FATAL) << "Invalid dimension: " << dimension;
return -1; // Avoid compiler warning about missing return value
}
} else if (filter_tensor_format == FORMAT_OIHW ||
filter_tensor_format == FORMAT_OIHW_VECT_I) {
switch (dimension) {
case 'O': return 0;
case 'I': return 1;
case '0': return 2;
case '1': return 3;
case '2': return 4;
case 'H': return NUM_SPATIAL_DIMS;
case 'W': return NUM_SPATIAL_DIMS + 1;
default:
LOG(FATAL) << "Invalid dimension: " << dimension;
return -1; // Avoid compiler warning about missing return value
}
} else {
LOG(FATAL) << "Invalid format: " << static_cast<int>(filter_tensor_format);
return -1; // Avoid compiler warning about missing return value
}
// clang-format on
}
inline int32 GetTensorDimIndex(TensorFormat format, char dimension) {
return GetTensorDimIndex<2>(format, dimension);
}
// Return the element from 'dimension_attributes' that corresponds to the
// specified 'dimension' according to 'tensor_format'.
template <typename T>
T GetTensorDim(gtl::ArraySlice<T> dimension_attributes,
TensorFormat tensor_format, char dimension) {
int index =
(GetTensorSpatialDims(dimension_attributes.size(), tensor_format) == 3)
? GetTensorDimIndex<3>(tensor_format, dimension)
: GetTensorDimIndex<2>(tensor_format, dimension);
CHECK(index >= 0 && index < dimension_attributes.size())
<< "Invalid index from the dimension: " << index << ", " << tensor_format
<< ", " << dimension;
return dimension_attributes[index];
}
// Return the element from 'dimension_attribute' that corresponds to the
// specified 'dimension' according to 'filter_tensor_format'.
template <typename T>
T GetFilterDim(gtl::ArraySlice<T> dimension_attribute,
FilterTensorFormat filter_tensor_format, char dimension) {
int index = (GetFilterTensorSpatialDims(dimension_attribute.size(),
filter_tensor_format) == 3)
? GetFilterDimIndex<3>(filter_tensor_format, dimension)
: GetFilterDimIndex<2>(filter_tensor_format, dimension);
CHECK(index >= 0 && index < dimension_attribute.size())
<< "Invalid index from the dimension: " << index << ", "
<< filter_tensor_format << ", " << dimension;
return dimension_attribute[index];
}
template <typename T>
T GetTensorDim(const std::vector<T>& attributes, TensorFormat format,
char dimension) {
return GetTensorDim(gtl::ArraySlice<T>(attributes), format, dimension);
}
// Return the size of the specified 'dimension' within 'tensor_shape'
// according to 'tensor_format'.
inline int64 GetTensorDim(const TensorShape& tensor_shape,
TensorFormat tensor_format, char dimension) {
return GetTensorDim(gtl::ArraySlice<int64>(tensor_shape.dim_sizes()),
tensor_format, dimension);
}
// Return the size of the specified 'dimension' within 'tensor_shape'
// according to 'tensor_filter_format'.
inline int64 GetFilterDim(const TensorShape& tensor_shape,
FilterTensorFormat tensor_filter_format,
char dimension) {
return GetFilterDim(gtl::ArraySlice<int64>(tensor_shape.dim_sizes()),
tensor_filter_format, dimension);
}
// Return the size of the specified 'dimension' of 'tensor' according to
// 'tensor_format'.
inline int64 GetTensorDim(const Tensor& tensor, TensorFormat tensor_format,
char dimension) {
return GetTensorDim(tensor.shape(), tensor_format, dimension);
}
// Return the size of the specified 'dimension' of 'tensor' according to
// 'filter_tensor_format'.
inline int64 GetFilterDim(const Tensor& tensor,
FilterTensorFormat filter_tensor_format,
char dimension) {
return GetFilterDim(tensor.shape(), filter_tensor_format, dimension);
}
// Return the string that specifies the data format for convnet operations.
string GetConvnetDataFormatAttrString();
string GetConvnet3dDataFormatAttrString();
// Return the string that specifies the filter format for convnet operations.
string GetConvnetFilterFormatAttrString();
string GetConvnet3dFilterFormatAttrString();
string GetConvnetDataFormat2D3DAttrString();
// Returns a tensor shape for the specified format and dimension sizes.
// Works for both 2D and 3D operations. The output shapes are as follows:
// FORMAT_NHWC: (N, spatial, C); rank = spatial.size() + 2
// FORMAT_NCHW: (N, C, spatial); rank = spatial.size() + 2
// FORMAT_NCHW_VECT_C: (N, C, spatial, InnerC); rank = spatial.size() + 3
// FORMAT_NHWC_VECT_W: (N, spatial, C, InnerW); rank = spatial.size() + 3
inline TensorShape ShapeFromFormat(TensorFormat format, int64 N,
gtl::ArraySlice<int64> spatial, int64 C) {
const int dims = GetTensorDimsFromSpatialDims(spatial.size(), format);
gtl::InlinedVector<int64, 6> dim_sizes(dims);
dim_sizes[GetTensorBatchDimIndex(dims, format)] = N;
for (int dim = 0; static_cast<size_t>(dim) < spatial.size(); dim++) {
auto dim_size = spatial[dim];
if (format == FORMAT_NHWC_VECT_W && dim == spatial.size() - 1) {
CHECK_EQ(0, dim_size % 4)
<< "FORMAT_NHWC_VECT_W requires W to be a multiple of 4, but W="
<< dim_size;
dim_sizes[GetTensorInnerWidthDimIndex(dims, format)] = 4;
dim_size /= 4;
}
dim_sizes[GetTensorSpatialDimIndex(dims, format, dim)] = dim_size;
}
int feature_index = GetTensorFeatureDimIndex(dims, format);
if (format == FORMAT_NCHW_VECT_C) {
CHECK_EQ(0, C % 4) << "NCHW_VECT_C requires C to be a multiple of 4, but C="
<< C;
C /= 4;
dim_sizes[GetTensorInnerFeatureDimIndex(dims, format)] = 4;
}
dim_sizes[feature_index] = C;
return TensorShape(dim_sizes);
}
// Return a tensor shape of the specified 'format', and dimensions.
// Works for both 2D and 3D operations. If 'format' is OIHW_VECT_I,
// the output TensorShape has spatial.size() + 3 dimensions, otherwise
// it has spatial.size() + 2 dimensions.
inline TensorShape ShapeFromFilterTensorFormat(FilterTensorFormat format,
gtl::ArraySlice<int64> spatial,
int64 I, int64 O) {
const int dims = GetFilterTensorDimsFromSpatialDims(spatial.size(), format);
gtl::InlinedVector<int64, 6> dim_sizes(dims);
dim_sizes[GetFilterTensorOutputChannelsDimIndex(dims, format)] = O;
for (int dim = 0; static_cast<size_t>(dim) < spatial.size(); dim++) {
dim_sizes[GetFilterTensorSpatialDimIndex(dims, format, dim)] = spatial[dim];
}
if (format == FORMAT_OIHW_VECT_I) {
CHECK_EQ(0, I % 4) << "OIHW_VECT_I requires I to be a multiple of 4, but I="
<< I;
I /= 4;
dim_sizes[GetFilterTensorInnerInputChannelsDimIndex(dims, format)] = 4;
}
dim_sizes[GetFilterTensorInputChannelsDimIndex(dims, format)] = I;
return TensorShape(dim_sizes);
}
// Return a tensor shape of the specified 'format', and dimensions.
inline TensorShape ShapeFromFormat(TensorFormat format, int64 N, int64 H,
int64 W, int64 C) {
return ShapeFromFormat(format, N, {H, W}, C);
}
// Return a filter tensor shape of the specified 'format', and dimensions.
inline TensorShape ShapeFromFilterTensorFormat(FilterTensorFormat format,
int64 H, int64 W, int64 I,
int64 O) {
return ShapeFromFilterTensorFormat(format, {H, W}, I, O);
}
// Returns a copy of the specified tensor 'src_shape' converted from
// 'src_format' to 'dst_format'.
inline TensorShape ShapeFromFormat(TensorFormat dst_format,
const TensorShape& src_shape,
TensorFormat src_format) {
if (src_format == dst_format) {
return src_shape;
}
const int64 batch = GetTensorDim(src_shape, src_format, 'N');
const int64 channels = GetTensorDim(src_shape, src_format, 'C') *
(src_format == FORMAT_NCHW_VECT_C ? 4 : 1);
const int num_src_spatial_dims =
GetTensorSpatialDims(src_shape.dims(), src_format);
std::vector<int64> spatial_dims(num_src_spatial_dims);
for (int spatial_dim = 0; spatial_dim < num_src_spatial_dims; ++spatial_dim) {
spatial_dims[spatial_dim] =
gtl::ArraySlice<int64>(src_shape.dim_sizes())[GetTensorSpatialDimIndex(
src_shape.dims(), src_format, spatial_dim)];
}
if (src_format == FORMAT_NHWC_VECT_W) {
spatial_dims[num_src_spatial_dims - 1] *= 4;
}
return ShapeFromFormat(dst_format, batch, {spatial_dims}, channels);
}
// Returns a copy of the specified filter tensor 'src_shape' converted from
// 'src_filter_format' to 'dst_filter_format'.
inline TensorShape ShapeFromFilterFormat(FilterTensorFormat dst_filter_format,
const TensorShape& src_shape,
FilterTensorFormat src_filter_format) {
if (src_filter_format == dst_filter_format) {
return src_shape;
}
const int64 output_channels = GetFilterDim(src_shape, src_filter_format, 'O');
const int64 input_channels =
GetFilterDim(src_shape, src_filter_format, 'I') *
(src_filter_format == FORMAT_OIHW_VECT_I ? 4 : 1);
if (GetFilterTensorSpatialDims(src_shape.dims(), src_filter_format) == 3) {
return ShapeFromFilterTensorFormat(
dst_filter_format,
{{GetFilterDim(src_shape, src_filter_format, '0'),
GetFilterDim(src_shape, src_filter_format, '1'),
GetFilterDim(src_shape, src_filter_format, '2')}},
input_channels, output_channels);
}
return ShapeFromFilterTensorFormat(
dst_filter_format,
{{GetFilterDim(src_shape, src_filter_format, 'H'),
GetFilterDim(src_shape, src_filter_format, 'W')}},
input_channels, output_channels);
}
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_TENSOR_FORMAT_H_
@@ -0,0 +1,195 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// The utility to read checkpoints for google brain tensor ops and v3
// checkpoints for dist_belief.
#ifndef TENSORFLOW_CORE_UTIL_TENSOR_SLICE_READER_H_
#define TENSORFLOW_CORE_UTIL_TENSOR_SLICE_READER_H_
#include <unordered_map>
#include <vector>
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_slice.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/saved_tensor_slice.pb.h"
#include "tensorflow/core/util/saved_tensor_slice_util.h"
#include "tensorflow/core/util/tensor_slice_set.h"
#include "tensorflow/core/util/tensor_slice_util.h"
namespace tensorflow {
namespace checkpoint {
// The reader reads in all the meta data about all the tensor slices. Then it
// will try to read the relevant data on-demand to produce the data for the
// slices needed.
// NOTE(yangke): another way to do this is to first load a list of the tensor
// slices needed and then just selectively read some of the meta data. That
// might optimize the loading but makes the logic a bit more complicated. We
// might want to revisit that.
// TODO(yangke): consider moving to TensorProto.
class TensorSliceReader {
public:
// Abstract interface for reading data out of a tensor slice checkpoint file
class Table {
public:
virtual ~Table();
virtual bool Get(const string& key, string* value) = 0;
};
typedef std::function<Status(const string&, Table**)> OpenTableFunction;
static const int kLoadAllShards = -1;
TensorSliceReader(const string& filepattern);
TensorSliceReader(const string& filepattern, OpenTableFunction open_function);
TensorSliceReader(const string& filepattern, OpenTableFunction open_function,
int preferred_shard);
virtual ~TensorSliceReader();
// Get the filename this reader is attached to.
const string& filepattern() const { return filepattern_; }
// Get the number of files matched.
int num_files() const { return sss_.size(); }
// Get the status of the reader.
const Status status() const { return status_; }
// Checks if the reader contains any slice of a tensor. In case the reader
// does contain the tensor, if "shape" is not nullptr, fill "shape" with the
// shape of the tensor; if "type" is not nullptr, fill "type" with the type
// of the tensor.
bool HasTensor(const string& name, TensorShape* shape, DataType* type) const;
// Checks if the reader contains all the data about a tensor slice, and if
// yes, copies the data of the slice to "data". The caller needs to make sure
// that "data" points to a buffer that holds enough data.
// This is a slow function since it needs to read sstables.
template <typename T>
bool CopySliceData(const string& name, const TensorSlice& slice,
T* data) const;
// Get the tensors.
const std::unordered_map<string, TensorSliceSet*>& Tensors() const {
return tensors_;
}
// Returns value for one tensor. Only single slice checkpoints are supported
// at the moment.
Status GetTensor(const string& name,
std::unique_ptr<tensorflow::Tensor>* out_tensor) const;
typedef std::unordered_map<string, TensorShape> VarToShapeMap;
typedef std::unordered_map<string, DataType> VarToDataTypeMap;
// Returns a map from tensor name to shape.
VarToShapeMap GetVariableToShapeMap() const;
// Returns a map from tensor name to data type.
VarToDataTypeMap GetVariableToDataTypeMap() const;
// Returns a string containing names and shapes of all the tensors.
const string DebugString() const;
private:
friend class TensorSliceWriteTestHelper;
void LoadShard(int shard) const;
void LoadAllShards() const;
const TensorSliceSet* FindTensorSlice(
const string& name, const TensorSlice& slice,
std::vector<std::pair<TensorSlice, string>>* details) const;
const string filepattern_;
const OpenTableFunction open_function_;
std::vector<string> fnames_;
std::unordered_map<string, int> fname_to_index_;
// Guards the attributes below.
mutable mutex mu_;
mutable bool all_shards_loaded_ = false;
mutable std::vector<std::unique_ptr<Table>> sss_;
mutable std::unordered_map<string, TensorSliceSet*> tensors_;
mutable Status status_;
TF_DISALLOW_COPY_AND_ASSIGN(TensorSliceReader);
};
Status OpenTableTensorSliceReader(const string& fname,
TensorSliceReader::Table** table);
template <typename T>
bool TensorSliceReader::CopySliceData(const string& name,
const TensorSlice& slice, T* data) const {
std::vector<std::pair<TensorSlice, string>> details;
const TensorSliceSet* tss;
{
mutex_lock l(mu_);
tss = FindTensorSlice(name, slice, &details);
if (!tss && !all_shards_loaded_) {
VLOG(1) << "Did not find slice in preferred shard, loading all shards."
<< name << ": " << slice.DebugString();
LoadAllShards();
tss = FindTensorSlice(name, slice, &details);
}
if (!tss) {
// No such tensor
return false;
}
}
// We have the data -- copy it over.
string value;
for (const auto& x : details) {
const TensorSlice& slice_s = x.first;
const string& fname = x.second;
int idx = gtl::FindWithDefault(fname_to_index_, fname, -1);
CHECK_GE(idx, 0) << "Failed to find the index for filename " << fname;
// We read a record in the corresponding sstable
const string key = EncodeTensorNameSlice(name, slice_s);
if (!sss_[idx]->Get(key, &value)) {
VLOG(1) << "Failed to seek to the record for tensor " << name
<< ", slice " << slice_s.DebugString()
<< ": computed key = " << key;
return false;
}
SavedTensorSlices sts;
if (!ParseProtoUnlimited(&sts, value)) {
VLOG(1) << "Failed to parse the record for tensor " << name << ", slice "
<< slice_s.DebugString() << ": computed key = " << key;
return false;
}
CopyDataFromTensorSliceToTensorSlice(
tss->shape(), slice_s, slice,
checkpoint::TensorProtoData<T>(sts.data().data()), data);
}
return true;
}
} // namespace checkpoint
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_TENSOR_SLICE_READER_H_
@@ -0,0 +1,88 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// The utility to read checkpoints for google brain tensor ops and v3
// checkpoints for dist_belief.
#ifndef TENSORFLOW_CORE_UTIL_TENSOR_SLICE_READER_CACHE_H_
#define TENSORFLOW_CORE_UTIL_TENSOR_SLICE_READER_CACHE_H_
#include <unordered_map>
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/tensor_slice_reader.h"
namespace tensorflow {
namespace checkpoint {
class TensorSliceReaderCache;
// Wrapper to a lazily allocated TensorSliceReaderCache.
class TensorSliceReaderCacheWrapper {
public:
TensorSliceReaderCacheWrapper();
~TensorSliceReaderCacheWrapper();
// Same as TensorSliceReaderCache::GetReader().
const TensorSliceReader* GetReader(
const string& filepattern,
TensorSliceReader::OpenTableFunction open_function,
int preferred_shard) const;
private:
mutable mutex mu_;
mutable TensorSliceReaderCache* cache_ = nullptr;
};
// A cache of TensorSliceReaders.
class TensorSliceReaderCache {
public:
TensorSliceReaderCache();
~TensorSliceReaderCache();
// Returns the TensorSliceReader corresponding to 'filepattern' and the
// open_function. May return nullptr if we can not create a new
// TensorSliceReader for the filepattern/open_function combination.
const TensorSliceReader* GetReader(
const string& filepattern,
TensorSliceReader::OpenTableFunction open_function, int preferred_shard);
private:
// Need to use a regular function type in the key map as std::function does
// not support ==.
typedef Status (*OpenFuncType)(const string&, TensorSliceReader::Table**);
// Protects attributes below.
mutex mu_;
// Maps of opened readers.
std::unordered_map<string, std::pair<OpenFuncType, TensorSliceReader*>>
readers_;
// Set of keys that a previous GetReader() call is still trying to populate.
std::set<string> still_opening_;
// Condition variable to notify when a reader has been created.
condition_variable cv_;
};
} // namespace checkpoint
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_TENSOR_SLICE_READER_CACHE_H_
@@ -0,0 +1,108 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// A class to manage slices of a tensor. You can "register" set of slices for a
// tensor and then "query" if we have data for a given slice.
// TODO(yangke): consider moving it to a more private place so that we don't
// need to expose the API.
#ifndef TENSORFLOW_UTIL_TENSOR_SLICE_SET_H_
#define TENSORFLOW_UTIL_TENSOR_SLICE_SET_H_
#include <string> // for string
#include <unordered_map>
#include <vector>
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_slice.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/status.h" // for Status
#include "tensorflow/core/lib/core/stringpiece.h" // for StringPiece
#include "tensorflow/core/platform/types.h" // for int64
namespace tensorflow {
namespace checkpoint {
class TensorSliceSet {
public:
TensorSliceSet(const TensorShape& shape, DataType type);
virtual ~TensorSliceSet();
const TensorShape& shape() const { return shape_; }
const DataType type() const { return type_; }
// Register a new slice for the tensor. The "tag" is an arbitrary string
// associated with the slice (in one application it denotes the name of the
// file that contains the slice); the "data" points to the data of the tensor
// slice (it can be a nullptr).
// We don't take the ownership of "data" and the caller needs to make sure
// the data is always available during the life time of the tensor slice set
// if it is not nullptr.
Status Register(const TensorSlice& slice, const string& tag,
const float* data);
// Query about a new slice: checks if we have data for "slice" and if we have
// the data and "data" is not nullptr, fill "data" with the slice data. The
// caller needs to make sure "data" point to a large enough buffer.
// TODO(yangke): avoid unnecessary copying by using a core::RefCounted
// pointer.
bool Query(const TensorSlice& slice, float* data) const;
// Alternative way of querying about a new slice: instead of copying the
// data, it returns a list of meta data about the stored slices that will
// supply data for the slice.
bool QueryMeta(
const TensorSlice& slice,
std::vector<std::pair<tensorflow::TensorSlice, string>>* results) const;
struct SliceInfo {
TensorSlice slice;
const string tag;
const float* data;
int64 num_floats;
};
// Returns the map from slice string to SliceInfo.
const std::unordered_map<string, SliceInfo>& Slices() const {
return slices_;
}
private:
const TensorShape shape_;
const DataType type_;
// We maintain a mapping from the slice string to the slice information.
std::unordered_map<string, SliceInfo> slices_;
// Minimal slice which contains all presented slices. Used for speeding up
// overlap check when slices are being added consequently.
TensorSlice slices_hull_;
};
// Registers "slice" in the TensorSliceSet stored in "tensor_slices", under key
// "name". Other arguments are used for validations. Does not modify the map
// or its values on non-OK.
// REQUIRES: tensor_slices != nullptr
Status RegisterTensorSlice(
const string& name, const TensorShape& shape, DataType type,
const string& tag, const TensorSlice& slice,
std::unordered_map<string, TensorSliceSet*>* tensor_slices);
} // namespace checkpoint
} // namespace tensorflow
#endif // TENSORFLOW_UTIL_TENSOR_SLICE_SET_H_
@@ -0,0 +1,191 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_UTIL_TENSOR_SLICE_UTIL_H_
#define TENSORFLOW_UTIL_TENSOR_SLICE_UTIL_H_
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_slice.h"
#include "tensorflow/core/platform/logging.h"
namespace tensorflow {
namespace {
// Some hackery to invoke eigen tensor to copy over tensor slices with variable
// dimension tensors.
// TODO(yangke): get rid of that once the variable dimension tensor support is
// in.
static const int kTensorSliceMaxRank = 8;
// Create a tensor map with the given shape: we support up to 8 dimensions. If
// the shape has less than 8 dimensions, we pad the remaining dimension with 1.
template <typename T>
Eigen::TensorMap<Eigen::Tensor<T, kTensorSliceMaxRank, Eigen::RowMajor>>
GetEigenTensorMapFromTensorShape(const TensorShape& shape, T* data) {
Eigen::DSizes<Eigen::DenseIndex, kTensorSliceMaxRank> dsizes =
shape.AsEigenDSizesWithPadding<kTensorSliceMaxRank>();
Eigen::TensorMap<Eigen::Tensor<T, kTensorSliceMaxRank, Eigen::RowMajor>> eig(
data, dsizes);
return eig;
}
// For everything except string, a standard Eigen cast and assignment works
template <typename DstT>
struct CopyThatWorksWithStringPointer {
template <typename SrcTensor, typename DstTensor, typename Shape>
static void Copy(const SrcTensor& s, Shape s_start, Shape len, DstTensor& d,
Shape d_start) {
d.slice(d_start, len) = s.slice(s_start, len).template cast<DstT>();
}
};
// Eigen makes it extremely difficult to dereference a tensor of string* into
// string, so we roll our own loop instead.
template <>
struct CopyThatWorksWithStringPointer<string> {
template <typename SrcTensor, typename DstTensor, typename Shape>
static void Copy(const SrcTensor& s, Shape s_start, Shape len, DstTensor& d,
Shape d_start) {
typedef typename SrcTensor::Index Index;
static_assert(kTensorSliceMaxRank == 8,
"If kTensorSliceMaxRank changes, modify the loop below.");
for (Index i0 = 0; i0 < len[0]; i0++) {
for (Index i1 = 0; i1 < len[1]; i1++) {
for (Index i2 = 0; i2 < len[2]; i2++) {
for (Index i3 = 0; i3 < len[3]; i3++) {
for (Index i4 = 0; i4 < len[4]; i4++) {
for (Index i5 = 0; i5 < len[5]; i5++) {
for (Index i6 = 0; i6 < len[6]; i6++) {
for (Index i7 = 0; i7 < len[7]; i7++) {
d(d_start[0] + i0, d_start[1] + i1, d_start[2] + i2,
d_start[3] + i3, d_start[4] + i4, d_start[5] + i5,
d_start[6] + i6, d_start[7] + i7) =
*s(s_start[0] + i0, s_start[1] + i1, s_start[2] + i2,
s_start[3] + i3, s_start[4] + i4, s_start[5] + i5,
s_start[6] + i6, s_start[7] + i7);
}
}
}
}
}
}
}
}
}
};
// Checkpointing of half is done by storing the raw 16 bits as a signed 32bit
// integer. To restore the checkpoint we need to do the reverse operation by
// reinterpreting the integer as a 16 bit float. This prevents us from using
// the default cast operation.
template <>
struct CopyThatWorksWithStringPointer<Eigen::half> {
template <typename SrcTensor, typename DstTensor, typename Shape>
static void Copy(const SrcTensor& s, Shape s_start, Shape len, DstTensor& d,
Shape d_start) {
typedef typename SrcTensor::Index Index;
static_assert(kTensorSliceMaxRank == 8,
"If kTensorSliceMaxRank changes, modify the loop below.");
for (Index i0 = 0; i0 < len[0]; i0++) {
for (Index i1 = 0; i1 < len[1]; i1++) {
for (Index i2 = 0; i2 < len[2]; i2++) {
for (Index i3 = 0; i3 < len[3]; i3++) {
for (Index i4 = 0; i4 < len[4]; i4++) {
for (Index i5 = 0; i5 < len[5]; i5++) {
for (Index i6 = 0; i6 < len[6]; i6++) {
for (Index i7 = 0; i7 < len[7]; i7++) {
d(d_start[0] + i0, d_start[1] + i1, d_start[2] + i2,
d_start[3] + i3, d_start[4] + i4, d_start[5] + i5,
d_start[6] + i6, d_start[7] + i7) =
Eigen::half_impl::raw_uint16_to_half(
s(s_start[0] + i0, s_start[1] + i1, s_start[2] + i2,
s_start[3] + i3, s_start[4] + i4, s_start[5] + i5,
s_start[6] + i6, s_start[7] + i7));
}
}
}
}
}
}
}
}
}
};
// Given a tensor described by "shape", two slices "slice_s" and "slice_d",
// and two pointers "ptr_s" and "ptr_d", where "ptr_s" points to a chunk of
// memory that stores the data for "slice_s" and "ptr_d" points to a chunk of
// memory that stores the data for "slice_d". This function copies the data
// that belongs to the intersection of the two slices from slice_s to
// slice_d. Uses Tensor cast<DstT>() to convert from SrcT to DstT. Returns true
// iff the two slices share any intersection (and thus some data is copied).
// TODO(yangke): figure out if we can make it private.
template <typename SrcT, typename DstT>
static bool CopyDataFromTensorSliceToTensorSlice(const TensorShape& shape,
const TensorSlice& slice_s,
const TensorSlice& slice_d,
const SrcT* ptr_s,
DstT* ptr_d) {
CHECK_LE(shape.dims(), kTensorSliceMaxRank)
<< "Only tensors of size up to " << kTensorSliceMaxRank
<< " are supported";
// We need to compute the intersection of the two slices.
TensorSlice inter;
if (!slice_s.Intersect(slice_d, &inter)) {
// There is no intersection: returns false.
return false;
} else {
// We need to compute the applied shapes after applying slice_s and
// slice_d.
TensorShape shp_s, shp_d;
Status s;
s = slice_s.SliceTensorShape(shape, &shp_s);
if (!s.ok()) {
LOG(WARNING) << s;
return false;
}
s = slice_d.SliceTensorShape(shape, &shp_d);
if (!s.ok()) {
LOG(WARNING) << s;
return false;
}
// We need to compute the relative slice of "inter" w.r.t. both slice_s and
// slice_d.
TensorSlice rel_s, rel_d;
slice_s.ComputeRelative(inter, &rel_s);
slice_d.ComputeRelative(inter, &rel_d);
// Get the eigen tensor maps to the data.
auto t_s = GetEigenTensorMapFromTensorShape(shp_s, ptr_s);
auto t_d = GetEigenTensorMapFromTensorShape(shp_d, ptr_d);
Eigen::DSizes<Eigen::DenseIndex, kTensorSliceMaxRank> s_start, s_len,
d_start, d_len;
rel_s.FillIndicesAndSizes<kTensorSliceMaxRank>(shp_s, &s_start, &s_len);
rel_d.FillIndicesAndSizes<kTensorSliceMaxRank>(shp_d, &d_start, &d_len);
CopyThatWorksWithStringPointer<DstT>::Copy(t_s, s_start, s_len, t_d,
d_start);
return true;
}
}
} // namespace
} // namespace tensorflow
#endif // TENSORFLOW_UTIL_TENSOR_SLICE_UTIL_H_
@@ -0,0 +1,195 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// The utility to write checkpoints for google brain tensor ops and v3
// checkpoints for dist_belief.
#ifndef TENSORFLOW_CORE_UTIL_TENSOR_SLICE_WRITER_H_
#define TENSORFLOW_CORE_UTIL_TENSOR_SLICE_WRITER_H_
#include <unordered_map>
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_slice.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/saved_tensor_slice.pb_text.h"
#include "tensorflow/core/util/saved_tensor_slice.pb.h"
#include "tensorflow/core/util/saved_tensor_slice_util.h"
namespace tensorflow {
namespace checkpoint {
class TensorSliceWriter {
public:
// Abstract interface that TensorSliceWriter uses for building
class Builder {
public:
virtual ~Builder() {}
virtual void Add(StringPiece key, StringPiece value) = 0;
virtual Status Finish(int64* file_size) = 0;
};
typedef std::function<Status(const string&, Builder**)> CreateBuilderFunction;
TensorSliceWriter(const string& filename,
CreateBuilderFunction create_builder);
virtual ~TensorSliceWriter() {}
// Adds a slice. We support float and int32 for now.
// TODO(yangke): add more supports
template <typename T>
Status Add(const string& name, const TensorShape& shape,
const TensorSlice& slice, const T* data);
Status Finish();
// Allocate "num_elements" elements in "ss" and save the data in "data"
// there.
template <typename T>
static Status SaveData(const T* data, int64 num_elements, SavedSlice* ss);
static size_t MaxBytesPerElement(DataType dt);
private:
static const size_t kMaxMessageBytes = 1LL << 31;
// Filling in the TensorProto in a SavedSlice will add the following
// header bytes, in addition to the data:
// - 1 byte: TensorProto tag and wire format
// - <= 5 bytes: TensorProto length
// - 1 byte: Repeated *_val tag and wire format
// - <= 5 bytes: *_val length
// However, we add 1KB of slack, to be conservative and guard
// against other additions to the TensorProto.
static const size_t kTensorProtoHeaderBytes = 1 << 10;
const string filename_;
const CreateBuilderFunction create_builder_;
const string tmpname_;
// A mapping from the tensor names to their index in meta_.saved_slice_meta()
std::unordered_map<string, int> name_to_index_;
// The metadata that holds all the saved tensor slices.
SavedTensorSlices sts_;
// The data to be written to the builder
std::map<string, string> data_;
// Total number of slices written
int slices_;
TF_DISALLOW_COPY_AND_ASSIGN(TensorSliceWriter);
};
template <typename T>
Status TensorSliceWriter::Add(const string& name, const TensorShape& shape,
const TensorSlice& slice, const T* data) {
// The tensor and the slice have to be compatible
if (shape.dims() != slice.dims()) {
return errors::Internal("Incompatible tensor shape and slice: ", "shape = ",
shape.DebugString(),
", slice = ", slice.DebugString());
}
DataType dt = DataTypeToEnum<T>::value;
// We need to add an entry for "name" if there isn't an entry already.
int index = gtl::FindWithDefault(name_to_index_, name, -1);
if (index >= 0) {
// The same tensor has been registered -- we verify that the shapes and the
// type agree.
const SavedSliceMeta& ssm = sts_.meta().tensor(index);
CHECK_EQ(name, ssm.name()) << ProtoShortDebugString(ssm);
TensorShape ssm_shape(ssm.shape());
if (!shape.IsSameSize(ssm_shape)) {
return errors::Internal(
"Mismatching shapes: existing tensor = ", ssm_shape.DebugString(),
", trying to add name ", name, ", shape = ", shape.DebugString());
}
if (dt != ssm.type()) {
return errors::Internal(
"Mismatching types: existing type = ", DataTypeString(ssm.type()),
", trying to add name ", name, ", type = ", DataTypeString(dt));
}
} else {
// Insert the new tensor name with the shape information
index = sts_.meta().tensor_size();
name_to_index_.insert(std::make_pair(name, index));
SavedSliceMeta* ssm = sts_.mutable_meta()->add_tensor();
ssm->set_name(name);
shape.AsProto(ssm->mutable_shape());
ssm->set_type(dt);
}
// Now we need to add the slice info the list of slices.
SavedSliceMeta* ssm = sts_.mutable_meta()->mutable_tensor(index);
slice.AsProto(ssm->add_slice());
// Now we need to add the real data.
{
SavedTensorSlices sts;
SavedSlice* ss = sts.mutable_data();
ss->set_name(name);
slice.AsProto(ss->mutable_slice());
TensorShape saved_shape(ssm->shape());
TensorShape sliced_shape;
TF_RETURN_IF_ERROR(slice.SliceTensorShape(saved_shape, &sliced_shape));
TF_RETURN_IF_ERROR(SaveData(data, sliced_shape.num_elements(), ss));
string key = EncodeTensorNameSlice(name, slice);
// TODO(yangke): consider doing a two-pass thing where the first pass just
// list the tensor slices we want to save and then another pass to actually
// set the data. Need to figure out if the interface works well.
std::pair<string, string> key_value(key, "");
if (!sts.AppendToString(&key_value.second)) {
return errors::Internal("Error writing Tensor. Possible size overflow.");
}
data_.insert(key_value);
}
++slices_;
return Status::OK();
}
template <typename T>
Status TensorSliceWriter::SaveData(const T* data, int64 num_elements,
SavedSlice* ss) {
size_t size_bound =
ss->ByteSize() + kTensorProtoHeaderBytes +
(MaxBytesPerElement(DataTypeToEnum<T>::value) * num_elements);
if (size_bound > kMaxMessageBytes) {
return errors::InvalidArgument(
"Tensor slice is too large to serialize (conservative estimate: ",
size_bound, " bytes)");
}
Fill(data, num_elements, ss->mutable_data());
DCHECK_GE(ss->ByteSize(), 0);
DCHECK_LE(ss->ByteSize(), size_bound);
return Status::OK();
}
template <>
Status TensorSliceWriter::SaveData(const string* data, int64 num_elements,
SavedSlice* ss);
// Create a table builder that will write to "filename" in
// tensorflow::io::Table format. If successful, return OK
// and set "*builder" to the allocated builder. Otherwise, return a
// non-OK status.
Status CreateTableTensorSliceBuilder(const string& filename,
TensorSliceWriter::Builder** builder);
} // namespace checkpoint
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_TENSOR_SLICE_WRITER_H_
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,149 @@
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_UTIL_TRANSFORM_OUTPUT_ITERATOR_H_
#define TENSORFLOW_UTIL_TRANSFORM_OUTPUT_ITERATOR_H_
#include <iostream>
#include <iterator>
namespace tensorflow {
template <typename StoreType, typename InputType, typename ConversionOp,
typename OffsetT = ptrdiff_t>
class TransformOutputIterator {
protected:
// Proxy object
struct Reference {
StoreType* ptr;
ConversionOp conversion_op;
/// Constructor
__host__ __device__ __forceinline__ Reference(StoreType* ptr,
ConversionOp conversion_op)
: ptr(ptr), conversion_op(conversion_op) {}
/// Assignment
__host__ __device__ __forceinline__ InputType operator=(InputType val) {
*ptr = conversion_op(val);
return val;
}
};
public:
// Required iterator traits
typedef TransformOutputIterator self_type; ///< My own type
typedef OffsetT difference_type; ///< Type to express the result of
///< subtracting one iterator from another
typedef void
value_type; ///< The type of the element the iterator can point to
typedef void pointer; ///< The type of a pointer to an element the iterator
///< can point to
typedef Reference reference; ///< The type of a reference to an element the
///< iterator can point to
typedef std::random_access_iterator_tag
iterator_category; ///< The iterator category
/*private:*/
StoreType* ptr;
ConversionOp conversion_op;
public:
/// Constructor
template <typename QualifiedStoreType>
__host__ __device__ __forceinline__ TransformOutputIterator(
QualifiedStoreType* ptr,
ConversionOp conversionOp) ///< Native pointer to wrap
: ptr(ptr), conversion_op(conversionOp) {}
/// Postfix increment
__host__ __device__ __forceinline__ self_type operator++(int) {
self_type retval = *this;
ptr++;
return retval;
}
/// Prefix increment
__host__ __device__ __forceinline__ self_type operator++() {
ptr++;
return *this;
}
/// Indirection
__host__ __device__ __forceinline__ reference operator*() const {
return Reference(ptr, conversion_op);
}
/// Addition
template <typename Distance>
__host__ __device__ __forceinline__ self_type operator+(Distance n) const {
self_type retval(ptr + n, conversion_op);
return retval;
}
/// Addition assignment
template <typename Distance>
__host__ __device__ __forceinline__ self_type& operator+=(Distance n) {
ptr += n;
return *this;
}
/// Subtraction
template <typename Distance>
__host__ __device__ __forceinline__ self_type operator-(Distance n) const {
self_type retval(ptr - n, conversion_op);
return retval;
}
/// Subtraction assignment
template <typename Distance>
__host__ __device__ __forceinline__ self_type& operator-=(Distance n) {
ptr -= n;
return *this;
}
/// Distance
__host__ __device__ __forceinline__ difference_type
operator-(self_type other) const {
return ptr - other.ptr;
}
/// Array subscript
template <typename Distance>
__host__ __device__ __forceinline__ reference operator[](Distance n) const {
return Reference(ptr + n, conversion_op);
}
/// Equal to
__host__ __device__ __forceinline__ bool operator==(const self_type& rhs) {
return (ptr == rhs.ptr);
}
/// Not equal to
__host__ __device__ __forceinline__ bool operator!=(const self_type& rhs) {
return (ptr != rhs.ptr);
}
/// ostream operator
friend std::ostream& operator<<(std::ostream& os, const self_type& itr) {
return os;
}
};
} // end namespace tensorflow
#endif // TENSORFLOW_UTIL_TRANSFORM_OUTPUT_ITERATOR_H_
@@ -0,0 +1,44 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// The utility to check Cudnn dependency and set Cudnn-related flags.
#ifndef TENSORFLOW_CORE_UTIL_USE_CUDNN_H_
#define TENSORFLOW_CORE_UTIL_USE_CUDNN_H_
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
// FP16ConvMode: The mode to set the internal compute type for cudnn convolution
// when the input data type is float16. Two types of modes are supported:
// kAccurate: Always use float32 as the internal compute type.
// kFast: Include both float32 and float16 compute type in the autotune.
enum class FP16ConvMode {
kAccurate = 1,
kFast = 2,
};
bool CanUseCudnn();
bool CudnnUseAutotune();
bool CudnnRnnUseAutotune();
bool CudnnDisableConv1x1Optimization();
FP16ConvMode CudnnConvComputeMode();
bool DebugCudnnRnn();
bool DebugCudnnRnnUseTensorOps();
int64 DebugCudnnRnnAlgo();
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_USE_CUDNN_H_
+61
View File
@@ -0,0 +1,61 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_UTIL_H_
#define TENSORFLOW_CORE_UTIL_UTIL_H_
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/stringpiece.h"
namespace tensorflow {
// If op_name has '/' in it, then return everything before the first '/'.
// Otherwise return empty string.
StringPiece NodeNamePrefix(const StringPiece& op_name);
// If op_name has '/' in it, then return everything before the last '/'.
// Otherwise return empty string.
StringPiece NodeNameFullPrefix(const StringPiece& op_name);
class MovingAverage {
public:
explicit MovingAverage(int window);
~MovingAverage();
void Clear();
double GetAverage() const;
void AddValue(double v);
private:
const int window_; // Max size of interval
double sum_; // Sum over interval
double* data_; // Actual data values
int head_; // Offset of the newest statistic in data_
int count_; // # of valid data elements in window
};
// Returns a string printing bytes in ptr[0..n). The output looks
// like "00 01 ef cd cd ef".
string PrintMemory(const char* ptr, size_t n);
// Given a flattened index into a tensor, computes a string s so that
// StrAppend("tensor", s) is a Python indexing expression. E.g.,
// "tensor", "tensor[i]", "tensor[i, j]", etc.
string SliceDebugString(const TensorShape& shape, const int64 flat);
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_UTIL_H_
@@ -0,0 +1,101 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_WORK_SHARDER_H_
#define TENSORFLOW_CORE_UTIL_WORK_SHARDER_H_
#include <functional>
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
// DEPRECATED: Prefer threadpool->TransformRangeConcurrently, which allows you
// to directly specify the shard size. Use this function only if you want to
// manually cap parallelism.
// Shards the "total" unit of work assuming each unit of work having
// roughly "cost_per_unit". Each unit of work is indexed 0, 1, ...,
// total - 1. Each shard contains 1 or more units of work and the
// total cost of each shard is roughly the same. The calling thread and the
// "workers" are used to compute each shard (calling work(start,
// limit). A common configuration is that "workers" is a thread pool
// with at least "max_parallelism" threads.
//
// "cost_per_unit" is an estimate of the number of CPU cycles (or nanoseconds
// if not CPU-bound) to complete a unit of work. Overestimating creates too
// many shards and CPU time will be dominated by per-shard overhead, such as
// Context creation. Underestimating may not fully make use of the specified
// parallelism.
//
// "work" should be a callable taking (int64, int64) arguments.
// work(start, limit) computes the work units from [start,
// limit), i.e., [start, limit) is a shard.
//
// Too much parallelism can also cause excessive thread switches,
// therefore, Shard() often limits the maximum parallelism. Each
// caller can provide the 1st argument max_parallelism. A thread can
// call SetMaxParallelism() so that all Shard() calls later limits the
// thread parallelism.
//
// REQUIRES: max_parallelism >= 0
// REQUIRES: workers != nullptr
// REQUIRES: total >= 0
// REQUIRES: cost_per_unit >= 0
void Shard(int max_parallelism, thread::ThreadPool* workers, int64 total,
int64 cost_per_unit, std::function<void(int64, int64)> work);
// Each thread has an associated option to express the desired maximum
// parallelism. Its default is a very large quantity.
//
// Within TF runtime, per-thread max parallelism affects Shard() and
// intra-op parallelism. E.g., if SetPerThreadMaxParallelism(1) is
// arranged to be called by a tf_compute thread, Shard() calls and
// eigen device assignment happens in that thread afterwards becomes
// single-threaded.
void SetPerThreadMaxParallelism(int max_parallelism);
int GetPerThreadMaxParallelism();
// Helper to set and unset per-thread max parallelism.
class ScopedPerThreadMaxParallelism {
public:
ScopedPerThreadMaxParallelism(int max_parallelism)
: previous_(GetPerThreadMaxParallelism()) {
SetPerThreadMaxParallelism(max_parallelism);
}
~ScopedPerThreadMaxParallelism() { SetPerThreadMaxParallelism(previous_); }
private:
int previous_ = -1;
};
// Implementation details for Shard().
class Sharder {
public:
typedef std::function<void()> Closure;
typedef std::function<void(Closure)> Runner;
typedef std::function<void(int64, int64)> Work;
// Refers to Shard()'s comment for the meaning of total,
// cost_per_unit, work, max_parallelism. runner is an interface to
// schedule a closure. Shard() uses thread::ThreadPool instead.
static void Do(int64 total, int64 cost_per_unit, const Work& work,
const Runner& runner, int max_parallelism);
};
} // end namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_WORK_SHARDER_H_