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