distribute_strategy_test.py 84.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
15
"""Tests for tf.keras models using tf.distribute.Strategy."""
16 17 18 19
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

20
from absl.testing import parameterized
21 22
import numpy as np
from tensorflow.python import keras
23
from tensorflow.python.data.experimental.ops import cardinality
24
from tensorflow.python.data.ops import dataset_ops
25
from tensorflow.python.distribute import combinations
26
from tensorflow.python.distribute import distribution_strategy_context
27
from tensorflow.python.distribute import mirrored_strategy
28
from tensorflow.python.distribute import parameter_server_strategy
29
from tensorflow.python.distribute import reduce_util
30 31
from tensorflow.python.distribute import strategy_combinations
from tensorflow.python.distribute import tpu_strategy
32
from tensorflow.python.eager import backprop
33
from tensorflow.python.eager import context
34
from tensorflow.python.eager import def_function
35
from tensorflow.python.framework import sparse_tensor
36
from tensorflow.python.keras import testing_utils
37
from tensorflow.python.keras.distribute import distributed_training_utils
38 39
from tensorflow.python.keras.engine import base_layer_utils
from tensorflow.python.keras.mixed_precision.experimental import policy
40
from tensorflow.python.keras.optimizer_v2 import gradient_descent as gradient_descent_keras
41
from tensorflow.python.keras.utils import np_utils
42
from tensorflow.python.ops import array_ops
43
from tensorflow.python.ops import check_ops
44
from tensorflow.python.ops import math_ops
45
from tensorflow.python.ops import nn
46
from tensorflow.python.ops import variables
47
from tensorflow.python.ops.losses import loss_reduction
48
from tensorflow.python.ops.ragged import ragged_tensor
49
from tensorflow.python.platform import test
50
from tensorflow.python.training import gradient_descent
51
from tensorflow.python.training import rmsprop
52
from tensorflow.python.util import nest
53 54 55 56 57 58

_RANDOM_SEED = 1337
_TRAIN_SIZE = 200
_INPUT_SIZE = (10,)
_NUM_CLASS = 2

59 60 61
# Note: Please make sure the tests in this file are also covered in
# keras_backward_compat_test for features that are supported with both APIs.

62 63
# TODO(anjalisridhar): Add a decorator that will allow us to run these tests as
# part of the tf.keras unit tests suite.
64 65


66 67 68 69 70 71 72 73
def simple_sequential_model():
  model = keras.models.Sequential()
  model.add(keras.layers.Dense(16, activation='relu', input_shape=_INPUT_SIZE))
  model.add(keras.layers.Dropout(0.1))
  model.add(keras.layers.Dense(_NUM_CLASS, activation='softmax'))
  return model


74 75 76 77 78 79 80 81 82 83 84 85 86 87
def simple_subclassed_model(num_labels=_NUM_CLASS):

  class _SimpleMLP(keras.Model):

    def __init__(self, num_labels):
      super(_SimpleMLP, self).__init__()
      self.dense = keras.layers.Dense(num_labels)

    def call(self, inputs):
      return self.dense(inputs)

  return _SimpleMLP(num_labels)


88 89 90 91 92 93 94 95 96 97 98 99
def simple_multi_inputs_multi_outputs_model():
  input_a = keras.layers.Input(shape=(16,), name='input_a')
  input_b = keras.layers.Input(shape=(16,), name='input_b')

  merged = keras.layers.concatenate([input_a, input_b], name='merge')
  output_c = keras.layers.Dense(3, activation='softmax', name='dense_2')(merged)
  output_d = keras.layers.Dense(2, activation='softmax', name='dense_3')(merged)
  model = keras.models.Model(
      inputs=[input_a, input_b], outputs=[output_c, output_d])
  return model


100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
def get_multi_inputs_multi_outputs_data():
  (a_train, c_train), (a_test, c_test) = testing_utils.get_test_data(
      train_samples=_TRAIN_SIZE,
      test_samples=50,
      input_shape=(16,),
      num_classes=3,
      random_seed=_RANDOM_SEED)
  (b_train, d_train), (b_test, d_test) = testing_utils.get_test_data(
      train_samples=_TRAIN_SIZE,
      test_samples=50,
      input_shape=(16,),
      num_classes=2,
      random_seed=_RANDOM_SEED)
  (m_train, _), (m_test, _) = testing_utils.get_test_data(
      train_samples=_TRAIN_SIZE,
      test_samples=50,
      input_shape=(8,),
      num_classes=2,
      random_seed=_RANDOM_SEED)

120 121 122 123
  c_train = np_utils.to_categorical(c_train)
  c_test = np_utils.to_categorical(c_test)
  d_train = np_utils.to_categorical(d_train)
  d_test = np_utils.to_categorical(d_test)
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142

  train_data = {
      'input_a': a_train,
      'input_b': b_train,
      'input_m': m_train,
      'output_c': c_train,
      'output_d': d_train
  }
  test_data = {
      'input_a': a_test,
      'input_b': b_test,
      'input_m': m_test,
      'output_c': c_test,
      'output_d': d_test
  }

  return (train_data, test_data)


143 144 145
def batch_wrapper(dataset, batch_size, distribution, repeat=None):
  if repeat:
    dataset = dataset.repeat(repeat)
146 147
  # TPUs currently require fully defined input shapes, drop_remainder ensures
  # the input will have fully defined shapes.
148 149
  if isinstance(distribution,
                (tpu_strategy.TPUStrategy, tpu_strategy.TPUStrategyV1)):
150 151 152 153 154
    return dataset.batch(batch_size, drop_remainder=True)
  else:
    return dataset.batch(batch_size)


155 156 157 158 159 160 161
def get_model():
  x = keras.layers.Input(shape=(3,), name='input')
  y = keras.layers.Dense(4, name='dense')(x)
  model = keras.Model(x, y)
  return model


162 163 164
def get_sample_weights_model():
  x = keras.layers.Input(shape=(1,), name='input')
  y = keras.layers.Dense(
165 166
      1, kernel_initializer='ones', bias_initializer='zeros', name='dense')(
          x)
167 168 169 170
  model = keras.Model(x, y)
  return model


171 172 173 174 175 176 177 178 179
def get_dataset(distribution):
  inputs = np.zeros((10, 3), dtype=np.float32)
  targets = np.zeros((10, 4), dtype=np.float32)
  dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))
  dataset = dataset.repeat(100)
  dataset = batch_wrapper(dataset, 10, distribution)
  return dataset


180 181 182 183 184 185 186 187
def get_predict_dataset(distribution):
  inputs = np.zeros((10, 3), dtype=np.float32)
  dataset = dataset_ops.Dataset.from_tensor_slices(inputs)
  dataset = dataset.repeat(100)
  dataset = batch_wrapper(dataset, 10, distribution)
  return dataset


188
def convert_numpy_to_dataset_with_unknown_cardinality(inputs, targets=None):
189 190 191 192 193 194 195
  if targets is not None:
    input_slices = (inputs, targets)
    dummy_op = (lambda inp, target: True)
  else:
    input_slices = inputs
    dummy_op = (lambda inp: True)

196 197 198
  original_dataset = (dataset_ops.Dataset.from_tensor_slices(input_slices))
  ds_with_unknown_cardinality = (
      original_dataset.filter(dummy_op).batch(10, drop_remainder=True))
199 200 201
  return ds_with_unknown_cardinality


202 203 204 205 206 207 208 209 210 211 212 213 214 215
def multi_input_output_model():
  a = keras.layers.Input(shape=(3,), name='input_a')
  b = keras.layers.Input(shape=(5,), name='input_b')
  # TODO(anjalisridhar): Change the output dimension of the second Dense layer
  # once the iterator output validation issue has been fixed.
  dense_1 = keras.layers.Dense(7, name='dense_1')
  dense_2 = keras.layers.Dense(7, name='dense_2')
  c = dense_1(a)
  d = dense_2(b)
  e = keras.layers.Dropout(0.5, name='dropout')(c)
  model = keras.models.Model([a, b], [d, e])
  return model


216 217 218 219
strategies_minus_default_minus_tpu = [
    strategy_combinations.one_device_strategy,
    strategy_combinations.one_device_strategy_gpu,
    strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
220 221
    strategy_combinations.mirrored_strategy_with_two_gpus,
    strategy_combinations.central_storage_strategy_with_gpu_and_cpu
222 223
]

224
strategies_minus_tpu = [
225 226 227 228
    strategy_combinations.default_strategy,
    strategy_combinations.one_device_strategy,
    strategy_combinations.one_device_strategy_gpu,
    strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
229 230
    strategy_combinations.mirrored_strategy_with_two_gpus,
    strategy_combinations.central_storage_strategy_with_gpu_and_cpu
231
]
232 233

tpu_strategies = [
234 235 236
    strategy_combinations.tpu_strategy,  # steps_per_run=2
    strategy_combinations.tpu_strategy_one_step
]
237 238


239
def strategy_minus_tpu_combinations():
240 241
  return combinations.combine(
      distribution=strategies_minus_tpu, mode=['graph', 'eager'])
242 243


244
def tpu_strategy_combinations():
245 246
  return combinations.combine(
      distribution=tpu_strategies, mode=['graph', 'eager'])
247 248 249


def tpu_strategy_combinations_graph_only():
250
  return combinations.combine(distribution=tpu_strategies, mode=['graph'])
251 252


253 254
def all_strategy_combinations():
  return strategy_minus_tpu_combinations() + tpu_strategy_combinations()
255 256


257 258 259
def all_strategy_combinations_plus_run_distributed():
  return (combinations.combine(
      distribution=strategies_minus_tpu,
260
      mode=['graph', 'eager']) + combinations.combine(
261
          distribution=tpu_strategies,
262
          mode=['graph', 'eager']))
263 264


265 266
def all_strategy_minus_default_and_tpu_combinations():
  return combinations.combine(
267
      distribution=[
268 269 270 271 272
          strategy_combinations.one_device_strategy,
          strategy_combinations.one_device_strategy_gpu,
          strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
          strategy_combinations.mirrored_strategy_with_two_gpus,
      ],
273
      mode=['graph', 'eager'])
274 275 276 277 278


def all_strategy_combinations_minus_default():
  return (all_strategy_minus_default_and_tpu_combinations() +
          tpu_strategy_combinations())
279 280


281
def strategy_and_optimizer_combinations():
282 283
  non_tpu_strategies = combinations.times(
      strategy_minus_tpu_combinations(),
284 285
      combinations.combine(
          optimizer=[
286 287 288 289
              strategy_combinations.adagrad_optimizer_v1_fn,
              strategy_combinations.adam_optimizer_v1_fn,
              strategy_combinations.gradient_descent_optimizer_v1_fn,
              strategy_combinations.rmsprop_optimizer_v1_fn,
290
              strategy_combinations.adadelta_optimizer_keras_v2_fn,
291 292
              strategy_combinations.adagrad_optimizer_keras_v2_fn,
              strategy_combinations.adam_optimizer_keras_v2_fn,
293
              strategy_combinations.adamax_optimizer_keras_v2_fn,
294
              strategy_combinations.gradient_descent_optimizer_keras_v2_fn,
295
              strategy_combinations.nadam_optimizer_keras_v2_fn,
296 297
              strategy_combinations.rmsprop_optimizer_keras_v2_fn,
              strategy_combinations.ftrl_optimizer_keras_v2_fn
298
          ]))
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
  tpu_strategies_graph = combinations.combine(
      distribution=tpu_strategies,
      mode=['graph'],
      optimizer=[
          strategy_combinations.adagrad_optimizer_v1_fn,
          strategy_combinations.adam_optimizer_v1_fn,
          strategy_combinations.gradient_descent_optimizer_v1_fn,
          strategy_combinations.rmsprop_optimizer_v1_fn,
          strategy_combinations.adagrad_optimizer_keras_v2_fn,
          strategy_combinations.adam_optimizer_keras_v2_fn,
          strategy_combinations.gradient_descent_optimizer_keras_v2_fn,
          strategy_combinations.rmsprop_optimizer_keras_v2_fn
      ])
  tpu_strategies_eager = combinations.combine(
      distribution=tpu_strategies,
      mode=['eager'],
      optimizer=[
          strategy_combinations.adagrad_optimizer_keras_v2_fn,
          strategy_combinations.adam_optimizer_keras_v2_fn,
          strategy_combinations.gradient_descent_optimizer_keras_v2_fn,
          strategy_combinations.rmsprop_optimizer_keras_v2_fn
      ])
  return non_tpu_strategies + tpu_strategies_eager + tpu_strategies_graph
