<p dir="auto">I recently ran into a problem, while using bazel to build a project.  This project is compiled as a dynamic linking library, using PyImport_Import to import python module. when there is "import tensorflow as tf" in the python file , application who calls the dynamic linking library crashed everytime, but when it‘s not there ,everything works just fine. where is the problem?<br>
my tensorflow version is 1.0.0,python 2.7.0,bazel 0.4.3</p>
<p dir="auto">here is the console information when the application crashes:</p>
<blockquote>
<p dir="auto">F tensorflow/core/framework/function.cc:1015] Check failed: GetOpGradFactory()-&gt;insert({op, func}).second Duplicated gradient for Softmax</p>
</blockquote>
<p dir="auto">here is the test python file looks like:<br>
`from <strong>future</strong> import print_function<br>
import tensorflow as tf<br>
import os<br>
import time<br>
from itertools import izip<br>
import numpy as np<br>
import wrapt<br>
import cv2<br>
def get_int( ):<br>
a = 10<br>
b = 20<br>
return a + b</p>
<p dir="auto">def get_str( s1, s2 ):<br>
#return s1 + s2<br>
#return 'Hello , TY'<br>
return ('Hello, World', 10, 20)`</p>
<p dir="auto">here is the source code of .so file:<br>
<code class="notranslate">   Py_Initialize(); if ( !Py_IsInitialized() ) { return -1; } PyEval_InitThreads(); PyThreadState *mainThreadState = NULL; //  save a pointer to the main PyThreadState object  mainThreadState = PyThreadState_Get(); //  release the lock  PyEval_ReleaseLock(); char* mockargv[1]={(char*)""}; PySys_SetArgv(1,mockargv); PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); pName_ = PyString_FromString("test_py"); displayPyObject(pName_); if(pName_ == NULL){ return -1; } pModule_ = PyImport_Import(pName_); displayPyObject(pModule_);</code></p>
<p dir="auto">and here is the dynamic linking library part of my BUILD file<br>
<code class="notranslate">cc_binary( name = "test.so", linkshared = 1, deps = [ ":test_lib", ], ) cc_library( name = "test_lib", visibility = ["//visibility:__subpackages__"], srcs = glob(["test.cpp" ], ), includes=["test.h"], linkopts = [ "-lm -lpthread -L/usr/lib/python2.7 -lpython2.7 -lopencv_core -lopencv_imgproc -lopencv_highgui -lopencv_ml -lfreeimage" ], deps = [ "//tensorflow/cc:cc_ops", "//tensorflow/core:framework", "//tensorflow/core:framework_internal", "//tensorflow/core:tensorflow", ], ) </code></p>
<p dir="auto">I can't find a way to pass a numpy tensor to layers.convolution2d weights/bias initialization arguments.<br>
I added support for this by modifying convolution2d, code is below. I need this feature in order  If you like this solution I can add this feature to other ops also and create a pull request.</p>
<p dir="auto">First I tried this:</p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="import tensorflow as tf
import tensorflow.contrib.layers as layers
import numpy as np

conv1_1 = np.random.rand(3, 3, 3, 64).astype(dtype=np.float32)
inputs = tf.placeholder(tf.float32, shape=(32, 96, 96, 3))
net = layers.convolution2d(inputs, 64, 3, weights_initializer=conv1_1, scope='conv1_1')"><pre class="notranslate"><code class="notranslate">import tensorflow as tf
import tensorflow.contrib.layers as layers
import numpy as np

conv1_1 = np.random.rand(3, 3, 3, 64).astype(dtype=np.float32)
inputs = tf.placeholder(tf.float32, shape=(32, 96, 96, 3))
net = layers.convolution2d(inputs, 64, 3, weights_initializer=conv1_1, scope='conv1_1')
</code></pre></div>
<p dir="auto">but get_variable method doesn't allow redundant shape argument when initializing from constant.</p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="Traceback (most recent call last):
  File &quot;tf1.py&quot;, line 16, in &lt;module&gt;
    net = layers.convolution2d(inputs, 64, 3, weights_initializer=conv1_1, scope='conv1_1')
  File &quot;/usr/lib/python3.5/site-packages/tensorflow/contrib/framework/python/ops/arg_scope.py&quot;, line 171, in func_with_args
    return func(*args, **current_args)
  File &quot;/usr/lib/python3.5/site-packages/tensorflow/contrib/layers/python/layers/layers.py&quot;, line 406, in convolution2d
    trainable=trainable)
  File &quot;/usr/lib/python3.5/site-packages/tensorflow/contrib/framework/python/ops/arg_scope.py&quot;, line 171, in func_with_args
    return func(*args, **current_args)
  File &quot;/usr/lib/python3.5/site-packages/tensorflow/contrib/framework/python/ops/variables.py&quot;, line 266, in model_variable
    caching_device=caching_device, device=device)
  File &quot;/usr/lib/python3.5/site-packages/tensorflow/contrib/framework/python/ops/arg_scope.py&quot;, line 171, in func_with_args
    return func(*args, **current_args)
  File &quot;/usr/lib/python3.5/site-packages/tensorflow/contrib/framework/python/ops/variables.py&quot;, line 230, in variable
    caching_device=caching_device)
  File &quot;/usr/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py&quot;, line 873, in get_variable
    custom_getter=custom_getter)
  File &quot;/usr/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py&quot;, line 700, in get_variable
    custom_getter=custom_getter)
  File &quot;/usr/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py&quot;, line 217, in get_variable
    validate_shape=validate_shape)
  File &quot;/usr/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py&quot;, line 202, in _true_getter
    caching_device=caching_device, validate_shape=validate_shape)
  File &quot;/usr/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py&quot;, line 479, in _get_single_variable
    raise ValueError(&quot;If initializer is a constant, do not specify shape.&quot;)
