Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2021-02-14 13:33:24

0001 /*
0002  * HelloWorld test of the TensorFlow interface.
0003  * Based on TensorFlow 2.1.
0004  * For more info, see https://gitlab.cern.ch/mrieger/CMSSW-DNN.
0005  *
0006  * Author: Marcel Rieger
0007  */
0008 
0009 #include <stdexcept>
0010 #include <cppunit/extensions/HelperMacros.h>
0011 
0012 #include "tensorflow/cc/saved_model/loader.h"
0013 #include "tensorflow/cc/saved_model/tag_constants.h"
0014 
0015 #include "testBase.h"
0016 
0017 class testHelloWorld : public testBase {
0018   CPPUNIT_TEST_SUITE(testHelloWorld);
0019   CPPUNIT_TEST(checkAll);
0020   CPPUNIT_TEST_SUITE_END();
0021 
0022 public:
0023   std::string pyScript() const override;
0024   void checkAll() override;
0025 };
0026 
0027 CPPUNIT_TEST_SUITE_REGISTRATION(testHelloWorld);
0028 
0029 std::string testHelloWorld::pyScript() const { return "creategraph.py"; }
0030 
0031 void testHelloWorld::checkAll() {
0032   std::string modelDir = dataPath_ + "/simplegraph";
0033 
0034   // object to load and run the graph / session
0035   tensorflow::Status status;
0036   tensorflow::SessionOptions sessionOptions;
0037   tensorflow::RunOptions runOptions;
0038   tensorflow::SavedModelBundle bundle;
0039 
0040   // load everything
0041   status = tensorflow::LoadSavedModel(sessionOptions, runOptions, modelDir, {"serve"}, &bundle);
0042   if (!status.ok()) {
0043     std::cout << status.ToString() << std::endl;
0044     return;
0045   }
0046 
0047   // fetch the session
0048   tensorflow::Session* session = bundle.session.release();
0049 
0050   // prepare inputs
0051   tensorflow::Tensor input(tensorflow::DT_FLOAT, {1, 10});
0052   float* d = input.flat<float>().data();
0053   for (size_t i = 0; i < 10; i++, d++) {
0054     *d = float(i);
0055   }
0056   tensorflow::Tensor scale(tensorflow::DT_FLOAT, {});
0057   scale.scalar<float>()() = 1.0;
0058 
0059   // prepare outputs
0060   std::vector<tensorflow::Tensor> outputs;
0061 
0062   // session run
0063   status = session->Run({{"input", input}, {"scale", scale}}, {"output"}, {}, &outputs);
0064   if (!status.ok()) {
0065     std::cout << status.ToString() << std::endl;
0066     return;
0067   }
0068 
0069   // log the output tensor
0070   std::cout << outputs[0].DebugString() << std::endl;
0071 
0072   // close the session
0073   status = session->Close();
0074   if (!status.ok()) {
0075     std::cerr << "error while closing session" << std::endl;
0076   }
0077   delete session;
0078 }