"vscode:/vscode.git/clone" did not exist on "6985e58938d40ad91ac07b0fddcfad8132e1447e"
ncf_keras_main.py 11.8 KB
Newer Older
Shining Sun's avatar
Shining Sun committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Copyright 2018 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.
# ==============================================================================
"""NCF framework to train and evaluate the NeuMF model.

The NeuMF model assembles both MF and MLP models under the NCF framework. Check
`neumf_model.py` for more details about the models.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os

# pylint: disable=g-bad-import-order
from absl import app as absl_app
from absl import flags
30
from absl import logging
Shining Sun's avatar
Shining Sun committed
31
32
33
34
import tensorflow as tf
# pylint: enable=g-bad-import-order

from official.datasets import movielens
35
from official.recommendation import constants as rconst
Shining Sun's avatar
Shining Sun committed
36
37
38
39
from official.recommendation import ncf_common
from official.recommendation import neumf_model
from official.utils.logs import logger
from official.utils.logs import mlperf_helper
40
from official.utils.misc import distribution_utils
41
from official.utils.misc import keras_utils
Shining Sun's avatar
Shining Sun committed
42
43
44
45
46
47
48
49
from official.utils.misc import model_helpers


FLAGS = flags.FLAGS


def _keras_loss(y_true, y_pred):
  # Here we are using the exact same loss used by the estimator
50
51
52
53
  loss = tf.keras.losses.sparse_categorical_crossentropy(
      y_pred=y_pred,
      y_true=tf.cast(y_true, tf.int32),
      from_logits=True)
Shining Sun's avatar
Shining Sun committed
54
55
56
57
58
59
60
61
62
  return loss


def _get_metric_fn(params):
  """Get the metrix fn used by model compile."""
  batch_size = params["batch_size"]

  def metric_fn(y_true, y_pred):
    """Returns the in_top_k metric."""
63
    softmax_logits = y_pred[0, :]
Shining Sun's avatar
Shining Sun committed
64
65
66
67
68
69
70
    logits = tf.slice(softmax_logits, [0, 1], [batch_size, 1])

    # The dup mask should be obtained from input data, but we did not yet find
    # a good way of getting it with keras, so we set it to zeros to neglect the
    # repetition correction
    dup_mask = tf.zeros([batch_size, 1])

71
    _, _, in_top_k, _, _ = (
Shining Sun's avatar
Shining Sun committed
72
73
74
75
76
77
78
79
        neumf_model.compute_eval_loss_and_metrics_helper(
            logits,
            softmax_logits,
            dup_mask,
            params["num_neg"],
            params["match_mlperf"],
            params["use_xla_for_gpu"]))

80
81
82
83
    is_training = tf.keras.backend.learning_phase()
    if isinstance(is_training, int):
      is_training = tf.constant(bool(is_training), dtype=tf.bool)

Shining Sun's avatar
Shining Sun committed
84
    in_top_k = tf.cond(
85
        is_training,
Shining Sun's avatar
Shining Sun committed
86
87
88
89
90
91
92
93
94
95
96
        lambda: tf.zeros(shape=in_top_k.shape, dtype=in_top_k.dtype),
        lambda: in_top_k)

    return in_top_k

  return metric_fn


def _get_train_and_eval_data(producer, params):
  """Returns the datasets for training and evalutating."""

97
98
99
100
101
102
103
104
105
106
107
108
109
  def preprocess_train_input(features, labels):
    """Pre-process the training data.

    This is needed because:
    - Distributed training does not support extra inputs. The current
      implementation does not use the VALID_POINT_MASK in the input, which makes
      it extra, so it needs to be removed.
    - The label needs to be extended to be used in the loss fn
    """
    features.pop(rconst.VALID_POINT_MASK)
    labels = tf.expand_dims(labels, -1)
    return features, labels

Shining Sun's avatar
Shining Sun committed
110
  train_input_fn = producer.make_input_fn(is_training=True)
111
112
  train_input_dataset = train_input_fn(params).map(
      preprocess_train_input)
113
114
  train_input_dataset = train_input_dataset.repeat(FLAGS.train_epochs)

Shining Sun's avatar
Shining Sun committed
115
  def preprocess_eval_input(features):
116
117
118
119
120
121
122
123
124
    """Pre-process the eval data.

    This is needed because:
    - Distributed training does not support extra inputs. The current
      implementation does not use the DUPLICATE_MASK in the input, which makes
      it extra, so it needs to be removed.
    - The label needs to be extended to be used in the loss fn
    """
    features.pop(rconst.DUPLICATE_MASK)
Shining Sun's avatar
Shining Sun committed
125
    labels = tf.zeros_like(features[movielens.USER_COLUMN])
126
    labels = tf.expand_dims(labels, -1)
Shining Sun's avatar
Shining Sun committed
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
    return features, labels

  eval_input_fn = producer.make_input_fn(is_training=False)
  eval_input_dataset = eval_input_fn(params).map(
      lambda features: preprocess_eval_input(features))

  return train_input_dataset, eval_input_dataset


class IncrementEpochCallback(tf.keras.callbacks.Callback):
  """A callback to increase the requested epoch for the data producer.

  The reason why we need this is because we can only buffer a limited amount of
  data. So we keep a moving window to represent the buffer. This is to move the
  one of the window's boundaries for each epoch.
  """

  def __init__(self, producer):
    self._producer = producer

  def on_epoch_begin(self, epoch, logs=None):
    self._producer.increment_request_epoch()


151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
class CustomEarlyStopping(tf.keras.callbacks.Callback):
  """Stop training has reached a desired hit rate."""

  def __init__(self, monitor, desired_value):
    super(CustomEarlyStopping, self).__init__()

    self.monitor = monitor
    self.desired = desired_value

  def on_epoch_end(self, epoch, logs=None):
    current = self.get_monitor_value(logs)
    if current and current >= self.desired:
      self.stopped_epoch = epoch
      self.model.stop_training = True

  def on_train_end(self, logs=None):
    if self.stopped_epoch > 0:
      print('Epoch %05d: early stopping' % (self.stopped_epoch + 1))

  def get_monitor_value(self, logs):
    logs = logs or {}
    monitor_value = logs.get(self.monitor)
    if monitor_value is None:
      logging.warning('Early stopping conditioned on metric `%s` '
                      'which is not available. Available metrics are: %s',
                      self.monitor, ','.join(list(logs.keys())))
    return monitor_value


Shining Sun's avatar
Shining Sun committed
180
181
182
183
def _get_keras_model(params):
  """Constructs and returns the model."""
  batch_size = params['batch_size']

184
185
186
187
  # The input layers are of shape (1, batch_size), to match the size of the
  # input data. The first dimension is needed because the input data are
  # required to be batched to use distribution strategies, and in this case, it
  # is designed to be of batch_size 1 for each replica.
Shining Sun's avatar
Shining Sun committed
188
  user_input = tf.keras.layers.Input(
189
      shape=(batch_size,),
190
      batch_size=params["batches_per_step"],
Shining Sun's avatar
Shining Sun committed
191
      name=movielens.USER_COLUMN,
192
      dtype=tf.int32)
Shining Sun's avatar
Shining Sun committed
193
194

  item_input = tf.keras.layers.Input(
195
      shape=(batch_size,),
196
      batch_size=params["batches_per_step"],
Shining Sun's avatar
Shining Sun committed
197
      name=movielens.ITEM_COLUMN,
198
199
200
201
      dtype=tf.int32)

  base_model = neumf_model.construct_model(
      user_input, item_input, params, need_strip=True)
Shining Sun's avatar
Shining Sun committed
202
203
204

  base_model_output = base_model.output

205
206
207
208
  logits = tf.keras.layers.Lambda(
      lambda x: tf.expand_dims(x, 0),
      name="logits")(base_model_output)

Shining Sun's avatar
Shining Sun committed
209
  zeros = tf.keras.layers.Lambda(
210
      lambda x: x * 0)(logits)
Shining Sun's avatar
Shining Sun committed
211
212

  softmax_logits = tf.keras.layers.concatenate(
213
      [zeros, logits],
Shining Sun's avatar
Shining Sun committed
214
215
216
217
218
219
220
221
222
223
224
225
      axis=-1)

  keras_model = tf.keras.Model(
      inputs=[user_input, item_input],
      outputs=softmax_logits)

  keras_model.summary()
  return keras_model


def run_ncf(_):
  """Run NCF training and eval with Keras."""
Shining Sun's avatar
Shining Sun committed
226
227
  # TODO(seemuch): Support different train and eval batch sizes
  if FLAGS.eval_batch_size != FLAGS.batch_size:
228
    logging.warning(
Shining Sun's avatar
Shining Sun committed
229
230
231
232
233
234
        "The Keras implementation of NCF currently does not support batch_size "
        "!= eval_batch_size ({} vs. {}). Overriding eval_batch_size to match "
        "batch_size".format(FLAGS.eval_batch_size, FLAGS.batch_size)
        )
    FLAGS.eval_batch_size = FLAGS.batch_size

Shining Sun's avatar
Shining Sun committed
235
  params = ncf_common.parse_flags(FLAGS)
236
  batch_size = params["batch_size"]
Shining Sun's avatar
Shining Sun committed
237

Shining Sun's avatar
Shining Sun committed
238
239
240
241
  # ncf_common rounds eval_batch_size (this is needed due to a reshape during
  # eval). This carries over that rounding to batch_size as well.
  params['batch_size'] = params['eval_batch_size']

Shining Sun's avatar
Shining Sun committed
242
243
244
245
246
247
248
  num_users, num_items, num_train_steps, num_eval_steps, producer = (
      ncf_common.get_inputs(params))

  params["num_users"], params["num_items"] = num_users, num_items
  producer.start()
  model_helpers.apply_clean(flags.FLAGS)

249
250
251
252
253
254
255
256
257
  batches_per_step = params["batches_per_step"]
  train_input_dataset, eval_input_dataset = _get_train_and_eval_data(producer,
                                                                     params)
  # It is required that for distributed training, the dataset must call
  # batch(). The parameter of batch() here is the number of replicas involed,
  # such that each replica evenly gets a slice of data.
  train_input_dataset = train_input_dataset.batch(batches_per_step)
  eval_input_dataset = eval_input_dataset.batch(batches_per_step)

258
259
260
261
262
263
264
265
266
  time_callback = keras_utils.TimeHistory(batch_size, FLAGS.log_steps)
  callbacks = [
      IncrementEpochCallback(producer), time_callback]

  if FLAGS.early_stopping:
    early_stopping_callback = CustomEarlyStopping(
        "val_metric_fn", desired_value=FLAGS.hr_threshold)
    callbacks.append(early_stopping_callback)

267
268
269
  strategy = ncf_common.get_distribution_strategy(params)
  with distribution_utils.get_strategy_scope(strategy):
    keras_model = _get_keras_model(params)
270
271
272
273
274
    optimizer = tf.keras.optimizers.Adam(
        learning_rate=params["learning_rate"],
        beta_1=params["beta1"],
        beta_2=params["beta2"],
        epsilon=params["epsilon"])
275
276
277
278
279
    time_callback = keras_utils.TimeHistory(batch_size, FLAGS.log_steps)

    keras_model.compile(
        loss=_keras_loss,
        metrics=[_get_metric_fn(params)],
280
281
        optimizer=optimizer,
        cloning=params["clone_model_in_keras_dist_strat"])
282
283

    history = keras_model.fit(train_input_dataset,
284
                              steps_per_epoch=num_train_steps,
285
                              epochs=FLAGS.train_epochs,
286
                              callbacks=callbacks,
287
288
                              validation_data=eval_input_dataset,
                              validation_steps=num_eval_steps,
289
290
                              verbose=2)

291
    logging.info("Training done. Start evaluating")
292
293
294
295
296

    eval_results = keras_model.evaluate(
        eval_input_dataset,
        steps=num_eval_steps,
        verbose=2)
Shining Sun's avatar
Shining Sun committed
297

298
  logging.info("Keras evaluation is done.")
Shining Sun's avatar
Shining Sun committed
299

300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
  stats = build_stats(history, eval_results, time_callback)
  return stats


def build_stats(history, eval_result, time_callback):
  """Normalizes and returns dictionary of stats.

    Args:
      history: Results of the training step. Supports both categorical_accuracy
        and sparse_categorical_accuracy.
      eval_output: Output of the eval step. Assumes first value is eval_loss and
        second value is accuracy_top_1.
      time_callback: Time tracking callback likely used during keras.fit.
    Returns:
      Dictionary of normalized results.
  """
  stats = {}
  if history and history.history:
    train_history = history.history
    stats['loss'] = train_history['loss'][-1]

  if eval_result:
    stats['eval_loss'] = eval_result[0]
    stats['eval_hit_rate'] = eval_result[1]

  if time_callback:
    timestamp_log = time_callback.timestamp_log
    stats['step_timestamp_log'] = timestamp_log
    stats['train_finish_time'] = time_callback.train_finish_time
    if len(timestamp_log) > 1:
      stats['avg_exp_per_second'] = (
          time_callback.batch_size * time_callback.log_steps *
          (len(time_callback.timestamp_log)-1) /
          (timestamp_log[-1].timestamp - timestamp_log[0].timestamp))

  return stats
Shining Sun's avatar
Shining Sun committed
336
337
338
339
340
341
342
343
344
345
346
347
348
349


def main(_):
  with logger.benchmark_context(FLAGS), \
      mlperf_helper.LOGGER(FLAGS.output_ml_perf_compliance_logging):
    mlperf_helper.set_ncf_root(os.path.split(os.path.abspath(__file__))[0])
    if FLAGS.tpu:
      raise ValueError("NCF in Keras does not support TPU for now")
    run_ncf(FLAGS)


if __name__ == "__main__":
  ncf_common.define_ncf_flags()
  absl_app.run(main)