ValueError: If initializer is a constant, do not specify shape."><pre class="notranslate"><code class="notranslate">Traceback (most recent call last):
  File "tf1.py", line 16, in &lt;module&gt;
    net = layers.convolution2d(inputs, 64, 3, weights_initializer=conv1_1, scope='conv1_1')
  File "/usr/lib/python3.5/site-packages/tensorflow/contrib/framework/python/ops/arg_scope.py", line 171, in func_with_args
    return func(*args, **current_args)
  File "/usr/lib/python3.5/site-packages/tensorflow/contrib/layers/python/layers/layers.py", line 406, in convolution2d
    trainable=trainable)
  File "/usr/lib/python3.5/site-packages/tensorflow/contrib/framework/python/ops/arg_scope.py", line 171, in func_with_args
    return func(*args, **current_args)
  File "/usr/lib/python3.5/site-packages/tensorflow/contrib/framework/python/ops/variables.py", line 266, in model_variable
    caching_device=caching_device, device=device)
  File "/usr/lib/python3.5/site-packages/tensorflow/contrib/framework/python/ops/arg_scope.py", line 171, in func_with_args
    return func(*args, **current_args)
  File "/usr/lib/python3.5/site-packages/tensorflow/contrib/framework/python/ops/variables.py", line 230, in variable
    caching_device=caching_device)
  File "/usr/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 873, in get_variable
    custom_getter=custom_getter)
  File "/usr/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 700, in get_variable
    custom_getter=custom_getter)
  File "/usr/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 217, in get_variable
    validate_shape=validate_shape)
  File "/usr/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 202, in _true_getter
    caching_device=caching_device, validate_shape=validate_shape)
  File "/usr/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 479, in _get_single_variable
    raise ValueError("If initializer is a constant, do not specify shape.")
ValueError: If initializer is a constant, do not specify shape.
</code></pre></div>
<p dir="auto">I removed redundant arguments but then convolution2d doesn't have default value for them.</p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="net = layers.convolution2d(inputs, weights_initializer=conv1_1, scope='conv1_1')"><pre class="notranslate"><code class="notranslate">net = layers.convolution2d(inputs, weights_initializer=conv1_1, scope='conv1_1')
</code></pre></div>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="Traceback (most recent call last):
  File &quot;tf1.py&quot;, line 14, in &lt;module&gt;
    net = layers.convolution2d(inputs, weights_initializer=conv1_1, scope='conv1_1')
  File &quot;/usr/lib/python3.5/site-packages/tensorflow/contrib/framework/python/ops/arg_scope.py&quot;, line 171, in func_with_args
    return func(*args, **current_args)
TypeError: convolution2d() missing 2 required positional arguments: 'num_outputs' and 'kernel_size'"><pre class="notranslate"><code class="notranslate">Traceback (most recent call last):
  File "tf1.py", line 14, in &lt;module&gt;
    net = layers.convolution2d(inputs, weights_initializer=conv1_1, scope='conv1_1')
  File "/usr/lib/python3.5/site-packages/tensorflow/contrib/framework/python/ops/arg_scope.py", line 171, in func_with_args
    return func(*args, **current_args)
