|
| 1 | +# Copyright 2021 Alibaba Group Holding Limited. 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 | +"""Test for estimator API.""" |
| 16 | + |
| 17 | +from __future__ import absolute_import |
| 18 | +from __future__ import division |
| 19 | +from __future__ import print_function |
| 20 | + |
| 21 | +import os |
| 22 | +import shutil |
| 23 | +import tempfile |
| 24 | +import numpy as np |
| 25 | + |
| 26 | +import tensorflow as tf |
| 27 | + |
| 28 | +import epl |
| 29 | +from test_utils import fix_randomness |
| 30 | + |
| 31 | + |
| 32 | +# pylint: disable=missing-docstring,unused-variable |
| 33 | +# pylint: disable=protected-access |
| 34 | +fix_randomness() |
| 35 | +def model_fn(features, labels, mode): |
| 36 | + """Model function.""" |
| 37 | + with tf.variable_scope('lr_softmax'): |
| 38 | + weights = tf.get_variable('weights', initializer=tf.zeros([78, 10])) |
| 39 | + biases = tf.get_variable('biases', initializer=tf.zeros([10])) |
| 40 | + logits = tf.matmul(features, weights) + biases |
| 41 | + global_step = tf.train.get_or_create_global_step() |
| 42 | + loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, |
| 43 | + logits=logits, |
| 44 | + weights=1.0) |
| 45 | + if mode == tf.estimator.ModeKeys.TRAIN: |
| 46 | + opt = tf.train.AdamOptimizer(0.1, name='adam') |
| 47 | + train_op = opt.minimize(loss, global_step=global_step, name='train') |
| 48 | + if epl.env.Env.get().cluster: |
| 49 | + epl.add_to_collection(loss, epl.GraphKeys.GLOBAL_MEAN_OBJECTS) |
| 50 | + return tf.estimator.EstimatorSpec( |
| 51 | + mode=mode, |
| 52 | + loss=loss, |
| 53 | + train_op=train_op) |
| 54 | + elif mode == tf.estimator.ModeKeys.EVAL: |
| 55 | + return tf.estimator.EstimatorSpec( |
| 56 | + mode=mode, |
| 57 | + loss=loss) |
| 58 | + else: |
| 59 | + raise ValueError( |
| 60 | + "Only TRAIN and EVAL modes are supported: %s" % (mode)) |
| 61 | + |
| 62 | + |
| 63 | +def model_fn_replicate(features, labels, mode): |
| 64 | + with epl.replicate(device_count=1): |
| 65 | + return model_fn(features, labels, mode) |
| 66 | + |
| 67 | +def input_fn(batch_size=2, estimator=True): |
| 68 | + """input function.""" |
| 69 | + num_x = np.random.randint(0, 10, (200, 78)).astype(dtype=np.float32) |
| 70 | + num_y = np.random.randint(0, 10, 200).astype(dtype=np.int32) |
| 71 | + dataset = tf.data.Dataset.from_tensor_slices((num_x, num_y)) \ |
| 72 | + .batch(batch_size).repeat(10) |
| 73 | + if not estimator: |
| 74 | + iterator = dataset.make_initializable_iterator() |
| 75 | + tf.add_to_collection(tf.GraphKeys.TABLE_INITIALIZERS, iterator.initializer) |
| 76 | + return dataset |
| 77 | + |
| 78 | +def _main(): |
| 79 | + config = epl.Config() |
| 80 | + epl.init(config) |
| 81 | + model_dir = tempfile.mkdtemp() |
| 82 | + model_dir = os.path.join(model_dir, str(epl.Env.get().cluster.worker_index)) |
| 83 | + run_config = tf.estimator.RunConfig(save_checkpoints_steps=5, |
| 84 | + model_dir=model_dir) |
| 85 | + estimator = tf.estimator.Estimator(model_fn=model_fn_replicate, config=run_config) |
| 86 | + hooks = [] |
| 87 | + hooks.append(tf.train.StepCounterHook(every_n_steps=1)) |
| 88 | + train_spec = tf.estimator.TrainSpec(input_fn=input_fn, max_steps=30, |
| 89 | + hooks=hooks) |
| 90 | + eval_spec = tf.estimator.EvalSpec(input_fn=input_fn, steps=10) |
| 91 | + tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) |
| 92 | + shutil.rmtree(model_dir) |
| 93 | +# pylint: enable=missing-docstring,unused-variable |
| 94 | +# pylint: enable=protected-access |
| 95 | + |
| 96 | +if __name__ == "__main__": |
| 97 | + tf.logging.set_verbosity(tf.logging.INFO) |
| 98 | + _main() |
0 commit comments