diff --git a/demo/mnist/api_train_v2.py b/demo/mnist/api_train_v2.py index 8a612cbc66d54ba3a3a9a444f85626812940cf6a..612b0d218fc0be68b668ffb8f1bfb0ba92c4d741 100644 --- a/demo/mnist/api_train_v2.py +++ b/demo/mnist/api_train_v2.py @@ -1,14 +1,5 @@ import paddle.v2 as paddle -import mnist_util - - -def train_reader(): - train_file = './data/raw_data/train' - generator = mnist_util.read_from_mnist(train_file) - for item in generator: - yield item - def main(): paddle.init(use_gpu=False, trainer_count=1) @@ -40,11 +31,13 @@ def main(): trainer = paddle.trainer.SGD(update_equation=adam_optimizer) trainer.train( - train_data_reader=train_reader, + reader=paddle.reader.batched( + paddle.reader.shuffle( + paddle.dataset.mnist.train(), buf_size=8192), + batch_size=32), cost=cost, parameters=parameters, event_handler=event_handler, - batch_size=32, # batch size should be refactor in Data reader reader_dict={images.name: 0, label.name: 1}) diff --git a/python/CMakeLists.txt b/python/CMakeLists.txt index 71af50a9a4ed835635362c24d6c1ae5e92de050b..48e0a1993d07f801e65dfa54a991995c593fe475 100644 --- a/python/CMakeLists.txt +++ b/python/CMakeLists.txt @@ -4,7 +4,7 @@ set(OUTPUT_DIR file(GLOB TRAINER_PY_FILES . ./paddle/trainer/*.py) file(GLOB HELPERS_PY_FILES . ./paddle/trainer_config_helpers/*.py) file(GLOB UTILS_PY_FILES . ./paddle/utils/*.py) -file(GLOB V2_PY_FILES . ./paddle/v2/*.py) +file(GLOB_RECURSE V2_PY_FILES ./paddle/v2/ *.py) set(PY_FILES paddle/__init__.py ${TRAINER_PY_FILES} @@ -24,7 +24,7 @@ add_custom_target(paddle_python ALL DEPENDS ${OUTPUT_DIR}/.timestamp) add_subdirectory(paddle/trainer_config_helpers/tests) -add_subdirectory(paddle/reader/tests) +add_subdirectory(paddle/v2/reader/tests) add_subdirectory(paddle/v2/tests) install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/dist/ diff --git a/python/paddle/reader/tests/CMakeLists.txt b/python/paddle/reader/tests/CMakeLists.txt deleted file mode 100644 index da072fb3dbeed5bee15fa1f64372ad8dec497070..0000000000000000000000000000000000000000 --- a/python/paddle/reader/tests/CMakeLists.txt +++ /dev/null @@ -1,9 +0,0 @@ -add_test(NAME reader_decorator_test - COMMAND ${PROJ_ROOT}/paddle/.set_python_path.sh -d ${PROJ_ROOT}/python/ - ${PYTHON_EXECUTABLE} ${PROJ_ROOT}/python/paddle/reader/tests/decorator_test.py - WORKING_DIRECTORY ${PROJ_ROOT}/python/paddle) - -add_test(NAME reader_creator_test - COMMAND ${PROJ_ROOT}/paddle/.set_python_path.sh -d ${PROJ_ROOT}/python/ - ${PYTHON_EXECUTABLE} ${PROJ_ROOT}/python/paddle/reader/tests/creator_test.py - WORKING_DIRECTORY ${PROJ_ROOT}/python/paddle) diff --git a/python/paddle/v2/__init__.py b/python/paddle/v2/__init__.py index 90321defef7674dde96d57f0e0455031ee64ee86..b31efe170dbf11771311ed5dbf4cd8b299b0c4ca 100644 --- a/python/paddle/v2/__init__.py +++ b/python/paddle/v2/__init__.py @@ -20,13 +20,16 @@ import event import data_type import topology import data_feeder +from . import dataset +from . import reader import attr import pooling import py_paddle.swig_paddle as api __all__ = [ 'optimizer', 'layer', 'activation', 'parameters', 'init', 'trainer', - 'event', 'data_type', 'attr', 'pooling', 'data_feeder', 'topology' + 'event', 'data_type', 'attr', 'pooling', 'data_feeder', 'dataset', 'reader', + 'topology' ] diff --git a/python/paddle/v2/dataset/__init__.py b/python/paddle/v2/dataset/__init__.py index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..9647e9850332b795f6480d26e4f9c736129782ae 100644 --- a/python/paddle/v2/dataset/__init__.py +++ b/python/paddle/v2/dataset/__init__.py @@ -0,0 +1,3 @@ +import mnist + +__all__ = ['mnist'] diff --git a/python/paddle/v2/dataset/mnist.py b/python/paddle/v2/dataset/mnist.py index a36c20e3fa3734bdc14c1f47779a61375f298511..f1315b35cd55c5387295f1f883b997cd6dd71bd1 100644 --- a/python/paddle/v2/dataset/mnist.py +++ b/python/paddle/v2/dataset/mnist.py @@ -1,10 +1,10 @@ """ MNIST dataset. """ -import numpy import paddle.v2.dataset.common import subprocess - +import numpy +import platform __all__ = ['train', 'test'] URL_PREFIX = 'http://yann.lecun.com/exdb/mnist/' @@ -20,12 +20,19 @@ TRAIN_LABEL_MD5 = 'd53e105ee54ea40749a09fcbcd1e9432' def reader_creator(image_filename, label_filename, buffer_size): def reader(): + if platform.system() == 'Darwin': + zcat_cmd = 'gzcat' + elif platform.system() == 'Linux': + zcat_cmd = 'zcat' + else: + raise NotImplementedError() + # According to http://stackoverflow.com/a/38061619/724872, we # cannot use standard package gzip here. - m = subprocess.Popen(["zcat", image_filename], stdout=subprocess.PIPE) + m = subprocess.Popen([zcat_cmd, image_filename], stdout=subprocess.PIPE) m.stdout.read(16) # skip some magic bytes - l = subprocess.Popen(["zcat", label_filename], stdout=subprocess.PIPE) + l = subprocess.Popen([zcat_cmd, label_filename], stdout=subprocess.PIPE) l.stdout.read(8) # skip some magic bytes while True: diff --git a/python/paddle/reader/__init__.py b/python/paddle/v2/reader/__init__.py similarity index 100% rename from python/paddle/reader/__init__.py rename to python/paddle/v2/reader/__init__.py diff --git a/python/paddle/reader/creator.py b/python/paddle/v2/reader/creator.py similarity index 100% rename from python/paddle/reader/creator.py rename to python/paddle/v2/reader/creator.py diff --git a/python/paddle/reader/decorator.py b/python/paddle/v2/reader/decorator.py similarity index 90% rename from python/paddle/reader/decorator.py rename to python/paddle/v2/reader/decorator.py index 9f4234358f469b9741dfef96aab3853d5972b5f4..5687f118ce277928d16f4ea48907cee120c73b47 100644 --- a/python/paddle/reader/decorator.py +++ b/python/paddle/v2/reader/decorator.py @@ -14,7 +14,7 @@ __all__ = [ 'map_readers', 'buffered', 'compose', 'chain', 'shuffle', - 'ComposeNotAligned' + 'ComposeNotAligned', 'batched' ] from Queue import Queue @@ -191,3 +191,25 @@ def buffered(reader, size): e = q.get() return data_reader + + +def batched(reader, batch_size): + """ + Create a batched reader. + :param reader: the data reader to read from. + :param batch_size: batch_size + :return: the batched reader. + """ + + def batched_reader(): + r = reader() + batch = [] + for instance in r: + batch.append(instance) + if len(batch) == batch_size: + yield batch + batch = [] + if batch: + yield batch + + return batched_reader diff --git a/python/paddle/v2/reader/tests/CMakeLists.txt b/python/paddle/v2/reader/tests/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..a51f700406b48f8186e45f1ced94765e343a8b5e --- /dev/null +++ b/python/paddle/v2/reader/tests/CMakeLists.txt @@ -0,0 +1,3 @@ +add_test(NAME reader_tests + COMMAND bash ${PROJ_ROOT}/python/paddle/v2/reader/tests/run_tests.sh + ${PYTHON_EXECUTABLE}) diff --git a/python/paddle/v2/reader/tests/__init__.py b/python/paddle/v2/reader/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/paddle/reader/tests/creator_test.py b/python/paddle/v2/reader/tests/creator_test.py similarity index 89% rename from python/paddle/reader/tests/creator_test.py rename to python/paddle/v2/reader/tests/creator_test.py index eda8ab6715b2be0c9cb6163adf60d8fbdf2d7e8c..9f8d7133b8694aae5541eff9576eaba8a31e77dc 100644 --- a/python/paddle/reader/tests/creator_test.py +++ b/python/paddle/v2/reader/tests/creator_test.py @@ -11,17 +11,19 @@ # 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. +import os import unittest -import paddle.reader.creator + import numpy as np -import os + +import paddle.v2.reader.creator class TestNumpyArray(unittest.TestCase): def test_numpy_array(self): l = [[1, 2, 3], [4, 5, 6]] x = np.array(l, np.int32) - reader = paddle.reader.creator.np_array(x) + reader = paddle.v2.reader.creator.np_array(x) for idx, e in enumerate(reader()): self.assertItemsEqual(e, l[idx]) @@ -29,7 +31,7 @@ class TestNumpyArray(unittest.TestCase): class TestTextFile(unittest.TestCase): def test_text_file(self): path = os.path.join(os.path.dirname(__file__), "test_data_creator.txt") - reader = paddle.reader.creator.text_file(path) + reader = paddle.v2.reader.creator.text_file(path) for idx, e in enumerate(reader()): self.assertEqual(e, str(idx * 2) + " " + str(idx * 2 + 1)) diff --git a/python/paddle/reader/tests/decorator_test.py b/python/paddle/v2/reader/tests/decorator_test.py similarity index 81% rename from python/paddle/reader/tests/decorator_test.py rename to python/paddle/v2/reader/tests/decorator_test.py index 0396a61786539bf57be4cab9ebbd108ade9e7c83..734154b9790a4dc118d11992343648364c907305 100644 --- a/python/paddle/reader/tests/decorator_test.py +++ b/python/paddle/v2/reader/tests/decorator_test.py @@ -11,9 +11,10 @@ # 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. -import unittest -import paddle.reader import time +import unittest + +import paddle.v2.reader def reader_creator_10(dur): @@ -37,7 +38,7 @@ class TestMap(unittest.TestCase): yield "h" yield "i" - r = paddle.reader.map_readers(tokenize, read) + r = paddle.v2.reader.map_readers(tokenize, read) for i, e in enumerate(r()): self.assertEqual(e, i) @@ -45,7 +46,7 @@ class TestMap(unittest.TestCase): class TestBuffered(unittest.TestCase): def test_read(self): for size in range(20): - b = paddle.reader.buffered(reader_creator_10(0), size) + b = paddle.v2.reader.buffered(reader_creator_10(0), size) c = 0 for i in b(): self.assertEqual(i, c) @@ -54,7 +55,7 @@ class TestBuffered(unittest.TestCase): def test_buffering(self): # read have 30ms delay. - b = paddle.reader.buffered(reader_creator_10(0.03), 10) + b = paddle.v2.reader.buffered(reader_creator_10(0.03), 10) last_time = time.time() for idx, i in enumerate(b()): elapsed_time = time.time() - last_time @@ -68,17 +69,17 @@ class TestBuffered(unittest.TestCase): class TestCompose(unittest.TestCase): def test_compse(self): - reader = paddle.reader.compose( + reader = paddle.v2.reader.compose( reader_creator_10(0), reader_creator_10(0)) for idx, e in enumerate(reader()): self.assertEqual(e, (idx, idx)) def test_compose_not_aligned(self): total = 0 - reader = paddle.reader.compose( - paddle.reader.chain(reader_creator_10(0), reader_creator_10(0)), + reader = paddle.v2.reader.compose( + paddle.v2.reader.chain(reader_creator_10(0), reader_creator_10(0)), reader_creator_10(0)) - with self.assertRaises(paddle.reader.ComposeNotAligned): + with self.assertRaises(paddle.v2.reader.ComposeNotAligned): for e in reader(): total += 1 # expecting 10, not 20 @@ -86,8 +87,8 @@ class TestCompose(unittest.TestCase): def test_compose_not_aligned_no_check(self): total = 0 - reader = paddle.reader.compose( - paddle.reader.chain(reader_creator_10(0), reader_creator_10(0)), + reader = paddle.v2.reader.compose( + paddle.v2.reader.chain(reader_creator_10(0), reader_creator_10(0)), reader_creator_10(0), check_alignment=False) for e in reader(): @@ -98,7 +99,7 @@ class TestCompose(unittest.TestCase): class TestChain(unittest.TestCase): def test_chain(self): - c = paddle.reader.chain(reader_creator_10(0), reader_creator_10(0)) + c = paddle.v2.reader.chain(reader_creator_10(0), reader_creator_10(0)) idx = 0 for e in c(): self.assertEqual(e, idx % 10) @@ -111,7 +112,7 @@ class TestShuffle(unittest.TestCase): case = [(0, True), (1, True), (10, False), (100, False)] a = reader_creator_10(0) for size, checkEq in case: - s = paddle.reader.shuffle(a, size) + s = paddle.v2.reader.shuffle(a, size) total = 0 for idx, e in enumerate(s()): if checkEq: diff --git a/python/paddle/v2/reader/tests/run_tests.sh b/python/paddle/v2/reader/tests/run_tests.sh new file mode 100755 index 0000000000000000000000000000000000000000..a544a5636021bcf8bd9a35966c91ae343c149d14 --- /dev/null +++ b/python/paddle/v2/reader/tests/run_tests.sh @@ -0,0 +1,35 @@ +#!/bin/bash +# Copyright (c) 2016 PaddlePaddle 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. + + +pushd `dirname $0` > /dev/null +SCRIPTPATH=$PWD +popd > /dev/null + +cd $SCRIPTPATH +$1 -m pip install ../../../../../paddle/dist/*.whl + +test_list="creator_test.py decorator_test.py" + +export PYTHONPATH=$PWD/../../../../../python/ + +for fn in $test_list +do + echo "test $fn" + $1 $fn + if [ $? -ne 0 ]; then + exit 1 + fi +done diff --git a/python/paddle/reader/tests/test_data_creator.txt b/python/paddle/v2/reader/tests/test_data_creator.txt similarity index 100% rename from python/paddle/reader/tests/test_data_creator.txt rename to python/paddle/v2/reader/tests/test_data_creator.txt diff --git a/python/paddle/v2/trainer.py b/python/paddle/v2/trainer.py index 2aeddaff89748ef6c769e1793345f5b143b941c6..bf8b181e42064f01a78b92313805b5fed3a3ceac 100644 --- a/python/paddle/v2/trainer.py +++ b/python/paddle/v2/trainer.py @@ -27,19 +27,13 @@ class ITrainer(object): The interface of Trainer. The only exposed method is `train`. """ - def train(self, - train_data_reader, - cost, - parameters, - test_data_reader=None, - event_handler=None): + def train(self, reader, topology, parameters, event_handler=None): """ train method. - :param train_data_reader: - :param cost: + :param reader: + :param topology: :param parameters: - :param test_data_reader: :param event_handler: :return: """ @@ -61,26 +55,22 @@ class SGD(ITrainer): self.__optimizer__ = update_equation def train(self, - train_data_reader, + reader, cost, parameters, num_passes=1, - test_data_reader=None, event_handler=None, - batch_size=32, reader_dict=None): """ Training method. Will train num_passes of input data. - :param train_data_reader: - :param cost: cost layers, to be optimized. + :param reader: + :param topology: Network Topology, use one or more Layers to represent it. :param parameters: The parameter pools. :param num_passes: The total train passes. - :param test_data_reader: :param event_handler: Event handler. A method will be invoked when event occurred. :type event_handler: (BaseEvent) => None - :param batch_size: Not important, will be removed after data refactor. :return: """ if event_handler is None: @@ -112,9 +102,9 @@ class SGD(ITrainer): event_handler(v2_event.BeginPass(pass_id)) pass_evaluator.start() updater.startPass() - for batch_id, data_batch in enumerate( - __data_reader_to_batch__(train_data_reader, batch_size, - topology)): + for batch_id, data_batch in enumerate(reader()): + pass_type = updater.startBatch(len(data_batch)) + gm.forwardBackward(feeder(data_batch), out_args, pass_type) batch_evaluator.start() event_handler( v2_event.BeginIteration( @@ -144,56 +134,19 @@ class SGD(ITrainer): gm.finish() -def __data_reader_to_batch__(reader, batch_size, topology): - """ - This function is not important, and will be removed when data refactored. - """ - - def input_reorder(func): - for item in func(): - retv = [] - for __layer_name__ in topology.proto().input_layer_names: - retv.append(item[__layer_name__]) - yield retv - - return __generator_to_batch__(input_reorder(reader), batch_size=batch_size) - - -def __generator_to_batch__(generator, batch_size): - """ - This function is not important, and will be removed when data refactored. - """ - ret_val = list() - for each_item in generator: - ret_val.append(each_item) - if len(ret_val) == batch_size: - yield ret_val - ret_val = list() - if len(ret_val) != 0: - yield ret_val - - -def __check_train_args__(train_data_reader, topology, parameters, - test_data_reader, event_handler, **kwargs): +def __check_train_args__(reader, topology, parameters, event_handler, **kwargs): """ Check train function's argument types """ - if not callable(train_data_reader) or not isinstance(train_data_reader(), - collections.Iterator): - raise ValueError('train_data_reader should be a function, ' - 'which can return a iterator') - - if test_data_reader is not None: - if not callable(test_data_reader) or not isinstance( - test_data_reader(), collections.Iterator): - raise ValueError('test_data_reader should be a function, which can ' - 'return a iterator') + if not callable(reader) or not isinstance(reader(), collections.Iterator): + raise TypeError('train_data_reader should be a function, ' + 'which can return a iterator') if not isinstance(topology, Topology): - raise ValueError('topology should be a model config') + raise TypeError('topology should be a model config') if not isinstance(parameters, v2_parameters.Parameters): - raise ValueError('parameters should be a parameter pool') + raise TypeError('parameters should be a parameter pool') if not callable(event_handler): - raise ValueError('event handler should be a function') + raise TypeError('event handler should be a function') diff --git a/python/setup.py.in b/python/setup.py.in index 1e1324eea825ab1945a38cb43eceec29a4ebb1a1..68ca35265cf13265ad0b171b0f70e20b83006ff9 100644 --- a/python/setup.py.in +++ b/python/setup.py.in @@ -5,7 +5,9 @@ packages=['paddle', 'paddle.trainer', 'paddle.trainer_config_helpers', 'paddle.utils', - 'paddle.v2'] + 'paddle.v2', + 'paddle.v2.dataset', + 'paddle.v2.reader'] setup(name='paddle', version='${PADDLE_VERSION}',