1+ // ===- TFUtils.h - utilities for tensorflow C API ---------------*- C++ -*-===//
2+ //
3+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4+ // See https://llvm.org/LICENSE.txt for license information.
5+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6+ //
7+ // ===----------------------------------------------------------------------===//
8+ //
9+ #ifndef LLVM_ANALYSIS_UTILS_TFUTILS_H
10+ #define LLVM_ANALYSIS_UTILS_TFUTILS_H
11+
12+ #include " tensorflow/c/c_api.h"
13+ #include " llvm/IR/LLVMContext.h"
14+
15+ #include < memory>
16+ #include < vector>
17+
18+ namespace llvm {
19+
20+ // / Load a SavedModel, find the given inputs and outputs, and setup storage
21+ // / for input tensors. The user is responsible for correctly dimensioning the
22+ // / input tensors and setting their values before calling evaluate().
23+ // / To initialize:
24+ // / - construct the object
25+ // / - initialize the input tensors using initInput. Indices must correspond to
26+ // / indices in the InputNames used at construction.
27+ // / To use:
28+ // / - set input values by using getInput to get each input tensor, and then
29+ // / setting internal scalars, for all dimensions (tensors are row-major:
30+ // / https://github.com/tensorflow/tensorflow/blob/r1.5/tensorflow/c/c_api.h#L205)
31+ // / - prepare an output vector of TF_Output* type, with the correct number of
32+ // / outputs (i.e. same as OutputNames). Initialize the vector with nullptr
33+ // / values.
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+ // / - deallocate each output tensor in the output vector, using TF_DeleteTensor.
38+ class TFModelEvaluator final {
39+ public:
40+ // / The result of a model evaluation. Handles the lifetime of the output
41+ // / TF_Tensor objects, which means that their values need to be used before
42+ // / the EvaluationResult's dtor is called.
43+ class EvaluationResult {
44+ public:
45+ ~EvaluationResult () {
46+ for (auto *P : Output)
47+ if (P)
48+ TF_DeleteTensor (P);
49+ }
50+
51+ EvaluationResult (const EvaluationResult &) = delete ;
52+ EvaluationResult (EvaluationResult &&Other)
53+ : OutputSize(Other.OutputSize), Output(std::move(Other.Output)) {
54+ Other.Output .clear ();
55+ };
56+
57+ // / Get a pointer to the first element of the tensor at Index.
58+ template <typename T> T *getTensorValue (size_t Index) {
59+ return static_cast <T *>(TF_TensorData (Output[Index]));
60+ }
61+
62+ private:
63+ friend class TFModelEvaluator ;
64+ EvaluationResult (size_t OutputSize)
65+ : OutputSize(OutputSize), Output(OutputSize){};
66+
67+ const size_t OutputSize;
68+ std::vector<TF_Tensor *> Output;
69+ };
70+
71+ using TFGraphPtr = std::unique_ptr<TF_Graph, decltype (&TF_DeleteGraph)>;
72+ using TFSessionOptionsPtr =
73+ std::unique_ptr<TF_SessionOptions, decltype (&TF_DeleteSessionOptions)>;
74+ using TFStatusPtr = std::unique_ptr<TF_Status, decltype (&TF_DeleteStatus)>;
75+
76+ TFModelEvaluator (StringRef SavedModelPath,
77+ const std::vector<std::string> &InputNames,
78+ const std::vector<std::string> &OutputNames,
79+ const char *Tags = " serve" );
80+ ~TFModelEvaluator ();
81+ TFModelEvaluator (const TFModelEvaluator &) = delete ;
82+ TFModelEvaluator (TFModelEvaluator &&) = delete ;
83+
84+ // / Evaluate the model, assuming it is valid. Returns None if the evaluation
85+ // / fails or the model is invalid, or an EvaluationResult otherwise. The
86+ // / inputs are assumed to have been already provided via getInput(). When
87+ // / returning None, it also marks the object invalid. Pass an Output vector
88+ // / with the same size as OutputNames, but with nullptr values. evaluate()
89+ // / will populate it with tensors, matching in index the corresponding
90+ // / OutputNames. The caller is responsible for the deallocation of those
91+ // / tensors, using TF_DeleteTensor.
92+ Optional<EvaluationResult> evaluate ();
93+
94+ // / Provides access to the input vector. It is already dimensioned correctly,
95+ // / but the values need to be allocated by the user.
96+ std::vector<TF_Tensor *> &getInput () { return Input; }
97+
98+ // / Returns true if the tensorflow model was loaded successfully, false
99+ // / otherwise.
100+ bool isValid () const { return !!Session; }
101+
102+ // / Initialize the input at Index as a tensor of the given type and dimensions
103+ void initInput (int Index, TF_DataType Type,
104+ const std::vector<int64_t > &Dimensions);
105+
106+ private:
107+ // / The objects necessary for carrying out an evaluation of the SavedModel.
108+ // / They are expensive to set up, and we maintain them accross all the
109+ // / evaluations of the model.
110+ TF_Session *Session = nullptr ;
111+ TFGraphPtr Graph;
112+ TFSessionOptionsPtr Options;
113+
114+ // / The specification of the input nodes.
115+ std::vector<TF_Output> InputFeed;
116+
117+ // / The input tensors. They must match by index of the corresponding InputFeed
118+ // / value. We set up the tensors once and just mutate theirs scalars before
119+ // / each evaluation. The input tensors keep their value after an evaluation.
120+ std::vector<TF_Tensor *> Input;
121+
122+ // / The specification of the output nodes. When evaluating, the tensors in the
123+ // / output tensor vector must match by index the corresponding element in the
124+ // / OutputFeed.
125+ std::vector<TF_Output> OutputFeed;
126+
127+ // / Reusable utility for deleting the session.
128+ void deleteSession ();
129+
130+ // / Reusable utility for ensuring we can bind the requested Name to a node in
131+ // / the SavedModel Graph.
132+ bool checkReportAndReset (const TF_Output &Output, StringRef Name);
133+ };
134+ } // namespace llvm
135+
136+ #endif // LLVM_ANALYSIS_UTILS_TFUTILS_H
0 commit comments