322 323


324 325
class TestDistributionStrategyWithNumpyArrays(test.TestCase,
                                              parameterized.TestCase):
326

327
  @combinations.generate(all_strategy_combinations())
328 329 330 331 332 333 334
  def test_calculating_input_params_no_steps_no_batch_size(self, distribution):
    # Calculate the per_replica_batch_size scaling factor for strategies
    # that use per_core_batch_size
    replica_scale_factor = 1.0
    if not distributed_training_utils.global_batch_size_supported(distribution):
      replica_scale_factor = distribution.num_replicas_in_sync

335
    with self.cached_session():
336 337
      # Default global batch size 32 for input with 64 samples run in 2 steps
      steps, batch_size = distributed_training_utils.get_input_params(
338
          distribution, 64, steps=None, batch_size=None)
339 340 341 342 343
      self.assertEqual(batch_size, 32 // replica_scale_factor)
      self.assertEqual(steps, 2)

      # Computed global batch size 20 is lower than 32 if we pass less samples.
      steps, batch_size = distributed_training_utils.get_input_params(
344
          distribution, 20, steps=None, batch_size=None)
345 346 347
      self.assertEqual(batch_size, 20 // replica_scale_factor)
      self.assertEqual(steps, 1)

348
  @combinations.generate(all_strategy_combinations())
349 350
  def test_calculating_input_params_with_steps_no_batch_size(
      self, distribution):
351 352 353 354 355 356 357 358 359
    # Calculate the per_replica_batch_size scaling factor for strategies
    # that use per_core_batch_size
    replica_scale_factor = 1.0
    if not distributed_training_utils.global_batch_size_supported(distribution):
      replica_scale_factor = distribution.num_replicas_in_sync

    with self.cached_session():
      # Computed global batch size is correct for number of specified 1 step
      steps, batch_size = distributed_training_utils.get_input_params(
360
          distribution, 64, steps=1, batch_size=None)
361
      self.assertEqual(batch_size, 64 // replica_scale_factor)
362 363
      self.assertEqual(steps, 1)

364 365
      # Computed global batch size is correct for number of specified 2 steps
      steps, batch_size = distributed_training_utils.get_input_params(
366
          distribution, 64, steps=2, batch_size=None)
367
      self.assertEqual(batch_size, 32 // replica_scale_factor)
368 369
      self.assertEqual(steps, 2)

370 371 372
      # All samples can not be consumed in specified number of steps
      with self.assertRaisesRegexp(ValueError, 'not divisible by steps'):
        distributed_training_utils.get_input_params(
373
            distribution, 63, steps=2, batch_size=None)
374 375 376 377 378 379

      # This cases is different for different strategies due to the
      # difference in supported batch size being global or per-replica.
      if replica_scale_factor == 1:
        # Computed global batch size is correct even if not sharadable
        steps, batch_size = distributed_training_utils.get_input_params(
380
            distribution, 63, steps=3, batch_size=None)
381 382 383 384
        self.assertEqual(batch_size, 21)
        self.assertEqual(steps, 3)
      else:
        # Computed global batch size can not be sharded across replicas
385 386 387
        with self.assertRaisesRegexp(
            ValueError, 'could not be sharded evenly '
            'across the sync replicas'):
388
          distributed_training_utils.get_input_params(
389
              distribution, 63, steps=1, batch_size=None)
390

391
  @combinations.generate(all_strategy_combinations())
392 393
  def test_calculating_input_params_no_steps_with_batch_size(
      self, distribution):
394 395 396 397 398 399
    # Calculate the per_replica_batch_size scaling factor for strategies
    # that use per_core_batch_size
    replica_scale_factor = 1.0
    if not distributed_training_utils.global_batch_size_supported(distribution):
      replica_scale_factor = distribution.num_replicas_in_sync

400
    with self.cached_session():
401 402
      # Computed steps is correct for specified batch size
      steps, batch_size = distributed_training_utils.get_input_params(
403
          distribution, 64, steps=None, batch_size=16)
404 405 406 407 408
      self.assertEqual(batch_size, 16)
      self.assertEqual(steps, 4 // replica_scale_factor)

      # Computed steps is correct for specified batch size
      steps, batch_size = distributed_training_utils.get_input_params(
409
          distribution, 64, steps=None, batch_size=32)
410 411 412
      self.assertEqual(batch_size, 32)
      self.assertEqual(steps, 2 // replica_scale_factor)

413
  @combinations.generate(all_strategy_combinations())
414 415
  def test_calculating_input_params_with_steps_with_batch_size(
      self, distribution):
416 417 418
    with self.cached_session():
      # No change to steps and batch size if both specified and feasible
      steps, batch_size = distributed_training_utils.get_input_params(
419
          distribution, 64, steps=5, batch_size=3)
420 421 422 423 424 425
      self.assertEqual(batch_size, 3)
      self.assertEqual(steps, 5)

      # Number of samples is less than global batch size * steps
      with self.assertRaisesRegexp(ValueError, 'less than samples required'):
        distributed_training_utils.get_input_params(
426
            distribution, 64, steps=10, batch_size=13)
427

428
  @combinations.generate(all_strategy_combinations_plus_run_distributed())
429
  def test_calling_model_with_numpy_arrays(self, distribution):
430
    with self.cached_session():
431
      with distribution.scope():
432
        optimizer_fn = gradient_descent_keras.SGD
433
        optimizer = optimizer_fn(0.001)
434 435 436
        model = get_model()
        loss = 'mse'
        metrics = ['mae']
437
        model.compile(
438 439
            optimizer,
            loss,
440
            metrics=metrics)
441

442 443
        inputs = np.zeros((64, 3), dtype=np.float32)
        targets = np.zeros((64, 4), dtype=np.float32)
444

445
        # Call fit with validation data
446 447 448 449 450 451 452
        model.fit(
            inputs,
            targets,
            epochs=1,
            batch_size=2,
            verbose=0,
            validation_data=(inputs, targets))
453

454 455 456 457
        # TODO(anjalisridhar): We need tests for when the batch size and steps
        # are smaller and results in a 0 batch_size and steps value.
        model.evaluate(inputs, targets)
        model.evaluate(inputs, targets, batch_size=8)
458

459 460
        model.predict(inputs)
        model.predict(inputs, batch_size=8)
461

462
  @combinations.generate(all_strategy_combinations_plus_run_distributed())
463
  def test_calling_model_with_mixed_precision(self, distribution):
464 465 466
    if isinstance(distribution.extended,
                  parameter_server_strategy.ParameterServerStrategyExtended):
      self.skipTest('b/152097775')
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
    if isinstance(distribution,
                  (tpu_strategy.TPUStrategy, tpu_strategy.TPUStrategyV1)):
      policy_name = 'mixed_bfloat16'
    else:
      policy_name = 'mixed_float16'
    with self.cached_session(), \
         distribution.scope(), \
         policy.policy_scope(policy_name):
      optimizer_fn = gradient_descent_keras.SGD
      optimizer = optimizer_fn(0.001)
      x = keras.layers.Input(shape=(3,), name='input')
      y = keras.layers.Dense(4, name='dense')(x)
      y = keras.layers.Activation('softmax', dtype='float32')(y)
      model = keras.Model(x, y)
      loss = 'mse'
      metrics = ['mae']
      model.compile(
          optimizer,
          loss,
486
          metrics=metrics)
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507

      # We need to pass float32 since TPUs do not support float64, even though
      # these arrays will immediately be casted to bfloat16 on TPUs. We also
      # cannot pass bfloat16, as Numpy does not support it.
      inputs = np.zeros((64, 3), dtype='float32')
      targets = np.zeros((64, 4), dtype='float32')

      model.fit(
          inputs,
          targets,
          epochs=1,
          batch_size=2,
          verbose=0,
          validation_data=(inputs, targets))

      model.evaluate(inputs, targets)
      model.evaluate(inputs, targets, batch_size=8)

      model.predict(inputs)
      model.predict(inputs, batch_size=8)

508
  @combinations.generate(all_strategy_combinations_plus_run_distributed())
509
  def test_operator_overload_mixed_precision(self, distribution):
510 511 512 513
    # Regression test that tests a fixed bug does not reoccur. Adding an
    # AutoCastVariable to a tensor on a TPU, where the variable was the LHS of
    # the '+' operator, used to cause the gradient w.r.t. the variable to be
    # None.
514 515 516 517
    if isinstance(distribution.extended,
                  parameter_server_strategy.ParameterServerStrategyExtended):
      self.skipTest('b/152097775')

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
    if isinstance(distribution,
                  (tpu_strategy.TPUStrategy, tpu_strategy.TPUStrategyV1)):
      policy_name = 'mixed_bfloat16'
    else:
      policy_name = 'mixed_float16'

    class MyLayer(keras.layers.Layer):

      def build(self, _):
        self.v1 = self.add_weight('v', ())
        self.v2 = self.add_weight('v', ())

      def call(self, inp):
        inp += self.v1
        return self.v2 + inp

    with self.cached_session(), distribution.scope():
      layer = MyLayer(dtype=policy.Policy(policy_name))
      def run_fn():
        x = np.array([1.])
        with backprop.GradientTape() as tape:
          y = layer(x)
        grad_v1, grad_v2 = tape.gradient(y, [layer.v1, layer.v2])
        return grad_v1, grad_v2
542 543
      if context.executing_eagerly():
        run_fn = def_function.function(run_fn)
544 545

      grad_v1, grad_v2 = distribution.run(run_fn)
546 547 548
      self.assertIsNotNone(grad_v1)
      self.assertIsNotNone(grad_v2)

549 550 551 552 553
  @combinations.generate(
      combinations.combine(
          distribution=[strategy_combinations.one_device_strategy] +
          tpu_strategies,
          mode=['graph', 'eager']))
554 555 556 557 558 559 560 561 562 563
  def test_optimizer_in_cross_replica_context_raises_error(self, distribution):

    with self.cached_session(), distribution.scope():
      model = keras.models.Sequential([keras.layers.Dense(1)])
      x = np.array([[1.]])
      with backprop.GradientTape() as tape:
        y = model(x)
      gradients = tape.gradient(y, model.trainable_variables)
      optimizer = gradient_descent_keras.SGD()

564 565
      with self.assertRaisesRegex(RuntimeError,
                                  'cannot be called in cross-replica context'):
566 567
        optimizer.apply_gradients(zip(gradients, model.trainable_variables))

568
  @combinations.generate(all_strategy_combinations_plus_run_distributed())
569
  def test_calling_model_with_nested_numpy_arrays(self, distribution):
570
    with self.cached_session():
571
      with distribution.scope():
572
        optimizer_fn = gradient_descent_keras.SGD
573
        optimizer = optimizer_fn(learning_rate=0.001)
574 575
        model = multi_input_output_model()
        loss = 'mse'
576 577
        model.compile(
            optimizer,
578
            loss)
579 580

      input_a_np = np.asarray(np.random.random((64, 3)), dtype=np.float32)
581
      input_b_np = np.asarray(np.random.random((64, 5)), dtype=np.float32)
582 583
      inputs = [input_a_np, input_b_np]

584 585
      output_d_np = np.asarray(np.random.random((64, 7)), dtype=np.float32)
      output_e_np = np.asarray(np.random.random((64, 7)), dtype=np.float32)
586 587 588 589 590 591 592 593 594 595 596 597 598
      targets = [output_d_np, output_e_np]

      # Call fit with validation data
      model.fit(inputs, targets, epochs=1, batch_size=8, verbose=0)

      # TODO(anjalisridhar): We need tests for when the batch size and steps are
      # smaller and results in a 0 batch_size and steps value.
      model.evaluate(inputs, targets)
      model.evaluate(inputs, targets, batch_size=8)

      model.predict(inputs)
      model.predict(inputs, batch_size=8)

599
  @combinations.generate(
600 601
      combinations.combine(
          distribution=strategies_minus_tpu,
602 603
          mode=['graph', 'eager']))
  def test_numpy_with_sample_weights(self, distribution):
604 605 606 607
    with self.cached_session(), distribution.scope():
      model = get_sample_weights_model()
      optimizer = rmsprop.RMSPropOptimizer(learning_rate=0.001)
      loss = 'mse'
608 609
      model.compile(
          optimizer,
610
          loss)
611 612 613 614 615

      inputs = np.array([[0], [1], [2], [3]], np.float32)
      targets = np.array([[2], [4], [6], [8]], np.float32)
      sample_weights = np.array([0.25, 0.5, 0.75, 1], np.float32)

616 617 618 619 620 621
      result = model.evaluate(
          inputs,
          targets,
          batch_size=2,
          sample_weight=sample_weights,
          verbose=1)
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
      # The per sample loss is multipled by the corresponding sample weight. The
      # average of these weighted losses is the return value of the `evaluate`
      # call. For example, in the test above the average weighted loss is
      # calculated in the following manner:
      # batch_1 = (((2-0)^2) * 0.25 + ((4-1)^2) * 0.5) / 2 = 5.5 / 2 = 2.75
      # batch_2 = (((6-2)^2 * 0.75) + ((8-3)^2 * 1)) / 2 = 37 / 2 = 18.5
      # final result = (batch_1 + batch_2) / 2 = 10.625.
      # The first time we divide by number of input samples and the second time
      # we divide by number of steps/batches that the loss is aggregated over.
      self.assertAllClose(result, 10.625)

      # We now test without passing sample_weights:
      # batch_1 = ((2-0)^2) + ((4-1)^2) / 2 = 13 / 2 = 6.5
      # batch_2 = ((6-2)^2) + ((8-3)^2) / 2 = 41 / 2 = 20.5
      # final result = (batch_1 + batch_2) / 2 =  27 / 2 = 13.5
      result = model.evaluate(inputs, targets, batch_size=2, verbose=1)
      self.assertAllClose(result, 13.5)

640
  @combinations.generate(all_strategy_combinations_plus_run_distributed())
641
  def test_flatten_predict_outputs(self, distribution):
642
    with self.cached_session():
643 644
      with distribution.scope():
        model = multi_input_output_model()
645
        optimizer_fn = gradient_descent_keras.SGD
646
        optimizer = optimizer_fn(learning_rate=0.001)
647
        loss = 'mse'
648 649
        model.compile(
            optimizer,
650
            loss)
651 652 653 654 655 656

      # We take 6 input samples with each input having a dimension of 3 or 5.
      input_a_np = np.asarray(np.random.random((6, 3)), dtype=np.float32)
      input_b_np = np.asarray(np.random.random((6, 5)), dtype=np.float32)
      inputs = [input_a_np, input_b_np]

657
      outs = model.predict(inputs)
658 659 660
      # `predict` a list that is equal in length to the number of model outputs.
      # In this test our model has two outputs and each element of `outs`
      # corresponds to all the samples of one of the model outputs.
661
      self.assertLen(outs, 2)
662 663 664 665 666
      # Each of the output samples have a dimension of 7. We should process all
      # the available input samples(6).
      self.assertAllEqual([6, 7], outs[0].shape)
      self.assertAllEqual([6, 7], outs[1].shape)

667
  @combinations.generate(
668
      combinations.times(tpu_strategy_combinations_graph_only(),
669 670 671 672 673
                         combinations.combine(batch_size=[4, 6])))
  def test_evaluate_with_partial_batch(self, distribution, batch_size):
    with self.cached_session():
      optimizer = gradient_descent.GradientDescentOptimizer(0.001)
      loss = 'mse'
674
      metrics = ['mae', keras.metrics.CategoricalAccuracy()]
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709

      with distribution.scope():
        model_with_ds_strategy = get_model()
        model_with_ds_strategy.compile(optimizer, loss, metrics=metrics)

      cpu_model = get_model()
      cpu_model.compile(optimizer, loss, metrics=metrics)

      x = np.random.random((10, 3)).astype('float32')
      y = np.random.random((10, 4)).astype('float32')

      # As sample size is 10, we batch by 4 so that the last batch is
      # a partial batch. Also `evaluate()` using numpy array as inputs without
      # distribution strategy uses entire sample as a single batch. As so,
      # we remove parameters `batch_size` and `steps`.
      cpu_model.set_weights(model_with_ds_strategy.get_weights())
      evaluate_ground_truth = cpu_model.evaluate(x, y)

      # We don't compare the loss as loss is currently not computed as metric
      # in Keras, the loss value is inaccurate for last partial batch due to
      # more weights for the last batch samples.
      steps = np.ceil(10.0 / batch_size)
      self.assertAllClose(
          model_with_ds_strategy.evaluate(
              x, y, batch_size=batch_size, steps=steps)[1:],
          evaluate_ground_truth[1:],
          atol=1e-5,
          rtol=1e-5)
      # Test that `steps` is inferred correctly when final partial batch exists.
      self.assertAllClose(
          model_with_ds_strategy.evaluate(x, y, batch_size=batch_size)[1:],
          evaluate_ground_truth[1:],
          atol=1e-5,
          rtol=1e-5)

710
  @combinations.generate(
711
      combinations.times(
712 713
          tpu_strategy_combinations_graph_only()))
  def test_predict_with_partial_batch(self, distribution):
714 715 716 717 718 719
    with self.cached_session():
      optimizer = gradient_descent.GradientDescentOptimizer(0.001)
      loss = 'mse'

      with distribution.scope():
        model_with_ds_strategy = get_model()
720
        model_with_ds_strategy.compile(
721
            optimizer,
722
            loss)
723 724 725 726

      cpu_model = get_model()
      cpu_model.compile(optimizer, loss)

727
      inputs = np.random.random((10, 3)).astype(np.float32)
728 729

      # As sample size is 10, we batch by 4 so that the last batch is
730
      # a partial batch. Also `predict()` using numpy array as inputs without
731 732 733
      # distribution strategy uses entire sample as a single batch. As so,
      # we remove parameters `batch_size` and `steps`.
      cpu_model.set_weights(model_with_ds_strategy.get_weights())
734
      predict_ground_truth = cpu_model.predict(inputs)
735 736
      self.assertAllClose(
          model_with_ds_strategy.predict(inputs, batch_size=4, steps=3),
737 738 739 740 741 742 743 744 745
          predict_ground_truth,
          atol=1e-5,
          rtol=1e-5)
      # Test that `steps` is inferred correctly when final partial batch exists.
      self.assertAllClose(
          model_with_ds_strategy.predict(inputs, batch_size=4),
          predict_ground_truth,
          atol=1e-5,
          rtol=1e-5)
746

747
  @combinations.generate(tpu_strategy_combinations_graph_only())
748 749 750 751 752 753 754 755 756 757 758 759
  def test_no_target_model(self, distribution):
    with self.cached_session():
      optimizer = gradient_descent.GradientDescentOptimizer(0.001)

      class MyLayer(keras.layers.Layer):

        def call(self, inputs, training=None):
          self.add_loss(math_ops.reduce_sum(inputs), inputs=True)
          return inputs

      with distribution.scope():
        model = keras.models.Sequential()
760 761
        model.add(
            keras.layers.Dense(16, activation='relu', input_shape=_INPUT_SIZE))
762 763 764 765 766 767 768 769 770 771
        model.add(MyLayer())
        model.add(keras.layers.Dense(_NUM_CLASS, activation='softmax'))

        model.compile(optimizer)
        inputs = np.zeros((20, 10), np.float32)

        model.fit(inputs, epochs=1, steps_per_epoch=2)
        model.predict(inputs, steps=1)
        model.evaluate(inputs, steps=1)

772
  @combinations.generate(
773
      combinations.times(
774
          tpu_strategy_combinations_graph_only()))
775
  def test_predict_multi_output_model_with_partial_batch(
776
      self, distribution):
777 778 779 780 781 782
    with self.cached_session():
      optimizer = gradient_descent.GradientDescentOptimizer(0.001)
      loss = 'mse'

      with distribution.scope():
        model_with_ds_strategy = simple_multi_inputs_multi_outputs_model()
783
        model_with_ds_strategy.compile(
784
            optimizer,
785
            loss)
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803

      cpu_model = simple_multi_inputs_multi_outputs_model()
      cpu_model.compile(optimizer, loss)

      input_data, _ = get_multi_inputs_multi_outputs_data()
      input_dict = {
          'input_a': input_data['input_a'],
          'input_b': input_data['input_b'],
      }

      # As sample size is 200, we batch by 18 so that the last batch is
      # a partial batch. Also `fit()` using numpy array as inputs without
      # distribution strategy uses entire sample as a single batch. As so,
      # we remove parameters `batch_size` and `steps`.
      cpu_model.set_weights(model_with_ds_strategy.get_weights())
      self.assertAllClose(
          model_with_ds_strategy.predict(input_dict, batch_size=18, steps=12),
          cpu_model.predict(input_dict),
804 805
          atol=1e-4,
          rtol=1e-4)
806

807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
  @combinations.generate(all_strategy_combinations_plus_run_distributed())
  def test_gradients_are_none(self, distribution):

    if not context.executing_eagerly():
      self.skipTest('None gradients are not supported in graph mode')

    class DenseWithExtraWeight(keras.layers.Dense):

      def build(self, input_shape):
        # Gradients w.r.t. extra_weights are None
        self.extra_weight_1 = self.add_weight('extra_weight_1', shape=(),
                                              initializer='ones')
        super(DenseWithExtraWeight, self).build(input_shape)
        self.extra_weight_2 = self.add_weight('extra_weight_2', shape=(),
                                              initializer='ones')

    with distribution.scope():
      model = keras.Sequential([DenseWithExtraWeight(4, input_shape=(4,))])
      model.compile('adam', 'mse')

    inputs = np.random.normal(size=(64, 4))
    targets = np.random.normal(size=(64, 4))
    old_kernel = model.get_weights()[1]
    model.fit(inputs, targets)
    new_kernel = model.get_weights()[1]
    self.assertNotAllEqual(old_kernel, new_kernel)

834 835 836 837

class TestDistributionStrategyWithDatasets(test.TestCase,
                                           parameterized.TestCase):

838
  @combinations.generate(all_strategy_combinations_plus_run_distributed())
839
  def test_calling_model_on_same_dataset(self, distribution):
840
    with self.cached_session():
841
      with distribution.scope():
842
        optimizer_fn = gradient_descent_keras.SGD
843
        optimizer = optimizer_fn(0.001)
844 845 846
        model = get_model()
        loss = 'mse'
        metrics = ['mae', keras.metrics.CategoricalAccuracy()]
847
        model.compile(
848 849
            optimizer,
            loss,
850
            metrics=metrics)
851

852
      dataset = get_dataset(distribution)
853 854

      # Call fit with validation data
855 856 857 858 859 860 861 862 863 864 865 866 867 868
      model.fit(
          dataset,
          epochs=1,
          steps_per_epoch=2,
          verbose=0,
          validation_data=dataset,
          validation_steps=2)
      model.fit(
          dataset,
          epochs=1,
          steps_per_epoch=2,
          verbose=0,
          validation_data=dataset,
          validation_steps=2)
869
      model.predict(get_predict_dataset(distribution), steps=2)
870

871
  @combinations.generate(all_strategy_combinations_plus_run_distributed())
872
  def test_model_interleaved_eval_same_as_direct_eval(
873
      self, distribution):
874
    with self.cached_session():
875
      with distribution.scope():
876
        optimizer_fn = gradient_descent_keras.SGD
877 878
        user_controlled_model = get_model()
        user_controlled_model.compile(
879
            optimizer_fn(0.001),
880
            loss='mse',
881
            metrics=['mae', keras.metrics.CategoricalAccuracy()])
882 883 884 885

        interleaved_model = get_model()
        interleaved_model.set_weights(user_controlled_model.get_weights())
        interleaved_model.compile(
886
            optimizer_fn(0.001),
887
            loss='mse',
888
            metrics=['mae', keras.metrics.CategoricalAccuracy()])
889 890 891 892

      dataset = get_dataset(distribution)

      # Call fit with validation interleaved
893
      interleaved_output = interleaved_model.fit(
894 895 896 897 898 899 900
          dataset,
          epochs=2,
          steps_per_epoch=2,
          verbose=1,
          validation_data=dataset,
          validation_steps=2,
          shuffle=False)
901 902 903 904 905

      # Manually control the validation running after each epoch.
      user_controlled_output = []
      for _ in range(2):
        user_controlled_model.fit(
906
            dataset, epochs=1, steps_per_epoch=2, verbose=1, shuffle=False)
907 908 909 910 911
        user_controlled_output.append(
            user_controlled_model.evaluate(dataset, steps=2))

      self.assertEqual(interleaved_output.history['val_loss'],
                       [x[0] for x in user_controlled_output])
S
Shining Sun 已提交
912 913 914 915 916 917
      val_mean_absolute_error = interleaved_output.history.get(
          'val_mean_absolute_error')
      if not val_mean_absolute_error:
        # The name of the metric changed in TF2.0
        val_mean_absolute_error = interleaved_output.history['val_mae']
      self.assertEqual(val_mean_absolute_error,
918
                       [x[1] for x in user_controlled_output])
919 920
      self.assertEqual(interleaved_output.history['val_categorical_accuracy'],
                       [x[2] for x in user_controlled_output])
921

922
  @combinations.generate(all_strategy_combinations_plus_run_distributed())
923
  def test_fit_with_tuple_and_dict_dataset_inputs(self, distribution):
924
    with self.cached_session():
925
      with distribution.scope():
926
        optimizer_fn = gradient_descent_keras.SGD
927
        optimizer = optimizer_fn(learning_rate=0.001)
928 929 930
        model = multi_input_output_model()
        loss = 'mse'
        metrics = ['mae', keras.metrics.CategoricalAccuracy()]
931
        model.compile(
932 933
            optimizer,
            loss,
934
            metrics=metrics)
935

936 937 938 939
      input_a_np = np.random.random((10, 3)).astype('float32')
      input_b_np = np.random.random((10, 5)).astype('float32')
      output_d_np = np.random.random((10, 7)).astype('float32')
      output_e_np = np.random.random((10, 7)).astype('float32')
940 941

      # Test with tuples
942 943
      dataset_tuple = dataset_ops.Dataset.from_tensor_slices(
          ((input_a_np, input_b_np), (output_d_np, output_e_np)))
944 945 946 947 948 949
      dataset_tuple = dataset_tuple.repeat(100)
      dataset_tuple = dataset_tuple.batch(10)

      model.fit(dataset_tuple, epochs=1, steps_per_epoch=2, verbose=1)

      # Test with dict
950 951 952 953
      dataset_dict = dataset_ops.Dataset.from_tensor_slices(({
          'input_a': input_a_np,
          'input_b': input_b_np
      }, (output_d_np, output_e_np)))
954 955 956 957 958
      dataset_dict = dataset_dict.repeat(100)
      dataset_dict = dataset_dict.batch(10)

      model.fit(dataset_dict, epochs=1, steps_per_epoch=2, verbose=1)

959
  @combinations.generate(all_strategy_combinations_plus_run_distributed())
960
  def test_fit_with_dictionary_in_the_dataset_b135161171(
961
      self, distribution):
962 963 964 965 966 967 968 969

    def custom_loss(predict, label, weight):
      bce = keras.losses.binary_crossentropy(label, predict)
      return math_ops.reduce_mean(bce * weight)

    with self.cached_session():
      with distribution.scope():
        input_img = keras.layers.Input([64, 64, 3], name='img')
970
        input_lbl = keras.layers.Input([64, 64, 1], name='lbl')
971 972 973 974 975 976 977 978 979
        input_weight = keras.layers.Input([64, 64], name='weight')
        predict = keras.layers.Conv2D(2, [1, 1], padding='same')(input_img)
        loss_lambda = keras.layers.Lambda(
            lambda x: custom_loss(*x), name='my_loss')
        my_loss = loss_lambda([predict, input_lbl, input_weight])
        model = keras.models.Model(
            inputs=[input_img, input_lbl, input_weight],
            outputs=[predict, my_loss])
        model.add_loss(model.get_layer('my_loss').output)
980
        model.compile(
981
            optimizer='adam')
982

T
Thomas O'Malley 已提交
983 984 985 986 987 988 989 990 991 992
      if context.executing_eagerly():

        def map_fn(img, lbl, weight):
          inputs = {'img': img, 'lbl': lbl, 'weight': weight}
          return (inputs,)
      else:

        def map_fn(img, lbl, weight):
          inputs = {'img': img, 'lbl': lbl, 'weight': weight}
          return inputs, {}
993 994

      fake_imgs = np.ones([50, 64, 64, 3], dtype=np.float32)
995
      fake_lbls = np.ones([50, 64, 64, 1], dtype=np.float32)
996 997 998 999 1000 1001 1002
      fake_weights = np.ones([50, 64, 64], dtype=np.float32)

      data = dataset_ops.Dataset.from_tensor_slices(
          (fake_imgs, fake_lbls, fake_weights)).map(map_fn).batch(10)

      model.fit(data)

1003
  @combinations.generate(all_strategy_combinations_plus_run_distributed())
1004
  def test_fit_eval_and_predict_methods_on_dataset_without_steps(
1005
      self, distribution):
1006 1007
    with self.cached_session():
      with distribution.scope():
1008
        optimizer_fn = gradient_descent_keras.SGD
1009
        optimizer = optimizer_fn(0.001)
1010 1011 1012
        model = get_model()
        loss = 'mse'
        metrics = ['mae', keras.metrics.CategoricalAccuracy()]
1013
        model.compile(
1014 1015
            optimizer,
            loss,
1016
            metrics=metrics)
1017 1018 1019 1020 1021

      inputs = np.zeros((1000, 3), dtype=np.float32)
      targets = np.zeros((1000, 4), dtype=np.float32)
      # steps/steps_per_epoch are calculated when using numpy arrays as
      # input data.
1022 1023
      fit_with_numpy = model.fit(
          inputs, targets, epochs=1, batch_size=10).history
1024 1025 1026 1027
      eval_with_numpy = model.evaluate(inputs, targets, batch_size=10)
      predict_with_numpy = model.predict(inputs, batch_size=10)

      dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))
1028
      dataset = dataset.batch(10, drop_remainder=True)
1029 1030 1031 1032 1033
      fit_with_ds = model.fit(dataset, epochs=1).history
      eval_with_ds = model.evaluate(dataset)
      predict_dataset = dataset_ops.Dataset.from_tensor_slices(inputs)
      predict_dataset = predict_dataset.batch(10, drop_remainder=True)
      predict_with_ds = model.predict(predict_dataset)
1034 1035
      self.assertAllClose(fit_with_numpy, fit_with_ds, atol=1e-4, rtol=1e-4)
      self.assertAllClose(eval_with_numpy, eval_with_ds, atol=1e-4, rtol=1e-4)
1036 1037 1038
      self.assertAllClose(
          predict_with_numpy, predict_with_ds, atol=1e-4, rtol=1e-4)

1039
  @combinations.generate(
1040
      combinations.times(
1041
          strategy_minus_tpu_combinations()))
1042
  def test_on_dataset_with_unknown_cardinality_without_steps(
1043
      self, distribution, mode):
1044 1045
    with self.cached_session():
      with distribution.scope():
1046
        optimizer_fn = gradient_descent_keras.SGD
1047
        optimizer = optimizer_fn(0.001)
1048 1049 1050
        model = get_model()
        loss = 'mse'
        metrics = ['mae', keras.metrics.CategoricalAccuracy()]
1051
        model.compile(
1052 1053
            optimizer,
            loss,
1054
            metrics=metrics)
1055 1056 1057 1058 1059

      inputs = np.zeros((1000, 3), dtype=np.float32)
      targets = np.zeros((1000, 4), dtype=np.float32)
      # steps/steps_per_epoch are calculated when using numpy arrays as
      # input data.
1060 1061
      fit_with_numpy = model.fit(
          inputs, targets, epochs=1, batch_size=10).history
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
      fit_with_numpy_multiple_epochs = model.fit(
          inputs, targets, epochs=2, batch_size=10).history
      eval_with_numpy = model.evaluate(inputs, targets, batch_size=10)
      predict_with_numpy = model.predict(inputs, batch_size=10)

      dataset = convert_numpy_to_dataset_with_unknown_cardinality(
          inputs, targets)
      predict_dataset = convert_numpy_to_dataset_with_unknown_cardinality(
          inputs)

1072 1073 1074 1075 1076 1077
      self.assertEqual(
          keras.backend.get_value(cardinality.cardinality(dataset)),
          cardinality.UNKNOWN)
      self.assertEqual(
          keras.backend.get_value(cardinality.cardinality(predict_dataset)),
          cardinality.UNKNOWN)
1078 1079 1080

      eval_with_ds = model.evaluate(dataset)
      predict_with_ds = model.predict(predict_dataset)
1081
      self.assertAllClose(eval_with_numpy, eval_with_ds, atol=1e-4, rtol=1e-4)
1082 1083 1084
      self.assertAllClose(
          predict_with_numpy, predict_with_ds, atol=1e-4, rtol=1e-4)

1085 1086 1087
      fit_with_ds = model.fit(dataset, epochs=1).history
      fit_with_ds_multiple_epochs = model.fit(dataset, epochs=2).history
      self.assertAllClose(fit_with_numpy, fit_with_ds, atol=1e-4, rtol=1e-4)
1088 1089
      self.assertAllClose(
          fit_with_numpy_multiple_epochs,
1090 1091 1092
          fit_with_ds_multiple_epochs,
          atol=1e-4,
          rtol=1e-4)
1093

1094
  @combinations.generate(
1095
      combinations.times(
1096 1097
          tpu_strategy_combinations()))
  def test_on_dataset_with_unknown_cardinality(self, distribution):
1098 1099 1100 1101 1102
    with self.cached_session():
      with distribution.scope():
        model = get_model()
        loss = 'mse'
        metrics = ['mae', keras.metrics.CategoricalAccuracy()]
1103 1104 1105
        model.compile(
            gradient_descent.GradientDescentOptimizer(0.001),
            loss,
1106
            metrics=metrics)
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119

      inputs = np.zeros((1000, 3), dtype=np.float32)
      targets = np.zeros((1000, 4), dtype=np.float32)
      # steps/steps_per_epoch are calculated when using numpy arrays as
      # input data.
      eval_with_numpy = model.evaluate(inputs, targets, batch_size=10)
      predict_with_numpy = model.predict(inputs, batch_size=10)

      dataset = convert_numpy_to_dataset_with_unknown_cardinality(
          inputs, targets)
      predict_dataset = convert_numpy_to_dataset_with_unknown_cardinality(
          inputs)

1120 1121 1122 1123 1124 1125
      self.assertEqual(
          keras.backend.get_value(cardinality.cardinality(dataset)),
          cardinality.UNKNOWN)
      self.assertEqual(
          keras.backend.get_value(cardinality.cardinality(predict_dataset)),
          cardinality.UNKNOWN)
1126 1127 1128

      eval_with_ds = model.evaluate(dataset, steps=100)
      predict_with_ds = model.predict(predict_dataset, steps=100)
1129
      self.assertAllClose(eval_with_numpy, eval_with_ds, atol=1e-4, rtol=1e-4)
1130 1131 1132 1133
      self.assertAllClose(
          predict_with_numpy, predict_with_ds, atol=1e-4, rtol=1e-4)

      with self.assertRaisesRegexp(ValueError,
T
Taehoon Lee 已提交
1134
                                   'Number of steps could not be inferred'):
1135
        model.fit(dataset, epochs=1)
1136

1137
  @combinations.generate(all_strategy_combinations_plus_run_distributed())
1138
  def test_fit_eval_and_predict_methods_on_dataset(
1139
      self, distribution):
1140
    with self.cached_session():
1141
      with distribution.scope():
1142
        optimizer_fn = gradient_descent_keras.SGD
1143
        optimizer = optimizer_fn(0.001)
1144 1145 1146
        model = get_model()
        loss = 'mse'
        metrics = ['mae', keras.metrics.CategoricalAccuracy()]
1147
        model.compile(
1148 1149
            optimizer,
            loss,
1150
            metrics=metrics)
1151

1152
      dataset = get_dataset(distribution)
1153 1154 1155

      model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1)
      model.evaluate(dataset, steps=2, verbose=1)
1156
      model.predict(get_predict_dataset(distribution), steps=2)
1157

1158
  @combinations.generate(strategy_and_optimizer_combinations())
1159
  def test_fit_eval_and_predict_with_optimizer(self, distribution, optimizer):
1160
    with self.cached_session():
1161

1162
      with distribution.scope():
1163

1164 1165
        model = get_model()
        loss = 'mse'
1166 1167
        model.compile(
            optimizer(),
1168
            loss)
1169 1170 1171 1172 1173

      dataset = get_dataset(distribution)

      model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1)
      model.evaluate(dataset, steps=2, verbose=1)
1174
      model.predict(get_predict_dataset(distribution), steps=2)
1175

1176 1177 1178
  @combinations.generate(
      combinations.combine(
          distribution=[
1179 1180
              strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
              strategy_combinations.one_device_strategy
1181
          ],
1182 1183
          mode=['graph', 'eager']))
  def test_dataset_wrong_input_shape(self, distribution, mode):
1184 1185 1186 1187
    if mode == 'graph':
      self.skipTest(
          'TODO(b/120943676, b/120957836): Re-enable for graph once the '
          'validation code is restored.')
1188
    with self.cached_session():
1189
      with distribution.scope():
1190
        optimizer_fn = gradient_descent_keras.SGD
1191
        optimizer = optimizer_fn(learning_rate=0.001)
1192 1193
        model = get_model()
        loss = 'mse'
1194 1195
        model.compile(
            optimizer,
1196
            loss)
1197

1198 1199
      # Wrong input shape
      inputs = np.zeros((10, 5), dtype=np.float32)
1200 1201 1202
      targets = np.zeros((10, 4), dtype=np.float32)
      dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))
      dataset = dataset.repeat(100)
