data_pipeline.py 36.3 KB
Newer Older
Frederick Liu's avatar
Frederick Liu committed
1
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
2
3
4
5
6
7
8
9
10
11
12
13
#
# 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.
Frederick Liu's avatar
Frederick Liu committed
14

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"""Asynchronous data producer for the NCF pipeline."""

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

import atexit
import functools
import os
import sys
import tempfile
import threading
import time
import timeit
import traceback
Taylor Robie's avatar
Taylor Robie committed
30
import typing
31

32
from absl import logging
33
34
35
36
import numpy as np
from six.moves import queue
import tensorflow as tf

37
from tensorflow.python.tpu.datasets import StreamingFilesDataset
38
from official.recommendation import constants as rconst
39
from official.recommendation import movielens
Hongkun Yu's avatar
Hongkun Yu committed
40
from official.recommendation import popen_helper
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from official.recommendation import stat_utils

SUMMARY_TEMPLATE = """General:
{spacer}Num users: {num_users}
{spacer}Num items: {num_items}

Training:
{spacer}Positive count:          {train_pos_ct}
{spacer}Batch size:              {train_batch_size} {multiplier}
{spacer}Batch count per epoch:   {train_batch_ct}

Eval:
{spacer}Positive count:          {eval_pos_ct}
{spacer}Batch size:              {eval_batch_size} {multiplier}
{spacer}Batch count per epoch:   {eval_batch_ct}"""


class DatasetManager(object):
  """Helper class for handling TensorFlow specific data tasks.

  This class takes the (relatively) framework agnostic work done by the data
  constructor classes and handles the TensorFlow specific portions (TFRecord
  management, tf.Dataset creation, etc.).
  """
65
66
67
68
69
70
71
72
73

  def __init__(self,
               is_training,
               stream_files,
               batches_per_epoch,
               shard_root=None,
               deterministic=False,
               num_train_epochs=None):
    # type: (bool, bool, int, typing.Optional[str], bool, int) -> None
Taylor Robie's avatar
Taylor Robie committed
74
    """Constructs a `DatasetManager` instance.
Hongkun Yu's avatar
Hongkun Yu committed
75

Taylor Robie's avatar
Taylor Robie committed
76
77
    Args:
      is_training: Boolean of whether the data provided is training or
Hongkun Yu's avatar
Hongkun Yu committed
78
79
        evaluation data. This determines whether to reuse the data (if
        is_training=False) and the exact structure to use when storing and
Taylor Robie's avatar
Taylor Robie committed
80
81
82
83
84
        yielding data.
      stream_files: Boolean indicating whether data should be serialized and
        written to file shards.
      batches_per_epoch: The number of batches in a single epoch.
      shard_root: The base directory to be used when stream_files=True.
85
      deterministic: Forgo non-deterministic speedups. (i.e. sloppy=True)
Hongkun Yu's avatar
Hongkun Yu committed
86
87
      num_train_epochs: Number of epochs to generate. If None, then each call to
        `get_dataset()` increments the number of epochs requested.
Taylor Robie's avatar
Taylor Robie committed
88
    """
89
    self._is_training = is_training
90
    self._deterministic = deterministic
91
92
    self._stream_files = stream_files
    self._writers = []
Hongkun Yu's avatar
Hongkun Yu committed
93
94
95
    self._write_locks = [
        threading.RLock() for _ in range(rconst.NUM_FILE_SHARDS)
    ] if stream_files else []
96
97
    self._batches_per_epoch = batches_per_epoch
    self._epochs_completed = 0
98
    self._epochs_requested = num_train_epochs if num_train_epochs else 0
99
100
101
102
103
104
105
    self._shard_root = shard_root

    self._result_queue = queue.Queue()
    self._result_reuse = []

  @property
  def current_data_root(self):
Hongkun Yu's avatar
Hongkun Yu committed
106
107
108
    subdir = (
        rconst.TRAIN_FOLDER_TEMPLATE.format(self._epochs_completed)
        if self._is_training else rconst.EVAL_FOLDER)
109
110
111
112
113
114
115
116
    return os.path.join(self._shard_root, subdir)

  def buffer_reached(self):
    # Only applicable for training.
    return (self._epochs_completed - self._epochs_requested >=
            rconst.CYCLES_TO_BUFFER and self._is_training)

  @staticmethod
117
  def serialize(data):
118
119
    """Convert NumPy arrays into a TFRecords entry."""

120
    def create_int_feature(values):
121
      values = np.squeeze(values)
122
123
      return tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))

124
    feature_dict = {
125
126
        k: create_int_feature(v.astype(np.int64)) for k, v in data.items()
    }
127

Hongkun Yu's avatar
Hongkun Yu committed
128
129
    return tf.train.Example(features=tf.train.Features(
        feature=feature_dict)).SerializeToString()
130

131
132
  @staticmethod
  def deserialize(serialized_data, batch_size=None, is_training=True):
133
134
135
136
137
138
    """Convert serialized TFRecords into tensors.

    Args:
      serialized_data: A tensor containing serialized records.
      batch_size: The data arrives pre-batched, so batch size is needed to
        deserialize the data.
Hongkun Yu's avatar
Hongkun Yu committed
139
140
      is_training: Boolean, whether data to deserialize to training data or
        evaluation data.
141
142
    """

