Skip to content

Commit 83080a2

Browse files
committed
[llvm] Native size estimator for training -Oz inliner
Summary: This is an experimental ML-based native size estimator, necessary for computing partial rewards during -Oz inliner policy training. Data extraction for model training will be provided in a separate patch. RFC: http://lists.llvm.org/pipermail/llvm-dev/2020-April/140763.html Reviewers: davidxl, jdoerfert Subscribers: mgorny, hiraditya, mgrang, arphaman, llvm-commits Tags: #llvm Differential Revision: https://reviews.llvm.org/D82817
1 parent 153a0b8 commit 83080a2

14 files changed

Lines changed: 11464 additions & 10 deletions

File tree

‎llvm/CMakeLists.txt‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -981,6 +981,18 @@ if (NOT TENSORFLOW_AOT_PATH STREQUAL "")
981981
${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}/tf_runtime)
982982
endif()
983983

984+
set(TENSORFLOW_C_LIB_PATH "" CACHE PATH "Path to TensorFlow C library install")
985+
find_library(tensorflow_c_api tensorflow PATHS ${TENSORFLOW_C_LIB_PATH}/lib)
986+
987+
# Similar to the above Tensorflow dependency, please refer to the same script.
988+
# In this case, the latest C API library is available for download from
989+
# https://www.tensorflow.org/install/lang_c
990+
if (tensorflow_c_api)
991+
set(LLVM_HAVE_TF_API "ON" CACHE BOOL "Full Tensorflow API available")
992+
add_definitions("-DLLVM_HAVE_TF_API")
993+
include_directories(${TENSORFLOW_C_LIB_PATH}/include)
994+
endif()
995+
984996
# Put this before tblgen. Else we have a circular dependence.
985997
add_subdirectory(lib/Demangle)
986998
add_subdirectory(lib/Support)
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
//===- InlineSizeEstimatorAnalysis.h - ML size estimator --------*- 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+
10+
#ifndef LLVM_ANALYSIS_INLINESIZEESTIMATORANALYSIS_H
11+
#define LLVM_ANALYSIS_INLINESIZEESTIMATORANALYSIS_H
12+
13+
#include "llvm/IR/PassManager.h"
14+
15+
namespace llvm {
16+
class Function;
17+
18+
class TFModelEvaluator;
19+
class InlineSizeEstimatorAnalysis
20+
: public AnalysisInfoMixin<InlineSizeEstimatorAnalysis> {
21+
public:
22+
InlineSizeEstimatorAnalysis();
23+
InlineSizeEstimatorAnalysis(InlineSizeEstimatorAnalysis &&);
24+
~InlineSizeEstimatorAnalysis();
25+
26+
static AnalysisKey Key;
27+
using Result = Optional<size_t>;
28+
Result run(const Function &F, FunctionAnalysisManager &FAM);
29+
static bool isEvaluatorRequested();
30+
31+
private:
32+
std::unique_ptr<TFModelEvaluator> Evaluator;
33+
};
34+
} // namespace llvm
35+
#endif // LLVM_ANALYSIS_INLINESIZEESTIMATORANALYSIS_H
Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
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

‎llvm/lib/Analysis/CMakeLists.txt‎

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,35 @@
11
set(CommonMLSources MLInlineAdvisor.cpp)
22
set(ReleaseModeMLSources ReleaseModeModelRunner.cpp)
3+
set(DevelopmentModeMLSources TFUtils.cpp)
34

4-
if (DEFINED LLVM_HAVE_TF_AOT)
5-
include(TensorFlowCompile)
6-
tfcompile(models/inliner serve action InlinerSizeModel llvm::InlinerSizeModel)
7-
list(APPEND ReleaseModeMLSources
8-
$<TARGET_OBJECTS:tf_xla_runtime_objects>
9-
${GENERATED_OBJS}
10-
)
11-
set(MLPolicySources ${CommonMLSources} ${ReleaseModeMLSources})
5+
if (DEFINED LLVM_HAVE_TF_AOT OR DEFINED LLVM_HAVE_TF_API)
6+
set(MLPolicySources ${CommonMLSources})
7+
if (DEFINED LLVM_HAVE_TF_AOT)
8+
include(TensorFlowCompile)
9+
tfcompile(models/inliner serve action InlinerSizeModel llvm::InlinerSizeModel)
10+
list(APPEND ReleaseModeMLSources
11+
$<TARGET_OBJECTS:tf_xla_runtime_objects>
12+
${GENERATED_OBJS}
13+
)
14+
LIST(APPEND MLPolicySources ${ReleaseModeMLSources})
15+
else()
16+
LIST(APPEND LLVM_OPTIONAL_SOURCES ${ReleaseModeMLSources})
17+
endif()
18+
19+
if (DEFINED LLVM_HAVE_TF_API)
20+
LIST(APPEND MLPolicySources ${DevelopmentModeMLSources})
21+
LIST(APPEND MLLinkDeps ${tensorflow_c_api})
22+
else()
23+
LIST(APPEND LLVM_OPTIONAL_SOURCES ${DevelopmentModeMLSources})
24+
endif()
1225
else()
13-
set(LLVM_OPTIONAL_SOURCES ${CommonMLSources} ${ReleaseModeMLSources})
26+
LIST(APPEND LLVM_OPTIONAL_SOURCES
27+
${CommonMLSources}
28+
${DevelopmentModeMLSources}
29+
${ReleaseModeMLSources}
30+
)
1431
endif()
32+
1533

1634
add_llvm_component_library(LLVMAnalysis
1735
AliasAnalysis.cpp
@@ -57,6 +75,7 @@ add_llvm_component_library(LLVMAnalysis
5775
InlineCost.cpp
5876
InlineAdvisor.cpp
5977
InlineFeaturesAnalysis.cpp
78+
InlineSizeEstimatorAnalysis.cpp
6079
InstCount.cpp
6180
InstructionPrecedenceTracking.cpp
6281
InstructionSimplify.cpp
@@ -124,4 +143,7 @@ add_llvm_component_library(LLVMAnalysis
124143

125144
DEPENDS
126145
intrinsics_gen
146+
147+
LINK_LIBS
148+
${MLLinkDeps}
127149
)

0 commit comments

Comments
 (0)