ModelUnderTrainingRunner.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //===- ModelUnderTrainingRunner.cpp - 'development' mode 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. // Implementation of a MLModelRunner for 'development' mode, i.e. evaluation
  10. // happens off a model that's provided from the command line and is interpreted.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Config/config.h"
  14. #if defined(LLVM_HAVE_TF_API)
  15. #include "llvm/Analysis/ModelUnderTrainingRunner.h"
  16. using namespace llvm;
  17. ModelUnderTrainingRunner::ModelUnderTrainingRunner(
  18. LLVMContext &Ctx, const std::string &ModelPath,
  19. const std::vector<TensorSpec> &InputSpecs,
  20. const std::vector<LoggedFeatureSpec> &OutputSpecs)
  21. : MLModelRunner(Ctx, MLModelRunner::Kind::Development),
  22. OutputSpecs(OutputSpecs) {
  23. Evaluator = std::make_unique<TFModelEvaluator>(
  24. ModelPath, InputSpecs, [&](size_t I) { return OutputSpecs[I].Spec; },
  25. OutputSpecs.size());
  26. if (!Evaluator || !Evaluator->isValid()) {
  27. Ctx.emitError("Failed to create saved model evaluator");
  28. Evaluator.reset();
  29. return;
  30. }
  31. }
  32. void *ModelUnderTrainingRunner::evaluateUntyped() {
  33. LastEvaluationResult = Evaluator->evaluate();
  34. if (!LastEvaluationResult.hasValue()) {
  35. Ctx.emitError("Error evaluating model.");
  36. return nullptr;
  37. }
  38. return LastEvaluationResult->getUntypedTensorValue(0);
  39. }
  40. void *ModelUnderTrainingRunner::getTensorUntyped(size_t Index) {
  41. return Evaluator->getUntypedInput(Index);
  42. }
  43. std::unique_ptr<ModelUnderTrainingRunner>
  44. ModelUnderTrainingRunner::createAndEnsureValid(
  45. LLVMContext &Ctx, const std::string &ModelPath, StringRef DecisionName,
  46. const std::vector<TensorSpec> &InputSpecs,
  47. StringRef OutputSpecsPathOverride) {
  48. std::unique_ptr<ModelUnderTrainingRunner> MUTR;
  49. if (auto MaybeOutputSpecs = loadOutputSpecs(Ctx, DecisionName, ModelPath,
  50. OutputSpecsPathOverride))
  51. MUTR.reset(new ModelUnderTrainingRunner(Ctx, ModelPath, InputSpecs,
  52. *MaybeOutputSpecs));
  53. if (MUTR && MUTR->isValid())
  54. return MUTR;
  55. Ctx.emitError("Could not load the policy model from the provided path");
  56. return nullptr;
  57. }
  58. #endif // defined(LLVM_HAVE_TF_API)