xref: /netbsd-src/external/apache2/llvm/dist/llvm/lib/Analysis/DevelopmentModeInlineAdvisor.cpp (revision 82d56013d7b633d116a93943de88e08335357a7c)
1 //===- DevelopmentModeInlineAdvisor.cpp - runtime-loadable model runner  --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a model runner using Tensorflow C APIs, allowing the
11 // loading of a model from a command line option.
12 //
13 //===----------------------------------------------------------------------===//
14 #include "llvm/Config/config.h"
15 #if defined(LLVM_HAVE_TF_API)
16 
17 #include "llvm/Analysis/CallGraph.h"
18 #include "llvm/Analysis/InlineSizeEstimatorAnalysis.h"
19 #include "llvm/Analysis/MLInlineAdvisor.h"
20 #include "llvm/Analysis/Utils/TFUtils.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/ManagedStatic.h"
24 
25 #include <vector>
26 
27 using namespace llvm;
28 
29 static cl::opt<std::string> TrainingLog(
30     "training-log", cl::Hidden,
31     cl::desc("Path where the development - mode inlining log is saved."));
32 
33 static cl::opt<std::string> TFModelUnderTrainingPath(
34     "ml-inliner-model-under-training", cl::Hidden,
35     cl::desc(R"(Path to SavedModel from the previous training iteration.
36 The directory is also expected to contain a JSON specification of the
37 outputs expected to be logged, where the first entry must be the
38 inlining decision. The file containing the specification should be
39 called output_spec.json. The expected JSON value is an array of
40 dictionaries. Each dictionary should have 2 keys:
41 
42 - "tensor_spec, followed by the TensorSpec description of the
43 output; and
44 - "logging_name", a string indicating the name to use when
45 logging the output values.
46 
47 Example:
48 [
49   {
50     "logging_name" : "some_name",
51     "tensor_spec" : {
52       "name" : "model_name",
53       "port" : 0,
54       "shape" : [2, 3],
55       "type" : "float"
56       }
57   }
58 ]
59 
60 The first value must always correspond to the decision.)"));
61 
62 static cl::opt<std::string> TFOutputSpecOverride(
63     "ml-inliner-output-spec-override", cl::Hidden,
64     cl::desc("Override the path to the output spec json file. See "
65              "-ml-inliner-model-under-training documentation for the "
66              "specification of that file."));
67 
68 static cl::opt<std::string> TFFeedPrefix("ml-inliner-trained-model-feed-prefix",
69                                          cl::Hidden, cl::init("action_"),
70                                          cl::desc("Prefix for feature names."));
71 
72 namespace {
73 /// An InlineEvent, used by TrainingLogger.
74 struct InlineEvent {
75   /// What the default policy's decision would have been.
76   int64_t DefaultDecision = 0;
77 
78   /// What we advised. When training off the default policy, this is the same as
79   /// DefaultDecision.
80   int64_t AdvisedDecision = 0;
81 
82   /// What actually happened. This would be 'false' in the case of an inline
83   /// error, even if AdvisedDecision were true, otherwise it agrees with
84   /// AdvisedDecision.
85   bool Effect = false;
86 
87   /// What the change in size was: size_after - size_before
88   int64_t Reward = 0;
89 };
90 
91 /// Collect data we may use for training a model, and write it as a textual
92 /// Tensorflow SequenceExample
93 /// (https://www.tensorflow.org/api_docs/python/tf/train/SequenceExample)
94 /// protobuf (https://developers.google.com/protocol-buffers).
95 /// Because this is a protobuf, we cannot just stream the events as they come.
96 /// Internally, TrainingLogger stores data in column-major format, because that
97 /// lines up with how TF SequenceExample represents it.
98 class ModelUnderTrainingRunner;
99 class TrainingLogger final {
100 public:
101   TrainingLogger(StringRef LogFileName, const ModelUnderTrainingRunner *MUTR);
102 
103   /// Log one inlining event.
104   void logInlineEvent(const InlineEvent &Event,
105                       const MLModelRunner &ModelRunner);
106 
107   /// Print the stored tensors.
108   void print();
109 
110 private:
111   StringRef LogFileName;
112   const ModelUnderTrainingRunner *const MUTR;
113   std::unique_ptr<Logger> L;
114   std::vector<bool> Effects;
115   /// There's at least one output. We'll set this to a different value if MUTR
116   /// is avaliable.
117   size_t OutputCount = 1;
118   /// Set these 2 clearly OOB, to make sure we set them later.
119   size_t DefaultDecisionPos = std::numeric_limits<size_t>::max();
120   size_t DecisionPos = std::numeric_limits<size_t>::max();
121 };
122 
123 /// An extension of the MLInlineAdvisor for the 'development' mode, targeting
124 /// the offline training scenario. Note that training happens outside of the
125 /// compiler, this facility is concerned with producing training data ("logs").
126 /// This InlineAdvisor can operate in the following modes:
127 ///
128 /// 1) collect logs for the default policy. This is useful for bootstrapping
129 /// training, which will be considerably faster by starting from a reasonable
130 /// policy.
131 ///
132 /// 2) collect logs for the ML policy, using a model from a previous
133 /// training. Potentially, that model uses internally some small random
134 /// perturbation of its weights, to induce exploration (setting this up is the
135 /// responsibility of the training algorithm). The logs would then be used to
136 /// retrain and improve on this model.
137 ///
138 /// 3) use the provided model, with no logging. This is useful for end to end
139 /// validation - the model, in this case, is a release candidate and shouldn't
140 /// have random perturbations. It is a convenience feature: rather than needing
141 /// to take the release candidate model and compile it in 'release' mode,
142 /// validate it, then potentially discard it, it's easier to just pass the model
143 /// to the compiler, albeit compilation would be slower, as a one-off. Once the
144 /// model behaves satisfactorily, it can be compiled AOT, for efficiency, in
145 /// release mode. The expectation is that a well-trained model provides a good
146 /// policy over a sufficiently diverse codebase, over many changes (i.e.
147 /// training happens seldom).
148 class DevelopmentModeMLInlineAdvisor : public MLInlineAdvisor {
149 public:
150   DevelopmentModeMLInlineAdvisor(
151       Module &M, ModuleAnalysisManager &MAM,
152       std::unique_ptr<MLModelRunner> ModelRunner,
153       std::function<bool(CallBase &)> GetDefaultAdvice, bool IsDoingInference,
154       std::unique_ptr<TrainingLogger> Logger);
155 
156   size_t getTotalSizeEstimate();
157 
158   virtual ~DevelopmentModeMLInlineAdvisor();
updateNativeSizeEstimate(int64_t Change)159   void updateNativeSizeEstimate(int64_t Change) {
160     *CurrentNativeSize += Change;
161   }
162   void resetNativeSize(Function *F) {
163     PreservedAnalyses PA = PreservedAnalyses::all();
164     PA.abandon<InlineSizeEstimatorAnalysis>();
165     FAM.invalidate(*F, PA);
166   }
167 
168   std::unique_ptr<MLInlineAdvice>
169   getAdviceFromModel(CallBase &CB, OptimizationRemarkEmitter &ORE) override;
170 
171   Optional<size_t> getNativeSizeEstimate(const Function &F) const;
172 
173 private:
174   bool isLogging() const { return !!Logger; }
175   std::unique_ptr<MLInlineAdvice> getMandatoryAdviceImpl(CallBase &CB) override;
176 
177   std::function<bool(CallBase &)> GetDefaultAdvice;
178   const bool IsDoingInference;
179   std::unique_ptr<TrainingLogger> Logger;
180 
181   const Optional<int32_t> InitialNativeSize;
182   Optional<int32_t> CurrentNativeSize;
183 };
184 
185 /// A variant of MLInlineAdvice that tracks all non-trivial inlining
186 /// decisions, for training/logging.
187 class LoggingMLInlineAdvice : public MLInlineAdvice {
188 public:
189   LoggingMLInlineAdvice(DevelopmentModeMLInlineAdvisor *Advisor, CallBase &CB,
190                         OptimizationRemarkEmitter &ORE, bool Recommendation,
191                         TrainingLogger &Logger,
192                         Optional<size_t> CallerSizeEstimateBefore,
193                         Optional<size_t> CalleeSizeEstimateBefore,
194                         bool DefaultDecision, bool Mandatory = false)
195       : MLInlineAdvice(Advisor, CB, ORE, Recommendation), Logger(Logger),
196         CallerSizeEstimateBefore(CallerSizeEstimateBefore),
197         CalleeSizeEstimateBefore(CalleeSizeEstimateBefore),
198         DefaultDecision(DefaultDecision), Mandatory(Mandatory) {}
199 
200   virtual ~LoggingMLInlineAdvice() = default;
201 
202 private:
203   DevelopmentModeMLInlineAdvisor *getAdvisor() const {
204     return static_cast<DevelopmentModeMLInlineAdvisor *>(Advisor);
205   }
206   void recordInliningImpl() override {
207     MLInlineAdvice::recordInliningImpl();
208     getAdvisor()->resetNativeSize(Caller);
209     int Reward = std::numeric_limits<int>::max();
210     if (InlineSizeEstimatorAnalysis::isEvaluatorRequested() &&
211         !getAdvisor()->isForcedToStop()) {
212       int NativeSizeAfter = *getAdvisor()->getNativeSizeEstimate(*Caller) +
213                             *CalleeSizeEstimateBefore;
214       Reward = NativeSizeAfter -
215                (*CallerSizeEstimateBefore + *CalleeSizeEstimateBefore);
216       getAdvisor()->updateNativeSizeEstimate(Reward);
217     }
218     log(Reward, /*Success=*/true);
219   }
220 
221   void recordInliningWithCalleeDeletedImpl() override {
222     MLInlineAdvice::recordInliningWithCalleeDeletedImpl();
223     getAdvisor()->resetNativeSize(Caller);
224     if (InlineSizeEstimatorAnalysis::isEvaluatorRequested() &&
225         !getAdvisor()->isForcedToStop()) {
226       int NativeSizeAfter = *getAdvisor()->getNativeSizeEstimate(*Caller);
227       int Reward = NativeSizeAfter -
228                    (*CallerSizeEstimateBefore + *CalleeSizeEstimateBefore);
229       getAdvisor()->updateNativeSizeEstimate(Reward);
230       log(Reward, /*Success=*/true);
231     }
232   }
233 
234   void recordUnsuccessfulInliningImpl(const InlineResult &Result) override {
235     MLInlineAdvice::recordUnsuccessfulInliningImpl(Result);
236     log(NoReward, /*Success=*/false);
237   }
238 
239   void recordUnattemptedInliningImpl() override {
240     MLInlineAdvice::recordUnattemptedInliningImpl();
241     log(NoReward, /*Success=*/false);
242   }
243 
244   void log(int64_t Reward, bool Success) {
245     if (Mandatory)
246       return;
247     InlineEvent Event;
248     Event.AdvisedDecision = isInliningRecommended();
249     Event.DefaultDecision = DefaultDecision;
250     Event.Effect = Success;
251     Event.Reward = Reward;
252     Logger.logInlineEvent(Event, getAdvisor()->getModelRunner());
253   }
254 
255   static const int64_t NoReward = 0;
256   TrainingLogger &Logger;
257   const Optional<size_t> CallerSizeEstimateBefore;
258   const Optional<size_t> CalleeSizeEstimateBefore;
259   const int64_t DefaultDecision;
260   const int64_t Mandatory;
261 };
262 
263 /// A pseudo model runner. We use it to store feature values when collecting
264 /// logs for the default policy, but never ask it to 'run'.
265 class NoInferenceModelRunner : public MLModelRunner {
266 public:
267   NoInferenceModelRunner(LLVMContext &Ctx)
268       : MLModelRunner(Ctx), Features(NumberOfFeatures) {}
269   void setFeature(FeatureIndex Index, int64_t Value) override {
270     Features[static_cast<int>(Index)] = Value;
271   }
272 
273   int64_t getFeature(int Index) const override { return Features[Index]; }
274   bool run() override {
275     llvm_unreachable("We shouldn't call run on this model runner.");
276   }
277 
278 private:
279   InlineFeatures Features;
280 };
281 
282 /// ModelUnderTrainingRunner - training mode implementation. It uses TF C APIs
283 /// to dynamically load and evaluate a TF SavedModel
284 /// (https://www.tensorflow.org/guide/saved_model). Runtime performance is
285 /// sacrificed for ease of use while training.
286 class ModelUnderTrainingRunner final : public MLModelRunner {
287 public:
288   ModelUnderTrainingRunner(LLVMContext &Ctx, const std::string &ModelPath);
289 
290   bool run() override;
291 
292   // Disallows copy and assign.
293   ModelUnderTrainingRunner(const ModelUnderTrainingRunner &) = delete;
294   ModelUnderTrainingRunner &
295   operator=(const ModelUnderTrainingRunner &) = delete;
296 
297   void setFeature(FeatureIndex Index, int64_t Value) override;
298   int64_t getFeature(int Index) const override;
299   bool isValid() const { return !!Evaluator; }
300 
301   const std::vector<LoggedFeatureSpec> &outputLoggedFeatureSpecs() const {
302     return OutputSpecs;
303   }
304 
305   const Optional<TFModelEvaluator::EvaluationResult> &
306   lastEvaluationResult() const {
307     return LastEvaluationResult;
308   }
309 
310 private:
311   std::unique_ptr<TFModelEvaluator> Evaluator;
312   std::vector<LoggedFeatureSpec> OutputSpecs;
313   Optional<TFModelEvaluator::EvaluationResult> LastEvaluationResult;
314 
315   // The training framework needs some additional features.
316   const std::vector<TensorSpec> TrainingOnlyFeatures{
317       TensorSpec::createSpec<int64_t>(TFFeedPrefix + "inlining_default", {1}),
318       TensorSpec::createSpec<float>(TFFeedPrefix + "discount", {1}),
319       TensorSpec::createSpec<float>(TFFeedPrefix + "reward", {1}),
320       TensorSpec::createSpec<int32_t>(TFFeedPrefix + "step_type", {1})};
321 };
322 } // namespace
323 
324 TrainingLogger::TrainingLogger(StringRef LogFileName,
325                                const ModelUnderTrainingRunner *MUTR)
326     : LogFileName(LogFileName), MUTR(MUTR) {
327   // The first output is the inlining decision.
328   if (MUTR)
329     OutputCount = MUTR->outputLoggedFeatureSpecs().size();
330   std::vector<LoggedFeatureSpec> FT;
331 
332   for (size_t I = 0; I < NumberOfFeatures; ++I)
333     FT.push_back(
334         {TensorSpec::createSpec<int64_t>(FeatureNameMap.at(I), {1}), None});
335   if (MUTR && MUTR->outputLoggedFeatureSpecs().size() > 1)
336     append_range(FT, drop_begin(MUTR->outputLoggedFeatureSpecs()));
337 
338   DefaultDecisionPos = FT.size();
339   FT.push_back(
340       {TensorSpec::createSpec<int64_t>(DefaultDecisionName, {1}), None});
341 
342   DecisionPos = FT.size();
343   FT.push_back({TensorSpec::createSpec<int64_t>(DecisionName, {1}), None});
344 
345   L = std::make_unique<Logger>(
346       FT, TensorSpec::createSpec<int64_t>(RewardName, {1}),
347       InlineSizeEstimatorAnalysis::isEvaluatorRequested());
348 }
349 
350 /// Log one inlining event.
351 void TrainingLogger::logInlineEvent(const InlineEvent &Event,
352                                     const MLModelRunner &ModelRunner) {
353   size_t CurrentFeature = 0;
354   for (; CurrentFeature < NumberOfFeatures; ++CurrentFeature) {
355     int64_t F = ModelRunner.getFeature(CurrentFeature);
356     L->logTensorValue(CurrentFeature, &F);
357   }
358 
359   for (size_t I = 1; I < OutputCount; ++I) {
360     const auto &Result = *MUTR->lastEvaluationResult();
361     auto &Spec = MUTR->outputLoggedFeatureSpecs()[I].Spec;
362     const char *RawData =
363         reinterpret_cast<const char *>(Result.getUntypedTensorValue(I));
364     L->logTensorValue(CurrentFeature, RawData,
365                       Spec.getElementCount() * Spec.getElementByteSize());
366     ++CurrentFeature;
367   }
368 
369   assert(CurrentFeature == DefaultDecisionPos);
370   L->logTensorValue(DefaultDecisionPos, &Event.DefaultDecision);
371   L->logTensorValue(DecisionPos, &Event.AdvisedDecision);
372   if (InlineSizeEstimatorAnalysis::isEvaluatorRequested())
373     L->logReward(Event.Reward);
374 
375   // For debugging / later use
376   Effects.push_back(Event.Effect);
377 }
378 
379 void TrainingLogger::print() {
380   std::error_code EC;
381   raw_fd_ostream OutFile(LogFileName, EC);
382   L->print(OutFile);
383 }
384 
385 DevelopmentModeMLInlineAdvisor::DevelopmentModeMLInlineAdvisor(
386     Module &M, ModuleAnalysisManager &MAM,
387     std::unique_ptr<MLModelRunner> ModelRunner,
388     std::function<bool(CallBase &)> GetDefaultAdvice, bool IsDoingInference,
389     std::unique_ptr<TrainingLogger> Logger)
390     : MLInlineAdvisor(M, MAM, std::move(ModelRunner)),
391       GetDefaultAdvice(GetDefaultAdvice), IsDoingInference(IsDoingInference),
392       Logger(std::move(Logger)),
393       InitialNativeSize(isLogging() ? getTotalSizeEstimate() : 0),
394       CurrentNativeSize(InitialNativeSize) {
395   // We cannot have the case of neither inference nor logging.
396   assert(IsDoingInference || isLogging());
397 }
398 
399 DevelopmentModeMLInlineAdvisor::~DevelopmentModeMLInlineAdvisor() {
400   if (isLogging())
401     Logger->print();
402 }
403 
404 Optional<size_t>
405 DevelopmentModeMLInlineAdvisor::getNativeSizeEstimate(const Function &F) const {
406   if (!InlineSizeEstimatorAnalysis::isEvaluatorRequested())
407     return None;
408   auto &R =
409       FAM.getResult<InlineSizeEstimatorAnalysis>(const_cast<Function &>(F));
410   if (!R) {
411     F.getParent()->getContext().emitError(
412         "Native size estimator is not present.");
413     return 0;
414   }
415   return *R;
416 }
417 
418 std::unique_ptr<MLInlineAdvice>
419 DevelopmentModeMLInlineAdvisor::getMandatoryAdviceImpl(CallBase &CB) {
420   return std::make_unique<LoggingMLInlineAdvice>(
421       /*Advisor=*/this,
422       /*CB=*/CB, /*ORE=*/getCallerORE(CB), /*Recommendation=*/true,
423       /*Logger=*/*Logger,
424       /*CallerSizeEstimateBefore=*/getNativeSizeEstimate(*CB.getCaller()),
425       /*CalleeSizeEstimateBefore=*/
426       getNativeSizeEstimate(*CB.getCalledFunction()),
427       /*DefaultDecision=*/true, /*Mandatory*/ true);
428 }
429 
430 std::unique_ptr<MLInlineAdvice>
431 DevelopmentModeMLInlineAdvisor::getAdviceFromModel(
432     CallBase &CB, OptimizationRemarkEmitter &ORE) {
433   if (IsDoingInference && !isLogging())
434     return MLInlineAdvisor::getAdviceFromModel(CB, ORE);
435 
436   bool DefaultAdvice = GetDefaultAdvice(CB);
437   auto Recommendation = IsDoingInference ? ModelRunner->run() : DefaultAdvice;
438   return std::make_unique<LoggingMLInlineAdvice>(
439       /*Advisor=*/this,
440       /*CB=*/CB, /*ORE=*/ORE, /*Recommendation=*/Recommendation,
441       /*Logger=*/*Logger,
442       /*CallerSizeEstimateBefore=*/getNativeSizeEstimate(*CB.getCaller()),
443       /*CalleeSizeEstimateBefore=*/
444       getNativeSizeEstimate(*CB.getCalledFunction()),
445       /*DefaultDecision=*/DefaultAdvice);
446 }
447 
448 size_t DevelopmentModeMLInlineAdvisor::getTotalSizeEstimate() {
449   if (!InlineSizeEstimatorAnalysis::isEvaluatorRequested())
450     return 0;
451   size_t Ret = 0;
452   for (auto &F : M) {
453     if (F.isDeclaration())
454       continue;
455     if (isFunctionDeleted(&F))
456       continue;
457     Ret += *getNativeSizeEstimate(F);
458   }
459   return Ret;
460 }
461 
462 ModelUnderTrainingRunner::ModelUnderTrainingRunner(LLVMContext &Ctx,
463                                                    const std::string &ModelPath)
464     : MLModelRunner(Ctx) {
465   std::vector<TensorSpec> InputSpecs;
466   for (size_t I = 0; I < NumberOfFeatures; ++I)
467     InputSpecs.push_back(
468         TensorSpec::createSpec<int64_t>(TFFeedPrefix + FeatureNameMap[I], {1}));
469   append_range(InputSpecs, TrainingOnlyFeatures);
470   if (auto MaybeOutSpecs =
471           loadOutputSpecs(Ctx, DecisionName, ModelPath, TFOutputSpecOverride))
472     OutputSpecs = std::move(*MaybeOutSpecs);
473   else
474     return;
475 
476   Evaluator = std::make_unique<TFModelEvaluator>(
477       ModelPath, InputSpecs, [&](size_t I) { return OutputSpecs[I].Spec; },
478       OutputSpecs.size());
479   if (!Evaluator || !Evaluator->isValid()) {
480     Ctx.emitError("Failed to create inliner saved model evaluator");
481     Evaluator.reset();
482     return;
483   }
484 }
485 
486 bool ModelUnderTrainingRunner::run() {
487   LastEvaluationResult = Evaluator->evaluate();
488   if (!LastEvaluationResult.hasValue()) {
489     Ctx.emitError("Error evaluating model.");
490     return false;
491   }
492   int64_t Decision = *LastEvaluationResult->getTensorValue<int64_t>(0);
493   return static_cast<bool>(Decision);
494 }
495 
496 int64_t ModelUnderTrainingRunner::getFeature(int Index) const {
497   return *Evaluator->getInput<int64_t>(Index);
498 }
499 
500 void ModelUnderTrainingRunner::setFeature(FeatureIndex Index, int64_t Value) {
501   size_t NumericIndex = static_cast<size_t>(Index);
502   *(Evaluator->getInput<int64_t>(NumericIndex)) = Value;
503 }
504 
505 std::unique_ptr<InlineAdvisor> llvm::getDevelopmentModeAdvisor(
506     Module &M, ModuleAnalysisManager &MAM,
507     std::function<bool(CallBase &)> GetDefaultAdvice) {
508   auto &Ctx = M.getContext();
509   std::unique_ptr<MLModelRunner> Runner;
510   ModelUnderTrainingRunner *MUTRPtr = nullptr;
511   bool IsDoingInference = false;
512   if (TFModelUnderTrainingPath.empty())
513     Runner.reset(new NoInferenceModelRunner(Ctx));
514   else {
515     auto MUTR = std::make_unique<ModelUnderTrainingRunner>(
516         Ctx, TFModelUnderTrainingPath);
517     if (!MUTR || !MUTR->isValid()) {
518       Ctx.emitError("Could not load the policy model from the provided path");
519       return nullptr;
520     }
521     IsDoingInference = true;
522     MUTRPtr = MUTR.get();
523     Runner = std::move(MUTR);
524   }
525   std::unique_ptr<TrainingLogger> Logger;
526   if (!TrainingLog.empty())
527     Logger = std::make_unique<TrainingLogger>(TrainingLog, MUTRPtr);
528 
529   return std::make_unique<DevelopmentModeMLInlineAdvisor>(
530       M, MAM, std::move(Runner), GetDefaultAdvice, IsDoingInference,
531       std::move(Logger));
532 }
533 #endif // defined(LLVM_HAVE_TF_API)
534