1203
      dataset = dataset.batch(10)
1204

T
Thomas O'Malley 已提交
1205
      with self.assertRaisesRegexp(ValueError, 'incompatible with the layer'):
1206 1207
        model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0)

1208 1209 1210 1211 1212
  @combinations.generate(
      combinations.combine(
          distribution=[
              strategy_combinations.mirrored_strategy_with_gpu_and_cpu
          ],
1213
          mode=['graph', 'eager']))
1214
  def test_dataset_external_batch_input_validation(
1215
      self, distribution):
1216
    with self.cached_session():
1217
      with distribution.scope():
1218 1219
        optimizer_fn = gradient_descent_keras.SGD
        optimizer = optimizer_fn(learning_rate=0.001)
1220 1221
        model = get_model()
        loss = 'mse'
1222 1223
        model.compile(
            optimizer,
1224
            loss)
1225

1226 1227 1228
      # Batching is done outside tf.data's `batch`
      inputs = np.zeros((100, 10, 3), dtype=np.float32)
      targets = np.zeros((100, 10, 4), dtype=np.float32)
1229 1230 1231
      dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))
      dataset = dataset.repeat(100)

1232
      model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1)
1233

1234 1235 1236 1237 1238 1239
  @combinations.generate(
      combinations.combine(
          distribution=[
              strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
              strategy_combinations.mirrored_strategy_with_two_gpus
          ],
1240 1241
          mode=['graph', 'eager']))
  def test_learning_phase_value(self, distribution):