143
144
145
146
147
148
    def _get_feature_map(batch_size, is_training=True):
      """Returns data format of the serialized tf record file."""

      if is_training:
        return {
            movielens.USER_COLUMN:
149
                tf.io.FixedLenFeature([batch_size, 1], dtype=tf.int64),
150
            movielens.ITEM_COLUMN:
151
                tf.io.FixedLenFeature([batch_size, 1], dtype=tf.int64),
152
            rconst.VALID_POINT_MASK:
153
                tf.io.FixedLenFeature([batch_size, 1], dtype=tf.int64),
154
            "labels":
155
                tf.io.FixedLenFeature([batch_size, 1], dtype=tf.int64)
156
157
158
159
        }
      else:
        return {
            movielens.USER_COLUMN:
160
                tf.io.FixedLenFeature([batch_size, 1], dtype=tf.int64),
161
            movielens.ITEM_COLUMN:
162
                tf.io.FixedLenFeature([batch_size, 1], dtype=tf.int64),
163
            rconst.DUPLICATE_MASK:
164
                tf.io.FixedLenFeature([batch_size, 1], dtype=tf.int64)
165
166
        }

167
    features = tf.io.parse_single_example(
168
        serialized_data, _get_feature_map(batch_size, is_training=is_training))
169
170
    users = tf.cast(features[movielens.USER_COLUMN], rconst.USER_DTYPE)
    items = tf.cast(features[movielens.ITEM_COLUMN], rconst.ITEM_DTYPE)
171

172
    if is_training:
173
174
      valid_point_mask = tf.cast(features[rconst.VALID_POINT_MASK], tf.bool)
      fake_dup_mask = tf.zeros_like(users)
175
      return {
Hongkun Yu's avatar
Hongkun Yu committed
176
177
178
179
180
181
          movielens.USER_COLUMN:
              users,
          movielens.ITEM_COLUMN:
              items,
          rconst.VALID_POINT_MASK:
              valid_point_mask,
182
          rconst.TRAIN_LABEL_KEY:
Hongkun Yu's avatar
Hongkun Yu committed
183
184
185
              tf.reshape(tf.cast(features["labels"], tf.bool), (batch_size, 1)),
          rconst.DUPLICATE_MASK:
              fake_dup_mask
186
187
      }
    else:
188
189
      labels = tf.cast(tf.zeros_like(users), tf.bool)
      fake_valid_pt_mask = tf.cast(tf.zeros_like(users), tf.bool)
190
191
192
193
194
195
      return {
          movielens.USER_COLUMN:
              users,
          movielens.ITEM_COLUMN:
              items,
          rconst.DUPLICATE_MASK:
196
              tf.cast(features[rconst.DUPLICATE_MASK], tf.bool),
197
198
199
200
201
          rconst.VALID_POINT_MASK:
              fake_valid_pt_mask,
          rconst.TRAIN_LABEL_KEY:
              labels
      }
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216

  def put(self, index, data):
    # type: (int, dict) -> None
    """Store data for later consumption.

    Because there are several paths for storing and yielding data (queues,
    lists, files) the data producer simply provides the data in a standard
    format at which point the dataset manager handles storing it in the correct
    form.

    Args:
      index: Used to select shards when writing to files.
      data: A dict of the data to be stored. This method mutates data, and
        therefore expects to be the only consumer.
    """
217
218
219
    if self._is_training:
      mask_start_index = data.pop(rconst.MASK_START_INDEX)
      batch_size = data[movielens.ITEM_COLUMN].shape[0]
220
221
      data[rconst.VALID_POINT_MASK] = np.expand_dims(
          np.less(np.arange(batch_size), mask_start_index), -1)
222
223

    if self._stream_files:
224
      example_bytes = self.serialize(data)
225
226
227
228
      with self._write_locks[index % rconst.NUM_FILE_SHARDS]:
        self._writers[index % rconst.NUM_FILE_SHARDS].write(example_bytes)

    else:
229
230
      self._result_queue.put((
          data, data.pop("labels")) if self._is_training else data)
231
232
233

  def start_construction(self):
    if self._stream_files:
234
      tf.io.gfile.makedirs(self.current_data_root)
235
      template = os.path.join(self.current_data_root, rconst.SHARD_TEMPLATE)
Hongkun Yu's avatar
Hongkun Yu committed
236
237
238
239
      self._writers = [
          tf.io.TFRecordWriter(template.format(i))
          for i in range(rconst.NUM_FILE_SHARDS)
      ]
240
241
242
243
244
245
246
247
248
249
250
251

  def end_construction(self):
    if self._stream_files:
      [writer.close() for writer in self._writers]
      self._writers = []
      self._result_queue.put(self.current_data_root)

    self._epochs_completed += 1

  def data_generator(self, epochs_between_evals):
    """Yields examples during local training."""
    assert not self._stream_files
Taylor Robie's avatar
Taylor Robie committed
252
    assert self._is_training or epochs_between_evals == 1
253
254
255
256
257
258

    if self._is_training:
      for _ in range(self._batches_per_epoch * epochs_between_evals):
        yield self._result_queue.get(timeout=300)

    else:
