TFUtils.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- TFUtils.h - utilities for tensorflow C API ---------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. #ifndef LLVM_ANALYSIS_UTILS_TFUTILS_H
  15. #define LLVM_ANALYSIS_UTILS_TFUTILS_H
  16. #include "llvm/Config/llvm-config.h"
  17. #ifdef LLVM_HAVE_TF_API
  18. #include "llvm/IR/LLVMContext.h"
  19. #include "llvm/Support/JSON.h"
  20. #include <memory>
  21. #include <vector>
  22. namespace llvm {
  23. /// Load a SavedModel, find the given inputs and outputs, and setup storage
  24. /// for input tensors. The user is responsible for correctly dimensioning the
  25. /// input tensors and setting their values before calling evaluate().
  26. /// To initialize:
  27. /// - construct the object
  28. /// - initialize the input tensors using initInput. Indices must correspond to
  29. /// indices in the InputNames used at construction.
  30. /// To use:
  31. /// - set input values by using getInput to get each input tensor, and then
  32. /// setting internal scalars, for all dimensions (tensors are row-major:
  33. /// https://github.com/tensorflow/tensorflow/blob/r1.5/tensorflow/c/c_api.h#L205)
  34. /// - call evaluate. The input tensors' values are not consumed after this, and
  35. /// may still be read.
  36. /// - use the outputs in the output vector
  37. class TFModelEvaluatorImpl;
  38. class EvaluationResultImpl;
  39. /// TensorSpec encapsulates the specification of a tensor: its dimensions, or
  40. /// "shape" (row-major), its type (see TensorSpec::getDataType specializations
  41. /// for supported types), its name and port (see "TensorFlow: Large-Scale
  42. /// Machine Learning on Heterogeneous Distributed Systems", section 4.2, para 2:
  43. /// https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/45166.pdf)
  44. ///
  45. /// TensorSpec is used to set up a TFModelEvaluator by describing the expected
  46. /// inputs and outputs.
  47. class TensorSpec final {
  48. public:
  49. template <typename T>
  50. static TensorSpec createSpec(const std::string &Name,
  51. const std::vector<int64_t> &Shape,
  52. int Port = 0) {
  53. return TensorSpec(Name, Port, getDataType<T>(), Shape);
  54. }
  55. const std::string &name() const { return Name; }
  56. int port() const { return Port; }
  57. int typeIndex() const { return TypeIndex; }
  58. const std::vector<int64_t> &shape() const { return Shape; }
  59. bool operator==(const TensorSpec &Other) const {
  60. return Name == Other.Name && Port == Other.Port &&
  61. TypeIndex == Other.TypeIndex && Shape == Other.Shape;
  62. }
  63. bool operator!=(const TensorSpec &Other) const { return !(*this == Other); }
  64. /// Get the number of elements in a tensor with this shape.
  65. size_t getElementCount() const { return ElementCount; }
  66. /// Get the size, in bytes, of one element.
  67. size_t getElementByteSize() const;
  68. template <typename T> bool isElementType() const {
  69. return getDataType<T>() == TypeIndex;
  70. }
  71. private:
  72. TensorSpec(const std::string &Name, int Port, int TypeIndex,
  73. const std::vector<int64_t> &Shape);
  74. template <typename T> static int getDataType() {
  75. llvm_unreachable("Undefined tensor type");
  76. }
  77. std::string Name;
  78. int Port = 0;
  79. int TypeIndex = 0;
  80. std::vector<int64_t> Shape;
  81. size_t ElementCount = 0;
  82. };
  83. /// Construct a TensorSpec from a JSON dictionary of the form:
  84. /// { "name": <string>,
  85. /// "port": <int>,
  86. /// "type": <string. Use LLVM's types, e.g. float, double, int64_t>,
  87. /// "shape": <array of ints> }
  88. /// For the "type" field, see the C++ primitive types used in
  89. /// TFUTILS_SUPPORTED_TYPES.
  90. Optional<TensorSpec> getTensorSpecFromJSON(LLVMContext &Ctx,
  91. const json::Value &Value);
  92. struct LoggedFeatureSpec {
  93. TensorSpec Spec;
  94. Optional<std::string> LoggingName;
  95. };
  96. /// Load the output specs. If SpecFileOverride is not empty, that path is used.
  97. /// Otherwise, the file is assumed to be called 'output_spec.json' and be found
  98. /// under ModelPath (the model directory).
  99. /// The first output tensor name must match ExpectedDecisionName.
  100. /// In case of error, the return is None and the error is logged.
  101. Optional<std::vector<LoggedFeatureSpec>>
  102. loadOutputSpecs(LLVMContext &Ctx, StringRef ExpectedDecisionName,
  103. StringRef ModelPath, StringRef SpecFileOverride = StringRef());
  104. /// Logging utility - given an ordered specification of features, and assuming
  105. /// a scalar reward, allow logging feature values and rewards, and then print
  106. /// as tf.train.SequenceExample text protobuf.
  107. /// The assumption is that, for an event to be logged (i.e. a set of feature
  108. /// values and a reward), the user calls the log* API for each feature exactly
  109. /// once, providing the index matching the position in the feature spec list
  110. /// provided at construction:
  111. /// event 0:
  112. /// logTensorValue(0, ...)
  113. /// logTensorValue(1, ...)
  114. /// ...
  115. /// logReward(...)
  116. /// event 1:
  117. /// logTensorValue(0, ...)
  118. /// logTensorValue(1, ...)
  119. /// ...
  120. /// logReward(...)
  121. ///
  122. /// At the end, call print to generate the protobuf.
  123. class Logger final {
  124. public:
  125. /// Construct a Logger. If IncludeReward is false, then logReward shouldn't
  126. /// be called, and the reward feature won't be printed out.
  127. Logger(const std::vector<LoggedFeatureSpec> &FeatureSpecs,
  128. const TensorSpec &RewardSpec, bool IncludeReward)
  129. : FeatureSpecs(FeatureSpecs), RewardSpec(RewardSpec),
  130. RawLogData(FeatureSpecs.size() + IncludeReward),
  131. IncludeReward(IncludeReward) {}
  132. template <typename T> void logReward(T Value) {
  133. assert(IncludeReward);
  134. logTensorValue(RawLogData.size() - 1, &Value);
  135. }
  136. template <typename T> void logFinalReward(T Value) {
  137. assert(RawLogData.back().empty());
  138. logReward(Value);
  139. }
  140. template <typename T>
  141. void logTensorValue(size_t FeatureID, const T *Value, size_t Size = 1) {
  142. const char *Start = reinterpret_cast<const char *>(Value);
  143. const char *End = Start + sizeof(T) * Size;
  144. RawLogData[FeatureID].insert(RawLogData[FeatureID].end(), Start, End);
  145. }
  146. void print(raw_ostream &OS);
  147. private:
  148. std::vector<LoggedFeatureSpec> FeatureSpecs;
  149. TensorSpec RewardSpec;
  150. /// RawData has one entry per feature, plus one more for the reward.
  151. /// Each feature's values are then stored in a vector, in succession.
  152. /// This means the ith event is stored at [*][i]
  153. std::vector<std::vector<char>> RawLogData;
  154. const bool IncludeReward;
  155. };
  156. class TFModelEvaluator final {
  157. public:
  158. /// The result of a model evaluation. Handles the lifetime of the output
  159. /// tensors, which means that their values need to be used before
  160. /// the EvaluationResult's dtor is called.
  161. class EvaluationResult {
  162. public:
  163. EvaluationResult(const EvaluationResult &) = delete;
  164. EvaluationResult &operator=(const EvaluationResult &Other) = delete;
  165. EvaluationResult(EvaluationResult &&Other);
  166. EvaluationResult &operator=(EvaluationResult &&Other);
  167. ~EvaluationResult();
  168. /// Get a (const) pointer to the first element of the tensor at Index.
  169. template <typename T> T *getTensorValue(size_t Index) {
  170. return static_cast<T *>(getUntypedTensorValue(Index));
  171. }
  172. template <typename T> const T *getTensorValue(size_t Index) const {
  173. return static_cast<T *>(getUntypedTensorValue(Index));
  174. }
  175. /// Get a (const) pointer to the untyped data of the tensor.
  176. void *getUntypedTensorValue(size_t Index);
  177. const void *getUntypedTensorValue(size_t Index) const;
  178. private:
  179. friend class TFModelEvaluator;
  180. EvaluationResult(std::unique_ptr<EvaluationResultImpl> Impl);
  181. std::unique_ptr<EvaluationResultImpl> Impl;
  182. };
  183. TFModelEvaluator(StringRef SavedModelPath,
  184. const std::vector<TensorSpec> &InputSpecs,
  185. const std::vector<TensorSpec> &OutputSpecs,
  186. const char *Tags = "serve");
  187. TFModelEvaluator(StringRef SavedModelPath,
  188. const std::vector<TensorSpec> &InputSpecs,
  189. function_ref<TensorSpec(size_t)> GetOutputSpecs,
  190. size_t OutputSpecsSize, const char *Tags = "serve");
  191. ~TFModelEvaluator();
  192. TFModelEvaluator(const TFModelEvaluator &) = delete;
  193. TFModelEvaluator(TFModelEvaluator &&) = delete;
  194. /// Evaluate the model, assuming it is valid. Returns None if the evaluation
  195. /// fails or the model is invalid, or an EvaluationResult otherwise. The
  196. /// inputs are assumed to have been already provided via getInput(). When
  197. /// returning None, it also invalidates this object.
  198. Optional<EvaluationResult> evaluate();
  199. /// Provides access to the input vector.
  200. template <typename T> T *getInput(size_t Index) {
  201. return static_cast<T *>(getUntypedInput(Index));
  202. }
  203. /// Returns true if the tensorflow model was loaded successfully, false
  204. /// otherwise.
  205. bool isValid() const { return !!Impl; }
  206. private:
  207. void *getUntypedInput(size_t Index);
  208. std::unique_ptr<TFModelEvaluatorImpl> Impl;
  209. };
  210. /// List of supported types, as a pair:
  211. /// - C++ type
  212. /// - enum name (implementation-specific)
  213. #define TFUTILS_SUPPORTED_TYPES(M) \
  214. M(float, TF_FLOAT) \
  215. M(double, TF_DOUBLE) \
  216. M(int8_t, TF_INT8) \
  217. M(uint8_t, TF_UINT8) \
  218. M(int16_t, TF_INT16) \
  219. M(uint16_t, TF_UINT16) \
  220. M(int32_t, TF_INT32) \
  221. M(uint32_t, TF_UINT32) \
  222. M(int64_t, TF_INT64) \
  223. M(uint64_t, TF_UINT64)
  224. #define TFUTILS_GETDATATYPE_DEF(T, E) \
  225. template <> int TensorSpec::getDataType<T>();
  226. TFUTILS_SUPPORTED_TYPES(TFUTILS_GETDATATYPE_DEF)
  227. #undef TFUTILS_GETDATATYPE_DEF
  228. } // namespace llvm
  229. #endif // LLVM_HAVE_TF_API
  230. #endif // LLVM_ANALYSIS_UTILS_TFUTILS_H
  231. #ifdef __GNUC__
  232. #pragma GCC diagnostic pop
  233. #endif