1242 1243 1244
    # TODO(anjalisridhar): Modify this test to use Lambdas since we can compare
    # meaningful values. Currently we don't pass the learning phase if the
    # Lambda layer uses the learning phase.
1245
    with self.cached_session():
1246 1247 1248 1249 1250 1251
      with distribution.scope():
        x = keras.layers.Input(shape=(1,), name='input')
        y = keras.layers.Dense(1, kernel_initializer='ones')(x)
        z = keras.layers.Dropout(0.9999)(y)
        model = keras.Model(x, z)
        initial_weights = model.get_weights()
1252

1253
        optimizer_fn = gradient_descent_keras.SGD
1254
        optimizer = optimizer_fn(0.005)
1255 1256
        loss = 'mse'
        metrics = ['acc']
1257
        model.compile(
1258 1259
            optimizer,
            loss,
1260
            metrics=metrics)
1261

1262
      batch_size = 8
1263 1264
      if isinstance(distribution, mirrored_strategy.MirroredStrategy):
        # MirroredStrategy uses global batch size.
1265
        batch_size = 8 * distribution.num_replicas_in_sync
1266

1267 1268
      inputs = np.ones((10, 1), dtype=np.float32)
      targets = np.ones((10, 1), dtype=np.float32)
1269
      dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))
1270
      dataset = dataset.repeat().batch(batch_size)
