Back to home page

Project CMSSW displayed by LXR

 
 

    


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

0001 /*
0002  * Tests for loading graphs via the converted protobuf files.
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 "PhysicsTools/TensorFlow/interface/TensorFlow.h"
0013 
0014 #include "testBase.h"
0015 
0016 class testGraphLoading : public testBase {
0017   CPPUNIT_TEST_SUITE(testGraphLoading);
0018   CPPUNIT_TEST(checkAll);
0019   CPPUNIT_TEST_SUITE_END();
0020 
0021 public:
0022   std::string pyScript() const override;
0023   void checkAll() override;
0024 };
0025 
0026 CPPUNIT_TEST_SUITE_REGISTRATION(testGraphLoading);
0027 
0028 std::string testGraphLoading::pyScript() const { return "createconstantgraph.py"; }
0029 
0030 void testGraphLoading::checkAll() {
0031   std::string pbFile = dataPath_ + "/constantgraph.pb";
0032 
0033   // load the graph
0034   tensorflow::setLogging();
0035   tensorflow::GraphDef* graphDef = tensorflow::loadGraphDef(pbFile);
0036   CPPUNIT_ASSERT(graphDef != nullptr);
0037 
0038   // create a new session and add the graphDef
0039   tensorflow::Session* session = tensorflow::createSession(graphDef);
0040   CPPUNIT_ASSERT(session != nullptr);
0041 
0042   // check for exception
0043   CPPUNIT_ASSERT_THROW(tensorflow::createSession(nullptr), cms::Exception);
0044 
0045   // example evaluation
0046   tensorflow::Tensor input(tensorflow::DT_FLOAT, {1, 10});
0047   float* d = input.flat<float>().data();
0048   for (size_t i = 0; i < 10; i++, d++) {
0049     *d = float(i);
0050   }
0051   tensorflow::Tensor scale(tensorflow::DT_FLOAT, {});
0052   scale.scalar<float>()() = 1.0;
0053 
0054   std::vector<tensorflow::Tensor> outputs;
0055   tensorflow::Status status = session->Run({{"input", input}, {"scale", scale}}, {"output"}, {}, &outputs);
0056   if (!status.ok()) {
0057     std::cout << status.ToString() << std::endl;
0058     CPPUNIT_ASSERT(false);
0059   }
0060 
0061   // check the output
0062   CPPUNIT_ASSERT(outputs.size() == 1);
0063   std::cout << outputs[0].DebugString() << std::endl;
0064   CPPUNIT_ASSERT(outputs[0].matrix<float>()(0, 0) == 46.);
0065 
0066   // run again using the convenience helper
0067   outputs.clear();
0068   tensorflow::run(session, {{"input", input}, {"scale", scale}}, {"output"}, &outputs);
0069   CPPUNIT_ASSERT(outputs.size() == 1);
0070   std::cout << outputs[0].DebugString() << std::endl;
0071   CPPUNIT_ASSERT(outputs[0].matrix<float>()(0, 0) == 46.);
0072 
0073   // check for exception
0074   CPPUNIT_ASSERT_THROW(tensorflow::run(session, {{"foo", input}}, {"output"}, &outputs), cms::Exception);
0075 
0076   // cleanup
0077   CPPUNIT_ASSERT(tensorflow::closeSession(session));
0078   delete graphDef;
0079 }