Skip to content

Commit a722cdf

Browse files
committed
Fix loss computation bug in Model training/eval methods with eager execution enabled.
Fixes tensorflow#18642. PiperOrigin-RevId: 193423288
1 parent d4c31b5 commit a722cdf

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

tensorflow/python/keras/_impl/keras/engine/training_eager.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ def _model_loss(model, inputs, targets, sample_weights=None, training=False):
150150
weighted_masked_fn = training_utils.weighted_masked_objective(loss_fn)
151151
with backend.name_scope(model.output_names[i] + '_loss'):
152152
output_loss = weighted_masked_fn(
153-
outs[i], targets[i], weights, mask=mask)
153+
targets[i], outs[i], weights, mask=mask)
154154
loss_metrics.append(backend.mean(output_loss))
155155

156156
loss_weight = model.loss_weights_list[i]

tensorflow/python/keras/_impl/keras/engine/training_eager_test.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import numpy as np
2222

2323
from tensorflow.python.framework import ops
24+
from tensorflow.python.framework import test_util as tf_test_util
2425
from tensorflow.python.keras._impl import keras
2526
from tensorflow.python.keras._impl.keras import testing_utils
2627
from tensorflow.python.platform import test
@@ -625,6 +626,30 @@ def test_class_weight_invalid_use_case(self):
625626
model.fit(x_np, [y_np, y_np], epochs=1, sample_weight={'1': bad_w_np})
626627

627628

629+
class CorrectnessTest(test.TestCase):
630+
631+
@tf_test_util.run_in_graph_and_eager_modes()
632+
def test_loss_correctness(self):
633+
# Test that training loss is the same in eager and graph
634+
# (by comparing it to a reference value in a deterministic case)
635+
model = keras.Sequential()
636+
model.add(keras.layers.Dense(3,
637+
activation='relu',
638+
input_dim=4,
639+
kernel_initializer='ones'))
640+
model.add(keras.layers.Dense(2,
641+
activation='softmax',
642+
kernel_initializer='ones'))
643+
model.compile(loss='sparse_categorical_crossentropy',
644+
optimizer=RMSPropOptimizer(learning_rate=0.001))
645+
x = np.ones((100, 4))
646+
np.random.seed(123)
647+
y = np.random.randint(0, 1, size=(100, 1))
648+
history = model.fit(x, y, epochs=1, batch_size=10)
649+
self.assertEqual(
650+
np.around(history.history['loss'][-1], decimals=4), 0.6173)
651+
652+
628653
if __name__ == '__main__':
629654
ops.enable_eager_execution()
630655
test.main()

0 commit comments

Comments
 (0)