1271 1272
      hist = model.fit(dataset, epochs=1, steps_per_epoch=20, verbose=1)
      self.assertAlmostEqual(hist.history['acc'][0], 0, 0)
1273

1274 1275
      with distribution.scope():
        model.set_weights(initial_weights)
1276 1277 1278
      # TODO(psv/anjalisridhar): Enable these lines after we fix b/117431185.
      # evaluate_output = model.evaluate(dataset, steps=20)
      # self.assertAlmostEqual(evaluate_output[1], 1, 0)
1279 1280 1281

      inputs = np.ones((10, 1), dtype=np.float32)
      predict_dataset = dataset_ops.Dataset.from_tensor_slices(inputs)
1282 1283

      predict_dataset = predict_dataset.repeat().batch(batch_size)
1284
      output = model.predict(predict_dataset, steps=10)
1285 1286
      # `predict` runs for 10 steps
      ref_output = np.ones((160, 1), dtype=np.float32)
1287
      self.assertArrayNear(output, ref_output, 1e-1)
1288

1289
  @combinations.generate(all_strategy_combinations_plus_run_distributed())
1290
  def testOptimizerWithCallbacks(self, distribution):
1291
    with self.cached_session():
1292 1293 1294 1295
      with distribution.scope():
        model = get_model()
        optimizer = gradient_descent_keras.SGD(0.01)
        loss = 'mse'
1296 1297
        model.compile(
            optimizer,
1298
            loss)
1299 1300 1301 1302 1303 1304

      dataset = get_dataset(distribution)

      def schedule(_):
        return 0.001

1305 1306 1307 1308 1309 1310
      model.fit(
          dataset,
          epochs=1,
          steps_per_epoch=2,
          verbose=0,
          callbacks=[keras.callbacks.LearningRateScheduler(schedule)])
1311
      self.assertAllClose(0.001, keras.backend.get_value(model.optimizer.lr))
1312

1313
  @combinations.generate(
1314
      combinations.times(tpu_strategy_combinations_graph_only(),
1315 1316 1317 1318 1319 1320
                         combinations.combine(batch_size=[4, 6])))
  def test_evaluate_with_dataset_with_partial_batch(self, distribution,
                                                    batch_size):
    with self.cached_session():
      optimizer = gradient_descent.GradientDescentOptimizer(0.001)
      loss = 'mse'
1321
      metrics = ['mae', keras.metrics.CategoricalAccuracy()]
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353

      with distribution.scope():
        model_with_ds_strategy = get_model()
        model_with_ds_strategy.compile(optimizer, loss, metrics=metrics)

      cpu_model = get_model()
      cpu_model.compile(optimizer, loss, metrics=metrics)

      x = np.random.random((10, 3)).astype('float32')
      y = np.random.random((10, 4)).astype('float32')
      dataset = dataset_ops.Dataset.from_tensor_slices((x, y))

      # As sample size is 10, we make the last batch a partial batch.
      cpu_model.set_weights(model_with_ds_strategy.get_weights())
      dataset_with_partial_batch = dataset.batch(batch_size)

      # We don't compare the loss as loss is currently not computed as metric
      # in Keras, the loss value is inaccurate for last partial batch due to
      # more weights for the last batch samples.
      steps = np.ceil(10.0 / batch_size)
      self.assertAllClose(
          model_with_ds_strategy.evaluate(
              dataset_with_partial_batch, steps=steps)[1:],
          cpu_model.evaluate(dataset_with_partial_batch, steps=steps)[1:],
          atol=1e-5,
          rtol=1e-5)
      self.assertAllClose(
          model_with_ds_strategy.evaluate(dataset_with_partial_batch)[1:],
          cpu_model.evaluate(dataset_with_partial_batch)[1:],
          atol=1e-5,
          rtol=1e-5)

1354
  @combinations.generate(
1355
      combinations.times(
1356
          tpu_strategy_combinations_graph_only()))
1357
  def test_predict_with_dataset_with_partial_batch(
1358
      self, distribution):
1359 1360 1361 1362 1363 1364
    with self.cached_session():
      optimizer = gradient_descent.GradientDescentOptimizer(0.001)
      loss = 'mse'

      with distribution.scope():
        model_with_ds_strategy = get_model()
1365
        model_with_ds_strategy.compile(
1366
            optimizer,
1367
            loss)
1368 1369 1370 1371

      cpu_model = get_model()
      cpu_model.compile(optimizer, loss)

1372
      inputs = np.random.random((10, 3)).astype(np.float32)
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
      dataset = dataset_ops.Dataset.from_tensor_slices((inputs))

      # As sample size is 10, we batch by 4 so that the last batch is
      # a partial batch.
      dataset_with_partial_batch = dataset.batch(4)
      cpu_model.set_weights(model_with_ds_strategy.get_weights())

      self.assertAllClose(
          model_with_ds_strategy.predict(dataset_with_partial_batch, steps=3),
          cpu_model.predict(dataset_with_partial_batch, steps=3),
1383 1384
          atol=1e-5,
          rtol=1e-5)
1385

1386
  @combinations.generate(
1387
      combinations.times(
1388
          tpu_strategy_combinations_graph_only()))
1389
  def test_predict_multi_output_model_with_dataset_with_partial_batch(
1390
      self, distribution):
1391 1392 1393 1394 1395 1396
    with self.cached_session():
      optimizer = gradient_descent.GradientDescentOptimizer(0.001)
      loss = 'mse'

      with distribution.scope():
        model_with_ds_strategy = simple_multi_inputs_multi_outputs_model()
