Back to home page

Project CMSSW displayed by LXR

 
 

    


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

0001 /*
0002  * Tests visible device interface 
0003  * For more info,
0004  * https://github.com/tensorflow/tensorflow/blob/3bc73f5e2ac437b1d9d559751af789c8c965a7f9/tensorflow/core/framework/device_attributes.proto
0005  * https://stackoverflow.com/questions/74110853/how-to-check-if-tensorflow-is-using-the-cpu-with-the-c-api\
0006  *
0007  * Author: Davide Valsecchi
0008  */
0009 
0010 #include <stdexcept>
0011 #include <cppunit/extensions/HelperMacros.h>
0012 
0013 #include "PhysicsTools/TensorFlow/interface/TensorFlow.h"
0014 #include "tensorflow/core/framework/device_attributes.pb.h"
0015 
0016 #include "testBase.h"
0017 
0018 class testVisibleDevices : public testBase {
0019   CPPUNIT_TEST_SUITE(testVisibleDevices);
0020   CPPUNIT_TEST(test);
0021   CPPUNIT_TEST_SUITE_END();
0022 
0023 public:
0024   std::string pyScript() const override;
0025   void test() override;
0026 };
0027 
0028 CPPUNIT_TEST_SUITE_REGISTRATION(testVisibleDevices);
0029 
0030 std::string testVisibleDevices::pyScript() const { return "createconstantgraph.py"; }
0031 
0032 void testVisibleDevices::test() {
0033   std::string pbFile = dataPath_ + "/constantgraph.pb";
0034   tensorflow::Backend backend = tensorflow::Backend::cpu;
0035   tensorflow::Options options{backend};
0036 
0037   // load the graph
0038   tensorflow::GraphDef* graphDef = tensorflow::loadGraphDef(pbFile);
0039   CPPUNIT_ASSERT(graphDef != nullptr);
0040 
0041   // create a new session and add the graphDef
0042   tensorflow::Session* session = tensorflow::createSession(graphDef, options);
0043   CPPUNIT_ASSERT(session != nullptr);
0044 
0045   // check for exception
0046   CPPUNIT_ASSERT_THROW(tensorflow::createSession(nullptr, options), cms::Exception);
0047 
0048   std::vector<tensorflow::DeviceAttributes> response;
0049   tensorflow::Status status = session->ListDevices(&response);
0050   CPPUNIT_ASSERT(status.ok());
0051 
0052   // If a single device is found, we assume that it's the CPU.
0053   // You can check that name if you want to make sure that this is the case
0054   std::cout << "Available devices: " << response.size() << std::endl;
0055   CPPUNIT_ASSERT(response.size() == 1);
0056 
0057   for (unsigned int i = 0; i < response.size(); ++i) {
0058     std::cout << i << " " << response[i].name() << " type: " << response[i].device_type() << std::endl;
0059   }
0060 
0061   // cleanup
0062   CPPUNIT_ASSERT(tensorflow::closeSession(session));
0063   CPPUNIT_ASSERT(session == nullptr);
0064   delete graphDef;
0065 }