Taylor Robie's avatar
Taylor Robie committed
259
260
261
262
263
264
265
266
267
268
269
270
      if self._result_reuse:
        assert len(self._result_reuse) == self._batches_per_epoch

        for i in self._result_reuse:
          yield i
      else:
        # First epoch.
        for _ in range(self._batches_per_epoch * epochs_between_evals):
          result = self._result_queue.get(timeout=300)
          self._result_reuse.append(result)
          yield result

Shining Sun's avatar
Shining Sun committed
271
272
  def increment_request_epoch(self):
    self._epochs_requested += 1
273
274
275
276
277
278
279
280
281

  def get_dataset(self, batch_size, epochs_between_evals):
    """Construct the dataset to be used for training and eval.

    For local training, data is provided through Dataset.from_generator. For
    remote training (TPUs) the data is first serialized to files and then sent
    to the TPU through a StreamingFilesDataset.

    Args:
282
      batch_size: The per-replica batch size of the dataset.
Hongkun Yu's avatar
Hongkun Yu committed
283
284
      epochs_between_evals: How many epochs worth of data to yield. (Generator
        mode only.)
285
    """
Shining Sun's avatar
Shining Sun committed
286
    self.increment_request_epoch()
287
288
289
290
291
292
293
294
    if self._stream_files:
      if epochs_between_evals > 1:
        raise ValueError("epochs_between_evals > 1 not supported for file "
                         "based dataset.")
      epoch_data_dir = self._result_queue.get(timeout=300)
      if not self._is_training:
        self._result_queue.put(epoch_data_dir)  # Eval data is reused.

Hongkun Yu's avatar
Hongkun Yu committed
295
296
      file_pattern = os.path.join(epoch_data_dir,
                                  rconst.SHARD_TEMPLATE.format("*"))
297
      dataset = StreamingFilesDataset(
Hongkun Yu's avatar
Hongkun Yu committed
298
299
300
301
          files=file_pattern,
          worker_job=popen_helper.worker_job(),
          num_parallel_reads=rconst.NUM_FILE_SHARDS,
          num_epochs=1,
302
          sloppy=not self._deterministic)
303
304
305
306
      map_fn = functools.partial(
          self.deserialize,
          batch_size=batch_size,
          is_training=self._is_training)
307
308
309
      dataset = dataset.map(map_fn, num_parallel_calls=16)

    else:
Hongkun Yu's avatar
Hongkun Yu committed
310
311
312
313
      types = {
          movielens.USER_COLUMN: rconst.USER_DTYPE,
          movielens.ITEM_COLUMN: rconst.ITEM_DTYPE
      }
314
315
316
317
      shapes = {
          movielens.USER_COLUMN: tf.TensorShape([batch_size, 1]),
          movielens.ITEM_COLUMN: tf.TensorShape([batch_size, 1])
      }
318
319
320

      if self._is_training:
        types[rconst.VALID_POINT_MASK] = np.bool
321
        shapes[rconst.VALID_POINT_MASK] = tf.TensorShape([batch_size, 1])
322
323

        types = (types, np.bool)
324
        shapes = (shapes, tf.TensorShape([batch_size, 1]))
325
326
327

      else:
        types[rconst.DUPLICATE_MASK] = np.bool
328
        shapes[rconst.DUPLICATE_MASK] = tf.TensorShape([batch_size, 1])
329
330
331
332

      data_generator = functools.partial(
          self.data_generator, epochs_between_evals=epochs_between_evals)
      dataset = tf.data.Dataset.from_generator(
Hongkun Yu's avatar
Hongkun Yu committed
333
          generator=data_generator, output_types=types, output_shapes=shapes)
334
335
336
337
338
339
340

    return dataset.prefetch(16)

  def make_input_fn(self, batch_size):
    """Create an input_fn which checks for batch size consistency."""

    def input_fn(params):
341
342
343
      """Returns batches for training."""

      # Estimator passes batch_size during training and eval_batch_size during
344
      # eval.
Hongkun Yu's avatar
Hongkun Yu committed
345
346
347
      param_batch_size = (
          params["batch_size"] if self._is_training else
          params.get("eval_batch_size") or params["batch_size"])
348
349
350
351
      if batch_size != param_batch_size:
        raise ValueError("producer batch size ({}) differs from params batch "
                         "size ({})".format(batch_size, param_batch_size))

Hongkun Yu's avatar
Hongkun Yu committed
352
353
354
355
      epochs_between_evals = (
          params.get("epochs_between_evals", 1) if self._is_training else 1)
      return self.get_dataset(
          batch_size=batch_size, epochs_between_evals=epochs_between_evals)
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370

    return input_fn


class BaseDataConstructor(threading.Thread):
  """Data constructor base class.

  This class manages the control flow for constructing data. It is not meant
  to be used directly, but instead subclasses should implement the following
  two methods:

    self.construct_lookup_variables
    self.lookup_negative_items

  """
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393

  def __init__(
      self,
      maximum_number_epochs,  # type: int
      num_users,  # type: int
      num_items,  # type: int
      user_map,  # type: dict
      item_map,  # type: dict
      train_pos_users,  # type: np.ndarray
      train_pos_items,  # type: np.ndarray
      train_batch_size,  # type: int
      batches_per_train_step,  # type: int
      num_train_negatives,  # type: int
      eval_pos_users,  # type: np.ndarray
      eval_pos_items,  # type: np.ndarray
      eval_batch_size,  # type: int
      batches_per_eval_step,  # type: int
      stream_files,  # type: bool
      deterministic=False,  # type: bool
      epoch_dir=None,  # type: str
      num_train_epochs=None,  # type: int
      create_data_offline=False  # type: bool
  ):