1397
        model_with_ds_strategy.compile(
1398
            optimizer,
1399
            loss)
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419

      cpu_model = simple_multi_inputs_multi_outputs_model()
      cpu_model.compile(optimizer, loss)

      input_data, _ = get_multi_inputs_multi_outputs_data()
      input_dict = {
          'input_a': input_data['input_a'],
          'input_b': input_data['input_b'],
      }

      dataset = dataset_ops.Dataset.from_tensor_slices(input_dict)

      # As sample size is 200, we batch by 18 using 12 steps per epoch so
      # that the last batch is a partial batch.
      dataset_with_partial_batch = dataset.batch(18)
      cpu_model.set_weights(model_with_ds_strategy.get_weights())

      self.assertAllClose(
          model_with_ds_strategy.predict(dataset_with_partial_batch, steps=12),
          cpu_model.predict(dataset_with_partial_batch, steps=12),
1420 1421
          atol=1e-4,
          rtol=1e-4)
1422

1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
  @combinations.generate(all_strategy_combinations_minus_default())
  def test_match_model_input_matches_with_dataset_tensors(self, distribution):

    def _create_model_input_output_tensors():
      input_a = keras.layers.Input(shape=(16,), name='z_input_sorted_last')
      input_b = keras.layers.Input(shape=(32,), name='a_input_sorted_first')
      intermediate_a = keras.layers.Dense(10)(input_a)
      intermediate_b = keras.layers.Dense(10)(input_b)
      merged = keras.layers.Add()([intermediate_a, intermediate_b])
      output = keras.layers.Dense(2)(merged)
      return input_a, input_b, output

    input_dict = {
        'z_input_sorted_last': np.random.rand(32, 16).astype(np.float32),
        'a_input_sorted_first': np.random.rand(32, 32).astype(np.float32)
    }
    target = np.ones((32, 2), dtype=np.float32)
    dataset = dataset_ops.Dataset.from_tensor_slices((input_dict, target))
    dataset = dataset.batch(4, drop_remainder=True)

    with self.cached_session():
      with distribution.scope():
        input_a, input_b, output = _create_model_input_output_tensors()
        # `input_a`, which has input name that comes last in alphanumeric
        # order, is the first input of the model input layers. If tensors
        # from `input_dict` is blindly flattened and passed to model
        # inputs incorrectly, this would result in `input_a` input layer
        # matching with tensor `a_input_sorted_first` and would result in
        # shape mismatch.
        model_with_array_input = keras.models.Model(
            inputs=[input_a, input_b], outputs=output)
        model_with_array_input.compile('sgd', 'mse')
        model_weights = model_with_array_input.get_weights()
        model_with_array_input_fit = model_with_array_input.fit(
            dataset, steps_per_epoch=1, epochs=1).history

        input_a, input_b, output = _create_model_input_output_tensors()
        model_with_dict_input = keras.models.Model(
            inputs={
                'z_input_sorted_last': input_a,
                'a_input_sorted_first': input_b,
            },
            outputs=output)
        model_with_dict_input.compile('sgd', 'mse')
        model_with_dict_input.set_weights(model_weights)
        model_with_dict_input_fit = model_with_dict_input.fit(
            dataset, steps_per_epoch=1, epochs=1).history
        self.assertAllClose(
            model_with_dict_input_fit,
            model_with_array_input_fit,
            atol=1e-4,
            rtol=1e-4)

1476
  @combinations.generate(
1477 1478
      combinations.combine(
          distribution=strategies_minus_tpu,
1479 1480
          mode=['graph', 'eager']))
  def test_dataset_with_sample_weights(self, distribution):
1481 1482 1483 1484
    with self.cached_session(), distribution.scope():
      model = get_sample_weights_model()
      optimizer = rmsprop.RMSPropOptimizer(learning_rate=0.001)
      loss = 'mse'
1485 1486
      model.compile(
          optimizer,
1487
          loss)
1488 1489 1490 1491

      inputs = np.array([[0], [1], [2], [3]], np.float32)
      targets = np.array([[2], [4], [6], [8]], np.float32)
      sample_weights = np.array([0.25, 0.5, 0.75, 1], np.float32)
1492 1493
      ds = dataset_ops.Dataset.from_tensor_slices(
          (inputs, targets, sample_weights)).batch(2)
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
      result = model.evaluate(ds, verbose=1)
      # The per sample loss is multipled by the corresponding sample weight. The
      # average of these weighted losses is the return value of the `evaluate`
      # call. For example, in the test above the average weighted loss is
      # calculated in the following manner:
      # batch_1 = (((2-0)^2) * 0.25 + ((4-1)^2) * 0.5) / 2 = 5.5 / 2 = 2.75
      # batch_2 = (((6-2)^2 * 0.75) + ((8-3)^2 * 1)) / 2 = 37 / 2 = 18.5
      # final result = (batch_1 + batch_2) / 2 = 10.625.
      # The first time we divide by number of input samples and the second time
      # we divide by number of steps/batches that the loss is aggregated over.
      self.assertAllClose(result, 10.625)

      # We now test without passing sample_weights:
      # batch_1 = ((2-0)^2) + ((4-1)^2) / 2 = 13 / 2 = 6.5
      # batch_2 = ((6-2)^2) + ((8-3)^2) / 2 = 41 / 2 = 20.5
      # final result = (batch_1 + batch_2) / 2 =  27 / 2 = 13.5
      ds = dataset_ops.Dataset.from_tensor_slices((inputs, targets)).batch(2)
      result = model.evaluate(ds, verbose=1)
      self.assertAllClose(result, 13.5)

1514

1515
class TestRegularizerLoss(test.TestCase, parameterized.TestCase):
1516

1517 1518 1519 1520 1521 1522 1523 1524 1525
  class IdentityRegularizer(keras.regularizers.Regularizer):

    def __call__(self, x):
      return array_ops.identity(x)

  class AddLayer(keras.layers.Layer):

    def build(self, _):
      self.v = self.add_weight(
1526 1527
          'v', (),
          initializer='ones',
1528 1529 1530 1531 1532 1533 1534
          regularizer=TestRegularizerLoss.IdentityRegularizer())

    def call(self, inputs):
      return inputs + self.v

  @staticmethod
  def loss_fn(_, y_pred):
1535
    return math_ops.reduce_mean(y_pred)
1536

1537
  @combinations.generate(
1538
      combinations.times(
1539 1540
          strategy_combinations.all_strategy_combinations_minus_default()))
  def test_regularizer_loss(self, distribution):
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
    batch_size = 2
    if not distributed_training_utils.global_batch_size_supported(distribution):
      batch_size //= distribution.num_replicas_in_sync

      # Given an input x, which is always 1, and variable v, this model computes
      # Loss=x+v+regularizer_loss, where regularizer_loss=v and the variable is
      # initialized to 1. Therefore, this model computes Loss=1+2v, and so the
      # gradient dLoss/dv = 2. This gradient of 2 is averaged over all examples
      # in a batch and then multiplied by the learning rate of 1. As a result,
      # the model update for one batch should subtract 2 from v, resulting in v
      # being -1. If the regularizer loss is not scaled correctly by number of
      # replicas, the variable value will be incorrect when number of replicas
      # >1. For e.g. it will be -2 if num replicas = 2.
    with distribution.scope():
1555
      x = keras.layers.Input(shape=(1,), batch_size=batch_size)
1556 1557 1558
      y = TestRegularizerLoss.AddLayer()(x)
      model = keras.models.Model(inputs=x, outputs=y)
      opt = gradient_descent_keras.SGD(1.)
1559 1560
      model.compile(
          opt,
1561
          loss=TestRegularizerLoss.loss_fn)
1562 1563 1564 1565
      model.fit(
          x=np.array([[1.], [1.]], dtype=np.float32),
          y=np.array([[1.], [1.]], dtype=np.float32),
          batch_size=batch_size)
1566 1567 1568 1569
      v = model.get_weights()[0]
      self.assertEqual(-1.0, v)


1570 1571 1572
class TestDistributionStrategyWithKerasModels(test.TestCase,
                                              parameterized.TestCase):

1573
  @combinations.generate(all_strategy_combinations_plus_run_distributed())
1574
  def test_distribution_strategy_on_sequential_model(
1575
      self, distribution):
1576
    with distribution.scope():
1577
      optimizer_fn = gradient_descent_keras.SGD
1578
      optimizer = optimizer_fn(learning_rate=0.001)
1579 1580
      model = simple_sequential_model()
      loss = 'mse'
1581 1582
      model.compile(
          optimizer,
1583
          loss)
1584 1585 1586 1587

      inputs = np.zeros((20, 10), np.float32)
      targets = np.zeros((20, 2), np.float32)

1588 1589 1590
    model.fit(inputs, targets, epochs=1, batch_size=10)
    model.predict(inputs, batch_size=10)
    model.evaluate(inputs, targets, batch_size=10)
1591

1592
  @combinations.generate(all_strategy_combinations_plus_run_distributed())
1593
  def test_distribution_strategy_on_functional_model(
1594
      self, distribution):
1595
    with distribution.scope():
1596
      optimizer_fn = gradient_descent_keras.SGD
1597
      optimizer = optimizer_fn(learning_rate=0.001)
1598 1599
      model = get_model()
      loss = 'mse'
1600 1601
      model.compile(
          optimizer,
1602
          loss)
1603 1604 1605 1606

      inputs = np.zeros((64, 3), dtype=np.float32)
      targets = np.zeros((64, 4), dtype=np.float32)

1607 1608 1609
    model.fit(inputs, targets, epochs=1)
    model.predict(inputs)
    model.evaluate(inputs, targets)
1610

1611
  @combinations.generate(
1612
      combinations.times(
1613 1614
          all_strategy_combinations_minus_default()))
  def test_distribution_strategy_one_dimensional(self, distribution):
1615 1616 1617 1618 1619 1620 1621
    with distribution.scope():
      inp = keras.layers.Input(shape=(10,))
      out = keras.layers.Dense(3, activation='softmax')(inp)
      model = keras.Model(inputs=[inp], outputs=[out])
      model.compile(
          optimizer='rmsprop',
          loss='sparse_categorical_crossentropy',
1622
          metrics=['sparse_categorical_accuracy'])
1623 1624 1625 1626 1627 1628

      x = np.random.random((64, 10)).astype('float32')
      y = np.random.randint(3, size=64)

      model.fit(x, y, epochs=1, steps_per_epoch=2)

1629 1630 1631 1632 1633 1634 1635 1636
  @combinations.generate(
      combinations.combine(
          distribution=[
              strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
              strategy_combinations.mirrored_strategy_with_two_gpus
          ],
          mode=['graph', 'eager'],
          reduction=[
1637
              loss_reduction.ReductionV2.AUTO,
1638 1639 1640 1641
              loss_reduction.ReductionV2.SUM_OVER_BATCH_SIZE,
              loss_reduction.ReductionV2.SUM
          ]))
  def test_distribution_strategy_with_loss_reduction_types(
1642
      self, distribution, reduction):
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
    np.random.seed(_RANDOM_SEED)

    def _get_model():
      inputs = keras.Input((10,))
      x1 = keras.layers.Dense(10, kernel_initializer='zeros')(inputs)
      x2 = keras.layers.Dense(10, kernel_initializer='zeros')(x1)
      outputs = keras.layers.Dense(1, kernel_initializer='zeros')(x2)
      model = keras.Model(inputs, outputs)
      return model

    x = np.random.random((64, 10))
    y = np.random.random((64, 1))
    dataset = dataset_ops.Dataset.from_tensor_slices((x, y))
    dataset = dataset.batch(32)

    model = _get_model()
    model.compile(
        'sgd', loss=keras.losses.MeanSquaredError(reduction=reduction))
    history = model.fit(dataset, steps_per_epoch=2, epochs=1, shuffle=False)

    with distribution.scope():
      ds_model = _get_model()
      ds_model.compile(
          'sgd',
1667
          loss=keras.losses.MeanSquaredError(reduction=reduction))