TypeError: convolution2d() missing 2 required positional arguments: 'num_outputs' and 'kernel_size'
</code></pre></div>
<p dir="auto">I fixed the problem by adding support inside convolution2d code here:<br>
<a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/layers/python/layers/layers.py#L322">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/layers/python/layers/layers.py#L322</a><br>
It works now and I don't have to pass redundant arguments.</p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="@add_arg_scope
def convolution2d(inputs,
                  num_outputs=None,
                  kernel_size=None,
                  stride=1,
                  padding='SAME',
                  rate=1,
                  activation_fn=nn.relu,
                  normalizer_fn=None,
                  normalizer_params=None,
                  weights_initializer=initializers.xavier_initializer(),
                  weights_regularizer=None,
                  biases_initializer=init_ops.zeros_initializer,
                  biases_regularizer=None,
                  reuse=None,
                  variables_collections=None,
                  outputs_collections=None,
                  trainable=True,
                  scope=None):
  with variable_scope.variable_op_scope([inputs],
                                        scope, 'Conv', reuse=reuse) as sc:
    inputs = ops.convert_to_tensor(inputs)
    dtype = inputs.dtype.base_dtype
    stride_h, stride_w = utils.two_element_tuple(stride)
    if rate &gt; 1 and (stride_h &gt; 1 or stride_w &gt; 1):
      raise ValueError('Only one of rate or stride can be larger than one')
    num_filters_in = utils.last_dimension(inputs.get_shape(), min_rank=4)

    initializing_from_value = False
    if weights_initializer is not None and not callable(weights_initializer):
      initializing_from_value = True
      weights_shape = None
    else:
      if kernel_size == None or num_outputs == None:
        raise ValueError('Kernel size and number of outputs must be defined')
      kernel_h, kernel_w = utils.two_element_tuple(kernel_size)
      weights_shape = [kernel_h, kernel_w,
                       num_filters_in, num_outputs]
    if biases_initializer is not None and not callable(biases_initializer):
      bias_shape = None
    else:
      if num_outputs == None:
        raise ValueError('Number of outputs must be defined')
      bias_shape = [num_outputs]

    weights_collections = utils.get_variable_collections(
        variables_collections, 'weights')
    weights = variables.model_variable('weights',
                                       shape=weights_shape,
                                       dtype=dtype,
                                       initializer=weights_initializer,
                                       regularizer=weights_regularizer,
                                       collections=weights_collections,
                                       trainable=trainable)
    if rate &gt; 1:
      outputs = nn.atrous_conv2d(inputs, weights, rate, padding=padding)
    else:
      outputs = nn.conv2d(inputs, weights, [1, stride_h, stride_w, 1],
                          padding=padding)
    if normalizer_fn:
      normalizer_params = normalizer_params or {}
      outputs = normalizer_fn(outputs, **normalizer_params)
    else:
      if biases_initializer is not None:
        biases_collections = utils.get_variable_collections(
            variables_collections, 'biases')
        biases = variables.model_variable('biases',
                                          shape=bias_shape,
                                          dtype=dtype,
                                          initializer=biases_initializer,
                                          regularizer=biases_regularizer,
                                          collections=biases_collections,
                                          trainable=trainable)
        outputs = nn.bias_add(outputs, biases)
    if activation_fn:
      outputs = activation_fn(outputs)
    return utils.collect_named_outputs(outputs_collections, sc.name, outputs)"><pre class="notranslate"><code class="notranslate">@add_arg_scope
def convolution2d(inputs,
                  num_outputs=None,
                  kernel_size=None,
                  stride=1,
                  padding='SAME',
                  rate=1,
                  activation_fn=nn.relu,
                  normalizer_fn=None,
                  normalizer_params=None,
                  weights_initializer=initializers.xavier_initializer(),
                  weights_regularizer=None,
                  biases_initializer=init_ops.zeros_initializer,
                  biases_regularizer=None,
                  reuse=None,
                  variables_collections=None,
                  outputs_collections=None,
                  trainable=True,
                  scope=None):
  with variable_scope.variable_op_scope([inputs],
                                        scope, 'Conv', reuse=reuse) as sc:
    inputs = ops.convert_to_tensor(inputs)
    dtype = inputs.dtype.base_dtype
    stride_h, stride_w = utils.two_element_tuple(stride)
    if rate &gt; 1 and (stride_h &gt; 1 or stride_w &gt; 1):
      raise ValueError('Only one of rate or stride can be larger than one')
    num_filters_in = utils.last_dimension(inputs.get_shape(), min_rank=4)

    initializing_from_value = False
    if weights_initializer is not None and not callable(weights_initializer):
      initializing_from_value = True
      weights_shape = None
    else:
      if kernel_size == None or num_outputs == None:
        raise ValueError('Kernel size and number of outputs must be defined')
      kernel_h, kernel_w = utils.two_element_tuple(kernel_size)
      weights_shape = [kernel_h, kernel_w,
                       num_filters_in, num_outputs]
    if biases_initializer is not None and not callable(biases_initializer):
      bias_shape = None
    else:
      if num_outputs == None:
        raise ValueError('Number of outputs must be defined')
      bias_shape = [num_outputs]

    weights_collections = utils.get_variable_collections(
        variables_collections, 'weights')
    weights = variables.model_variable('weights',
                                       shape=weights_shape,
                                       dtype=dtype,
                                       initializer=weights_initializer,
                                       regularizer=weights_regularizer,
                                       collections=weights_collections,
                                       trainable=trainable)
    if rate &gt; 1:
      outputs = nn.atrous_conv2d(inputs, weights, rate, padding=padding)
    else:
      outputs = nn.conv2d(inputs, weights, [1, stride_h, stride_w, 1],
                          padding=padding)
    if normalizer_fn:
      normalizer_params = normalizer_params or {}
      outputs = normalizer_fn(outputs, **normalizer_params)
    else:
      if biases_initializer is not None:
        biases_collections = utils.get_variable_collections(
            variables_collections, 'biases')
        biases = variables.model_variable('biases',
                                          shape=bias_shape,
                                          dtype=dtype,
                                          initializer=biases_initializer,
                                          regularizer=biases_regularizer,
                                          collections=biases_collections,
                                          trainable=trainable)
        outputs = nn.bias_add(outputs, biases)
    if activation_fn:
      outputs = activation_fn(outputs)
    return utils.collect_named_outputs(outputs_collections, sc.name, outputs)
</code></pre></div>