#include "core.hpp" // Opaque ABI subset of the LiteRT 2.3 TensorFlow Lite C signature-runner API. extern "C" { struct TfLiteModel; struct TfLiteInterpreterOptions; struct TfLiteInterpreter; struct TfLiteSignatureRunner; struct TfLiteTensor; TfLiteModel* TfLiteModelCreateFromFile(const char*); void TfLiteModelDelete(TfLiteModel*); TfLiteInterpreterOptions* TfLiteInterpreterOptionsCreate(); void TfLiteInterpreterOptionsSetNumThreads(TfLiteInterpreterOptions*, int32_t); void TfLiteInterpreterOptionsDelete(TfLiteInterpreterOptions*); TfLiteInterpreter* TfLiteInterpreterCreate(const TfLiteModel*, const TfLiteInterpreterOptions*); void TfLiteInterpreterDelete(TfLiteInterpreter*); TfLiteSignatureRunner* TfLiteInterpreterGetSignatureRunner(const TfLiteInterpreter*, const char*); void TfLiteSignatureRunnerDelete(TfLiteSignatureRunner*); int TfLiteSignatureRunnerAllocateTensors(TfLiteSignatureRunner*); TfLiteTensor* TfLiteSignatureRunnerGetInputTensor(TfLiteSignatureRunner*, const char*); const TfLiteTensor* TfLiteSignatureRunnerGetOutputTensor(const TfLiteSignatureRunner*, const char*); int TfLiteSignatureRunnerInvoke(TfLiteSignatureRunner*); int TfLiteTensorCopyFromBuffer(TfLiteTensor*, const void*, size_t); int TfLiteTensorCopyToBuffer(const TfLiteTensor*, void*, size_t); } template using Handle = std::unique_ptr; class CpuGraph final : public Graph { Handle model{nullptr, TfLiteModelDelete}; Handle interpreter{nullptr, TfLiteInterpreterDelete}; Handle signature{nullptr, TfLiteSignatureRunnerDelete}; public: explicit CpuGraph(const fs::path& path) { model.reset(TfLiteModelCreateFromFile(path.c_str())); require(bool(model), "load " + path.string()); Handle opts( TfLiteInterpreterOptionsCreate(), TfLiteInterpreterOptionsDelete); require(bool(opts), "create CPU options"); TfLiteInterpreterOptionsSetNumThreads(opts.get(), 4); interpreter.reset(TfLiteInterpreterCreate(model.get(), opts.get())); require(bool(interpreter), "create CPU interpreter"); signature.reset(TfLiteInterpreterGetSignatureRunner(interpreter.get(), "serving_default")); require(signature && TfLiteSignatureRunnerAllocateTensors(signature.get()) == 0, "allocate signature"); } void run(const std::vector& inputs, const Outputs& outputs) override { for (size_t i=0; i open_graph(const fs::path& path, bool) { return std::make_unique(path); }