Tpetra parallel linear algebra Version of the Day
Tpetra_Details_copyOffsets.hpp
Go to the documentation of this file.
1/*
2// @HEADER
3// ***********************************************************************
4//
5// Tpetra: Templated Linear Algebra Services Package
6// Copyright (2008) Sandia Corporation
7//
8// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
9// the U.S. Government retains certain rights in this software.
10//
11// Redistribution and use in source and binary forms, with or without
12// modification, are permitted provided that the following conditions are
13// met:
14//
15// 1. Redistributions of source code must retain the above copyright
16// notice, this list of conditions and the following disclaimer.
17//
18// 2. Redistributions in binary form must reproduce the above copyright
19// notice, this list of conditions and the following disclaimer in the
20// documentation and/or other materials provided with the distribution.
21//
22// 3. Neither the name of the Corporation nor the names of the
23// contributors may be used to endorse or promote products derived from
24// this software without specific prior written permission.
25//
26// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
27// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
30// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
31// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
32// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
33// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
34// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
35// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
36// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37//
38// ************************************************************************
39// @HEADER
40*/
41
42#ifndef TPETRA_DETAILS_COPYOFFSETS_HPP
43#define TPETRA_DETAILS_COPYOFFSETS_HPP
44
49
50#include "TpetraCore_config.h"
52#include "Kokkos_Core.hpp"
53#include <limits>
54#include <type_traits>
55
56namespace Tpetra {
57namespace Details {
58
59//
60// Implementation details for copyOffsets (see below).
61// Users should skip over this anonymous namespace.
62//
63namespace { // (anonymous)
64
65 // Implementation detail of copyOffsets (see below). Determines
66 // whether integer overflow is impossible on assignment from an
67 // InputType to an OutputType.
68 //
69 // Implicit here is the assumption that both input and output types
70 // are integers.
71 template<class OutputType, class InputType>
72 struct OutputCanFitInput {
73 private:
74 static constexpr bool output_signed = std::is_signed<OutputType>::value;
75 static constexpr bool input_signed = std::is_signed<InputType>::value;
76
77 public:
78 static const bool value = sizeof (OutputType) > sizeof (InputType) ||
79 (sizeof (OutputType) == sizeof (InputType) &&
80 ! output_signed && input_signed);
81 };
82
83 // Avoid warnings for "unsigned integer < 0" comparisons.
84 template<class InputType,
85 bool input_signed = std::is_signed<InputType>::value>
86 struct Negative {};
87
88 template<class InputType>
89 struct Negative<InputType, true> {
90 static KOKKOS_INLINE_FUNCTION bool
91 negative (const InputType src) {
92 return src < InputType (0);
93 }
94 };
95
96 template<class InputType>
97 struct Negative<InputType, false> {
98 static KOKKOS_INLINE_FUNCTION bool
99 negative (const InputType /* src */) {
100 return false;
101 }
102 };
103
104 template<class InputType>
105 KOKKOS_INLINE_FUNCTION bool negative (const InputType src) {
106 return Negative<InputType>::negative (src);
107 }
108
109 template<class OutputType, class InputType>
110 struct OverflowChecker {
111 private:
112 static constexpr bool output_signed = std::is_signed<OutputType>::value;
113 static constexpr bool input_signed = std::is_signed<InputType>::value;
114
115 public:
116 // 1. Signed to unsigned could overflow due to negative numbers.
117 // 2. Larger to smaller could overflow.
118 // 3. Same size but unsigned to signed could overflow.
119 static constexpr bool could_overflow =
120 (! output_signed && input_signed) ||
121 (sizeof (OutputType) < sizeof (InputType)) ||
122 (sizeof (OutputType) == sizeof (InputType) &&
123 output_signed && ! input_signed);
124
125 KOKKOS_INLINE_FUNCTION bool
126 overflows (const InputType src) const
127 {
128 if (! could_overflow) {
129 return false;
130 }
131 else {
132 // Signed to unsigned could overflow due to negative numbers.
133 if (! output_signed && input_signed) {
134 return negative (src);
135 }
136 // We're only comparing InputType with InputType here, so this
137 // should not emit warnings.
138 return src < minDstVal_ || src > maxDstVal_;
139 }
140 }
141
142 private:
143 // If InputType is unsigned and OutputType is signed, casting max
144 // OutputType to InputType could overflow. See #5548.
145 InputType minDstVal_ = input_signed ?
146 std::numeric_limits<OutputType>::min () : OutputType (0);
147 InputType maxDstVal_ = std::numeric_limits<OutputType>::max ();
148 };
149
150
151 template<class OutputViewType, class InputViewType>
152 void
153 errorIfOverflow (const OutputViewType& dst,
154 const InputViewType& src,
155 const size_t overflowCount)
156 {
157 if (overflowCount == 0) {
158 return;
159 }
160
161 std::ostringstream os;
162 const bool plural = overflowCount != size_t (1);
163 os << "copyOffsets: " << overflowCount << " value" <<
164 (plural ? "s" : "") << " in src were too big (in the "
165 "sense of integer overflow) to fit in dst.";
166
167 const bool verbose = Details::Behavior::verbose ();
168 if (verbose) {
169 const size_t maxNumToPrint =
171 const size_t srcLen (src.extent (0));
172 if (srcLen <= maxNumToPrint) {
173 auto dst_h = Kokkos::create_mirror_view (dst);
174 auto src_h = Kokkos::create_mirror_view (src);
175 Kokkos::deep_copy (src_h, src);
176 Kokkos::deep_copy (dst_h, dst);
177
178 os << " src: [";
179 for (size_t k = 0; k < srcLen; ++k) {
180 os << src_h[k];
181 if (k + size_t (1) < srcLen) {
182 os << ", ";
183 }
184 }
185 os << "], ";
186
187 os << " dst: [";
188 for (size_t k = 0; k < srcLen; ++k) {
189 os << dst_h[k];
190 if (k + size_t (1) < srcLen) {
191 os << ", ";
192 }
193 }
194 os << "].";
195 }
196 else {
197 os << " src.extent(0) > " << maxNumToPrint << ", Tpetra's "
198 "verbose print count threshold. To increase this, set the "
199 "environment variable TPETRA_VERBOSE_PRINT_COUNT_THRESHOLD "
200 "to the desired threshold and rerun. You do NOT need to "
201 "rebuild Trilinos.";
202 }
203 }
204 TEUCHOS_TEST_FOR_EXCEPTION(true, std::runtime_error, os.str ());
205 }
206
207 // Implementation detail of copyOffsets (see below).
208 //
209 // Kokkos parallel_reduce functor for copying offset ("ptr") arrays.
210 // Tpetra::Details::FixedHashTable uses this in its "copy"
211 // constructor for converting between different Device types. All
212 // the action happens in the partial specializations for different
213 // values of outputCanFitInput. "Output can fit input" means that
214 // casting the input's value type to the output's value type will
215 // never result in integer overflow.
216 template<class OutputViewType,
217 class InputViewType,
218 const bool outputCanFitInput =
219 OutputCanFitInput<typename OutputViewType::non_const_value_type,
220 typename InputViewType::non_const_value_type>::value>
221 class CopyOffsetsFunctor {};
222
223 // Specialization for when overflow is possible.
224 template<class OutputViewType, class InputViewType>
225 class CopyOffsetsFunctor<OutputViewType, InputViewType, false> {
226 public:
227 using execution_space = typename OutputViewType::execution_space;
228 using size_type = typename OutputViewType::size_type;
229 using value_type = size_t;
230
231 using input_value_type = typename InputViewType::non_const_value_type;
232 using output_value_type = typename OutputViewType::non_const_value_type;
233
234 CopyOffsetsFunctor (const OutputViewType& dst, const InputViewType& src) :
235 dst_ (dst), src_ (src)
236 {
237 static_assert (Kokkos::Impl::SpaceAccessibility<
238 typename OutputViewType::memory_space,
239 typename InputViewType::memory_space>::accessible,
240 "CopyOffsetsFunctor (implements copyOffsets): Output "
241 "View's space must be able to access the input View's "
242 "memory space.");
243 }
244
245 KOKKOS_INLINE_FUNCTION void
246 operator () (const size_type i, value_type& overflowCount) const {
247 const input_value_type src_i = src_(i);
248 if (checker_.overflows (src_i)) {
249 ++overflowCount;
250 }
251 dst_(i) = static_cast<output_value_type> (src_i);
252 }
253
254 KOKKOS_INLINE_FUNCTION void
255 operator () (const size_type i) const {
256 const input_value_type src_i = src_(i);
257 dst_(i) = static_cast<output_value_type> (src_i);
258 }
259
260 KOKKOS_INLINE_FUNCTION void init (value_type& overflowCount) const {
261 overflowCount = 0;
262 }
263
264 KOKKOS_INLINE_FUNCTION void
265 join (volatile value_type& result,
266 const volatile value_type& current) const {
267 result += current;
268 }
269
270 private:
271 OutputViewType dst_;
272 InputViewType src_;
273 OverflowChecker<output_value_type, input_value_type> checker_;
274 };
275
276 // Specialization for when overflow is impossible.
277 template<class OutputViewType, class InputViewType>
278 class CopyOffsetsFunctor<OutputViewType, InputViewType, true> {
279 public:
280 using execution_space = typename OutputViewType::execution_space;
281 using size_type = typename OutputViewType::size_type;
282 using value_type = size_t;
283
284 CopyOffsetsFunctor (const OutputViewType& dst, const InputViewType& src) :
285 dst_ (dst),
286 src_ (src)
287 {
288 static_assert (Kokkos::Impl::SpaceAccessibility<
289 typename OutputViewType::memory_space,
290 typename InputViewType::memory_space>::accessible,
291 "CopyOffsetsFunctor (implements copyOffsets): Output "
292 "View's space must be able to access the input View's "
293 "memory space.");
294 }
295
296 KOKKOS_INLINE_FUNCTION void
297 operator () (const size_type i, value_type& /* overflowCount */) const {
298 // Overflow is impossible in this case, so there's no need to check.
299 dst_(i) = src_(i);
300 }
301
302 KOKKOS_INLINE_FUNCTION void
303 operator () (const size_type i) const {
304 dst_(i) = src_(i);
305 }
306
307 KOKKOS_INLINE_FUNCTION void init (value_type& overflowCount) const {
308 overflowCount = 0;
309 }
310
311 KOKKOS_INLINE_FUNCTION void
312 join (volatile value_type& /* result */,
313 const volatile value_type& /* current */) const
314 {}
315
316 private:
317 OutputViewType dst_;
318 InputViewType src_;
319 };
320
321 // Implementation detail of copyOffsets (see below).
322 //
323 // We specialize copyOffsets on two different conditions:
324 //
325 // 1. Are the two Views' layouts the same, and do the input and
326 // output Views have the same value type?
327 // 2. Can the output View's execution space access the input View's
328 // memory space?
329 //
330 // If (1) is true, that makes the implementation simple: just call
331 // Kokkos::deep_copy (FixedHashTable always uses the same layout, no
332 // matter the device type). Otherwise, we need a custom copy
333 // functor. If (2) is true, then we can use CopyOffsetsFunctor
334 // directly. Otherwise, we have to copy the input View into the
335 // output View's memory space, before we can use the functor.
336 //
337 template<class OutputViewType,
338 class InputViewType,
339 const bool sameLayoutsSameOffsetTypes =
340 std::is_same<typename OutputViewType::array_layout,
341 typename InputViewType::array_layout>::value &&
342 std::is_same<typename OutputViewType::non_const_value_type,
343 typename InputViewType::non_const_value_type>::value,
344 const bool outputExecSpaceCanAccessInputMemSpace =
345 Kokkos::Impl::SpaceAccessibility<
346 typename OutputViewType::memory_space,
347 typename InputViewType::memory_space>::accessible>
348 struct CopyOffsetsImpl {
349 static void run (const OutputViewType& dst, const InputViewType& src);
350 };
351
352 // Specialization for sameLayoutsSameOffsetTypes = true:
353 //
354 // If both input and output Views have the same layout, and both
355 // input and output use the same type for offsets, then we don't
356 // need to check for overflow, and we can use Kokkos::deep_copy
357 // directly. It doesn't matter whether the output execution space
358 // can access the input memory space: Kokkos::deep_copy takes care
359 // of the details.
360 template<class OutputViewType,
361 class InputViewType,
362 const bool outputExecSpaceCanAccessInputMemSpace>
363 struct CopyOffsetsImpl<OutputViewType, InputViewType,
364 true, outputExecSpaceCanAccessInputMemSpace> {
365 static void run (const OutputViewType& dst, const InputViewType& src) {
366 static_assert (std::is_same<typename OutputViewType::non_const_value_type,
367 typename InputViewType::non_const_value_type>::value,
368 "CopyOffsetsImpl (implementation of copyOffsets): In order"
369 " to call this specialization, the input and output must "
370 "use the same offset type.");
371 static_assert (static_cast<int> (OutputViewType::rank) ==
372 static_cast<int> (InputViewType::rank),
373 "CopyOffsetsImpl (implementation of copyOffsets): In order"
374 " to call this specialization, src and dst must have the "
375 "same rank.");
376 static_assert (std::is_same<typename OutputViewType::array_layout,
377 typename InputViewType::array_layout>::value,
378 "CopyOffsetsImpl (implementation of copyOffsets): In order"
379 " to call this specialization, src and dst must have the "
380 "the same array_layout.");
381 Kokkos::deep_copy (dst, src);
382 }
383 };
384
385 // Specializations for sameLayoutsSameOffsetTypes = false:
386 //
387 // If input and output don't have the same layout, or use different
388 // types for offsets, then we can't use Kokkos::deep_copy directly,
389 // and we may have to check for overflow.
390
391 // Specialization for sameLayoutsSameOffsetTypes = false and
392 // outputExecSpaceCanAccessInputMemSpace = true:
393 //
394 // If the output execution space can access the input memory space,
395 // then we can use CopyOffsetsFunctor directly.
396 template<class OutputViewType,
397 class InputViewType>
398 struct CopyOffsetsImpl<OutputViewType, InputViewType,
399 false, true> {
400 static void run (const OutputViewType& dst, const InputViewType& src) {
401 static_assert (static_cast<int> (OutputViewType::rank) ==
402 static_cast<int> (InputViewType::rank),
403 "CopyOffsetsImpl (implementation of copyOffsets): "
404 "src and dst must have the same rank.");
405 constexpr bool sameLayoutsSameOffsetTypes =
406 std::is_same<typename OutputViewType::array_layout,
407 typename InputViewType::array_layout>::value &&
408 std::is_same<typename OutputViewType::non_const_value_type,
409 typename InputViewType::non_const_value_type>::value;
410 static_assert (! sameLayoutsSameOffsetTypes,
411 "CopyOffsetsImpl (implements copyOffsets): In order to "
412 "call this specialization, sameLayoutsSameOffsetTypes "
413 "must be false. That is, either the input and output "
414 "must have different array layouts, or their value types "
415 "must differ.");
416 static_assert (Kokkos::Impl::SpaceAccessibility<
417 typename OutputViewType::memory_space,
418 typename InputViewType::memory_space>::accessible,
419 "CopyOffsetsImpl (implements copyOffsets): In order to "
420 "call this specialization, the output View's space must "
421 "be able to access the input View's memory space.");
422 using functor_type = CopyOffsetsFunctor<OutputViewType, InputViewType>;
423 using execution_space = typename OutputViewType::execution_space;
424 using size_type = typename OutputViewType::size_type;
425 using range_type = Kokkos::RangePolicy<execution_space, size_type>;
426
427 const bool debug = Details::Behavior::debug ();
428 if (debug) {
429 size_t overflowCount = 0; // output argument of the reduction
430 Kokkos::parallel_reduce ("Tpetra::Details::copyOffsets",
431 range_type (0, dst.extent (0)),
432 functor_type (dst, src),
433 overflowCount);
434 errorIfOverflow (dst, src, overflowCount);
435 }
436 else {
437 Kokkos::parallel_for ("Tpetra::Details::copyOffsets",
438 range_type (0, dst.extent (0)),
439 functor_type (dst, src));
440 }
441 }
442 };
443
444 // Specialization for sameLayoutsSameOffsetTypes = false and
445 // outputExecSpaceCanAccessInputMemSpace = false.
446 //
447 // If the output execution space canNOT access the input memory
448 // space, then we can't use CopyOffsetsFunctor directly. Instead,
449 // tell Kokkos to copy the input View's data into the output View's
450 // memory space _first_. Since the offset types are different for
451 // this specialization, we can't just call Kokkos::deep_copy
452 // directly between the input and output Views of offsets; that
453 // wouldn't compile.
454 //
455 // This case can and does come up in practice: If the output View's
456 // execution space is Cuda, it cannot currently access host memory
457 // (that's the opposite direction from what UVM allows).
458 // Furthermore, that case specifically requires overflow checking,
459 // since (as of 28 Jan 2016 at least) Kokkos::Cuda uses a smaller
460 // offset type than Kokkos' host spaces.
461 template<class OutputViewType, class InputViewType>
462 struct CopyOffsetsImpl<OutputViewType, InputViewType,
463 false, false> {
464 static void run (const OutputViewType& dst, const InputViewType& src) {
465 static_assert (static_cast<int> (OutputViewType::rank) ==
466 static_cast<int> (InputViewType::rank),
467 "CopyOffsetsImpl (implementation of copyOffsets): In order"
468 " to call this specialization, src and dst must have the "
469 "same rank.");
470 constexpr bool sameLayoutsSameOffsetTypes =
471 std::is_same<typename OutputViewType::array_layout,
472 typename InputViewType::array_layout>::value &&
473 std::is_same<typename OutputViewType::non_const_value_type,
474 typename InputViewType::non_const_value_type>::value;
475 static_assert (! sameLayoutsSameOffsetTypes,
476 "CopyOffsetsImpl (implements copyOffsets): In order to "
477 "call this specialization, sameLayoutsSameOffsetTypes "
478 "must be false. That is, either the input and output "
479 "must have different array layouts, or their value types "
480 "must differ.");
481 using output_space_copy_type =
482 Kokkos::View<typename InputViewType::non_const_value_type*,
483 Kokkos::LayoutLeft, typename OutputViewType::device_type>;
484 using Kokkos::view_alloc;
485 using Kokkos::WithoutInitializing;
486 output_space_copy_type
487 outputSpaceCopy (view_alloc ("outputSpace", WithoutInitializing),
488 src.extent (0));
489 Kokkos::deep_copy (outputSpaceCopy, src);
490
491 // The output View's execution space can access
492 // outputSpaceCopy's data, so we can run the functor now.
493 using functor_type =
494 CopyOffsetsFunctor<OutputViewType, output_space_copy_type>;
495 using execution_space = typename OutputViewType::execution_space;
496 using size_type = typename OutputViewType::size_type;
497 using range_type = Kokkos::RangePolicy<execution_space, size_type>;
498
499 const bool debug = Details::Behavior::debug ();
500 if (debug) {
501 size_t overflowCount = 0;
502 Kokkos::parallel_reduce ("Tpetra::Details::copyOffsets",
503 range_type (0, dst.extent (0)),
504 functor_type (dst, outputSpaceCopy),
505 overflowCount);
506 errorIfOverflow (dst, src, overflowCount);
507 }
508 else {
509 Kokkos::parallel_for ("Tpetra::Details::copyOffsets",
510 range_type (0, dst.extent (0)),
511 functor_type (dst, outputSpaceCopy));
512 }
513 }
514 };
515} // namespace (anonymous)
516
528template<class OutputViewType, class InputViewType>
529void
530copyOffsets (const OutputViewType& dst, const InputViewType& src)
531{
532 static_assert (Kokkos::Impl::is_view<OutputViewType>::value,
533 "OutputViewType (the type of dst) must be a Kokkos::View.");
534 static_assert (Kokkos::Impl::is_view<InputViewType>::value,
535 "InputViewType (the type of src) must be a Kokkos::View.");
536 static_assert (std::is_same<typename OutputViewType::value_type,
537 typename OutputViewType::non_const_value_type>::value,
538 "OutputViewType (the type of dst) must be a nonconst Kokkos::View.");
539 static_assert (static_cast<int> (OutputViewType::rank) == 1,
540 "OutputViewType (the type of dst) must be a rank-1 Kokkos::View.");
541 static_assert (static_cast<int> (InputViewType::rank) == 1,
542 "InputViewType (the type of src) must be a rank-1 Kokkos::View.");
543 static_assert (std::is_integral<typename std::decay<decltype (dst(0)) >::type>::value,
544 "The entries of dst must be built-in integers.");
545 static_assert (std::is_integral<typename std::decay<decltype (src(0)) >::type>::value,
546 "The entries of src must be built-in integers.");
547
548 TEUCHOS_TEST_FOR_EXCEPTION
549 (dst.extent (0) != src.extent (0), std::invalid_argument,
550 "copyOffsets: dst.extent(0) = " << dst.extent (0)
551 << " != src.extent(0) = " << src.extent (0) << ".");
552
553 CopyOffsetsImpl<OutputViewType, InputViewType>::run (dst, src);
554}
555
556} // namespace Details
557} // namespace Tpetra
558
559#endif // TPETRA_DETAILS_COPYOFFSETS_HPP
Declaration of Tpetra::Details::Behavior, a class that describes Tpetra's behavior.
static bool debug()
Whether Tpetra is in debug mode.
static bool verbose()
Whether Tpetra is in verbose mode.
static size_t verbosePrintCountThreshold()
Number of entries below which arrays, lists, etc. will be printed in debug mode.
Implementation details of Tpetra.
void copyOffsets(const OutputViewType &dst, const InputViewType &src)
Copy row offsets (in a sparse graph or matrix) from src to dst. The offsets may have different types.
Namespace Tpetra contains the class and methods constituting the Tpetra library.
void deep_copy(MultiVector< DS, DL, DG, DN > &dst, const MultiVector< SS, SL, SG, SN > &src)
Copy the contents of the MultiVector src into dst.