394
395
396
397
398
399
400
401
402
403
404
405
406
407
    # General constants
    self._maximum_number_epochs = maximum_number_epochs
    self._num_users = num_users
    self._num_items = num_items
    self.user_map = user_map
    self.item_map = item_map
    self._train_pos_users = train_pos_users
    self._train_pos_items = train_pos_items
    self.train_batch_size = train_batch_size
    self._num_train_negatives = num_train_negatives
    self._batches_per_train_step = batches_per_train_step
    self._eval_pos_users = eval_pos_users
    self._eval_pos_items = eval_pos_items
    self.eval_batch_size = eval_batch_size
408
409
    self.num_train_epochs = num_train_epochs
    self.create_data_offline = create_data_offline
410
411
412
413
414
415
416

    # Training
    if self._train_pos_users.shape != self._train_pos_items.shape:
      raise ValueError(
          "User positives ({}) is different from item positives ({})".format(
              self._train_pos_users.shape, self._train_pos_items.shape))

Taylor Robie's avatar
Taylor Robie committed
417
    (self._train_pos_count,) = self._train_pos_users.shape
418
    self._elements_in_epoch = (1 + num_train_negatives) * self._train_pos_count
Hongkun Yu's avatar
Hongkun Yu committed
419
420
421
    self.train_batches_per_epoch = self._count_batches(self._elements_in_epoch,
                                                       train_batch_size,
                                                       batches_per_train_step)
422
423
424
425
426

    # Evaluation
    if eval_batch_size % (1 + rconst.NUM_EVAL_NEGATIVES):
      raise ValueError("Eval batch size {} is not divisible by {}".format(
          eval_batch_size, 1 + rconst.NUM_EVAL_NEGATIVES))
Hongkun Yu's avatar
Hongkun Yu committed
427
428
    self._eval_users_per_batch = int(eval_batch_size //
                                     (1 + rconst.NUM_EVAL_NEGATIVES))
429
430
431
432
433
434
435
436
    self._eval_elements_in_epoch = num_users * (1 + rconst.NUM_EVAL_NEGATIVES)
    self.eval_batches_per_epoch = self._count_batches(
        self._eval_elements_in_epoch, eval_batch_size, batches_per_eval_step)

    # Intermediate artifacts
    self._current_epoch_order = np.empty(shape=(0,))
    self._shuffle_iterator = None

Taylor Robie's avatar
Taylor Robie committed
437
    self._shuffle_with_forkpool = not stream_files
438
    if stream_files:
439
      self._shard_root = epoch_dir or tempfile.mkdtemp(prefix="ncf_")
Bruce Fontaine's avatar
Bruce Fontaine committed
440
441
      if not create_data_offline:
        atexit.register(tf.io.gfile.rmtree, self._shard_root)
442
443
444
    else:
      self._shard_root = None

445
446
447
448
449
450
451
452
    self._train_dataset = DatasetManager(True, stream_files,
                                         self.train_batches_per_epoch,
                                         self._shard_root, deterministic,
                                         num_train_epochs)
    self._eval_dataset = DatasetManager(False, stream_files,
                                        self.eval_batches_per_epoch,
                                        self._shard_root, deterministic,
                                        num_train_epochs)
453
454
455
456
457
458

    # Threading details
    super(BaseDataConstructor, self).__init__()
    self.daemon = True
    self._stop_loop = False
    self._fatal_exception = None
459
    self.deterministic = deterministic
460

Taylor Robie's avatar
Taylor Robie committed
461
  def __str__(self):
462
463
464
    multiplier = ("(x{} devices)".format(self._batches_per_train_step)
                  if self._batches_per_train_step > 1 else "")
    summary = SUMMARY_TEMPLATE.format(
Hongkun Yu's avatar
Hongkun Yu committed
465
466
467
        spacer="  ",
        num_users=self._num_users,
        num_items=self._num_items,
468
469
470
        train_pos_ct=self._train_pos_count,
        train_batch_size=self.train_batch_size,
        train_batch_ct=self.train_batches_per_epoch,
Hongkun Yu's avatar
Hongkun Yu committed
471
472
473
474
        eval_pos_ct=self._num_users,
        eval_batch_size=self.eval_batch_size,
        eval_batch_ct=self.eval_batches_per_epoch,
        multiplier=multiplier)
Taylor Robie's avatar
Taylor Robie committed
475
    return super(BaseDataConstructor, self).__str__() + "\n" + summary
476
477
478

  @staticmethod
  def _count_batches(example_count, batch_size, batches_per_step):
Taylor Robie's avatar
Taylor Robie committed
479
    """Determine the number of batches, rounding up to fill all devices."""
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
    x = (example_count + batch_size - 1) // batch_size
    return (x + batches_per_step - 1) // batches_per_step * batches_per_step

  def stop_loop(self):
    self._stop_loop = True

  def construct_lookup_variables(self):
    """Perform any one time pre-compute work."""
    raise NotImplementedError

  def lookup_negative_items(self, **kwargs):
    """Randomly sample negative items for given users."""
    raise NotImplementedError

  def _run(self):
    atexit.register(self.stop_loop)
    self._start_shuffle_iterator()
    self.construct_lookup_variables()
    self._construct_training_epoch()
    self._construct_eval_epoch()
    for _ in range(self._maximum_number_epochs - 1):
      self._construct_training_epoch()
