Openspiel+Bazel+Tensorflow build failure
Hello,
I tried to use Bazel to build Openspiel. It succeeds. But when I tried to use Bazel to build Openspiel in a Tensorflow folder, it failed.
I put open_spiel folder in Tensorflow folder. I used Tensorflow's WORKSPACE. It gives following errors(seemed that compiling passed, while linking failed with errors on absl). I tried removing .bazelrc file in Tensorflow source folder, and Bazel build passed again. Could anyone help? Thanks a lot.
Environment: WSL Ubuntu 18.04; Openspiel latest version; Bazel 1.2.1; Tensorflow: using source codes; Python 3.6.
Linking of rule '//tensorflow/open_spiel/games:go_test' failed (Exit 1)
bazel-out/k8-opt/bin/tensorflow/open_spiel/tests/_objs/basic_tests/basic_tests.o:basic_tests.cc:function std::__cxx11::basic_string<char, std::char_traits
Best regards, Lancelot
Hi @lancelot-ch ,
Yes I think this is being cause by a recent bug in abseil. We got around it by fixing the checkout to a specific commit number for now, so if you pull from master (+ get rid of the abseil-cpp directory that install.sh clones, rerun install.sh) then I think you'll be fine.
There is also a very quick fix to a single file in abseil that you can apply and also abseil should be fixed by tomorrow. For details, see: https://github.com/abseil/abseil-cpp/issues/640
Thanks, @lanctot !
I tried the fix, and the problem isn't solved yet. I felt that could be the cause, given that I downloaded Abseil-cpp on March 9. However, even if I delete that and switched to the March 7 version Abseil-cpp as you suggested, the problem is still there.
One thought is that, I am using Bazel to build, so the change of a Cmake file might not help. Also, I remembered that I encountered this problem during previous build and by using below command I can circumvent this issue.
bazel build --copt=-std=c++17 open_spiel/games/go_test
Therefore the current problem might be induced by Tensorflow? Since it also drags in another version of Abseil? I am confused.
Good point, agreed: it cannot be due to a change in CMake files in your case.
But I guess it must be related because those are the exact same errors I was getting (but in different files).
Thanks, @lanctot !
I tried the fix, and the problem isn't solved yet. I felt that could be the cause, given that I downloaded Abseil-cpp on March 9. However, even if I delete that and switched to the March 7 version Abseil-cpp as you suggested, the problem is still there.
One thought is that, I am using Bazel to build, so the change of a Cmake file might not help. Also, I remembered that I encountered this problem Therefore the current problem might be induced by Tensorflow? Since it also drags in another version of Abseil? I am confused.
Might be.
I will point the team to this issue, maybe someone will have an idea.
You could also try following up on the abseil-cpp thread, they responded pretty quickly and they might have an idea (even if it may not be directly related to absl).
When you say you put open_spiel in a TensorFlow folder, what exactly do you mean?
I think the problem is likely that you are accidentally doing a mixed-mode compile somehow. I think TensorFlow by default uses C++14 and it looks like open_spiel uses C++17. Linking will fail in this case because absl::string_view is its own backport type in C++14, but becomes std::string_view in C++17. The differing ABI is probably what is causing this not to link.
This is probably the single most common issue that trips people up. https://github.com/abseil/abseil-cpp/blob/master/FAQ.md#how-to-i-set-the-c-dialect-used-to-build-abseil https://github.com/abseil/abseil-cpp/blob/master/FAQ.md#what-is-abi-and-why-dont-you-recommend-using-a-pre-compiled-version-of-abseil
Thanks, @lanctot @derekmauro
By "put open_spiel in a TensorFlow folder", I mean I cloned Tensorflow souce codes, and put open_spiel in the souce code folder like "tensorflow/tensorflow/open_speil/spiel.cc" etc. I kept Tensorflow root folder WORKSPACE file. I cloned Abseil-cpp to open_spiel folder, like "tensorflow/tensorflow/open_spiel/Abseil-cpp". I used "bazel build --copt=-std=c++17 open_spiel/games/go_test" to build.
My goal is to use Openspiel for a C++ program for AlphaZero selp-play computation. With network inference, I am thinking of using Tensorflow C++ API, which has to be built from source codes, which leads to current situation.
Meanwhile, I will tweak with ABI options and see if I can work around this issue. If there are other options to achieve my goal, please let me know.
Thanks.
I'll also point you to https://abseil.io/blog/201901115-options and https://github.com/abseil/abseil-cpp/blob/master/absl/base/options.h. You should be able to make this work with a little tweaking.
Thanks a lot, @derekmauro . I will give it a try.
I am not sure if I can handle it well though. Tensorflow will pull in an older version of Abseil as well. I might also work with that also. Besides, Tensorflow default with C++14 and OpenSpiel requires C++17. I had not expected such a difficult senario...
@lanctot @lancelot-ch Thanks for this thread, it saves my day. I have been using gcc/9.2.0 to compile and the abseil issue was gone after pulling the master head again.
Thanks a lot, @derekmauro . I will give it a try.
I am not sure if I can handle it well though. Tensorflow will pull in an older version of Abseil as well. I might also work with that also. Besides, Tensorflow default with C++14 and OpenSpiel requires C++17. I had not expected such a difficult senario...
We are about to release some code in the next few weeks that would require TF inference (note, btw in contrib/ we have some code there already; it's not supported but works internally).
We might spend a bit of effort trying to see how to get this to work because it would be nice to support the TF-compiled code. It's unfortunately not high priority, but we can at least try. I agree the C++14 / C++17 mix is awkward.
One option is to go back down to C++14 until TF allows C++17 (I'm not sure how many C++17 features we truly rely on); this would require some work on our part, probably not much. But, it feels like the wrong direction. We will soon need to support TF 2.2 because Ubuntu comes with Python 3.8 ( see https://github.com/deepmind/open_spiel/issues/166 for details ), and it would be really nice if TF 2.2 supported C++17, because then we would not have to mix C++ standards and would not have to go back to an old standard just to support compiling with TF.
Thanks, @lanctot . I didn't notice there is already a TF example. I will read it through. On a quick study, I feel I am also on a similar route. With the link you recommended in the example note, I also read it. It mentions either go with Bazel or link to a TF API in .so file.
I took the first path with Bazel and programmed below codes following codes and instructions from other links with some revisions. Meanwhile the TF inference in C++ works, but I cannot get it work when combined with TF, which induces this thread's question.
I also tried with the second path to link to a compiled TF .so file. But I know little about this linking thing so I failed several times. Probably I need to wait when Openspiel develops more progress.
With the methods Derek suggested earlier, I am still playing with it. Every time I changed the settings of Abseil option.h, I have to compile the whole TF again. It takes a very long time to try every possible solution. So far I still cannot get it. It seems that I always can only satisfy one of Openspiel or TF inference.
Bazel+TF inference solution example:
hello.cc #include "memory" #include "vector" #include "string" #include "unordered_set" #include "iostream"
#include "tensorflow/core/public/session.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/cc/saved_model/loader.h" #include "tensorflow/cc/saved_model/tag_constants.h"
//using std; using tensorflow::Tensor; using tensorflow::TensorShape; using tensorflow::Status; using tensorflow::Session; using tensorflow::SavedModelBundle; using tensorflow::SessionOptions; using tensorflow::RunOptions;
int main(void) { const std::string export_dir = "./tensorflow/test6/model"; SavedModelBundle bundle; SessionOptions session_options; RunOptions run_options;
// Load model from SavedModel Status status = tensorflow::LoadSavedModel(session_options, run_options, export_dir, {tensorflow::kSavedModelTagServe}, &bundle); if (!status.ok()) { std::cout << "Failed to load saved model" << std::endl; std::cout << status.ToString() << std::endl; return -1; }
Tensor input(tensorflow::DT_FLOAT, tensorflow::TensorShape({1,2,2,2})); input.tensor<float, 4>()(0,0,0,0) = 1; input.tensor<float, 4>()(0,0,0,1) = 2; input.tensor<float, 4>()(0,0,1,0) = 3; input.tensor<float, 4>()(0,0,1,1) = 4; input.tensor<float, 4>()(0,1,0,0) = 5; input.tensor<float, 4>()(0,1,0,1) = 6; input.tensor<float, 4>()(0,1,1,0) = 7; input.tensor<float, 4>()(0,1,1,1) = 8; //vectortensorflow::Tensor outputs; //string output_node = "output";
// Prediction
std::vector
return 0; }
BUILD
load("//tensorflow:tensorflow.bzl", "tf_cc_binary")
package( default_visibility = ["//tensorflow:internal"], licenses = ["notice"], # Apache 2.0 )
tf_cc_binary( name = "Hello", srcs = [ "hello.cc", ],
deps = select({
"//conditions:default": [
"//tensorflow/cc:cc_ops",
"//tensorflow/core:core_cpu",
"//tensorflow/core:framework",
"//tensorflow/core:framework_internal",
"//tensorflow/core:lib",
"//tensorflow/core:protos_all_cc",
"//tensorflow/core:tensorflow",
"//tensorflow/cc/saved_model:tag_constants",
"//tensorflow/cc/saved_model:loader",
],
}),
)
train.py import numpy as np import tensorflow.compat.v1 as tf tf.disable_eager_execution()
board_height=2 board_width=2 train = np.array([[[[1,1],[2,2]],[[3,3],[4,4]]]], dtype='float32') x = tf.placeholder( tf.float32, shape=[None, 2, 2, 2],name='input') input_state = tf.transpose(x, [0, 2, 3, 1])
conv1 = tf.layers.conv2d(inputs=input_state, filters=32, kernel_size=[3, 3], padding="same", data_format="channels_last", activation=tf.nn.relu) conv2 = tf.layers.conv2d(inputs=conv1, filters=64, kernel_size=[3, 3], padding="same", data_format="channels_last", activation=tf.nn.relu) conv3 = tf.layers.conv2d(inputs=conv2, filters=128, kernel_size=[3, 3], padding="same", data_format="channels_last", activation=tf.nn.relu)
action_conv = tf.layers.conv2d(inputs=conv3, filters=4, kernel_size=[1, 1], padding="same", data_format="channels_last", activation=tf.nn.relu)
action_conv_flat = tf.reshape( action_conv, [-1, 2 * board_height * board_width])
prediction = tf.layers.dense(inputs=action_conv_flat, units=board_height * board_width, activation=tf.nn.log_softmax,name="output") evaluation_conv = tf.layers.conv2d(inputs=conv3, filters=2, kernel_size=[1, 1], padding="same", data_format="channels_last", activation=tf.nn.relu) evaluation_conv_flat = tf.reshape( evaluation_conv, [-1, 2 * board_height * board_width]) evaluation_fc1 = tf.layers.dense(inputs=evaluation_conv_flat, units=64, activation=tf.nn.relu)
evaluation_fc2 = tf.layers.dense(inputs=evaluation_fc1, units=1, activation=tf.nn.tanh,name="value") for tensor in tf.get_default_graph().get_operations(): print (tensor.name)
test_data = np.array([[[[1,2],[3,4]],[[5,6],[7,8]]]], dtype='float32') test_label = test_data
with tf.Session() as sess: sess.run(tf.global_variables_initializer())
results = sess.run([prediction, evaluation_fc2], feed_dict={ x: test_data })
print(results)
# Save model
inputs_dict = {
"x": x
}
outputs_dict = {
"output/LogSoftmax": prediction, "value/Tanh":evaluation_fc2
}
tf.saved_model.simple_save(sess, './model', inputs_dict, outputs_dict)
I also tried with the second path to link to a compiled TF .so file. But I know little about this linking thing so I failed several times. Probably I need to wait when Openspiel develops more progress.
Interesting, I didn't realize this was an option. Can you point me to any places you found on how to do this or where you found out about it? If we could get it to work without having to compile TF from scratch, I'd far prefer that option. I wonder if the pip packages come with everything you need, though (we would need the headers in addition to the .so).
After a few quick searches and I found that TF actually has a CMake build: https://github.com/tensorflow/tensorflow/tree/9590c4c32dd4346ea5c35673336f5912c6072bf2/tensorflow/contrib/cmake . This is great, it might make it easier to integrate with OpenSpiel. I'll keep you posted if look at this further and make any progress.
@lanctot At Openspiel tf_trajectories.h file's note link, https://tebesu.github.io/posts/Training-a-TensorFlow-graph-in-C++-API, it says "There are two ways to compile this: one is bazel and the other is linking against the tensorflow library. I prefer the latter."
https://stackoverflow.com/questions/42898577/list-of-headers-to-use-tensorflow-c-api-using-libtensorflow-cc-so
The above link mentioned how to link to libtensorflow_cc.so file. But I just cannot reproduce it on my system. While I still think this is a promising way to avoid having to unify TF and Openspiel's source codes' compiler. It seems to be such an elegant solution, that we can use a Tensorflow C++ API, just like Tensorflow Python API and Tensofrflow C API from TF.
@lanctot And please also refer to the following two links. One uses Bazel while another uses Cmake. There are some parts I cannot fully follow so I am still studying them.
https://github.com/FloopCZ/tensorflow_cc
https://github.com/bitbionic/keras-to-tensorflow
Quick heads-up that I've been playing around with tensorflow_cc; for now just trying to get it to compile with TF2.2 and Ubuntu 20.04 (we need to change OpenSpiel to support these soon so I'm taking the opportunity to try it in this environment).
I've run into some trouble:
- https://github.com/FloopCZ/tensorflow_cc/issues/216
- https://github.com/FloopCZ/tensorflow_cc/issues/218
It's great that TF can be compiled with CMake.. it would make supporting compiling with it externally within OpenSpiel a lot easier.
Ok, I've managed to compile Tensorflow via CMake using tensorflow_cc (and a very new version as well, TF2.2rc2 on Ubuntu 20.04!) Thanks for pointing us out to that @lancelot-ch , seems like a great project.
This is the first step to getting OpenSpiel + TF compiling externally together. I can't promise any time lines, but it means we're just a few steps from getting them to work together.
@lanctot Thanks for your wonderful contribution. I tried a few times but with no luck. Recently I am occupied with some other work, but I will be eager to be looking forward to your new milestones!
Hi,
I was able to build latest commit (4300bc4fafa0ef43d2f707fe5cdea120f0be3ecb) with Tensorflow v1.15.2 (via TensorflowCC and Bazel 0.26.1) on my macOS Catalina (Apple Clang 11.0.3). I had to modify some cmake files and rename some #include statements. Please see the diff here.
However, I'm getting the following error from vpnet_test (ctest --verbose -R vpnet_test):
20: dyld: lazy symbol binding failed: Symbol not found: __ZN10open_spiel10algorithms14CreateGraphDefERKNS_4GameEddRKNSt3__112basic_stringIcNS4_11char_traitsIcEENS4_9allocatorIcEEEESC_SA_iib
20: Referenced from: ~/open_spiel/build/algorithms/alpha_zero/vpnet_test
20: Expected in: flat namespace
20:
20: dyld: Symbol not found: __ZN10open_spiel10algorithms14CreateGraphDefERKNS_4GameEddRKNSt3__112basic_stringIcNS4_11char_traitsIcEENS4_9allocatorIcEEEESC_SA_iib
20: Referenced from: ~/open_spiel/build/algorithms/alpha_zero/vpnet_test
20: Expected in: flat namespace
20:
1/1 Test #20: vpnet_test .......................Child aborted***Exception: 1.06 sec
Do you have any ideas?
I also tried on an Ubuntu 18.04 machine with clang version 6.0.0-1ubuntu2. This time, the build failed with following errors:
CMakeFiles/vpnet_test.dir/vpnet_test.cc.o: In function `open_spiel::algorithms::(anonymous namespace)::BuildModel(open_spiel::Game const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool)':
vpnet_test.cc:(.text+0x90a): undefined reference to `open_spiel::algorithms::CreateGraphDef(open_spiel::Game const&, double, double, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, int, bool)'
vpnet_test.cc:(.text+0xa9d): undefined reference to `open_spiel::algorithms::VPNetModel::VPNetModel(open_spiel::Game const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
CMakeFiles/vpnet_test.dir/vpnet_test.cc.o: In function `open_spiel::algorithms::(anonymous namespace)::TestModelCreation(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)':
vpnet_test.cc:(.text+0xddf): undefined reference to `open_spiel::algorithms::VPNetModel::Inference(std::vector<open_spiel::algorithms::VPNetModel::InferenceInputs, std::allocator<open_spiel::algorithms::VPNetModel::InferenceInputs> > const&)'
vpnet_test.cc:(.text+0xf5e): undefined reference to `open_spiel::algorithms::VPNetModel::Learn(std::vector<open_spiel::algorithms::VPNetModel::TrainInputs, std::allocator<open_spiel::algorithms::VPNetModel::TrainInputs> > const&)'
CMakeFiles/vpnet_test.dir/vpnet_test.cc.o: In function `open_spiel::algorithms::(anonymous namespace)::TestModelLearnsSimple(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)':
vpnet_test.cc:(.text+0x14d7): undefined reference to `open_spiel::algorithms::VPNetModel::Inference(std::vector<open_spiel::algorithms::VPNetModel::InferenceInputs, std::allocator<open_spiel::algorithms::VPNetModel::InferenceInputs> > const&)'
vpnet_test.cc:(.text+0x17a2): undefined reference to `open_spiel::algorithms::VPNetModel::Learn(std::vector<open_spiel::algorithms::VPNetModel::TrainInputs, std::allocator<open_spiel::algorithms::VPNetModel::TrainInputs> > const&)'
CMakeFiles/vpnet_test.dir/vpnet_test.cc.o: In function `open_spiel::algorithms::(anonymous namespace)::TestModelLearnsOptimal(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::vector<open_spiel::algorithms::VPNetModel::TrainInputs, std::allocator<open_spiel::algorithms::VPNetModel::TrainInputs> > const&)':
vpnet_test.cc:(.text+0x21bf): undefined reference to `open_spiel::algorithms::VPNetModel::Learn(std::vector<open_spiel::algorithms::VPNetModel::TrainInputs, std::allocator<open_spiel::algorithms::VPNetModel::TrainInputs> > const&)'
collect2: error: ld returned 1 exit status
algorithms/alpha_zero/CMakeFiles/vpnet_test.dir/build.make:393: recipe for target 'algorithms/alpha_zero/vpnet_test' failed
make[2]: *** [algorithms/alpha_zero/vpnet_test] Error 1
CMakeFiles/Makefile2:4606: recipe for target 'algorithms/alpha_zero/CMakeFiles/vpnet_test.dir/all' failed
P.S: The TensorflowCC (Tensorflow v1.15.2) is working without problem in both environments.