1668 1669 1670 1671 1672
      ds_history = ds_model.fit(
          dataset, steps_per_epoch=2, epochs=1, shuffle=False)
    self.assertArrayNear(history.history['loss'], ds_history.history['loss'],
                         1e-5)

1673
  @combinations.generate(
1674
      combinations.times(
1675
          all_strategy_combinations_minus_default()))
1676
  def test_distribution_strategy_with_symbolic_add_loss(
1677
      self, mode, distribution):
1678

1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
    def _make_model_with_add_loss():
      inputs = keras.Input((10,))
      x1 = keras.layers.Dense(10, kernel_initializer='zeros')(inputs)
      x2 = keras.layers.Dense(10, kernel_initializer='zeros')(x1)
      outputs = keras.layers.Dense(1, kernel_initializer='zeros')(x2)
      model = keras.Model(inputs, outputs)
      model.add_loss(math_ops.reduce_mean(x1))
      model.add_loss(math_ops.reduce_mean(outputs))
      return model

    x = np.ones((64, 10)).astype('float32')

    model = _make_model_with_add_loss()
1692
    model.compile('sgd')
1693
    history = model.fit(x, epochs=1)
1694 1695 1696

    with distribution.scope():
      ds_model = _make_model_with_add_loss()
1697
      ds_model.compile(
1698
          'sgd')
1699
      ds_history = ds_model.fit(x, epochs=1)
1700 1701 1702

    self.assertAllClose(history.history, ds_history.history)

1703
  # TODO(omalleyt): Investigate flakiness and re-enable.
1704
  @combinations.generate(all_strategy_minus_default_and_tpu_combinations())
1705 1706
  def DISABLED_test_distribution_strategy_with_callable_add_loss(
      self, distribution):
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734

    def _make_model():
      inputs = keras.Input((10,))
      x1 = keras.layers.Dense(10, kernel_initializer='zeros')(inputs)
      x2 = keras.layers.Dense(10, kernel_initializer='zeros')(x1)
      d = keras.layers.Dense(1, kernel_initializer='zeros')
      outputs = d(x2)
      model = keras.Model(inputs, outputs)
      model.add_loss(lambda: 100. * math_ops.reduce_mean(d.kernel))
      return model

    x = np.ones((64, 10)).astype('float32')
    y = np.ones((64, 1)).astype('float32')

    model = _make_model()
    self.assertLen(model.losses, 1)

    model.compile('sgd', 'mse')
    history = model.fit(x, y, steps_per_epoch=2, epochs=1)

    with distribution.scope():
      ds_model = _make_model()
      self.assertLen(ds_model.losses, 1)
      ds_model.compile('sgd', 'mse')
      ds_history = ds_model.fit(x, y, steps_per_epoch=2, epochs=1)

    self.assertAllClose(history.history, ds_history.history)

1735
  @combinations.generate(
1736
      combinations.times(
1737
          all_strategy_minus_default_and_tpu_combinations()))
1738
  def test_distribution_strategy_with_add_metric_in_call(
1739
      self, distribution):
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766

    class Bias(keras.layers.Layer):

      def build(self, input_shape):
        self.bias = self.add_weight(name='bias', initializer='zeros', shape=())

      def call(self, inputs):
        self.add_metric(
            math_ops.reduce_mean(inputs), name='bias', aggregation='mean')
        return inputs + self.bias

    def _make_model_with_add_metric():
      inputs = keras.Input((10,))
      x1 = keras.layers.Dense(10, kernel_initializer='zeros')(inputs)
      x2 = Bias()(x1)
      outputs = keras.layers.Dense(1, kernel_initializer='zeros')(x2)
      model = keras.Model(inputs, outputs)
      return model

    x = np.ones((64, 10)).astype('float32')
    y = np.ones((64, 1)).astype('float32')

    model = _make_model_with_add_metric()
    self.assertLen(model.metrics, 1)

    model.compile('sgd', 'mse')
    history = model.fit(
1767
        x, y, validation_data=(x, y), validation_steps=2, epochs=2)
1768 1769 1770 1771

    with distribution.scope():
      ds_model = _make_model_with_add_metric()
      self.assertLen(ds_model.metrics, 1)
1772 1773
      ds_model.compile(
          'sgd',
1774
          'mse')
1775
      ds_history = ds_model.fit(
1776
          x, y, validation_data=(x, y), validation_steps=2, epochs=2)
T
Thomas O'Malley 已提交
1777 1778 1779
      # includes stateful loss metric in eager.
      metrics_len = 2 if context.executing_eagerly() else 1
      self.assertLen(ds_model.metrics, metrics_len)
1780 1781 1782

    self.assertAllClose(history.history, ds_history.history)

1783 1784 1785 1786 1787 1788 1789 1790
  @combinations.generate(
      combinations.combine(
          distribution=[
              strategy_combinations.one_device_strategy,
              strategy_combinations.one_device_strategy_gpu,
              strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
              strategy_combinations.mirrored_strategy_with_two_gpus,
          ],
1791
          mode=['eager']))
1792
  def test_distribution_strategy_with_add_metric_object(
1793
      self, distribution):
1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820

    class Bias(keras.layers.Layer):

      def build(self, input_shape):
        self.bias = self.add_weight(name='bias', initializer='zeros', shape=())
        self.mean = keras.metrics.Mean(name='mean')

      def call(self, inputs):
        self.add_metric(self.mean(inputs))
        return inputs + self.bias

    def _make_model_with_add_metric_object():
      inputs = keras.Input((10,))
      x1 = keras.layers.Dense(10, kernel_initializer='zeros')(inputs)
      x2 = Bias()(x1)
      outputs = keras.layers.Dense(1, kernel_initializer='zeros')(x2)
      model = keras.Model(inputs, outputs)
      return model

    x = np.ones((64, 10)).astype('float32')
    y = np.ones((64, 1)).astype('float32')

    model = _make_model_with_add_metric_object()
    self.assertLen(model.metrics, 1)

    model.compile('sgd', 'mse')
    history = model.fit(
1821
        x, y, validation_data=(x, y), validation_steps=2, epochs=2)
1822 1823 1824 1825

    with distribution.scope():
      ds_model = _make_model_with_add_metric_object()
      self.assertLen(ds_model.metrics, 1)
1826 1827
      ds_model.compile(
          'sgd',
1828
          'mse')
1829
      ds_history = ds_model.fit(
1830
          x, y, validation_data=(x, y), validation_steps=2, epochs=2)
T
Thomas O'Malley 已提交
1831 1832 1833
      # includes stateful loss metric in eager.
      metrics_len = 2 if context.executing_eagerly() else 1
      self.assertLen(ds_model.metrics, metrics_len)
1834 1835 1836

    self.assertAllClose(history.history, ds_history.history)

1837
  @combinations.generate(
1838
      # TODO(phillypham): Why does validation_steps > 1 not work on TPUs?
1839
      combinations.times(
1840
          all_strategy_minus_default_and_tpu_combinations()))
1841
  def test_distribution_strategy_with_add_metric_outside_call(
1842
      self, distribution):
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860

    def _make_model_with_add_metric():
      inputs = keras.Input((10,))
      x1 = keras.layers.Dense(10, kernel_initializer='zeros')(inputs)
      outputs = keras.layers.Dense(1, kernel_initializer='zeros')(x1)
      model = keras.Model(inputs, outputs)
      model.add_metric(
          math_ops.reduce_mean(x1), name='mid_mean', aggregation='mean')
      return model

    x = np.ones((64, 10)).astype('float32')
    y = np.ones((64, 1)).astype('float32')

    model = _make_model_with_add_metric()
    self.assertLen(model.metrics, 1)

    model.compile('sgd', 'mse')
    history = model.fit(
1861
        x, y, validation_data=(x, y), validation_steps=2, epochs=2)
1862 1863 1864 1865

    with distribution.scope():
      ds_model = _make_model_with_add_metric()
      self.assertLen(ds_model.metrics, 1)
1866 1867
      ds_model.compile(
          'sgd',
1868
          'mse')
1869
      ds_history = ds_model.fit(
1870
          x, y, validation_data=(x, y), validation_steps=2, epochs=2)
T
Thomas O'Malley 已提交
1871 1872 1873
      # includes stateful loss metric in eager.
      metrics_len = 2 if context.executing_eagerly() else 1
      self.assertLen(ds_model.metrics, metrics_len)
1874 1875 1876

    self.assertAllClose(history.history, ds_history.history)

1877 1878 1879
  @combinations.generate(
      combinations.combine(
          distribution=strategies_minus_tpu,
1880 1881
          mode=['eager']))
  def test_sparse_tensor_outputs(self, distribution):
1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908

    class ToSparse(keras.layers.Layer):
      """Create a sparse tensor based on a given dense tensor."""

      def call(self, inputs):
        indices = array_ops.where_v2(math_ops.not_equal(inputs, 0))
        values = array_ops.gather_nd(inputs, indices)
        shape = array_ops.shape(inputs, out_type='int64')
        return sparse_tensor.SparseTensor(indices, values, dense_shape=shape)

    model = keras.Sequential([ToSparse()])

    # Define some input data with additional padding.
    input_data = np.array([[1, 0, 0], [2, 3, 0]])
    output = model.predict(input_data, batch_size=2)

    expected_indices = np.array([[0, 0], [1, 0], [1, 1]])
    expected_values = np.array([1, 2, 3])
    expected_dense_shape = np.array([2, 3])

    self.assertAllEqual(output.indices, expected_indices)
    self.assertAllEqual(output.values, expected_values)
    self.assertAllEqual(output.dense_shape, expected_dense_shape)

  @combinations.generate(
      combinations.combine(
          distribution=strategies_minus_tpu,
1909 1910
          mode=['eager']))
  def test_ragged_tensor_outputs(self, distribution):
1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932

    class ToRagged(keras.layers.Layer):
      """Create a ragged tensor based on a given dense tensor."""

      def __init__(self, padding, ragged_rank=1, **kwargs):
        super(ToRagged, self).__init__(**kwargs)
        self._padding = padding
        self._ragged_rank = ragged_rank

      def call(self, inputs):
        return ragged_tensor.RaggedTensor.from_tensor(
            inputs, padding=self._padding, ragged_rank=self._ragged_rank)

    model = keras.Sequential([ToRagged(padding=0)])

    # Define some input data with additional padding.
    input_data = np.array([[1, 0, 0], [2, 3, 0]])
    output = model.predict(input_data, batch_size=2)

    expected_values = [[1], [2, 3]]
    self.assertAllEqual(expected_values, output)