502
    self.stop_loop()
503
504
505
506
507
508
509

  def run(self):
    try:
      self._run()
    except Exception as e:
      # The Thread base class swallows stack traces, so unfortunately it is
      # necessary to catch and re-raise to get debug output
Taylor Robie's avatar
Taylor Robie committed
510
      traceback.print_exc()
511
512
513
514
515
      self._fatal_exception = e
      sys.stderr.flush()
      raise

  def _start_shuffle_iterator(self):
516
517
518
519
    if self._shuffle_with_forkpool:
      pool = popen_helper.get_forkpool(3, closing=False)
    else:
      pool = popen_helper.get_threadpool(1, closing=False)
520
521
522
    atexit.register(pool.close)
    args = [(self._elements_in_epoch, stat_utils.random_int32())
            for _ in range(self._maximum_number_epochs)]
523
524
    imap = pool.imap if self.deterministic else pool.imap_unordered
    self._shuffle_iterator = imap(stat_utils.permutation, args)
525
526
527
528
529
530
531
532

  def _get_training_batch(self, i):
    """Construct a single batch of training data.

    Args:
      i: The index of the batch. This is used when stream_files=True to assign
        data to file shards.
    """
Hongkun Yu's avatar
Hongkun Yu committed
533
534
535
    batch_indices = self._current_epoch_order[i *
                                              self.train_batch_size:(i + 1) *
                                              self.train_batch_size]
Taylor Robie's avatar
Taylor Robie committed
536
    (mask_start_index,) = batch_indices.shape
537
538
539
540
541
542
543
544
545
546
547
548

    batch_ind_mod = np.mod(batch_indices, self._train_pos_count)
    users = self._train_pos_users[batch_ind_mod]

    negative_indices = np.greater_equal(batch_indices, self._train_pos_count)
    negative_users = users[negative_indices]

    negative_items = self.lookup_negative_items(negative_users=negative_users)

    items = self._train_pos_items[batch_ind_mod]
    items[negative_indices] = negative_items

Taylor Robie's avatar
Taylor Robie committed
549
    labels = np.logical_not(negative_indices)
550
551
552
553
554
555
556
557
558
559
560
561
562
563

    # Pad last partial batch
    pad_length = self.train_batch_size - mask_start_index
    if pad_length:
      # We pad with arange rather than zeros because the network will still
      # compute logits for padded examples, and padding with zeros would create
      # a very "hot" embedding key which can have performance implications.
      user_pad = np.arange(pad_length, dtype=users.dtype) % self._num_users
      item_pad = np.arange(pad_length, dtype=items.dtype) % self._num_items
      label_pad = np.zeros(shape=(pad_length,), dtype=labels.dtype)
      users = np.concatenate([users, user_pad])
      items = np.concatenate([items, item_pad])
      labels = np.concatenate([labels, label_pad])

564
565
566
567
568
569
570
571
572
573
574
    self._train_dataset.put(
        i, {
            movielens.USER_COLUMN:
                np.reshape(users, (self.train_batch_size, 1)),
            movielens.ITEM_COLUMN:
                np.reshape(items, (self.train_batch_size, 1)),
            rconst.MASK_START_INDEX:
                np.array(mask_start_index, dtype=np.int32),
            "labels":
                np.reshape(labels, (self.train_batch_size, 1)),
        })
575
576
577
578
579
580
581

  def _wait_to_construct_train_epoch(self):
    count = 0
    while self._train_dataset.buffer_reached() and not self._stop_loop:
      time.sleep(0.01)
      count += 1
      if count >= 100 and np.log10(count) == np.round(np.log10(count)):
582
        logging.info(
583
584
585
586
            "Waited {} times for training data to be consumed".format(count))

  def _construct_training_epoch(self):
    """Loop to construct a batch of training data."""
587
588
589
    if not self.create_data_offline:
      self._wait_to_construct_train_epoch()

590
591
592
593
594
595
    start_time = timeit.default_timer()
    if self._stop_loop:
      return

    self._train_dataset.start_construction()
    map_args = list(range(self.train_batches_per_epoch))
Taylor Robie's avatar
Taylor Robie committed
596
    self._current_epoch_order = next(self._shuffle_iterator)
597

Hongkun Yu's avatar
Hongkun Yu committed
598
599
600
    get_pool = (
        popen_helper.get_fauxpool
        if self.deterministic else popen_helper.get_threadpool)
601
    with get_pool(6) as pool:
602
603
604
      pool.map(self._get_training_batch, map_args)
    self._train_dataset.end_construction()

605
    logging.info("Epoch construction complete. Time: {:.1f} seconds".format(
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
        timeit.default_timer() - start_time))

  @staticmethod
  def _assemble_eval_batch(users, positive_items, negative_items,
                           users_per_batch):
    """Construct duplicate_mask and structure data accordingly.

    The positive items should be last so that they lose ties. However, they
    should not be masked out if the true eval positive happens to be
    selected as a negative. So instead, the positive is placed in the first
    position, and then switched with the last element after the duplicate
    mask has been computed.

    Args:
      users: An array of users in a batch. (should be identical along axis 1)
      positive_items: An array (batch_size x 1) of positive item indices.
      negative_items: An array of negative item indices.
Hongkun Yu's avatar
Hongkun Yu committed
623
624
      users_per_batch: How many users should be in the batch. This is passed as
        an argument so that ncf_test.py can use this method.
625
626
627
628
629
630
631

    Returns:
      User, item, and duplicate_mask arrays.
    """
    items = np.concatenate([positive_items, negative_items], axis=1)

    # We pad the users and items here so that the duplicate mask calculation
