tensorflow / tensorflow/probability

Variational conv layers divergence not applied in tf.function

Open
#883 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

layers
Dominant language
Jupyter Notebook
Stars
4.4k
Forks
1.1k
PR merge metrics
No merged PRs in 30d

Description

For some reason, _ConvolutionVariational uses a boolean flag to avoid calling _apply_divergence again when evaluating the call function. Unfortunately, this breaks the layer when being used inside of tf.function. The change of state causes function retracing and the KL-divergence terms no longer appear in model.losses. Note that this is not a problem with _DenseVariational layers because no such flag is applied.

Simple example:

optim = tf.keras.optimizers.Adam()
@tf.function
def train_batch(x, y, kl_weight=tf.constant(0.01)):
    logits = model(x)
    print(model.losses)
    print(x.shape, y.shape)
    nll = tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=logits)
    kl = tf.math.add_n(model.losses)
    loss = nll + kl_weight*kl
    grads = tf.gradients(loss, model.trainable_variables)
    optim.apply_gradients(zip(grads, model.trainable_variables))
    return nll, kl

model can be any Keras Model with a variational conv layer.

This should be a simple fix. We just need to remove the flag and call _apply_divergence unconditionally in call.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in tensorflow_probability/python/layers/conv_variational.py at _ConvolutionVariational and compare its divergence handling with tensorflow_probability/python/layers/dense_variational.py. Reproduce the supplied example with a variational convolution layer inside tf.function, then verify that KL-divergence terms remain present in model.losses without retracing-related loss changes.

Written by the indexing model from the issue text.

Assessment

Tech stack
keras, python, tensorflow
Domain
machine-learning
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.