import tensorflow as tf
operations = [
tf.keras.layers.Dense(64, activation='sigmoid'),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(64, activation=None),
]
def call(x):
# Sample 2 of the 3 operations.
sampled_ids = tf.random.categorical(
tf.zeros((1, len(operations))), num_samples=2, dtype=tf.int32,
)[0]
# Compute their output given x.
op_results_eager = tf.stack([operations[op_id](x) for op_id in sampled_ids])
# Try to replicate op_results_eager in graph_mode without evaluating all operations!
op_result_functs = [lambda: op(x) for op in operations]
op_results_graph = tf.stack([tf.switch_case(branch_index=op_id, branch_fns=op_result_functs) for op_id in sampled_ids])
tf.print(tf.reduce_all(tf.equal(op_results_eager, op_results_graph)))
return op_results_graph
for _ in range(1000):
call(tf.ones(shape=(1, 5)))
I need the same result as in op_results_eager but with statements that allow wrapping call() as tf.function while still evaluating only the sampled operations.
As you can see, I tried to build the indexing as a switch case, but that doesn't even give the right result in eager execution.