Taylor Robie's avatar
Taylor Robie committed
632
    # will include padding. The metric function relies on all padded elements
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
    # except the positive being marked as duplicate to mask out padded points.
    if users.shape[0] < users_per_batch:
      pad_rows = users_per_batch - users.shape[0]
      padding = np.zeros(shape=(pad_rows, users.shape[1]), dtype=np.int32)
      users = np.concatenate([users, padding.astype(users.dtype)], axis=0)
      items = np.concatenate([items, padding.astype(items.dtype)], axis=0)

    duplicate_mask = stat_utils.mask_duplicates(items, axis=1).astype(np.bool)

    items[:, (0, -1)] = items[:, (-1, 0)]
    duplicate_mask[:, (0, -1)] = duplicate_mask[:, (-1, 0)]

    assert users.shape == items.shape == duplicate_mask.shape
    return users, items, duplicate_mask

  def _get_eval_batch(self, i):
    """Construct a single batch of evaluation data.

    Args:
      i: The index of the batch.
    """
    low_index = i * self._eval_users_per_batch
    high_index = (i + 1) * self._eval_users_per_batch
Hongkun Yu's avatar
Hongkun Yu committed
656
657
658
659
    users = np.repeat(
        self._eval_pos_users[low_index:high_index, np.newaxis],
        1 + rconst.NUM_EVAL_NEGATIVES,
        axis=1)
660
    positive_items = self._eval_pos_items[low_index:high_index, np.newaxis]
Hongkun Yu's avatar
Hongkun Yu committed
661
662
663
    negative_items = (
        self.lookup_negative_items(negative_users=users[:, :-1]).reshape(
            -1, rconst.NUM_EVAL_NEGATIVES))
664
665
666
667

    users, items, duplicate_mask = self._assemble_eval_batch(
        users, positive_items, negative_items, self._eval_users_per_batch)

668
669
670
671
672
673
674
675
676
    self._eval_dataset.put(
        i, {
            movielens.USER_COLUMN:
                np.reshape(users.flatten(), (self.eval_batch_size, 1)),
            movielens.ITEM_COLUMN:
                np.reshape(items.flatten(), (self.eval_batch_size, 1)),
            rconst.DUPLICATE_MASK:
                np.reshape(duplicate_mask.flatten(), (self.eval_batch_size, 1)),
        })
677
678
679
680
681
682
683
684
685
686

  def _construct_eval_epoch(self):
    """Loop to construct data for evaluation."""
    if self._stop_loop:
      return

    start_time = timeit.default_timer()

    self._eval_dataset.start_construction()
    map_args = [i for i in range(self.eval_batches_per_epoch)]
687

Hongkun Yu's avatar
Hongkun Yu committed
688
689
690
    get_pool = (
        popen_helper.get_fauxpool
        if self.deterministic else popen_helper.get_threadpool)
691
    with get_pool(6) as pool:
692
693
694
      pool.map(self._get_eval_batch, map_args)
    self._eval_dataset.end_construction()

695
    logging.info("Eval construction complete. Time: {:.1f} seconds".format(
696
697
698
        timeit.default_timer() - start_time))

  def make_input_fn(self, is_training):
Taylor Robie's avatar
Taylor Robie committed
699
700
    # It isn't feasible to provide a foolproof check, so this is designed to
    # catch most failures rather than provide an exhaustive guard.
701
    if self._fatal_exception is not None:
Hongkun Yu's avatar
Hongkun Yu committed
702
703
      raise ValueError("Fatal exception in the data production loop: {}".format(
          self._fatal_exception))
704

Hongkun Yu's avatar
Hongkun Yu committed
705
706
707
    return (self._train_dataset.make_input_fn(self.train_batch_size)
            if is_training else self._eval_dataset.make_input_fn(
                self.eval_batch_size))
708

Shining Sun's avatar
Shining Sun committed
709
710
711
  def increment_request_epoch(self):
    self._train_dataset.increment_request_epoch()

712
713
714

class DummyConstructor(threading.Thread):
  """Class for running with synthetic data."""
715

716
717
718
719
720
  def __init__(self, *args, **kwargs):
    super(DummyConstructor, self).__init__(*args, **kwargs)
    self.train_batches_per_epoch = rconst.SYNTHETIC_BATCHES_PER_EPOCH
    self.eval_batches_per_epoch = rconst.SYNTHETIC_BATCHES_PER_EPOCH

721
722
723
724
725
726
  def run(self):
    pass

  def stop_loop(self):
    pass

Shining Sun's avatar
Shining Sun committed
727
728
729
  def increment_request_epoch(self):
    pass

730
731
732
733
734
  @staticmethod
  def make_input_fn(is_training):
    """Construct training input_fn that uses synthetic data."""

    def input_fn(params):
735
736
737
      """Returns dummy input batches for training."""

      # Estimator passes batch_size during training and eval_batch_size during
