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 FAM.invalidate<InlineSizeEstimatorAnalysis>(*F); 164 } 165 166 std::unique_ptr<MLInlineAdvice> 167 getMandatoryAdvice(CallBase &CB, OptimizationRemarkEmitter &ORE) override; 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 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 FT.insert(FT.end(), MUTR->outputLoggedFeatureSpecs().begin() + 1, 336 MUTR->outputLoggedFeatureSpecs().end()); 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::getMandatoryAdvice( 420 CallBase &CB, OptimizationRemarkEmitter &ORE) { 421 if (!isLogging()) 422 return MLInlineAdvisor::getMandatoryAdvice(CB, ORE); 423 424 return std::make_unique<LoggingMLInlineAdvice>( 425 /*Advisor=*/this, 426 /*CB=*/CB, /*ORE=*/ORE, /*Recommendation=*/true, /*Logger=*/*Logger, 427 /*CallerSizeEstimateBefore=*/getNativeSizeEstimate(*CB.getCaller()), 428 /*CalleeSizeEstimateBefore=*/ 429 getNativeSizeEstimate(*CB.getCalledFunction()), 430 /*DefaultDecision=*/true, /*Mandatory*/ true); 431 } 432 433 std::unique_ptr<MLInlineAdvice> 434 DevelopmentModeMLInlineAdvisor::getAdviceFromModel( 435 CallBase &CB, OptimizationRemarkEmitter &ORE) { 436 if (IsDoingInference && !isLogging()) 437 return MLInlineAdvisor::getAdviceFromModel(CB, ORE); 438 439 bool DefaultAdvice = GetDefaultAdvice(CB); 440 auto Recommendation = IsDoingInference ? ModelRunner->run() : DefaultAdvice; 441 return std::make_unique<LoggingMLInlineAdvice>( 442 /*Advisor=*/this, 443 /*CB=*/CB, /*ORE=*/ORE, /*Recommendation=*/Recommendation, 444 /*Logger=*/*Logger, 445 /*CallerSizeEstimateBefore=*/getNativeSizeEstimate(*CB.getCaller()), 446 /*CalleeSizeEstimateBefore=*/ 447 getNativeSizeEstimate(*CB.getCalledFunction()), 448 /*DefaultDecision=*/DefaultAdvice); 449 } 450 451 size_t DevelopmentModeMLInlineAdvisor::getTotalSizeEstimate() { 452 if (!InlineSizeEstimatorAnalysis::isEvaluatorRequested()) 453 return 0; 454 size_t Ret = 0; 455 for (auto &F : M) { 456 if (F.isDeclaration()) 457 continue; 458 if (isFunctionDeleted(&F)) 459 continue; 460 Ret += *getNativeSizeEstimate(F); 461 } 462 return Ret; 463 } 464 465 ModelUnderTrainingRunner::ModelUnderTrainingRunner(LLVMContext &Ctx, 466 const std::string &ModelPath) 467 : MLModelRunner(Ctx) { 468 std::vector<TensorSpec> InputSpecs; 469 for (size_t I = 0; I < NumberOfFeatures; ++I) 470 InputSpecs.push_back( 471 TensorSpec::createSpec<int64_t>(TFFeedPrefix + FeatureNameMap[I], {1})); 472 InputSpecs.insert(InputSpecs.end(), TrainingOnlyFeatures.begin(), 473 TrainingOnlyFeatures.end()); 474 if (auto MaybeOutSpecs = 475 loadOutputSpecs(Ctx, DecisionName, ModelPath, TFOutputSpecOverride)) 476 OutputSpecs = std::move(*MaybeOutSpecs); 477 else 478 return; 479 480 Evaluator = std::make_unique<TFModelEvaluator>( 481 ModelPath, InputSpecs, [&](size_t I) { return OutputSpecs[I].Spec; }, 482 OutputSpecs.size()); 483 if (!Evaluator || !Evaluator->isValid()) { 484 Ctx.emitError("Failed to create inliner saved model evaluator"); 485 Evaluator.reset(); 486 return; 487 } 488 } 489 490 bool ModelUnderTrainingRunner::run() { 491 LastEvaluationResult = Evaluator->evaluate(); 492 if (!LastEvaluationResult.hasValue()) { 493 Ctx.emitError("Error evaluating model."); 494 return false; 495 } 496 int64_t Decision = *LastEvaluationResult->getTensorValue<int64_t>(0); 497 return static_cast<bool>(Decision); 498 } 499 500 int64_t ModelUnderTrainingRunner::getFeature(int Index) const { 501 return *Evaluator->getInput<int64_t>(Index); 502 } 503 504 void ModelUnderTrainingRunner::setFeature(FeatureIndex Index, int64_t Value) { 505 size_t NumericIndex = static_cast<size_t>(Index); 506 *(Evaluator->getInput<int64_t>(NumericIndex)) = Value; 507 } 508 509 std::unique_ptr<InlineAdvisor> llvm::getDevelopmentModeAdvisor( 510 Module &M, ModuleAnalysisManager &MAM, 511 std::function<bool(CallBase &)> GetDefaultAdvice) { 512 auto &Ctx = M.getContext(); 513 std::unique_ptr<MLModelRunner> Runner; 514 ModelUnderTrainingRunner *MUTRPtr = nullptr; 515 bool IsDoingInference = false; 516 if (TFModelUnderTrainingPath.empty()) 517 Runner.reset(new NoInferenceModelRunner(Ctx)); 518 else { 519 auto MUTR = std::make_unique<ModelUnderTrainingRunner>( 520 Ctx, TFModelUnderTrainingPath); 521 if (!MUTR || !MUTR->isValid()) { 522 Ctx.emitError("Could not load the policy model from the provided path"); 523 return nullptr; 524 } 525 IsDoingInference = true; 526 MUTRPtr = MUTR.get(); 527 Runner = std::move(MUTR); 528 } 529 std::unique_ptr<TrainingLogger> Logger; 530 if (!TrainingLog.empty()) 531 Logger = std::make_unique<TrainingLogger>(TrainingLog, MUTRPtr); 532 533 return std::make_unique<DevelopmentModeMLInlineAdvisor>( 534 M, MAM, std::move(Runner), GetDefaultAdvice, IsDoingInference, 535 std::move(Logger)); 536 } 537 #endif // defined(LLVM_HAVE_TF_API) 538