tensorflow icon indicating copy to clipboard operation
tensorflow copied to clipboard

Inconsistent behavior for tf.variable_scope

Open nasimrahaman opened this issue 9 years ago • 17 comments

Problem:

Tensorflow doesn't place ops (e.g. mul) in pre-existing variable scopes (and automatically creates a new scope instead).

Minimal Reproducible Example

with tf.variable_scope('layer123'):
    v = tf.get_variable('v', [], initializer=tf.constant_initializer(42., tf.float32))
    w = v * 2
print(w.name)    # Prints 'layer123/mul:0'

However,

with tf.variable_scope('layer123'):
    v = tf.get_variable('v', [], initializer=tf.constant_initializer(42., tf.float32))

with tf.variable_scope('layer123'):
    w = v * 2

print(w.name)    # Prints 'layer123_1/mul:0'

Observe that for the latter, the op w is placed in a different variable scope, auto-named layer123_1.

I've tried the following, to the same effect:

with tf.variable_scope('layer123') as scope:
    v = tf.get_variable('v', [], initializer=tf.constant_initializer(42., tf.float32))

with tf.variable_scope(scope):
    w = v * 2

print(w.name)    # Prints 'layer123_1/mul:0'
with tf.variable_scope('layer123'):
    v = tf.get_variable('v', [], initializer=tf.constant_initializer(42., tf.float32))

with tf.variable_scope('layer123', reuse=True):
    w = v * 2

print(w.name)    # Prints 'layer123_1/mul:0'

VersionSpec

Tensorflow version: 0.11.0 (GPU) OS: Ubuntu 14.04 (w/ CUDA 8)

nasimrahaman avatar Dec 08 '16 10:12 nasimrahaman

Sorry about this confusion. Your third example at least seems to contradict the variable_scope documentation: "When opening a variable scope using a captured object instead of a string, we do not alter the current name scope for ops."

@ebrevdo can you give some guidance?

michaelisard avatar Dec 08 '16 18:12 michaelisard

No problem! But if this is purely a documentation issue, I'd really appreciate any pointers to a workaround (i.e. to guarantee that w.name == 'layer123/mul'). Thank you!

nasimrahaman avatar Dec 08 '16 18:12 nasimrahaman

I think that tf.name_scope is the right thing to use for naming ops rather than variables, but since I know this has changed over time I defer to @ebrevdo for a definitive answer.

michaelisard avatar Dec 08 '16 18:12 michaelisard

I believe variable and name scopes are exclusive. variable_scope and name_scope change their own scope hierarchies independently.

On Thu, Dec 8, 2016 at 10:27 AM, Michael Isard [email protected] wrote:

I think that tf.name_scope https://www.tensorflow.org/versions/r0.12/api_docs/python/framework.html#name_scope is the right thing to use for naming ops rather than variables, but since I know this has changed over time I defer to @ebrevdo https://github.com/ebrevdo for a definitive answer.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/tensorflow/tensorflow/issues/6189#issuecomment-265815454, or mute the thread https://github.com/notifications/unsubscribe-auth/ABtim3asKUKZVRqv6gHwD_W-xGm8dl6Pks5rGEv5gaJpZM4LHrZ6 .

ebrevdo avatar Dec 08 '16 18:12 ebrevdo

