I just asked a question on the same topic but for custom models (How do I find the derivative of a custom model in Keras?) but realised quickly that this was trying to run befor
I ended up getting this to work with a variant of the answer to this question: Get Gradients with Keras Tensorflow 2.0
x_tensor = tf.convert_to_tensor(input_data, dtype=tf.float32)
with tf.GradientTape() as t:
t.watch(x_tensor)
output = model(x_tensor)
result = output
gradients = t.gradient(output, x_tensor)
This allows me to obtain both the output and the gradient without redundant computation.