1933 1934
  @combinations.generate(
      combinations.combine(
1935 1936
          distribution=strategies_minus_default_minus_tpu + tpu_strategies,
          mode=['eager']))
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
  def test_correctness_of_add_loss_with_merge_call(self, distribution):
    batch_size = 32

    def _get_model():
      inputs = keras.layers.Input(shape=(1,))
      labels = keras.layers.Input(shape=(1,))
      x = keras.layers.Dense(10, activation='relu')(inputs)
      y = keras.layers.Dense(1)(x)
      model = keras.models.Model([inputs, labels], y)
      model.add_loss(keras.losses.mean_squared_error(labels, y))
      return model

    def _get_data():
      x_train = np.random.rand(64, 1)
      y_train = 3 * x_train
      x_train = x_train.astype('float32')
      y_train = y_train.astype('float32')
      dataset = dataset_ops.DatasetV2.from_tensor_slices((x_train, y_train))
      dataset = dataset.batch(batch_size)
      return dataset

    with distribution.scope():
      model = _get_model()
      optimizer = gradient_descent_keras.SGD(0.2)

      @def_function.function
      def train_step(dist_inputs):

        def step_fn(inputs):
          with backprop.GradientTape() as tape:
            logits = model(inputs)

            # Invoke a merge_call()
            distribution_strategy_context.get_replica_context().merge_call(
                lambda d: None)

            # Verify that there is only one loss on the model.
            assert len(model.losses) == 1
            loss_from_model = math_ops.reduce_sum(
                model.losses) * 1.0 / batch_size

            # Compute loss in this loop.
            loss = keras.losses.mean_squared_error(inputs[1], logits)
            loss = nn.compute_average_loss(loss, global_batch_size=batch_size)

            # Verify that the loss computed in this loop is equivalent to the
            # loss from the model that was added via add_loss.
            check_ops.assert_equal(loss, loss_from_model)

          grads = tape.gradient(loss, model.trainable_variables)
          optimizer.apply_gradients(zip(grads, model.trainable_variables))
          return loss

1990
        per_replica_losses = distribution.run(step_fn, args=(dist_inputs,))
1991 1992 1993 1994 1995 1996 1997 1998
        return distribution.reduce(
            reduce_util.ReduceOp.SUM, per_replica_losses, axis=None)

      dataset = distribution.experimental_distribute_dataset(_get_data())
      for _ in range(2):
        for x in dataset:
          train_step(x)

1999

2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
# Models to exercise inserting ancillary layers with add_loss and add_metric.
def _functional_with_add_loss_and_metric(input_shape, num_classes, l1, l2):
  inputs = keras.Input(input_shape, name='images')
  x = keras.layers.Conv2D(32, kernel_size=5, activation='relu')(inputs)
  x = keras.layers.MaxPooling2D(pool_size=2)(x)
  x = keras.layers.Conv2D(64, kernel_size=5, activation='relu')(x)
  x = keras.layers.MaxPooling2D(pool_size=2)(x)
  # Apply L2 regularization to embedding. Use a mix of TensorFlow ops and layers
  # to exercise all code paths.
  x = keras.layers.Flatten(name='embedding')(x)
  l2_loss = math_ops.reduce_mean(math_ops.reduce_sum(math_ops.square(x), -1))
  # Apply L1 regularization to next layer.
  x = keras.layers.Dense(1024, activation='relu', name='sparse_embedding')(x)
  l1_loss = keras.layers.Lambda(
      lambda x: math_ops.reduce_mean(math_ops.reduce_sum(x, -1)),
      name='l1_loss')(
          x)
  outputs = keras.layers.Dense(num_classes, name='logits')(x)
  model = keras.Model(inputs=inputs, outputs=outputs)
  # Weight regularization terms.
  model.add_loss(keras.layers.Lambda(lambda x: x * l2)(l2_loss))
  model.add_metric(l2_loss, aggregation='mean', name='l2_loss')
  model.add_loss(l1_loss * l1)
  model.add_metric(l1_loss, aggregation='mean', name='l1_loss')
  return model


def _sequential_with_add_loss_and_metric(input_shape, num_classes, l1, l2):
  model = keras.Sequential([
      keras.layers.Conv2D(
          32, kernel_size=5, activation='relu', input_shape=input_shape),
      keras.layers.MaxPooling2D(pool_size=2),
      keras.layers.Conv2D(64, kernel_size=5, activation='relu'),
      keras.layers.MaxPooling2D(pool_size=2),
      keras.layers.Flatten(name='embedding'),
      keras.layers.Dense(1024, activation='relu', name='sparse_embedding'),
      keras.layers.Dense(num_classes, name='logits'),
  ])
  # Extract layer outputs, add regularization terms, and rescale the metric.
  # Use a mix of TensorFlow ops and layers to exercise all code paths.
  x = model.get_layer('sparse_embedding').get_output_at(-1)
  l1_loss = l1 * math_ops.reduce_mean(math_ops.reduce_sum(x, -1))
  model.add_loss(l1_loss)
  model.add_metric(
      keras.layers.Lambda(lambda x: math_ops.divide(x, l1))(l1_loss),
      aggregation='mean',
      name='l1_loss')
  x = model.get_layer('embedding').get_output_at(-1)
  l2_loss = keras.layers.Lambda(
      lambda x: l2 * math_ops.reduce_mean(math_ops.reduce_sum(x * x, -1)),
      name='l2_loss')(
          x)
  model.add_loss(l2_loss)
  model.add_metric(l2_loss / l2, aggregation='mean', name='l2_loss')
  return model


2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
def _functional_with_layer_reuse(input_shape, num_classes, l1, l2):
  base_model = keras.Sequential([
      keras.layers.Conv2D(
          32, kernel_size=5, activation='relu', input_shape=input_shape),
      keras.layers.MaxPooling2D(pool_size=2),
      keras.layers.Conv2D(64, kernel_size=5, activation='relu'),
      keras.layers.MaxPooling2D(pool_size=2),
      keras.layers.Flatten(),
      keras.layers.Dense(1024, activation='relu'),
      keras.layers.Dense(num_classes, name='logits'),
  ])
  inputs = keras.Input(input_shape, name='images')
  logits = base_model(inputs)
  model = keras.Model(inputs=inputs, outputs=logits)
  # Reuse sequential layer and create new nodes.
  zero_logits = base_model(array_ops.zeros_like(inputs))
  one_logits = base_model(array_ops.ones_like(inputs))
  # L2 loss.
  l2_loss = math_ops.reduce_mean(
      math_ops.reduce_sum(math_ops.square(logits - zero_logits), -1))
  model.add_loss(l2_loss * l2)
  model.add_metric(l2_loss, aggregation='mean', name='l2_loss')
  # L1 loss.
  l1_loss = math_ops.reduce_mean(
      math_ops.reduce_sum(math_ops.abs(logits - one_logits), -1))
  model.add_loss(l1_loss * l1)
  model.add_metric(l1_loss, aggregation='mean', name='l1_loss')
  return model


2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097
class TestDistributionStrategyWithMultipleAddLossAndMetricCalls(
    test.TestCase, parameterized.TestCase):
  """Tests complex models with multiple add loss and metric calls."""

  @combinations.generate(
      combinations.times(
          all_strategy_combinations_minus_default(),
          combinations.combine(
              model_fn=[
                  _functional_with_add_loss_and_metric,
                  _sequential_with_add_loss_and_metric,
2098
                  _functional_with_layer_reuse,
2099 2100 2101 2102 2103
              ],
              l1=[0.01],
              l2=[0.1])))
  def test_fit_and_evaluate(self, distribution, model_fn, l1, l2):
    # Make fake MNIST-like image data.
P
Philip Pham 已提交
2104
    np.random.seed(_RANDOM_SEED)
2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127
    dataset = dataset_ops.DatasetV2.from_tensor_slices(
        (np.random.uniform(size=(64, 28, 28, 1)).astype(np.float32),
         np.random.randint(0, 10, size=(64,))))
    dataset = dataset.shuffle(64).batch(
        8 * distribution.num_replicas_in_sync, drop_remainder=True)
    # Make model with distribution strategy and initialize with dataset shape.
    input_shape = dataset_ops.get_structure(dataset)[0].shape[1:]
    with distribution.scope():
      model = model_fn(input_shape, 10, l1, l2)
      model.compile(
          optimizer=keras.optimizers.adam_v2.Adam(1e-4),
          loss=keras.losses.SparseCategoricalCrossentropy(
              from_logits=True,
              reduction=loss_reduction.ReductionV2.SUM_OVER_BATCH_SIZE),
          metrics=[
              keras.metrics.SparseCategoricalAccuracy(),
              keras.metrics.SparseCategoricalCrossentropy(from_logits=True),
          ])
    # Non-eager training doesn't support steps_per_epoch=None.
    for unused_epoch in range(2):
      model.fit(dataset)
    results = dict(zip(model.metrics_names, model.evaluate(dataset)))
    # Sanity checks.
P
Philip Pham 已提交
2128
    self.assertBetween(results['sparse_categorical_accuracy'], 0.02, 1.)
2129 2130 2131 2132 2133 2134 2135 2136
    self.assertGreater(results['l2_loss'], 0.)
    self.assertGreater(results['l1_loss'], 0.)
    # Assert correctness of the loss calculation and updating of metrics.
    self.assertNear(
        results['l1_loss'] * l1 + results['l2_loss'] * l2 +
        results['sparse_categorical_crossentropy'], results['loss'], 1e-6)


2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
class DeterministicModel(keras.Model):
  """Deterministic Model that always outputs the same initial result.

  It verifies the `call` method is run inside the same distribution
  strategy that the model was initially passed.
  """

  def __init__(self, strategy):
    super(DeterministicModel, self).__init__()
    self.x = None
    self.strategy = strategy

  def build(self, input_shape):
    self.x = variables.Variable(array_ops.ones(shape=()))

  def call(self, inputs, training=None, mask=None):
    active_strategy = distribution_strategy_context.get_strategy()
    if active_strategy is not self.strategy:
      raise ValueError('Model must execute call w/ the original strategy')
    return self.x * inputs


class TestModelCapturesStrategy(test.TestCase, parameterized.TestCase):
  """Tests that model creation captures the strategy."""

  @combinations.generate(
      combinations.combine(
          distribution=strategy_combinations.all_strategies,
          mode=['eager']))
  def test_fit_and_evaluate(self, distribution):
    dataset = dataset_ops.DatasetV2.from_tensor_slices(
        (array_ops.ones(shape=(64,)), array_ops.ones(shape=(64,))))
    dataset = dataset.batch(8 * distribution.num_replicas_in_sync)
    # Make model with distribution strategy
    with distribution.scope():
      model = DeterministicModel(distribution)

    # Compile & evaluate the model outside of the distribution strategy scope
    model.compile(
        optimizer=keras.optimizers.adam_v2.Adam(1e-4),
        loss=keras.losses.MeanSquaredError(),
        metrics=['binary_accuracy'])

    # Non-eager training doesn't support steps_per_epoch=None.
    for unused_epoch in range(2):
      model.fit(dataset)

    results = model.evaluate(dataset)
    results = dict(zip(model.metrics_names, results))

    # Check that the metrics have a result we expect
    self.assertEqual(results['binary_accuracy'], 1.0)
    self.assertAllClose(results['loss'], 0.0)

    # Assert that all metric/optimizer/model variables were made in the
    # distribution strategy (Test that compile uses the captured
    # distribution strategy)
    metric_vars = nest.flatten(
        [metric.variables for metric in model.metrics])
    for var in metric_vars:
      self.assertTrue(distribution.extended.variable_created_in_scope(var))
    for var in model.optimizer._weights:
      self.assertTrue(distribution.extended.variable_created_in_scope(var))
    for var in model.variables:
      self.assertTrue(distribution.extended.variable_created_in_scope(var))

    # Make sure the metric must be created in the same scope as the model:
    # This shouldn't raise any validation errors
    with distribution.scope():
      metric = keras.metrics.BinaryAccuracy()
    model.compile(
        optimizer=keras.optimizers.adam_v2.Adam(1e-4),
        loss=keras.losses.MeanSquaredError(),
        metrics=[metric])

    # This should raise an error because the metric is constructed
    # outside of the scope, and not by compile
    if distribution_strategy_context.has_strategy():
      with self.assertRaisesRegexp(
          ValueError, 'All metrics must be created in'):
        model.compile(
            optimizer=keras.optimizers.adam_v2.Adam(1e-4),
            loss=keras.losses.MeanSquaredError(),
            metrics=[keras.metrics.BinaryAccuracy()])

2222
if __name__ == '__main__':
2223
  base_layer_utils.enable_v2_dtype_behavior()
2224
  test.main()