You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ir_callback_test.cc 15 kB

4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. /**
  2. * Copyright 2020-2021 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <memory>
  17. #include <list>
  18. #include "common/common.h"
  19. #include "minddata/dataset/callback/ds_callback.h"
  20. #include "minddata/dataset/core/client.h"
  21. #include "minddata/dataset/engine/datasetops/epoch_ctrl_op.h"
  22. #include "minddata/dataset/engine/datasetops/source/random_data_op.h"
  23. #include "minddata/dataset/engine/tree_adapter.h"
  24. #include "minddata/dataset/include/dataset/datasets.h"
  25. #include "minddata/dataset/include/dataset/transforms.h"
  26. #include "minddata/dataset/kernels/data/no_op.h"
  27. #include "utils/log_adapter.h"
  28. using namespace mindspore::dataset;
  29. using mindspore::LogStream;
  30. using mindspore::MsLogLevel::INFO;
  31. namespace mindspore {
  32. namespace dataset {
  33. namespace test {
  34. class TestCallback : public DSCallback {
  35. public:
  36. TestCallback(int32_t step_size)
  37. : DSCallback(step_size),
  38. begin_(true),
  39. epoch_begin_(true),
  40. step_begin_(true),
  41. end_(false),
  42. epoch_end_(true),
  43. step_end_(true) {
  44. all_names_.reserve(32);
  45. all_step_nums_.reserve(32);
  46. all_ep_nums_.reserve(32);
  47. }
  48. Status DSBegin(const CallbackParam &cb_param) override {
  49. std::lock_guard<std::mutex> guard(lock_);
  50. all_names_.push_back("BGN");
  51. all_step_nums_.push_back(cb_param.cur_step_num_);
  52. all_ep_nums_.push_back(cb_param.cur_epoch_num_);
  53. return Status::OK();
  54. }
  55. Status DSEpochBegin(const CallbackParam &cb_param) override {
  56. std::lock_guard<std::mutex> guard(lock_);
  57. all_names_.push_back("EPBGN");
  58. all_step_nums_.push_back(cb_param.cur_step_num_);
  59. all_ep_nums_.push_back(cb_param.cur_epoch_num_);
  60. return Status::OK();
  61. }
  62. Status DSNStepBegin(const CallbackParam &cb_param) override {
  63. std::lock_guard<std::mutex> guard(lock_);
  64. all_names_.push_back("SPBGN");
  65. all_step_nums_.push_back(cb_param.cur_step_num_);
  66. all_ep_nums_.push_back(cb_param.cur_epoch_num_);
  67. return Status::OK();
  68. }
  69. Status DSEnd(const CallbackParam &cb_param) override {
  70. std::lock_guard<std::mutex> guard(lock_);
  71. all_names_.push_back("END");
  72. all_step_nums_.push_back(cb_param.cur_step_num_);
  73. all_ep_nums_.push_back(cb_param.cur_epoch_num_);
  74. return Status::OK();
  75. }
  76. Status DSEpochEnd(const CallbackParam &cb_param) override {
  77. std::lock_guard<std::mutex> guard(lock_);
  78. all_names_.push_back("EPEND");
  79. all_step_nums_.push_back(cb_param.cur_step_num_);
  80. all_ep_nums_.push_back(cb_param.cur_epoch_num_);
  81. return Status::OK();
  82. }
  83. Status DSNStepEnd(const CallbackParam &cb_param) override {
  84. std::lock_guard<std::mutex> guard(lock_);
  85. all_names_.push_back("SPEND");
  86. all_step_nums_.push_back(cb_param.cur_step_num_);
  87. all_ep_nums_.push_back(cb_param.cur_epoch_num_);
  88. return Status::OK();
  89. }
  90. bool IsBeginNeeded() override { return begin_; }
  91. bool IsEpochBeginNeeded() override { return epoch_begin_; }
  92. bool IsNStepBeginNeeded() override { return step_begin_; }
  93. bool IsEndNeeded() override { return end_; }
  94. bool IsEpochEndNeeded() override { return epoch_end_; }
  95. bool IsNStepEndNeeded() override { return step_end_; }
  96. std::vector<std::string> all_names(size_t len) {
  97. std::vector<std::string> res(all_names_.begin(), all_names_.begin() + len);
  98. std::sort(res.begin(), res.end());
  99. return res;
  100. }
  101. std::vector<int64_t> all_step_nums(size_t len) {
  102. std::vector<int64_t> res(all_step_nums_.begin(), all_step_nums_.begin() + len);
  103. std::sort(res.begin(), res.end());
  104. return res;
  105. }
  106. std::vector<int64_t> all_ep_nums(size_t len) {
  107. std::vector<int64_t> res(all_ep_nums_.begin(), all_ep_nums_.begin() + len);
  108. std::sort(res.begin(), res.end());
  109. return res;
  110. }
  111. // flag for turning callback on and off
  112. bool begin_, epoch_begin_, step_begin_, end_, epoch_end_, step_end_;
  113. // name of the callback function in sequence, BGN, EPBGN, SPB, END, EPEND, SPEND
  114. std::vector<std::string> all_names_;
  115. std::vector<int64_t> all_step_nums_, all_ep_nums_;
  116. std::mutex lock_;
  117. };
  118. } // namespace test
  119. } // namespace dataset
  120. } // namespace mindspore
  121. class MindDataTestCallback : public UT::DatasetOpTesting {
  122. public:
  123. void SetUp() override {
  124. DatasetOpTesting::SetUp();
  125. GlobalInit();
  126. }
  127. void TestBasicCallback(std::shared_ptr<ExecutionTree> tree, std::shared_ptr<DatasetOp> callback_node,
  128. int32_t step_size) {
  129. // config callback
  130. Status rc;
  131. std::shared_ptr<test::TestCallback> tst_cb = std::make_shared<test::TestCallback>(step_size);
  132. std::shared_ptr<DSCallback> cb1 = tst_cb;
  133. std::vector<std::shared_ptr<DSCallback>> cbs = {};
  134. cbs.push_back(cb1);
  135. callback_node->AddCallbacks(std::move(cbs));
  136. ASSERT_OK(tree->Prepare());
  137. ASSERT_OK(tree->Launch());
  138. // Start the loop of reading tensors from our pipeline
  139. DatasetIterator di(tree);
  140. TensorMap tensor_map;
  141. rc = di.GetNextAsMap(&tensor_map);
  142. EXPECT_TRUE(rc.IsOk());
  143. while (!tensor_map.empty()) {
  144. rc = di.GetNextAsMap(&tensor_map);
  145. EXPECT_TRUE(rc.IsOk());
  146. }
  147. std::vector<std::string> callback_names = {"BGN", "EPBGN", "SPBGN", "SPEND", "SPBGN", "SPEND", "EPEND"};
  148. std::sort(callback_names.begin(), callback_names.end());
  149. std::vector<int64_t> all_steps = {0, 0, 1, 1, 65, 65, 88};
  150. std::vector<int64_t> all_epochs = {0, 1, 1, 1, 1, 1, 1};
  151. // doing resize to make sure no unexpected epoch_end or extra epoch_begin is called
  152. size_t len = 7;
  153. EXPECT_EQ(tst_cb->all_names(len), callback_names);
  154. EXPECT_EQ(tst_cb->all_step_nums(len), all_steps);
  155. EXPECT_EQ(tst_cb->all_ep_nums(len), all_epochs);
  156. }
  157. std::vector<std::shared_ptr<DatasetOp>> GenerateNodes() {
  158. // config leaf_op, use random_data to avoid I/O
  159. std::unique_ptr<DataSchema> schema = std::make_unique<DataSchema>();
  160. TensorShape shape({}); // empty shape is a 1-value scalar Tensor
  161. ColDescriptor col("label", DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 0, &shape);
  162. EXPECT_OK(schema->AddColumn(col));
  163. std::shared_ptr<ConfigManager> config_manager = GlobalContext::config_manager();
  164. int32_t op_connector_size = config_manager->op_connector_size();
  165. int32_t num_workers = config_manager->num_parallel_workers();
  166. int32_t num_rows = 44;
  167. std::shared_ptr<RandomDataOp> leaf =
  168. std::make_shared<RandomDataOp>(num_workers, op_connector_size, num_rows, std::move(schema));
  169. // config mapOp
  170. std::vector<std::string> input_columns = {"label"};
  171. std::vector<std::string> output_columns = {};
  172. std::vector<std::shared_ptr<TensorOp>> op_list;
  173. std::shared_ptr<TensorOp> my_no_op = std::make_shared<NoOp>();
  174. op_list.push_back(my_no_op);
  175. std::shared_ptr<MapOp> map_op =
  176. std::make_shared<MapOp>(input_columns, output_columns, std::move(op_list), num_workers, op_connector_size);
  177. PadInfo pad_map;
  178. std::shared_ptr<BatchOp> batch_op =
  179. std::make_shared<BatchOp>(1, false, false, op_connector_size, num_workers, std::vector<std::string>{}, pad_map);
  180. // config RepeatOp
  181. int32_t num_repeats = 2;
  182. std::shared_ptr<RepeatOp> repeat_op = std::make_shared<RepeatOp>(num_repeats);
  183. // start build then launch tree
  184. leaf->SetTotalRepeats(num_repeats);
  185. leaf->SetNumRepeatsPerEpoch(num_repeats);
  186. map_op->SetTotalRepeats(num_repeats);
  187. map_op->SetNumRepeatsPerEpoch(num_repeats);
  188. batch_op->SetTotalRepeats(num_repeats);
  189. batch_op->SetNumRepeatsPerEpoch(num_repeats);
  190. return {leaf, map_op, batch_op, repeat_op};
  191. }
  192. };
  193. /// Feature: Callback
  194. /// Description: Test callbacks with mappable dataset (RandomDataset)
  195. /// Expectation: number and order of callbacks generated are correct
  196. TEST_F(MindDataTestCallback, TestBasicCallback) {
  197. MS_LOG(INFO) << "Doing: MindDataTestCallback-TestBasicCallback";
  198. // Test Mapop
  199. auto nodes = GenerateNodes();
  200. auto tree = Build(nodes);
  201. TestBasicCallback(tree, nodes[1], 64);
  202. // Test LeafOp
  203. nodes = GenerateNodes();
  204. tree = Build(nodes);
  205. TestBasicCallback(tree, nodes[0], 64);
  206. // Test BatchOp
  207. nodes = GenerateNodes();
  208. tree = Build(nodes);
  209. TestBasicCallback(tree, nodes[2], 64);
  210. }
  211. TEST_F(MindDataTestCallback, TestMultiEpochCallback) {
  212. MS_LOG(INFO) << "Doing: MindDataTestCallback-TestMultiEpochCallback";
  213. // config callback
  214. Status rc;
  215. std::shared_ptr<test::TestCallback> tst_cb = std::make_shared<test::TestCallback>(4);
  216. std::shared_ptr<DSCallback> cb1 = tst_cb;
  217. // config leaf_op, use random_data to avoid I/O
  218. std::shared_ptr<ConfigManager> config_manager = GlobalContext::config_manager();
  219. int32_t op_connector_size = config_manager->op_connector_size();
  220. int32_t num_workers = config_manager->num_parallel_workers();
  221. std::unique_ptr<DataSchema> schema = std::make_unique<DataSchema>();
  222. TensorShape shape({}); // empty shape is a 1-value scalar Tensor
  223. ColDescriptor col("label", DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 0, &shape);
  224. ASSERT_OK(schema->AddColumn(col));
  225. std::shared_ptr<RandomDataOp> leaf = std::make_shared<RandomDataOp>(4, op_connector_size, 4, std::move(schema));
  226. // config mapOp
  227. std::vector<std::string> input_columns = {"label"};
  228. std::vector<std::string> output_columns = {};
  229. std::vector<std::shared_ptr<TensorOp>> op_list;
  230. std::shared_ptr<TensorOp> my_no_op = std::make_shared<NoOp>();
  231. op_list.push_back(my_no_op);
  232. std::shared_ptr<MapOp> map_op =
  233. std::make_shared<MapOp>(input_columns, output_columns, std::move(op_list), num_workers, op_connector_size);
  234. std::vector<std::shared_ptr<DSCallback>> cbs = {};
  235. cbs.push_back(cb1);
  236. map_op->AddCallbacks(std::move(cbs));
  237. EXPECT_TRUE(rc.IsOk());
  238. int32_t num_repeats = 2;
  239. // config RepeatOp
  240. std::shared_ptr<RepeatOp> repeat_op = std::make_shared<RepeatOp>(num_repeats);
  241. // config EpochCtrlOp
  242. std::shared_ptr<EpochCtrlOp> epoch_ctrl_op = std::make_shared<EpochCtrlOp>(num_repeats);
  243. // start build then launch tree
  244. leaf->SetTotalRepeats(4);
  245. leaf->SetNumRepeatsPerEpoch(2);
  246. map_op->SetTotalRepeats(4);
  247. map_op->SetNumRepeatsPerEpoch(2);
  248. std::shared_ptr<ExecutionTree> tree = Build({leaf, map_op, repeat_op, epoch_ctrl_op});
  249. rc = tree->Prepare();
  250. EXPECT_TRUE(rc.IsOk());
  251. rc = tree->Launch();
  252. EXPECT_TRUE(rc.IsOk());
  253. // Start the loop of reading tensors from our pipeline
  254. DatasetIterator di(tree);
  255. TensorMap tensor_map;
  256. size_t num_epochs = 2;
  257. for (int ep_num = 0; ep_num < num_epochs; ++ep_num) {
  258. ASSERT_OK(di.GetNextAsMap(&tensor_map));
  259. EXPECT_TRUE(rc.IsOk());
  260. while (tensor_map.size() != 0) {
  261. rc = di.GetNextAsMap(&tensor_map);
  262. EXPECT_TRUE(rc.IsOk());
  263. }
  264. }
  265. std::vector<std::string> callback_names = {"BGN", "EPBGN", "SPBGN", "SPEND", "SPBGN", "SPEND", "EPEND",
  266. "EPBGN", "SPBGN", "SPEND", "SPBGN", "SPEND", "EPEND"};
  267. std::sort(callback_names.begin(), callback_names.end());
  268. std::vector<int64_t> all_steps = {0, 0, 1, 1, 5, 5, 8, 8, 9, 9, 13, 13, 16};
  269. std::vector<int64_t> all_epochs = {0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2};
  270. size_t len = 13;
  271. EXPECT_EQ(tst_cb->all_names(len), callback_names);
  272. EXPECT_EQ(tst_cb->all_ep_nums(len), all_epochs);
  273. EXPECT_EQ(tst_cb->all_step_nums(len), all_steps);
  274. }
  275. TEST_F(MindDataTestCallback, TestSelectedCallback) {
  276. MS_LOG(INFO) << "Doing: MindDataTestCallback-TestSelectedCallback";
  277. // config callback
  278. Status rc;
  279. std::shared_ptr<test::TestCallback> tst_cb = std::make_shared<test::TestCallback>(4);
  280. // turn off the epochs
  281. tst_cb->epoch_begin_ = false;
  282. tst_cb->epoch_end_ = false;
  283. std::shared_ptr<SchemaObj> schema = Schema();
  284. ASSERT_OK(schema->add_column("label", mindspore::DataType::kNumberTypeUInt32, {}));
  285. std::shared_ptr<Dataset> ds = RandomData(4, schema);
  286. ASSERT_NE(ds, nullptr);
  287. ds->SetNumWorkers(1);
  288. // config mapOp
  289. ds = ds->Map({std::make_shared<transforms::TypeCast>(mindspore::DataType::kNumberTypeUInt64)}, {"label"}, {}, {},
  290. nullptr, {tst_cb});
  291. ds->SetNumWorkers(1);
  292. ASSERT_NE(ds, nullptr);
  293. ds = ds->Repeat(2);
  294. ASSERT_NE(ds, nullptr);
  295. int32_t num_epochs = 2;
  296. auto itr = ds->CreateIterator({}, num_epochs);
  297. for (int ep_num = 0; ep_num < num_epochs; ++ep_num) {
  298. std::unordered_map<std::string, mindspore::MSTensor> row;
  299. ASSERT_OK(itr->GetNextRow(&row));
  300. while (!row.empty()) {
  301. ASSERT_OK(itr->GetNextRow(&row));
  302. }
  303. }
  304. std::vector<std::string> callback_names = {"BGN", "SPBGN", "SPEND", "SPBGN", "SPEND",
  305. "SPBGN", "SPEND", "SPBGN", "SPEND"};
  306. std::sort(callback_names.begin(), callback_names.end());
  307. std::vector<int64_t> all_steps = {0, 1, 1, 5, 5, 9, 9, 13, 13};
  308. std::vector<int64_t> all_epochs = {0, 1, 1, 1, 1, 2, 2, 2, 2};
  309. size_t len = 9;
  310. EXPECT_EQ(tst_cb->all_names(len), callback_names);
  311. EXPECT_EQ(tst_cb->all_ep_nums(len), all_epochs);
  312. EXPECT_EQ(tst_cb->all_step_nums(len), all_steps);
  313. }
  314. TEST_F(MindDataTestCallback, TestCAPICallback) {
  315. MS_LOG(INFO) << "Doing: MindDataTestCallback-TestCAPICallback";
  316. // config callback
  317. std::shared_ptr<test::TestCallback> tst_cb = std::make_shared<test::TestCallback>(64);
  318. std::shared_ptr<DSCallback> cb1 = tst_cb;
  319. // Create a RandomDataset. Use random_data to avoid I/O
  320. std::shared_ptr<SchemaObj> schema = Schema();
  321. ASSERT_OK(schema->add_column("label", mindspore::DataType::kNumberTypeUInt32, {}));
  322. std::shared_ptr<Dataset> ds = RandomData(44, schema);
  323. ASSERT_NE(ds, nullptr);
  324. ds = ds->Map({std::make_shared<transforms::TypeCast>(mindspore::DataType::kNumberTypeUInt64)}, {"label"}, {}, {},
  325. nullptr, {cb1});
  326. ASSERT_NE(ds, nullptr);
  327. ds = ds->Repeat(2);
  328. ASSERT_NE(ds, nullptr);
  329. auto tree_adapter = std::make_shared<TreeAdapter>();
  330. // Disable IR optimization pass
  331. tree_adapter->SetOptimize(false);
  332. // using tree_adapter to set num_epoch = 1
  333. ASSERT_OK(tree_adapter->Compile(ds->IRNode(), 1));
  334. TensorRow row;
  335. ASSERT_OK(tree_adapter->GetNext(&row));
  336. while (!row.empty()) {
  337. ASSERT_OK(tree_adapter->GetNext(&row));
  338. }
  339. std::vector<std::string> callback_names = {"BGN", "EPBGN", "SPBGN", "SPEND", "SPBGN", "SPEND", "EPEND"};
  340. std::sort(callback_names.begin(), callback_names.end());
  341. std::vector<int64_t> all_steps = {0, 0, 1, 1, 65, 65, 88};
  342. std::vector<int64_t> all_epochs = {0, 1, 1, 1, 1, 1, 1};
  343. // doing resize to make sure no unexpected epoch_end or extra epoch_begin is called
  344. size_t len = 7;
  345. EXPECT_EQ(tst_cb->all_names(len), callback_names);
  346. EXPECT_EQ(tst_cb->all_step_nums(len), all_steps);
  347. EXPECT_EQ(tst_cb->all_ep_nums(len), all_epochs);
  348. }