Skip to content

Commit

Permalink
Templatize the examples.
Browse files Browse the repository at this point in the history
  • Loading branch information
pratikvn committed Apr 25, 2020
1 parent 120963c commit 09a9f8c
Show file tree
Hide file tree
Showing 18 changed files with 350 additions and 219 deletions.
14 changes: 8 additions & 6 deletions examples/custom-logger/custom-logger.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -188,14 +188,16 @@ int main(int argc, char *argv[])
// with one column/one row. The advantage of this concept is that using
// multiple vectors is a now a natural extension of adding columns/rows are
// necessary.
using vec = gko::matrix::Dense<>;
using ValueType = double;
using IndexType = int;
using vec = gko::matrix::Dense<ValueType>;
// The gko::matrix::Csr class is used here, but any other matrix class such
// as gko::matrix::Coo, gko::matrix::Hybrid, gko::matrix::Ell or
// gko::matrix::Sellp could also be used.
using mtx = gko::matrix::Csr<>;
using mtx = gko::matrix::Csr<ValueType, IndexType>;
// The gko::solver::Cg is used here, but any other solver class can also be
// used.
using cg = gko::solver::Cg<>;
using cg = gko::solver::Cg<ValueType>;

// Print the ginkgo version information.
std::cout << gko::version_info::get() << std::endl;
Expand Down Expand Up @@ -251,14 +253,14 @@ int main(int argc, char *argv[])
cg::build()
.with_criteria(
gko::stop::Iteration::build().with_max_iters(20u).on(exec),
gko::stop::ResidualNormReduction<>::build()
gko::stop::ResidualNormReduction<ValueType>::build()
.with_reduction_factor(1e-15)
.on(exec))
.on(exec);

// Instantiate a ResidualLogger logger.
auto logger = std::make_shared<ResidualLogger<double>>(exec, gko::lend(A),
gko::lend(b));
auto logger = std::make_shared<ResidualLogger<ValueType>>(
exec, gko::lend(A), gko::lend(b));

// Add the previously created logger to the solver factory. The logger will
// be automatically propagated to all solvers created from this factory.
Expand Down
2 changes: 1 addition & 1 deletion examples/custom-matrix-format/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ if (GINKGO_BUILD_CUDA AND GINKGO_BUILD_OMP)
stencil_kernel.cu)
target_link_libraries(custom-matrix-format ginkgo)
target_include_directories(custom-matrix-format PRIVATE
${PROJECT_SOURCE_DIR})
${PROJECT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR})
endif()
58 changes: 34 additions & 24 deletions examples/custom-matrix-format/custom-matrix-format.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// A CUDA kernel implementing the stencil, which will be used if running on the
// CUDA executor. Unfortunately, NVCC has serious problems interpreting some
// parts of Ginkgo's code, so the kernel has to be compiled separately.
extern void stencil_kernel(std::size_t size, const double *coefs,
const double *b, double *x);
template <typename ValueType>
extern void stencil_kernel(std::size_t size, const ValueType *coefs,
const ValueType *b, ValueType *x);


