We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
ocr_recognition 的参数说明与代码不相符
说明中的 --train_images 与 --train_list 两个参数，在代码中并不存在；运行时，带上这两个参数会报错。

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `fluid/PaddleCV/ocr_recognition/train.py`
Content:
```
1 """Trainer for OCR CTC or attention model."""
2 from __future__ import absolute_import
3 from __future__ import division
4 from __future__ import print_function
5 import paddle.fluid as fluid
6 from utility import add_arguments, print_arguments, to_lodtensor, get_ctc_feeder_data, get_attention_feeder_data
7 import paddle.fluid.profiler as profiler
8 from crnn_ctc_model import ctc_train_net
9 from attention_model import attention_train_net
10 import data_reader
11 import argparse
12 import functools
13 import sys
14 import time
15 import os
16 import numpy as np
17 
18 parser = argparse.ArgumentParser(description=__doc__)
19 add_arg = functools.partial(add_arguments, argparser=parser)
20 # yapf: disable
21 add_arg('batch_size',        int,   32,         "Minibatch size.")
22 add_arg('total_step',        int,   720000,    "The number of iterations. Zero or less means whole training set. More than 0 means the training set might be looped until # of iterations is reached.")
23 add_arg('log_period',        int,   1000,       "Log period.")
24 add_arg('save_model_period', int,   15000,      "Save model period. '-1' means never saving the model.")
25 add_arg('eval_period',       int,   15000,      "Evaluate period. '-1' means never evaluating the model.")
26 add_arg('save_model_dir',    str,   "./models", "The directory the model to be saved to.")
27 add_arg('model',    str,   "crnn_ctc",           "Which type of network to be used. 'crnn_ctc' or 'attention'")
28 add_arg('init_model',        str,   None,       "The init model file of directory.")
29 add_arg('use_gpu',           bool,  True,      "Whether use GPU to train.")
30 add_arg('min_average_window',int,   10000,     "Min average window.")
31 add_arg('max_average_window',int,   12500,     "Max average window. It is proposed to be set as the number of minibatch in a pass.")
32 add_arg('average_window',    float, 0.15,      "Average window.")
33 add_arg('parallel',          bool,  False,     "Whether use parallel training.")
34 add_arg('profile',           bool,  False,      "Whether to use profiling.")
35 add_arg('skip_batch_num',    int,   0,          "The number of first minibatches to skip as warm-up for better performance test.")
36 add_arg('skip_test',         bool,  False,      "Whether to skip test phase.")
37 # yapf: enable
38 
39 
40 def train(args):
41     """OCR training"""
42 
43     if args.model == "crnn_ctc":
44         train_net = ctc_train_net
45         get_feeder_data = get_ctc_feeder_data
46     else:
47         train_net = attention_train_net
48         get_feeder_data = get_attention_feeder_data
49 
50     num_classes = None
51     train_images = None
52     train_list = None
53     test_images = None
54     test_list = None
55     num_classes = data_reader.num_classes(
56     ) if num_classes is None else num_classes
57     data_shape = data_reader.data_shape()
58     # define network
59     sum_cost, error_evaluator, inference_program, model_average = train_net(
60         args, data_shape, num_classes)
61 
62     # data reader
63     train_reader = data_reader.train(
64         args.batch_size,
65         train_images_dir=train_images,
66         train_list_file=train_list,
67         cycle=args.total_step > 0,
68         model=args.model)
69     test_reader = data_reader.test(
70         test_images_dir=test_images, test_list_file=test_list, model=args.model)
71 
72     # prepare environment
73     place = fluid.CPUPlace()
74     if args.use_gpu:
75         place = fluid.CUDAPlace(0)
76     exe = fluid.Executor(place)
77 
78     if 'ce_mode' in os.environ:
79         fluid.default_startup_program().random_seed = 90
80 
81     exe.run(fluid.default_startup_program())
82 
83     # load init model
84     if args.init_model is not None:
85         model_dir = args.init_model
86         model_file_name = None
87         if not os.path.isdir(args.init_model):
88             model_dir = os.path.dirname(args.init_model)
89             model_file_name = os.path.basename(args.init_model)
90         fluid.io.load_params(exe, dirname=model_dir, filename=model_file_name)
91         print("Init model from: %s." % args.init_model)
92 
93     train_exe = exe
94     error_evaluator.reset(exe)
95     if args.parallel:
96         train_exe = fluid.ParallelExecutor(
97             use_cuda=True if args.use_gpu else False, loss_name=sum_cost.name)
98 
99     fetch_vars = [sum_cost] + error_evaluator.metrics
100 
101     def train_one_batch(data):
102         var_names = [var.name for var in fetch_vars]
103         if args.parallel:
104             results = train_exe.run(var_names,
105                                     feed=get_feeder_data(data, place))
106             results = [np.array(result).sum() for result in results]
107         else:
108             results = train_exe.run(feed=get_feeder_data(data, place),
109                                     fetch_list=fetch_vars)
110             results = [result[0] for result in results]
111         return results
112 
113     def test(iter_num):
114         error_evaluator.reset(exe)
115         for data in test_reader():
116             exe.run(inference_program, feed=get_feeder_data(data, place))
117         _, test_seq_error = error_evaluator.eval(exe)
118         print("\nTime: %s; Iter[%d]; Test seq error: %s.\n" % (
119             time.time(), iter_num, str(test_seq_error[0])))
120 
121         #Note: The following logs are special for CE monitoring.
122         #Other situations do not need to care about these logs.
123         print("kpis	test_acc	%f" % (1 - test_seq_error[0]))
124 
125     def save_model(args, exe, iter_num):
126         filename = "model_%05d" % iter_num
127         fluid.io.save_params(
128             exe, dirname=args.save_model_dir, filename=filename)
129         print("Saved model to: %s/%s." % (args.save_model_dir, filename))
130 
131     iter_num = 0
132     stop = False
133     start_time = time.time()
134     while not stop:
135         total_loss = 0.0
136         total_seq_error = 0.0
137         batch_times = []
138         # train a pass
139         for data in train_reader():
140             if args.total_step > 0 and iter_num == args.total_step + args.skip_batch_num:
141                 stop = True
142                 break
143             if iter_num < args.skip_batch_num:
144                 print("Warm-up iteration")
145             if iter_num == args.skip_batch_num:
146                 profiler.reset_profiler()
147             start = time.time()
148             results = train_one_batch(data)
149             batch_time = time.time() - start
150             fps = args.batch_size / batch_time
151             batch_times.append(batch_time)
152             total_loss += results[0]
153             total_seq_error += results[2]
154 
155             iter_num += 1
156             # training log
157             if iter_num % args.log_period == 0:
158                 print("\nTime: %s; Iter[%d]; Avg loss: %.3f; Avg seq err: %.3f" % (
159                     time.time(), iter_num,
160                     total_loss / (args.log_period * args.batch_size),
161                     total_seq_error / (args.log_period * args.batch_size)))
162                 print("kpis	train_cost	%f" % (total_loss / (args.log_period *
163                                                             args.batch_size)))
164                 print("kpis	train_acc	%f" % (
165                     1 - total_seq_error / (args.log_period * args.batch_size)))
166                 total_loss = 0.0
167                 total_seq_error = 0.0
168 
169             # evaluate
170             if not args.skip_test and iter_num % args.eval_period == 0:
171                 if model_average:
172                     with model_average.apply(exe):
173                         test(iter_num)
174                 else:
175                     test(iter_num)
176 
177             # save model
178             if iter_num % args.save_model_period == 0:
179                 if model_average:
180                     with model_average.apply(exe):
181                         save_model(args, exe, iter_num)
182                 else:
183                     save_model(args, exe, iter_num)
184         end_time = time.time()
185         print("kpis	train_duration	%f" % (end_time - start_time))
186         # Postprocess benchmark data
187         latencies = batch_times[args.skip_batch_num:]
188         latency_avg = np.average(latencies)
189         latency_pc99 = np.percentile(latencies, 99)
190         fpses = np.divide(args.batch_size, latencies)
191         fps_avg = np.average(fpses)
192         fps_pc99 = np.percentile(fpses, 1)
193 
194         # Benchmark output
195         print('\nTotal examples (incl. warm-up): %d' %
196               (iter_num * args.batch_size))
197         print('average latency: %.5f s, 99pc latency: %.5f s' % (latency_avg,
198                                                                  latency_pc99))
199         print('average fps: %.5f, fps for 99pc latency: %.5f' % (fps_avg,
200                                                                  fps_pc99))
201 
202 
203 def main():
204     args = parser.parse_args()
205     print_arguments(args)
206     if args.profile:
207         if args.use_gpu:
208             with profiler.cuda_profiler("cuda_profiler.txt", 'csv') as nvprof:
209                 train(args)
210         else:
211             with profiler.profiler("CPU", sorted_key='total') as cpuprof:
212                 train(args)
213     else:
214         train(args)
215 
216 
217 if __name__ == "__main__":
218     main()
219
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/fluid/PaddleCV/ocr_recognition/train.py b/fluid/PaddleCV/ocr_recognition/train.py
--- a/fluid/PaddleCV/ocr_recognition/train.py
+++ b/fluid/PaddleCV/ocr_recognition/train.py
@@ -24,6 +24,10 @@
 add_arg('save_model_period', int,   15000,      "Save model period. '-1' means never saving the model.")
 add_arg('eval_period',       int,   15000,      "Evaluate period. '-1' means never evaluating the model.")
 add_arg('save_model_dir',    str,   "./models", "The directory the model to be saved to.")
+add_arg('train_images',      str,   None,       "The directory of images to be used for training.")
+add_arg('train_list',        str,   None,       "The list file of images to be used for training.")
+add_arg('test_images',       str,   None,       "The directory of images to be used for test.")
+add_arg('test_list',         str,   None,       "The list file of images to be used for training.")
 add_arg('model',    str,   "crnn_ctc",           "Which type of network to be used. 'crnn_ctc' or 'attention'")
 add_arg('init_model',        str,   None,       "The init model file of directory.")
 add_arg('use_gpu',           bool,  True,      "Whether use GPU to train.")
@@ -48,10 +52,6 @@
         get_feeder_data = get_attention_feeder_data
 
     num_classes = None
-    train_images = None
-    train_list = None
-    test_images = None
-    test_list = None
     num_classes = data_reader.num_classes(
     ) if num_classes is None else num_classes
     data_shape = data_reader.data_shape()
@@ -62,12 +62,12 @@
     # data reader
     train_reader = data_reader.train(
         args.batch_size,
-        train_images_dir=train_images,
-        train_list_file=train_list,
+        train_images_dir=args.train_images,
+        train_list_file=args.train_list,
         cycle=args.total_step > 0,
         model=args.model)
     test_reader = data_reader.test(
-        test_images_dir=test_images, test_list_file=test_list, model=args.model)
+        test_images_dir=args.test_images, test_list_file=args.test_list, model=args.model)
 
     # prepare environment
     place = fluid.CPUPlace()

{"golden_diff": "diff --git a/fluid/PaddleCV/ocr_recognition/train.py b/fluid/PaddleCV/ocr_recognition/train.py\n--- a/fluid/PaddleCV/ocr_recognition/train.py\n+++ b/fluid/PaddleCV/ocr_recognition/train.py\n@@ -24,6 +24,10 @@\n add_arg('save_model_period', int,   15000,      \"Save model period. '-1' means never saving the model.\")\n add_arg('eval_period',       int,   15000,      \"Evaluate period. '-1' means never evaluating the model.\")\n add_arg('save_model_dir',    str,   \"./models\", \"The directory the model to be saved to.\")\n+add_arg('train_images',      str,   None,       \"The directory of images to be used for training.\")\n+add_arg('train_list',        str,   None,       \"The list file of images to be used for training.\")\n+add_arg('test_images',       str,   None,       \"The directory of images to be used for test.\")\n+add_arg('test_list',         str,   None,       \"The list file of images to be used for training.\")\n add_arg('model',    str,   \"crnn_ctc\",           \"Which type of network to be used. 'crnn_ctc' or 'attention'\")\n add_arg('init_model',        str,   None,       \"The init model file of directory.\")\n add_arg('use_gpu',           bool,  True,      \"Whether use GPU to train.\")\n@@ -48,10 +52,6 @@\n         get_feeder_data = get_attention_feeder_data\n \n     num_classes = None\n-    train_images = None\n-    train_list = None\n-    test_images = None\n-    test_list = None\n     num_classes = data_reader.num_classes(\n     ) if num_classes is None else num_classes\n     data_shape = data_reader.data_shape()\n@@ -62,12 +62,12 @@\n     # data reader\n     train_reader = data_reader.train(\n         args.batch_size,\n-        train_images_dir=train_images,\n-        train_list_file=train_list,\n+        train_images_dir=args.train_images,\n+        train_list_file=args.train_list,\n         cycle=args.total_step > 0,\n         model=args.model)\n     test_reader = data_reader.test(\n-        test_images_dir=test_images, test_list_file=test_list, model=args.model)\n+        test_images_dir=args.test_images, test_list_file=args.test_list, model=args.model)\n \n     # prepare environment\n     place = fluid.CPUPlace()\n", "issue": "ocr_recognition \u7684\u53c2\u6570\u8bf4\u660e\u4e0e\u4ee3\u7801\u4e0d\u76f8\u7b26\n\u8bf4\u660e\u4e2d\u7684 --train_images \u4e0e --train_list \u4e24\u4e2a\u53c2\u6570\uff0c\u5728\u4ee3\u7801\u4e2d\u5e76\u4e0d\u5b58\u5728\uff1b\u8fd0\u884c\u65f6\uff0c\u5e26\u4e0a\u8fd9\u4e24\u4e2a\u53c2\u6570\u4f1a\u62a5\u9519\u3002\n", "before_files": [{"content": "\"\"\"Trainer for OCR CTC or attention model.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport paddle.fluid as fluid\nfrom utility import add_arguments, print_arguments, to_lodtensor, get_ctc_feeder_data, get_attention_feeder_data\nimport paddle.fluid.profiler as profiler\nfrom crnn_ctc_model import ctc_train_net\nfrom attention_model import attention_train_net\nimport data_reader\nimport argparse\nimport functools\nimport sys\nimport time\nimport os\nimport numpy as np\n\nparser = argparse.ArgumentParser(description=__doc__)\nadd_arg = functools.partial(add_arguments, argparser=parser)\n# yapf: disable\nadd_arg('batch_size',        int,   32,         \"Minibatch size.\")\nadd_arg('total_step',        int,   720000,    \"The number of iterations. Zero or less means whole training set. More than 0 means the training set might be looped until # of iterations is reached.\")\nadd_arg('log_period',        int,   1000,       \"Log period.\")\nadd_arg('save_model_period', int,   15000,      \"Save model period. '-1' means never saving the model.\")\nadd_arg('eval_period',       int,   15000,      \"Evaluate period. '-1' means never evaluating the model.\")\nadd_arg('save_model_dir',    str,   \"./models\", \"The directory the model to be saved to.\")\nadd_arg('model',    str,   \"crnn_ctc\",           \"Which type of network to be used. 'crnn_ctc' or 'attention'\")\nadd_arg('init_model',        str,   None,       \"The init model file of directory.\")\nadd_arg('use_gpu',           bool,  True,      \"Whether use GPU to train.\")\nadd_arg('min_average_window',int,   10000,     \"Min average window.\")\nadd_arg('max_average_window',int,   12500,     \"Max average window. It is proposed to be set as the number of minibatch in a pass.\")\nadd_arg('average_window',    float, 0.15,      \"Average window.\")\nadd_arg('parallel',          bool,  False,     \"Whether use parallel training.\")\nadd_arg('profile',           bool,  False,      \"Whether to use profiling.\")\nadd_arg('skip_batch_num',    int,   0,          \"The number of first minibatches to skip as warm-up for better performance test.\")\nadd_arg('skip_test',         bool,  False,      \"Whether to skip test phase.\")\n# yapf: enable\n\n\ndef train(args):\n    \"\"\"OCR training\"\"\"\n\n    if args.model == \"crnn_ctc\":\n        train_net = ctc_train_net\n        get_feeder_data = get_ctc_feeder_data\n    else:\n        train_net = attention_train_net\n        get_feeder_data = get_attention_feeder_data\n\n    num_classes = None\n    train_images = None\n    train_list = None\n    test_images = None\n    test_list = None\n    num_classes = data_reader.num_classes(\n    ) if num_classes is None else num_classes\n    data_shape = data_reader.data_shape()\n    # define network\n    sum_cost, error_evaluator, inference_program, model_average = train_net(\n        args, data_shape, num_classes)\n\n    # data reader\n    train_reader = data_reader.train(\n        args.batch_size,\n        train_images_dir=train_images,\n        train_list_file=train_list,\n        cycle=args.total_step > 0,\n        model=args.model)\n    test_reader = data_reader.test(\n        test_images_dir=test_images, test_list_file=test_list, model=args.model)\n\n    # prepare environment\n    place = fluid.CPUPlace()\n    if args.use_gpu:\n        place = fluid.CUDAPlace(0)\n    exe = fluid.Executor(place)\n\n    if 'ce_mode' in os.environ:\n        fluid.default_startup_program().random_seed = 90\n\n    exe.run(fluid.default_startup_program())\n\n    # load init model\n    if args.init_model is not None:\n        model_dir = args.init_model\n        model_file_name = None\n        if not os.path.isdir(args.init_model):\n            model_dir = os.path.dirname(args.init_model)\n            model_file_name = os.path.basename(args.init_model)\n        fluid.io.load_params(exe, dirname=model_dir, filename=model_file_name)\n        print(\"Init model from: %s.\" % args.init_model)\n\n    train_exe = exe\n    error_evaluator.reset(exe)\n    if args.parallel:\n        train_exe = fluid.ParallelExecutor(\n            use_cuda=True if args.use_gpu else False, loss_name=sum_cost.name)\n\n    fetch_vars = [sum_cost] + error_evaluator.metrics\n\n    def train_one_batch(data):\n        var_names = [var.name for var in fetch_vars]\n        if args.parallel:\n            results = train_exe.run(var_names,\n                                    feed=get_feeder_data(data, place))\n            results = [np.array(result).sum() for result in results]\n        else:\n            results = train_exe.run(feed=get_feeder_data(data, place),\n                                    fetch_list=fetch_vars)\n            results = [result[0] for result in results]\n        return results\n\n    def test(iter_num):\n        error_evaluator.reset(exe)\n        for data in test_reader():\n            exe.run(inference_program, feed=get_feeder_data(data, place))\n        _, test_seq_error = error_evaluator.eval(exe)\n        print(\"\\nTime: %s; Iter[%d]; Test seq error: %s.\\n\" % (\n            time.time(), iter_num, str(test_seq_error[0])))\n\n        #Note: The following logs are special for CE monitoring.\n        #Other situations do not need to care about these logs.\n        print(\"kpis\ttest_acc\t%f\" % (1 - test_seq_error[0]))\n\n    def save_model(args, exe, iter_num):\n        filename = \"model_%05d\" % iter_num\n        fluid.io.save_params(\n            exe, dirname=args.save_model_dir, filename=filename)\n        print(\"Saved model to: %s/%s.\" % (args.save_model_dir, filename))\n\n    iter_num = 0\n    stop = False\n    start_time = time.time()\n    while not stop:\n        total_loss = 0.0\n        total_seq_error = 0.0\n        batch_times = []\n        # train a pass\n        for data in train_reader():\n            if args.total_step > 0 and iter_num == args.total_step + args.skip_batch_num:\n                stop = True\n                break\n            if iter_num < args.skip_batch_num:\n                print(\"Warm-up iteration\")\n            if iter_num == args.skip_batch_num:\n                profiler.reset_profiler()\n            start = time.time()\n            results = train_one_batch(data)\n            batch_time = time.time() - start\n            fps = args.batch_size / batch_time\n            batch_times.append(batch_time)\n            total_loss += results[0]\n            total_seq_error += results[2]\n\n            iter_num += 1\n            # training log\n            if iter_num % args.log_period == 0:\n                print(\"\\nTime: %s; Iter[%d]; Avg loss: %.3f; Avg seq err: %.3f\" % (\n                    time.time(), iter_num,\n                    total_loss / (args.log_period * args.batch_size),\n                    total_seq_error / (args.log_period * args.batch_size)))\n                print(\"kpis\ttrain_cost\t%f\" % (total_loss / (args.log_period *\n                                                            args.batch_size)))\n                print(\"kpis\ttrain_acc\t%f\" % (\n                    1 - total_seq_error / (args.log_period * args.batch_size)))\n                total_loss = 0.0\n                total_seq_error = 0.0\n\n            # evaluate\n            if not args.skip_test and iter_num % args.eval_period == 0:\n                if model_average:\n                    with model_average.apply(exe):\n                        test(iter_num)\n                else:\n                    test(iter_num)\n\n            # save model\n            if iter_num % args.save_model_period == 0:\n                if model_average:\n                    with model_average.apply(exe):\n                        save_model(args, exe, iter_num)\n                else:\n                    save_model(args, exe, iter_num)\n        end_time = time.time()\n        print(\"kpis\ttrain_duration\t%f\" % (end_time - start_time))\n        # Postprocess benchmark data\n        latencies = batch_times[args.skip_batch_num:]\n        latency_avg = np.average(latencies)\n        latency_pc99 = np.percentile(latencies, 99)\n        fpses = np.divide(args.batch_size, latencies)\n        fps_avg = np.average(fpses)\n        fps_pc99 = np.percentile(fpses, 1)\n\n        # Benchmark output\n        print('\\nTotal examples (incl. warm-up): %d' %\n              (iter_num * args.batch_size))\n        print('average latency: %.5f s, 99pc latency: %.5f s' % (latency_avg,\n                                                                 latency_pc99))\n        print('average fps: %.5f, fps for 99pc latency: %.5f' % (fps_avg,\n                                                                 fps_pc99))\n\n\ndef main():\n    args = parser.parse_args()\n    print_arguments(args)\n    if args.profile:\n        if args.use_gpu:\n            with profiler.cuda_profiler(\"cuda_profiler.txt\", 'csv') as nvprof:\n                train(args)\n        else:\n            with profiler.profiler(\"CPU\", sorted_key='total') as cpuprof:\n                train(args)\n    else:\n        train(args)\n\n\nif __name__ == \"__main__\":\n    main()\n", "path": "fluid/PaddleCV/ocr_recognition/train.py"}], "after_files": [{"content": "\"\"\"Trainer for OCR CTC or attention model.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport paddle.fluid as fluid\nfrom utility import add_arguments, print_arguments, to_lodtensor, get_ctc_feeder_data, get_attention_feeder_data\nimport paddle.fluid.profiler as profiler\nfrom crnn_ctc_model import ctc_train_net\nfrom attention_model import attention_train_net\nimport data_reader\nimport argparse\nimport functools\nimport sys\nimport time\nimport os\nimport numpy as np\n\nparser = argparse.ArgumentParser(description=__doc__)\nadd_arg = functools.partial(add_arguments, argparser=parser)\n# yapf: disable\nadd_arg('batch_size',        int,   32,         \"Minibatch size.\")\nadd_arg('total_step',        int,   720000,    \"The number of iterations. Zero or less means whole training set. More than 0 means the training set might be looped until # of iterations is reached.\")\nadd_arg('log_period',        int,   1000,       \"Log period.\")\nadd_arg('save_model_period', int,   15000,      \"Save model period. '-1' means never saving the model.\")\nadd_arg('eval_period',       int,   15000,      \"Evaluate period. '-1' means never evaluating the model.\")\nadd_arg('save_model_dir',    str,   \"./models\", \"The directory the model to be saved to.\")\nadd_arg('train_images',      str,   None,       \"The directory of images to be used for training.\")\nadd_arg('train_list',        str,   None,       \"The list file of images to be used for training.\")\nadd_arg('test_images',       str,   None,       \"The directory of images to be used for test.\")\nadd_arg('test_list',         str,   None,       \"The list file of images to be used for training.\")\nadd_arg('model',    str,   \"crnn_ctc\",           \"Which type of network to be used. 'crnn_ctc' or 'attention'\")\nadd_arg('init_model',        str,   None,       \"The init model file of directory.\")\nadd_arg('use_gpu',           bool,  True,      \"Whether use GPU to train.\")\nadd_arg('min_average_window',int,   10000,     \"Min average window.\")\nadd_arg('max_average_window',int,   12500,     \"Max average window. It is proposed to be set as the number of minibatch in a pass.\")\nadd_arg('average_window',    float, 0.15,      \"Average window.\")\nadd_arg('parallel',          bool,  False,     \"Whether use parallel training.\")\nadd_arg('profile',           bool,  False,      \"Whether to use profiling.\")\nadd_arg('skip_batch_num',    int,   0,          \"The number of first minibatches to skip as warm-up for better performance test.\")\nadd_arg('skip_test',         bool,  False,      \"Whether to skip test phase.\")\n# yapf: enable\n\n\ndef train(args):\n    \"\"\"OCR training\"\"\"\n\n    if args.model == \"crnn_ctc\":\n        train_net = ctc_train_net\n        get_feeder_data = get_ctc_feeder_data\n    else:\n        train_net = attention_train_net\n        get_feeder_data = get_attention_feeder_data\n\n    num_classes = None\n    num_classes = data_reader.num_classes(\n    ) if num_classes is None else num_classes\n    data_shape = data_reader.data_shape()\n    # define network\n    sum_cost, error_evaluator, inference_program, model_average = train_net(\n        args, data_shape, num_classes)\n\n    # data reader\n    train_reader = data_reader.train(\n        args.batch_size,\n        train_images_dir=args.train_images,\n        train_list_file=args.train_list,\n        cycle=args.total_step > 0,\n        model=args.model)\n    test_reader = data_reader.test(\n        test_images_dir=args.test_images, test_list_file=args.test_list, model=args.model)\n\n    # prepare environment\n    place = fluid.CPUPlace()\n    if args.use_gpu:\n        place = fluid.CUDAPlace(0)\n    exe = fluid.Executor(place)\n\n    if 'ce_mode' in os.environ:\n        fluid.default_startup_program().random_seed = 90\n\n    exe.run(fluid.default_startup_program())\n\n    # load init model\n    if args.init_model is not None:\n        model_dir = args.init_model\n        model_file_name = None\n        if not os.path.isdir(args.init_model):\n            model_dir = os.path.dirname(args.init_model)\n            model_file_name = os.path.basename(args.init_model)\n        fluid.io.load_params(exe, dirname=model_dir, filename=model_file_name)\n        print(\"Init model from: %s.\" % args.init_model)\n\n    train_exe = exe\n    error_evaluator.reset(exe)\n    if args.parallel:\n        train_exe = fluid.ParallelExecutor(\n            use_cuda=True if args.use_gpu else False, loss_name=sum_cost.name)\n\n    fetch_vars = [sum_cost] + error_evaluator.metrics\n\n    def train_one_batch(data):\n        var_names = [var.name for var in fetch_vars]\n        if args.parallel:\n            results = train_exe.run(var_names,\n                                    feed=get_feeder_data(data, place))\n            results = [np.array(result).sum() for result in results]\n        else:\n            results = train_exe.run(feed=get_feeder_data(data, place),\n                                    fetch_list=fetch_vars)\n            results = [result[0] for result in results]\n        return results\n\n    def test(iter_num):\n        error_evaluator.reset(exe)\n        for data in test_reader():\n            exe.run(inference_program, feed=get_feeder_data(data, place))\n        _, test_seq_error = error_evaluator.eval(exe)\n        print(\"\\nTime: %s; Iter[%d]; Test seq error: %s.\\n\" % (\n            time.time(), iter_num, str(test_seq_error[0])))\n\n        #Note: The following logs are special for CE monitoring.\n        #Other situations do not need to care about these logs.\n        print(\"kpis\ttest_acc\t%f\" % (1 - test_seq_error[0]))\n\n    def save_model(args, exe, iter_num):\n        filename = \"model_%05d\" % iter_num\n        fluid.io.save_params(\n            exe, dirname=args.save_model_dir, filename=filename)\n        print(\"Saved model to: %s/%s.\" % (args.save_model_dir, filename))\n\n    iter_num = 0\n    stop = False\n    start_time = time.time()\n    while not stop:\n        total_loss = 0.0\n        total_seq_error = 0.0\n        batch_times = []\n        # train a pass\n        for data in train_reader():\n            if args.total_step > 0 and iter_num == args.total_step + args.skip_batch_num:\n                stop = True\n                break\n            if iter_num < args.skip_batch_num:\n                print(\"Warm-up iteration\")\n            if iter_num == args.skip_batch_num:\n                profiler.reset_profiler()\n            start = time.time()\n            results = train_one_batch(data)\n            batch_time = time.time() - start\n            fps = args.batch_size / batch_time\n            batch_times.append(batch_time)\n            total_loss += results[0]\n            total_seq_error += results[2]\n\n            iter_num += 1\n            # training log\n            if iter_num % args.log_period == 0:\n                print(\"\\nTime: %s; Iter[%d]; Avg loss: %.3f; Avg seq err: %.3f\" % (\n                    time.time(), iter_num,\n                    total_loss / (args.log_period * args.batch_size),\n                    total_seq_error / (args.log_period * args.batch_size)))\n                print(\"kpis\ttrain_cost\t%f\" % (total_loss / (args.log_period *\n                                                            args.batch_size)))\n                print(\"kpis\ttrain_acc\t%f\" % (\n                    1 - total_seq_error / (args.log_period * args.batch_size)))\n                total_loss = 0.0\n                total_seq_error = 0.0\n\n            # evaluate\n            if not args.skip_test and iter_num % args.eval_period == 0:\n                if model_average:\n                    with model_average.apply(exe):\n                        test(iter_num)\n                else:\n                    test(iter_num)\n\n            # save model\n            if iter_num % args.save_model_period == 0:\n                if model_average:\n                    with model_average.apply(exe):\n                        save_model(args, exe, iter_num)\n                else:\n                    save_model(args, exe, iter_num)\n        end_time = time.time()\n        print(\"kpis\ttrain_duration\t%f\" % (end_time - start_time))\n        # Postprocess benchmark data\n        latencies = batch_times[args.skip_batch_num:]\n        latency_avg = np.average(latencies)\n        latency_pc99 = np.percentile(latencies, 99)\n        fpses = np.divide(args.batch_size, latencies)\n        fps_avg = np.average(fpses)\n        fps_pc99 = np.percentile(fpses, 1)\n\n        # Benchmark output\n        print('\\nTotal examples (incl. warm-up): %d' %\n              (iter_num * args.batch_size))\n        print('average latency: %.5f s, 99pc latency: %.5f s' % (latency_avg,\n                                                                 latency_pc99))\n        print('average fps: %.5f, fps for 99pc latency: %.5f' % (fps_avg,\n                                                                 fps_pc99))\n\n\ndef main():\n    args = parser.parse_args()\n    print_arguments(args)\n    if args.profile:\n        if args.use_gpu:\n            with profiler.cuda_profiler(\"cuda_profiler.txt\", 'csv') as nvprof:\n                train(args)\n        else:\n            with profiler.profiler(\"CPU\", sorted_key='total') as cpuprof:\n                train(args)\n    else:\n        train(args)\n\n\nif __name__ == \"__main__\":\n    main()\n", "path": "fluid/PaddleCV/ocr_recognition/train.py"}]}