Saturday, October 1, 2016

How to build and test new Op in TensorFlow

I would think install TensorFlow from source code would be a benefit. However if one didn't do so, how can one build and test the new Op in TensorFlow?

For building the Op just with binary installed, just write a simple Makefile in the directory where source code resides, and put the following content into it:

TF_INC=$(shell python -c "from tensorflow import sysconfig; print(sysconfig.get_include())")
all:
g++ -std=c++11 -shared foo_bar.cc -o foo_bar.so -fPIC -I ${TF_INC} -D_GLIBCXX_USE_CXX11_ABI=0


For testing, just write the following Python script:

import tensorflow as tf
import unittest

def test():

    class FooBarTest(unittest.TestCase):
        def testFooBar(self):
            foo_bar_module = tf.load_op_library('/directory/to/foo_bar.so')
            with tf.Session():
                result = foo_bar_module.foo_bar([1, 2, 3])
                self.assertListEqual(result.eval().tolist(), [1, 2, 3])
    suite = unittest.TestSuite()
    for test_name in ['testFooBar']:
        suite.addTest(FooBarTest(test_name))
    unittest.TextTestRunner(verbosity = 2).run(suite)

if __name__ == '__main__':
    test()
    

Enjoy the hacking!

No comments:

Post a Comment