parallel_for_test.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. // Ceres Solver - A fast non-linear least squares minimizer
  2. // Copyright 2018 Google Inc. All rights reserved.
  3. // http://ceres-solver.org/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are met:
  7. //
  8. // * Redistributions of source code must retain the above copyright notice,
  9. // this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above copyright notice,
  11. // this list of conditions and the following disclaimer in the documentation
  12. // and/or other materials provided with the distribution.
  13. // * Neither the name of Google Inc. nor the names of its contributors may be
  14. // used to endorse or promote products derived from this software without
  15. // specific prior written permission.
  16. //
  17. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  18. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  20. // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  21. // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  22. // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  23. // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  24. // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  25. // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  26. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  27. // POSSIBILITY OF SUCH DAMAGE.
  28. //
  29. // Author: vitus@google.com (Michael Vitus)
  30. #include "ceres/parallel_for.h"
  31. #include <cmath>
  32. #include <condition_variable>
  33. #include <mutex>
  34. #include <numeric>
  35. #include <random>
  36. #include <thread>
  37. #include <tuple>
  38. #include <vector>
  39. #include "ceres/context_impl.h"
  40. #include "ceres/internal/config.h"
  41. #include "ceres/parallel_vector_ops.h"
  42. #include "glog/logging.h"
  43. #include "gmock/gmock.h"
  44. #include "gtest/gtest.h"
  45. namespace ceres::internal {
  46. using testing::ElementsAreArray;
  47. using testing::UnorderedElementsAreArray;
  48. // Tests the parallel for loop computes the correct result for various number of
  49. // threads.
  50. TEST(ParallelFor, NumThreads) {
  51. ContextImpl context;
  52. context.EnsureMinimumThreads(/*num_threads=*/2);
  53. const int size = 16;
  54. std::vector<int> expected_results(size, 0);
  55. for (int i = 0; i < size; ++i) {
  56. expected_results[i] = std::sqrt(i);
  57. }
  58. for (int num_threads = 1; num_threads <= 8; ++num_threads) {
  59. std::vector<int> values(size, 0);
  60. ParallelFor(&context, 0, size, num_threads, [&values](int i) {
  61. values[i] = std::sqrt(i);
  62. });
  63. EXPECT_THAT(values, ElementsAreArray(expected_results));
  64. }
  65. }
  66. // Tests parallel for loop with ranges
  67. TEST(ParallelForWithRange, NumThreads) {
  68. ContextImpl context;
  69. context.EnsureMinimumThreads(/*num_threads=*/2);
  70. const int size = 16;
  71. std::vector<int> expected_results(size, 0);
  72. for (int i = 0; i < size; ++i) {
  73. expected_results[i] = std::sqrt(i);
  74. }
  75. for (int num_threads = 1; num_threads <= 8; ++num_threads) {
  76. std::vector<int> values(size, 0);
  77. ParallelFor(
  78. &context, 0, size, num_threads, [&values](std::tuple<int, int> range) {
  79. auto [start, end] = range;
  80. for (int i = start; i < end; ++i) values[i] = std::sqrt(i);
  81. });
  82. EXPECT_THAT(values, ElementsAreArray(expected_results));
  83. }
  84. }
  85. // Tests the parallel for loop with the thread ID interface computes the correct
  86. // result for various number of threads.
  87. TEST(ParallelForWithThreadId, NumThreads) {
  88. ContextImpl context;
  89. context.EnsureMinimumThreads(/*num_threads=*/2);
  90. const int size = 16;
  91. std::vector<int> expected_results(size, 0);
  92. for (int i = 0; i < size; ++i) {
  93. expected_results[i] = std::sqrt(i);
  94. }
  95. for (int num_threads = 1; num_threads <= 8; ++num_threads) {
  96. std::vector<int> values(size, 0);
  97. ParallelFor(
  98. &context, 0, size, num_threads, [&values](int thread_id, int i) {
  99. values[i] = std::sqrt(i);
  100. });
  101. EXPECT_THAT(values, ElementsAreArray(expected_results));
  102. }
  103. }
  104. // Tests nested for loops do not result in a deadlock.
  105. TEST(ParallelFor, NestedParallelForDeadlock) {
  106. ContextImpl context;
  107. context.EnsureMinimumThreads(/*num_threads=*/2);
  108. // Increment each element in the 2D matrix.
  109. std::vector<std::vector<int>> x(3, {1, 2, 3});
  110. ParallelFor(&context, 0, 3, 2, [&x, &context](int i) {
  111. std::vector<int>& y = x.at(i);
  112. ParallelFor(&context, 0, 3, 2, [&y](int j) { ++y.at(j); });
  113. });
  114. const std::vector<int> results = {2, 3, 4};
  115. for (const std::vector<int>& value : x) {
  116. EXPECT_THAT(value, ElementsAreArray(results));
  117. }
  118. }
  119. // Tests nested for loops do not result in a deadlock for the parallel for with
  120. // thread ID interface.
  121. TEST(ParallelForWithThreadId, NestedParallelForDeadlock) {
  122. ContextImpl context;
  123. context.EnsureMinimumThreads(/*num_threads=*/2);
  124. // Increment each element in the 2D matrix.
  125. std::vector<std::vector<int>> x(3, {1, 2, 3});
  126. ParallelFor(&context, 0, 3, 2, [&x, &context](int thread_id, int i) {
  127. std::vector<int>& y = x.at(i);
  128. ParallelFor(&context, 0, 3, 2, [&y](int thread_id, int j) { ++y.at(j); });
  129. });
  130. const std::vector<int> results = {2, 3, 4};
  131. for (const std::vector<int>& value : x) {
  132. EXPECT_THAT(value, ElementsAreArray(results));
  133. }
  134. }
  135. TEST(ParallelForWithThreadId, UniqueThreadIds) {
  136. // Ensure the hardware supports more than 1 thread to ensure the test will
  137. // pass.
  138. const int num_hardware_threads = std::thread::hardware_concurrency();
  139. if (num_hardware_threads <= 1) {
  140. LOG(ERROR)
  141. << "Test not supported, the hardware does not support threading.";
  142. return;
  143. }
  144. ContextImpl context;
  145. context.EnsureMinimumThreads(/*num_threads=*/2);
  146. // Increment each element in the 2D matrix.
  147. std::vector<int> x(2, -1);
  148. std::mutex mutex;
  149. std::condition_variable condition;
  150. int count = 0;
  151. ParallelFor(&context,
  152. 0,
  153. 2,
  154. 2,
  155. [&x, &mutex, &condition, &count](int thread_id, int i) {
  156. std::unique_lock<std::mutex> lock(mutex);
  157. x[i] = thread_id;
  158. ++count;
  159. condition.notify_all();
  160. condition.wait(lock, [&]() { return count == 2; });
  161. });
  162. EXPECT_THAT(x, UnorderedElementsAreArray({0, 1}));
  163. }
  164. // Helper function for partition tests
  165. bool BruteForcePartition(
  166. int* costs, int start, int end, int max_partitions, int max_cost);
  167. // Basic test if MaxPartitionCostIsFeasible and BruteForcePartition agree on
  168. // simple test-cases
  169. TEST(GuidedParallelFor, MaxPartitionCostIsFeasible) {
  170. std::vector<int> costs, cumulative_costs, partition;
  171. costs = {1, 2, 3, 5, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0};
  172. cumulative_costs.resize(costs.size());
  173. std::partial_sum(costs.begin(), costs.end(), cumulative_costs.begin());
  174. const auto dummy_getter = [](const int v) { return v; };
  175. // [1, 2, 3] [5], [0 ... 0, 7, 0, ... 0]
  176. EXPECT_TRUE(MaxPartitionCostIsFeasible(0,
  177. costs.size(),
  178. 3,
  179. 7,
  180. 0,
  181. cumulative_costs.data(),
  182. dummy_getter,
  183. &partition));
  184. EXPECT_TRUE(BruteForcePartition(costs.data(), 0, costs.size(), 3, 7));
  185. // [1, 2, 3, 5, 0 ... 0, 7, 0, ... 0]
  186. EXPECT_TRUE(MaxPartitionCostIsFeasible(0,
  187. costs.size(),
  188. 3,
  189. 18,
  190. 0,
  191. cumulative_costs.data(),
  192. dummy_getter,
  193. &partition));
  194. EXPECT_TRUE(BruteForcePartition(costs.data(), 0, costs.size(), 3, 18));
  195. // Impossible since there is item of cost 7
  196. EXPECT_FALSE(MaxPartitionCostIsFeasible(0,
  197. costs.size(),
  198. 3,
  199. 6,
  200. 0,
  201. cumulative_costs.data(),
  202. dummy_getter,
  203. &partition));
  204. EXPECT_FALSE(BruteForcePartition(costs.data(), 0, costs.size(), 3, 6));
  205. // Impossible
  206. EXPECT_FALSE(MaxPartitionCostIsFeasible(0,
  207. costs.size(),
  208. 2,
  209. 10,
  210. 0,
  211. cumulative_costs.data(),
  212. dummy_getter,
  213. &partition));
  214. EXPECT_FALSE(BruteForcePartition(costs.data(), 0, costs.size(), 2, 10));
  215. }
  216. // Randomized tests for MaxPartitionCostIsFeasible
  217. TEST(GuidedParallelFor, MaxPartitionCostIsFeasibleRandomized) {
  218. std::vector<int> costs, cumulative_costs, partition;
  219. const auto dummy_getter = [](const int v) { return v; };
  220. // Random tests
  221. const int kNumTests = 1000;
  222. const int kMaxElements = 32;
  223. const int kMaxPartitions = 16;
  224. const int kMaxElCost = 8;
  225. std::mt19937 rng;
  226. std::uniform_int_distribution<int> rng_N(1, kMaxElements);
  227. std::uniform_int_distribution<int> rng_M(1, kMaxPartitions);
  228. std::uniform_int_distribution<int> rng_e(0, kMaxElCost);
  229. for (int t = 0; t < kNumTests; ++t) {
  230. const int N = rng_N(rng);
  231. const int M = rng_M(rng);
  232. int total = 0;
  233. costs.clear();
  234. for (int i = 0; i < N; ++i) {
  235. costs.push_back(rng_e(rng));
  236. total += costs.back();
  237. }
  238. cumulative_costs.resize(N);
  239. std::partial_sum(costs.begin(), costs.end(), cumulative_costs.begin());
  240. std::uniform_int_distribution<int> rng_seg(0, N - 1);
  241. int start = rng_seg(rng);
  242. int end = rng_seg(rng);
  243. if (start > end) std::swap(start, end);
  244. ++end;
  245. int first_admissible = 0;
  246. for (int threshold = 1; threshold <= total; ++threshold) {
  247. const bool bruteforce =
  248. BruteForcePartition(costs.data(), start, end, M, threshold);
  249. if (bruteforce && !first_admissible) {
  250. first_admissible = threshold;
  251. }
  252. const bool binary_search =
  253. MaxPartitionCostIsFeasible(start,
  254. end,
  255. M,
  256. threshold,
  257. start ? cumulative_costs[start - 1] : 0,
  258. cumulative_costs.data(),
  259. dummy_getter,
  260. &partition);
  261. EXPECT_EQ(bruteforce, binary_search);
  262. EXPECT_LE(partition.size(), M + 1);
  263. // check partition itself
  264. if (binary_search) {
  265. ASSERT_GT(partition.size(), 1);
  266. EXPECT_EQ(partition.front(), start);
  267. EXPECT_EQ(partition.back(), end);
  268. const int num_partitions = partition.size() - 1;
  269. EXPECT_LE(num_partitions, M);
  270. for (int j = 0; j < num_partitions; ++j) {
  271. int total = 0;
  272. for (int k = partition[j]; k < partition[j + 1]; ++k) {
  273. EXPECT_LT(k, end);
  274. EXPECT_GE(k, start);
  275. total += costs[k];
  276. }
  277. EXPECT_LE(total, threshold);
  278. }
  279. }
  280. }
  281. }
  282. }
  283. TEST(GuidedParallelFor, PartitionRangeForParallelFor) {
  284. std::vector<int> costs, cumulative_costs, partition;
  285. const auto dummy_getter = [](const int v) { return v; };
  286. // Random tests
  287. const int kNumTests = 1000;
  288. const int kMaxElements = 32;
  289. const int kMaxPartitions = 16;
  290. const int kMaxElCost = 8;
  291. std::mt19937 rng;
  292. std::uniform_int_distribution<int> rng_N(1, kMaxElements);
  293. std::uniform_int_distribution<int> rng_M(1, kMaxPartitions);
  294. std::uniform_int_distribution<int> rng_e(0, kMaxElCost);
  295. for (int t = 0; t < kNumTests; ++t) {
  296. const int N = rng_N(rng);
  297. const int M = rng_M(rng);
  298. int total = 0;
  299. costs.clear();
  300. for (int i = 0; i < N; ++i) {
  301. costs.push_back(rng_e(rng));
  302. total += costs.back();
  303. }
  304. cumulative_costs.resize(N);
  305. std::partial_sum(costs.begin(), costs.end(), cumulative_costs.begin());
  306. std::uniform_int_distribution<int> rng_seg(0, N - 1);
  307. int start = rng_seg(rng);
  308. int end = rng_seg(rng);
  309. if (start > end) std::swap(start, end);
  310. ++end;
  311. int first_admissible = 0;
  312. for (int threshold = 1; threshold <= total; ++threshold) {
  313. const bool bruteforce =
  314. BruteForcePartition(costs.data(), start, end, M, threshold);
  315. if (bruteforce) {
  316. first_admissible = threshold;
  317. break;
  318. }
  319. }
  320. EXPECT_TRUE(first_admissible != 0 || total == 0);
  321. partition = PartitionRangeForParallelFor(
  322. start, end, M, cumulative_costs.data(), dummy_getter);
  323. ASSERT_GT(partition.size(), 1);
  324. EXPECT_EQ(partition.front(), start);
  325. EXPECT_EQ(partition.back(), end);
  326. const int num_partitions = partition.size() - 1;
  327. EXPECT_LE(num_partitions, M);
  328. for (int j = 0; j < num_partitions; ++j) {
  329. int total = 0;
  330. for (int k = partition[j]; k < partition[j + 1]; ++k) {
  331. EXPECT_LT(k, end);
  332. EXPECT_GE(k, start);
  333. total += costs[k];
  334. }
  335. EXPECT_LE(total, first_admissible);
  336. }
  337. }
  338. }
  339. // Recursively try to partition range into segements of total cost
  340. // less than max_cost
  341. bool BruteForcePartition(
  342. int* costs, int start, int end, int max_partitions, int max_cost) {
  343. if (start == end) return true;
  344. if (start < end && max_partitions == 0) return false;
  345. int total_cost = 0;
  346. for (int last_curr = start + 1; last_curr <= end; ++last_curr) {
  347. total_cost += costs[last_curr - 1];
  348. if (total_cost > max_cost) break;
  349. if (BruteForcePartition(
  350. costs, last_curr, end, max_partitions - 1, max_cost))
  351. return true;
  352. }
  353. return false;
  354. }
  355. // Tests if guided parallel for loop computes the correct result for various
  356. // number of threads.
  357. TEST(GuidedParallelFor, NumThreads) {
  358. ContextImpl context;
  359. context.EnsureMinimumThreads(/*num_threads=*/2);
  360. const int size = 16;
  361. std::vector<int> expected_results(size, 0);
  362. for (int i = 0; i < size; ++i) {
  363. expected_results[i] = std::sqrt(i);
  364. }
  365. std::vector<int> costs, cumulative_costs;
  366. for (int i = 1; i <= size; ++i) {
  367. int cost = i * i;
  368. costs.push_back(cost);
  369. if (i == 1) {
  370. cumulative_costs.push_back(cost);
  371. } else {
  372. cumulative_costs.push_back(cost + cumulative_costs.back());
  373. }
  374. }
  375. for (int num_threads = 1; num_threads <= 8; ++num_threads) {
  376. std::vector<int> values(size, 0);
  377. ParallelFor(
  378. &context,
  379. 0,
  380. size,
  381. num_threads,
  382. [&values](int i) { values[i] = std::sqrt(i); },
  383. cumulative_costs.data(),
  384. [](const int v) { return v; });
  385. EXPECT_THAT(values, ElementsAreArray(expected_results));
  386. }
  387. }
  388. TEST(ParallelAssign, D2MulX) {
  389. const int kVectorSize = 1024 * 1024;
  390. const int kMaxNumThreads = 8;
  391. const double kEpsilon = 1e-16;
  392. const Vector D_full = Vector::Random(kVectorSize * 2);
  393. const ConstVectorRef D(D_full.data() + kVectorSize, kVectorSize);
  394. const Vector x = Vector::Random(kVectorSize);
  395. const Vector y_expected = D.array().square() * x.array();
  396. ContextImpl context;
  397. context.EnsureMinimumThreads(kMaxNumThreads);
  398. for (int num_threads = 1; num_threads <= kMaxNumThreads; ++num_threads) {
  399. Vector y_observed(kVectorSize);
  400. ParallelAssign(
  401. &context, num_threads, y_observed, D.array().square() * x.array());
  402. // We might get non-bit-exact result due to different precision in scalar
  403. // and vector code. For example, in x86 mode mingw might emit x87
  404. // instructions for scalar code, thus making bit-exact check fail
  405. EXPECT_NEAR((y_expected - y_observed).squaredNorm(),
  406. 0.,
  407. kEpsilon * y_expected.squaredNorm());
  408. }
  409. }
  410. TEST(ParallelAssign, SetZero) {
  411. const int kVectorSize = 1024 * 1024;
  412. const int kMaxNumThreads = 8;
  413. ContextImpl context;
  414. context.EnsureMinimumThreads(kMaxNumThreads);
  415. for (int num_threads = 1; num_threads <= kMaxNumThreads; ++num_threads) {
  416. Vector x = Vector::Random(kVectorSize);
  417. ParallelSetZero(&context, num_threads, x);
  418. CHECK_EQ(x.squaredNorm(), 0.);
  419. }
  420. }
  421. } // namespace ceres::internal