738
      # eval.
Hongkun Yu's avatar
Hongkun Yu committed
739
740
741
      batch_size = (
          params["batch_size"] if is_training else
          params.get("eval_batch_size") or params["batch_size"])
742
743
744
      num_users = params["num_users"]
      num_items = params["num_items"]

745
746
747
      users = tf.random.uniform([batch_size, 1],
                                dtype=tf.int32,
                                minval=0,
748
                                maxval=num_users)
749
750
751
      items = tf.random.uniform([batch_size, 1],
                                dtype=tf.int32,
                                minval=0,
752
753
754
                                maxval=num_items)

      if is_training:
755
756
757
758
759
760
761
762
763
764
        valid_point_mask = tf.cast(
            tf.random.uniform([batch_size, 1],
                              dtype=tf.int32,
                              minval=0,
                              maxval=2), tf.bool)
        labels = tf.cast(
            tf.random.uniform([batch_size, 1],
                              dtype=tf.int32,
                              minval=0,
                              maxval=2), tf.bool)
765
766
767
768
769
770
        data = {
            movielens.USER_COLUMN: users,
            movielens.ITEM_COLUMN: items,
            rconst.VALID_POINT_MASK: valid_point_mask,
        }, labels
      else:
771
772
773
774
775
        dupe_mask = tf.cast(
            tf.random.uniform([batch_size, 1],
                              dtype=tf.int32,
                              minval=0,
                              maxval=2), tf.bool)
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
        data = {
            movielens.USER_COLUMN: users,
            movielens.ITEM_COLUMN: items,
            rconst.DUPLICATE_MASK: dupe_mask,
        }

      dataset = tf.data.Dataset.from_tensors(data).repeat(
          rconst.SYNTHETIC_BATCHES_PER_EPOCH * params["batches_per_step"])
      dataset = dataset.prefetch(32)
      return dataset

    return input_fn


class MaterializedDataConstructor(BaseDataConstructor):
  """Materialize a table of negative examples for fast negative generation.

  This class creates a table (num_users x num_items) containing all of the
  negative examples for each user. This table is conceptually ragged; that is to
Taylor Robie's avatar
Taylor Robie committed
795
  say the items dimension will have a number of unused elements at the end equal
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
  to the number of positive elements for a given user. For instance:

  num_users = 3
  num_items = 5
  positives = [[1, 3], [0], [1, 2, 3, 4]]

  will generate a negative table:
  [
    [0         2         4         int32max  int32max],
    [1         2         3         4         int32max],
    [0         int32max  int32max  int32max  int32max],
  ]

  and a vector of per-user negative counts, which in this case would be:
    [3, 4, 1]

  When sampling negatives, integers are (nearly) uniformly selected from the
  range [0, per_user_neg_count[user]) which gives a column_index, at which
  point the negative can be selected as:
    negative_table[user, column_index]

  This technique will not scale; however MovieLens is small enough that even
  a pre-compute which is quadratic in problem size will still fit in memory. A
  more scalable lookup method is in the works.
  """
Hongkun Yu's avatar
Hongkun Yu committed
821

822
823
824
825
826
827
828
829
830
831
  def __init__(self, *args, **kwargs):
    super(MaterializedDataConstructor, self).__init__(*args, **kwargs)
    self._negative_table = None
    self._per_user_neg_count = None

  def construct_lookup_variables(self):
    # Materialize negatives for fast lookup sampling.
    start_time = timeit.default_timer()
    inner_bounds = np.argwhere(self._train_pos_users[1:] -
                               self._train_pos_users[:-1])[:, 0] + 1
Taylor Robie's avatar
Taylor Robie committed
832
    (upper_bound,) = self._train_pos_users.shape
833
    index_bounds = [0] + inner_bounds.tolist() + [upper_bound]
Hongkun Yu's avatar
Hongkun Yu committed
834
835
    self._negative_table = np.zeros(
        shape=(self._num_users, self._num_items), dtype=rconst.ITEM_DTYPE)
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851

    # Set the table to the max value to make sure the embedding lookup will fail
    # if we go out of bounds, rather than just overloading item zero.
    self._negative_table += np.iinfo(rconst.ITEM_DTYPE).max
    assert self._num_items < np.iinfo(rconst.ITEM_DTYPE).max

    # Reuse arange during generation. np.delete will make a copy.
    full_set = np.arange(self._num_items, dtype=rconst.ITEM_DTYPE)

    self._per_user_neg_count = np.zeros(
        shape=(self._num_users,), dtype=np.int32)

    # Threading does not improve this loop. For some reason, the np.delete
    # call does not parallelize well. Multiprocessing incurs too much
    # serialization overhead to be worthwhile.
    for i in range(self._num_users):
Hongkun Yu's avatar
Hongkun Yu committed
852
      positives = self._train_pos_items[index_bounds[i]:index_bounds[i + 1]]
853
854
855
856
      negatives = np.delete(full_set, positives)
      self._per_user_neg_count[i] = self._num_items - positives.shape[0]
      self._negative_table[i, :self._per_user_neg_count[i]] = negatives

857
    logging.info("Negative sample table built. Time: {:.1f} seconds".format(
858
859
860
861
862
863
        timeit.default_timer() - start_time))

  def lookup_negative_items(self, negative_users, **kwargs):
    negative_item_choice = stat_utils.very_slightly_biased_randint(
        self._per_user_neg_count[negative_users])
    return self._negative_table[negative_users, negative_item_choice]