// A stencil matrix class representing the 3pt stencil linear operator.
Expand All @@ -57,21 +58,22 @@ extern void stencil_kernel(std::size_t size, const double *coefs,
// implementation of the static create method. This method will forward all its
// arguments to the constructor to create the object, and return an
// std::unique_ptr to the created object.
class StencilMatrix : public gko::EnableLinOp<StencilMatrix>,
public gko::EnableCreateMethod<StencilMatrix> {
template <typename ValueType>
class StencilMatrix : public gko::EnableLinOp<StencilMatrix<ValueType>>,
public gko::EnableCreateMethod<StencilMatrix<ValueType>> {
public:
// This constructor will be called by the create method. Here we initialize
// the coefficients of the stencil.
StencilMatrix(std::shared_ptr<const gko::Executor> exec,
gko::size_type size = 0, double left = -1.0,
double center = 2.0, double right = -1.0)
gko::size_type size = 0, ValueType left = -1.0,
ValueType center = 2.0, ValueType right = -1.0)
: gko::EnableLinOp<StencilMatrix>(exec, gko::dim<2>{size}),
coefficients(exec, {left, center, right})
{}

protected:
using vec = gko::matrix::Dense<>;
using coef_type = gko::Array<double>;
using vec = gko::matrix::Dense<ValueType>;
using coef_type = gko::Array<ValueType>;

// Here we implement the application of the linear operator, x = A * b.
// apply_impl will be called by the apply method, after the arguments have
Expand Down Expand Up @@ -156,14 +158,15 @@ class StencilMatrix : public gko::EnableLinOp<StencilMatrix>,

// Creates a stencil matrix in CSR format for the given number of discretization
// points.
void generate_stencil_matrix(gko::matrix::Csr<> *matrix)
template <typename ValueType, typename IndexType>
void generate_stencil_matrix(gko::matrix::Csr<ValueType, IndexType> *matrix)
{
const auto discretization_points = matrix->get_size()[0];
auto row_ptrs = matrix->get_row_ptrs();
auto col_idxs = matrix->get_col_idxs();
auto values = matrix->get_values();
int pos = 0;
const double coefs[] = {-1, 2, -1};
IndexType pos = 0;
const ValueType coefs[] = {-1, 2, -1};
row_ptrs[0] = pos;
for (int i = 0; i < discretization_points; ++i) {
for (auto ofs : {-1, 0, 1}) {
Expand All @@ -179,8 +182,9 @@ void generate_stencil_matrix(gko::matrix::Csr<> *matrix)


// Generates the RHS vector given `f` and the boundary conditions.
template <typename Closure>
void generate_rhs(Closure f, double u0, double u1, gko::matrix::Dense<> *rhs)
template <typename Closure, typename ValueType>
void generate_rhs(Closure f, ValueType u0, ValueType u1,
gko::matrix::Dense<ValueType> *rhs)
{
const auto discretization_points = rhs->get_size()[0];
auto values = rhs->get_values();
Expand All @@ -195,7 +199,9 @@ void generate_rhs(Closure f, double u0, double u1, gko::matrix::Dense<> *rhs)


// Prints the solution `u`.
void print_solution(double u0, double u1, const gko::matrix::Dense<> *u)
template <typename ValueType>
void print_solution(ValueType u0, ValueType u1,
const gko::matrix::Dense<ValueType> *u)
{
std::cout << u0 << '\n';
for (int i = 0; i < u->get_size()[0]; ++i) {
Expand All @@ -207,8 +213,9 @@ void print_solution(double u0, double u1, const gko::matrix::Dense<> *u)

// Computes the 1-norm of the error given the computed `u` and the correct
// solution function `correct_u`.
template <typename Closure>
double calculate_error(int discretization_points, const gko::matrix::Dense<> *u,
template <typename Closure, typename ValueType>
double calculate_error(int discretization_points,
const gko::matrix::Dense<ValueType> *u,
Closure correct_u)
{
const auto h = 1.0 / (discretization_points + 1);
Expand All @@ -226,9 +233,12 @@ double calculate_error(int discretization_points, const gko::matrix::Dense<> *u,
int main(int argc, char *argv[])
{
// Some shortcuts
using vec = gko::matrix::Dense<double>;
using mtx = gko::matrix::Csr<double, int>;
using cg = gko::solver::Cg<double>;
using ValueType = double;
using IndexType = int;

using vec = gko::matrix::Dense<ValueType>;
using mtx = gko::matrix::Csr<ValueType, IndexType>;
using cg = gko::solver::Cg<ValueType>;

if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " DISCRETIZATION_POINTS [executor]"
Expand All @@ -255,8 +265,8 @@ int main(int argc, char *argv[])
const auto app_exec = exec_map["omp"];

// problem:
auto correct_u = [](double x) { return x * x * x; };
auto f = [](double x) { return 6 * x; };
auto correct_u = [](ValueType x) { return x * x * x; };
auto f = [](ValueType x) { return 6 * x; };
auto u0 = correct_u(0);
auto u1 = correct_u(1);

Expand All @@ -273,14 +283,14 @@ int main(int argc, char *argv[])
.with_criteria(gko::stop::Iteration::build()
.with_max_iters(discretization_points)
.on(exec),
gko::stop::ResidualNormReduction<>::build()
gko::stop::ResidualNormReduction<ValueType>::build()
.with_reduction_factor(1e-6)
.on(exec))
.on(exec)
// notice how our custom StencilMatrix can be used in the same way as
// any built-in type
->generate(
StencilMatrix::create(exec, discretization_points, -1, 2, -1))
->generate(StencilMatrix<ValueType>::create(exec, discretization_points,
-1, 2, -1))
->apply(lend(rhs), lend(u));

print_solution(u0, u1, lend(u));
Expand Down
15 changes: 11 additions & 4 deletions examples/custom-matrix-format/stencil_kernel.cu
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <cstdlib>


#include "stencil_kernel.hpp"


namespace {


// a parallel CUDA kernel that computes the application of a 3 point stencil
__global__ void stencil_kernel_impl(std::size_t size, const double *coefs,
const double *b, double *x)
template <typename ValueType>
__global__ void stencil_kernel_impl(std::size_t size, const ValueType *coefs,
const ValueType *b, ValueType *x)
{
const auto thread_id = blockIdx.x * blockDim.x + threadIdx.x;
if (thread_id >= size) {
Expand All @@ -58,10 +62,13 @@ __global__ void stencil_kernel_impl(std::size_t size, const double *coefs,
} // namespace


void stencil_kernel(std::size_t size, const double *coefs, const double *b,
double *x)
template <typename ValueType>
void stencil_kernel(std::size_t size, const ValueType *coefs,
const ValueType *b, ValueType *x)
{
constexpr auto block_size = 512;
const auto grid_size = (size + block_size - 1) / block_size;
stencil_kernel_impl<<<grid_size, block_size>>>(size, coefs, b, x);
}

INSTANTIATE_FOR_EACH_VALUE_TYPE(STENCIL_KERNEL);
47 changes: 47 additions & 0 deletions examples/custom-matrix-format/stencil_kernel.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*******************************<GINKGO LICENSE>******************************
Copyright (c) 2017-2020, the Ginkgo authors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************<GINKGO LICENSE>*******************************/

#ifndef STENCIL_KERNEL_HPP_
#define STENCIL_KERNEL_HPP_


#define INSTANTIATE_FOR_EACH_VALUE_TYPE(_macro) \
template _macro(float); \
template _macro(double);


#define STENCIL_KERNEL(_type) \
void stencil_kernel(std::size_t size, const _type *coefs, const _type *b, \
_type *x);


#endif
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,12 @@ void run_solver(volatile bool *stop_iteration_process,
std::shared_ptr<gko::Executor> exec)
{
// Some shortcuts
using mtx = gko::matrix::Csr<>;
using vec = gko::matrix::Dense<>;
using bicg = gko::solver::Bicgstab<>;
using ValueType = double;
using IndexType = int;

using mtx = gko::matrix::Csr<ValueType, IndexType>;
using vec = gko::matrix::Dense<ValueType>;
using bicg = gko::solver::Bicgstab<ValueType>;

// Read Data
auto A = share(gko::read<mtx>(std::ifstream("data/A.mtx"), exec));
Expand Down
12 changes: 7 additions & 5 deletions examples/ginkgo-overhead/ginkgo-overhead.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,18 +38,20 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <iostream>


[[noreturn]] void print_usage_and_exit(const char *name)
{
[[noreturn]] void print_usage_and_exit(const char *name) {
std::cerr << "Usage: " << name << " [NUM_ITERS]" << std::endl;
std::exit(-1);
}


int main(int argc, char *argv[])
{
using vec = gko::matrix::Dense<>;
using mtx = gko::matrix::Dense<>;
using cg = gko::solver::Cg<>;
using ValueType = double;
using IndexType = int;

using vec = gko::matrix::Dense<ValueType>;
using mtx = gko::matrix::Csr<ValueType, IndexType>;
using cg = gko::solver::Cg<ValueType>;

long unsigned num_iters = 1000000;
if (argc > 2) {
Expand Down
8 changes: 6 additions & 2 deletions examples/ginkgo-ranges/ginkgo-ranges.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,16 @@ void print_lu(const gko::range<Accessor> &A)

int main(int argc, char *argv[])
{
using ValueType = double;
using IndexType = int;

// Print version information
std::cout << gko::version_info::get() << std::endl;

// Create some test data, add some padding just to demonstrate how to use it
// with ranges.
// clang-format off
double data[] = {
ValueType data[] = {
2., 4., 5., -1.0,
4., 11., 12., -1.0,
6., 24., 24., -1.0
Expand All @@ -97,7 +100,8 @@ int main(int argc, char *argv[])

// Create a 3-by-3 range, with a 2D row-major accessor using data as the
// underlying storage. Set the stride (a.k.a. "LDA") to 4.
auto A = gko::range<gko::accessor::row_major<double, 2>>(data, 3u, 3u, 4u);
auto A =
gko::range<gko::accessor::row_major<ValueType, 2>>(data, 3u, 3u, 4u);

// use the LU factorization routine defined above to factorize the matrix
factorize(A);
Expand Down
19 changes: 12 additions & 7 deletions examples/ilu-preconditioned-solver/ilu-preconditioned-solver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
int main(int argc, char *argv[])
{
// Some shortcuts
using vec = gko::matrix::Dense<>;
using mtx = gko::matrix::Csr<>;
using gmres = gko::solver::Gmres<>;
using ValueType = double;
using IndexType = int;

using vec = gko::matrix::Dense<ValueType>;
using mtx = gko::matrix::Csr<ValueType, IndexType>;
using gmres = gko::solver::Gmres<ValueType>;

// Print version information
std::cout << gko::version_info::get() << std::endl;
Expand Down Expand Up @@ -73,15 +76,17 @@ int main(int argc, char *argv[])
auto x = gko::read<vec>(std::ifstream("data/x0.mtx"), exec);

// Generate incomplete factors using ParILU
auto par_ilu_fact = gko::factorization::ParIlu<>::build().on(exec);
auto par_ilu_fact =
gko::factorization::ParIlu<ValueType, IndexType>::build().on(exec);
// Generate concrete factorization for input matrix
auto par_ilu = par_ilu_fact->generate(A);

// Generate an ILU preconditioner factory by setting lower and upper
// triangular solver - in this case the exact triangular solves
auto ilu_pre_factory =
gko::preconditioner::Ilu<gko::solver::LowerTrs<>,
gko::solver::UpperTrs<>, false>::build()
gko::preconditioner::Ilu<gko::solver::LowerTrs<ValueType, IndexType>,
gko::solver::UpperTrs<ValueType, IndexType>,
false>::build()
.on(exec);

// Use incomplete factors to generate ILU preconditioner
Expand All @@ -95,7 +100,7 @@ int main(int argc, char *argv[])
gko::solver::Gmres<>::build()
.with_criteria(
gko::stop::Iteration::build().with_max_iters(1000u).on(exec),
gko::stop::ResidualNormReduction<>::build()
gko::stop::ResidualNormReduction<ValueType>::build()
.with_reduction_factor(1e-15)
.on(exec))
.with_generated_preconditioner(gko::share(ilu_preconditioner))
Expand Down
Loading

0 comments on commit 09a9f8c

Please sign in to comment.