Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-04-06 12:24:15

0001 /*
0002  * Tests for working with constant sessions.
0003  * For more info, see https://gitlab.cern.ch/mrieger/CMSSW-DNN.
0004  *
0005  * Author: Marcel Rieger
0006  */
0007 
0008 #include <stdexcept>
0009 #include <cppunit/extensions/HelperMacros.h>
0010 
0011 #include "PhysicsTools/TensorFlow/interface/TensorFlow.h"
0012 
0013 #include "testBase.h"
0014 
0015 class testConstSession : public testBase {
0016   CPPUNIT_TEST_SUITE(testConstSession);
0017   CPPUNIT_TEST(test);
0018   CPPUNIT_TEST_SUITE_END();
0019 
0020 public:
0021   std::string pyScript() const override;
0022   void test() override;
0023 };
0024 
0025 CPPUNIT_TEST_SUITE_REGISTRATION(testConstSession);
0026 
0027 std::string testConstSession::pyScript() const { return "createconstantgraph.py"; }
0028 
0029 void testConstSession::test() {
0030   std::string pbFile = dataPath_ + "/constantgraph.pb";
0031 
0032   std::cout << "Testing CPU backend" << std::endl;
0033   tensorflow::Backend backend = tensorflow::Backend::cpu;
0034 
0035   // load the graph
0036   tensorflow::Options options{backend};
0037   tensorflow::GraphDef* graphDef = tensorflow::loadGraphDef(pbFile);
0038   CPPUNIT_ASSERT(graphDef != nullptr);
0039 
0040   // create a new session and add the graphDef
0041   const tensorflow::Session* session = tensorflow::createSession(graphDef, options);
0042   CPPUNIT_ASSERT(session != nullptr);
0043 
0044   // example evaluation
0045   tensorflow::Tensor input(tensorflow::DT_FLOAT, {1, 10});
0046   float* d = input.flat<float>().data();
0047   for (size_t i = 0; i < 10; i++, d++) {
0048     *d = float(i);
0049   }
0050   tensorflow::Tensor scale(tensorflow::DT_FLOAT, {});
0051   scale.scalar<float>()() = 1.0;
0052   std::vector<tensorflow::Tensor> outputs;
0053 
0054   // run using the convenience helper
0055   outputs.clear();
0056   tensorflow::run(session, {{"input", input}, {"scale", scale}}, {"output"}, &outputs);
0057   CPPUNIT_ASSERT(outputs.size() == 1);
0058   std::cout << outputs[0].DebugString() << std::endl;
0059   CPPUNIT_ASSERT(outputs[0].matrix<float>()(0, 0) == 46.);
0060 
0061   // check for exception
0062   CPPUNIT_ASSERT_THROW(tensorflow::run(session, {{"foo", input}}, {"output"}, &outputs), cms::Exception);
0063 
0064   // cleanup
0065   CPPUNIT_ASSERT(tensorflow::closeSession(session));
0066   CPPUNIT_ASSERT(session == nullptr);
0067   delete graphDef;
0068 }