I ran another test (on @michaelisard 's advice):

with tf.name_scope('layer123') as scope:
    v = tf.Variable(3., name='v')
    
with tf.name_scope('layer123'):
    w = v * 2

print(w.name)    # still prints 'layer123_1/mul:0'

Replacing the first name_scope with variable_scope and Variable with get_variable did not change anything. However, I've found this works:

with tf.name_scope('layer123') as scope:
    v = tf.Variable(3., name='v')

with tf.name_scope(scope):
    w = v * 2

print(w.name)    # prints 'layer123/mul:0' like it should

This is quite unsatisfactory, for obvious reasons (e.g. get_variable functionality is rendered useless, encapsulation is broken, etc.).

nasimrahaman avatar Dec 08 '16 18:12 nasimrahaman

w is not a variable, it's a Tensor. w.name gives the Tensor's name, but v.name returns the variable's name as you would see in the checkpoint.

independently, you can do:

with variable_scope(...) as varscope: create_variables

with variable_scope(varscope, reuse=True): reuse variables via get_variable

On Thu, Dec 8, 2016 at 10:45 AM, Nasim Rahaman [email protected] wrote:

I ran another test (on @michaelisard https://github.com/michaelisard 's advice):

with tf.name_scope('layer123') as scope: v = tf.Variable(3., name='v') with tf.name_scope('layer123'): w = v * 2 print(w.name) # still prints 'layer123_1/mul:0'

Replacing the first name_scope with variable_scope and Variable with get_variable did not change anything. However, I've found this works:

with tf.name_scope('layer123') as scope: v = tf.Variable(3., name='v') with tf.name_scope(scope): w = v * 2 print(w.name) # prints 'layer123/mul:0' like it should

This is quite unsatisfactory, for obvious reasons (e.g. get_variable functionality is rendered useless, etc.).

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/tensorflow/tensorflow/issues/6189#issuecomment-265820123, or mute the thread https://github.com/notifications/unsubscribe-auth/ABtimxopoVQzOCx_S29w4DO_llkqZJMnks5rGFBQgaJpZM4LHrZ6 .

ebrevdo avatar Dec 08 '16 19:12 ebrevdo

@ebrevdo I understand that w is a Tensor resulting from the mul op, and that it's not possible to access it via something like tf.get_variable('mul'). I just need the mul op to reside in the same "name-group" as the variable v (such that w.name == layer123/mul:0), for prettier Tensorboard visualization. Certainly, this is possible when w is defined immediately after v without exiting the first variable_scope, as shown in the very first example. I was looking for a way for this to work after I had once exited the first variable_scope.

Also, I've tried the following, which also doesn't work:

with tf.variable_scope('layer123') as varscope:
    v = tf.get_variable('v', [], initializer=tf.constant_initializer(3., tf.float32))

with tf.variable_scope(varscope, reuse=True):
    w = v * 2

print(w.name)    # Prints 'layer123_1/mul:0'

EDIT/CLARIFICATION: I understand that your reply:

w is not a variable, it's a Tensor. w.name gives the Tensor's name, but v.name returns the variable's name as you would see in the checkpoint.

was a reply to my statement:

This is quite unsatisfactory, for obvious reasons (e.g. get_variable functionality is rendered useless, encapsulation is broken, etc.).

I was referring to having to use tf.name_scope instead of tf.variable_scope to have consistent naming behaviour, because the former is ignored by tf.get_variable. :)

nasimrahaman avatar Dec 08 '16 20:12 nasimrahaman

Here's a use-case for re-opening variable scopes without renaming. Consider a OOP design where a class declares a couple of TensorFlow variables and then provides multiple methods on those variables.

class Foo(object):
    def __init__(self):
        self.x = tf.get_variable('x', [], initializer=tf.constant(0.0))

    def meth(self, foo):
        z = tf.multiply(foo, 3.14, name='z')
        self.x.assign(z)

The easiest to visualize (in TensorBoard) pattern would to be have one variable scope per instance of class and call of method.

f0 = Foo()      # Foo/__init__/x
f1 = Foo()      # Foo_1/__init__/x
f0.meth(1.0)    # Foo/meth/*
f0.meth(2.0)    # Foo/meth_1/*
f1.meth(3.0)    # Foo_1/meth/*

The way that I thought of to implement this is to create a VariableScope on each instance, and then reopen it for each method call before creating another variable scope for the method. The reopening of the variable scope for each method call without changing the naming is currently not possible, so this scheme doesn't work.

eamartin avatar Feb 20 '17 02:02 eamartin

Thanks @ppwwyyxx . The main issue here that @nasimrahaman and I are looking for is the naming. Additionally, there's no need for the variable scope just to access the variables as the variables themselves could be saved on the instance (no get_variable call).

For my previous example, the suggested scheme would currently give the names:

f0 = Foo()      # Foo/__init__/x
f1 = Foo()      # Foo_1/__init__/x
f0.meth(1.0)    # Foo_2/meth/*
f0.meth(2.0)    # Foo_3/meth/*
f1.meth(3.0)    # Foo_4/meth/*

which doesn't help at all with distinguishing calls to different instances of Foo.

eamartin avatar Feb 20 '17 03:02 eamartin

@eamartin My bad earlier. I just found you can do something like this: (from #6007)

class Foo(object):
    def __init__(self):
        with tf.variable_scope(None, 'Foo'):
            self.sc = tf.get_variable_scope()
            self.x = tf.get_variable('x', initializer=0.0)
            print(self.x)

    def meth(self, foo):
        with tf.name_scope(self.sc.original_name_scope):
            z = tf.multiply(foo, 3.14, name='z')
            print(z)

f0 = Foo()      # Foo/x
f1 = Foo()      # Foo_1/x
f0.meth(1.0)    # Foo/z
f0.meth(2.0)    # Foo/z_1
f1.meth(3.0)    # Foo_1/z

Maybe this will help?

ppwwyyxx avatar Feb 20 '17 03:02 ppwwyyxx

Thanks @ppwwyyxx , this works for my OOP use-case. I wasn't aware of original_name_scope, this could use some docs!

One tricky case with this pattern: If you want to re-open the scope and create new variables, how do you give the appropriate names to the created ops in the re-opened scope? Here's the workaround:

First attempt:

import tensorflow as tf

with tf.variable_scope('foo') as scope:
    x = tf.get_variable('x', initializer=1.0)
    x2 = tf.multiply(x, 2, name='x2')

with tf.variable_scope(scope):
    y = tf.get_variable('y', initializer=2.0)
    y2 = tf.multiply(y, 2, name='y2')

print(x, x2, y, y2)

outputs Tensor("foo/x/read:0", shape=(), dtype=float32) Tensor("foo/x2:0", shape=(), dtype=float32) Tensor("foo/y/read:0", shape=(), dtype=float32) Tensor("foo_1/y2:0", shape=(), dtype=float32). This is wrong for foo_1/y2.

Next (ugly approach): Add a with tf.name_scope(scope.original_name_scope): block inside of the with tf.variable_scope(scope): block. This leads to correct output Tensor("foo/x/read:0", shape=(), dtype=float32) Tensor("foo/x2:0", shape=(), dtype=float32) Tensor("foo/y/read:0", shape=(), dtype=float32) Tensor("foo/y2:0", shape=(), dtype=float32)

eamartin avatar Feb 20 '17 04:02 eamartin

@eamartin Yes that's a bit tricky. I hope tensorflow can change the default behavior, i.e. when you reenter a variable scope, you should expect to automatically reenter its name scope as well instead of creating a new one.

ppwwyyxx avatar Feb 20 '17 04:02 ppwwyyxx

Hi everyone. I am having this problem too. Is there any method to have a consistent variable scope name and the variable names now? I am worry about that Foo/x and Foo_1/x are two independent variables (please correct me if I am wrong). Thank you.

weitliu avatar May 12 '17 05:05 weitliu

It has been 14 days with no activity and this issue has an assignee.Please update the label and/or status accordingly.

tensorflowbutler avatar Dec 20 '17 19:12 tensorflowbutler

https://github.com/tensorflow/tensorflow/pull/14390 now supports opening a variable scope without a new name scope already. I think this issue is resolved.

ppwwyyxx avatar Dec 20 '17 19:12 ppwwyyxx

Great!

ebrevdo avatar Dec 21 '17 07:12 ebrevdo

Hi @ebrevdo @ppwwyyxx @michaelisard , I think I am facing a similar problem but not sure about it. My TensorFlow version is 1.2.1.

I am trying to finetune resnet_50 from tensorflow.slim package on my own data.

To have the training and validation cycles together I use,

        with slim.arg_scope(resnet_arg_scope()):
            self.network_logits,_     = resnet_v1_50(inputs=inputs) 
            self.network_logits_val,_ = resnet_v1_50(inputs=inputs, reuse=True, is_training=False) ## Define a new function for testing but reuse the same model variables

Note, that my intension is to reuse the variables in the trained model for validation. However, on my TensorBoard I get two seperate resnet_50_v1 and resnet_50_v1_1 blocks.

 full graph

However, when I zoomed in to the block resnet_50_v1_1 (The block used in the validation cycle), I only see a set of operators(i.e. all the variables are passed from resnet_50_v1).

zoomed_1_1

This is how a similar block looks inside the resnet_50_v1 (The block used in the training cycle),

train zoomed cropped

I think this sperate blocks appear due to the discussed name_scope issue . If that is the case is my code technically safe? To me this is just a problem of easthetic appearance on tensorboard. Please correct me if I am wrong.

Could you please help me clarify why I am getting two distinct blocks resnet_50_v1 and resnet_50_v1_1? Is my code technically safe from what it appears? Thanks in Advance!

studentSam0000 avatar Jan 10 '18 02:01 studentSam0000