0

The following code will not produce "Fizz" when the value of i is a multiple of 3:

@tf.function
def fizzbuzz(n):
  msg = tf.constant('')
  for i in tf.range(n):
    if int(i % 3) == 0:
      msg += 'Fizz'
    elif tf.equal(i % 5, 0):
      msg += 'Buzz'
    else:
      msg += tf.as_string(i)
    msg += '\n'
  return msg

print(fizzbuzz(tf.constant(15)).numpy().decode())

But if one comments the @tf.function decorator out, it works normally for multiples of 3. How come?

soloice
  • 980
  • 8
  • 17

1 Answers1

0

Following fix worked for me: Use a combination of tf.mod and tf.equal instead of % and ==.

I encountered this problem some days ago and I am not sure, if it's a bug or desired behaviour.

@tf.function
def fizzbuzz(n):
    msg = tf.constant('')
    for i in tf.range(n):
        if tf.equal(tf.mod(i, 3), 0):
            msg += 'Fizz'
        elif tf.equal(i % 5, 0):
            msg += 'Buzz'
        else:
            msg += tf.as_string(i)
        msg += '\n'
    return msg
print(fizzbuzz(tf.constant(15)).numpy().decode())
# Output
#Fizz
#1
#2
#Fizz
#4
#Buzz
#Fizz
#7
#8
#Fizz
#Buzz
#11
#Fizz
#13
#14
Sparky05
  • 4,692
  • 1
  • 10
  • 27
  • Actually, you don't need `tf.mod`: `tf.equal(i % 3, 0)` will work. I'm just wondering if this is a bug. – soloice Apr 28 '19 at 03:17
  • I don't think that it is the desired behaviour and you may want to fill an issue on GitHub: https://github.com/tensorflow/tensorflow/issues to ask the developers – Sparky05 Apr 29 '19 at 07:25