864
865
866
867
868
869
870
871
872
873
874


class BisectionDataConstructor(BaseDataConstructor):
  """Use bisection to index within positive examples.

  This class tallies the number of negative items which appear before each
  positive item for a user. This means that in order to select the ith negative
  item for a user, it only needs to determine which two positive items bound
  it at which point the item id for the ith negative is a simply algebraic
  expression.
  """
Hongkun Yu's avatar
Hongkun Yu committed
875

876
877
878
879
880
881
882
  def __init__(self, *args, **kwargs):
    super(BisectionDataConstructor, self).__init__(*args, **kwargs)
    self.index_bounds = None
    self._sorted_train_pos_items = None
    self._total_negatives = None

  def _index_segment(self, user):
Hongkun Yu's avatar
Hongkun Yu committed
883
    lower, upper = self.index_bounds[user:user + 2]
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
    items = self._sorted_train_pos_items[lower:upper]

    negatives_since_last_positive = np.concatenate(
        [items[0][np.newaxis], items[1:] - items[:-1] - 1])

    return np.cumsum(negatives_since_last_positive)

  def construct_lookup_variables(self):
    start_time = timeit.default_timer()
    inner_bounds = np.argwhere(self._train_pos_users[1:] -
                               self._train_pos_users[:-1])[:, 0] + 1
    (upper_bound,) = self._train_pos_users.shape
    self.index_bounds = np.array([0] + inner_bounds.tolist() + [upper_bound])

    # Later logic will assume that the users are in sequential ascending order.
    assert np.array_equal(self._train_pos_users[self.index_bounds[:-1]],
                          np.arange(self._num_users))

    self._sorted_train_pos_items = self._train_pos_items.copy()

    for i in range(self._num_users):
Hongkun Yu's avatar
Hongkun Yu committed
905
      lower, upper = self.index_bounds[i:i + 2]
906
907
      self._sorted_train_pos_items[lower:upper].sort()

Hongkun Yu's avatar
Hongkun Yu committed
908
909
    self._total_negatives = np.concatenate(
        [self._index_segment(i) for i in range(self._num_users)])
910

911
    logging.info("Negative total vector built. Time: {:.1f} seconds".format(
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
        timeit.default_timer() - start_time))

  def lookup_negative_items(self, negative_users, **kwargs):
    output = np.zeros(shape=negative_users.shape, dtype=rconst.ITEM_DTYPE) - 1

    left_index = self.index_bounds[negative_users]
    right_index = self.index_bounds[negative_users + 1] - 1

    num_positives = right_index - left_index + 1
    num_negatives = self._num_items - num_positives
    neg_item_choice = stat_utils.very_slightly_biased_randint(num_negatives)

    # Shortcuts:
    # For points where the negative is greater than or equal to the tally before
    # the last positive point there is no need to bisect. Instead the item id
    # corresponding to the negative item choice is simply:
    #   last_postive_index + 1 + (neg_choice - last_negative_tally)
    # Similarly, if the selection is less than the tally at the first positive
    # then the item_id is simply the selection.
    #
    # Because MovieLens organizes popular movies into low integers (which is
    # preserved through the preprocessing), the first shortcut is very
    # efficient, allowing ~60% of samples to bypass the bisection. For the same
    # reason, the second shortcut is rarely triggered (<0.02%) and is therefore
    # not worth implementing.
    use_shortcut = neg_item_choice >= self._total_negatives[right_index]
    output[use_shortcut] = (
        self._sorted_train_pos_items[right_index] + 1 +
Hongkun Yu's avatar
Hongkun Yu committed
940
        (neg_item_choice - self._total_negatives[right_index]))[use_shortcut]
941

942
943
944
945
    if np.all(use_shortcut):
      # The bisection code is ill-posed when there are no elements.
      return output

946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
    not_use_shortcut = np.logical_not(use_shortcut)
    left_index = left_index[not_use_shortcut]
    right_index = right_index[not_use_shortcut]
    neg_item_choice = neg_item_choice[not_use_shortcut]

    num_loops = np.max(
        np.ceil(np.log2(num_positives[not_use_shortcut])).astype(np.int32))

    for i in range(num_loops):
      mid_index = (left_index + right_index) // 2
      right_criteria = self._total_negatives[mid_index] > neg_item_choice
      left_criteria = np.logical_not(right_criteria)

      right_index[right_criteria] = mid_index[right_criteria]
      left_index[left_criteria] = mid_index[left_criteria]

    # Expected state after bisection pass:
    #   The right index is the smallest index whose tally is greater than the
    #   negative item choice index.

    assert np.all((right_index - left_index) <= 1)

    output[not_use_shortcut] = (
        self._sorted_train_pos_items[right_index] -
Hongkun Yu's avatar
Hongkun Yu committed
970
        (self._total_negatives[right_index] - neg_item_choice))
971
972
973
974
975
976
977
978
979
980
981
982

    assert np.all(output >= 0)

    return output


def get_constructor(name):
  if name == "bisection":
    return BisectionDataConstructor
  if name == "materialized":
    return MaterializedDataConstructor
  raise ValueError("Unrecognized constructor: {}".format(name))