1# Copyright 2019 The TensorFlow Authors. All Rights Reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14# ============================================================================== 15"""Code for creating a dataset out of a NumPy array.""" 16 17import numpy as np 18 19from tensorflow.python.data.ops import dataset_ops 20from tensorflow.python.eager import context 21from tensorflow.python.framework import dtypes 22from tensorflow.python.framework import ops 23from tensorflow.python.ops import array_ops 24from tensorflow.python.ops import variable_scope 25from tensorflow.python.util import nest 26 27 28def init_var_from_numpy(input_var, numpy_input, session): 29 """Initialize `input_var` to `numpy_input` using `session` in graph mode.""" 30 with ops.init_scope(): 31 if context.executing_eagerly(): 32 input_var.assign(numpy_input) 33 return 34 35 assert session is not None 36 session.run(input_var.initializer) 37 38 start_placeholder = array_ops.placeholder(dtypes.int64, ()) 39 end_placeholder = array_ops.placeholder(dtypes.int64, ()) 40 slice_placeholder = array_ops.placeholder(input_var.dtype) 41 assign_slice_op = input_var[start_placeholder:end_placeholder].assign( 42 slice_placeholder) 43 44 # If each batch element is > 64 MB, then we copy each batch element 45 # individually. Otherwise, the slices will be < 128 MB. There might be 46 # padding which might mean that the slices are 128 MB even if the size of 47 # the tensor allocated is less than 128 MB. This formula gives slices with 48 # size: ceil(64 MB / byte size per batch element) bytes. Using ceil() 49 # guarantees we get a number >= 1. 50 51 # Calculate the size of each batch element. 52 byte_size_per_batch_element = ( 53 np.prod(numpy_input.shape[1:]) * input_var.dtype.size) 54 55 # Calculate number of elements we want to copy per slice. 56 batch_size_per_slice = int( 57 np.ceil((64 << 20) / byte_size_per_batch_element)) 58 59 # Copy slices of the above size starting at 0, except the last slice will be 60 # smaller. 61 start = 0 62 limit = numpy_input.shape[0] 63 while start < limit: 64 end = min(start + batch_size_per_slice, limit) 65 session.run(assign_slice_op, feed_dict={ 66 start_placeholder: start, 67 end_placeholder: end, 68 slice_placeholder: numpy_input[start:end]}) 69 start = end 70 71 72def one_host_numpy_dataset(numpy_input, colocate_with, session): 73 """Create a dataset on `colocate_with` from `numpy_input`.""" 74 75 def create_colocated_variable(next_creator, **kwargs): 76 kwargs["colocate_with"] = colocate_with 77 return next_creator(**kwargs) 78 79 numpy_flat = nest.flatten(numpy_input) 80 with variable_scope.variable_creator_scope(create_colocated_variable): 81 vars_flat = tuple(variable_scope.variable(array_ops.zeros(i.shape, i.dtype), 82 trainable=False) 83 for i in numpy_flat) 84 for v, i in zip(vars_flat, numpy_flat): 85 init_var_from_numpy(v, i, session) 86 vars_nested = nest.pack_sequence_as(numpy_input, vars_flat) 87 return dataset_ops.Dataset.from_tensor_slices(vars_nested) 88 89 90class SingleDevice(object): 91 """Used with `colocate_with` to create a non-mirrored variable.""" 92 93 def __init__(self, device): 94 self.device = device 95