repo_name
stringclasses 10
values | file_path
stringlengths 29
222
| content
stringlengths 24
926k
| extention
stringclasses 5
values |
---|---|---|---|
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/simple_host_streaming/src/multi_kernel.hpp | //
// This file contains all of the FPGA device code for the multi-kernel design
//
#ifndef __MULTI_KERNEL_HPP__
#define __MULTI_KERNEL_HPP__
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
using namespace sycl;
// Forward declare the kernel names to reduce name mangling
class K0;
class K1;
class K2;
class P;
class C;
//
// A generic kernel to produce data from host memory to a SYCL pipe.
//
// The following is a block diagram of this kernel:
//
// |-----------------| |--------------------------|
// | CPU |-----| | in_ptr | FPGA |---| InPipe |
// | | RAM |--|---------|------>| P |========> ... |
// | |-----| | | |---| |
// |-----------------| |--------------------------|
//
template<typename T, typename InPipe>
event SubmitProducer(queue &q, T* in_ptr, size_t size) {
return q.single_task<P>([=]() [[intel::kernel_args_restrict]] {
host_ptr<T> in(in_ptr);
for (size_t i = 0; i < size; i++) {
auto data = in[i];
InPipe::write(data);
}
});
}
//
// A generic kernel to consume data from a SYCL pipe and write it to host memory
//
// The following is a block diagram of this kernel:
//
// |-----------------| |--------------------------|
// | CPU |-----| | out_ptr | FPGA |---| OutPipe |
// | | RAM |<-|---------|-------| C |<======== ... |
// | |-----| | | |---| |
// |-----------------| |--------------------------|
//
template<typename T, typename OutPipe>
event SubmitConsumer(queue &q, T* out_ptr, size_t size) {
return q.single_task<C>([=]() [[intel::kernel_args_restrict]] {
host_ptr<T> out(out_ptr);
for (size_t i = 0; i < size; i++) {
auto data = OutPipe::read();
*(out + i) = data;
}
});
}
// A generic kernel that reads from an input pipe and writes to an output pipe
//
// The following is a block diagram of this kernel:
//
// InPipe |--------| OutPipe
// ... ========>| Kernel |=========> ...
// |--------|
template<typename KernelClass, typename T, typename InPipe, typename OutPipe>
event SubmitSinglePipeWorker(queue &q, size_t size) {
return q.single_task<KernelClass>([=]() [[intel::kernel_args_restrict]] {
for (size_t i = 0; i < size; i++) {
auto data = InPipe::read();
// computation could be placed here
OutPipe::write(data);
}
});
}
//
// This function creates the pipeline design for the multi-kernel version.
// It instantiates 3 SubmitSinglePipeWorker functions (above) and connects
// them with internal pipes Pipe0 and Pipe1. This function represents a generic
// pipeline made of 3 kernels (K0, K1, and K2) connected by pipes (a common
// FPGA design pattern). The function that calls this can connect the design
// to the InPipe and OutPipe in whatever fashion it likes.
//
// The following is a block diagram of this kernel this function creates:
//
// InPipe |----| Pipe0 |----| Pipe1 |----| OutPipe
// ... ========>| K0 |======>| K1 |======>| K2 |========> ...
// |----| |----| |----|
//
template<typename T, typename InPipe, typename OutPipe>
std::vector<event> SubmitMultiKernelWorkers(queue &q, size_t size) {
// internal pipes between kernels
using Pipe0 = sycl::pipe<class Pipe0Class, T>;
using Pipe1 = sycl::pipe<class Pipe1Class, T>;
// submit the kernels
event e0 = SubmitSinglePipeWorker<K0, T, InPipe, Pipe0>(q, size);
event e1 = SubmitSinglePipeWorker<K1, T, Pipe0, Pipe1>(q, size);
event e2 = SubmitSinglePipeWorker<K2, T, Pipe1, OutPipe>(q, size);
// return the events
return {e0, e1, e2};
}
#endif /* __MULTI_KERNEL_HPP__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/simple_host_streaming/src/single_kernel.hpp | //
// This file contains all of the FPGA device code for the single-kernel design
//
#ifndef __SINGLE_KERNEL_HPP__
#define __SINGLE_KERNEL_HPP__
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
using namespace sycl;
// Forward declare the kernel names to reduce name mangling
class K;
// submit the kernel for the single-kernel design
template<typename T>
event SubmitSingleWorker(queue &q, T *in_ptr, T *out_ptr, size_t count) {
return q.single_task<K>([=]() [[intel::kernel_args_restrict]] {
// using a host_ptr class tells the compiler that this pointer lives in
// the hosts address space
host_ptr<T> in(in_ptr);
host_ptr<T> out(out_ptr);
for (size_t i = 0; i < count; i++) {
// do a simple copy - more complex computation can go here
T data = *(in + i);
*(out + i) = data;
}
});
}
#endif /* __SINGLE_KERNEL_HPP__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/explicit_data_movement/src/explicit_data_movement.cpp | #include <assert.h>
#include <algorithm>
#include <chrono>
#include <iomanip>
#include <numeric>
#include <random>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include <type_traits>
#include "exception_handler.hpp"
// Forward declare the kernel names in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class ImplicitKernel;
class ExplicitKernel;
//
// This version of the kernel demonstrates implicit data movement
// through SYCL buffers and accessors.
//
template <typename T>
double SubmitImplicitKernel(sycl::queue &q, std::vector<T> &in,
std::vector<T> &out, size_t size) {
// start the timer
auto start = std::chrono::high_resolution_clock::now();
{
// set up the input and output buffers
sycl::buffer in_buf(in);
sycl::buffer out_buf(out);
// launch the computation kernel
auto kernel_event = q.submit([&](sycl::handler &h) {
// When targeting an FPGA family/part, the compiler infers memory
// interfaces based on the unique buffer_locations specified on kernel
// arguments whereas when a BSP is specified to the compiler, the
// buffer_location is used to select from the available memory interfaces
// supported by the BSP. Here, we specify 0 on the accessor arguments
// whereas the pointer arguments in ExplicitKernel are specified to be in
// buffer_location 1, when targeting an FPGA family/part.
sycl::ext::oneapi::accessor_property_list location_of_buffer{
sycl::ext::intel::buffer_location<0>};
sycl::accessor in_a(in_buf, h, sycl::read_only, location_of_buffer);
sycl::ext::oneapi::accessor_property_list location_of_buffer_no_init{
sycl::no_init, sycl::ext::intel::buffer_location<0>};
sycl::accessor out_a(out_buf, h, sycl::write_only,
location_of_buffer_no_init);
h.single_task<ImplicitKernel>([=]() [[intel::kernel_args_restrict]] {
for (size_t i = 0; i < size; i++) {
out_a[i] = in_a[i] * i;
}
});
});
}
// We use the scope above to synchronize the FPGA kernels.
// Exiting the scope will cause the buffer destructors to be called
// which will wait until the kernel finishes and copy the data back to the
// host (if the buffer was written to).
// Therefore, at this point in the code, we know the kernels have finished
// and the data has been transferred back to the host.
// stop the timer
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> diff = end - start;
return diff.count();
}
//
// This version of the kernel demonstrates explicit data movement
// through explicit USM.
//
template <typename T>
double SubmitExplicitKernel(sycl::queue &q, std::vector<T> &in,
std::vector<T> &out, size_t size) {
#if defined(IS_BSP)
// USM device allocations are more commonly supported by FPGA boards than
// other types of USM allocations like host and shared allocations.
// Allocate the device memory
T *in_ptr = sycl::malloc_device<T>(
size, q,
sycl::ext::intel::experimental::property::usm::buffer_location(0));
T *out_ptr = sycl::malloc_device<T>(
size, q,
sycl::ext::intel::experimental::property::usm::buffer_location(0));
#else
// When targeting an FPGA family/part, use USM host or shared allocations
// since USM device allocations are not supported. Here we use USM shared
// allocation.
T *in_ptr = sycl::malloc_host<T>(
size, q,
sycl::ext::intel::experimental::property::usm::buffer_location(1));
T *out_ptr = sycl::malloc_host<T>(
size, q,
sycl::ext::intel::experimental::property::usm::buffer_location(1));
#endif
// ensure we successfully allocated the device memory
if (in_ptr == nullptr) {
std::cerr << "ERROR: failed to allocate space for 'in_ptr'\n";
return 0;
}
if (out_ptr == nullptr) {
std::cerr << "ERROR: failed to allocate space for 'out_ptr'\n";
return 0;
}
// start the timer
auto start = std::chrono::high_resolution_clock::now();
// copy host input data to the device's memory
auto copy_host_to_device_event =
q.memcpy(in_ptr, in.data(), size * sizeof(T));
#if !defined(IS_BSP)
// When targeting a FPGA family/part, the compiler infers as many global
// memory interfaces for the design as unique buffer locations. The
// ImplicitKernel specifies buffer_location 0 on the accessor argument
// allowing the compiler to infer an interface for buffer_location 0.
// Here, we use annotated_arg to specify buffer_location on the USM pointer
// kernel argument to allow the compiler to infer an interface for
// buffer_location 1
sycl::ext::oneapi::experimental::annotated_arg in_ptr_d(
in_ptr, sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::buffer_location<1>});
sycl::ext::oneapi::experimental::annotated_arg out_ptr_d(
out_ptr, sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::buffer_location<1>});
#endif
// launch the computation kernel
auto kernel_event = q.submit([&](sycl::handler &h) {
// this kernel must wait until the data is copied from the host's to
// the device's memory
h.depends_on(copy_host_to_device_event);
h.single_task<ExplicitKernel>([=]() [[intel::kernel_args_restrict]] {
#if defined(IS_BSP)
// Explicitly create device pointers to inform the compiler that these
// pointers point to device memory
sycl::device_ptr<T> in_ptr_d(in_ptr);
sycl::device_ptr<T> out_ptr_d(out_ptr);
#endif
for (size_t i = 0; i < size; i++) {
out_ptr_d[i] = in_ptr_d[i] * i;
}
});
});
// copy output data back from device to host
auto copy_device_to_host_event = q.submit([&](sycl::handler &h) {
// we cannot copy the output data from the device's to the host's memory
// until the computation kernel has finished
h.depends_on(kernel_event);
h.memcpy(out.data(), out_ptr, size * sizeof(T));
});
// wait for copy back to finish
copy_device_to_host_event.wait();
// stop the timer
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> diff = end - start;
// free the device memory
// note that these are calls to sycl::free()
free(in_ptr, q);
free(out_ptr, q);
return diff.count();
}
//
// main driver program
//
int main(int argc, char *argv[]) {
// The data type for our design. Assert that it is arithmetic.
// Templating allows us to easily change the data type of the entire design.
using Type = int;
static_assert(std::is_arithmetic<Type>::value);
// the default arguments
#if defined(FPGA_EMULATOR)
size_t size = 10000;
size_t iters = 1;
#elif defined(FPGA_SIMULATOR)
size_t size = 100;
size_t iters = 1;
#else
size_t size = 100000000;
size_t iters = 5;
#endif
// Allow the size to be changed by a command line argument
if (argc > 1) {
size = atoi(argv[1]);
}
// check the size
if (size <= 0) {
std::cerr << "ERROR: size must be greater than 0\n";
return 1;
}
try {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
// queue properties to enable profiling
auto prop_list =
sycl::property_list{sycl::property::queue::enable_profiling()};
// create the device queue
sycl::queue q(selector, fpga_tools::exception_handler, prop_list);
// make sure the device supports USM device allocations
auto device = q.get_device();
if (!device.get_info<sycl::info::device::usm_device_allocations>()) {
std::cerr << "ERROR: The selected device does not support USM device"
<< " allocations\n";
return 1;
}
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
// input and output data
std::vector<Type> in(size);
std::vector<Type> out_gold(size), out_implicit(size), out_explicit(size);
// generate some random input data
std::generate(in.begin(), in.end(), [=] { return Type(rand() % 100); });
// compute gold output data
for (size_t i = 0; i < size; i++) {
out_gold[i] = in[i] * i;
}
// run the ImplicitKernel
std::cout << "Running the ImplicitKernel with size=" << size << "\n";
std::vector<double> implicit_kernel_latency(iters);
for (size_t i = 0; i < iters; i++) {
implicit_kernel_latency[i] =
SubmitImplicitKernel<Type>(q, in, out_implicit, size);
}
// run the ExplicitKernel
std::cout << "Running the ExplicitKernel with size=" << size << "\n";
std::vector<double> explicit_kernel_latency(iters);
for (size_t i = 0; i < iters; i++) {
explicit_kernel_latency[i] =
SubmitExplicitKernel<Type>(q, in, out_explicit, size);
}
// validate the outputs
bool passed = true;
// validate ImplicitKernel output
for (size_t i = 0; i < size; i++) {
if (out_gold[i] != out_implicit[i]) {
std::cout << "FAILED: mismatch at entry " << i
<< " of 'ImplicitKernel' output "
<< "(" << out_gold[i] << "," << out_implicit[i] << ")"
<< "\n";
passed = false;
}
}
// validate ExplicitKernel kernel
for (size_t i = 0; i < size; i++) {
if (out_gold[i] != out_explicit[i]) {
std::cout << "FAILED: mismatch at entry " << i
<< " of 'ExplicitKernel' kernel output "
<< "(" << out_gold[i] << "," << out_explicit[i] << ")"
<< "\n";
passed = false;
}
}
if (passed) {
// The emulator does not accurately represent real hardware performance.
// Therefore, we don't show performance results when running in emulation.
#if !defined(FPGA_EMULATOR) && !defined(FPGA_SIMULATOR)
double implicit_avg_lat =
std::accumulate(implicit_kernel_latency.begin() + 1,
implicit_kernel_latency.end(), 0.0) /
(double)(iters - 1);
double explicit_avg_lat =
std::accumulate(explicit_kernel_latency.begin() + 1,
explicit_kernel_latency.end(), 0.0) /
(double)(iters - 1);
std::cout << "Average latency for the ImplicitKernel: "
<< implicit_avg_lat << " ms\n";
std::cout << "Average latency for the ExplicitKernel: "
<< explicit_avg_lat << " ms\n";
#endif
std::cout << "PASSED\n";
return 0;
} else {
std::cout << "FAILED\n";
return 1;
}
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/onchip_memory_cache/src/onchip_memory_cache.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <algorithm>
#include <chrono>
#include "onchip_memory_with_cache.hpp" // DirectProgramming/C++SYCL_FPGA/include
#include "unrolled_loop.hpp" // DirectProgramming/C++SYCL_FPGA/include
#include "exception_handler.hpp"
#if defined(FPGA_SIMULATOR)
// Smaller size to keep the runtime reasonable
constexpr int kInitNumInputs = 16 * 1024; // Default number of inputs
// Only test a single cache depth in simulation mode
constexpr int kMaxCacheDepth = 5; // max cache depth to test
constexpr int kMinCacheDepth = 5; // min cache depth to test
#else
constexpr int kInitNumInputs = 16 * 1024 * 1024; // Default number of inputs
constexpr int kMaxCacheDepth = MAX_CACHE_DEPTH; // max cache depth to test
constexpr int kMinCacheDepth = MIN_CACHE_DEPTH; // min cache depth to test
#endif
constexpr int kNumOutputs = 64; // Number of outputs
constexpr int kInitSeed = 42; // Seed for randomizing data inputs
constexpr double kNs = 1000000000.0; // number of nanoseconds in a second
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
template<size_t cache_depth> class HistogramID;
template<size_t k_cache_depth>
void ComputeHistogram(sycl::queue &q, sycl::buffer<uint32_t>& input_buf,
sycl::buffer<uint32_t>& output_buf, sycl::event& e) {
// Enqueue kernel
e = q.submit([&](sycl::handler& h) {
// Get accessors to the SYCL buffers
sycl::accessor input(input_buf, h, sycl::read_only);
sycl::accessor output(output_buf, h, sycl::write_only, sycl::no_init);
h.single_task<HistogramID<k_cache_depth>>(
[=]() [[intel::kernel_args_restrict]] {
// On-chip memory for Histogram
// A k_cache_depth of 0 is equivalent to a standard array with no cache
fpga_tools::OnchipMemoryWithCache<uint32_t, kNumOutputs, k_cache_depth>
histogram(0);
// Compute the Histogram
for (uint32_t n = 0; n < kInitNumInputs; ++n) {
uint32_t hist_group = input[n] % kNumOutputs;
auto hist_count = histogram.read(hist_group);
hist_count++;
histogram.write(hist_group, hist_count);
}
// Write output to global memory
for (uint32_t hist_group = 0; hist_group < kNumOutputs; ++hist_group) {
output[hist_group] = histogram.read(hist_group);
}
});
});
}
int main() {
// Host and kernel profiling
sycl::event e;
unsigned long t1_kernel, t2_kernel;
double time_kernel;
// Create queue, get platform and device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
#ifndef FPGA_HARDWARE
std::cout << "\nEmulator and simulator outputs do not demonstrate "
"true hardware performance. The design may need to run "
"on actual hardware to observe the performance benefit "
"of the optimization exemplified in this tutorial.\n\n";
#endif
try {
auto prop_list =
sycl::property_list{sycl::property::queue::enable_profiling()};
sycl::queue q(selector, fpga_tools::exception_handler, prop_list);
sycl::platform platform = q.get_context().get_platform();
sycl::device device = q.get_device();
std::cout << "Platform name: "
<< platform.get_info<sycl::info::platform::name>().c_str()
<< "\n";
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
std::cout << "\nNumber of inputs: " << kInitNumInputs << "\n";
std::cout << "Number of outputs: " << kNumOutputs << "\n\n";
// Create input and output buffers
auto input_buf = sycl::buffer<uint32_t>(sycl::range<1>(kInitNumInputs));
auto output_buf = sycl::buffer<uint32_t>(sycl::range<1>(kNumOutputs));
srand(kInitSeed);
// Compute the reference solution
uint32_t gold[kNumOutputs];
{
// Get host-side accessors to the SYCL buffers
sycl::host_accessor input_host(input_buf, sycl::write_only);
// Initialize random input
for (int i = 0; i < kInitNumInputs; ++i) {
input_host[i] = rand();
}
for (int hist_group = 0; hist_group < kNumOutputs; ++hist_group) {
gold[hist_group] = 0;
}
for (int i = 0; i < kInitNumInputs; ++i) {
int hist_group = input_host[i] % kNumOutputs;
gold[hist_group]++;
}
}
// Host accessor is now out-of-scope and is destructed. This is required
// in order to unblock the kernel's subsequent accessor to the same buffer.
// iterate over the cache depths
for (int i = kMinCacheDepth; i < kMaxCacheDepth + 1; i++) {
std::cout << "Beginning run with cache depth " << i;
if (i == 0) { std::cout << " (no cache)"; }
std::cout << std::endl;
// ComputeHistogram is templated on the cache depth, and template
// parameters must be compile time constants. This unrolled loop allows
// us to convert the runtime variable i into a compile time constant j.
fpga_tools::UnrolledLoop<kMinCacheDepth, kMaxCacheDepth+1>([&](auto j) {
if (j == i) {
ComputeHistogram<j>(q, input_buf, output_buf, e);
}
});
// Wait for kernel to finish
q.wait();
// Compute kernel execution time
t1_kernel =
e.get_profiling_info<sycl::info::event_profiling::command_start>();
t2_kernel =
e.get_profiling_info<sycl::info::event_profiling::command_end>();
time_kernel = (t2_kernel - t1_kernel) / kNs;
// Get accessor to output buffer. Accessing the buffer at this point in
// the code will block on kernel completion.
sycl::host_accessor output_host(output_buf);
// Verify output and print pass/fail, and clear the output buffer
bool passed = true;
int num_errors = 0;
for (int hist_group = 0; hist_group < kNumOutputs; hist_group++) {
if (num_errors < 10 && output_host[hist_group] != gold[hist_group]) {
passed = false;
std::cout << " data mismatch in bucket: " << hist_group
<< ", expected " << gold[hist_group]
<< ", received from kernel: " << output_host[hist_group]
<< std::endl;
num_errors++;
}
output_host[hist_group] = 0;
}
if (passed) {
std::cout << "Data check succeeded for cache depth " << i
<< std::endl;
std::cout.setf(std::ios::fixed);
double N_MB = (kInitNumInputs * sizeof(uint32_t)) /
(1024 * 1024); // Input size in MB
std::cout << "Kernel execution time: " << time_kernel << " seconds"
<< std::endl;
std::cout << "Kernel throughput for cache depth " << i << ": "
<< (N_MB / time_kernel) << " MB/s" << std::endl << std::endl;
} else {
std::cout << "Verification FAILED" << std::endl;
return 1;
}
}
std::cout << "Verification PASSED" << std::endl;
} catch (sycl::exception const& e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/optimize_inner_loop/src/optimize_inner_loop.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <algorithm>
#include <array>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <random>
#include <type_traits>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include "exception_handler.hpp"
using namespace sycl;
// allow the maximum random number value to be controlled from the command line
#ifndef RAND_RANGE_MAX
#define RAND_RANGE_MAX 3
#endif
//// constants
constexpr int kNumKernels = 3;
constexpr int kRandRangeMax = RAND_RANGE_MAX;
constexpr double kProbSuccess = 1.0 / kRandRangeMax;
// Forward declare the kernel names in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
// Templating allows us to instantiate multiple versions of the kernel.
template <int version>
class Producer;
template <int version>
class Consumer;
// Declare the pipe class name globally to reduce name mangling.
// Templating allows us to instantiate multiple versions of pipes for each
// version of the kernel.
template <int version>
class PipeClass;
//
// Submits the kernel, which is templated on the variables:
// version - The version ID of the kernel
// in_element_upper_bound - The upperbound (inclusive) on the elements of the
// 'in' vector (a negative value implies no bound). In
// other words: if in_element_upper_bound >= 0, then
// in[i] <= in_element_upper_bound, for all elements
// of 'in'
// spec_iters - The number of speculated iterations to set for the
// inner loop
//
template <int version, int in_element_upper_bound, int spec_iters>
void SubmitKernels(std::vector<int> &in, int &res, double &kernel_time_ms) {
// static asserts: these cause the compiler to fail if the conditions fail
static_assert(version >= 0, "Invalid kernel version");
static_assert(spec_iters >= 0, "spec_iters must be positive");
// the device selector
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
// the pipe
using Pipe = pipe<PipeClass<version>, bool>;
kernel_time_ms = 0.0;
int size = in.size();
try {
// create the device queue with profiling enabled
auto prop_list = property_list{property::queue::enable_profiling()};
queue q(selector, fpga_tools::exception_handler, prop_list);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
// The input data buffer
buffer in_buf(in);
// The output data buffer
// Scalar inputs are passed to the kernel using the lambda capture,
// but a SYCL buffer must be used to return a scalar from the kernel.
buffer<int, 1> res_buf(&res, 1);
// submit the Producer kernel
event p_e = q.submit([&](handler &h) {
// the input buffer accessor
accessor in_a(in_buf, h, read_only);
h.single_task<Producer<version>>([=]() [[intel::kernel_args_restrict]] {
for (int i = 0; i < size; i++) {
// read the input value, which is in the range [0,InnerLoopBound]
int val = in_a[i];
// 'in_element_upper_bound' is a constant (a template variable).
// Therefore, the condition 'in_element_upper_bound < 0', and
// therefore the taken branch of this if-else statement, can be
// determined at compile time. This results in the branch that is NOT
// taken being optimized away. Both versions of the inner loop apply
// the speculated_iterations attribute, where the number of speculated
// iterations is determined by the template variable 'spec_iters'.
if (in_element_upper_bound < 0) {
// In this version of the inner loop, we do NOT provide an
// upperbound on the loop index variable 'j'. While it may be easy
// for you to read the code and reason that
// 'j<in_element_upper_bound' is always true by looking at the rest
// of the program, it is much more difficult for the compiler. As a
// result, the compiler will be conservative and assume this inner
// loop may have a large trip count and decide to make (or not make)
// optimizations accordingly.
[[intel::speculated_iterations(spec_iters)]] for (int j = 0;
j < val; j++) {
Pipe::write(true);
}
} else {
// In this version of the inner loop, we provide an upper bound
// on the loop index variable 'j' by adding the
// 'j<in_element_upper_bound' loop exit condition. This provides the
// compiler with a constant upperbound on the trip count and allows
// it to make optimizations accordingly.
[[intel::speculated_iterations(
spec_iters)]] for (int j = 0;
j < val && j <= in_element_upper_bound;
j++) {
Pipe::write(true);
}
}
}
// tell the consumer that we are done producing data
Pipe::write(false);
});
});
// submit the Consumer kernel
event c_e = q.submit([&](handler &h) {
// the output buffer accessor
accessor res_a(res_buf, h, write_only, no_init);
h.single_task<Consumer<version>>([=]() [[intel::kernel_args_restrict]] {
// local register to accumulate into
int local_sum = 0;
// keep grabbing data from the Producer until it tells us to stop
while (Pipe::read()) {
local_sum++;
}
// copy back the result to global memory
res_a[0] = local_sum;
});
});
// get the kernel time in milliseconds
// this excludes memory transfer and queuing overhead
double startk =
p_e.template get_profiling_info<info::event_profiling::command_start>();
double endk =
c_e.template get_profiling_info<info::event_profiling::command_end>();
kernel_time_ms = (endk - startk) * 1e-6f;
} catch (exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
}
//
// main function
//
int main(int argc, char *argv[]) {
// set the input size based on whether we are in emulation or FPGA hardware
#if defined(FPGA_EMULATOR) || defined(FPGA_SIMULATOR)
int size = 5000;
#else
int size = 5000000;
#endif
// Allow the size to be changed by a command line argument
if (argc > 1) {
size = atoi(argv[1]);
}
// check that the size makes sense
if (size <= 0) {
std::cerr << "ERROR: 'size' must be strictly positive\n";
return 1;
}
// generate random input data and compute golden result
std::vector<int> in(size);
int golden_result = 0;
std::cout << "generating " << size << " random numbers in the range "
<< "[0," << kRandRangeMax << "]\n";
// The random number generator (rng)
std::default_random_engine rng;
// A binomial distribution will generate random numbers in the range
// [0,kRandRangeMax], where the expected value is kRandRangeMax*kProbSuccess.
// We have set these constants such that the expected value is 1. This
// means that the number of inner loop iterations in the Producer kernel
// is in the range [0,kRandRangeMax], but is 1 on average. For more info see:
// https://en.cppreference.com/w/cpp/numeric/random/binomial_distribution
std::binomial_distribution<int> bin_dist(kRandRangeMax, kProbSuccess);
// generate the random input data
std::generate(in.begin(), in.end(), [&] { return bin_dist(rng); });
// compute the golden result
golden_result = std::accumulate(in.begin(), in.end(), 0);
// the result variables from the kernels
std::array<int, kNumKernels> result;
std::array<double, kNumKernels> ktime;
// version 0
//
// For the inner loop, this version has the bounding of the inner loop
// disabled (-1 for in_element_upper_bound disables inner loop bounding)
// and sets 2 speculated iterations.
std::cout << "Running kernel 0\n";
SubmitKernels<0, -1, 2>(in, result[0], ktime[0]);
// version 1
//
// For the inner loop, this version has the bounding of the inner loop
// disabled (-1 for in_element_upper_bound disables inner loop bounding)
// and sets 0 speculated iterations.
std::cout << "Running kernel 1\n";
SubmitKernels<1, -1, 0>(in, result[1], ktime[1]);
// version 2
//
// For the inner loop, this version bounds the inner loop (the max value
// generated by our RNG above, kRandRangeMax) and has 0 speculated iterations.
std::cout << "Running kernel 2\n";
SubmitKernels<2, kRandRangeMax, 0>(in, result[2], ktime[2]);
// validate the results
bool success = true;
for (int i = 0; i < kNumKernels; i++) {
if (result[i] != golden_result) {
std::cerr << "ERROR: Kernel " << i << " result mismatch: " << result[i]
<< " != " << golden_result << " (result != expected)\n";
success = false;
}
}
if (success) {
// the emulator does not accurately represent real hardware performance.
// Therefore, we don't show performance results when running in emulation.
#if !defined(FPGA_EMULATOR) && !defined(FPGA_SIMULATOR)
double input_size_bytes = size * sizeof(int);
// only display two decimal points
std::cout << std::fixed << std::setprecision(2);
// compute and print the performance results
for (int i = 0; i < kNumKernels; i++) {
std::cout << "Kernel " << i
<< " throughput: " << (input_size_bytes / ktime[i]) * 1e-3
<< " MB/s \n";
}
#endif
std::cout << "PASSED\n";
return 0;
} else {
std::cout << "FAILED\n";
return 1;
}
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/double_buffering/src/double_buffering.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <cmath>
#include <iomanip>
#include <random>
#include "exception_handler.hpp"
using namespace sycl;
// kTimes = # times to execute the kernel. kTimes must be >= 2
// kSize = # of floats to process on each kernel execution.
// run less in emulation to avoid high run time
#if defined(FPGA_EMULATOR)
constexpr int kTimes = 20;
constexpr int kSize = 4096;
#elif defined(FPGA_SIMULATOR)
constexpr int kTimes = 10;
constexpr int kSize = 1024;
#else
constexpr int kTimes = 100;
constexpr int kSize = 2621440;
#endif
// Kernel executes a power function (base^kPow). Must be
// >= 2. Can increase this to increase kernel execution
// time, but ProcessOutput() time will also increase.
#if defined(FPGA_SIMULATOR)
constexpr int kPow = 5;
#else
constexpr int kPow = 20;
#endif
// Number of iterations through the main loop
constexpr int kNumRuns = 2;
bool pass = true;
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class SimpleVpow;
/* Kernel function.
Performs buffer_b[i] = buffer_a[i] ** pow
Only supports pow >= 2.
This kernel is not meant to be an optimal implementation of the power
operation -- it's just a sample kernel for this tutorial whose execution time
is easily controlled via the pow parameter. SYCL buffers are created
externally and passed in by reference to control (external to this function)
when the buffers are destructed. The destructor causes a blocking buffer
transfer from device to host and double buffering requires us to not block
here (because we need to launch another kernel). So we only want this
transfer to occur at the end of overall execution, not at the end of each
individual kernel execution.
*/
void SimplePow(sycl::queue &q, buffer<float, 1> &buffer_a,
buffer<float, 1> &buffer_b, event &e) {
// Submit to the queue and execute the kernel
e = q.submit([&](handler &h) {
// Get kernel access to the buffers
accessor accessor_a(buffer_a, h, read_only);
accessor accessor_b(buffer_b, h, read_write, no_init);
const int num = kSize;
assert(kPow >= 2);
const int p = kPow - 1; // Assumes pow >= 2;
h.single_task<SimpleVpow>([=]() [[intel::kernel_args_restrict]] {
for (int j = 0; j < p; j++) {
if (j == 0) {
for (int i = 0; i < num; i++) {
accessor_b[i] = accessor_a[i] * accessor_a[i];
}
} else {
for (int i = 0; i < num; i++) {
accessor_b[i] = accessor_b[i] * accessor_a[i];
}
}
}
});
});
event update_host_event;
update_host_event = q.submit([&](handler &h) {
accessor accessor_b(buffer_b, h, read_only);
/*
Explicitly instruct the SYCL runtime to copy the kernel's output buffer
back to the host upon kernel completion. This is not required for
functionality since the buffer access in ProcessOutput() also implicitly
instructs the runtime to copy the data back. But it should be noted that
this buffer access blocks ProcessOutput() until the kernel is complete
and the data is copied. In contrast, update_host() instructs the runtime
to perform the copy earlier. This allows ProcessOutput() to optionally
perform more useful work *before* making the blocking buffer access. Said
another way, this allows ProcessOutput() to potentially perform more work
in parallel with the runtime's copy operation.
*/
h.update_host(accessor_b);
});
}
// Returns kernel execution time for a given SYCL event from a queue.
unsigned long SyclGetExecTimeNs(event e) {
unsigned long start_time =
e.get_profiling_info<info::event_profiling::command_start>();
unsigned long end_time = e.get_profiling_info<info::event_profiling::command_end>();
return (end_time - start_time);
}
// Local pow function for verifying results
float MyPow(float input, int pow) {
return (pow == 0) ? 1 : input * MyPow(input, pow - 1);
}
/* Compares kernel output against expected output. Only compares part of the
output so that this method completes quickly. This is done
intentionally/artificially keep host-processing time shorter than kernel
execution time. Grabs kernel output data from its SYCL buffer. Reading from
this buffer is a blocking operation that will block on the kernel completing.
Queries and records execution time of the kernel that just completed. This
is a natural place to do this because ProcessOutput() is blocked on kernel
completion.
*/
void ProcessOutput(buffer<float, 1> &input_buf, buffer<float, 1> &output_buf,
int exec_number, event e,
unsigned long &total_kernel_time_per_slot) {
host_accessor input_buf_acc(input_buf, read_only);
host_accessor output_buf_acc(output_buf, read_only);
int num_errors = 0;
int num_errors_to_print = 10;
// Max fractional difference between FPGA pow result and CPU pow result
// Anything greater than this will be considered an error
constexpr double epsilon = 0.01;
/* The use of update_host() in the kernel function allows for additional
host-side operations to be performed here, in parallel with the buffer copy
operation from device to host, before the blocking access to the output
buffer is made via output_buf_acc[]. To be clear, no real operations are
done here and this is just a note that this is the place
where you *could* do it. */
for (int i = 0; i < kSize / 8; i++) {
const double expected_value = MyPow(input_buf_acc[i], kPow);
const bool out_invalid = std::abs((output_buf_acc[i] - expected_value) /
expected_value) > epsilon;
if ((num_errors < num_errors_to_print) && out_invalid) {
if (num_errors == 0) {
pass = false;
std::cout << "Verification failed on kernel execution # " << exec_number
<< ". Showing up to " << num_errors_to_print
<< " mismatches.\n";
}
std::cout << "Verification failed on kernel execution # " << exec_number
<< ", at element " << i << ". Expected " << std::fixed
<< std::setprecision(16) << expected_value << " but got "
<< output_buf_acc[i] << "\n";
num_errors++;
}
}
// At this point we know the kernel has completed,
// so can query the profiling data.
total_kernel_time_per_slot += SyclGetExecTimeNs(e);
}
/*
Generates input data for the next kernel execution. Only fills part of the
buffer so that this method completes quickly. This is done
intentionally/artificially keep host-processing time shorter than kernel
execution time. Writes the data into the associated SYCL buffer. The write
will block until the previous kernel execution, that is using this buffer,
completes.
*/
void ProcessInput(buffer<float, 1> &buf) {
// We are generating completely new input data, so can the no_init property
// here to indicate we don't care about the SYCL buffer's current contents.
host_accessor buf_acc(buf, write_only, no_init);
// RNG seed
auto seed = std::chrono::system_clock::now().time_since_epoch().count();
// RNG engine
std::default_random_engine dre(seed);
// generate random numbers between 1 and 2
std::uniform_real_distribution<float> di(1.0f, 2.0f);
// Randomly generate a start value and increment from there.
// Compared to randomly generating every value, this is done to
// speed up this function a bit.
float start_val = di(dre);
for (int i = 0; i < kSize / 8; i++) {
buf_acc[i] = start_val;
start_val++;
}
}
int main() {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
#ifndef FPGA_HARDWARE
std::cout << "\nEmulator and simulator outputs do not demonstrate "
"true hardware performance. The design may need to run "
"on actual hardware to observe the performance benefit "
"of the optimization exemplified in this tutorial.\n\n";
#endif
try {
auto prop_list = property_list{property::queue::enable_profiling()};
sycl::queue q(selector, fpga_tools::exception_handler, prop_list);
platform platform = q.get_context().get_platform();
device device = q.get_device();
std::cout << "Platform name: "
<< platform.get_info<info::platform::name>().c_str() << "\n";
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
std::cout << "Executing kernel " << kTimes << " times in each round.\n\n";
// Create a vector to store the input/output SYCL buffers
std::vector<buffer<float, 1>> input_buf;
std::vector<buffer<float, 1>> output_buf;
// SYCL events for each kernel launch.
event sycl_events[2];
// In nanoseconds. Total execution time of kernels in a given slot.
unsigned long total_kernel_time_per_slot[2];
// Total execution time of all kernels.
unsigned long total_kernel_time = 0;
// Allocate vectors to store the host-side copies of the input data
// Create and allocate the SYCL buffers
for (int i = 0; i < 2; i++) {
input_buf.push_back(buffer<float, 1>(range<1>(kSize)));
output_buf.push_back(buffer<float, 1>(range<1>(kSize)));
}
/*
Main loop. This loop runs twice to show the performance difference without
and with double buffering.
*/
for (int i = 0; i < kNumRuns; i++) {
for (int i = 0; i < 2; i++) {
total_kernel_time_per_slot[i] = 0; // Initialize timers to zero.
}
switch (i) {
case 0: {
std::cout << "*** Beginning execution, without double buffering\n";
break;
}
case 1: {
std::cout << "*** Beginning execution, with double buffering.\n";
break;
}
default: {
std::cout << "*** Beginning execution.\n";
}
}
// Start the timer. This will include the time to process the input data
// for the first 2 kernel executions.
auto start = std::chrono::steady_clock::now();
if (i == 0) { // Single buffering
for (int i = 0; i < kTimes; i++) {
// Only print every few iterations, just to limit the prints.
if (i % 10 == 0) {
std::cout << "Launching kernel #" << i << "\n";
}
ProcessInput(input_buf[0]);
SimplePow(q, input_buf[0], output_buf[0], sycl_events[0]);
ProcessOutput(input_buf[0], output_buf[0], i, sycl_events[0],
total_kernel_time_per_slot[0]);
}
} else { // Double buffering
// Process input for first 2 kernel launches and queue them. Then block
// on processing the output of the first kernel.
ProcessInput(input_buf[0]);
ProcessInput(input_buf[1]);
std::cout << "Launching kernel #0\n";
SimplePow(q, input_buf[0], output_buf[0], sycl_events[0]);
for (int i = 1; i < kTimes; i++) {
if (i % 10 == 0) {
std::cout << "Launching kernel #" << i << "\n";
} // Only print every few iterations, just to limit the prints.
// Launch the next kernel
SimplePow(q, input_buf[i % 2], output_buf[i % 2], sycl_events[i % 2]);
// Process output from previous kernel. This will block on kernel
// completion.
ProcessOutput(input_buf[(i - 1) % 2], output_buf[(i - 1) % 2], i,
sycl_events[(i - 1) % 2],
total_kernel_time_per_slot[(i - 1) % 2]);
// Generate input for the next kernel.
ProcessInput(input_buf[(i - 1) % 2]);
}
// Process output of the final kernel
ProcessOutput(input_buf[(kTimes - 1) % 2], output_buf[(kTimes - 1) % 2],
i, sycl_events[(kTimes - 1) % 2],
total_kernel_time_per_slot[(kTimes - 1) % 2]);
}
// Add up the overall kernel execution time.
total_kernel_time = 0;
for (int i = 0; i < 2; i++) {
total_kernel_time += total_kernel_time_per_slot[i];
}
// Stop the timer.
auto end = std::chrono::steady_clock::now();
double time_span = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();
std::cout << "\nOverall execution time "
<< ((i == 0) ? "without" : "with")
<< " double buffering = " << (unsigned)(time_span * 1000)
<< " ms\n";
std::cout << "Total kernel-only execution time "
<< ((i == 0) ? "without" : "with") << " double buffering = "
<< (unsigned)(total_kernel_time / 1000000) << " ms\n";
std::cout << "Throughput = " << std::setprecision(8)
<< (float)kSize * (float)kTimes * (float)sizeof(float) /
(float)time_span / 1000000
<< " MB/s\n\n\n";
}
if (pass) {
std::cout << "Verification PASSED\n";
} else {
std::cout << "Verification FAILED\n";
return 1;
}
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
std::cerr << "If you are targeting the FPGA simulator, compile with "
"-DFPGA_SIMULATOR.\n";
}
std::terminate();
}
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/pipe_array/src/pipe_array.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
#include "pipe_utils.hpp"
#include "unrolled_loop.hpp"
#include "exception_handler.hpp"
using namespace sycl;
constexpr size_t kNumRows = 2;
constexpr size_t kNumCols = 2;
constexpr size_t kNumberOfConsumers = kNumRows * kNumCols;
constexpr size_t kDepth = 2;
using ProducerToConsumerPipeMatrix =
fpga_tools::PipeArray< // Defined in "pipe_utils.hpp".
class ProducerConsumerPipe, // An identifier for the pipe.
uint64_t, // The type of data in the pipe.
kDepth, // The capacity of each pipe.
kNumRows, // array dimension.
kNumCols // array dimension.
>;
// Forward declare the kernel names in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class ProducerTutorial;
template <size_t consumer_id> class ConsumerTutorial;
void Producer(queue &q, buffer<uint64_t, 1> &input_buffer) {
std::cout << "Enqueuing producer...\n";
auto e = q.submit([&](handler &h) {
accessor in(input_buffer, h, read_only);
auto num_elements = input_buffer.size();
auto num_passes = num_elements / kNumberOfConsumers;
// The producer kernel writes to every pipe in the 2D pipe array
h.single_task<ProducerTutorial>([=]() {
size_t input_idx = 0;
for (size_t pass = 0; pass < num_passes; pass++) {
// Template-based unroll (outer "i" loop)
fpga_tools::UnrolledLoop<kNumRows>([&input_idx, in](auto i) {
// Template-based unroll (inner "j" loop)
fpga_tools::UnrolledLoop<kNumCols>([&input_idx, &i, in](auto j) {
// Write a value to the <i,j> pipe of the pipe array
ProducerToConsumerPipeMatrix::PipeAt<i, j>::write(in[input_idx++]);
});
});
}
});
});
}
// Do some work on the data (any function could be substituted)
uint64_t ConsumerWork(uint64_t i) { return i * i; }
template <size_t consumer_id>
void Consumer(queue &q, buffer<uint64_t, 1> &out_buf) {
std::cout << "Enqueuing consumer " << consumer_id << "...\n";
auto e = q.submit([&](handler &h) {
accessor out(out_buf, h, write_only, no_init);
auto num_elements = out_buf.size();
// The consumer kernel reads from a single pipe, determined by consumer_id
h.single_task<ConsumerTutorial<consumer_id>>([=]() {
constexpr size_t x = consumer_id / kNumCols;
constexpr size_t y = consumer_id % kNumCols;
for (size_t i = 0; i < num_elements; ++i) {
auto input = ProducerToConsumerPipeMatrix::PipeAt<x, y>::read();
out[i] = ConsumerWork(input);
}
});
});
}
int main(int argc, char *argv[]) {
uint64_t array_size = 1;
array_size <<= 10;
// Parse optional data size argument
if (argc > 1) {
std::string option(argv[1]);
if (option == "-h" || option == "--help") {
std::cout << "Usage: \n<executable> <data size>\n\nFAILED\n";
return 1;
} else {
array_size = std::stoi(option);
}
}
std::cout << "Input Array Size: " << array_size << "\n";
// Check input validity
if (array_size % kNumberOfConsumers != 0) {
std::cout << "Array size must be a multiple of the number of consumers! "
"Exiting...\n";
return 0;
}
// Set up producer input vector, and kNumberOfConsumers output vectors
uint64_t items_per_consumer = array_size / kNumberOfConsumers;
std::vector<uint64_t> producer_input(array_size, -1);
std::array<std::vector<uint64_t>, kNumberOfConsumers> consumer_output;
for (auto &output : consumer_output)
output.resize(items_per_consumer, -1);
// Initialize producer input
for (size_t i = 0; i < array_size; i++)
producer_input[i] = i;
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
try {
queue q(selector, fpga_tools::exception_handler);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
// Enqueue producer
buffer<uint64_t,1> producer_buffer(producer_input);
Producer(q, producer_buffer);
std::vector<buffer<uint64_t,1>> consumer_buffers;
// Use template-based unroll to enqueue multiple consumers
fpga_tools::UnrolledLoop<kNumberOfConsumers>([&](auto consumer_id) {
consumer_buffers.emplace_back(consumer_output[consumer_id].data(),
items_per_consumer);
Consumer<consumer_id>(q, consumer_buffers.back());
});
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
// Verify result
for (size_t i = 0; i < items_per_consumer; ++i) {
for (size_t consumer = 0; consumer < kNumberOfConsumers; ++consumer) {
auto fpga_result = consumer_output[consumer][i];
auto expected_result = ConsumerWork(kNumberOfConsumers * i + consumer);
if (fpga_result != expected_result) {
std::cout << "FAILED: The results are incorrect\n";
std::cout << "On Input: " << kNumberOfConsumers * i + consumer
<< " Expected: " << expected_result << " Got: " << fpga_result
<< "\n";
return 1;
}
}
}
std::cout << "PASSED: The results are correct\n";
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/buffered_host_streaming/src/HostStreamer.hpp | #ifndef __HOSTSTREAMER_HPP__
#define __HOSTSTREAMER_HPP__
#include <assert.h>
#include <array>
#include <atomic>
#include <condition_variable>
#include <deque>
#include <exception>
#include <map>
#include <mutex>
#include <functional>
#include <queue>
#include <stdexcept>
#include <thread>
#include <tuple>
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
using namespace sycl;
//
// A thread safe wrapper around std::queue.
// FUTURE WORK: We could probably use conditional variables to improve
// lock performance.
//
template<typename T>
class ConcurrentQueue {
private:
std::queue<T> q_;
std::mutex mtx_;
public:
bool Empty() {
std::scoped_lock lock(mtx_);
return q_.size() == 0;
}
size_t Size() {
std::scoped_lock lock(mtx_);
return q_.size();
}
void Pop() {
std::scoped_lock lock(mtx_);
q_.pop();
}
T& Front() {
std::scoped_lock lock(mtx_);
return q_.front();
}
void Push(const T &data) {
std::scoped_lock lock(mtx_);
q_.push(data);
}
// these are useful in case the user of the queue wants to lock/unlock
// the entire queue themselves
std::mutex& GetMutex() { return mtx_; }
void Lock() { mtx_.lock(); }
void Unlock() { mtx_.unlock(); }
};
// Declare these out of the HostStreamer to reduce name mangling
template<typename Id>
class ProducerKernelId;
template<typename Id>
class ProducerPipeId;
template<typename Id>
class ConsumerKernelId;
template<typename Id>
class ConsumerPipeId;
//
// This class is used to stream to and/or from the host and device.
// It provides a set of APIs for high throughput, and a set of APIs
// for low latency.
//
// Template parameters:
// Id: The unique ID for the HostStreamer. This is
// necessary since the pipes used to stream data
// to/from the device must be unique. Having multiple
// instances of this class would make sense.
// ProducerType: The datatype to stream from the host to the device
// ConsumerType: The datatype to stream from the device to the host
// min_producer_capacity: The minimum capacity of the ProducerPipe
// min_consumer_capacity: The minimum capacity of the ConsumerPipe
//
// Using the HostStreamer results in a CPU-FPGA system that looks like this:
//
// |------------| |---------------------------------------------|
// | <CPU> | | <FPGA> |--------------| |
// | |-----| | | |----------| ProducerPipe | | |
// | | |--|---|->| Producer |==============|=> ... | |
// | | | | | |----------| | | |
// | | USM | | | | User Kernels | |
// | | | | | |----------| ConsumerPipe | | |
// | | |<-|---|--| Consumer |<=============|== ... | |
// | |-----| | | |----------| | | |
// | | | |--------------| |
// |------------| |---------------------------------------------|
//
// The interaction with USM and the Producer and Consumer kernels are abstracted
// from the user's device code ('User Kernels'). The abstraction is that input
// data (type=ProduceType) will be streamed from the host to the device through
// the ProducerPipe (HostStreamer<...>::ProducerPipe) and/or streamed from the
// device to the host through the ConsumerPipe (HostStreamer<...>::ProducerPipe)
//
template <typename Id, typename ProducerType, typename ConsumerType,
size_t min_producer_capacity=0, size_t min_consumer_capacity=0>
class HostStreamer {
private:
// The constructor is private to avoid creating an instance of the class
// The point of this is that every HostStreamer with a given 'Id' (the first
// template parameter) is associated with a single Producer and Consumer pipe,
// which are static. Therefore, having multiple instances of the same
// HostStreamer doesn't make sense. To have multiple streaming inputs/outputs,
// use multiple instances of HostStreamer with different 'Id' template
// parameters, like you would when using SYCL pipes.
HostStreamer() {}
// Producer specific data structures
static inline std::vector<ProducerType*> producer_buffer_{};
static inline size_t num_producer_buffers_{};
static inline size_t producer_buffer_size_{};
static inline std::map<ProducerType*, size_t> producer_ptr_to_idx_map_{};
static inline size_t producer_buffer_idx_{};
// Consumer specific data structures
static inline std::vector<ConsumerType*> consumer_buffer_{};
static inline size_t num_consumer_buffers_{};
static inline size_t consumer_buffer_size_{};
static inline size_t consumer_buffer_idx_{};
// These counters track the number of outstanding produce and consume
// requests, respectively. Requests are outstanding from the time the Producer
// acquires the pointer or the Consumer launches the read, until the
// the KernelLaunchAndWaitThread waits on the kernel event associated with
// the request. Each counter has an associated mutex for thread safety.
static inline size_t produce_requests_outstanding_{};
static inline std::mutex produce_requests_outstanding_mtx_{};
static inline size_t consume_requests_outstanding_{};
static inline std::mutex consume_requests_outstanding_mtx_{};
// The Producer and Consumer queues. Produce and Consume events
// from user API calls first go into these queues, respectively.
//
// producer_consumer_tuple =
// <size_t: index into producer_buffer or consumer buffer,
// size_t: the count of elements to be produced/consumer>
using producer_consumer_tuple = std::tuple<size_t, size_t>;
static inline ConcurrentQueue<producer_consumer_tuple> produce_q_{};
static inline ConcurrentQueue<producer_consumer_tuple> consume_q_{};
// The KernelLaunchAndWaitThread grabs requests from the Producer and Consumer
// queues (declared above) and places them into the launch queue. From there
// the KernelLaunchAndWaitThread grabs requests from the launch queue, and
// adds them to the actual SYCL queue by launching the necessary Producer or
// Consumer SYCL kernel.
//
// launch_queue_tuple =
// <size_t: index into producer_buffer or consumer buffer,
// size_t: the count of elements to be produced/consumer,
// event: the SYCL event for the launched kernel
// bool: true for producer, false for consumer>
using launch_queue_tuple = std::tuple<size_t, size_t, event, bool>;
static inline ConcurrentQueue<launch_queue_tuple> launch_q_{};
// A pointer to the SYCL queue which launches the actual kernels to do the
// producing and consuming. We don't use a reference here due to static
// initialization issues.
static inline queue* sycl_q_{};
// This is the number of kernels (both Producer and Consumer kernels)
// that we want to have in-flight (i.e. in the SYCL queue) before waiting on
// the oldest event to finish. Setting this too low (e.g. 1) will result in
// us NOT taking advantage of fast kernel relaunch and a drop in throughput.
// Setting this too high (e.g. 2000) will result in kernels that are in-flight
// finishing execution before we call wait (event.wait()) on them.
// This too will result in a drop in throughput.
static inline size_t wait_threshold_{};
// Signals to the KernelLaunchAndWaitThread to flush the launch queue
static inline std::atomic<bool> flush_{false};
// This breaks the while() loop in the KernelLaunchAndWaitThread.
// this allows the KernelLaunchAndWaitThread to be safely terminated so the
// main thread can join with it.
static inline std::atomic<bool> kill_kernel_thread_flag_{false};
// A pointer to the KernelLaunchAndWaitThread C++ thread object
static inline std::thread *kernel_thread_{nullptr};
// track whether the single instance has been initialized or not
static inline bool initialized_{false};
// Convenience methods for querying the status of the Producer, Consumer,
// and Launch queues
static bool ProducerQueueFull() {
return produce_q_.Size() == num_producer_buffers_;
}
static bool ProducerQueueEmpty() {
return produce_q_.Empty();
}
static bool ConsumerQueueFull() {
return consume_q_.Size() == num_consumer_buffers_;
}
static bool ConsumerQueueEmpty() {
return consume_q_.Empty();
}
static bool LaunchQueueEmpty() {
return launch_q_.Empty();
}
// This function will run in a separate CPU thread. It's job is to grab
// produce and consume requests from the Producer and Consumer queue
// (produce_q_ and consume_q_, respectively), merge them into a single request
// queue (launch_q_), and finally launch the actual SYCL kernels into the SYCL
// queue (sycl_q_) to perform the request. It also performs the callbacks
// to the user code when the requests have been completed.
static void KernelLaunchAndWaitThread() {
size_t producer_count = 0;
size_t consumer_count = 0;
// Do this loop until told (by main thread) to stop via the
// 'kill_kernel_thread_flag_' atomic shared variable.
while (!kill_kernel_thread_flag_) {
// If there is a Produce request to launch, do it
if (!ProducerQueueEmpty()) {
// grab the oldest request from the produce queue
size_t buf_idx;
size_t count;
std::tie(buf_idx, count) = produce_q_.Front();
// launch the kernel and push the request to the launch queue
auto e = LaunchProducerKernel(producer_buffer_[buf_idx], count);
launch_q_.Push(std::make_tuple(buf_idx, count, e, true));
// pop from the Producer queue
produce_q_.Pop();
// accumulate producer count
producer_count += count;
}
// If there is a Consume request to launch, do it
if (!ConsumerQueueEmpty()) {
// grab the oldest request from the consume queue
size_t buf_idx;
size_t count;
std::tie(buf_idx, count) = consume_q_.Front();
// Only launch consumer when there is enough producer count
if (producer_count >= consumer_count + count) {
// launch the kernel and push the request to the launch queue
auto e = LaunchConsumerKernel(consumer_buffer_[buf_idx], count);
launch_q_.Push(std::make_tuple(buf_idx, count, e, false));
// pop from the Consumer queue
consume_q_.Pop();
// accumulate consumer count
consumer_count += count;
}
}
// Wait on the oldest event to finish given 2 conditions:
// 1) there are a certain number of kernels in-flight
// (i.e. launch_q_.size() >= wait_threshold_)
// 2) the user has requested us to flush the launch queue and the
// launch queue is not empty (i.e. flush_ && launch_q_.size() != 0)
if ((launch_q_.Size() >= wait_threshold_) ||
(flush_ && !LaunchQueueEmpty())) {
// grab the oldest request from the launch queue
size_t buf_idx;
size_t count;
event e;
bool request_was_producer;
std::tie(buf_idx, count, e, request_was_producer) = launch_q_.Front();
// wait on the oldest event to finish
e.wait();
// call the appropriate callback
if (request_was_producer) {
//std::cout << "Calling Producer Callback" << std::endl;
producer_callback(count);
producer_count -= count;
} else {
//std::cout << "Calling Consumer Callback" << std::endl;
consumer_callback(consumer_buffer_[buf_idx], count);
consumer_count -= count;
}
// Pop from the launch queue. This has to be done AFTER waiting on
// the SYCL kernel event and calling the callback.
launch_q_.Pop();
// We just acted upon a request by launching the kernel
// (at some earlier time), waiting on the kernel, and acting on the
// data via a callback. Therefore, the request is complete! So reduce
// the number of outstanding requests for the Producer or Consumer
// appropriately. Don't forget the (correct) lock!
if (request_was_producer) {
////////////////////////////////////////
// Entering critical section
produce_requests_outstanding_mtx_.lock();
assert(produce_requests_outstanding_ > 0);
produce_requests_outstanding_--;
produce_requests_outstanding_mtx_.unlock();
// Exiting critical section
////////////////////////////////////////
} else {
////////////////////////////////////////
// Entering critical section
consume_requests_outstanding_mtx_.lock();
assert(consume_requests_outstanding_ > 0);
consume_requests_outstanding_--;
consume_requests_outstanding_mtx_.unlock();
// Exiting critical section
////////////////////////////////////////
}
}
}
}
public:
// The Producer and Consumer SYCL pipes.
// This allows device code (i.e. user kernels) to connect to the input and
// the output.
using ProducerPipe = sycl::ext::intel::pipe<ProducerPipeId<Id>,
ProducerType,
min_producer_capacity>;
using ConsumerPipe = sycl::ext::intel::pipe<ConsumerPipeId<Id>,
ConsumerType,
min_consumer_capacity>;
// The user can query the input and output types of the pipes
// E.g.
// using MyStreamer = HostStreamer<class MyStreamerClass, int, 32, float, 32>;
// MyStreamer::produce_type (=int)
// MyStreamer::consume_type (=float)
using produce_type = ProducerType;
using consume_type = ConsumerType;
// The callback functions for Producer and Consumer, respectively.
// By default, they are empty functions that do nothing. It is the user's job
// to specify their own callback functions.
// NOTE: the user will certainly want to capture the 'consumer_callback',
// but may not care about capturing the 'producer_callback'.
static inline std::function<void(size_t)>
producer_callback = [](size_t) {};
static inline std::function<void(const ConsumerType*, size_t)>
consumer_callback = [](const ConsumerType*, size_t) {};
// getter and setter to override the maximum number of kernels in-flight
static inline size_t wait_threshold() { return wait_threshold_; }
static inline void wait_threshold(size_t wt) { wait_threshold_ = wt; }
//////////////////////////////////////////////////////////////////////////////
// Initialization
static void init(queue& q,
size_t num_producer_buffers=2,
size_t producer_buffer_size=65536,
size_t num_consumer_buffers=2,
size_t consumer_buffer_size=65536) {
// if already initialized, deal with teardown first
// NOTE: must do this before re-initialzing
if (initialized_) {
std::cout << "WARNING: HostStreamer<...>::init() was called without "
<< "HostStreamer<...>::destroy() being called first. "
<< "Reinitializing.\n";
// For now, simply destroy first.
// FUTURE WORK: we could probably do something smart by looking
// at the change in the device queue, the number of producer/consumer
// buffers, and the size of those buffers. But this will likely not
// affect performance much, so we will just destroy for now.
destroy();
}
// save a pointer to the SYCL queue
sycl_q_ = &q;
// the number of Producer buffers is the number of Producer kernels that
// we can have in-flight at once (since the operate on different buffers).
// Likewise for the Consumer buffers. Therefore, the number of kernels
// that we want in-flight at once (determined by the wait_threshold_)
// is determined by the total number of Producer and Consumer buffers.
wait_threshold_ = num_producer_buffers + num_consumer_buffers;
//////////////////////////////////////////////
// Producer
num_producer_buffers_ = num_producer_buffers;
producer_buffer_size_ = producer_buffer_size;
producer_buffer_.resize(num_producer_buffers_);
producer_buffer_idx_ = 0;
// allocate USM space for buffers
for (auto& b : producer_buffer_) {
b = malloc_host<ProducerType>(producer_buffer_size_, *sycl_q_);
if (b == nullptr) {
std::cerr << "Could not allocate USM memory for producer buffer\n";
std::terminate();
}
}
// build the USM pointer->buffer index map
for (size_t i = 0; i < num_producer_buffers_; i++) {
producer_ptr_to_idx_map_[producer_buffer_[i]] = i;
}
produce_requests_outstanding_ = 0;
//////////////////////////////////////////////
//////////////////////////////////////////////
// Consumer
num_consumer_buffers_ = num_consumer_buffers;
consumer_buffer_size_ = consumer_buffer_size;
consumer_buffer_.resize(num_consumer_buffers_);
consumer_buffer_idx_ = 0;
// allocate USM space for buffers
for (auto& b : consumer_buffer_) {
b = malloc_host<ConsumerType>(consumer_buffer_size_, *sycl_q_);
if (b == nullptr) {
std::cerr << "Could not allocate USM memory for consumer buffer\n";
std::terminate();
}
}
consume_requests_outstanding_ = 0;
//////////////////////////////////////////////
// start the KernelLaunchAndWaitThread
flush_ = false;
kill_kernel_thread_flag_ = false;
kernel_thread_ = new std::thread(&KernelLaunchAndWaitThread);
// have been initialized
initialized_ = true;
}
// Destruction
// must be the last API call made
static void destroy() {
// make sure we have initialized the HostStreamer
if (initialized_) {
// stop the kernel thread safely, join with it, and destroy the thread
kill_kernel_thread_flag_ = true;
kernel_thread_->join();
delete kernel_thread_;
kernel_thread_ = nullptr;
// free all the USM memory
for (auto& b : producer_buffer_) {
sycl::free(b, *sycl_q_);
b = nullptr;
}
for (auto& b : consumer_buffer_) {
sycl::free(b, *sycl_q_);
b = nullptr;
}
// clear the buffer pointer -> idx map
producer_ptr_to_idx_map_.clear();
// nullptr the SYCL queue pointer
sycl_q_ = nullptr;
// no longer initialized
initialized_ = false;
} else {
std::cout << "WARNING: HostStreamer<...>::destroy() called on an "
<< "uninitialized HostStreamer. Nothing to do.\n";
}
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// high throughput, high(er) latency API
// The user calls this function to attempt at acquiring a buffer.
// If a buffer is available for use, this function returns it. Otherwise
// it returns nullptr. The point of the acquire/release for producing data
// is to avoid copying data from the user into USM buffers. Giving them the
// pointers allows them to produce the data directly into the USM buffers.
//
// FUTURE WORK: Could probably improve the locking here
static ProducerType* AcquireProducerBuffer() {
ProducerType *acquired_ptr = nullptr;
///////////////////////////////////
// Entering critical section
// this allows AcquireProducerBuffer to be called from different threads
produce_requests_outstanding_mtx_.lock();
// if we have room for another produce request
if (produce_requests_outstanding_ < num_producer_buffers_) {
// There is room for another produce request grab the 'head' produce
// buffer, move to the next buffer, and increment the number of produce
// requests outstanding
acquired_ptr = producer_buffer_[producer_buffer_idx_];
producer_buffer_idx_ = (producer_buffer_idx_ + 1) % num_producer_buffers_;
produce_requests_outstanding_++;
}
produce_requests_outstanding_mtx_.unlock();
// Exiting critical section
///////////////////////////////////
return acquired_ptr;
}
// The user calls this function to release a previously acquired buffer
// (via a call to AcquireProducerBuffer) back to the API. This implies that
// the user has produced their data into the buffer and are ready for
// the request to continue (i.e. the kernel to produce the data to be
// launched). The user may not want to use all of the buffer (all
// 'producer_buffer_size_; elements). The 'release_size' argument allows
// them to specificy how much data they produced into the buffer, which should
// be less than or equal to the size of the buffer ('producer_buffer_size_').
static void ReleaseProducerBuffer(ProducerType* acquired_ptr,
size_t release_size) {
// error checking
if (ProducerQueueFull()) {
std::cerr << "ERROR: ReleaseProducerBuffer was called but "
<< "the Producer queue is full. This should not be possible. "
<< "This could be caused by calling ReleaseProducerBuffer more "
<< "than once for the same pointer returned by "
<< "AcquireProducerBuffer\n";
std::terminate();
}
// error checking
if (release_size > producer_buffer_size_) {
std::cerr << "ERROR: tried to write " << release_size << " elements but "
<< "the buffer size is only " << producer_buffer_size_ << "\n";
std::terminate();
}
// find the buffer index based on the pointer
auto it = producer_ptr_to_idx_map_.find(acquired_ptr);
// error checking, make sure the pointer to release is actually one of the
// buffers that were acquired.
if (it == producer_ptr_to_idx_map_.end()) {
std::cerr << "ERROR: an unknown pointer was passed to "
<< "ReleaseProducerBuffer.\n";
std::terminate();
}
// get the buffer index from the iterator
size_t buf_idx = it->second;
// push the produce request
produce_q_.Push(std::make_tuple(buf_idx, release_size));
}
// This single API call is used by the user to create a consume request.
// The return boolean indicates whether the request was accepted or not (based
// on the number of outstanding consume requests). If the call succeeds (i.e.
// this function returns 'true') then the reques was accepted and the
// 'consumer_callback' function will be called sometime in the future by the
// API as a response to this request.
static bool RequestConsumer(size_t launch_size) {
bool success;
///////////////////////////////////
// Entering critical section
// this allows AcquireProducerBuffer to be called from different threads
consume_requests_outstanding_mtx_.lock();
if (consume_requests_outstanding_ >= num_consumer_buffers_) {
// full of reading consume events, failed to do a new one
assert(consume_requests_outstanding_ == num_consumer_buffers_);
success = false;
} else {
// error checking
if (launch_size > consumer_buffer_size_) {
std::cerr << "ERROR: tried to read " << launch_size << " elements but "
<< "the buffer size is only " << consumer_buffer_size_
<< "\n";
std::terminate();
}
// error checking
if (ConsumerQueueFull()) {
std::cerr << "ERROR: LaunchConsumer was called and was about to launch "
<< "a new Consumer kernel, but the Consumer queue is full\n";
std::terminate();
}
// Push the consume request, move to the next Consumer buffer, increment
// the number of outstanding Consume requests, and set the success code.
consume_q_.Push(std::make_tuple(consumer_buffer_idx_, launch_size));
consumer_buffer_idx_ = (consumer_buffer_idx_ + 1) % num_consumer_buffers_;
consume_requests_outstanding_++;
success = true;
}
consume_requests_outstanding_mtx_.unlock();
// Exiting critical section
///////////////////////////////////
return success;
}
// Tell the KernelLaunchAndWaitThread to flush the launch queue.
static void Flush() {
flush_ = true;
}
// This synchronizes with the KernelLaunchAndWaitThread.
// This should be called once the user is done performing ALL request
// (i.e. both Produce and Consume request).
// NOTE: this API call is blocking. It will block until all of the kernels
// have been launched and finished.
static void Sync() {
// flush the launch queue
Flush();
// wait until the all of the queues are empty
while (
!(LaunchQueueEmpty() && ProducerQueueEmpty() && ConsumerQueueEmpty())) {
}
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// low latency, low throughput API
// these functions behave a lot like host pipes and are convenient to use
// if one does not care about throughput
static void Write(const ProducerType &data) {
// write the data into the first buffer
producer_buffer_[0][0] = data;
// launch kernel to produce a single element of data to the ProducerPipe
auto e = LaunchProducerKernel(producer_buffer_[0], 1);
// wait for kernel to finish before returning to user (synchronous)
e.wait();
}
static ConsumerType Read() {
// launch a kernel to read one element from the ConsumerPipe
auto e = LaunchConsumerKernel(consumer_buffer_[0], 1);
// wait for kernel to finish before returning to user (synchronous)
e.wait();
// return the data read
return consumer_buffer_[0][0];
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// Kernel functions
// NOTE: the code in these functions are device code. This means they get
// synthesized into FPGA kernels.
static event LaunchProducerKernel(ProducerType *usm_ptr, size_t count) {
return sycl_q_->single_task<ProducerKernelId<Id>>([=] {
host_ptr<ProducerType> ptr(usm_ptr);
for (size_t i = 0; i < count; i++) {
// host->device: read from USM and write to the ProducerPipe
auto val = *(ptr + i);
ProducerPipe::write(val);
}
});
}
static event LaunchConsumerKernel(ConsumerType *usm_ptr, size_t count) {
return sycl_q_->single_task<ConsumerKernelId<Id>>([=] {
host_ptr<ConsumerType> ptr(usm_ptr);
for (size_t i = 0; i < count; i++) {
// device->host: read from the ConsumerPipe and write to USM
auto val = ConsumerPipe::read();
*(ptr + i) = val;
}
});
}
//////////////////////////////////////////////////////////////////////////////
};
#endif /* __HOSTSTREAMER_HPP__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/buffered_host_streaming/src/streaming_without_api.hpp | #ifndef __STREAMING_WITHOUT_API_HPP__
#define __STREAMING_WITHOUT_API_HPP__
#include <algorithm>
#include <numeric>
#include <atomic>
#include <queue>
#include <thread>
#include <vector>
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "common.hpp"
using namespace sycl;
using namespace std::chrono;
////////////////////////////////////////////////////////////////////////////////
// forward declare functions
template<typename T>
void DoOneIteration(queue& q, size_t buffers, size_t buffer_count, size_t reps,
size_t iterations, size_t threads,
T *in_stream, T *out_stream,
std::vector<high_resolution_clock::time_point>& time_in,
std::vector<high_resolution_clock::time_point>& time_out,
high_resolution_clock::time_point& start,
high_resolution_clock::time_point& end);
template<typename T>
bool DoWork(queue& q, size_t buffers, size_t buffer_count, size_t reps,
size_t iterations, size_t threads);
template<typename T>
void ProducerThread(T* in_stream, size_t buffer_count, size_t reps, int threads,
std::atomic<bool>& data_valid, T*& out_ptr);
template<typename T>
void KernelThread(queue& q, size_t buffers, size_t buffer_count, size_t reps,
int threads,
std::vector<T*>& in_buf, std::vector<T*>& out_buf,
std::atomic<bool>& produce_data_valid, T*& in_ptr,
T* out_stream,
std::vector<high_resolution_clock::time_point>& time_in,
std::vector<high_resolution_clock::time_point>& time_out);
template<typename T>
void DoOneIteration(queue& q, size_t buffers, size_t buffer_count, size_t reps,
size_t iterations, size_t threads,
T *in_stream, T *out_stream,
std::vector<high_resolution_clock::time_point>& time_in,
std::vector<high_resolution_clock::time_point>& time_out,
high_resolution_clock::time_point& start,
high_resolution_clock::time_point& end);
template<typename T>
event SubmitKernel(queue &q, T *in_ptr, size_t count, T *out_ptr);
////////////////////////////////////////////////////////////////////////////////
//
// This function contains the logic to perform the buffered streaming.
// It performs a single iteration of the design. This function will be called
// multiple times to improve the accuracy of the performance measurement.
//
template<typename T>
void DoOneIteration(queue& q, size_t buffers, size_t buffer_count, size_t reps,
size_t iterations, size_t threads,
T *in_stream, T *out_stream,
std::vector<high_resolution_clock::time_point>& time_in,
std::vector<high_resolution_clock::time_point>& time_out,
high_resolution_clock::time_point& start,
high_resolution_clock::time_point& end) {
// the Producer and Consumer get half of the total threads, each.
// std::max() guards against the case where there is only 1 thread.
size_t half_threads = std::max(size_t(1), threads/2);
// allocate space for the USM buffers
std::vector<T*> in(buffers);
std::vector<T*> out(buffers);
for (size_t i = 0; i < buffers; i++) {
if ((in[i] = malloc_host<T>(buffer_count, q)) == nullptr) {
std::cerr << "ERROR: could not allocate space for 'in[" << i << "]'\n";
std::terminate();
}
if ((out[i] = malloc_host<T>(buffer_count, q)) == nullptr) {
std::cerr << "ERROR: could not allocate space for 'out[" << i << "]'\n";
std::terminate();
}
}
// inter-thread communication variables
T* produce_ptr(in[0]);
std::atomic<bool> produce_data_valid(false);
start = high_resolution_clock::now();
// start the Producer in a new thread (starts in the ProducerThread<T>
// function)
std::thread producer_thread(ProducerThread<T>,
in_stream, buffer_count, reps,
half_threads,
std::ref(produce_data_valid),
std::ref(produce_ptr));
// run the kernel in this thread
KernelThread<T>(q, buffers, buffer_count, reps, half_threads,
in, out, produce_data_valid, produce_ptr,
out_stream, time_in, time_out);
// wait for producer to finish
producer_thread.join();
end = high_resolution_clock::now();
// free the USM buffers
for (size_t i = 0; i < buffers; i++) {
sycl::free(in[i], q);
sycl::free(out[i], q);
}
}
//
// The top level function for doing work with the design. It deals with timing,
// checking errors, and running multiple iterations to improve performance
// accuracy.
//
template<typename T>
bool DoWork(queue& q, size_t buffers, size_t buffer_count, size_t reps,
size_t iterations, size_t threads) {
// track how many errors we detect in the output
size_t total_errors = 0;
// timing data
std::vector<double> latency_ms(iterations);
std::vector<double> process_time_ms(iterations);
// create input and output streams of data for ALL the data to be processed
size_t total_count = buffer_count * reps;
std::vector<T> in_stream(total_count);
std::vector<T> out_stream(total_count);
// generate random input data
std::generate_n(in_stream.begin(), total_count, [] { return rand() % 100; });
// track the input and output times for each repetition (latency)
std::vector<high_resolution_clock::time_point> time_in(reps);
std::vector<high_resolution_clock::time_point> time_out(reps);
for (size_t i = 0; i < iterations; i++) {
// reset thread sharing variables and output stream
std::fill_n(out_stream.begin(), total_count, 0);
// do an iteration
high_resolution_clock::time_point start, end;
DoOneIteration(q, buffers, buffer_count, reps, iterations, threads,
in_stream.data(), out_stream.data(),
time_in, time_out, start, end);
// validate the results
total_errors += CountErrors(out_stream.data(), total_count,
in_stream.data());
// find the average latency for all reps
double avg_rep_latency = 0.0;
for (size_t j = 0; j < reps; j++) {
duration<double, std::milli> l = time_out[j] - time_in[j];
avg_rep_latency += l.count();
}
latency_ms[i] = avg_rep_latency / reps;
// track the total processing time
duration<double, std::milli> process_time = end - start;
process_time_ms[i] = process_time.count();
}
// print the performance info
PrintPerformanceInfo<T>("without API", total_count, latency_ms, process_time_ms);
return total_errors == 0;
}
//
// The producer thread function. All production of data happens in this function
// which is run in a separate CPU thread from the launching of kernels and
// consumption of data.
//
template<typename T>
void ProducerThread(T* in_stream, size_t buffer_count, size_t reps, int threads,
std::atomic<bool>& data_valid, T*& out_ptr) {
// In our case, the Producer's job is simple. It has an input stream of data
// ('in_stream') whose size is buffer_count * reps elements
// (i.e. ALL of the data).
// When signalled to, it produces buffer_count elements to 'out_ptr', which is
// a shared variable between the Producer thread and the thread launching the
// kernels.
size_t rep = 0;
while (rep < reps) {
// The 'data_valid' flag is also shared between the Producer thread
// and the kernel launching thread. The kernel thread sets 'data_valid' to
// false when it is ready for the Producer to produce new data to 'out_ptr'.
// The 'data_valid' flag is the mechanism by which the Producer thread
// tells the kernel launching thread that the input data is ready, AND how
// the kernel launcher thread tells the Producer thread that it is ready
// for new data.
if (!data_valid) {
// The kernel has signalled to the Producer that it is ready for new data,
// so copy 'buffer_count' elements to the shared pointer 'out_ptr'
ProducerFunction(out_ptr,
in_stream + buffer_count*rep,
buffer_count,
threads);
// once the data has been produced, raise the 'data_valid' flag, which
// signals to the kernel launching thread that the data at 'out_ptr' is
// valid and ready to use. Remember, the kernel launching thread will
// lower this flag when it is ready for new data to be produced!
data_valid = true;
rep++;
}
}
}
//
// This function handles both the launching of SYCL kernels and the
// consumption of the data.
//
template<typename T>
void KernelThread(queue& q, size_t buffers, size_t buffer_count, size_t reps,
int threads,
std::vector<T*>& in_buf, std::vector<T*>& out_buf,
std::atomic<bool>& produce_data_valid, T*& in_ptr,
T* out_stream,
std::vector<high_resolution_clock::time_point>& time_in,
std::vector<high_resolution_clock::time_point>& time_out) {
// initialize
size_t in_rep = 0;
size_t out_rep = 0;
size_t buf_idx = 0;
// queue to track the inflight kernel events and the index of the buffer
// they are using (for multi-buffering).
std::queue<std::pair<event, size_t>> user_kernel_q;
// do work
while(out_rep < reps) {
// Conditions for processing new input (launching a new kernel):
// (NOTE: conditions 1, 2, AND 3 must be met)
// 1) there is room in the queue (based on number of buffers)
// 2) we have more input data to process
// 3) the input data from the producer is valid (set by Producer thread)
//
// Conditions for consuming kernel output (waiting on oldest kernel to end):
// (NOTE: conditions 1 OR 2 need to be met)
// 1) the queue is full
// 2) we have processed all of the input data (no kernels left to launch)
bool queue_full = (user_kernel_q.size() == buffers);
bool all_input_data_processed = (in_rep == reps);
if (!queue_full && !all_input_data_processed && produce_data_valid) {
// launch the kernel
event e = SubmitKernel(q, in_buf[buf_idx], buffer_count, out_buf[buf_idx]);
// push the new kernel event and buffer index pair into the queue
user_kernel_q.push(std::make_pair(e, buf_idx));
// mark the input time of this buffer (to track the latency)
time_in[in_rep] = high_resolution_clock::now();
// move to the next buffer (n-way buffering)
buf_idx = (buf_idx + 1) % buffers;
// if after pushing the new kernel there is still space in the queue,
// then tell the producer we are ready to accept new data in the
// next buffer
if (user_kernel_q.size() < buffers) {
// NOTE: order important for these two statements (described later)
in_ptr = in_buf[buf_idx];
produce_data_valid = false;
}
// we started the processing of another input
in_rep++;
} else if (queue_full || all_input_data_processed) {
// pop the oldest event/buffer index pair in the queue
auto event_index_pair = user_kernel_q.front();
user_kernel_q.pop();
// wait on the kernel event to finish
event_index_pair.first.wait();
// mark the output time of this buffer (to track the latency)
time_out[out_rep] = high_resolution_clock::now();
// tell the Producer that it can start producing the next input
// data BEFORE consuming the output, so that the Producer can start
// producing the next data while this thread consumes the output
// (which we are about to do below).
// NOTE: the order is important here. Switch the 'in_ptr' to the other
// buffer BEFORE lowering the 'produce_data_valid' flag (which signals to
// the Producer to start producing data into 'in_ptr'). I.e. we need to
// set the correct pointer BEFORE signalling to the Producer to produce
// to that pointer.
in_ptr = in_buf[buf_idx];
produce_data_valid = false;
// consume the output
// (NOTE: the kernel launching and Consumer use the same thread)
ConsumerFunction(out_stream + out_rep*buffer_count,
out_buf[event_index_pair.second],
buffer_count,
threads);
// we have processed another output
out_rep++;
}
}
}
// Forward declare the kernel name to reduce name mangling
class Kernel;
//
// Submit the kernel for the single-kernel design
//
template<typename T>
event SubmitKernel(queue &q, T *in_ptr, size_t count, T *out_ptr) {
return q.single_task<Kernel>([=]() [[intel::kernel_args_restrict]] {
// using a host_ptr class tells the compiler that this pointer lives in
// the host's address space
host_ptr<T> in(in_ptr);
host_ptr<T> out(out_ptr);
for (size_t i = 0; i < count; i++) {
T data = *(in + i);
*(out + i) = data;
}
});
}
#endif /* __STREAMING_WITHOUT_API_HPP__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/buffered_host_streaming/src/streaming_with_api.hpp | #ifndef __STREAMING_WITH_API_HPP__
#define __STREAMING_WITH_API_HPP__
#include <algorithm>
#include <numeric>
#include <queue>
#include <thread>
#include <vector>
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "common.hpp"
#include "HostStreamer.hpp"
using namespace sycl;
using namespace std::chrono;
////////////////////////////////////////////////////////////////////////////////
// forward declare functions
template<typename T>
void DoOneIterationAPI(queue& q, size_t buffers, size_t buffer_count,
size_t reps, size_t iterations, size_t threads,
T *in_stream, T *out_stream,
std::vector<high_resolution_clock::time_point>& time_in,
std::vector<high_resolution_clock::time_point>& time_out,
high_resolution_clock::time_point& start,
high_resolution_clock::time_point& end);
template<typename T>
bool DoWorkAPI(queue& q, size_t buffers, size_t buffer_count, size_t reps,
size_t iterations, size_t threads);
////////////////////////////////////////////////////////////////////////////////
// Forward declare the kernel and HostStreamer name to reduce name mangling
class APIKernel;
class MyStreamerId;
//
// This function contains the logic for buffered streaming.
// It perform a single iteration of the design. The calling function will
// call this function multiple times to increase the performance
// measurement accuracy.
//
template<typename T>
void DoOneIterationAPI(queue& q, size_t buffers, size_t buffer_count,
size_t reps, size_t iterations, size_t threads,
T *in_stream, T *out_stream,
std::vector<high_resolution_clock::time_point>& time_in,
std::vector<high_resolution_clock::time_point>& time_out,
high_resolution_clock::time_point& start,
high_resolution_clock::time_point& end) {
// The Producer and Consumer get half of the total threads, each.
// std::max() guards against the case where there is only 1 thread.
size_t half_threads = std::max(size_t(1), threads/2);
// total number of elements
size_t total_count = buffer_count * reps;
// Alias 'MyStreamer' to the templated HostStreamer. The streamer
// will stream in and out elements of type 'T'.
// Template arguments for HostStreamer (in order)
// Id: MyStreamerId
// ProducerType: T
// ConsumerType: T
// min_producer_capacity: 0 (implicit)
// min_consumer_capacity: 0 (implicit)
using MyStreamer = HostStreamer<MyStreamerId, T, T>;
// Initialize the streamer
// # of Producer buffers = 'buffers'
// size of Producer buffers = 'buffer_count'
// # of Consumer buffers = 'buffers'
// size of Consumer buffers = 'buffer_count'
MyStreamer::init(q, buffers, buffer_count, buffers, buffer_count);
//////////////////////////////////////////////////////////////////////////
// Setup the Producer and Consumer callback function for the HostStreamer.
// This consumer_callback function is called when the kernel, which is
// launched by a consumer request (i.e. MyStreamer::RequestConsumer),
// completes and the output data (ptr) is ready to be processed by the host.
// There will be one call to this callback for every successful call to
// MyStreamer::RequestConsumer.
int out_rep = 0;
MyStreamer::consumer_callback = [&](const T* ptr, size_t count) {
// mark the time we received this data (for latency measurements)
time_out[out_rep] = high_resolution_clock::now();
// Consume the output
// In this simple design, the Consumer simply copies the output (ptr)
// into a larger buffer (out_stream). In a 'real' system, this may
// be moving the data somewhere else, or performing more computation on it.
ConsumerFunction(&out_stream[out_rep*buffer_count],
ptr,
count,
half_threads);
// next repetition
out_rep++;
};
// In our case, we don't really care about the producer_callback. It is
// called when the kernel that did the producing finishes. The API defaults
// the callback to an empty function, so we could omit the code that sets
// 'producer_callback' below, but we include it for completeness.
MyStreamer::producer_callback = [&](size_t /*count*/) {
// nothing to do...
};
//////////////////////////////////////////////////////////////////////////
// Launch the FPGA processing kernel. This kernel is only launched ONCE!
// Therefore, it has to be able to process ALL of the data. In this example,
// we know the total amount of data to be processed ('total_count') and
// therefore we can easily bound the computation of this kernel. In other
// cases, this may not be possible and an infinite loop may be required (i.e.
// read from the Producer pipe and produce to the Consumer pipe, forever).
auto kernel_event = q.single_task<APIKernel>([=] {
// process ALL of the possible data
for (size_t i = 0; i < total_count; i++) {
// read from the producer pipe
auto data = MyStreamer::ProducerPipe::read();
// <<<<< your computation goes here! >>>>>
// write to the consumer pipe
MyStreamer::ConsumerPipe::write(data);
}
});
start = high_resolution_clock::now();
// Start the producer thread.
// The code in the lambda runs in a different thread and therefore does not
// block the process of the 'main' thread.
std::thread producer_thread([&] {
size_t rep = 0;
T *buffer = nullptr;
while (rep < reps) {
// try to acquire the buffer from the HostStreamer API
buffer = MyStreamer::AcquireProducerBuffer();
// check if we acquired the buffer
if (buffer != nullptr) {
// If we acquired the buffer, produce to it.
// In our design, we simply produce data by copying from a portion
// of the larger 'in_stream' buffer to the buffer we just acquired
// ('buffer'). In a 'real' design, this production may actual
// computation (e.g. a random number generator), come from another
// process, from an IO device (e.g. Ethernet), etc.
ProducerFunction(buffer,
&in_stream[buffer_count*rep],
buffer_count,
half_threads);
// The producing is done, release the buffer. This releases 'ownership'
// of 'buffer' back to the API and creates a produce request to the API
// to produce 'buffer_count' elements from 'buffer' to the device
// (through MyStreamer::ProducerPipe).
MyStreamer::ReleaseProducerBuffer(buffer, buffer_count);
// mark input time for this rep (for latency measurements)
time_in[rep] = high_resolution_clock::now();
// rep done
rep++;
}
}
});
// Make all of the asynchronous consume requests
size_t in_rep = 0;
while (in_rep < reps) {
// This simply makes a Consumer request. If MyStreamer::RequestConsumer
// returns 'false', the request was NOT accepted by the API and therefore
// you should try again. If MyStreamer::RequestConsumer returns 'true' the
// request was accepted and, at some later time, you (the API user) will be
// notified that the request is complete by the consumer_callback
// (MyStreamer::consume_callback, defined earlier in this function)
// which will provide the output data and size.
if (MyStreamer::RequestConsumer(buffer_count)) {
in_rep++;
}
}
// Wait for the producer thread to finish. It will finish once all of the
// produce requests have been launched (that doesn't mean they are done).
producer_thread.join();
// Synchronize with the HostStreamer. This will wait until the launch queue is
// empty, which happens when all of the produce and consume requests have been
// completed (i.e. kernel launched, complete, and callback complete).
MyStreamer::Sync();
// Wait on the main processing kernel event.
// NOTE: if the kernel executed forever (i.e. a while(1)-loop) this would
// block forever, and therefore should be omitted. The fact that all the
// data was consumed by the Consumer (MyStreamer::Sync() returned)
// implies the computation is done.
kernel_event.wait();
end = high_resolution_clock::now();
// destroy the streamer data structures
MyStreamer::destroy();
}
//
// The top level function for doing work with the API. It deals with timing,
// checking errors, and running multiple iterations to improve performance
// accuracy.
//
template<typename T>
bool DoWorkAPI(queue& q, size_t buffers, size_t buffer_count, size_t reps,
size_t iterations, size_t threads) {
// track how many errors we detect in the output
size_t total_errors = 0;
// timing data
std::vector<double> latency_ms(iterations);
std::vector<double> process_time_ms(iterations);
// track the input and output times for each repetition (latency)
std::vector<high_resolution_clock::time_point> time_in(reps);
std::vector<high_resolution_clock::time_point> time_out(reps);
// create input and output streams of data for ALL the data to be processed
size_t total_count = buffer_count * reps;
std::vector<T> in_stream(total_count);
std::vector<T> out_stream(total_count);
// generate random input data
std::generate_n(in_stream.begin(), total_count, [] { return rand() % 100; });
for (size_t i = 0; i < iterations; i++) {
// reset stuff
std::fill_n(out_stream.begin(), total_count, 0);
// do the iteration
high_resolution_clock::time_point start, end;
DoOneIterationAPI(q, buffers, buffer_count, reps, iterations, threads,
in_stream.data(), out_stream.data(),
time_in, time_out, start, end);
// validate the results
total_errors += CountErrors(out_stream.data(), total_count,
in_stream.data());
// find the average latency for all reps
double avg_rep_latency = 0.0;
for (size_t j = 0; j < reps; j++) {
duration<double, std::milli> l = time_out[j] - time_in[j];
avg_rep_latency += l.count();
}
latency_ms[i] = avg_rep_latency / reps;
// track the total processing time
duration<double, std::milli> process_time = end - start;
process_time_ms[i] = process_time.count();
}
// print the performance info
PrintPerformanceInfo<T>("with API", total_count, latency_ms, process_time_ms);
return total_errors == 0;
}
#endif /* __STREAMING_WITH_API_HPP__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/buffered_host_streaming/src/buffered_host_streaming.cpp | #include <assert.h>
#include <algorithm>
#include <array>
#include <chrono>
#include <iomanip>
#include <numeric>
#include <functional>
#include <string>
#include <thread>
#include <type_traits>
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "exception_handler.hpp"
#include "streaming_without_api.hpp"
#include "streaming_with_api.hpp"
using namespace sycl;
// the type used
// NOTE: the tutorial assumes the use of a sycl::vec datatype (like long8).
// Therefore, 'Type' must be a sycl::vec datatype (e.g. int8, char64, etc).
using Type = long8;
// forward declare the roofline analysis function
template<typename T>
void DoRooflineAnalysis(queue& q, size_t buffer_count, size_t iterations,
size_t threads);
// the main function
int main(int argc, char* argv[]) {
// parse command line arguments
#if defined(FPGA_EMULATOR)
size_t reps = 20;
size_t buffer_count = 1 << 12; // 4096
size_t iterations = 2;
#elif defined(FPGA_SIMULATOR)
size_t reps = 2;
size_t buffer_count = 1 << 8; // 256
size_t iterations = 2;
#else
size_t reps = 200;
size_t buffer_count = 1 << 19; // 524388
size_t iterations = 5;
#endif
// auto-detect the number of available threads
size_t detected_threads = (size_t)(std::thread::hardware_concurrency());
// thread::hardware_concurrency() returns 0 if it cannot determine
// the number of threads, so fallback to 2
size_t threads = std::max(size_t(2), detected_threads);
size_t buffers = 2;
bool need_help = false;
// parse the command line arguments
for (int i = 1; i < argc; i++) {
std::string arg(argv[i]);
if (arg == "--help" || arg == "-h") {
need_help = true;
} else {
std::string str_after_equals = arg.substr(arg.find("=") + 1);
if (arg.find("--reps=") == 0) {
reps = atoi(str_after_equals.c_str());
} else if (arg.find("--buffers=") == 0) {
buffers = atoi(str_after_equals.c_str());
} else if (arg.find("--buffer_count=") == 0) {
buffer_count = atoi(str_after_equals.c_str());
} else if (arg.find("--iterations=") == 0) {
iterations = std::max(2, atoi(str_after_equals.c_str()) + 1);
} else if (arg.find("--threads=") == 0) {
threads = atoi(str_after_equals.c_str());
} else {
std::cout << "WARNING: ignoring unknown argument '" << arg << "'\n";
}
}
}
// print help is asked
if (need_help) {
std::cout << "USAGE: "
<< "./buffered_host_streaming "
<< "[--reps=<int>] "
<< "[--buffers=<int>] "
<< "[--buffer_count=<int>] "
<< "[--iterations=<int>] "
<< "[--threads=<int>]\n";
return 0;
}
// check the reps
if (reps <= 0) {
std::cerr << "ERROR: 'reps' must be greater than 0\n";
std::terminate();
}
// check the buffer_count
if (buffer_count <= 0) {
std::cerr << "ERROR: 'buffer_count' must be greater than 0\n";
std::terminate();
}
// check the number of iterations
if (iterations <= 0) {
std::cerr << "ERROR: 'iterations' must be positive\n";
std::terminate();
}
if (threads <= 0) {
std::cerr << "ERROR: 'threads' must be positive\n";
std::terminate();
}
// print info
std::cout << "Repetitions: " << reps << "\n";
std::cout << "Buffers: " << buffers << "\n";
std::cout << "Buffer Count: " << buffer_count << "\n";
std::cout << "Iterations: " << iterations-1 << "\n";
std::cout << "Total Threads: " << threads << "\n";
std::cout << "\n";
bool passed = true;
try {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
// queue properties to enable profiling
property_list prop_list { property::queue::enable_profiling() };
// create the device queue
queue q(selector, fpga_tools::exception_handler, prop_list);
// make sure the device supports USM host allocations
auto device = q.get_device();
if (!device.get_info<info::device::usm_host_allocations>()) {
std::cerr << "ERROR: The selected device does not support USM host"
<< " allocations\n";
std::terminate();
}
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
///////////////////////////////////////////////////////////////////////////
// find the bandwidth of each processing component in our design
std::cout << "Running the roofline analysis\n";
DoRooflineAnalysis<Type>(q, buffer_count, iterations, threads);
std::cout << "Done the roofline analysis\n\n";
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// run the design that does not use the API (see streaming_without_api.hpp)
std::cout << "Running the full design without API\n";
passed &= DoWork<Type>(q, buffers, buffer_count, reps, iterations, threads);
std::cout << "\n";
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// run the design that uses the API (see streaming_with_api.hpp)
std::cout << "Running the full design with API\n";
passed &= DoWorkAPI<Type>(q, buffers, buffer_count, reps, iterations,
threads);
std::cout << "\n";
///////////////////////////////////////////////////////////////////////////
} catch (exception const& e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
if(passed) {
std::cout << "PASSED\n";
return 0;
} else {
std::cout << "FAILED\n";
return 1;
}
}
// This function performs a bandwidth test on the individual components of the
// processing pipeline: Producer, Consumer, and the FPGA kernel.
// It computes (and returns) the maximum possible throughput of the full design
// when the individual components are combined.
template<typename T>
void DoRooflineAnalysis(queue& q, size_t buffer_count, size_t iterations,
size_t threads) {
// allocate some memory to work with
T *tmp_in[2], *tmp_out[2];
for (size_t i = 0; i < 2; i++) {
if ((tmp_in[i] = malloc_host<T>(buffer_count, q)) == nullptr) {
std::cerr << "ERROR: could not allocate space for "
<< "'tmp_in[" << i << "]'\n";
std::terminate();
}
if ((tmp_out[i] = malloc_host<T>(buffer_count, q)) == nullptr) {
std::cerr << "ERROR: could not allocate space for "
<< "'tmp_out[" << i << "]'\n";
std::terminate();
}
}
// the Producer and Consumer get half of the total threads, each.
// std::max() guards against the case where there is only 1 thread.
size_t half_threads = std::max(size_t(1), threads/2);
// these tests are quick, so run some extra iterations for more accuracy
size_t bw_test_iterations = iterations * 4 + 1;
// timing variables
high_resolution_clock::time_point start, end;
duration<double, std::milli> delta_ms;
double processing_time_producer = 0.0, tp_producer;
double processing_time_consumer = 0.0, tp_consumer;
double processing_time_producer_consumer = 0.0, tp_producer_consumer;
double processing_time_kernel = 0.0, tp_kernel;
// the total number of megabytes processed by the operations
double size_mb = sizeof(T) * buffer_count * 1e-6;
// do multiple interations of the test to improve measurement accuracy
for (size_t i = 0; i < bw_test_iterations; i++) {
// generate some data
std::fill_n(tmp_out[0], buffer_count, i);
std::fill_n(tmp_out[1], buffer_count, i);
// Producer in isolation
start = high_resolution_clock::now();
// ProducerFunction is defined in common.hpp
ProducerFunction(tmp_out[0], tmp_in[0], buffer_count, half_threads);
end = high_resolution_clock::now();
delta_ms = end - start;
if (i > 0) processing_time_producer += delta_ms.count();
// wait 10ms
std::this_thread::sleep_for(std::chrono::milliseconds(10));
// Consumer in isolation
start = high_resolution_clock::now();
// ConsumerFunction is defined in common.hpp
ConsumerFunction(tmp_in[0], tmp_out[0], buffer_count, half_threads);
end = high_resolution_clock::now();
delta_ms = end - start;
if (i > 0) processing_time_consumer += delta_ms.count();
// wait 10ms
std::this_thread::sleep_for(std::chrono::milliseconds(10));
// Producer & Consumer at the same time
// NOTE: this is the most accurate measurement of our actual design,
// since the Producer and Consumer will be executing in parallel (see
// README.md for more details on this).
// The ProducerFunction and ConsumerFunction are defined in common.hpp
start = high_resolution_clock::now();
std::thread producer_thread([&] {
ProducerFunction(tmp_out[0], tmp_in[0], buffer_count, half_threads);
});
ConsumerFunction(tmp_out[1], tmp_in[1], buffer_count, half_threads);
producer_thread.join();
end = high_resolution_clock::now();
delta_ms = end - start;
if (i > 0) processing_time_producer_consumer += delta_ms.count();
// wait 10ms
std::this_thread::sleep_for(std::chrono::milliseconds(10));
// Kernel in isolation
start = high_resolution_clock::now();
// SubmitKernel is defined in streaming_without_api.hpp
auto e = SubmitKernel(q, tmp_in[0], buffer_count, tmp_out[0]);
e.wait();
end = high_resolution_clock::now();
delta_ms = end - start;
if (i > 0) processing_time_kernel += delta_ms.count();
// wait 10ms
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
// average the processing times across iterations
processing_time_producer /= (bw_test_iterations-1);
processing_time_consumer /= (bw_test_iterations-1);
processing_time_producer_consumer /= (bw_test_iterations-1);
processing_time_kernel /= (bw_test_iterations-1);
// compute throughputs
tp_producer = size_mb / (processing_time_producer * 1e-3);
tp_consumer = size_mb / (processing_time_consumer * 1e-3);
tp_producer_consumer = size_mb / (processing_time_producer_consumer * 1e-3);
tp_kernel = size_mb / (processing_time_kernel * 1e-3);
// print results
std::cout << std::fixed << std::setprecision(4);
std::cout << "Producer (" << half_threads << " threads)\n";
std::cout << "\tTime: " << processing_time_producer << " ms\n";
std::cout << "\tThroughput: " << tp_producer << " MB/s\n";
std::cout << "Consumer (" << half_threads << " threads)\n";
std::cout << "\tTime: " << processing_time_consumer << " ms\n";
std::cout << "\tThroughput: " << tp_consumer << " MB/s\n";
std::cout << "Producer & Consumer (" << half_threads << " threads, each)\n";
std::cout << "\tTime: " << processing_time_producer_consumer << " ms\n";
std::cout << "\tThroughput: " << tp_producer_consumer << " MB/s\n";
std::cout << "Kernel\n";
std::cout << "\tTime: " << processing_time_kernel << " ms\n";
std::cout << "\tThroughput: " << tp_kernel << " MB/s\n";
// find the minimum throughput (which will bottleneck the design)
std::vector<double> tps = {tp_producer,
tp_consumer,
tp_producer_consumer,
tp_kernel};
// the index of the min throughput
int min_tp_idx = std::min_element(tps.begin(), tps.end()) - tps.begin();
// the minimum throughput
double min_tp = tps[min_tp_idx];
// check if the bottleneck throughput is the kernel
bool kernel_is_limit = (min_tp_idx == tps.size()-1);
// the minimum throughput is the maximum throughput of the full design
std::cout << "\n";
std::cout << "Maximum Design Throughput: " << min_tp << " MB/s\n";
std::cout << "The FPGA kernel "
<< (kernel_is_limit ? "limits" : "does not limit")
<< " the performance of the design\n";
// free temp USM memory
for (size_t i = 0; i < 2; i++) {
sycl::free(tmp_in[i], q);
sycl::free(tmp_out[i], q);
}
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/buffered_host_streaming/src/common.hpp | #ifndef __COMMON_HPP__
#define __COMMON_HPP__
#include <algorithm>
#include <chrono>
#include <numeric>
#include <vector>
#include <thread>
// A multithreaded version of memcpy.
// On modern processors with multiple cores and threads, a single-threaded
// memcpy cannot saturate the memory bandwidth (not even close). Moreover,
// a single-threaded memcpy doesn't even get close to the PCIe bandwidth.
// To improve the performance of the Producer and Consumer functions
// (which are simply memcpy in our simple design) we use a multi-threaded
// version of memcpy.
template<typename T>
void memcpy_threaded(T* dst, const T* src, size_t count, int num_threads) {
if (num_threads == 1) {
// if the number of threads is 1, just do a regular memcpy()
memcpy(dst, src, count * sizeof(T));
} else {
// multi-threaded memcpy()
std::vector<std::thread> threads;
// number of elements per thread = count num_threads
size_t count_per_thread = count / num_threads;
// the last thread may have a different count if 'num_threads' is not
// a multiple of 'count'.
size_t count_last_thread = count - (num_threads-1)*count_per_thread;
// thread lambda function
auto f = [](T* dst, const T* src, size_t count) {
memcpy(dst, src, count * sizeof(T));
};
// launch the threads
for (int i = 0; i < num_threads; i++) {
size_t t_count = (i == num_threads-1) ? count_last_thread
: count_per_thread;
threads.push_back(std::thread(f,
dst + i*count_per_thread,
src + i*count_per_thread,
t_count));
}
// wait for the threads to finish
for (auto& t : threads) {
t.join();
}
}
}
// The Producer function is a simple memcpy() from input to output
template<typename T>
void ProducerFunction(T* dst, const T* src, size_t count, int num_threads) {
memcpy_threaded(dst, src, count, num_threads);
}
// The Consumer function is a simple memcpy() from input to output
template<typename T>
void ConsumerFunction(T* dst, const T* src, size_t count, int num_threads) {
memcpy_threaded(dst, src, count, num_threads);
}
// A helper function to compute and print the performance info
template<typename T>
void PrintPerformanceInfo(std::string postfix, size_t count,
std::vector<double>& latency_ms,
std::vector<double>& process_time_ms) {
// compute the input size in MB
double input_size_mb = (sizeof(T) * count) * 1e-6;
// compute the average latency and processing time
assert(latency_ms.size() == process_time_ms.size());
double iterations = latency_ms.size() - 1;
double avg_latency_ms = std::accumulate(latency_ms.begin() + 1,
latency_ms.end(),
0.0) / iterations;
double avg_processing_time_ms = std::accumulate(process_time_ms.begin() + 1,
process_time_ms.end(),
0.0) / iterations;
// compute the throughput
double avg_tp_mb_s = input_size_mb / (avg_processing_time_ms * 1e-3);
// print info
std::cout << std::fixed << std::setprecision(4);
std::cout << "Average latency " << postfix << ": "
<< avg_latency_ms << " ms\n";
std::cout << "Average processing time " << postfix << ": "
<< avg_processing_time_ms << " ms\n";
std::cout << "Average throughput " << postfix << ": "
<< avg_tp_mb_s << " MB/s\n";
}
// given an output ('out') and a reference ('ref') count the number of errors
template<typename T>
size_t CountErrors(T* out, size_t count, T* ref) {
size_t errors = 0;
for (size_t i = 0; i < count; i++) {
auto comp = (out[i] == ref[i]);
for (auto j = 0; j < comp.size(); j++) {
if (!comp[j]) {
errors++;
}
}
}
return errors;
}
#endif /* __COMMON_HPP__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/zero_copy_data_transfer/src/buffer_kernel.hpp | #ifndef __BUFFER_KERNEL_HPP__
#define __BUFFER_KERNEL_HPP__
#pragma once
#include <vector>
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
using namespace sycl;
using namespace std::chrono;
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class BufferWorker;
// kernel using buffers to transfer data
template <typename T>
double SubmitBufferKernel(queue& q, std::vector<T>& in, std::vector<T>& out,
const unsigned int size) {
// start timer
auto start = high_resolution_clock::now();
{
// set up the input/output buffers
buffer in_buf(in);
buffer out_buf(out);
// launch the computation kernel
auto kernel_event = q.submit([&](handler& h) {
#if defined (IS_BSP)
accessor in_a(in_buf, h, read_only);
accessor out_a(out_buf, h, write_only, no_init);
#else
// When targeting an FPGA family/part, the compiler infers memory
// interfaces based on the unique buffer_location property specified
// on kernel arguments
// With this property, we tell the compiler that these buffers
// are in a location "1" whereas the pointers from ZeroCopyKernel
// are in the location "0"
sycl::ext::oneapi::accessor_property_list location_of_buffer{
ext::intel::buffer_location<1>};
accessor in_a(in_buf, h, read_only, location_of_buffer);
sycl::ext::oneapi::accessor_property_list location_of_buffer_no_init{
no_init, ext::intel::buffer_location<1>};
accessor out_a(out_buf, h, write_only, location_of_buffer_no_init);
#endif
h.single_task<BufferWorker>([=]() [[intel::kernel_args_restrict]] {
for (size_t i = 0; i < size; i++) {
out_a[i] = in_a[i] * i;
}
});
});
}
// We use the scope above to synchronize the FPGA kernels.
// Exiting the scope will cause the buffer destructors to be called
// which will wait until the kernels finish and copy the data back to the
// host (if the buffer was written to).
// Therefore, at this point in the code, we know the kernels have finished
// and the data has been transferred back to the host.
// stop the timer
auto end = high_resolution_clock::now();
duration<double, std::milli> diff = end - start;
return diff.count();
}
#endif /* __BUFFER_KERNEL_HPP__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/zero_copy_data_transfer/src/zero_copy_data_transfer.cpp | #include <assert.h>
#include <algorithm>
#include <chrono>
#include <iomanip>
#include <numeric>
#include <random>
#include <type_traits>
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "exception_handler.hpp"
#include "buffer_kernel.hpp"
#include "zero_copy_kernel.hpp"
using namespace sycl;
// the data type - assert that it is arithmetic
// this allows the design to easily switch between types by changing
// the line below
using Type = int;
static_assert(std::is_arithmetic<Type>::value);
int main(int argc, char* argv[]) {
// parse command line arguments
#if defined(FPGA_EMULATOR)
size_t size = 10000;
size_t iterations = 1;
#elif FPGA_SIMULATOR
size_t size = 700;
size_t iterations = 1;
#else
size_t size = 100000000;
size_t iterations = 5;
#endif
// Allow the size to be changed by a command line argument
if (argc > 1) {
size = atoi(argv[1]);
}
// check the size
if (size <= 0) {
std::cerr << "ERROR: size must be greater than 0\n";
return 1;
}
try {
// device selector
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
// create the device queue
queue q(selector, fpga_tools::exception_handler);
// make sure the device supports USM host allocations
auto device = q.get_device();
if (!device.get_info<info::device::usm_host_allocations>()) {
std::cerr << "ERROR: The selected device does not support USM host"
<< " allocations\n";
return 1;
}
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
// the golden output
std::vector<Type> out_gold(size);
// input and output data for the buffer version
std::vector<Type> in_buffer(size), out_buffer(size);
// input and output data for the zero-copy version
// malloc_host allocates memory specifically in the host's address space
#if defined(IS_BSP)
Type* in_zero_copy = malloc_host<Type>(size, q.get_context());
Type* out_zero_copy = malloc_host<Type>(size, q.get_context());
#else
// The USM pointers passed into the kernel must be allocated with the same
// buffer_location as the one specified on the kernel argument with the
// annotated_arg class.
Type *in_zero_copy = sycl::malloc_host<Type>(
size, q,
sycl::ext::intel::experimental::property::usm::buffer_location(0));
Type *out_zero_copy = sycl::malloc_host<Type>(
size, q,
sycl::ext::intel::experimental::property::usm::buffer_location(0));
#endif
// ensure that we could allocate space for both the input and output
if (in_zero_copy == NULL) {
std::cerr << "ERROR: failed to allocate space for 'in_zero_copy'\n";
return 1;
}
if (out_zero_copy == NULL) {
std::cerr << "ERROR: failed to allocate space for 'out_zero_copy'\n";
return 1;
}
// generate some random input data and compute the golden result
for (int i = 0; i < size; i++) {
// generate a random value
Type n = Type(rand() % 100);
// populate the inputs
in_buffer[i] = in_zero_copy[i] = n;
// compute the golden result
out_gold[i] = n * i;
}
// run the buffer version kernel
std::cout << "Running the buffer kernel version with size=" << size << "\n";
std::vector<double> buffer_kernel_latency(iterations);
for (size_t i = 0; i < iterations; i++) {
buffer_kernel_latency[i] = SubmitBufferKernel<Type>(q, in_buffer,
out_buffer, size);
}
// run the the zero-copy version kernel
std::cout << "Running the zero-copy kernel version with size=" << size
<< "\n";
std::vector<double> zero_copy_latency(iterations);
for (size_t i = 0; i < iterations; i++) {
zero_copy_latency[i] = SubmitZeroCopyKernel<Type>(q, in_zero_copy,
out_zero_copy, size);
}
// validate the outputs
// validate the buffer version
for (int i = 0; i < size; i++) {
if (out_gold[i] != out_buffer[i]) {
std::cerr << "ERROR: mismatch at entry " << i
<< " of 'Buffer' kernel output "
<< "(" << out_gold[i] << "," << out_buffer[i] << ")"
<< "\n";
return 1;
}
}
// validate the the zero-copy version
for (int i = 0; i < size; i++) {
if (out_gold[i] != out_zero_copy[i]) {
std::cerr << "ERROR: mismatch at entry " << i
<< " of 'ZeroCopy' kernel output "
<< "(" << out_gold[i] << "," << out_zero_copy[i] << ")"
<< "\n";
return 1;
}
}
// The FPGA emulator or simulator do not accurately represent the hardware performance
// so we don't print performance results when running with the emulator or simulator
#ifdef FPGA_EMULATOR
#elif FPGA_SIMULATOR
#else
// Compute the average latency across all iterations.
// We use the first iteration as a 'warmup' for the FPGA,
// so we ignore its results.
double buffer_avg_lat = std::accumulate(buffer_kernel_latency.begin() + 1,
buffer_kernel_latency.end(), 0.0) /
(iterations - 1);
double zero_copy_avg_lat =
std::accumulate(zero_copy_latency.begin() + 1,
zero_copy_latency.end(), 0.0) /
(iterations - 1);
std::cout << "Average latency for the buffer kernel: " << buffer_avg_lat
<< " ms\n";
std::cout << "Average latency for the zero-copy kernel: "
<< zero_copy_avg_lat << " ms\n";
#endif
// free the USM host allocations
// note that these are calls to sycl::free()
free(in_zero_copy, q);
free(out_zero_copy, q);
} catch (exception const& e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
std::cout << "PASSED\n";
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/zero_copy_data_transfer/src/zero_copy_kernel.hpp | #ifndef __ZERO_COPY_KERNEL_HPP__
#define __ZERO_COPY_KERNEL_HPP__
#pragma once
#include <vector>
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
using namespace sycl;
using namespace std::chrono;
//
// The structure of the kernels in this design is shown in the diagram below.
// The Producer kernel reads the data from CPU memory (via PCIe), producing it
// for the ZeroCopyKernel via a pipe. The Worker does the computation on the
// input data and writes it to the ConsumePipe. The consumer reads the data
// from this pipe and writes the output back to the CPU memory (via PCIe).
//
// |-----------------------------------|
// | FPGA |
// |-------------| | |
// | | | |- --------| |----------------| |
// |-------| | |--->| Producer |==>| | |
// | | | | | |----------| | | |
// | CPU |<-->| Host Memory | | | ZeroCopyKernel | |
// | | | | | |----------| | | |
// |-------| | |<---| Consumer |<==| | |
// | | | |----------| |----------------| |
// |-------------| | |
// |-----------------------------------|
//
//
// As shown in the image above and the code below, we have split this design
// into three kernels:
// 1) Producer
// 2) ZeroCopyKernel
// 3) Consumer
// We do this to decouple the reads/writes from/to the Host Memory over PCIe.
// Decoupling the memory accesses and using SYCL pipes with a substantial
// depth ('kPipeDepth' below) allows the kernel to be more resilient against
// stalls while reading/writing from/to the Host Memory over PCIe.
//
// Forward declare the kernel names in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class ZeroCopyKernel;
class Producer;
class Consumer;
// pipes
template <typename T>
using ProducePipe = pipe<class ProducePipeClass, T>;
template <typename T>
using ConsumePipe = pipe<class ConsumePipeClass, T>;
//
// reads the input data from the hosts memory
// and writes it to the ProducePipe
//
template <typename T>
event SubmitProducer(queue& q, T* in_data, size_t size) {
#if !defined(IS_BSP)
// When targeting an FPGA family/part, the compiler infers memory
// interfaces based on the unique buffer_location property specified
// on kernel arguments
// With this property, we tell the compiler that these buffers
// are in a location "0" whereas the pointers from BufferKernel
// are in the location "1"
sycl::ext::oneapi::experimental::annotated_arg h_in_data(
in_data, sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::buffer_location<0>});
#endif
return q.single_task<Producer>([=]() [[intel::kernel_args_restrict]] {
#if defined(IS_BSP)
// using a host_ptr tells the compiler that this pointer lives in the
// hosts address space
host_ptr<T> h_in_data(in_data);
#endif
for (size_t i = 0; i < size; i++) {
T data_from_host_memory = *(h_in_data + i);
ProducePipe<T>::write(data_from_host_memory);
}
});
}
//
// The worker kernel in the device:
// 1) read input data from the ProducePipe
// 2) perform computation
// 3) write the output data to the ConsumePipe
//
template <typename T>
event SubmitWorker(queue& q, size_t size) {
return q.single_task<ZeroCopyKernel>([=]() [[intel::kernel_args_restrict]] {
for (size_t i = 0; i < size; i++) {
T data = ProducePipe<T>::read();
T value = data * i; // perform computation
ConsumePipe<T>::write(value);
}
});
}
//
// reads output data from the device via ConsumePipe
// and writes it to the hosts memory
//
template <typename T>
event SubmitConsumer(queue& q, T* out_data, size_t size) {
#if !defined(IS_BSP)
// When targeting an FPGA family/part, the compiler infers memory
// interfaces based on the unique buffer_location property specified
// on kernel arguments
// With this property, we tell the compiler that these buffers
// are in a location "0" whereas the pointers from BufferKernel
// are in the location "1"
sycl::ext::oneapi::experimental::annotated_arg h_out_data(
out_data, sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::buffer_location<0>});
#endif
return q.single_task<Consumer>([=]() [[intel::kernel_args_restrict]] {
#if defined(IS_BSP)
// using a host_ptr tells the compiler that this pointer lives in the
// hosts address space
host_ptr<T> h_out_data(out_data);
#endif
for (size_t i = 0; i < size; i++) {
T data_to_host_memory = ConsumePipe<T>::read();
*(h_out_data + i) = data_to_host_memory;
}
});
}
template <typename T>
double SubmitZeroCopyKernel(queue& q, T* in, T* out, size_t size) {
// start the timer
auto start = high_resolution_clock::now();
// start the kernels
auto worker_event = SubmitWorker<T>(q, size);
auto producer_event = SubmitProducer<T>(q, in, size);
auto consumer_event = SubmitConsumer<T>(q, out, size);
// wait for all the kernels to finish
q.wait();
// stop the timer
auto end = high_resolution_clock::now();
duration<double, std::milli> diff = end - start;
return diff.count();
}
#endif /* __ZERO_COPY_KERNEL_HPP__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/loop_carried_dependency/src/loop_carried_dependency.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <string>
#include "exception_handler.hpp"
using namespace sycl;
using namespace std;
// Forward declare the kernel names in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class UnOptKernel;
class OptKernel;
event Unoptimized(queue &q, const vector<double> &vec_a,
const vector<double> &vec_b, double &result, size_t N) {
buffer b_a(vec_a);
buffer b_b(vec_b);
buffer b_result(&result, range(1));
auto e = q.submit([&](handler &h) {
accessor a(b_a, h, read_only);
accessor b(b_b, h, read_only);
accessor result(b_result, h, write_only, no_init);
h.single_task<UnOptKernel>([=]() {
double sum = 0;
for (size_t i = 0; i < N; i++) {
for (size_t j = 0; j < N; j++) {
sum += a[i * N + j];
}
sum += b[i];
}
result[0] = sum;
});
});
return e;
}
event Optimized(queue &q, const vector<double> &vec_a,
const vector<double> &vec_b, double &result, size_t N) {
buffer b_a(vec_a);
buffer b_b(vec_b);
buffer b_result(&result, range(1));
auto e = q.submit([&](handler &h) {
accessor a(b_a, h, read_only);
accessor b(b_b, h, read_only);
accessor result(b_result, h, write_only, no_init);
h.single_task<OptKernel>([=]() [[intel::kernel_args_restrict]] {
double sum = 0;
for (size_t i = 0; i < N; i++) {
// Step 1: Definition
double sum_2 = 0;
// Step 2: Accumulation of array A values for one outer loop iteration
for (size_t j = 0; j < N; j++) {
sum_2 += a[i * N + j];
}
// Step 3: Addition of array B value for an outer loop iteration
sum += sum_2;
sum += b[i];
}
result[0] = sum;
});
});
return e;
}
void PrintTime(const event &e, queue &q, const char *kind) {
double start_k = e.get_profiling_info<info::event_profiling::command_start>();
double end_k = e.get_profiling_info<info::event_profiling::command_end>();
cout << "Run: " << kind << ":\n";
#if defined(FPGA_SIMULATOR)
double kernel_time = (double)(end_k - start_k) * 1e-9;
cout << "kernel time : " << kernel_time << " s\n";
#else
double kernel_time = (double)(end_k - start_k) * 1e-6;
cout << "kernel time : " << kernel_time << " ms\n";
#endif
}
int main(int argc, char *argv[]) {
#if defined(FPGA_SIMULATOR)
constexpr size_t kMaxN = 400;
#else
constexpr size_t kMaxN = 16000;
#endif
size_t n = kMaxN;
if (argc > 1) {
string option(argv[1]);
if (option == "-h" || option == "--help") {
cout << "Usage: <executable> <data size>\n\nFAILED\n";
return 1;
} else {
n = stoi(option);
}
}
// Cap the value of n.
n = std::max(std::min((size_t)n, (size_t)kMaxN), (size_t)100);
cout << "Number of elements: " << n << '\n';
vector<double> vec_a(n * n);
vector<double> vec_b(n);
double answer = 0;
// initialize data and compute golden result
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < n; j++) {
vec_a[i * n + j] = i + j;
answer += i + j;
}
vec_b[i] = i;
answer += i;
}
// Initialize queue with device selector and enabling profiling
// Create queue, get platform and device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
#ifndef FPGA_HARDWARE
cout << "\nEmulator and simulator outputs do not demonstrate true "
"hardware performance. The design may need to run on actual "
"hardware to observe the performance benefit of the optimization "
"exemplified in this tutorial.\n\n";
#endif
double unopt_sum = -1, opt_sum = -1;
try {
// Create a profiling queue
queue q(selector, fpga_tools::exception_handler,
property::queue::enable_profiling{});
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
// compute result on device
PrintTime(Unoptimized(q, vec_a, vec_b, unopt_sum, n), q, "Unoptimized");
PrintTime(Optimized(q, vec_a, vec_b, opt_sum, n), q, "Optimized");
// q's destructor invokes q's exception handler on any device exceptions.
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
// Check the results
bool failed = false;
if (unopt_sum != answer) {
cout << "Unoptimized: expected: " << answer << ", result: " << unopt_sum
<< '\n';
failed = true;
}
if (opt_sum != answer) {
cout << "Optimized: expected: " << answer << ", result: " << opt_sum
<< '\n';
failed = true;
}
if (failed) {
cout << "FAILED\n";
return 1;
}
cout << "PASSED\n";
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/shannonization/src/IntersectionKernel.hpp | #ifndef __INTERSECTIONKERNEL_HPP__
#define __INTERSECTIONKERNEL_HPP__
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
// the kernel class names
// templated on the version of the kernel
// Best practice: forward declare the kernel names in the global scope
// to reduce compiler name mangling in the optimization reports.
template<int Version> class ProducerA;
template<int Version> class ProducerB;
template<int Version> class Worker;
// the pipe class names
// templated on the version of the kernel
template<int Version> class ProduceAPipeClass;
template<int Version> class ProduceBPipeClass;
//
// The base IntersectionKernel struct definition
// The idea of the IntersectionKernel struct is to define
// a templated function that we will (partially) override for different
// versions of the kernel. This is called "partial template specialization".
// It is not possible to do partial template specialization on functions
// (the reason for why are outside the scope of this tutorial).
// However, one can do partial template specialization on classes and structs.
// Therefore, the IntersectionKernel struct will allow use to have a templated
// kernel that we will partially template on the 'Version' parameter to define
// different versions of the kernel.
//
template <int Version, int II, class APipe, class BPipe>
struct IntersectionKernel {
int operator()(int a_size, int b_size) const;
};
//
// Version 0
// This is the baseline version of the algorithm with no optimizations
// Note that we have partially override this struct with Version=0
//
template <int II, class APipe, class BPipe>
struct IntersectionKernel<0, II, APipe, BPipe> {
int operator()(int a_size, int b_size) const {
// initialize variables
unsigned int a = APipe::read();
unsigned int b = BPipe::read();
int a_count = 1;
int b_count = 1;
int n = 0;
[[intel::initiation_interval(II)]]
while (a_count < a_size || b_count < b_size) {
// increment the intersection counter if the table elements match
if (a == b) {
n++;
}
///////////////////////////////////////////////////////////////////////
// To achieve an II of 1, all of the code in this block must occur in
// in the same clock cycle. Why? The path taken by the NEXT iteration
// of this loop depends on the result of this computation for the
// CURRENT iteration of this loop. That is, the critical path is
// two COMPAREs (a < b, a_count < a_size), an AND, an ADD (a_count++)
// and a pipe read (::read()). This will results in a long critical
// path and therefore either an increased II or decreased Fmax.
if (a < b && a_count < a_size) {
a = APipe::read();
a_count++;
} else if (b_count < b_size) {
b = BPipe::read();
b_count++;
}
///////////////////////////////////////////////////////////////////////
};
// check the last elements
if (a == b) {
n++;
}
return n;
}
};
//
// Version 1
// Note that we have partially override this struct with Version=1
//
template <int II, class APipe, class BPipe>
struct IntersectionKernel<1, II, APipe, BPipe> {
int operator()(int a_size, int b_size) const {
// initialize variables
unsigned int a = APipe::read();
unsigned int b = BPipe::read();
int a_count = 1;
int b_count = 1;
int a_count_next = 2;
int b_count_next = 2;
int n = 0;
[[intel::initiation_interval(II)]]
while (a_count < a_size || b_count < b_size) {
// increment the intersection counter if the table elements match
if (a == b) {
n++;
}
///////////////////////////////////////////////////////////////////////
// In this version of the kernel, we remove the ADD from the critical
// path by precomputing it. a_count_next stores the value for
// next loop iteration that wants to increment a_count (and likewise
// for (b_count_next and b_count). This removes the ADD from the
// critical path and replaces it by a read to the register holding
// a_count_next. This results in a reduction to the critical path and
// improved Fmax/II.
if (a < b && a_count < a_size) {
a = APipe::read();
a_count = a_count_next;
a_count_next++;
} else if (b_count < b_size) {
b = BPipe::read();
b_count = b_count_next;
b_count_next++;
}
///////////////////////////////////////////////////////////////////////
};
// check the last elements
if (a == b) {
n++;
}
return n;
}
};
//
// Version 2
// Note that we have partially override this struct with Version=2
//
template <int II, class APipe, class BPipe>
struct IntersectionKernel<2, II, APipe, BPipe> {
int operator()(int a_size, int b_size) const {
// initialize variables
unsigned int a = APipe::read();
unsigned int b = BPipe::read();
int a_count = 1;
int b_count = 1;
int n = 0;
bool a_count_inrange = a_count < a_size;
bool b_count_inrange = b_count < b_size;
bool a_count_next_inrange = a_count < (a_size - 1);
bool b_count_next_inrange = b_count < (b_size - 1);
bool keep_going = true;
[[intel::initiation_interval(II)]]
while (keep_going) {
// increment the intersection counter if the table elements match
if (a == b) {
n++;
}
///////////////////////////////////////////////////////////////////////
// In this version of the kernel, we do the same optimization as
// Version 1 for a_count by adding the variable a_count_next_next.
// This precomputes the a_count values for the next TWO iterations
// of the loop that read from APipe. We also precompute the check
// for whether a_count and a_count_next are still in range using
// the a_count_inrange and a_count_next_inrange variables.
if (a < b && a_count_inrange) {
a = APipe::read();
// first update the variables that determine whether
// the current counters are in range of the table
a_count_inrange = a_count_next_inrange;
a_count_next_inrange = (a_count < (a_size - 2));
a_count++;
} else if (b_count_inrange) {
b = BPipe::read();
// first update the variables that determine whether
// the current counters are in range of the table
b_count_inrange = b_count_next_inrange;
b_count_next_inrange = (b_count < (b_size - 2));
b_count++;
}
///////////////////////////////////////////////////////////////////////
keep_going = a_count_inrange || b_count_inrange;
};
// check the last elements
if (a == b) {
n++;
}
return n;
}
};
//
// Version 3
// Note that we have partially override this struct with Version=3
// Version 3 is the same as version 2 but uses non-blocking pipes. This
// requires some minor code modifications
//
template <int II, class APipe, class BPipe>
struct IntersectionKernel<3, II, APipe, BPipe> {
int operator()(int a_size, int b_size) const {
// initialize variables
unsigned int a;
unsigned int b;
int a_count = 1;
int b_count = 1;
int n = 0;
bool a_count_inrange = a_count < a_size;
bool b_count_inrange = b_count < b_size;
bool a_count_next_inrange = a_count < (a_size - 1);
bool b_count_next_inrange = b_count < (b_size - 1);
bool keep_going = true;
bool a_valid = false;
bool b_valid = false;
const int total_compares = (a_size < b_size) ? b_size : a_size;
int num_compares = 0;
int num_compares_next = 1;
int num_compares_next_next = 2;
bool num_compares_in_range = num_compares < total_compares;
bool num_compares_next_in_range = num_compares_next < total_compares;
[[intel::initiation_interval(II)]]
while (keep_going) {
if (!a_valid || !b_valid) {
if (!a_valid) {
a = APipe::read(a_valid);
} else {
b = BPipe::read(b_valid);
}
} else {
if (a == b) {
n++;
num_compares_in_range = num_compares_next_in_range;
num_compares_next_in_range = num_compares_next_next < total_compares;
num_compares = num_compares_next;
num_compares_next = num_compares_next_next;
num_compares_next_next++;
}
////////////////////////////////////////////////////////////////////////
// In this version of the kernel, we do the same optimization as
// Version 1 for a_count by adding the variable a_count_next_next.
// This precomputes the a_count values for the next TWO iterations
// of the loop that read from APipe. We also precompute the check
// for whether a_count and a_count_next are still in range using
// the a_count_inrange and a_count_next_inrange variables.
if (a < b && a_count_inrange) {
a = APipe::read(a_valid);
// first update the variables that determine whether
// the current counters are in range of the table
a_count_inrange = a_count_next_inrange;
a_count_next_inrange = (a_count < (a_size - 2));
a_count++;
} else if (b_count_inrange) {
b = BPipe::read(b_valid);
// first update the variables that determine whether
// the current counters are in range of the table
b_count_inrange = b_count_next_inrange;
b_count_next_inrange = (b_count < (b_size - 2));
b_count++;
}
////////////////////////////////////////////////////////////////////////
}
keep_going = num_compares_in_range;
}
return n;
}
};
#endif /* __INTERSECTIONKERNEL_HPP__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/shannonization/src/shannonization.cpp | #include <algorithm>
#include <numeric>
#include <string>
#include <type_traits>
#include <vector>
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "IntersectionKernel.hpp"
#include "exception_handler.hpp"
using namespace sycl;
//
// print the usage
//
void Usage() {
std::cout
<< "USAGE: ./intersection [--A=<size of list A>] [--B=<size of list B>]"
<< "[--iters=<number of times to run the kernel>] [-h --help]\n";
}
//
// helper to check if string 'str' starts with 'prefix'
//
bool StrStartsWith(std::string& str, std::string prefix) {
return str.find(prefix) == 0;
}
//
// Helper to count instances of an element 'x' in a sorted vector 'v'.
// Since the vector is sorted, this algorithm has O(logn) complexity,
// rather than the naive O(n) complexity.
//
unsigned int CountSorted(std::vector<unsigned int>& v, int x) {
// find first occurrence of 'x' in 'v'
auto low = std::lower_bound(v.begin(), v.end(), x);
// check if element was present
if (low == v.end() || *low != x) {
return 0;
}
// find last occurrence of x in array
auto high = std::upper_bound(low, v.end(), x);
// return count
return high - low;
}
//
// Submit the three kernels that make up the whole design
//
template <int Version, int II>
event SubmitKernels(queue& q, std::vector<unsigned int>& a,
std::vector<unsigned int>& b, int& n) {
// static asserts
static_assert(Version >= 0 && Version <= 3, "Invalid kernel version");
static_assert(II > 0, "II target must be positive and non-zero");
// the pipes for this Version of the design
using ProduceAPipe = pipe<ProduceAPipeClass<Version>, unsigned int>;
using ProduceBPipe = pipe<ProduceBPipeClass<Version>, unsigned int>;
// input sizes
const int a_size = a.size();
const int b_size = b.size();
// setup the input buffers
buffer a_buf(a);
buffer b_buf(b);
// setup the output buffer
buffer<int,1> n_buf(&n, 1);
// submit the kernel that produces table A
q.submit([&](handler& h) {
accessor a_accessor(a_buf, h, read_only);
h.single_task<ProducerA<Version>>([=]() [[intel::kernel_args_restrict]] {
for (int i = 0; i < a_size; i++) {
ProduceAPipe::write(a_accessor[i]);
}
});
});
// submit the kernel that produces table B
q.submit([&](handler& h) {
accessor b_accessor(b_buf, h, read_only);
h.single_task<ProducerB<Version>>([=]() [[intel::kernel_args_restrict]] {
for (int i = 0; i < b_size; i++) {
ProduceBPipe::write(b_accessor[i]);
}
});
});
// submit the kernel that performs the intersection
event e = q.submit([&](handler& h) {
// output accessor
accessor n_accessor(n_buf, h, write_only, no_init);
h.single_task<Worker<Version>>([=]() [[intel::kernel_args_restrict]] {
// The 'Version' template parameter will choose between the different
// versions of the kernel defined in IntersectionKernel.hpp.
// The operator() of the IntersectionKernel object will return the
// size of the intersection of A and B.
IntersectionKernel<Version, II, ProduceAPipe, ProduceBPipe> K;
n_accessor[0] = K(a_size, b_size);
});
});
return e;
}
//
// This function performs the intersection by submitting the
// different kernels. This method also validates the output
// of the kernels and prints performance information
//
template <int Version, int II>
bool Intersection(queue& q, std::vector<unsigned int>& a,
std::vector<unsigned int>& b, int golden_n) {
// For emulation, just do a single iteration.
// For hardware, perform multiple iterations for a more
// accurate throughput measurement
#if defined(FPGA_EMULATOR) || defined(FPGA_SIMULATOR)
int iterations = 1;
#else
int iterations = 5;
#endif
std::cout << "Running " << iterations
<< ((iterations == 1) ? " iteration" : " iterations")
<< " of kernel " << Version
<< " with |A|=" << a.size()
<< " and |B|=" << b.size() << "\n";
bool success = true;
std::vector<double> kernel_latency(iterations);
// perform multiple iterations of the kernel to get a more accurate
// throughput measurement
for (size_t i = 0; i < iterations && success; i++) {
// run kernel
int n = 0;
event e = SubmitKernels<Version,II>(q, a, b, n);
// check output
if (golden_n != n) {
success = false;
std::cerr << "ERROR: Kernel version " << Version << " output is incorrect"
<< " (Expected=" << golden_n << ", Result=" << n << ")\n";
}
// get profiling info
auto start = e.get_profiling_info<info::event_profiling::command_start>();
auto end = e.get_profiling_info<info::event_profiling::command_end>();
kernel_latency[i] = (end - start) / 1e9;
}
// If all the iterations were successful, print the throughput results.
// The FPGA emulator does not accurately represent the hardware performance
// so we don't print performance results when running with the emulator
if (success) {
#if !defined(FPGA_EMULATOR) && !defined(FPGA_SIMULATOR)
// Compute the average throughput across all iterations.
// We use the first iteration as a 'warmup' for the FPGA,
// so we ignore its results.
double avg_kernel_latency =
std::accumulate(kernel_latency.begin() + 1, kernel_latency.end(), 0.0) /
(double)(iterations - 1);
double input_size_megabytes =
((a.size() + b.size()) * sizeof(unsigned int)) / (1024.0 * 1024.0);
const double avg_throughput = input_size_megabytes / avg_kernel_latency;
std::cout << "Kernel " << Version
<< " average throughput: " << avg_throughput << " MB/s\n";
#endif
}
return success;
}
int main(int argc, char** argv) {
// parse the command line arguments
#if defined(FPGA_EMULATOR) || defined(FPGA_SIMULATOR)
unsigned int a_size = 128;
unsigned int b_size = 256;
#else
unsigned int a_size = 16384;
unsigned int b_size = 32768;
#endif
bool need_help = false;
for (int i = 1; i < argc; i++) {
std::string arg(argv[i]);
if (arg == "--help" || arg == "-h") {
need_help = true;
} else {
std::string str_after_equals = arg.substr(arg.find("=") + 1);
if (StrStartsWith(arg, "--A=")) {
a_size = std::stoi(str_after_equals);
} else if (StrStartsWith(arg, "--B=")) {
b_size = std::stoi(str_after_equals);
} else {
std::cout << "WARNING: ignoring unknown argument '" << arg << "'\n";
}
}
}
// ensure the arrays have more than 3 elements
if (a_size <= 3) {
std::cout << "WARNING: array A must have more than 3 "
"elements, increasing its size\n";
a_size = 4;
}
if (b_size <= 3) {
std::cout << "WARNING: array A must have more than 3"
"elements, increasing its size\n";
b_size = 4;
}
// print help if needed or asked
if (need_help) {
Usage();
return 0;
}
std::cout << "Generating input data\n";
// seed the random number generator
srand(777);
// initialize input data
std::vector<unsigned int> a(a_size), b(b_size);
std::iota(a.begin(), a.end(), 0);
std::generate(b.begin(), b.end(), [=] { return rand() % a_size; });
std::sort(b.begin(), b.end());
std::cout << "Computing golden result\n";
// compute the golden result
int golden_n = 0;
for (int i = 0; i < a_size; i++) {
golden_n += CountSorted(b, a[i]);
}
try {
// queue properties to enable profiling
auto props = property_list{property::queue::enable_profiling()};
// the device selector
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
// create the device queue
queue q(selector, props);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
bool success = true;
// Instantiate multiple versions of the kernel
// The II achieved by the compiler can differ between FPGA architectures
//
// On Arria® 10, we are able to achieve an II of 1 for all versions of the
// kernel.
// Version 2 of the kernel can achieve the highest Fmax with
// an II of 1 (and therefore has the highest throughput).
// Since this tutorial compiles to a single FPGA image, this is not
// reflected in the final design (that is, version 1 bottlenecks the Fmax
// of the entire design, which contains versions 0, 1 and 2).
// However, the difference between versions 1 and 2
// can be seen in the "Block Scheduled Fmax" columns in the
// "Loop Analysis" tab of the HTML reports.
//
// On Stratix® 10 and Agilex® 7, the same discussion applies, but version 0
// can only achieve an II of 3 while versions 1 and 2 can only achieve
// an II of 2. On Stratix® 10 and Agilex® 7, we can achieve an II of 1 if we use
// non-blocking pipe reads in the IntersectionKernel, which is shown in
// version 3 of the kernel.
//
#if defined(A10)
success &= Intersection<0,1>(q, a, b, golden_n);
success &= Intersection<1,1>(q, a, b, golden_n);
success &= Intersection<2,1>(q, a, b, golden_n);
success &= Intersection<3,1>(q, a, b, golden_n);
#elif defined(S10)
success &= Intersection<0,3>(q, a, b, golden_n);
success &= Intersection<1,2>(q, a, b, golden_n);
success &= Intersection<2,2>(q, a, b, golden_n);
success &= Intersection<3,1>(q, a, b, golden_n);
#elif defined(Agilex7)
success &= Intersection<0,3>(q, a, b, golden_n);
success &= Intersection<1,2>(q, a, b, golden_n);
success &= Intersection<2,2>(q, a, b, golden_n);
success &= Intersection<3,1>(q, a, b, golden_n);
#else
success &= Intersection<0,3>(q, a, b, golden_n);
success &= Intersection<1,3>(q, a, b, golden_n);
success &= Intersection<2,3>(q, a, b, golden_n);
success &= Intersection<3,3>(q, a, b, golden_n);
#endif
if (success) {
std::cout << "PASSED\n";
} else {
std::cout << "FAILED\n";
}
} catch (exception const& e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/triangular_loop/src/triangular_loop.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <chrono>
#include "exception_handler.hpp"
using namespace sycl;
// Seed for randomizing data inputs
constexpr int kInitSeed = 42;
// This tutorial runs twice to show the impact with
// and without the optimization.
constexpr int kNumRuns = 2;
// number of nanoseconds in a second
constexpr double kNs = 1000000000.0;
// Number of inputs. Don't set this too large, otherwise
// computation of the reference solution will take a long time on
// the host (the time is proportional to kSize^2)
#if defined(FPGA_SIMULATOR)
constexpr int kSize = 256;
#else
constexpr int kSize = 8 * 1024;
#endif
// >=1. Minimum number of iterations of the inner loop that must be
// executed in the optimized implementation. Set this approximately
// equal to the ii of inner loop in the unoptimized implementation.
constexpr int kM = 50;
// do not use with unary operators, e.g., kMin(x++, y++)
constexpr int Min(int X, int Y) { return (((X) < (Y)) ? (X) : (Y)); };
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class Task;
// This method represents the operation you perform on the loop-carried variable
// in the triangular loop (i.e. a dot product or something that may take many
// cycles to complete).
int SomethingComplicated(int x) { return (int)sycl::sqrt((float)x); }
// This kernel function implements two data paths: with and without the
// optimization. 'optimize' specifies which path to take.
void TriangularLoop(sycl::queue&q, buffer<uint32_t>& input_buf,
buffer<uint32_t>& output_buf, uint32_t n, event& e,
bool optimize) {
// Enqueue kernel
e = q.submit([&](handler& h) {
// Get accessors to the SYCL buffers
accessor input(input_buf, h, read_only);
accessor output(output_buf, h, write_only, no_init);
h.single_task<Task>([=]() [[intel::kernel_args_restrict]] {
// See README for description of the loop_bound calculation.
const int real_iterations = (n * (n + 1) / 2 - 1);
const int extra_dummy_iterations = (kM - 2) * (kM - 1) / 2;
const int loop_bound = real_iterations + extra_dummy_iterations;
// Local memory for the buffer to be operated on
uint32_t local_buf[kSize];
// Read the input_buf from global mem and load it into the local mem
for (uint32_t i = 0; i < kSize; i++) {
local_buf[i] = input[i];
}
// Perform the triangular loop computation
if (!optimize) { // Unoptimized loop.
for (int x = 0; x < n; x++) {
for (int y = x + 1; y < n; y++) {
local_buf[y] = local_buf[y] + SomethingComplicated(local_buf[x]);
}
}
} else { // Optimized loop.
// Indices to track the execution inside the single, merged loop.
int x = 0, y = 1;
// Specify that the minimum dependence-distance of loop-carried
// variables is kM iterations. We ensure this is true by modifying the y
// index such that a minimum of kM iterations are always executed.
[[intel::ivdep(kM)]] for (int i = 0; i < loop_bound; i++) {
// Determine if this iteration is a dummy iteration or a real
// iteration in which the computation should be performed.
bool compute = y > x;
// Perform the computation if needed.
if (compute) {
local_buf[y] = local_buf[y] + SomethingComplicated(local_buf[x]);
}
// Figure out the next value for the indices.
y++;
// If we've hit the end, set y such that a minimum of kM
// iterations are exected.
if (y == n) {
x++;
y = Min(n - kM, x + 1);
}
}
}
// Write the output to global mem
for (uint32_t i = 0; i < kSize; i++) {
output[i] = local_buf[i];
}
});
});
}
int main() {
// Host and kernel profiling
event e;
unsigned long t1_kernel, t2_kernel;
double time_kernel;
// Create queue, get platform and device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
try {
auto prop_list =
property_list{property::queue::enable_profiling()};
sycl::queue q(selector, fpga_tools::exception_handler, prop_list);
platform platform = q.get_context().get_platform();
device device = q.get_device();
std::cout << "Platform name: "
<< platform.get_info<info::platform::name>().c_str() << "\n";
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
// Create input and output buffers
auto input_buf = buffer<uint32_t>(range<1>(kSize));
auto output_buf = buffer<uint32_t>(range<1>(kSize));
srand(kInitSeed);
// Compute the reference solution
uint32_t gold[kSize];
{
// Get host-side accessors to the SYCL buffers.
host_accessor input_host(input_buf, write_only);
// Initialize random input
for (int i = 0; i < kSize; ++i) {
input_host[i] = rand() % 256;
}
for (int i = 0; i < kSize; ++i) {
gold[i] = input_host[i];
}
}
// Host accessor now out-of-scope and is destructed. This is required in
// order to unblock the kernel's subsequent accessor to the same buffer.
for (int x = 0; x < kSize; x++) {
for (int y = x + 1; y < kSize; y++) {
gold[y] += SomethingComplicated(gold[x]);
}
}
std::cout << "Length of input array: " << kSize << "\n\n";
for (int i = 0; i < kNumRuns; i++) {
switch (i) {
case 0: {
std::cout
<< "Beginning run without triangular loop optimization.\n\n";
TriangularLoop(q, input_buf, output_buf, kSize, e, false);
break;
}
case 1: {
std::cout << "Beginning run with triangular loop optimization.\n\n";
TriangularLoop(q, input_buf, output_buf, kSize, e, true);
break;
}
default: {
TriangularLoop(q, input_buf, output_buf, kSize, e, false);
}
}
// Wait for kernels to finish
q.wait();
t1_kernel = e.get_profiling_info<info::event_profiling::command_start>();
t2_kernel = e.get_profiling_info<info::event_profiling::command_end>();
time_kernel = (t2_kernel - t1_kernel) / kNs;
// Get accessor to output buffer. Accessing the buffer at this point in
// the code will block on kernel completion.
host_accessor output_host(output_buf, read_only);
// Verify output and print pass/fail
bool passed = true;
int num_errors = 0;
for (int b = 0; b < kSize; b++) {
if (num_errors < 10 && output_host[b] != gold[b]) {
passed = false;
std::cout << " Mismatch at element " << b << ". expected " << gold[b]
<< ")\n";
num_errors++;
}
}
if (passed) {
std::cout << "Verification PASSED\n\n";
// Report host execution time and throughput
std::cout.setf(std::ios::fixed);
std::cout << "Execution time: " << time_kernel << " seconds\n";
int num_iterations =
kSize * (kSize + 1) / 2 -
1; // One piece of data is processed on each iteration. This
// formula is taken from the loop_bound calculation.
#if defined(FPGA_SIMULATOR)
double N_KB = (sizeof(uint32_t) * num_iterations) /
1024; // Amount of data processed, in kB
std::cout << "Throughput " << (i == 0 ? "without" : "with")
<< " optimization: " << N_KB / time_kernel << " KB/s\n\n";
#else
double N_MB = (sizeof(uint32_t) * num_iterations) /
(1024 * 1024); // Amount of data processed, in mB
std::cout << "Throughput " << (i == 0 ? "without" : "with")
<< " optimization: " << N_MB / time_kernel << " MB/s\n\n";
#endif
} else {
std::cout << "Verification FAILED\n";
return 1;
}
}
} catch (sycl::exception const& e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/autorun/src/autorun.hpp | #ifndef __AUTORUN_HPP__
#define __AUTORUN_HPP__
#include <sycl/sycl.hpp>
#include <type_traits>
/*
This header defines the Autorun kernel utility. This utility is used to
launch kernels that are submitted before main begins. It is typically used
to launch kernels that run forever.
Two classes are defined in this header file: Autorun and AutorunForever.
Autorun creates an autorun kernel that is NOT implicitly wrapped in an infinite
loop.
AutorunForever creates a kernel and wraps it in a while(1) loop.
Autorun creates the kernel and does not wrap it in a while(1) loop.
Usually when using Autorun the user will have the while(1) loop explicitly in
their code.
The following describes the common template and constructor arguments for both
the Autorun and AutorunForever.
Template Args:
KernelID (optional): the name of the autorun kernel.
DeviceSelector: The type of the device selector.
KernelFunctor: the kernel functor type.
Constructor Arguments:
device_selector: the SYCL device selector
kernel: the user-defined kernel functor.
This defines the logic of the autorun kernel.
*/
namespace fpga_tools {
namespace detail {
// Autorun implementation
template <bool run_forever, typename KernelID>
struct Autorun_impl {
// Constructor with a kernel name
template <typename DeviceSelector, typename KernelFunctor>
Autorun_impl(DeviceSelector device_selector, KernelFunctor kernel) {
// static asserts to ensure KernelFunctor is callable
static_assert(std::is_invocable_r_v<void, KernelFunctor>,
"KernelFunctor must be callable with no arguments");
// create the device queue
sycl::queue q{device_selector};
// submit the user's kernel
if constexpr (run_forever) {
if constexpr (std::is_same_v<KernelID, void>) {
// AutorunForever, kernel name not given
q.single_task([=] {
while (1) {
kernel();
}
});
} else {
// AutorunForever, kernel name given
q.single_task<KernelID>([=] {
while (1) {
kernel();
}
});
}
} else {
// run the kernel as-is, if the user wanted it to run forever they
// will write their own explicit while-loop
if constexpr (std::is_same_v<KernelID, void>) {
// Autorun, kernel name not given
q.single_task(kernel);
} else {
// Autorun, kernel name given
q.single_task<KernelID>(kernel);
}
}
}
};
} // namespace detail
// Autorun
template <typename KernelID = void>
using Autorun = detail::Autorun_impl<false, KernelID>;
// AutorunForever
template <typename KernelID = void>
using AutorunForever = detail::Autorun_impl<true, KernelID>;
} // namespace fpga_tools
#endif /* __AUTORUN_HPP__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/autorun/src/autorun.cpp | #include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "exception_handler.hpp"
#include "autorun.hpp"
#include <algorithm>
#include <iostream>
#include <vector>
using namespace sycl;
// choose the device selector based on emulation or actual hardware
// we make this a global variable so it can be used by the autorun kernels
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
// declare the kernel names globally to reduce name mangling
class ARProducerID;
class ARKernelID;
class ARConsumerID;
class ARForeverProducerID;
class ARForeverKernelID;
class ARForeverConsumerID;
// declare the pipe names globally to reduce name mangling
class ARProducePipeID;
class ARConsumePipeID;
class ARForeverProducePipeID;
class ARForeverConsumePipeID;
// pipes
using ARProducePipe = ext::intel::pipe<ARProducePipeID, int>;
using ARConsumePipe = ext::intel::pipe<ARConsumePipeID, int>;
using ARForeverProducePipe = ext::intel::pipe<ARForeverProducePipeID, int>;
using ARForeverConsumePipe = ext::intel::pipe<ARForeverConsumePipeID, int>;
////////////////////////////////////////////////////////////////////////////////
// Autorun user kernel and global variable
struct MyAutorun {
void operator()() const {
// notice that in this version, we explicitly add the while(1)-loop
while (1) {
auto d = ARProducePipe::read();
ARConsumePipe::write(d);
}
}
};
// declaring a global instance of this class causes the constructor to be called
// before main() starts, and the constructor launches the kernel.
fpga_tools::Autorun<ARKernelID> ar_kernel{selector, MyAutorun{}};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// AutorunForever user kernel and global variable
// The AutorunForever kernel implicitly wraps the code below in a while(1) loop
struct MyAutorunForever {
void operator()() const {
// this code is implicitly placed in a while(1)-loop by the
// fpga_tools::AutorunForever class
auto d = ARForeverProducePipe::read();
ARForeverConsumePipe::write(d);
}
};
// declaring a global instance of this class causes the constructor to be called
// before main() starts, and the constructor launches the kernel.
fpga_tools::AutorunForever<ARForeverKernelID> ar_forever_kernel{
selector, MyAutorunForever{}};
////////////////////////////////////////////////////////////////////////////////
//
// Submit a kernel to read data from global memory and write to a pipe
//
template <typename KernelID, typename Pipe>
event SubmitProducerKernel(queue& q, buffer<int, 1>& in_buf) {
return q.submit([&](handler& h) {
accessor in(in_buf, h, read_only);
int size = in_buf.size();
h.single_task<KernelID>([=] {
for (int i = 0; i < size; i++) {
Pipe::write(in[i]);
}
});
});
}
//
// Submit a kernel to read data from a pipe and write to global memory
//
template <typename KernelID, typename Pipe>
event SubmitConsumerKernel(queue& q, buffer<int, 1>& out_buf) {
return q.submit([&](handler& h) {
accessor out(out_buf, h, write_only, no_init);
int size = out_buf.size();
h.single_task<KernelID>([=] {
for (int i = 0; i < size; i++) {
out[i] = Pipe::read();
}
});
});
}
int main() {
int count = 5000;
bool passed = true;
std::vector<int> in_data(count), out_data(count);
// populate random input data, clear output data
std::generate(in_data.begin(), in_data.end(), [] { return rand() % 100; });
std::fill(out_data.begin(), out_data.end(), -1);
try {
// create the queue
queue q(selector, fpga_tools::exception_handler);
sycl::device device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
// stream data through the Autorun kernel
std::cout << "Running the Autorun kernel test\n";
{
// Create input and output buffers
buffer in_buf(in_data);
buffer out_buf(out_data);
SubmitProducerKernel<ARProducerID, ARProducePipe>(q, in_buf);
SubmitConsumerKernel<ARConsumerID, ARConsumePipe>(q, out_buf);
}
// validate the results
// operator== for a vector checks sizes, then checks per-element
passed &= (out_data == in_data);
// stream data through the AutorunForever kernel
std::cout << "Running the AutorunForever kernel test\n";
{
// Create input and output buffers
buffer in_buf(in_data);
buffer out_buf(out_data);
SubmitProducerKernel<ARForeverProducerID, ARForeverProducePipe>(q,
in_buf);
SubmitConsumerKernel<ARForeverConsumerID, ARForeverConsumePipe>(q,
out_buf);
}
// validate the results
// operator== for a vector checks sizes, then checks per-element
passed &= (out_data == in_data);
} catch (sycl::exception const& e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
if (passed) {
std::cout << "PASSED\n";
return 0;
} else {
std::cout << "FAILED\n";
return 1;
}
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/io_streaming/src/HostSideChannel.hpp | #ifndef __HOSTSIDECHANNEL_HPP__
#define __HOSTSIDECHANNEL_HPP__
#include <iostream>
#include <type_traits>
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "FakeIOPipes.hpp"
using namespace sycl;
//
// This class provides a convenient, but low-bandwidth and relatively high
// latency, side channel to send data from the host to the device. It exposes
// a read() interface to the DEVICE code that the user can treat just like a
// SYCL pipe. It also exposes a write interface to the HOST that allows the
// user to easily write data from host to the device
//
template <typename Id, typename T, bool use_host_alloc, size_t min_capacity=0>
class HostToDeviceSideChannel {
protected:
using MyProducer = Producer<Id, T, use_host_alloc, min_capacity>;
static inline queue* q_{nullptr};
public:
// disable copy constructor and operator=
HostToDeviceSideChannel()=delete;
HostToDeviceSideChannel(const HostToDeviceSideChannel &)=delete;
HostToDeviceSideChannel& operator=(HostToDeviceSideChannel const &)=delete;
static void Init(queue &q) {
q_ = &q;
MyProducer::Init(q, 1);
};
static void Destroy(queue &q) {
q_ = nullptr;
MyProducer::Destroy(q);
};
static T read() {
// DEVICE CODE
return MyProducer::Pipe::read();
}
static T read(bool &success_code) {
// DEVICE CODE
return MyProducer::Pipe::read(success_code);
}
// blocking
static void write(const T &data) {
// HOST CODE
// populate the data
MyProducer::Data()[0] = data;
// start the kernel and wait on it to finish (blocking)
event dma, kernel;
std::tie(dma, kernel) = MyProducer::Start(*q_);
dma.wait();
kernel.wait();
}
// non-blocking
// Call .wait() on the returned event to wait for the write to take place
static event write(const T &data, bool &success_code) {
// HOST CODE
// always succeed
success_code = true;
// populate the data
MyProducer::Data()[0] = data;
// start the kernel and return the kernel event
return MyProducer::Start(*q_).second;
}
};
//
// This class provides a convenient, but not highly performing, side channel
// to send data from the device to the host. It exposes a read() interface
// to the HOST code that lets the user get updates from the device.
// It also exposes a write interface to the DEVICE that allows the user to
// easily write data from device to the host.
//
template <typename Id, typename T, bool use_host_alloc, size_t min_capacity=0>
class DeviceToHostSideChannel {
protected:
using MyConsumer = Consumer<Id, T, use_host_alloc, min_capacity>;
static inline queue* q_{nullptr};
public:
// disable copy constructor and operator=
DeviceToHostSideChannel()=delete;
DeviceToHostSideChannel(const DeviceToHostSideChannel &)=delete;
DeviceToHostSideChannel& operator=(DeviceToHostSideChannel const &)=delete;
static void Init(queue &q) {
q_ = &q;
MyConsumer::Init(q, 1);
};
static void Destroy(queue &q) {
q_ = nullptr;
MyConsumer::Destroy(q);
};
// blocking
static T read() {
// HOST CODE
// launch the kernel to read the data from the pipe into memory
// and wait for it to finish (blocking)
event dma, kernel;
std::tie(dma, kernel) = MyConsumer::Start(*q_);
dma.wait();
kernel.wait();
// the kernel has finished, so return the data
return MyConsumer::Data()[0];
}
// non-blocking
// call .wait() on the returned event to wait for the read to take place,
// then access the data using ::Data()[0]
static event read(bool &success_code) {
// start the kernel and return the event
// the user can use ::Data() later to get the data
// return the DMA event, since it happen second
success_code = true;
return MyConsumer::Start(*q_).first;
}
static void write(const T &data) {
// DEVICE CODE
MyConsumer::Pipe::write(data);
}
static void write(const T &data, bool &success_code) {
// DEVICE CODE
MyConsumer::Pipe::write(data, success_code);
}
static T Data() {
return MyConsumer::Data()[0];
}
};
#endif /* __HOSTSIDECHANNEL_HPP__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/io_streaming/src/SideChannelTest.hpp | #ifndef __SIDECHANNELTEST_HPP__
#define __SIDECHANNELTEST_HPP__
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "FakeIOPipes.hpp"
#include "HostSideChannel.hpp"
using namespace sycl;
using namespace std::chrono_literals;
// declare the kernel and pipe ID stucts globally to reduce name mangling
struct SideChannelMainKernel;
struct SideChannelReadIOPipeID { static constexpr unsigned id = 0; };
struct SideChannelWriteIOPipeID { static constexpr unsigned id = 1; };
struct HostToDeviceSideChannelID;
struct DeviceToHostSideChannelID;
struct HostToDeviceTermSideChannelID;
//
// Submit the main processing kernel (or kernels, in general).
// This function is templated on the IO pipes and the side channels.
// It is agnostic to whether the the system is using real or fake IO pipes.
//
// This kernel streams data into and out of IO pipes (IOPipeIn and IOPipeOut,
// respectively). If the value matches the current value of 'match_num', it
// sends the value to the host via the HostToDeviceSideChannel. In the outer
// loop, it reads configuration data from the host via the
// HostToDeviceSideChannel and HostToDeviceTermSideChannel. The former updates
// 'match_num' and the latter causes this kernel to break from the outer loop
// and terminate.
//
template<class IOPipeIn, class IOPipeOut,
class HostToDeviceSideChannel, class DeviceToHostSideChannel,
class HostToDeviceTermSideChannel>
event SubmitSideChannelKernels(queue& q, int initial_match_num,
size_t frame_size) {
// the maximum number of consecutive input read misses before
// breaking out of the computation loop
// Why would you want to break out of the processing loop? One example
// is if you are expecting asynchronous updates from the host through a
// side channel.
constexpr size_t kTimeoutCounterMax = 1024;
// submit the main processing kernel
return q.single_task<SideChannelMainKernel>([=] {
int match_num = initial_match_num;
size_t timeout_counter;
size_t samples_processed = 0;
bool terminate = false;
while (!terminate) {
// check for an update to the sum_threshold from the host
bool valid_update;
int tmp = HostToDeviceSideChannel::read(valid_update);
if (valid_update) match_num = tmp;
// reset the timeout counter
timeout_counter = 0;
// if we processed a full frame, reset the counter
// this places a maximum on the number of elements we process before
// checking for an update from the host
if (samples_processed == frame_size) samples_processed = 0;
// do the main processing
while ((samples_processed != frame_size) &&
(timeout_counter != kTimeoutCounterMax)) {
// read from the input IO pipe
bool valid_read;
auto val = IOPipeIn::read(valid_read);
if (valid_read) {
// reset the timeout counter since we read a valid piece of data
timeout_counter = 0;
// processed another sample in this frame
samples_processed++;
// check if the value matches
if (val == match_num) {
// value matches, so tell the host about it
DeviceToHostSideChannel::write(val);
}
// propagate the input value to the output
IOPipeOut::write(val);
} else {
// increment the timeout counter since the read was invalid
timeout_counter++;
}
}
// the host uses this side channel to tell the kernel to exit
// Any successful read from this channel means the host wants this
// kernel to end; the actual value read doesn't matter
(void)HostToDeviceTermSideChannel::read(terminate);
}
});
}
//
// This function builds the full system using fake IO pipes.
// It creates, produces, and consumes the fake data and validates the output
//
template<typename T, bool use_usm_host_alloc>
bool RunSideChannelsSystem(queue& q, size_t count) {
//////////////////////////////////////////////////////////////////////////////
// IO pipes
// these are the FAKE IO pipes
using FakeIOPipeInProducer = Producer<SideChannelReadIOPipeID,
T, use_usm_host_alloc>;
using FakeIOPipeOutConsumer = Consumer<SideChannelWriteIOPipeID,
T, use_usm_host_alloc>;
using ReadIOPipe = typename FakeIOPipeInProducer::Pipe;
using WriteIOPipe = typename FakeIOPipeOutConsumer::Pipe;
// initialize the fake IO pipes
FakeIOPipeInProducer::Init(q, count);
FakeIOPipeOutConsumer::Init(q, count);
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// the side channels
using MyHostToDeviceSideChannel =
HostToDeviceSideChannel<HostToDeviceSideChannelID,
int, use_usm_host_alloc, 1>;
using MyHostToDeviceTermSideChannel =
HostToDeviceSideChannel<HostToDeviceTermSideChannelID,
char, use_usm_host_alloc, 1>;
// This side channel is used to sent updates from the device to the host.
// We explicitly set the depth of the FIFO to '8' here. If the host does not
// read from this side channel quick enough it will causes the main processing
// kernel to stall. Therefore, sizing the FIFO is something to consider when
// designing a 'real' system that uses side channels. In this tutorial, the
// frequency of updates from the device is so low that this channel can be
// shallow.
using MyDeviceToHostSideChannel =
DeviceToHostSideChannel<DeviceToHostSideChannelID,
int, use_usm_host_alloc, 8>;
// initialize the side channels
MyHostToDeviceSideChannel::Init(q);
MyHostToDeviceTermSideChannel::Init(q);
MyDeviceToHostSideChannel::Init(q);
//////////////////////////////////////////////////////////////////////////////
// get the pointer to the fake input data
auto i_stream_data = FakeIOPipeInProducer::Data();
// Create some random input data
// The range of the random number is [0, count/4), which means the probability
// of a number ('match_num') matching any number in the list is 1/(count/4)=
// 4/count. Therefore, the average number of matches in the input stream
// is count * (4/count) = 4.
int rand_max = std::max(4, (int)(count / 4));
size_t frame_size = 1024;
std::generate_n(i_stream_data, count, [&] { return rand() % rand_max; } );
// submit the main kernels, once and only once
auto main_kernel =
SubmitSideChannelKernels<ReadIOPipe, WriteIOPipe, MyHostToDeviceSideChannel,
MyDeviceToHostSideChannel,
MyHostToDeviceTermSideChannel>(q, -1, frame_size);
//////////////////////////////////////////////////////////////////////////////
// this lambda will perform a single test to detect all `match_num` elements
auto test_lambda = [&](int match_num) {
// determine expected number of updates for this 'match_num'
size_t expected_updated_count =
std::count(i_stream_data, i_stream_data + count, match_num);
std::vector<int> device_updates;
device_updates.reserve(expected_updated_count);
std::cout << "Checking for values matching '" << match_num << "', "
<< "expecting " << expected_updated_count << " matches\n";
// first, update the kernel with the number to match (blocking)
MyHostToDeviceSideChannel::write(match_num);
// This sleep is an artifact of validating the side channel updates.
// The line of code above writes the new 'match_num' data into
// a pipe to be read by the main processing kernel on the device. However,
// just because the value was written to the pipe doesn't mean that the main
// processing kernel has seen it. For a 'real' streaming design, we
// typically wouldn't care about this race condition since the host->device
// updates are asyncrhonous. However, for the sake of this tutorial, we want
// to be able to validate that the host->device side channel update took
// place. Therefore, we add a sleep here; 10ms should be plenty of time
// for the main processing kernel to read the value from the FIFO where we
// know it resides (since the previous operation is blocking).
std::this_thread::sleep_for(10ms);
// launch the producer and consumer to send the data through the kernel
event producer_dma_event, producer_kernel_event;
event consumer_dma_event, consumer_kernel_event;
std::tie(producer_dma_event, producer_kernel_event) =
FakeIOPipeInProducer::Start(q);
std::tie(consumer_dma_event, consumer_kernel_event) =
FakeIOPipeOutConsumer::Start(q);
// get updates from the device
for (size_t i = 0; i < expected_updated_count; i++) {
auto device_update = MyDeviceToHostSideChannel::read();
device_updates.push_back(device_update);
}
// wait for producer and consumer to finish, including the DMA events
// NOTE: if USM host allocations are used, the dma events are noops.
producer_dma_event.wait();
producer_kernel_event.wait();
consumer_dma_event.wait();
consumer_kernel_event.wait();
bool test_passed = true;
// get the pointer to the fake output data
auto o_stream_data = FakeIOPipeOutConsumer::Data();
// validate the output
for (size_t i = 0; i < count; i++) {
if (o_stream_data[i] != i_stream_data[i]) {
std::cerr << "ERROR: output mismatch at entry " << i << ": "
<< o_stream_data[i] << " != " << i_stream_data[i]
<< " (out != in)\n";
test_passed &= false;
}
}
// validate the updates from the device
for (size_t i = 0; i < expected_updated_count; i++) {
if (device_updates[i] != match_num) {
std::cerr << "ERROR: unexpected update value from device: "
<< device_updates[i] << " != " << match_num
<< " (update != expected)\n";
test_passed &= false;
}
}
return test_passed;
};
//////////////////////////////////////////////////////////////////////////////
// run a couple tests with random 'match_num'
// NOTE: the main processing kernel does NOT exit between these calls
bool passed = true;
passed &= test_lambda(rand() % rand_max);
passed &= test_lambda(rand() % rand_max);
passed &= test_lambda(rand() % rand_max);
// we are done testing now, so send a signal to main processing kernel to exit
MyHostToDeviceTermSideChannel::write(0);
// wait for the main kernel to finish
main_kernel.wait();
// destroy the fake IO pipes and the side channels
FakeIOPipeInProducer::Destroy(q);
FakeIOPipeOutConsumer::Destroy(q);
MyHostToDeviceSideChannel::Destroy(q);
MyHostToDeviceTermSideChannel::Destroy(q);
MyDeviceToHostSideChannel::Destroy(q);
return passed;
}
#endif /* __SIDECHANNELTEST_HPP__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/io_streaming/src/LoopbackTest.hpp | #ifndef __LOOPBACKTEST_HPP__
#define __LOOPBACKTEST_HPP__
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "FakeIOPipes.hpp"
// If the 'USE_REAL_IO_PIPES' macro is defined, this test will use real IO pipes.
// To use this, ensure you have a BSP that supports IO pipes.
// NOTE: define this BEFORE including the LoopbackTest.hpp and
// SideChannelTest.hpp which will check for the presence of this macro.
//#define USE_REAL_IO_PIPES
using namespace sycl;
// declare the kernel and pipe ID stucts globally to reduce name mangling
struct LoopBackMainKernel;
struct LoopBackReadIOPipeID { static constexpr unsigned id = 0; };
struct LoopBackWriteIOPipeID { static constexpr unsigned id = 1; };
//
// The simplest processing kernel. Streams data in 'IOPipeIn' and streams
// it out 'IOPipeOut'. The developer of this kernel uses this abstraction
// to create a streaming kernel. They don't particularly care whether the IO
// pipes are 'real' or not, that is up to the system designer who works on
// stitching together the whole system. In this tutorial, the stitching of the
// full system is done below in the 'RunLoopbackSystem' function.
//
template<class IOPipeIn, class IOPipeOut>
event SubmitLoopbackKernel(queue& q, size_t count) {
return q.single_task<LoopBackMainKernel>([=] {
for (size_t i = 0; i < count; i++) {
auto data = IOPipeIn::read();
// !!! Your processing can go here !!!
IOPipeOut::write(data);
}
});
}
//
// Run the loopback system
//
template<typename T, bool use_usm_host_alloc>
bool RunLoopbackSystem(queue& q, size_t count) {
bool passed = true;
//////////////////////////////////////////////////////////////////////////////
// IO pipes
constexpr size_t kIOPipeDepth = 4;
#ifndef USE_REAL_IO_PIPES
// these are FAKE IO pipes (and their producer/consumer)
using FakeIOPipeInProducer = Producer<LoopBackReadIOPipeID,
T, use_usm_host_alloc, kIOPipeDepth>;
using FakeIOPipeOutConsumer = Consumer<LoopBackWriteIOPipeID,
T, use_usm_host_alloc, kIOPipeDepth>;
using ReadIOPipe = typename FakeIOPipeInProducer::Pipe;
using WriteIOPipe = typename FakeIOPipeOutConsumer::Pipe;
// initialize the fake IO pipes
FakeIOPipeInProducer::Init(q, count);
FakeIOPipeOutConsumer::Init(q, count);
#else
// these are REAL IO pipes
using ReadIOPipe =
ext::intel::kernel_readable_io_pipe<LoopBackReadIOPipeID,
T, kIOPipeDepth>;
using WriteIOPipe =
ext::intel::kernel_writeable_io_pipe<LoopBackWriteIOPipeID,
T, kIOPipeDepth>;
#endif
//////////////////////////////////////////////////////////////////////////////
// FAKE IO PIPES ONLY
#ifndef USE_REAL_IO_PIPES
// get the pointer to the fake input data
auto i_stream_data = FakeIOPipeInProducer::Data();
// create some random input data for the fake IO pipe
std::generate_n(i_stream_data, count, [&] { return rand() % 100; } );
#endif
// submit the main processing kernel
auto kernel_event = SubmitLoopbackKernel<ReadIOPipe, WriteIOPipe>(q, count);
// FAKE IO PIPES ONLY
#ifndef USE_REAL_IO_PIPES
// start the producer and consumer
event produce_dma_e, produce_kernel_e;
event consume_dma_e, consume_kernel_e;
std::tie(produce_dma_e, produce_kernel_e) = FakeIOPipeInProducer::Start(q);
std::tie(consume_dma_e, consume_kernel_e) = FakeIOPipeOutConsumer::Start(q);
// wait for producer and consumer to finish including the DMA events.
// NOTE: if USM host allocations are used, the dma events are noops.
produce_dma_e.wait();
produce_kernel_e.wait();
consume_dma_e.wait();
consume_kernel_e.wait();
#endif
// Wait for main kernel to finish.
// NOTE: we can only wait on the loopback kernel because it knows how much
// data it expects to process ('count'). In general, this may not be the
// case and you may want the processing kernel to run 'forever' (or until the
// host tells it to stop). For an example of this, see 'SideChannelTest.hpp'.
kernel_event.wait();
// FAKE IO PIPES ONLY
#ifndef USE_REAL_IO_PIPES
// get the pointer to the fake input data
auto o_stream_data = FakeIOPipeOutConsumer::Data();
// validate the output
for (size_t i = 0; i < count; i++) {
if (o_stream_data[i] != i_stream_data[i]) {
std::cerr << "ERROR: output mismatch at entry " << i << ": "
<< o_stream_data[i] << " != " << i_stream_data[i]
<< " (out != in)\n";
passed &= false;
}
}
#endif
return passed;
}
#endif /* __LOOPBACKTEST_HPP__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/io_streaming/src/FakeIOPipes.hpp | #ifndef __FAKEIOPIPES_HPP__
#define __FAKEIOPIPES_HPP__
#include <iostream>
#include <type_traits>
#include <utility>
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
// the "detail" namespace is commonly used in C++ as an internal namespace
// (to a file) that is not meant to be visible to the public and should be
// ignored by external users. That is to say, you should never have the line:
// "using namespace detail;" in your code!
//
// "internal" is another common name for a namespace like this.
namespace detail {
using namespace sycl;
template <typename ID, typename T, bool use_host_alloc>
class ProducerConsumerBaseImpl {
protected:
// private members
static inline T *host_data_{nullptr};
static inline T *device_data_{nullptr};
static inline size_t count_{};
static inline bool initialized_{false};
// use some fancy C++ metaprogramming to get the correct pointer type
// based on the template variable
typedef
typename std::conditional_t<use_host_alloc, host_ptr<T>, device_ptr<T>>
kernel_ptr_type;
// private constructor so users cannot make an object
ProducerConsumerBaseImpl(){};
static T *get_kernel_ptr() {
return use_host_alloc ? host_data_ : device_data_;
}
static void initialized_check() {
if (!initialized_) {
std::cerr << "ERROR: Init() has not been called\n";
std::terminate();
}
}
public:
// disable copy constructor and operator=
ProducerConsumerBaseImpl(const ProducerConsumerBaseImpl &) = delete;
ProducerConsumerBaseImpl &operator=(ProducerConsumerBaseImpl const &) =
delete;
static void Init(queue &q, size_t count) {
// make sure init hasn't already been called
if (initialized_) {
std::cerr << "ERROR: Init() was already called\n";
std::terminate();
}
// track count
count_ = count;
// check for USM support
device d = q.get_device();
if (use_host_alloc && !d.get_info<info::device::usm_host_allocations>()) {
std::cerr << "ERROR: The selected device does not support USM host"
<< " allocations\n";
std::terminate();
}
if (!use_host_alloc && !d.get_info<info::device::usm_device_allocations>()) {
std::cerr << "ERROR: The selected device does not support USM device"
<< " allocations\n";
std::terminate();
}
// Allocate the space the user requested. Calling a different malloc
// based on whether the user wants to use USM host allocations or not.
if (use_host_alloc) {
host_data_ = malloc_host<T>(count_, q);
} else {
host_data_ = new T[count_];
}
if (host_data_ == nullptr) {
std::cerr << "ERROR: failed to allocate space for host_data_\n";
std::terminate();
}
// if not using host allocations, allocate device memory
if (!use_host_alloc) {
device_data_ = malloc_device<T>(count_, q);
if (device_data_ == nullptr) {
std::cerr << "ERROR: failed to allocate space for"
<< "device_data_\n";
std::terminate();
}
}
initialized_ = true;
}
static void Destroy(queue &q) {
initialized_check();
// free memory depending on 'use_host_alloc' flag
if (use_host_alloc) {
// free USM host allocation
sycl::free(host_data_, q);
} else {
// free C++ allocated memory
delete[] host_data_;
// free USM device allocation
sycl::free(device_data_, q);
}
initialized_ = false;
}
static size_t Count() {
initialized_check();
return count_;
}
static T *Data() {
initialized_check();
return host_data_;
}
};
////////////////////////////////////////////////////////////////////////////////
// Producer implementation
template <typename Id, typename T, bool use_host_alloc, size_t min_capacity>
class ProducerImpl : public ProducerConsumerBaseImpl<Id, T, use_host_alloc> {
private:
// base implementation alias
using BaseImpl = ProducerConsumerBaseImpl<Id, T, use_host_alloc>;
using kernel_ptr_type = typename BaseImpl::kernel_ptr_type;
// IDs for the pipe and kernel
class PipeID;
class KernelID;
// private constructor so users cannot make an object
ProducerImpl(){};
public:
// disable copy constructor and operator=
ProducerImpl(const ProducerImpl &) = delete;
ProducerImpl &operator=(ProducerImpl const &) = delete;
// the pipe to connect to in device code
using Pipe = sycl::ext::intel::pipe<PipeID, T, min_capacity>;
// the implementation of the static
static std::pair<event, event> Start(queue &q,
size_t count = BaseImpl::count_) {
// make sure initialized has been called
BaseImpl::initialized_check();
// can't produce more data than exists
if (count > BaseImpl::count_) {
std::cerr << "ERROR: Start() called with count=" << count
<< " but allocated size is " << BaseImpl::count_ << "\n";
std::terminate();
}
// If we aren't using USM host allocations, must transfer memory to device
event dma_event;
if (!use_host_alloc) {
dma_event = q.memcpy(BaseImpl::device_data_, BaseImpl::host_data_,
BaseImpl::count_ * sizeof(T));
}
// pick the right pointer to pass to the kernel
auto kernel_ptr = BaseImpl::get_kernel_ptr();
// launch the kernel (use event.depends_on to wait on the memcpy)
auto kernel_event = q.submit([&](handler &h) {
// the kernel must wait until the DMA transfer is done before launching
// this will only take affect it we actually performed the DMA above
h.depends_on(dma_event);
// the producing kernel
// NO-FORMAT comments are for clang-format
h.single_task<Id>([=
]() [[intel::kernel_args_restrict]] { // NO-FORMAT: Attribute
kernel_ptr_type ptr(kernel_ptr);
for (size_t i = 0; i < count; i++) {
auto d = *(ptr + i);
Pipe::write(d);
}
});
});
return std::make_pair(dma_event, kernel_event);
}
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Consumer implementation
template <typename Id, typename T, bool use_host_alloc, size_t min_capacity>
class ConsumerImpl : public ProducerConsumerBaseImpl<Id, T, use_host_alloc> {
private:
// base implementation alias
using BaseImpl = ProducerConsumerBaseImpl<Id, T, use_host_alloc>;
using kernel_ptr_type = typename BaseImpl::kernel_ptr_type;
// IDs for the pipe and kernel
class PipeID;
class KernelID;
// private constructor so users cannot make an object
ConsumerImpl(){};
public:
// disable copy constructor and operator=
ConsumerImpl(const ConsumerImpl &) = delete;
ConsumerImpl &operator=(ConsumerImpl const &) = delete;
// the pipe to connect to in device code
using Pipe = sycl::ext::intel::pipe<PipeID, T, min_capacity>;
static std::pair<event, event> Start(queue &q,
size_t count = BaseImpl::count_) {
// make sure initialized has been called
BaseImpl::initialized_check();
// can't produce more data than exists
if (count > BaseImpl::count_) {
std::cerr << "ERROR: Start() called with count=" << count
<< " but allocated size is " << BaseImpl::count_ << "\n";
std::terminate();
}
// pick the right pointer to pass to the kernel
auto kernel_ptr = BaseImpl::get_kernel_ptr();
// launch the kernel to read the output into device side global memory
auto kernel_event = q.submit([&](handler &h) {
// NO-FORMAT comments are for clang-format
h.single_task<Id>([=
]() [[intel::kernel_args_restrict]] { // NO-FORMAT: Attribute
kernel_ptr_type ptr(kernel_ptr);
for (size_t i = 0; i < count; i++) {
auto d = Pipe::read();
*(ptr + i) = d;
}
});
});
// if the user wanted to use board memory, copy the data back to the host
event dma_event;
if (!use_host_alloc) {
// launch a task to copy the data back from the device. Use the
// event.depends_on signal to wait for the kernel to finish first.
dma_event = q.submit([&](handler &h) {
h.depends_on(kernel_event);
h.memcpy(BaseImpl::host_data_, BaseImpl::device_data_,
BaseImpl::count_ * sizeof(T));
});
}
return std::make_pair(dma_event, kernel_event);
}
};
////////////////////////////////////////////////////////////////////////////////
} // namespace detail
// alias the implementations to face the user
template <typename Id, typename T, bool use_host_alloc, size_t min_capacity = 0>
using Producer = detail::ProducerImpl<Id, T, use_host_alloc, min_capacity>;
template <typename Id, typename T, bool use_host_alloc, size_t min_capacity = 0>
using Consumer = detail::ConsumerImpl<Id, T, use_host_alloc, min_capacity>;
// convenient aliases to get a host or device allocation producer/consumer
template <typename Id, typename T, size_t min_capacity = 0>
using HostConsumer = Consumer<Id, T, true, min_capacity>;
template <typename Id, typename T, size_t min_capacity = 0>
using DeviceConsumer = Consumer<Id, T, false, min_capacity>;
template <typename Id, typename T, size_t min_capacity = 0>
using HostProducer = Producer<Id, T, true, min_capacity>;
template <typename Id, typename T, size_t min_capacity = 0>
using DeviceProducer = Producer<Id, T, false, min_capacity>;
#endif /* __FAKEIOPIPES_HPP__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/io_streaming/src/io_streaming.cpp | #include <algorithm>
#include <chrono>
#include <iostream>
#include <numeric>
#include <chrono>
#include <thread>
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "exception_handler.hpp"
// The type that will stream through the IO pipe. When using real IO pipes,
// make sure the width of this datatype matches the width of the IO pipe, which
// you can find in the BSP XML file.
using IOPipeType = int;
#include "LoopbackTest.hpp"
#include "SideChannelTest.hpp"
using namespace sycl;
// check is USM host allocations are enabled
#if defined(USM_HOST_ALLOCATIONS)
constexpr bool kUseUSMHostAllocation = true;
#else
constexpr bool kUseUSMHostAllocation = false;
#endif
int main() {
bool passed = true;
#if defined(FPGA_EMULATOR)
size_t count = 1 << 12;
#elif defined(FPGA_SIMULATOR)
size_t count = 1 << 5;
#else
size_t count = 1 << 24;
#endif
try {
// device selector
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
// queue properties to enable SYCL profiling of kernels
auto prop_list = property_list{property::queue::enable_profiling()};
// create the device queue
queue q(selector, fpga_tools::exception_handler, prop_list);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
// run the loopback example system
// see 'LoopbackTest.hpp'
std::cout << "Running loopback test\n";
passed &=
RunLoopbackSystem<IOPipeType, kUseUSMHostAllocation>(q, count);
// run the side channel example system
// see 'SideChannelTest.hpp'
std::cout << "Running side channel test\n";
passed &=
RunSideChannelsSystem<IOPipeType, kUseUSMHostAllocation>(q, count);
} catch (exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
if (passed) {
std::cout << "PASSED\n";
return 0;
} else {
std::cout << "FAILED\n";
return 1;
}
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/DesignPatterns/n_way_buffering/src/n_way_buffering.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <cmath>
#include <iomanip>
#include <random>
#include <thread>
#include "exception_handler.hpp"
using namespace sycl;
// N-way buffering. N must be >= 1.
constexpr int kLocalN = 5;
// # times to execute the kernel. kTimes must be >= kLocalN
#if defined(FPGA_EMULATOR)
constexpr int kTimes = 20;
#elif defined(FPGA_SIMULATOR)
constexpr int kTimes = 10;
#else
constexpr int kTimes = 100;
#endif
// # of floats to process on each kernel execution.
#if defined(FPGA_EMULATOR)
constexpr int kSize = 4096;
#elif defined(FPGA_SIMULATOR)
constexpr int kSize = 256;
#else
constexpr int kSize = 2621440; // ~10MB
#endif
// Kernel executes a power function (base^kPow). Must be
// >= 2. Can increase this to increase kernel execution
// time, but ProcessOutput() time will also increase.
#if defined(FPGA_SIMULATOR)
constexpr int kPow = 5;
#else
constexpr int kPow = 20;
#endif
// Number of iterations through the main loop
#if defined(FPGA_SIMULATOR)
constexpr int kNumRuns = 2;
#else
constexpr int kNumRuns = 4;
#endif
bool pass = true;
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class SimpleVpow;
/* Kernel function.
Performs buffer_b[i] = buffer_a[i] ** pow
Only supports pow >= 2.
This kernel is not meant to be an optimal implementation of the power
operation -- it's just a sample kernel for this tutorial whose execution time
is easily controlled via the pow parameter. SYCL buffers are created
externally and passed in by reference to control (external to this function)
when the buffers are destructed. The destructor causes a blocking buffer
transfer from device to host and N-way buffering requires us to not block
here (because we need to queue more kernels). So we only want this transfer
to occur at the end of overall execution, not at the end of each individual
kernel execution.
*/
void SimplePow(sycl::queue &q, buffer<float, 1> &buffer_a,
buffer<float, 1> &buffer_b, event &e) {
// Submit to the queue and execute the kernel
e = q.submit([&](handler &h) {
// Get kernel access to the buffers
accessor accessor_a(buffer_a, h, read_only);
accessor accessor_b(buffer_b, h, read_write, no_init);
const int num = kSize;
const int p = kPow - 1; // Assumes pow >= 2;
assert(kPow >= 2);
h.single_task<class SimpleVpow>([=]() [[intel::kernel_args_restrict]] {
for (int j = 0; j < p; j++) {
if (j == 0) {
for (int i = 0; i < num; i++) {
accessor_b[i] = accessor_a[i] * accessor_a[i];
}
} else {
for (int i = 0; i < num; i++) {
accessor_b[i] = accessor_b[i] * accessor_a[i];
}
}
}
});
});
event update_host_event;
update_host_event = q.submit([&](handler &h) {
accessor accessor_b(buffer_b, h, read_only);
/*
Explicitly instruct the SYCL runtime to copy the kernel's output buffer
back to the host upon kernel completion. This is not required for
functionality since the buffer access in ProcessOutput() also implicitly
instructs the runtime to copy the data back. But it should be noted that
this buffer access blocks ProcessOutput() until the kernel is complete
and the data is copied. In contrast, update_host() instructs the runtime
to perform the copy earlier. This allows ProcessOutput() to optionally
perform more useful work *before* making the blocking buffer access. Said
another way, this allows ProcessOutput() to potentially perform more work
in parallel with the runtime's copy operation.
*/
h.update_host(accessor_b);
});
}
// Returns kernel execution time for a given SYCL event from a queue.
unsigned long SyclGetExecTimeNs(event e) {
unsigned long start_time =
e.get_profiling_info<info::event_profiling::command_start>();
unsigned long end_time = e.get_profiling_info<info::event_profiling::command_end>();
return (end_time - start_time);
}
// Local pow function for verifying results
float MyPow(float input, int pow) {
return (pow == 0) ? 1 : input * MyPow(input, pow - 1);
}
/* Compares kernel output against expected output.
Grabs kernel output data from its SYCL buffer. Reading from this buffer is a
blocking operation that will block on the kernel completing. Grabs expected
output from a host-side copy of the input data. A copy is used to allow for
parallel generation of the input data for the next execution. Queries and
records execution time of the kernel that just completed. This is a natural
place to do this because ProcessOutput() is blocked on kernel completion.
*/
void ProcessOutput(buffer<float, 1> &output_buf, std::vector<float> &input_copy,
int exec_number, event e,
unsigned long &total_kernel_time_per_slot) {
host_accessor output_buf_acc(output_buf, read_only);
int num_errors = 0;
int num_errors_to_print = 10;
// Max fractional difference between FPGA pow result and CPU pow result
// Anything greater than this will be considered an error
constexpr double epsilon = 0.01;
/* The use of update_host() in the kernel function allows for additional
host-side operations to be performed here, in parallel with the buffer copy
operation from device to host, before the blocking access to the output
buffer is made via output_buf_acc[]. To be clear, no real operations are
done here and this is just a note that this is the place
where you *could* do it. */
for (int i = 0; i < kSize; i++) {
const double expected_value = MyPow(input_copy.data()[i], kPow);
const bool out_invalid = std::abs((output_buf_acc[i] - expected_value) /
expected_value) > epsilon;
if ((num_errors < num_errors_to_print) && out_invalid) {
if (num_errors == 0) {
pass = false;
std::cout << "Verification failed on kernel execution # " << exec_number
<< ". Showing up to " << num_errors_to_print
<< " mismatches.\n";
}
std::cout << "Verification failed on kernel execution # " << exec_number
<< ", at element " << i << ". Expected " << std::fixed
<< std::setprecision(16) << expected_value << " but got "
<< output_buf_acc[i] << "\n";
num_errors++;
}
}
// At this point we know the kernel has completed, so can query the profiling
// data.
total_kernel_time_per_slot += SyclGetExecTimeNs(e);
}
/*
Generates input data for the next kernel execution.
Writes the data into the associated SYCL buffer. The write will block until
the previous kernel execution, that is using this buffer, completes. Writes a
copy of the data into a host-side buffer that will later be used by
ProcessOutput().
*/
void ProcessInput(buffer<float, 1> &buf, std::vector<float> ©) {
// We are generating completely new input data, so can use the no_init property
// here to indicate we don't care about the SYCL buffer's current contents.
host_accessor buf_acc(buf, write_only, no_init);
// RNG seed
auto seed = std::chrono::system_clock::now().time_since_epoch().count();
// RNG engine
std::default_random_engine dre(seed);
// Values between 1 and 2
std::uniform_real_distribution<float> di(1.0f, 2.0f);
// Randomly generate a start value and increment from there.
// Compared to randomly generating every value, this is done to
// speed up this function a bit.
float start_val = di(dre);
for (int i = 0; i < kSize; i++) {
buf_acc[i] = start_val;
copy.data()[i] = start_val;
start_val++;
}
}
int main() {
// Create queue, get platform and device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
#ifndef FPGA_HARDWARE
std::cout << "\nEmulator and simulator outputs do not demonstrate "
"true hardware performance. The design may need to run "
"on actual hardware to observe the performance benefit "
"of the optimization exemplified in this tutorial.\n\n";
#endif
try {
auto prop_list = property_list{property::queue::enable_profiling()};
sycl::queue q(selector, fpga_tools::exception_handler, prop_list);
platform platform = q.get_context().get_platform();
device device = q.get_device();
std::cout << "Platform name: "
<< platform.get_info<info::platform::name>().c_str() << "\n";
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
std::cout << "Executing kernel " << kTimes << " times in each round.\n\n";
// Create a vector to store the input/output SYCL buffers
std::vector<buffer<float, 1>> input_buf;
std::vector<buffer<float, 1>> output_buf;
// For every execution slot, we need 2 host-side buffers
// to store copies of the input data. One is used to
// verify the previous kernel's output. The other stores
// the new data for the next kernel execution.
std::vector<float> input_buf_copy[2 * kLocalN];
// SYCL events for each kernel launch.
event sycl_events[kLocalN];
// In nanoseconds. Total execution time of kernels in a given slot.
unsigned long total_kernel_time_per_slot[kLocalN];
// Total execution time of all kernels.
unsigned long total_kernel_time = 0;
// Threads to process the output from each kernel
std::thread t_process_output[kLocalN];
// Threads to process the input data for the next kernel
std::thread t_process_input[kLocalN];
// Demonstrate with 1-way buffering first, then N-way buffering.
int N;
// st = "single threaded".
// Used to enable multi-threading in subsequent runs.
bool st = true;
// Allocate vectors to store the host-side copies of the input data
for (int i = 0; i < 2 * kLocalN; i++) {
input_buf_copy[i] = std::vector<float>(kSize);
}
// Create and allocate the SYCL buffers
for (int i = 0; i < kLocalN; i++) {
input_buf.push_back(buffer<float, 1>(range<1>(kSize)));
output_buf.push_back(buffer<float, 1>(range<1>(kSize)));
}
/*
Main loop.
This loop runs multiple times to demonstrate how performance can be
improved by increasing the number of buffers as well as multi-threading
the host-side operations. The first iteration is a base run, demonstrating
the performance with none of these optimizations (ie. 1-way buffering,
single-threaded).
*/
for (int i = 0; i < kNumRuns; i++) {
for (int i = 0; i < kLocalN; i++) {
total_kernel_time_per_slot[i] = 0; // Initialize timers to zero.
}
switch (i) {
case 0: {
std::cout << "*** Beginning execution, 1-way buffering, "
"single-threaded host operations\n";
N = 1;
st = true;
break;
}
case 1: {
std::cout << "*** Beginning execution, 1-way buffering, "
"multi-threaded host operations.\n";
N = 1;
st = false;
break;
}
case 2: {
std::cout << "*** Beginning execution, 2-way buffering, "
"multi-threaded host operationss\n";
N = 2;
st = false;
break;
}
case 3: {
std::cout << "*** Beginning execution, N=" << kLocalN
<< "-way buffering, multi-threaded host operations\n";
N = kLocalN;
st = false;
break;
}
default:
std::cout << "*** Beginning execution.\n";
}
// Start the timer. This will include the time to process the
// input data for the first N kernel executions.
auto start = std::chrono::steady_clock::now();
// Process the input data for first N kernel executions. For
// multi-threaded runs, this is done in parallel.
for (int i = 0; i < N; i++) {
t_process_input[i] = std::thread(ProcessInput, std::ref(input_buf[i]),
std::ref(input_buf_copy[i]));
if (st) {
t_process_input[i].join();
}
}
/*
It's useful to think of the kernel execution space as having N slots.
Conceptually, the slots are executed chronologically sequentially on the
device (i.e. slot 0 to N-1). Each slot has its own buffering on both the
host and device. Before launching a kernel in a given slot, we must
process output data from the previous execution that occurred in that
slot and process new input data for the upcoming new execution in that
slot.
*/
for (int i = 0; i < kTimes; i++) {
// The current slot is i%N.
// Before each kernel launch, the ProcessOutput() must have completed
// for the last execution in this slot. The ProcessInput() must also
// have completed for the upcoming new execution for this slot. Block on
// both of these.
if (!st) {
// ProcessOutput() is only relevant after the
// first N kernels have been launched.
if (i >= N) {
t_process_output[i % N].join();
}
t_process_input[i % N].join();
}
// Launch the kernel. This is non-blocking with respect to main().
// Only print every few iterations, just to limit the prints.
if (i % 10 == 0) {
std::cout << "Launching kernel #" << i << "\n";
}
SimplePow(q, input_buf[i % N], output_buf[i % N], sycl_events[i % N]);
// Immediately launch threads for the ProcessOutput() and
// ProcessInput() for *this* slot. These are non-blocking with respect
// to main(), but they will individually be blocked until the
// corresponding kernel execution is complete. The ProcessOutput()
// compares the kernel output data against the input data. But
// ProcessInput() will be overwriting that input data in parallel.
// Therefore ProcessOutput() must compare against an older copy of the
// data. We ping-pong between host-side copies of the input data.
t_process_output[i % N] = std::thread(
ProcessOutput, std::ref(output_buf[i % N]),
std::ref(input_buf_copy[i % (2 * N)]), i, sycl_events[i % N],
std::ref(total_kernel_time_per_slot[i % N]));
// For single-threaded runs, force single-threaded operation by
// blocking here immediately.
if (st) {
t_process_output[i % N].join();
}
// For the final N kernel launches, no need to process
// input data because there will be no more launches.
if (i < kTimes - N) {
// The indexes for the input_buf_copy used by ProcessOutput() and
// ProcessInput() are spaced N apart.
t_process_input[i % N] =
std::thread(ProcessInput, std::ref(input_buf[i % N]),
std::ref(input_buf_copy[(i + N) % (2 * N)]));
if (st) {
t_process_input[i % N].join();
}
}
}
// Wait for the final N threads to finish and add up the overall kernel
// execution time.
total_kernel_time = 0;
for (int i = 0; i < N; i++) {
if (!st) {
t_process_output[i].join();
}
total_kernel_time += total_kernel_time_per_slot[i];
}
// Stop the timer.
auto end = std::chrono::steady_clock::now();
double time_span = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();
std::cout << "\nOverall execution time "
<< ((i == kNumRuns - 1) ? ("with N-way buffering ") : "")
<< "= " << (unsigned)(time_span * 1000) << " ms\n";
std::cout << "Total kernel-only execution time "
<< ((i == kNumRuns - 1) ? ("with N-way buffering ") : "")
<< "= " << (unsigned)(total_kernel_time / 1000000) << " ms\n";
std::cout << "Throughput = " << std::setprecision(8)
<< (float)kSize * (float)kTimes * (float)sizeof(float) /
(float)time_span / 1000000
<< " MB/s\n\n\n";
}
if (pass) {
std::cout << "Verification PASSED\n";
} else {
std::cout << "Verification FAILED\n";
return 1;
}
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
std::cerr << "If you are targeting the FPGA simulator, compile with "
"-DFPGA_SIMULATOR.\n";
}
std::terminate();
}
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/GettingStarted/fpga_template/src/fpga_template.cpp | #include <iostream>
// oneAPI headers
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include "exception_handler.hpp"
// Forward declare the kernel name in the global scope. This is an FPGA best
// practice that reduces name mangling in the optimization reports.
class VectorAddID;
struct VectorAdd {
int *const a_in;
int *const b_in;
int *const c_out;
int len;
void operator()() const {
for (int idx = 0; idx < len; idx++) {
int a_val = a_in[idx];
int b_val = b_in[idx];
int sum = a_val + b_val;
c_out[idx] = sum;
}
}
};
constexpr int kVectSize = 256;
int main() {
bool passed = false;
try {
// Use compile-time macros to select either:
// - the FPGA emulator device (CPU emulation of the FPGA)
// - the FPGA device (a real FPGA)
// - the simulator device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
sycl::queue q(selector, fpga_tools::exception_handler,
sycl::property::queue::enable_profiling{});
auto device = q.get_device();
// make sure the device supports USM host allocations
if (!device.has(sycl::aspect::usm_host_allocations)) {
std::cerr << "This design must either target a board that supports USM "
"Host/Shared allocations, or IP Component Authoring. "
<< std::endl;
std::terminate();
}
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
// declare arrays and fill them
// allocate in shared memory so the kernel can see them
int *a = sycl::malloc_shared<int>(kVectSize, q);
int *b = sycl::malloc_shared<int>(kVectSize, q);
int *c = sycl::malloc_shared<int>(kVectSize, q);
for (int i = 0; i < kVectSize; i++) {
a[i] = i;
b[i] = (kVectSize - i);
}
std::cout << "add two vectors of size " << kVectSize << std::endl;
q.single_task<VectorAddID>(VectorAdd{a, b, c, kVectSize}).wait();
// verify that VC is correct
passed = true;
for (int i = 0; i < kVectSize; i++) {
int expected = a[i] + b[i];
if (c[i] != expected) {
std::cout << "idx=" << i << ": result " << c[i] << ", expected ("
<< expected << ") A=" << a[i] << " + B=" << b[i] << std::endl;
passed = false;
}
}
std::cout << (passed ? "PASSED" : "FAILED") << std::endl;
sycl::free(a, q);
sycl::free(b, q);
sycl::free(c, q);
} catch (sycl::exception const &e) {
// Catches exceptions in the host code.
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
return passed ? EXIT_SUCCESS : EXIT_FAILURE;
} | cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/GettingStarted/fpga_compile/part1_cpp/src/vector_add.cpp | #include <iostream>
void VectorAdd(const int *a_in, const int *b_in, int *c_out, int len) {
for (int idx = 0; idx < len; idx++) {
int a_val = a_in[idx];
int b_val = b_in[idx];
int sum = a_val + b_val;
c_out[idx] = sum;
}
}
constexpr int kVectSize = 256;
int main() {
// declare arrays and fill them
int *vec_a = new int[kVectSize];
int *vec_b = new int[kVectSize];
int *vec_c = new int[kVectSize];
for (int i = 0; i < kVectSize; i++) {
vec_a[i] = i;
vec_b[i] = (kVectSize - i);
}
std::cout << "add two vectors of size " << kVectSize << std::endl;
VectorAdd(vec_a, vec_b, vec_c, kVectSize);
// verify that vector C is correct
bool passed = true;
for (int i = 0; i < kVectSize; i++) {
int expected = vec_a[i] + vec_b[i];
if (vec_c[i] != expected) {
std::cout << "idx=" << i << ": result " << vec_c[i] << ", expected ("
<< expected << ") A=" << vec_a[i] << " + B=" << vec_b[i]
<< std::endl;
passed = false;
}
}
std::cout << (passed ? "PASSED" : "FAILED") << std::endl;
delete[] vec_a;
delete[] vec_b;
delete[] vec_c;
return passed ? EXIT_SUCCESS : EXIT_FAILURE;
} | cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/GettingStarted/fpga_compile/part3_dpcpp_lambda_usm/src/vector_add.cpp | #include <iostream>
#include <vector>
// oneAPI headers
#include <CL/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
using namespace sycl;
// Forward declare the kernel name in the global scope. This is an FPGA best
// practice that reduces name mangling in the optimization reports.
class VectorAddID;
void VectorAdd(const int *vec_a_in, const int *vec_b_in, int *vec_c_out,
int len) {
for (int idx = 0; idx < len; idx++) {
int a_val = vec_a_in[idx];
int b_val = vec_b_in[idx];
int sum = a_val + b_val;
vec_c_out[idx] = sum;
}
}
constexpr int kVectSize = 256;
int main() {
bool passed = true;
try {
// Use compile-time macros to select either:
// - the FPGA emulator device (CPU emulation of the FPGA)
// - the FPGA device (a real FPGA)
// - the simulator device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
// create the device queue
sycl::queue q(selector);
// make sure the device supports USM host allocations
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
// declare arrays and fill them
// allocate in shared memory so the kernel can see them
int *vec_a = malloc_shared<int>(kVectSize, q);
int *vec_b = malloc_shared<int>(kVectSize, q);
int *vec_c = malloc_shared<int>(kVectSize, q);
for (int i = 0; i < kVectSize; i++) {
vec_a[i] = i;
vec_b[i] = (kVectSize - i);
}
std::cout << "add two vectors of size " << kVectSize << std::endl;
q.single_task<VectorAddID>([=]() {
VectorAdd(vec_a, vec_b, vec_c, kVectSize);
})
.wait();
// verify that vec_c is correct
for (int i = 0; i < kVectSize; i++) {
int expected = vec_a[i] + vec_b[i];
if (vec_c[i] != expected) {
std::cout << "idx=" << i << ": result " << vec_c[i] << ", expected ("
<< expected << ") A=" << vec_a[i] << " + B=" << vec_b[i]
<< std::endl;
passed = false;
}
}
std::cout << (passed ? "PASSED" : "FAILED") << std::endl;
free(vec_a, q);
free(vec_b, q);
free(vec_c, q);
} catch (sycl::exception const &e) {
// Catches exceptions in the host code.
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
return passed ? EXIT_SUCCESS : EXIT_FAILURE;
} | cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/GettingStarted/fpga_compile/part4_dpcpp_lambda_buffers/src/vector_add.cpp | #include <iostream>
// oneAPI headers
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
// Forward declare the kernel name in the global scope. This is an FPGA best
// practice that reduces name mangling in the optimization reports.
class VectorAddID;
void VectorAdd(const int *vec_a_in, const int *vec_b_in, int *vec_c_out,
int len) {
for (int idx = 0; idx < len; idx++) {
int a_val = vec_a_in[idx];
int b_val = vec_b_in[idx];
int sum = a_val + b_val;
vec_c_out[idx] = sum;
}
}
constexpr int kVectSize = 256;
int main() {
bool passed = true;
try {
// Use compile-time macros to select either:
// - the FPGA emulator device (CPU emulation of the FPGA)
// - the FPGA device (a real FPGA)
// - the simulator device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
// create the device queue
sycl::queue q(selector);
// make sure the device supports USM host allocations
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
// declare arrays and fill them
int *vec_a = new int[kVectSize];
int *vec_b = new int[kVectSize];
int *vec_c = new int[kVectSize];
for (int i = 0; i < kVectSize; i++) {
vec_a[i] = i;
vec_b[i] = (kVectSize - i);
}
std::cout << "add two vectors of size " << kVectSize << std::endl;
{
// copy the input arrays to buffers to share with kernel
sycl::buffer buffer_a{vec_a, sycl::range(kVectSize)};
sycl::buffer buffer_b{vec_b, sycl::range(kVectSize)};
sycl::buffer buffer_c{vec_c, sycl::range(kVectSize)};
q.submit([&](sycl::handler &h) {
// use accessors to interact with buffers from device code
sycl::accessor accessor_a{buffer_a, h, sycl::read_only};
sycl::accessor accessor_b{buffer_b, h, sycl::read_only};
sycl::accessor accessor_c{buffer_c, h, sycl::read_write, sycl::no_init};
h.single_task<VectorAddID>([=]() {
VectorAdd(&accessor_a[0], &accessor_b[0], &accessor_c[0], kVectSize);
});
});
}
// result is copied back to host automatically when accessors go out of
// scope.
// verify that VC is correct
for (int i = 0; i < kVectSize; i++) {
int expected = vec_a[i] + vec_b[i];
if (vec_c[i] != expected) {
std::cout << "idx=" << i << ": result " << vec_c[i] << ", expected ("
<< expected << ") A=" << vec_a[i] << " + B=" << vec_b[i]
<< std::endl;
passed = false;
}
}
std::cout << (passed ? "PASSED" : "FAILED") << std::endl;
delete[] vec_a;
delete[] vec_b;
delete[] vec_c;
} catch (sycl::exception const &e) {
// Catches exceptions in the host code.
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
return passed ? EXIT_SUCCESS : EXIT_FAILURE;
} | cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/GettingStarted/fpga_compile/part2_dpcpp_functor_usm/src/vector_add.cpp | #include <iostream>
// oneAPI headers
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
// Forward declare the kernel name in the global scope. This is an FPGA best
// practice that reduces name mangling in the optimization reports.
class VectorAddID;
struct VectorAdd {
int *const vec_a_in;
int *const vec_b_in;
int *const vec_c_out;
int len;
void operator()() const {
for (int idx = 0; idx < len; idx++) {
int a_val = vec_a_in[idx];
int b_val = vec_b_in[idx];
int sum = a_val + b_val;
vec_c_out[idx] = sum;
}
}
};
constexpr int kVectSize = 256;
int main() {
bool passed = true;
try {
// Use compile-time macros to select either:
// - the FPGA emulator device (CPU emulation of the FPGA)
// - the FPGA device (a real FPGA)
// - the simulator device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
// create the device queue
sycl::queue q(selector);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
if (!device.has(sycl::aspect::usm_host_allocations)) {
std::terminate();
}
// declare arrays and fill them
// allocate in shared memory so the kernel can see them
int *vec_a = sycl::malloc_shared<int>(kVectSize, q);
int *vec_b = sycl::malloc_shared<int>(kVectSize, q);
int *vec_c = sycl::malloc_shared<int>(kVectSize, q);
for (int i = 0; i < kVectSize; i++) {
vec_a[i] = i;
vec_b[i] = (kVectSize - i);
}
std::cout << "add two vectors of size " << kVectSize << std::endl;
q.single_task<VectorAddID>(VectorAdd{vec_a, vec_b, vec_c, kVectSize})
.wait();
// verify that vec_c is correct
for (int i = 0; i < kVectSize; i++) {
int expected = vec_a[i] + vec_b[i];
if (vec_c[i] != expected) {
std::cout << "idx=" << i << ": result " << vec_c[i] << ", expected ("
<< expected << ") A=" << vec_a[i] << " + B=" << vec_b[i]
<< std::endl;
passed = false;
}
}
std::cout << (passed ? "PASSED" : "FAILED") << std::endl;
sycl::free(vec_a, q);
sycl::free(vec_b, q);
sycl::free(vec_c, q);
} catch (sycl::exception const &e) {
// Catches exceptions in the host code.
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
return passed ? EXIT_SUCCESS : EXIT_FAILURE;
} | cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/GettingStarted/fast_recompile/src/kernel.hpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
using namespace sycl;
void RunKernel(queue& q, buffer<float,1>& buf_a, buffer<float,1>& buf_b,
buffer<float,1>& buf_r, size_t size);
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/GettingStarted/fast_recompile/src/kernel.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "kernel.hpp"
// This file contains 'almost' exclusively device code. The single-source SYCL
// code has been refactored between host.cpp and kernel.cpp to separate host and
// device code to the extent that the language permits.
//
// Note that ANY change in either this file or in kernel.hpp will be detected
// by the build system as a difference in the dependencies of device.o,
// triggering a full recompilation of the device code.
//
// This is true even of trivial changes, e.g. tweaking the function definition
// or the names of variables like 'q' or 'h', EVEN THOUGH these are not truly
// "device code".
// Forward declare the kernel names in the global scope. This FPGA best practice
// reduces compiler name mangling in the optimization reports.
class VectorAdd;
void RunKernel(queue& q, buffer<float,1>& buf_a, buffer<float,1>& buf_b,
buffer<float,1>& buf_r, size_t size){
// submit the kernel
q.submit([&](handler &h) {
// Data accessors
accessor a(buf_a, h, read_only);
accessor b(buf_b, h, read_only);
accessor r(buf_r, h, write_only, no_init);
// Kernel executes with pipeline parallelism on the FPGA.
// Use kernel_args_restrict to specify that a, b, and r do not alias.
h.single_task<VectorAdd>([=]() [[intel::kernel_args_restrict]] {
for (size_t i = 0; i < size; ++i) {
r[i] = a[i] + b[i];
}
});
});
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/GettingStarted/fast_recompile/src/host.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <iostream>
#include <vector>
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "exception_handler.hpp"
// This code sample demonstrates how to split the host and FPGA kernel code into
// separate compilation units so that they can be separately recompiled.
// Consult the README for a detailed discussion.
// - host.cpp (this file) contains exclusively code that executes on the host.
// - kernel.cpp contains almost exclusively code that executes on the device.
// - kernel.hpp contains only the forward declaration of a function containing
// the device code.
#include "kernel.hpp"
using namespace sycl;
// the tolerance used in floating point comparisons
constexpr float kTol = 0.001;
// the array size of vectors a, b and c
constexpr size_t kArraySize = 32;
int main() {
std::vector<float> vec_a(kArraySize);
std::vector<float> vec_b(kArraySize);
std::vector<float> vec_r(kArraySize);
// Fill vectors a and b with random float values
for (size_t i = 0; i < kArraySize; i++) {
vec_a[i] = rand() / (float)RAND_MAX;
vec_b[i] = rand() / (float)RAND_MAX;
}
// Select either the FPGA emulator, FPGA simulator or FPGA device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
try {
// Create a queue bound to the chosen device.
// If the device is unavailable, a SYCL runtime exception is thrown.
queue q(selector, fpga_tools::exception_handler);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
// create the device buffers
buffer device_a(vec_a);
buffer device_b(vec_b);
buffer device_r(vec_r);
// The definition of this function is in a different compilation unit,
// so host and device code can be separately compiled.
RunKernel(q, device_a, device_b, device_r, kArraySize);
} catch (exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
// At this point, the device buffers have gone out of scope and the kernel
// has been synchronized. Therefore, the output data (vec_r) has been updated
// with the results of the kernel and is safely accesible by the host CPU.
// Test the results
size_t correct = 0;
for (size_t i = 0; i < kArraySize; i++) {
float tmp = vec_a[i] + vec_b[i] - vec_r[i];
if (tmp * tmp < kTol * kTol) {
correct++;
}
}
// Summarize results
if (correct == kArraySize) {
std::cout << "PASSED: results are correct\n";
} else {
std::cout << "FAILED: results are incorrect\n";
}
return !(correct == kArraySize);
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/loop_fusion/src/loop_fusion.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <iomanip>
#include <iostream>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include "exception_handler.hpp"
#if defined(FPGA_SIMULATOR)
constexpr size_t kTripCount{100};
#else
constexpr size_t kTripCount{10000000};
#endif
constexpr size_t kDifferentTripCount{kTripCount + 1};
constexpr size_t kArraySize{100};
using FixedArray = std::array<int, kArraySize>;
using namespace sycl;
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class DefaultFusionKernel;
class NoFusionKernel;
class DefaultNoFusionKernel;
class FusionFunctionKernel;
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
// Handles error reporting
void ErrorReport(sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
// Returns kernel runtime in ns
auto KernelRuntime(event e) {
auto start{e.get_profiling_info<info::event_profiling::command_start>()};
auto end{e.get_profiling_info<info::event_profiling::command_end>()};
return (end - start);
}
// Fuses inner loops by default, since the trip counts are equal, and there are
// no dependencies between loops
void DefaultFusion(FixedArray &m_array_1, FixedArray &m_array_2) {
try {
queue q(selector, fpga_tools::exception_handler,
property::queue::enable_profiling{});
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
buffer buff_1(m_array_1);
buffer buff_2(m_array_2);
event e = q.submit([&](handler &h) {
accessor a_1(buff_1, h, write_only, no_init);
accessor a_2(buff_2, h, write_only, no_init);
h.single_task<DefaultFusionKernel>([=
]() [[intel::kernel_args_restrict]] { // NO-FORMAT: Attribute
for (size_t i = 0; i < kTripCount; i++) {
a_1[i % kArraySize] = i % kArraySize;
}
for (size_t i = 0; i < kTripCount; i++) {
a_2[i % kArraySize] = i % kArraySize;
}
});
});
auto kernel_time = KernelRuntime(e);
// Kernel consists of two loops with one array assignment and two modulos in
// each.
int num_ops_per_kernel = 6 * kTripCount;
std::cout << "Throughput for kernel with default loop fusion and with "
"equally-sized loops: "
<< ((double)num_ops_per_kernel / kernel_time) << " Ops/ns\n";
} catch (sycl::exception const &e) {
ErrorReport(e);
}
}
// Does not fuse inner loops because of the [[intel::nofusion]] attribute. Were
// this attribute not present, the loops would fuse by default.
void NoFusion(FixedArray &m_array_1, FixedArray &m_array_2) {
try {
queue q(selector, fpga_tools::exception_handler,
property::queue::enable_profiling{});
buffer buff_1(m_array_1);
buffer buff_2(m_array_2);
event e = q.submit([&](handler &h) {
accessor a_1(buff_1, h, write_only, no_init);
accessor a_2(buff_2, h, write_only, no_init);
h.single_task<NoFusionKernel>([=
]() [[intel::kernel_args_restrict]] { // NO-FORMAT: Attribute
[[intel::nofusion]] // NO-FORMAT: Attribute
for (size_t i = 0; i < kTripCount; i++) {
a_1[i % kArraySize] = i % kArraySize;
}
for (size_t i = 0; i < kTripCount; i++) {
a_2[i % kArraySize] = i % kArraySize;
}
});
});
auto kernel_time = KernelRuntime(e);
// Kernel consists of two loops with one array assignment and two modulos in
// each.
int num_ops_per_kernel = 6 * kTripCount;
std::cout << "Throughput for kernel with the nofusion attribute and with "
"equally-sized loops: "
<< ((double)num_ops_per_kernel / kernel_time) << " Ops/ns\n";
} catch (sycl::exception const &e) {
ErrorReport(e);
}
}
// Does not fuse inner loops by default, since the trip counts are different.
void DefaultNoFusion(FixedArray &m_array_1, FixedArray &m_array_2) {
try {
queue q(selector, fpga_tools::exception_handler,
property::queue::enable_profiling{});
buffer buff_1(m_array_1);
buffer buff_2(m_array_2);
event e = q.submit([&](handler &h) {
accessor a_1(buff_1, h, write_only, no_init);
accessor a_2(buff_2, h, write_only, no_init);
h.single_task<DefaultNoFusionKernel>([=
]() [[intel::kernel_args_restrict]] { // NO-FORMAT: Attribute
// Different tripcounts, does not fuse by default
for (size_t i = 0; i < kDifferentTripCount + 1; i++) {
a_1[i % kArraySize] = i % kArraySize;
}
for (size_t i = 0; i < kTripCount; i++) {
a_2[i % kArraySize] = i % kArraySize;
}
});
});
auto kernel_time = KernelRuntime(e);
// Kernel consists of two loops different trip counts, each with one array
// assignment and two modulos.
int num_ops_per_kernel = 3 * kDifferentTripCount + 3 * kTripCount;
std::cout << "Throughput for kernel without fusion by default with "
"unequally-sized loops: "
<< ((double)num_ops_per_kernel / kernel_time) << " Ops/ns\n";
} catch (sycl::exception const &e) {
ErrorReport(e);
}
}
// The compiler is explicitly told to fuse the inner loops using the
// fpga_loop_fuse<>() function. Were this function not used, the loops would not
// fuse by default, since the trip counts of the loops are different.
void FusionFunction(FixedArray &m_array_1, FixedArray &m_array_2) {
try {
queue q(selector, fpga_tools::exception_handler,
property::queue::enable_profiling{});
buffer buff_1(m_array_1);
buffer buff_2(m_array_2);
event e = q.submit([&](handler &h) {
accessor a_1(buff_1, h, write_only, no_init);
accessor a_2(buff_2, h, write_only, no_init);
h.single_task<FusionFunctionKernel>([=
]() [[intel::kernel_args_restrict]] { // NO-FORMAT: Attribute
sycl::ext::intel::fpga_loop_fuse([&] {
// Different tripcounts, does not fuse by default
for (size_t i = 0; i < kDifferentTripCount; i++) {
a_1[i % kArraySize] = i % kArraySize;
}
for (size_t i = 0; i < kTripCount; i++) {
a_2[i % kArraySize] = i % kArraySize;
}
});
});
});
auto kernel_time = KernelRuntime(e);
// Kernel consists of two loops different trip counts, each with one array
// assignment and two modulos.
int num_ops_per_kernel = 3 * kDifferentTripCount + 3 * kTripCount;
std::cout << "Throughput for kernel with a loop fusion function with "
"unequally-sized loops: "
<< ((double)num_ops_per_kernel / kernel_time) << " Ops/ns\n";
} catch (sycl::exception const &e) {
ErrorReport(e);
}
}
int main() {
// Arrays will be populated in kernel loops
FixedArray default_fusion_1;
FixedArray default_fusion_2;
FixedArray no_fusion_1;
FixedArray no_fusion_2;
FixedArray default_nofusion_1;
FixedArray default_nofusion_2;
FixedArray fusion_function_1;
FixedArray fusion_function_2;
// Instantiate kernel logic with and without loop fusion to compare
// performance
DefaultFusion(default_fusion_1, default_fusion_2);
NoFusion(no_fusion_1, no_fusion_2);
DefaultNoFusion(default_nofusion_1, default_nofusion_2);
FusionFunction(fusion_function_1, fusion_function_2);
// Verify results: arrays should be equal, and the i^th element shoul equal i
for (size_t i = 0; i < kArraySize; i++) {
if (default_fusion_1[i] != default_fusion_2[i] ||
default_fusion_1[i] != i) {
std::cout << "FAILED: The DefaultFusionKernel results are incorrect"
<< '\n';
return 1;
}
}
for (size_t i = 0; i < kArraySize; i++) {
if (no_fusion_1[i] != no_fusion_2[i] || no_fusion_1[i] != i) {
std::cout << "FAILED: The NoFusionKernel results are incorrect" << '\n';
return 1;
}
}
for (size_t i = 0; i < kArraySize; i++) {
if (default_nofusion_1[i] != default_nofusion_2[i] ||
default_nofusion_1[i] != i) {
std::cout << "FAILED: The DefaultNoFusionKernel results are incorrect"
<< '\n';
return 1;
}
}
for (size_t i = 0; i < kArraySize; i++) {
if (fusion_function_1[i] != fusion_function_2[i] ||
fusion_function_1[i] != i) {
std::cout << "FAILED: The FusionFunctionKernel results are incorrect"
<< '\n';
return 1;
}
}
std::cout << "PASSED: The results are correct" << '\n';
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/ac_int/src/ac_int.cpp | #include <sycl/sycl.hpp>
#include <sycl/ext/intel/ac_types/ac_int.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <bitset>
#include "exception_handler.hpp"
using namespace sycl;
// Forward declare the kernel names in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class BasicOpsInt;
class BasicOpsAcInt;
class ShiftOps;
class EfficientShiftOps;
class BitAccess;
using MyUInt2 = ac_int<2, false>;
using MyInt7 = ac_int<7, true>;
using MyInt14 = ac_int<14, true>;
using MyInt15 = ac_int<15, true>;
using MyInt28 = ac_int<28, true>;
void TestBasicOpsInt(queue &q, const int &a, const int &b, int &c, int &d,
int &e) {
buffer<int, 1> c_buf(&c, 1);
buffer<int, 1> d_buf(&d, 1);
buffer<int, 1> e_buf(&e, 1);
q.submit([&](handler &h) {
accessor c_acc(c_buf, h, write_only, no_init);
accessor d_acc(d_buf, h, write_only, no_init);
accessor e_acc(e_buf, h, write_only, no_init);
h.single_task<BasicOpsInt>([=]() [[intel::kernel_args_restrict]] {
c_acc[0] = a + b;
d_acc[0] = a * b;
e_acc[0] = a / b;
});
});
}
// Kernel `BasicOpsAcInt` consumes fewer resources than kernel `BasicOpsInt`.
void TestBasicOpsAcInt(queue &q, const MyInt14 &a, const MyInt14 &b, MyInt15 &c,
MyInt28 &d, MyInt15 &e) {
buffer<MyInt15, 1> c_buf(&c, 1);
buffer<MyInt28, 1> d_buf(&d, 1);
buffer<MyInt15, 1> e_buf(&e, 1);
q.submit([&](handler &h) {
accessor c_acc(c_buf, h, write_only, no_init);
accessor d_acc(d_buf, h, write_only, no_init);
accessor e_acc(e_buf, h, write_only, no_init);
h.single_task<BasicOpsAcInt>([=]() [[intel::kernel_args_restrict]] {
c_acc[0] = a + b;
d_acc[0] = a * b;
e_acc[0] = a / b;
});
});
}
void TestShiftOps(queue &q, const MyInt14 &a, const MyInt14 &b, MyInt14 &c) {
buffer<MyInt14, 1> c_buf(&c, 1);
q.submit([&](handler &h) {
accessor c_acc(c_buf, h, write_only, no_init);
h.single_task<ShiftOps>([=]() {
MyInt14 temp = a << b;
c_acc[0] = temp >> b;
});
});
}
// Kernel `EfficientShiftOps` consumes fewer resources than kernel `ShiftOps`.
void TestEfficientShiftOps(queue &q, const MyInt14 &a, const MyUInt2 &b,
MyInt14 &c) {
buffer<MyInt14, 1> c_buf(&c, 1);
q.submit([&](handler &h) {
accessor c_acc(c_buf, h, write_only, no_init);
h.single_task<EfficientShiftOps>([=]() {
MyInt14 temp = a << b;
c_acc[0] = temp >> b;
});
});
}
MyInt14 TestBitAccess(queue &q, const MyInt14 &a) {
MyInt14 res;
buffer<MyInt14, 1> res_buf(&res, 1);
q.submit([&](handler &h) {
accessor res_acc(res_buf, h, write_only, no_init);
h.single_task<BitAccess>([=]() {
// 0b1111101
MyInt7 temp = a.slc<7>(3);
res_acc[0] = 0; // Must be initialized before being accessed by the bit
// select operator `[]`. Using the `[]` operator on an
// uninitialized `ac_int` variable is undefined behavior
// and can give you unexpected results.
// 0 -> 0b1111101000
res_acc[0].set_slc(3, temp);
// 0b1111101000 -> 0b1111101111
res_acc[0][2] = 1;
res_acc[0][1] = 1;
res_acc[0][0] = 1;
});
});
return res;
}
int main() {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
bool passed = true;
try {
queue q(selector, fpga_tools::exception_handler);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
constexpr int kVal1 = 1000, kVal2 = 2;
{
MyInt14 input_a = kVal1, input_b = kVal2;
MyInt15 output_c;
MyInt28 output_d;
MyInt15 output_e;
TestBasicOpsAcInt(q, input_a, input_b, output_c, output_d, output_e);
int golden_c, golden_d, golden_e;
TestBasicOpsInt(q, input_a, input_b, golden_c, golden_d, golden_e);
if (output_c != golden_c || output_d != golden_d ||
output_e != golden_e) {
std::cout << "Result mismatch!\n"
<< "Kernel BasicOpsInt: addition = " << golden_c
<< ", multiplication = " << golden_d
<< ", division = " << golden_e << "\n"
<< "Kernel BasicOpsAcInt: addition = " << output_c
<< ", multiplication = " << output_d
<< ", division = " << output_e << "\n\n";
passed = false;
}
}
{
MyInt14 input_a = kVal1, input_b = kVal2;
MyUInt2 input_efficient_b = kVal2;
MyInt14 output_c, output_efficient_c;
TestShiftOps(q, input_a, input_b, output_c);
TestEfficientShiftOps(q, input_a, input_efficient_b, output_efficient_c);
if (output_c != output_efficient_c) {
std::cout << "Result mismatch!\n"
<< "Kernel ShiftOps: result = " << output_c << "\n"
<< "Kernel EfficientShiftOps: result = " << output_efficient_c
<< "\n\n";
passed = false;
}
}
{
MyInt14 input = kVal1;
MyInt14 output = TestBitAccess(q, input);
constexpr int kGolden = 0b001111101111;
if (output != kGolden) {
std::cout << "Kernel BitAccess result mismatch!\n"
<< "result = 0b" << std::bitset<14>(output) << "\n"
<< "golden = 0b" << std::bitset<14>(kGolden) << "\n\n";
passed = false;
}
}
} catch (exception const &e) {
// Catches exceptions in the host code.
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
if (passed) {
std::cout << "PASSED: all kernel results are correct.\n";
} else {
std::cout << "FAILED\n";
}
return passed ? 0 : 1;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/private_copies/src/private_copies.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <math.h>
#include <array>
#include <iomanip>
#include <iostream>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include "exception_handler.hpp"
using namespace sycl;
#if defined(FPGA_SIMULATOR)
// Smaller size to keep the runtime reasonable
constexpr size_t kSize = 512; //2^9
constexpr size_t kMaxIter = 100;
#else
constexpr size_t kSize = 8192; //2^13
constexpr size_t kMaxIter = 50000;
#endif
constexpr size_t kTotalOps = 2 * kMaxIter * kSize;
constexpr size_t kMaxValue = 128;
using IntArray = std::array<int, kSize>;
using IntScalar = std::array<int, 1>;
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
template <int num_copies> class Kernel;
// Launch a kernel on the device specified by selector.
// The kernel's functionality is designed to show the
// performance impact of the private_copies attribute.
template <int num_copies, bool first_call = false>
void SimpleMathWithShift(const IntArray &array, int shift, IntScalar &result) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
double kernel_time = 0.0;
try {
queue q(selector, fpga_tools::exception_handler,
property::queue::enable_profiling{});
if constexpr (first_call){
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
}
buffer buffer_array(array);
buffer<int, 1> buffer_result(result.data(), 1);
event e = q.submit([&](handler &h) {
accessor accessor_array(buffer_array, h, read_only);
accessor accessor_result(buffer_result, h, write_only, no_init);
h.single_task<Kernel<num_copies>>([=]() [[intel::kernel_args_restrict]] {
int r = 0;
for (size_t i = 0; i < kMaxIter; i++) {
// Request num_copies private copies for array a. This limits the
// concurrency of the outer loop to num_copies and also limits the
// memory use of a.
[[intel::private_copies(num_copies)]] int a[kSize];
for (size_t j = 0; j < kSize; j++) {
a[j] = accessor_array[(i * 4 + j) % kSize] * shift;
}
// The trip count of this loop is different from the loop above to
// prevent the compiler optimizing array `a` out.
for (size_t j = 0; j < kSize / 2; j++)
r += a[j];
}
accessor_result[0] = r;
});
});
// SYCL event profiling allows the kernel execution to be timed
double start = e.get_profiling_info<info::event_profiling::command_start>();
double end = e.get_profiling_info<info::event_profiling::command_end>();
kernel_time = (double)(end - start) * 1e-6;
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
// The performance of the kernel is measured in GFlops, based on:
// 1) the number of operations performed by the kernel.
// This can be calculated easily for the simple example kernel.
// 2) the kernel execution time reported by SYCL event profiling.
std::cout << "Kernel time when private_copies is set to " << num_copies
<< ": " << kernel_time << " ms\n";
std::cout << "Kernel throughput when private_copies is set to " << num_copies
<< ": ";
std::cout << std::fixed << std::setprecision(3)
<< ((double)(kTotalOps) / kernel_time) / 1e6f << " GFlops\n";
}
// Calculates the expected results. Used to verify that the kernel
// is functionally correct.
int GoldenResult(const IntArray &input_arr, int shift) {
int gr = 0;
for (size_t i = 0; i < kMaxIter; i++) {
int a[kSize];
for (size_t j = 0; j < kSize; j++) {
a[j] = input_arr[(i * 4 + j) % kSize] * shift;
}
for (size_t j = 0; j < kSize / 2; j++)
gr += a[j];
}
return gr;
}
int main() {
bool success = true;
IntArray a;
IntScalar R0, R1, R2, R3, R4;
int shift = rand() % kMaxValue;
// initialize the input data
for (size_t i = 0; i < kSize; i++)
a[i] = rand() % kMaxValue;
// Run the kernel with different values of the private_copies
// attribute to determine the optimal private_copies number.
SimpleMathWithShift<0, true>(a, shift, R0);
SimpleMathWithShift<1>(a, shift, R1);
SimpleMathWithShift<2>(a, shift, R2);
SimpleMathWithShift<3>(a, shift, R3);
SimpleMathWithShift<4>(a, shift, R4);
// compute the actual result here
int gr = GoldenResult(a, shift);
// verify the results are correct
if (gr != R0[0]) {
std::cout << "Private copies 0: mismatch: " << R0[0] << " != " << gr
<< " (kernel != expected)" << '\n';
success = false;
}
if (gr != R1[0]) {
std::cout << "Private copies 1: mismatch: " << R1[0] << " != " << gr
<< " (kernel != expected)" << '\n';
success = false;
}
if (gr != R2[0]) {
std::cout << "Private copies 2: mismatch: " << R2[0] << " != " << gr
<< " (kernel != expected)" << '\n';
success = false;
}
if (gr != R3[0]) {
std::cout << "Private copies 3: mismatch: " << R3[0] << " != " << gr
<< " (kernel != expected)" << '\n';
success = false;
}
if (gr != R4[0]) {
std::cout << "Private copies 4: mismatch: " << R4[0] << " != " << gr
<< " (kernel != expected)" << '\n';
success = false;
}
if (success) {
std::cout << "PASSED: The results are correct\n";
return 0;
}
return 1;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/dsp_control/src/dsp_control.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "exception_handler.hpp"
using namespace sycl;
float subtract(float a, float b) { return a - b; }
// Forward declare the kernel names in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class GlobalControl;
class LocalControlPropagateOn;
class LocalControlPropagateOff;
// Runs the Kernel.
void KernelRun(const std::vector<float> &input_data,
std::vector<float> &output_data_add,
std::vector<float> &output_data_sub) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
try {
// Create the SYCL device queue.
queue q(selector, fpga_tools::exception_handler,
property::queue::enable_profiling{});
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
buffer input_buffer(input_data);
buffer output_add_buffer(output_data_add);
buffer output_sub_buffer(output_data_sub);
q.submit([&](handler &h) {
accessor input_a(input_buffer, h, read_only);
accessor output_add_a(output_add_buffer, h, write_only, no_init);
accessor output_sub_a(output_sub_buffer, h, write_only, no_init);
// Kernel that demonstrates DSP global control.
h.single_task<GlobalControl>([=]() [[intel::kernel_args_restrict]] {
// Command-line option `-Xsdsp-mode=prefer-softlogic` controls both
// addition and subtraction to be implemented in soft-logic.
output_add_a[0] = input_a[0] + input_a[1];
output_sub_a[0] = subtract(input_a[0], input_a[1]);
});
});
q.submit([&](handler &h) {
accessor input_a(input_buffer, h, read_only);
accessor output_add_a(output_add_buffer, h, write_only, no_init);
accessor output_sub_a(output_sub_buffer, h, write_only, no_init);
// Kernel that demonstrates DSP local control with Propagate::On.
h.single_task<LocalControlPropagateOn>([=
]() [[intel::kernel_args_restrict]] {
// The local control library function overrides the global control.
// Because the Propagate argument is On, not only the addition directly
// in the lambda, but also the subtraction in the subtract() function
// call inside the lambda are affected by the local control and will be
// implemented in DSP.
ext::intel::math_dsp_control<>([&] {
output_add_a[1] = input_a[0] + input_a[1];
output_sub_a[1] = subtract(input_a[0], input_a[1]);
});
});
});
q.submit([&](handler &h) {
accessor input_a(input_buffer, h, read_only);
accessor output_add_a(output_add_buffer, h, write_only, no_init);
accessor output_sub_a(output_sub_buffer, h, write_only, no_init);
// Kernel that demonstrates DSP local control with Propagate::Off.
h.single_task<LocalControlPropagateOff>([=
]() [[intel::kernel_args_restrict]] {
// The local control library function overrides the global control.
// Because the Propagate argument is Off, only the addition directly in
// the lambda is affected by the local control and will be implemented
// in DSP. The subtraction in the subtract() function call is only
// affected by the global control so will be implemented in soft-logic.
ext::intel::math_dsp_control<ext::intel::Preference::DSP,
ext::intel::Propagate::Off>([&] {
output_add_a[2] = input_a[0] + input_a[1];
output_sub_a[2] = subtract(input_a[0], input_a[1]);
});
});
});
} catch (exception const &e) {
// Catches exceptions in the host code.
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
}
int main() {
std::vector<float> input_data = {1.23f, 2.34f};
std::vector<float> output_data_add(3);
std::vector<float> output_data_sub(3);
KernelRun(input_data, output_data_add, output_data_sub);
bool passed = true;
float golden_add = input_data[0] + input_data[1];
float golden_sub = subtract(input_data[0], input_data[1]);
std::string kernel_names[] = {"GlobalControl", "LocalControlPropagateOn",
"LocalControlPropagateOff"};
for (int i = 0; i <= 2; i++) {
if (output_data_add[i] != golden_add) {
std::cout << "Kernel " << kernel_names[i] << " add output mismatch: \n"
<< "output = " << output_data_add[i]
<< ", golden = " << golden_add << "\n";
passed = false;
}
if (output_data_sub[i] != golden_sub) {
std::cout << "Kernel " << kernel_names[i] << " sub output mismatch: \n"
<< "output = " << output_data_sub[i]
<< ", golden = " << golden_sub << "\n";
passed = false;
}
}
if (passed) {
std::cout << "PASSED: all kernel results are correct.\n";
} else {
std::cout << "FAILED\n";
}
return passed ? 0 : 1;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/lsu_control/src/lsu_control.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <numeric>
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "exception_handler.hpp"
using namespace sycl;
// Forward declare the kernel names in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class KernelPrefetch;
class KernelBurst;
class KernelDefault;
// Aliases for LSU Control Extension types
// Implemented using template arguments such as prefetch & burst_coalesce
// on the new ext::intel::lsu class to specify LSU style and modifiers
using PrefetchingLSU = ext::intel::lsu<ext::intel::prefetch<true>,
ext::intel::statically_coalesce<false>>;
using PipelinedLSU = ext::intel::lsu<>;
using BurstCoalescedLSU = ext::intel::lsu<ext::intel::burst_coalesce<true>,
ext::intel::statically_coalesce<false>>;
// Input data and output data size constants
constexpr size_t kMaxVal = 128;
#if defined(FPGA_EMULATOR) || defined(FPGA_SIMULATOR)
constexpr size_t kBaseVal = 1024;
#else
constexpr size_t kBaseVal = 1048576;
#endif
constexpr size_t kNum = 3;
// Return the execution time of the event, in seconds
double GetExecutionTime(const event &e) {
double start_k = e.get_profiling_info<info::event_profiling::command_start>();
double end_k = e.get_profiling_info<info::event_profiling::command_end>();
double kernel_time = (end_k - start_k) * 1e-9; // ns to s
return kernel_time;
}
// Runs the Kernel
void KernelRun(const std::vector<int> &input_data, const size_t &input_size,
const size_t &output_size, std::vector<int> &output_data) {
std::fill(output_data.begin(), output_data.end(), -1);
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
try {
// create the SYCL device queue
queue q(selector, fpga_tools::exception_handler,
property::queue::enable_profiling{});
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
buffer output_buffer(output_data);
buffer input_buffer(input_data);
auto e_p = q.submit([&](handler &h) {
accessor output_a(output_buffer, h, write_only, no_init);
accessor input_a(input_buffer, h, read_only);
// Kernel that uses the prefetch LSU
h.single_task<KernelPrefetch>([=]() [[intel::kernel_args_restrict]] {
auto input_ptr =
input_a.template get_multi_ptr<access::decorated::no>();
auto output_ptr =
output_a.template get_multi_ptr<access::decorated::no>();
int total = 0;
for (size_t i = 0; i < input_size; i++) {
total += PrefetchingLSU::load(input_ptr + i);
}
output_ptr[0] = total;
});
});
auto e_b = q.submit([&](handler &h) {
accessor output_a(output_buffer, h, write_only, no_init);
accessor input_a(input_buffer, h, read_only);
// Kernel that uses the burst-coalesced LSU
h.single_task<KernelBurst>([=]() [[intel::kernel_args_restrict]] {
auto input_ptr =
input_a.template get_multi_ptr<access::decorated::no>();
auto output_ptr =
output_a.template get_multi_ptr<access::decorated::no>();
int total = 0;
for (size_t i = 0; i < input_size; i++) {
total += BurstCoalescedLSU::load(input_ptr + i);
}
output_ptr[1] = total;
});
});
auto e_d = q.submit([&](handler &h) {
accessor output_a(output_buffer, h, write_only, no_init);
accessor input_a(input_buffer, h, read_only);
// Kernel that uses the default LSUs
h.single_task<KernelDefault>([=]() [[intel::kernel_args_restrict]] {
auto input_ptr =
input_a.template get_multi_ptr<access::decorated::no>();
auto output_ptr =
output_a.template get_multi_ptr<access::decorated::no>();
int total = 0;
for (size_t i = 0; i < input_size; i++) {
total += input_ptr[i];
}
output_ptr[2] = total;
});
});
// Measure the execution time of each kernel
double p_time = GetExecutionTime(e_p);
double b_time = GetExecutionTime(e_b);
double d_time = GetExecutionTime(e_d);
double input_size_mb = (input_size * sizeof(int)/(1024*1024));
std::cout << "Kernel throughput with prefetch LSU: "
<< (input_size_mb/p_time) << " MB/s \n";
std::cout << "Kernel throughput with burst-coalesced LSU: "
<< (input_size_mb/b_time) << " MB/s \n";
std::cout << "Kernel throughput without LSU controls: "
<< (input_size_mb/d_time) << " MB/s \n";
} catch (exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
}
// This host side function performs the same computation as the device side
// kernel, and is used to verify functional correctness.
void GoldenRun(const std::vector<int> &input_data, const size_t &input_size,
const size_t &output_size, std::vector<int> &output_data) {
std::fill(output_data.begin(), output_data.end(), -1);
for (size_t i = 0; i < output_size; i++) {
int total = 0;
for (size_t j = 0; j < input_size; j++) {
// Match formulas from kernel above
total += input_data[j];
}
output_data[i] = total;
}
}
int main() {
bool passed = true;
const size_t input_size = kBaseVal + rand() % kMaxVal;
const size_t output_size = kNum;
std::vector<int> input_data(input_size);
std::vector<int> result_golden(output_size);
std::vector<int> result_kernel(output_size);
// Populate input_data with incrementing values starting with 0
std::iota(input_data.begin(), input_data.end(), 0);
GoldenRun(input_data, input_size, output_size, result_golden);
KernelRun(input_data, input_size, output_size, result_kernel);
for (size_t i = 0; i < output_size; i++) {
if (result_kernel[i] != result_golden[i]) {
std::cout << "Output Mismatch: \n"
<< "result_kernel[" << i << "] vs result_golden [" << i
<< "] = " << result_kernel[i] << "," << result_golden[i]
<< " \n";
passed = false;
}
}
if (passed) {
std::cout << "PASSED: all kernel results are correct.\n";
} else {
std::cout << "FAILED\n";
}
return passed ? 0 : 1;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/memory_attributes/src/memory_attributes.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "exception_handler.hpp"
using namespace sycl;
// constants for this tutorial
constexpr size_t kRows = 8;
#if defined(FPGA_SIMULATOR)
// Use a smaller unroll factor when running simulation
constexpr size_t kVec = 1;
#else
constexpr size_t kVec = 4;
#endif
constexpr size_t kMaxVal = 512;
#if defined (FPGA_SIMULATOR)
constexpr size_t kNumTests = 2;
#else
constexpr size_t kNumTests = 64;
#endif
constexpr size_t kMaxIter = 8;
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
// Templating allows us to easily instantiate different versions of the kernel.
template<int AttrType>
class Kernel;
// The shared compute function for host and device code
size_t Compute(unsigned init, unsigned dict_offset[][kVec]) {
// We do not provide any attributes for compare_offset and hash;
// we let the compiler decide what's best based on the access pattern
// and their size.
unsigned compare_offset[kVec][kVec];
unsigned hash[kVec];
#pragma unroll
for (size_t i = 0; i < kVec; i++) {
hash[i] = (++init) & (kRows - 1);
}
size_t count = 0, iter = 0;
do {
// After unrolling both loops, we have kVec*kVec reads from dict_offset
#pragma unroll
for (size_t i = 0; i < kVec; i++) {
#pragma unroll
for (size_t k = 0; k < kVec; ++k) {
compare_offset[k][i] = dict_offset[hash[i]][k];
}
}
// After unrolling, we have kVec writes to dict_offset
#pragma unroll
for (size_t k = 0; k < kVec; ++k) {
dict_offset[hash[k]][k] = (init << k);
}
init++;
#pragma unroll
for (size_t i = 0; i < kVec; i++) {
#pragma unroll
for (size_t k = 0; k < kVec; ++k) {
count += compare_offset[i][k];
}
}
} while (++iter < kMaxIter);
return count;
}
// We use partial template specialization to apply different attributes to the
// 'dict_offset' variable in the kernel.
// This serves as a baseline implementation where no attributes are applied
// to the variable. The compiler uses heuristics to try and find the best
// configuration
template<int AttrType>
event submitKernel(queue& q, unsigned init, buffer<unsigned, 1>& d_buf,
buffer<unsigned, 1>& r_buf) {
auto e = q.submit([&](handler &h) {
accessor d_accessor(d_buf, h, read_only);
accessor r_accessor(r_buf, h, write_only, no_init);
h.single_task<Kernel<AttrType>>([=]() [[intel::kernel_args_restrict]] {
// Declare 'dict_offset' whose attributes are applied based on AttrType
unsigned dict_offset[kRows][kVec];
// Initialize 'dict_offset' with values from global memory.
for (size_t i = 0; i < kRows; ++i) {
#pragma unroll
for (size_t k = 0; k < kVec; ++k) {
// After unrolling, we end up with kVec writes to dict_offset.
dict_offset[i][k] = d_accessor[i * kVec + k];
}
}
// compute the result
r_accessor[0] = Compute(init, dict_offset);
});
});
return e;
}
// Define version 1 of the kernel - using a single pumped memory
template<>
event submitKernel<1>(queue& q, unsigned init, buffer<unsigned, 1>& d_buf,
buffer<unsigned, 1>& r_buf) {
auto e = q.submit([&](handler &h) {
accessor d_accessor(d_buf, h, read_only);
accessor r_accessor(r_buf, h, write_only, no_init);
h.single_task<Kernel<1>>([=]() [[intel::kernel_args_restrict]] {
// Declare 'dict_offset' whose attributes are applied based on AttrType
[[intel::singlepump,
intel::fpga_memory("MLAB"),
intel::numbanks(kVec),
intel::max_replicates(kVec)]]
unsigned dict_offset[kRows][kVec];
// Initialize 'dict_offset' with values from global memory.
for (size_t i = 0; i < kRows; ++i) {
#pragma unroll
for (size_t k = 0; k < kVec; ++k) {
// After unrolling, we end up with kVec writes to dict_offset.
dict_offset[i][k] = d_accessor[i * kVec + k];
}
}
// compute the result
r_accessor[0] = Compute(init, dict_offset);
});
});
return e;
}
// Define version 2 of the kernel - using a double pumped memory
template<>
event submitKernel<2>(queue& q, unsigned init, buffer<unsigned, 1>& d_buf,
buffer<unsigned, 1>& r_buf) {
auto e = q.submit([&](handler &h) {
accessor d_accessor(d_buf, h, read_only);
accessor r_accessor(r_buf, h, write_only, no_init);
h.single_task<Kernel<2>>([=]() [[intel::kernel_args_restrict]] {
// Declare 'dict_offset' whose attributes are applied based on AttrType
[[intel::doublepump,
intel::fpga_memory("MLAB"),
intel::numbanks(kVec),
intel::max_replicates(kVec)]]
unsigned dict_offset[kRows][kVec];
// Initialize 'dict_offset' with values from global memory.
for (size_t i = 0; i < kRows; ++i) {
#pragma unroll
for (size_t k = 0; k < kVec; ++k) {
// After unrolling, we end up with kVec writes to dict_offset.
dict_offset[i][k] = d_accessor[i * kVec + k];
}
}
// compute the result
r_accessor[0] = Compute(init, dict_offset);
});
});
return e;
}
template <int AttrType>
unsigned RunKernel(unsigned init, const unsigned dict_offset_init[],
bool first_run = false) {
unsigned result = 0;
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
try {
queue q(selector, fpga_tools::exception_handler);
if (first_run){
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
}
// Flatten the 2D array to a 1D buffer, because the
// buffer constructor requires a pointer to input data
// that is contiguous in memory.
buffer<unsigned, 1> d_buf(dict_offset_init, range<1>(kRows * kVec));
buffer<unsigned, 1> r_buf(&result, 1);
// submit the kernel
auto e = submitKernel<AttrType>(q, init, d_buf, r_buf);
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
return result;
}
// This host side function performs the same computation as the device side
// kernel, and is used to verify functional correctness.
unsigned GoldenRun(unsigned init, unsigned const dict_offset_init[]) {
unsigned dict_offset[kRows][kVec];
for (size_t i = 0; i < kRows; ++i) {
for (size_t k = 0; k < kVec; ++k) {
dict_offset[i][k] = dict_offset_init[i * kVec + k];
}
}
return Compute(init, dict_offset);
}
int main() {
srand(0);
bool passed = true;
for (size_t j = 0; j < kNumTests; j++) {
unsigned init = rand() % kMaxVal;
unsigned int dict_offset_init[kRows * kVec];
// initialize input data with random values
for (size_t i = 0; i < kRows; ++i) {
for (size_t k = 0; k < kVec; ++k) {
dict_offset_init[i * kVec + k] = rand() % kMaxVal;
}
}
// compute the golden result
unsigned golden_result = GoldenRun(init, dict_offset_init);
// run the kernel with 'singlepump' memory attribute
bool first_run = j==0;
unsigned result_sp = RunKernel<1>(init, dict_offset_init, first_run);
if (!(result_sp == golden_result)) {
passed = false;
std::cout << " Test#" << j
<< ": mismatch: " << result_sp << " != " << golden_result
<< " (result_sp != golden_result)\n";
}
// run the kernel with 'doublepump' memory attribute
unsigned result_dp = RunKernel<2>(init, dict_offset_init);
if (!(result_dp == golden_result)) {
passed = false;
std::cout << " Test#" << j
<< ": mismatch: " << result_dp << " != " << golden_result
<< " (result_dp != golden_result)\n";
}
// run the kernel with no memory attributes
unsigned result_na = RunKernel<0>(init, dict_offset_init);
if (!(result_na == golden_result)) {
passed = false;
std::cout << " Test#" << j
<< ": mismatch: " << result_na << " != " << golden_result
<< " (result_na != golden_result)\n";
}
}
if (passed) {
std::cout << "PASSED: all kernel results are correct.\n";
} else {
std::cout << "FAILED\n";
return 1;
}
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/stall_enable/src/stall_enable.cpp | #include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <iomanip>
#include <iostream>
#include "exception_handler.hpp"
using namespace sycl;
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class KernelComputeStallFree;
class KernelComputeStallEnable;
constexpr int kSeed = 0;
constexpr int kWork = 50;
constexpr int kNumElements = 1000;
constexpr int kTotalOps = kNumElements * kWork;
typedef long WorkType;
typedef std::vector<WorkType> WorkVec;
static WorkType RealWork(WorkType a, WorkType b) {
// This will create a large cluster, which will exaggerate
// the effect of the stall-enable cluster.
#pragma unroll
for (size_t j = 0; j < kWork; j++) {
if (j & 1)
a -= b;
else
a *= b;
}
return a;
}
using ReadAccessor =
accessor<WorkType, 1, access::mode::read, access::target::device>;
using WriteAccessor =
accessor<WorkType, 1, access::mode::write, access::target::device>;
static void Work(const ReadAccessor &vec_a, const ReadAccessor &vec_b,
const WriteAccessor &vec_res) {
for (size_t idx = 0; idx < kNumElements; idx += 2) {
auto a = vec_a[idx];
auto b = vec_b[idx];
vec_res[idx] = RealWork(a, b);
vec_res[idx+1] = RealWork(b, a);
}
}
void DoSomeWork(const WorkVec &vec_a, const WorkVec &vec_b, WorkVec &res) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
double kernel_time = 0.0;
try {
auto prop_list = property_list{property::queue::enable_profiling()};
queue q(selector, fpga_tools::exception_handler, prop_list);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
buffer buffer_in_a(vec_a);
buffer buffer_in_b(vec_b);
buffer buffer_out(res);
event e = q.submit([&](handler &h) {
accessor accessor_vec_a(buffer_in_a, h, read_only);
accessor accessor_vec_b(buffer_in_b, h, read_only);
accessor accessor_res(buffer_out, h, write_only, no_init);
// The kernel_args_restrict promises the compiler that this kernel's
// accessor arguments won't alias (i.e. non-overlapping memory regions).
#ifdef STALL_FREE
h.single_task<class KernelComputeStallFree>(
[=]() [[intel::kernel_args_restrict]] {
// Run using a function with stall free clusters
Work(accessor_vec_a, accessor_vec_b, accessor_res);
});
#else // STALL_FREE
h.single_task<class KernelComputeStallEnable>(
[=]() [[intel::kernel_args_restrict,
intel::use_stall_enable_clusters]] {
// Run using a function with stall enable clusters
Work(accessor_vec_a, accessor_vec_b, accessor_res);
});
#endif // STALL_FREE
});
// Kernel profiling data
double start = e.get_profiling_info<info::event_profiling::command_start>();
double end = e.get_profiling_info<info::event_profiling::command_end>();
// convert nanoseconds to microseconds
kernel_time = (double)(end - start) * 1e-3;
} catch (exception const &exc) {
std::cerr << "Caught synchronous SYCL exception:\n" << exc.what() << '\n';
if (exc.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
#ifdef STALL_FREE
std::cout << "Stall free"
#else
std::cout << "Stall enable"
#endif
<< " Kernel -- kernel time : " << kernel_time << " microseconds\n";
std::cout << "Throughput for kernel: ";
std::cout << std::fixed << std::setprecision(0)
<< (((double)kTotalOps * sizeof(WorkType) * 1e-3f) /
(kernel_time * 1e-6f)) << "KB/s\n";
}
int main() {
WorkVec vec_a(kNumElements);
WorkVec vec_b(kNumElements);
WorkVec vec_output(kNumElements);
WorkVec vec_expected(kNumElements);
// Populate the vectors
srand(kSeed);
for (size_t i = 0; i < kNumElements; i += 2) {
vec_a[i] = static_cast<WorkType>(rand());
vec_b[i] = static_cast<WorkType>(rand());
vec_expected[i] = RealWork(vec_a[i], vec_b[i]);
vec_expected[i+1] = RealWork(vec_b[i], vec_a[i]);
}
DoSomeWork(vec_a, vec_b, vec_output);
// Correctness check
bool passed = true;
for (size_t i = 0; i < kNumElements; i++) {
auto val = vec_output[i];
if (val != vec_expected[i]) {
std::cout << "FAILED: The results are incorrect\n"
<< "Index " << i << ": expected: "
<< vec_expected[i] << ", result: " << val
<< '\n';
passed = false;
}
}
if (passed) {
std::cout << "PASSED: The results are correct\n";
return 0;
} else {
std::cout << "FAILED\n";
return -1;
}
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/loop_unroll/src/loop_unroll.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
#include "exception_handler.hpp"
using namespace sycl;
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
template <int unroll_factor> class VAdd;
// This function instantiates the vector add kernel, which contains
// a loop that adds up the two summand arrays and stores the result
// into sum. This loop will be unrolled by the specified unroll_factor.
template <int unroll_factor>
void VecAdd(const std::vector<float> &summands1,
const std::vector<float> &summands2, std::vector<float> &sum,
size_t array_size) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
try {
queue q(selector, fpga_tools::exception_handler,
property::queue::enable_profiling{});
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
buffer buffer_summands1(summands1);
buffer buffer_summands2(summands2);
buffer buffer_sum(sum);
event e = q.submit([&](handler &h) {
accessor acc_summands1(buffer_summands1, h, read_only);
accessor acc_summands2(buffer_summands2, h, read_only);
accessor acc_sum(buffer_sum, h, write_only, no_init);
h.single_task<VAdd<unroll_factor>>([=]()
[[intel::kernel_args_restrict]] {
// Unroll the loop fully or partially, depending on unroll_factor
#pragma unroll unroll_factor
for (size_t i = 0; i < array_size; i++) {
acc_sum[i] = acc_summands1[i] + acc_summands2[i];
}
});
});
double start = e.get_profiling_info<info::event_profiling::command_start>();
double end = e.get_profiling_info<info::event_profiling::command_end>();
// convert from nanoseconds to ms
double kernel_time = (double)(end - start) * 1e-6;
std::cout << "unroll_factor " << unroll_factor
<< " kernel time : " << kernel_time << " ms\n";
std::cout << "Throughput for kernel with unroll_factor " << unroll_factor
<< ": ";
std::cout << std::fixed << std::setprecision(3)
#if defined(FPGA_SIMULATOR)
<< ((double)array_size / kernel_time) / 1e3f << " MFlops\n";
#else
<< ((double)array_size / kernel_time) / 1e6f << " GFlops\n";
#endif
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
}
int main(int argc, char *argv[]) {
#if defined(FPGA_SIMULATOR)
size_t array_size = 1 << 4;
#else
size_t array_size = 1 << 26;
#endif
if (argc > 1) {
std::string option(argv[1]);
if (option == "-h" || option == "--help") {
std::cout << "Usage: \n<executable> <data size>\n\nFAILED\n";
return 1;
} else {
array_size = std::stoi(option);
}
}
std::vector<float> summands1(array_size);
std::vector<float> summands2(array_size);
std::vector<float> sum_unrollx1(array_size);
std::vector<float> sum_unrollx2(array_size);
std::vector<float> sum_unrollx4(array_size);
std::vector<float> sum_unrollx8(array_size);
std::vector<float> sum_unrollx16(array_size);
// Initialize the two summand arrays (arrays to be added to each other) to
// 1:N and N:1, so that the sum of all elements is N + 1
for (size_t i = 0; i < array_size; i++) {
summands1[i] = static_cast<float>(i + 1);
summands2[i] = static_cast<float>(array_size - i);
}
std::cout << "Input Array Size: " << array_size << "\n";
// Instantiate VecAdd kernel with different unroll factors: 1, 2, 4, 8, 16
// The VecAdd kernel contains a loop that adds up the two summand arrays.
// This loop will be unrolled by the specified unroll factor.
// The sum array is expected to be identical, regardless of the unroll factor.
VecAdd<1>(summands1, summands2, sum_unrollx1, array_size);
VecAdd<2>(summands1, summands2, sum_unrollx2, array_size);
VecAdd<4>(summands1, summands2, sum_unrollx4, array_size);
VecAdd<8>(summands1, summands2, sum_unrollx8, array_size);
VecAdd<16>(summands1, summands2, sum_unrollx16, array_size);
// Verify that the output data is the same for every unroll factor
for (size_t i = 0; i < array_size; i++) {
if (sum_unrollx1[i] != summands1[i] + summands2[i] ||
sum_unrollx1[i] != sum_unrollx2[i] ||
sum_unrollx1[i] != sum_unrollx4[i] ||
sum_unrollx1[i] != sum_unrollx8[i] ||
sum_unrollx1[i] != sum_unrollx16[i]) {
std::cout << "FAILED: The results are incorrect\n";
return 1;
}
}
std::cout << "PASSED: The results are correct\n";
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/printf/src/printf.cpp | #include <sycl/sycl.hpp>
#include <iostream>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "exception_handler.hpp"
// According to the OpenCL C spec, the format string must be in the constant
// address space. To simplify code when invoking printf, the following macros
// are defined.
#ifdef __SYCL_DEVICE_ONLY__
#define CL_CONSTANT __attribute__((opencl_constant))
#else
#define CL_CONSTANT
#endif
using namespace sycl;
#define PRINTF(format, ...) \
{ \
static const CL_CONSTANT char _format[] = format; \
ext::oneapi::experimental::printf(_format, ##__VA_ARGS__); \
}
class BasicKernel;
int main(int argc, char* argv[]) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
queue q(selector);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
// Create some kernel arguments for printing.
int x = 123;
float y = 1.0f;
try {
q.submit([&](handler& h) {
h.single_task<BasicKernel>([=]() {
PRINTF("Result1: Hello, World!\n");
PRINTF("Result2: %%\n");
PRINTF("Result3: %d\n", x);
PRINTF("Result4: %u\n", 123);
PRINTF("Result5: %.2f\n", y);
PRINTF("Result6: print slash_n \\n \n");
PRINTF("Result7: Long: %ld\n", 650000L);
PRINTF("Result8: Preceding with blanks: %10d \n", 1977);
PRINTF("Result9: Preceding with zeros: %010d \n", 1977);
PRINTF("Result10: Some different radices: %d %x %o %#x %#o \n", 100,
100, 100, 100, 100);
PRINTF("Result11: ABC%c\n", 'D');
});
})
.wait();
} catch (sycl::exception const& e) {
std::cout << "Caught a synchronous SYCL exception: " << e.what() << "\n";
std::cout << "FAILED\n";
std::terminate();
}
return 0;
} | cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/speculated_iterations/src/speculated_iterations.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <array>
#include <iomanip>
#include <iostream>
#include <string>
#include <type_traits>
#include "exception_handler.hpp"
// Use smaller values if run on the emulator or simulator to keep the CPU
// runtime/simulation time reasonable
// Use the largest possible int values on the FPGA to show the difference in
// performance with and without speculated_iterations
#if defined(FPGA_EMULATOR)
constexpr float kUpper = 3.0f;
constexpr size_t kExpectedIterations = 1e3;
#elif defined(FPGA_SIMULATOR)
constexpr float kUpper = 2.0f;
constexpr size_t kExpectedIterations = 1e2;
#else
constexpr float kUpper = 8.0f;
constexpr size_t kExpectedIterations = 1e8;
#endif
using namespace sycl;
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
template <int N> class KernelCompute;
template <int spec_iter, bool first_call = false>
void ComplexExit(float bound, int &res) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
double kernel_time_ms = 0.0;
try {
// create the device queue with profiling enabled
auto prop_list = property_list{property::queue::enable_profiling()};
queue q(selector, fpga_tools::exception_handler, prop_list);
if constexpr (first_call){
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
}
// The scalar inputs are passed to the kernel using the lambda capture,
// but a SYCL buffer must be used to return a scalar from the kernel.
buffer<int, 1> buffer_res(&res, 1);
event e = q.submit([&](handler &h) {
accessor accessor_res(buffer_res, h, write_only, no_init);
h.single_task<class KernelCompute<spec_iter>>([=]() {
int x = 1;
// Computing the exit condition of this loop is a complex operation.
// Since the value of var is not known at compile time, the loop
// trip count is variable and the exit condition must be evaluated at
// each iteration.
[[intel::speculated_iterations(spec_iter)]]
while (sycl::log10((float)(x)) < bound) {
x++;
}
accessor_res[0] = x;
});
});
// get the kernel time in milliseconds
// this excludes memory transfer and queuing overhead
double startk =
e.template get_profiling_info<info::event_profiling::command_start>();
double endk =
e.template get_profiling_info<info::event_profiling::command_end>();
kernel_time_ms = (endk - startk) * 1e-6;
} catch (exception const &exc) {
std::cerr << "Caught synchronous SYCL exception:\n" << exc.what() << "\n";
if (exc.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
// MFLOPs = mega floating point operations per second
double mflops = (double)(kExpectedIterations) / kernel_time_ms;
std::cout << "Speculated Iterations: " << spec_iter
<< " -- kernel time: " << kernel_time_ms << " ms\n";
std::cout << std::fixed << std::setprecision(0)
<< "Performance for kernel with " << spec_iter
<< " speculated iterations: " << mflops << " MFLOPs\n";
}
int main(int argc, char *argv[]) {
float bound = kUpper;
// We don't want "bound" to be a compile-time known constant value
if (argc > 1) {
std::string option(argv[1]);
bound = std::stoi(option);
}
// result variables
int r0, r1, r2;
// Choose the number of speculated iterations based on the FPGA board selected.
// This reflects compute latency differences on different hardware
// architectures, and is a low-level optimization.
#if defined(A10)
ComplexExit<0, true>(bound, r0);
ComplexExit<10>(bound, r1);
ComplexExit<27>(bound, r2);
#elif defined(S10)
ComplexExit<0, true>(bound, r0);
ComplexExit<10>(bound, r1);
ComplexExit<54>(bound, r2);
#elif defined(Agilex7)
ComplexExit<0, true>(bound, r0);
ComplexExit<10>(bound, r1);
ComplexExit<50>(bound, r2);
#else
std::static_assert(false, "Invalid FPGA board macro");
#endif
bool passed = true;
if (std::fabs(std::log10(r0) - bound) > 1e-5) {
std::cout << "Test 0 result mismatch " << std::log10(r0)
<< " not within 0.00001 of " << bound << "\n";
passed = false;
}
if (std::fabs(std::log10(r1) - bound) > 1e-5) {
std::cout << "Test 1 result mismatch " << std::log10(r1)
<< " not within 0.00001 of " << bound << "\n";
passed = false;
}
if (std::fabs(std::log10(r2) - bound) > 1e-5) {
std::cout << "Test 2 result mismatch " << std::log10(r2)
<< " not within 0.00001 of " << bound << "\n";
passed = false;
}
std::cout << (passed ? "PASSED: The results are correct" : "FAILED") << "\n";
return passed ? 0 : -1;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/max_reinvocation_delay/src/max_reinvocation_delay.cpp | #include <iostream>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include "exception_handler.hpp"
constexpr int kFactors = 5;
// Forward declare the kernel and pipe names
// (This prevents unwanted name mangling in the optimization report.)
class ArithmeticSequence;
class ResultsPipe;
// Results pipe from device back to host
using PipeResults = sycl::ext::intel::experimental::pipe<ResultsPipe, int>;
// Computes and outputs the first "sequence_length" terms of the arithmetic
// sequences with first term "first_term" and factors 1 through kFactors.
struct ArithmeticSequenceKernel {
int first_term;
int sequence_length;
void operator()() const {
for (int factor = 1; factor <= kFactors; factor++) {
[[intel::max_reinvocation_delay(1)]] // NO-FORMAT: Attribute
for (int i = 0; i < sequence_length; i++) {
PipeResults::write(first_term + i * factor);
}
}
}
};
int main() {
try {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
sycl::queue q(selector, fpga_tools::exception_handler);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
int first_term = 0;
int sequence_length = 10;
q.single_task<ArithmeticSequence>(
ArithmeticSequenceKernel{first_term, sequence_length});
// Verify functional correctness
bool passed = true;
for (int factor = 1; factor <= kFactors; factor++) {
std::cout << "Calculating arithmetic sequence with factor = " << factor
<< std::endl;
for (int i = 0; i < sequence_length; i++) {
int val_device = PipeResults::read(q);
int val_host = first_term + i * factor;
passed &= (val_device == val_host);
if (val_device != val_host) {
std::cout << "Error: expected " << val_host << ", got " << val_device
<< std::endl;
}
}
}
std::cout << (passed ? "PASSED" : "FAILED") << std::endl;
return passed ? EXIT_SUCCESS : EXIT_FAILURE;
} catch (sycl::exception const &e) {
std::cerr << "Caught a synchronous SYCL exception: " << e.what()
<< std::endl;
std::cerr << " If you are targeting an FPGA hardware, "
"ensure that your system is plugged to an FPGA board that is "
"set up correctly"
<< std::endl;
std::cerr << " If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR"
<< std::endl;
std::terminate();
}
} | cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/mem_channel/src/mem_channel.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <chrono>
#include <numeric>
#include "exception_handler.hpp"
using namespace sycl;
#if defined(FPGA_SIMULATOR)
constexpr size_t vector_size = 10000; // size of input vectors
#else
constexpr size_t vector_size = 1000000; // size of input vectors
#endif
constexpr double kNs = 1e9; // number of nanoseconds in a second
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class VecAdd;
event runVecAdd(sycl::queue &q, const std::vector<int> &a_vec,
const std::vector<int> &b_vec, const std::vector<int> &c_vec,
std::vector<int> &sum_vec) {
#if defined(NO_INTERLEAVING) && defined(TWO_CHANNELS)
buffer a_buf(a_vec, {property::buffer::mem_channel{1}});
buffer b_buf(b_vec, {property::buffer::mem_channel{2}});
buffer c_buf(c_vec, {property::buffer::mem_channel{1}});
buffer sum_buf(sum_vec, {property::buffer::mem_channel{2}});
#elif defined(NO_INTERLEAVING) && defined(FOUR_CHANNELS)
buffer a_buf(a_vec, {property::buffer::mem_channel{1}});
buffer b_buf(b_vec, {property::buffer::mem_channel{2}});
buffer c_buf(c_vec, {property::buffer::mem_channel{3}});
buffer sum_buf(sum_vec, {property::buffer::mem_channel{4}});
#else
buffer a_buf(a_vec);
buffer b_buf(b_vec);
buffer c_buf(c_vec);
buffer sum_buf(sum_vec);
#endif
event e = q.submit([&](handler &h) {
accessor a(a_buf, h, read_only);
accessor b(b_buf, h, read_only);
accessor c(c_buf, h, read_only);
accessor sum(sum_buf, h, write_only, no_init);
h.single_task<VecAdd>([=]() [[intel::kernel_args_restrict]] {
for (int i = 0; i < vector_size; i++)
sum[i] = a[i] + b[i] + c[i];
});
});
return e;
}
int main() {
// Host and kernel profiling
event e;
uint64_t t1_kernel, t2_kernel;
double time_kernel;
// Create input and output vectors
std::vector<int> a, b, c, sum_fpga, sum_cpu;
a.resize(vector_size);
b.resize(vector_size);
c.resize(vector_size);
sum_fpga.resize(vector_size);
sum_cpu.resize(vector_size);
// Initialize input vectors with values from 0 to vector_size - 1
std::iota(a.begin(), a.end(), 0);
std::iota(b.begin(), b.end(), 0);
std::iota(c.begin(), c.end(), 0);
// Create queue, get platform and device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
try {
auto prop_list =
sycl::property_list{sycl::property::queue::enable_profiling()};
sycl::queue q(selector, fpga_tools::exception_handler, prop_list);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
std::cout << "\nVector size: " << vector_size << "\n";
e = runVecAdd(q, a, b, c, sum_fpga);
e.wait();
// Compute kernel execution time
t1_kernel = e.get_profiling_info<info::event_profiling::command_start>();
t2_kernel = e.get_profiling_info<info::event_profiling::command_end>();
time_kernel = (t2_kernel - t1_kernel) / kNs;
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
// Compute the reference solution
for (int i = 0; i < vector_size; ++i)
sum_cpu[i] = a[i] + b[i] + c[i];
// Verify output and print pass/fail
bool passed = true;
int num_errors = 0;
for (int b = 0; b < vector_size; b++) {
if (num_errors < 10 && sum_fpga[b] != sum_cpu[b]) {
passed = false;
std::cerr << " (mismatch, expected " << sum_cpu[b] << ")\n";
num_errors++;
}
}
if (passed) {
std::cout << "Verification PASSED\n\n";
// Report host execution time and throughput
std::cout.setf(std::ios::fixed);
// Input size in MB
constexpr double num_mb = (vector_size * sizeof(uint32_t)) / (1024 * 1024);
// Report kernel execution time and throughput
std::cout << "Kernel execution time: " << time_kernel << " seconds\n";
#if !defined(NO_INTERLEAVING)
std::cout << "Kernel throughput: " << (num_mb / time_kernel) << " MB/s\n\n";
#else
std::cout << "Kernel throughput without burst-interleaving: "
<< (num_mb / time_kernel) << " MB/s\n\n";
#endif
} else {
std::cerr << "Verification FAILED\n";
return 1;
}
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/experimental/hostpipes/src/hostpipes.cpp | #include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/ext/intel/experimental/pipes.hpp>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
// dpc_common.hpp can be found in the dev-utilities include folder.
// e.g., $ONEAPI_ROOT/dev-utilities//include/dpc_common.hpp
#include "exception_handler.hpp"
// forward declare kernel and pipe names to reduce name mangling
class LoopBackKernelID;
class H2DPipeID;
class D2HPipeID;
// the host pipes
using ValueT = int;
constexpr size_t kPipeMinCapacity = 8;
using H2DPipe = sycl::ext::intel::experimental::pipe<
// Usual pipe parameters
H2DPipeID, // An identifier for the pipe
ValueT, // The type of data in the pipe
kPipeMinCapacity // The capacity of the pipe
>;
using D2HPipe = sycl::ext::intel::experimental::pipe<
// Usual pipe parameters
D2HPipeID, // An identifier for the pipe
ValueT, // The type of data in the pipe
kPipeMinCapacity // The capacity of the pipe
>;
// forward declare the test functions
void AlternatingTest(sycl::queue&, ValueT*, ValueT*, size_t, size_t);
void LaunchCollectTest(sycl::queue&, ValueT*, ValueT*, size_t, size_t);
// offloaded computation
ValueT SomethingComplicated(ValueT val) { return (ValueT)(val * sqrt(val)); }
/////////////////////////////////////////
int main(int argc, char* argv[]) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
bool passed = true;
size_t count = 16;
if (argc > 1) count = atoi(argv[1]);
if (count <= 0) {
std::cerr << "ERROR: 'count' must be positive" << std::endl;
return 1;
}
if (count < kPipeMinCapacity) {
std::cerr
<< "ERROR: 'count' must be greater than the minimum pipe capacity ("
<< kPipeMinCapacity << ")" << std::endl;
return 1;
}
try {
// create the device queue
sycl::queue q(selector, fpga_tools::exception_handler,
sycl::property::queue::enable_profiling{});
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
// create input and golden output data
std::vector<ValueT> in(count), out(count), golden(count);
std::generate(in.begin(), in.end(), [] { return ValueT(rand() % 77); });
for (int i = 0; i < count; i++) {
golden[i] = SomethingComplicated(in[i]);
}
// validation lambda
auto validate = [](auto& in, auto& out, size_t size) {
for (int i = 0; i < size; i++) {
if (out[i] != in[i]) {
std::cout << "out[" << i << "] != in[" << i << "]"
<< " (" << out[i] << " != " << in[i] << ")" << std::endl;
return false;
}
}
return true;
};
// Alternating write-and-read
std::cout << "Running Alternating write-and-read" << std::endl;
std::fill(out.begin(), out.end(), 0);
AlternatingTest(q, in.data(), out.data(), count, 3);
passed &= validate(golden, out, count);
std::cout << std::endl;
// Launch and Collect
std::cout << "Running Launch and Collect" << std::endl;
std::fill(out.begin(), out.end(), 0);
LaunchCollectTest(q, in.data(), out.data(), kPipeMinCapacity, 3);
passed &= validate(out, golden, kPipeMinCapacity);
std::cout << std::endl;
} catch (sycl::exception const& e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
std::terminate();
}
if (passed) {
std::cout << "PASSED\n";
return 0;
} else {
std::cout << "FAILED\n";
return 1;
}
}
// This kernel reads a data element from InHostPipe, processes it,
// and writes the result to OutHostPipe
template <typename KernelId, // type identifier for kernel
typename InHostPipe, // host-to-device pipe
typename OutHostPipe // device-to-host pipe
>
sycl::event SubmitLoopBackKernel(sycl::queue& q, size_t count) {
return q.single_task<KernelId>([=] {
for (size_t i = 0; i < count; i++) {
auto d = InHostPipe::read();
auto r = SomethingComplicated(d);
OutHostPipe::write(r);
}
});
}
// This test launches SubmitLoopBackKernel, then alternates writes
// and reads to and from the H2DPipe and D2HPipe hostpipes respectively
void AlternatingTest(sycl::queue& q, ValueT* in, ValueT* out, size_t count,
size_t repeats) {
std::cout << "\t Run Loopback Kernel on FPGA" << std::endl;
auto e = SubmitLoopBackKernel<LoopBackKernelID, H2DPipe, D2HPipe>(
q, count * repeats);
for (size_t r = 0; r < repeats; r++) {
std::cout << "\t " << r << ": "
<< "Doing " << count << " writes & reads" << std::endl;
for (size_t i = 0; i < count; i++) {
// write data in host-to-device hostpipe
H2DPipe::write(q, in[i]);
// read data from device-to-host hostpipe
out[i] = D2HPipe::read(q);
}
}
// No need to wait on kernel to finish as the pipe reads are blocking
std::cout << "\t Done" << std::endl;
}
// This test launches SubmitLoopBackKernel, writes 'count'
// elements to H2DPipe, and then reads 'count' elements from
// D2HPipe
void LaunchCollectTest(sycl::queue& q, ValueT* in, ValueT* out, size_t count,
size_t repeats) {
std::cout << "\t Run Loopback Kernel on FPGA" << std::endl;
for (size_t r = 0; r < repeats; r++) {
std::cout << "\t " << r << ": "
<< "Doing " << count << " writes" << std::endl;
for (size_t i = 0; i < count; i++) {
// write data in host-to-device hostpipe
H2DPipe::write(q, in[i]);
}
}
auto e = SubmitLoopBackKernel<LoopBackKernelID, H2DPipe, D2HPipe>(
q, count * repeats);
for (size_t r = 0; r < repeats; r++) {
std::cout << "\t " << r << ": "
<< "Doing " << count << " reads" << std::endl;
for (size_t i = 0; i < count; i++) {
// read data from device-to-host hostpipe
out[i] = D2HPipe::read(q);
}
}
// No need to wait on kernel to finish as the pipe reads are blocking
std::cout << "\t Done" << std::endl;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/experimental/device_global/src/device_global.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <math.h>
#include <iostream>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include "exception_handler.hpp"
constexpr size_t kNumIterations = 4;
constexpr unsigned kNumWeightIncrements = 3;
constexpr unsigned kVectorSize = 4;
namespace exp = sycl::ext::oneapi::experimental;
using WeightsDeviceGlobalProperties =
decltype(exp::properties(exp::device_image_scope, exp::host_access_write));
// globally declared weights for the calculation
exp::device_global<int[kVectorSize], WeightsDeviceGlobalProperties> weights;
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class Kernel;
// Launch a kernel that does a weighted vector add
// result = a + (weights * b)
void WeightedVectorAdd(sycl::queue q, int *a, int *b, int *result) {
q.single_task<Kernel>([=]() [[intel::kernel_args_restrict]] {
for (auto i = 0; i < kVectorSize; i++) {
result[i] = a[i] + (weights[i] * b[i]);
}
});
q.wait();
}
int main() {
bool success = true;
try {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
sycl::queue q(selector, fpga_tools::exception_handler,
sycl::property::queue::enable_profiling{});
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
std::array<int, kVectorSize> host_weights;
int *a = sycl::malloc_host<int>(kVectorSize, q);
int *b = sycl::malloc_host<int>(kVectorSize, q);
int *result = sycl::malloc_host<int>(kVectorSize, q);
// Run the kernel with different sets of weights
for (auto weight = 0; weight <= kNumWeightIncrements; weight++) {
host_weights.fill(weight);
// Transfer data from the host to the device_global
q.copy(host_weights.data(), weights).wait();
// Update the input to the kernel and launch it
for (auto index = 0; index < kNumIterations; index++) {
std::fill(a, a + kVectorSize, index);
std::fill(b, b + kVectorSize, index);
WeightedVectorAdd(q, a, b, result);
// verify the results are correct
int expected_result = index + (weight * index);
for (auto element = 0; element < kVectorSize; element++) {
if (result[element] != expected_result) {
std::cerr << "Error: for expession {" << index << " + (" << weight
<< " x " << index << ")} expected all " << kVectorSize
<< " indicies to be " << expected_result << " but got "
<< result[element] << " at index " << element << "\n";
success = false;
}
}
}
}
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
if (success) {
std::cout << "PASSED: The results are correct\n";
return 0;
}
return 1;
} | cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/experimental/latency_control/src/latency_control.cpp | #include <sycl/sycl.hpp>
#include <numeric>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "exception_handler.hpp"
using BurstCoalescedLSU = sycl::ext::intel::experimental::lsu<
sycl::ext::intel::experimental::burst_coalesce<true>,
sycl::ext::intel::experimental::statically_coalesce<false>>;
int Operation(int a) { return a * 3 + 2; } // Arbitrary operations.
// Forward declare the kernel names in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class LatencyControl;
// Runs the Kernel.
void KernelRun(const std::vector<int> &in_data, std::vector<int> &out_data,
const size_t &size) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
try {
// Create the SYCL device queue.
sycl::queue q(selector, fpga_tools::exception_handler,
sycl::property::queue::enable_profiling{});
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
sycl::buffer in_buffer(in_data);
sycl::buffer out_buffer(out_data);
q.submit([&](sycl::handler &h) {
sycl::accessor in_accessor(in_buffer, h, sycl::read_only);
sycl::accessor out_accessor(out_buffer, h, sycl::write_only,
sycl::no_init);
h.single_task<LatencyControl>([=]() [[intel::kernel_args_restrict]] {
auto in_ptr =
in_accessor.template get_multi_ptr<sycl::access::decorated::no>();
auto out_ptr =
out_accessor.template get_multi_ptr<sycl::access::decorated::no>();
for (size_t i = 0; i < size; i++) {
// The following load has a label 0.
int value = BurstCoalescedLSU::load(
in_ptr + i,
sycl::ext::oneapi::experimental::properties(
sycl::ext::intel::experimental::latency_anchor_id<0>));
value = Operation(value);
// The following store occurs exactly 5 cycles after the label-0
// function, i.e., the load above.
BurstCoalescedLSU::store(
out_ptr + i, value,
sycl::ext::oneapi::experimental::properties(
sycl::ext::intel::experimental::latency_constraint<
0,
sycl::ext::intel::experimental::latency_control_type::
exact,
5>));
}
});
});
} catch (sycl::exception const &e) {
// Catches exceptions in the host code.
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
}
void GoldenRun(const std::vector<int> &in_data, std::vector<int> &out_data,
const size_t &size) {
for (size_t i = 0; i < size; i++) {
out_data[i] = Operation(in_data[i]);
}
}
int main() {
const size_t size = 5;
std::vector<int> input_data(size);
std::vector<int> result_kernel(size);
std::vector<int> result_golden(size);
// Populate in_data with incrementing values starting with 0
std::iota(input_data.begin(), input_data.end(), 0);
KernelRun(input_data, result_kernel, size);
GoldenRun(input_data, result_golden, size);
bool passed = true;
for (int i = 0; i < size; i++) {
if (result_kernel[i] != result_golden[i]) {
std::cout << "Output Mismatch: \n"
<< "result_kernel[" << i << "] = " << result_kernel[i]
<< ", result_golden[" << i << "] = " << result_golden[i]
<< " \n";
passed = false;
}
}
if (passed) {
std::cout << "PASSED: all kernel results are correct.\n";
} else {
std::cout << "FAILED\n";
}
return passed ? 0 : 1;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/kernel_args_restrict/src/kernel_args_restrict.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <algorithm>
#include <numeric>
#include <vector>
#include "exception_handler.hpp"
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
using namespace sycl;
// Forward declare the kernel names in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class KernelArgsRestrict;
class KernelArgsNoRestrict;
// Return the execution time of the event, in seconds
double GetExecutionTime(const event &e) {
double start_k = e.get_profiling_info<info::event_profiling::command_start>();
double end_k = e.get_profiling_info<info::event_profiling::command_end>();
double kernel_time = (end_k - start_k) * 1e-9; // ns to s
return kernel_time;
}
void RunKernels(size_t size, std::vector<int> &in, std::vector<int> &nr_out,
std::vector<int> &r_out) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
try {
// create the SYCL device queue
queue q(selector, fpga_tools::exception_handler,
property::queue::enable_profiling{});
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
buffer in_buf(in);
buffer nr_out_buf(nr_out);
buffer r_out_buf(r_out);
// submit the task that DOES NOT apply the kernel_args_restrict attribute
auto e_nr = q.submit([&](handler &h) {
accessor in_acc(in_buf, h, read_only);
accessor out_acc(nr_out_buf, h, write_only, no_init);
h.single_task<KernelArgsNoRestrict>([=]() {
for (size_t i = 0; i < size; i++) {
out_acc[i] = in_acc[i];
}
});
});
// submit the task that DOES apply the kernel_args_restrict attribute
auto e_r = q.submit([&](handler &h) {
accessor in_acc(in_buf, h, read_only);
accessor out_acc(r_out_buf, h, write_only, no_init);
h.single_task<KernelArgsRestrict>([=]() [[intel::kernel_args_restrict]] {
for (size_t i = 0; i < size; i++) {
out_acc[i] = in_acc[i];
}
});
});
// measure the execution time of each kernel
double size_mb = (size * sizeof(int)) / (1024 * 1024);
double nr_time = GetExecutionTime(e_nr);
double r_time = GetExecutionTime(e_r);
std::cout << "Size of vector: " << size << " elements\n";
std::cout << "Kernel throughput without attribute: " << (size_mb / nr_time)
<< " MB/s\n";
std::cout << "Kernel throughput with attribute: " << (size_mb / r_time)
<< " MB/s\n";
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
// Exiting the 'try' scope above, where the buffers were declared, will cause
// the buffer destructors to be called which will wait until the kernels that
// use them to finish and copy the data back to the host (if the buffer was
// written to).
// Therefore, at this point in the code, we know that the kernels have
// finished and the data has been transferred back to the host (in the
// 'nr_out' and 'r_out' vectors).
}
int main(int argc, char* argv[]) {
// size of vectors to copy, allow user to change it from the command line
#if defined(FPGA_SIMULATOR)
size_t size = 5000; // smaller size to keep the default runtime reasonable
#else
size_t size = 5000000;
#endif
if (argc > 1) size = atoi(argv[1]);
// input/output data
std::vector<int> in(size);
std::vector<int> nr_out(size), r_out(size);
// generate some input data
std::iota(in.begin(), in.end(), 0);
// clear the output data
std::fill(nr_out.begin(), nr_out.end(), -1);
std::fill(r_out.begin(), r_out.end(), -1);
// Run the kernels
RunKernels(size, in, nr_out, r_out);
// validate the results
bool passed = true;
for (size_t i = 0; i < size; i++) {
if (in[i] != nr_out[i]) {
std::cout << "FAILED: mismatch at entry " << i
<< " of 'KernelArgsNoRestrict' kernel output\n";
std::cout << " (" << in[i] << " != " << nr_out[i]
<< ", in[i] != out[i])\n";
passed = false;
break;
}
}
for (size_t i = 0; i < size; i++) {
if (in[i] != r_out[i]) {
std::cout << "FAILED: mismatch at entry " << i
<< " of 'KernelArgsRestrict' kernel output\n";
std::cout << " (" << in[i] << " != " << r_out[i]
<< ", in[i] != out[i])\n";
passed = false;
break;
}
}
if (passed) {
std::cout << "PASSED\n";
return 0;
} else {
std::cout << "FAILED\n";
return 0;
}
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/loop_ivdep/src/loop_ivdep.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <iomanip>
#include <iostream>
#include "exception_handler.hpp"
#if defined(FPGA_SIMULATOR)
constexpr size_t kRowLength = 16;
#else
constexpr size_t kRowLength = 128;
#endif
constexpr size_t kMinSafelen = 1;
constexpr size_t kMaxSafelen = kRowLength;
constexpr size_t kMatrixSize = kRowLength * kRowLength;
using namespace sycl;
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
template <size_t safe_len> class KernelCompute;
template <size_t safe_len>
void TransposeAndFold(const std::array<float, kMatrixSize> &m_input,
std::array<float, kMatrixSize> &m_output) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
double kernel_time = 0;
try {
queue q(selector, fpga_tools::exception_handler,
property::queue::enable_profiling{});
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
buffer buffer_input(m_input);
buffer buffer_output(m_output);
event e = q.submit([&](handler &h) {
accessor accessor_input(buffer_input, h, read_only);
accessor accessor_output(buffer_output, h, write_only, no_init);
h.single_task<KernelCompute<safe_len>>([=]()
[[intel::kernel_args_restrict]] {
float in_buffer[kRowLength][kRowLength];
float temp_buffer[kRowLength][kRowLength];
// Initialize local buffers
for (size_t i = 0; i < kMatrixSize; i++) {
in_buffer[i / kRowLength][i % kRowLength] = accessor_input[i];
temp_buffer[i / kRowLength][i % kRowLength] = 0;
}
// No iterations of the following loop store data into the same memory
// location that are less than kRowLength iterations apart.
// The ivdep here instructs the compiler that it can safely assume no
// loop-carried dependencies over safe_len consecutive iterations.
[[intel::ivdep(temp_buffer, safe_len)]]
for (size_t j = 0; j < kMatrixSize * kRowLength; j++) {
#pragma unroll
for (size_t i = 0; i < kRowLength; i++) {
temp_buffer[j % kRowLength][i] += in_buffer[i][j % kRowLength];
}
}
// Write result to output
for (size_t i = 0; i < kMatrixSize; i++) {
accessor_output[i] = temp_buffer[i / kRowLength][i % kRowLength];
}
});
});
double start = e.get_profiling_info<info::event_profiling::command_start>();
double end = e.get_profiling_info<info::event_profiling::command_end>();
// unit is nano second, convert to ms
kernel_time = (double)(end - start) * 1e-6;
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
std::cout << "safe_len: " << safe_len << " -- kernel time : " << kernel_time
<< " ms\n";
std::cout << "Throughput for kernel with safe_len " << safe_len << ": ";
std::cout << std::fixed << std::setprecision(0)
<< (((double)kMatrixSize * sizeof(float) * 1e-3f) /
(kernel_time * 1e-3f)) << "KB/s\n";
}
int main() {
std::array<float, kMatrixSize> A, B, C;
// Initialize input with random data
for (size_t i = 0; i < kMatrixSize; i++) {
A[i] = static_cast<float>(rand()) / static_cast<float>(RAND_MAX);
}
// Instantiate kernel logic with the min and max correct safelen parameter
// to compare performance.
TransposeAndFold<kMinSafelen>(A, B);
TransposeAndFold<kMaxSafelen>(A, C);
// You can also try removing the ivdep from the kernel entirely and
// recompiling to see what effect this has on performance.
// Verify result
for (size_t i = 0; i < kMatrixSize; i++) {
if (B[i] != C[i]) {
std::cout << "FAILED: The results are incorrect" << '\n';
return 1;
}
}
std::cout << "PASSED: The results are correct" << '\n';
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/fpga_reg/src/fpga_reg.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
#include "exception_handler.hpp"
using namespace sycl;
using namespace std;
// Artificial coefficient and offset data for our math function
#if defined(FPGA_SIMULATOR)
constexpr size_t kSize = 8;
constexpr int kCoeff[kSize] = {1, 2, 3, 4, 5, 6, 7, 8};
constexpr int kOffset[kSize] = {8, 7, 6, 5, 4, 3, 2, 1};
#else
constexpr size_t kSize = 64;
constexpr int kCoeff[kSize] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64};
constexpr int kOffset[kSize] = {
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
#endif
// The function our kernel will compute
// The "golden result" will be computed on the host to check the kernel result.
vector<int> GoldenResult(vector<int> vec) {
// The coefficients will be modified with each iteration of the outer loop.
int coeff[kSize];
for (size_t i = 0; i < kSize; i++) {
coeff[i] = kCoeff[i];
}
for (int &val : vec) {
// Do some arithmetic
int acc = 0;
for (size_t i = 0; i < kSize; i++) {
acc += coeff[i] * (val + kOffset[i]);
}
// Update coeff by rotating the values of the array
int tmp = coeff[0];
for (size_t i = 0; i < kSize - 1; i++) {
coeff[i] = coeff[i + 1];
}
coeff[kSize - 1] = tmp;
// Result
val = acc;
}
return vec;
}
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class SimpleMath;
void RunKernel(const std::vector<int> &vec_a,
std::vector<int> &vec_r) {
// Run the kernel on either the FPGA emulator, or FPGA simulator, or FPGA
// hardware
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
size_t input_size = vec_a.size();
try {
queue q(selector, fpga_tools::exception_handler,
property::queue::enable_profiling{});
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
buffer device_a(vec_a);
buffer device_r(vec_r);
event e = q.submit([&](handler &h) {
accessor a(device_a, h, read_only);
accessor r(device_r, h, write_only, no_init);
// FPGA-optimized kernel
// Using kernel_args_restrict tells the compiler that the input
// and output buffers won't alias.
h.single_task<class SimpleMath>([=]() [[intel::kernel_args_restrict]] {
// Force the compiler to implement the coefficient array in FPGA
// pipeline registers rather than in on-chip memory.
[[intel::fpga_register]] int coeff[kSize];
for (size_t i = 0; i < kSize; i++) {
coeff[i] = kCoeff[i];
}
// The compiler will pipeline the outer loop.
for (size_t i = 0; i < input_size; ++i) {
int acc = 0;
int val = a[i];
// Fully unroll the accumulator loop.
// All of the unrolled operations can be freely scheduled by the
// oneAPI DPC++/C++ Compiler's FPGA backend as part of a common data pipeline.
#pragma unroll
for (size_t j = 0; j < kSize; j++) {
#ifdef USE_FPGA_REG
// Use fpga_reg to insert a register between the copy of val used
// in each unrolled iteration.
val = ext::intel::fpga_reg(val);
// Since val is held constant across the kSize unrolled iterations,
// the FPGA hardware structure of val's distribution changes from a
// kSize-way fanout (without fpga_reg) to a chain of of registers
// with intermediate tap offs. Refer to the diagram in the README.
// Use fpga_reg to insert a register between each step in the acc
// adder chain.
acc = ext::intel::fpga_reg(acc) + (coeff[j] * (val + kOffset[j]));
// This transforms a compiler-inferred adder tree into an adder
// chain, altering the structure of the pipeline. Refer to the
// diagram in the README.
#else
// Without fpga_reg, the compiler schedules the operations here
// according to its default optimization heuristics.
acc += (coeff[j] * (val + kOffset[j]));
#endif
}
// Rotate the values of the coefficient array.
// The loop is fully unrolled. This is a canonical code structure;
// the oneAPI DPC++/C++ Compiler's FPGA backend infers a shift register here.
int tmp = coeff[0];
#pragma unroll
for (size_t j = 0; j < kSize - 1; j++) {
coeff[j] = coeff[j + 1];
}
coeff[kSize - 1] = tmp;
// Result
r[i] = acc;
}
});
});
// Measure kernel execution time
double start = e.get_profiling_info<info::event_profiling::command_start>();
double end = e.get_profiling_info<info::event_profiling::command_end>();
// Convert from nanoseconds to milliseconds.
double kernel_time = (end - start) * 1e-6;
// Kernel consists of two nested loops with 3 operations in the innermost
// loop: 2 additions and 1 multiplication operation.
size_t num_ops_per_kernel = input_size * kSize * 3;
cout << "Throughput for kernel with input size " << input_size
<< " and coefficient array size " << kSize << ": ";
cout << std::fixed << std::setprecision(6)
<< ((double)num_ops_per_kernel / kernel_time) / 1.0e6 << " GFlops\n";
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
}
int main(int argc, char *argv[]) {
#if defined(FPGA_SIMULATOR)
size_t input_size = 10;
#else
size_t input_size = 1e6;
#endif
// Optional command line override of default input size
if (argc > 1) {
string option(argv[1]);
if (option == "-h" || option == "--help") {
cout << "Usage: \n<executable> <input data size>\n\nFAILED\n";
return 1;
} else {
input_size = stoi(option);
}
}
// Initialize input vector
constexpr int max_val = 1<<10; // Conservative max to avoid integer overflow
vector<int> vec_a(input_size);
for (size_t i = 0; i < input_size; i++) {
vec_a[i] = rand() % max_val;
}
// Kernel result vector
vector<int> vec_r(input_size);
RunKernel(vec_a, vec_r);
// Test the results.
vector<int> golden_ref = GoldenResult(vec_a);
bool correct = true;
for (size_t i = 0; i < input_size; i++) {
if (vec_r[i] != golden_ref[i]) {
cout << "Found mismatch at " << i << ", "
<< vec_r[i] << " != " << golden_ref[i] << "\n";
correct = false;
}
}
if (correct) {
cout << "PASSED: Results are correct.\n";
} else {
cout << "FAILED: Results are incorrect.\n";
return 1;
}
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/optimization_targets/src/optimization_targets.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include "exception_handler.hpp"
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include <vector>
class Kernel;
#if defined(FPGA_SIMULATOR)
constexpr int kInputSize = 10;
#else
constexpr int kInputSize = 1000;
#endif
typedef int RGBType;
typedef std::vector<RGBType> RGBVec;
typedef float GreyType;
typedef std::vector<GreyType> GreyVec;
// Return the execution time of the event, in seconds
double GetExecutionTime(const sycl::event &e) {
double start_k =
e.get_profiling_info<sycl::info::event_profiling::command_start>();
double end_k =
e.get_profiling_info<sycl::info::event_profiling::command_end>();
double kernel_time = (end_k - start_k) * 1e-9; // ns to s
return kernel_time;
}
GreyType Compute(RGBType r, RGBType g, RGBType b) {
GreyType output =
(GreyType)r * 0.3f + (GreyType)g * 0.59f + (GreyType)b * 0.11f;
return output;
}
void RunKernel(const RGBVec &r, const RGBVec &g, const RGBVec &b,
GreyVec &out) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
try {
// create the SYCL device queue
sycl::queue q(selector, fpga_tools::exception_handler,
sycl::property::queue::enable_profiling{});
sycl::device device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
sycl::buffer r_buf(r);
sycl::buffer g_buf(g);
sycl::buffer b_buf(b);
sycl::buffer out_buf(out);
// submit the kernel
auto e = q.submit([&](sycl::handler &h) {
sycl::accessor r_acc(r_buf, h, sycl::read_only);
sycl::accessor g_acc(g_buf, h, sycl::read_only);
sycl::accessor b_acc(b_buf, h, sycl::read_only);
sycl::accessor out_acc(out_buf, h, sycl::write_only, sycl::no_init);
// FPGA-optimized kernel
// Using kernel_args_restrict tells the compiler that the input
// and output buffers won't alias.
h.single_task<Kernel>([=]() [[intel::kernel_args_restrict]] {
for (size_t i = 0; i < kInputSize; i++) {
out_acc[i] = Compute(r_acc[i], g_acc[i], b_acc[i]);
}
});
});
double exec_time = GetExecutionTime(e);
double inputMB = (kInputSize * sizeof(RGBType)) / (double)(1024 * 1024);
std::cout << "Kernel Throughput: " << (inputMB / exec_time) << "MB/s\n";
std::cout << "Exec Time: " << exec_time << "s, InputMB: " << inputMB
<< "MB\n";
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
}
int main() {
// input/output data
RGBVec r(kInputSize);
RGBVec g(kInputSize);
RGBVec b(kInputSize);
GreyVec out(kInputSize);
// generate random input data
srand(0);
for (size_t i = 0; i < kInputSize; i++) {
r[i] = static_cast<RGBType>(rand() % 256);
g[i] = static_cast<RGBType>(rand() % 256);
b[i] = static_cast<RGBType>(rand() % 256);
}
RunKernel(r, g, b, out);
bool passed = true;
// validate results
for (size_t i = 0; i < kInputSize; i++) {
GreyType golden = Compute(r[i], g[i], b[i]);
if (std::fabs(out[i] - golden) > 1e-4) {
std::cout << "Result mismatch:\n"
<< "out[" << i << "] = " << out[i] << "; golden = " << golden
<< '\n';
passed = false;
}
}
if (passed) {
std::cout << "PASSED: all kernel results are correct\n";
} else {
std::cout << "FAILED\n";
}
return passed ? 0 : 1;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/loop_coalesce/src/loop_coalesce.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <iomanip>
#include <iostream>
#include "exception_handler.hpp"
using namespace sycl;
// Matrix dimensions
constexpr size_t kNumRows = 4;
constexpr size_t kNumCols = 4;
constexpr size_t kNumElements = kNumRows * kNumCols;
// Total floating point ops performed by the kernel
constexpr size_t kTotalOps = (4 + (3*kNumCols)) * kNumElements;
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
template <int N> class KernelCompute;
// The kernel implements a matrix multiplication.
// This is not meant to be a high performance implementation on FPGA!
// It's just a simple kernel with nested loops to illustrate loop coalescing.
template <int coalesce_factor>
void MatrixMultiply(const std::vector<float> &matrix_a,
const std::vector<float> &matrix_b,
std::vector<float> &res) {
double kernel_time = 0.0;
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
try {
auto prop_list = property_list{property::queue::enable_profiling()};
queue q(selector, fpga_tools::exception_handler, prop_list);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
buffer buffer_in_a(matrix_a);
buffer buffer_in_b(matrix_b);
buffer buffer_out(res);
event e = q.submit([&](handler &h) {
accessor accessor_matrix_a(buffer_in_a, h, read_only);
accessor accessor_matrix_b(buffer_in_b, h, read_only);
accessor accessor_res(buffer_out, h, write_only, no_init);
// The kernel_args_restrict promises the compiler that this kernel's
// accessor arguments won't alias (i.e. non-overlapping memory regions).
h.single_task<class KernelCompute<coalesce_factor>>(
[=]() [[intel::kernel_args_restrict]] {
size_t idx = 0;
float a[kNumRows][kNumCols];
float b[kNumRows][kNumCols];
float tmp[kNumRows][kNumCols];
// The loop_coalesce instructs the compiler to attempt to "merge"
// coalesce_factor loop levels of this nested loop together.
// For example, a coalesce_factor of 2 turns this into a single loop.
[[intel::loop_coalesce(coalesce_factor)]]
for (size_t i = 0; i < kNumRows; ++i) {
for (size_t j = 0; j < kNumCols; ++j) {
a[i][j] = accessor_matrix_a[idx];
b[i][j] = accessor_matrix_b[idx];
tmp[i][j] = 0.0;
idx++;
}
}
// Applying loop_coalesce to the outermost loop of a deeply nested
// loop results coalescing from the outside in.
// For example, a coalesce_factor of 2 coalesces the "i" and "j" loops,
// making a doubly nested loop.
[[intel::loop_coalesce(coalesce_factor)]]
for (size_t i = 0; i < kNumRows; ++i) {
for (size_t j = 0; j < kNumCols; ++j) {
float sum = 0.0f;
for (size_t k = 0; k < kNumCols; ++k) {
sum += a[i][k] * b[k][j];
}
tmp[i][j] = sum;
}
}
idx = 0;
[[intel::loop_coalesce(coalesce_factor)]]
for (size_t i = 0; i < kNumRows; ++i) {
for (size_t j = 0; j < kNumCols; ++j) {
accessor_res[idx] = tmp[i][j];
idx++;
}
}
});
});
// Kernel profiling data
double start = e.get_profiling_info<info::event_profiling::command_start>();
double end = e.get_profiling_info<info::event_profiling::command_end>();
// convert nanoseconds to microseconds
kernel_time = (double)(end - start) * 1e-3;
} catch (exception const &exc) {
std::cerr << "Caught synchronous SYCL exception:\n" << exc.what() << '\n';
if (exc.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
std::cout << "Loop Coalesce: " << coalesce_factor
<< " -- kernel time : " << kernel_time << " microseconds\n";
std::cout << "Throughput for kernel with coalesce_factor " << coalesce_factor
<< ": ";
std::cout << std::fixed << std::setprecision(0)
<< (((double)kTotalOps * sizeof(float) * 1e-3f) /
(kernel_time * 1e-6f)) << "KB/s\n";
}
int main() {
std::vector<float> matrix_a(kNumElements);
std::vector<float> matrix_b(kNumElements);
std::vector<float> matrix_output_no_col(kNumElements);
std::vector<float> matrix_output(kNumElements);
// Specify the matrices to be multiplied
for (size_t i = 0; i < kNumRows; i++) {
size_t pos = i * kNumCols;
// Initialize A as identity matrix
matrix_a[i + pos] = 1.0;
for (size_t j = 0; j < kNumCols; j++) {
matrix_b[pos + j] = i * j + 1;
}
}
// Two versions of the simple matrix multiply kernel will be enqueued:
// - with coalesce_factor=1 (i.e. no loop coalescing)
// - with coalesce_factor=2 (coalesce two nested levels)
MatrixMultiply<1>(matrix_a, matrix_b, matrix_output_no_col);
MatrixMultiply<2>(matrix_a, matrix_b, matrix_output);
// Correctness check
bool passed = true;
for (size_t i = 0; i < kNumRows; i++) {
size_t pos = i * kNumCols;
for (size_t j = 0; j < kNumCols; j++) {
float val_noCol = matrix_output_no_col[pos + j];
float val = matrix_output[pos + j];
if (val_noCol != i * j + 1 || val != i * j + 1) {
std::cout << "FAILED: The results are incorrect\n";
passed = false;
}
}
}
if (passed) {
std::cout << "PASSED: The results are correct\n";
return 0;
} else {
std::cout << "FAILED\n";
return -1;
}
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/read_only_cache/src/read_only_cache.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <chrono>
#include "exception_handler.hpp"
using namespace sycl;
namespace ext_oneapi = sycl::ext::oneapi;
constexpr int kLUTSize = 512; // Size of the LUT.
constexpr int kNumOutputs = 131072; // Number of outputs.
constexpr double kNs = 1e9; // number of nanoseconds in a second
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class SqrtTest;
// Below are three different random number generators that are used to generate
// arbitrary indices to be used when accessing the LUT. Each generator is
// implemented using a "Linear-Feedback Shift Register" (LFSR).
uint16_t rand1(uint16_t &index, uint16_t &bits) {
bits = ((index >> 0) ^ (index >> 3) ^ (index >> 4) ^ (index >> 5)) & 1u;
return index = (index >> 1) | (bits << 15);
}
uint16_t rand2(uint16_t &index, uint16_t &bits) {
bits = ((index >> 0) ^ (index >> 1) ^ (index >> 2) ^ (index >> 3)) & 1u;
return index = (index >> 1) | (bits << 15);
}
uint16_t rand3(uint16_t &index, uint16_t &bits) {
bits = ((index >> 0) ^ (index >> 1) ^ (index >> 2) ^ (index >> 5)) & 1u;
return index = (index >> 1) | (bits << 15);
}
event runSqrtTest(sycl::queue &q, const std::vector<float> &sqrt_lut_vec,
std::vector<float> &output_vec) {
buffer sqrt_lut_buf(sqrt_lut_vec);
buffer output_buf(output_vec);
event e = q.submit([&](handler &h) {
accessor sqrt_lut(sqrt_lut_buf, h, read_only,
ext_oneapi::accessor_property_list{ext_oneapi::no_alias});
accessor output(
output_buf, h, write_only,
ext_oneapi::accessor_property_list{ext_oneapi::no_alias, no_init});
h.single_task<SqrtTest>([=]() {
uint16_t index = 0xFFFu; // An arbitrary non-zero starting state
uint16_t bits = 0;
for (int i = 0; i < kNumOutputs; i++)
output[i] = sqrt_lut[rand1(index, bits) % kLUTSize];
for (int i = 0; i < kNumOutputs; i++)
output[i] += sqrt_lut[rand2(index, bits) % kLUTSize];
for (int i = 0; i < kNumOutputs; i++)
output[i] += sqrt_lut[rand3(index, bits) % kLUTSize];
});
});
return e;
}
int main() {
// Host and kernel profiling
event e;
unsigned long t1_kernel, t2_kernel;
double time_kernel;
// Create input and output vectors
std::vector<float> sqrt_lut_vec(kLUTSize);
std::vector<float> output_vec(kNumOutputs);
for (int i = 0; i < kLUTSize; ++i) {
sqrt_lut_vec[i] = sycl::sqrt((float) i);
}
// Create queue, get platform and device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
try {
auto prop_list =
sycl::property_list{sycl::property::queue::enable_profiling()};
sycl::queue q(selector, fpga_tools::exception_handler, prop_list);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
std::cout << "\nSQRT LUT size: " << kLUTSize << "\n";
std::cout << "Number of outputs: " << kNumOutputs << "\n";
e = runSqrtTest(q, sqrt_lut_vec, output_vec);
e.wait();
// Compute kernel execution time
t1_kernel = e.get_profiling_info<info::event_profiling::command_start>();
t2_kernel = e.get_profiling_info<info::event_profiling::command_end>();
time_kernel = (t2_kernel - t1_kernel) / kNs;
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
// Compute the reference solution
uint16_t index = 0xFFFu; // An arbitrary non-zero starting state
uint16_t bits = 0;
float gold[kNumOutputs];
for (int i = 0; i < kNumOutputs; ++i)
gold[i] = sqrt_lut_vec[rand1(index, bits) % kLUTSize];
for (int i = 0; i < kNumOutputs; ++i)
gold[i] += sqrt_lut_vec[rand2(index, bits) % kLUTSize];
for (int i = 0; i < kNumOutputs; ++i)
gold[i] += sqrt_lut_vec[rand3(index, bits) % kLUTSize];
// Verify output and print pass/fail
bool passed = true;
int num_errors = 0;
for (int b = 0; b < kNumOutputs; b++) {
if (num_errors < 10 && output_vec[b] != gold[b]) {
passed = false;
std::cerr << " (mismatch, expected " << gold[b] << ")\n";
num_errors++;
}
}
if (passed) {
std::cout << "Verification PASSED\n\n";
// Report host execution time and throughput
std::cout.setf(std::ios::fixed);
// Input size in MB
constexpr double num_mb =
(static_cast<double>(kNumOutputs * sizeof(uint32_t))) / (1024 * 1024);
// Report kernel execution time and throughput
std::cout << "Kernel execution time: " << time_kernel << " seconds\n";
#if defined(CACHE_ENABLED)
std::cout << "Kernel throughput with the read-only cache: "
#else
std::cout << "Kernel throughput: "
#endif
<< (num_mb / time_kernel) << " MB/s\n\n";
} else {
std::cerr << "Verification FAILED\n";
return 1;
}
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/pipes/src/pipes.cpp | #include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "exception_handler.hpp"
using namespace sycl;
using ProducerToConsumerPipe = ext::intel::pipe< // Defined in the SYCL headers.
class ProducerConsumerPipeId, // An identifier for the pipe.
int, // The type of data in the pipe.
4>; // The capacity of the pipe.
// Forward declare the kernel names in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class ProducerTutorial;
class ConsumerTutorial;
// The Producer kernel reads data from a SYCL buffer and writes it to
// a pipe. This transfers the input data from the host to the Consumer kernel
// that is running concurrently.
event Producer(queue &q, buffer<int, 1> &input_buffer) {
std::cout << "Enqueuing producer...\n";
auto e = q.submit([&](handler &h) {
accessor input_accessor(input_buffer, h, read_only);
size_t num_elements = input_buffer.size();
h.single_task<ProducerTutorial>([=]() {
for (size_t i = 0; i < num_elements; ++i) {
ProducerToConsumerPipe::write(input_accessor[i]);
}
});
});
return e;
}
// An example of some simple work, to be done by the Consumer kernel
// on the input data
int ConsumerWork(int i) { return i * i; }
// The Consumer kernel reads data from the pipe, performs some work
// on the data, and writes the results to an output buffer
event Consumer(queue &q, buffer<int, 1> &out_buf) {
std::cout << "Enqueuing consumer...\n";
auto e = q.submit([&](handler &h) {
accessor out_accessor(out_buf, h, write_only, no_init);
size_t num_elements = out_buf.size();
h.single_task<ConsumerTutorial>([=]() {
for (size_t i = 0; i < num_elements; ++i) {
// read the input from the pipe
int input = ProducerToConsumerPipe::read();
// do work on the input
int answer = ConsumerWork(input);
// write the result to the output buffer
out_accessor[i] = answer;
}
});
});
return e;
}
int main(int argc, char *argv[]) {
// Default values for the buffer size is based on a reasonable runtime for
// different targets
#if defined(FPGA_SIMULATOR)
size_t array_size = 1 << 7;
#elif defined(FPGA_EMULATOR)
size_t array_size = 1 << 12;
#else
size_t array_size = 1 << 20;
#endif
// allow the user to change the buffer size at the command line
if (argc > 1) {
std::string option(argv[1]);
if (option == "-h" || option == "--help") {
std::cout << "Usage: \n./pipes <data size>\n\nFAILED\n";
return 1;
} else {
array_size = atoi(argv[1]);
}
}
std::cout << "Input Array Size: " << array_size << "\n";
std::vector<int> producer_input(array_size, -1);
std::vector<int> consumer_output(array_size, -1);
// Initialize the input data with random numbers smaller than 46340.
// Any number larger than this will have integer overflow when squared.
constexpr int max_val = 46340;
for (size_t i = 0; i < array_size; i++) {
producer_input[i] = rand() % max_val;
}
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
event producer_event, consumer_event;
try {
// property list to enable SYCL profiling for the device queue
auto props = property_list{property::queue::enable_profiling()};
// create the device queue with SYCL profiling enabled
queue q(selector, fpga_tools::exception_handler, props);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
// create the producer and consumer buffers
buffer producer_buffer(producer_input);
buffer consumer_buffer(consumer_output);
// Run the two kernels concurrently. The Producer kernel sends
// data via a pipe to the Consumer kernel.
producer_event = Producer(q, producer_buffer);
consumer_event = Consumer(q, consumer_buffer);
} catch (exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
// At this point, the producer_buffer and consumer_buffer have gone out
// of scope. This will cause their destructors to be called, which will in
// turn block until the Producer and Consumer kernels are finished and the
// output data is copied back to the host. Therefore, at this point it is
// safe and correct to access the contents of the consumer_output vector.
// start and end time of the Producer kernel
double p_start =
producer_event
.get_profiling_info<sycl::info::event_profiling::command_start>();
double p_end =
producer_event
.get_profiling_info<sycl::info::event_profiling::command_end>();
// start and end time of the Consumer kernel
double c_start =
consumer_event
.get_profiling_info<sycl::info::event_profiling::command_start>();
double c_end =
consumer_event
.get_profiling_info<sycl::info::event_profiling::command_end>();
// the total application time
double total_time_ms = (c_end - p_start) * 1e-6;
// the input size in MBs
double input_size_mb = array_size * sizeof(int) * 1e-6;
// the total application throughput
double throughput_mbs = input_size_mb / (total_time_ms * 1e-3);
// Print the start times normalized to the start time of the producer.
// i.e. the producer starts at 0ms and the other start/end times are
// reported as differences to that number (+X ms).
std::cout << std::fixed << std::setprecision(3);
std::cout << "\n";
std::cout << "Profiling Info\n";
std::cout << "\tProducer:\n";
std::cout << "\t\tStart time: " << 0 << " ms\n";
std::cout << "\t\tEnd time: +" << (p_end - p_start) * 1e-6 << " ms\n";
std::cout << "\t\tKernel Duration: " << (p_end - p_start) * 1e-6 << " ms\n";
std::cout << "\tConsumer:\n";
std::cout << "\t\tStart time: +" << (c_start - p_start) * 1e-6 << " ms\n";
std::cout << "\t\tEnd time: +" << (c_end - p_start) * 1e-6 << " ms\n";
std::cout << "\t\tKernel Duration: " << (c_end - c_start) * 1e-6 << " ms\n";
std::cout << "\tDesign Duration: " << total_time_ms << " ms\n";
std::cout << "\tDesign Throughput: " << throughput_mbs << " MB/s\n";
std::cout << "\n";
// Verify the result
for (size_t i = 0; i < array_size; i++) {
if (consumer_output[i] != ConsumerWork(producer_input[i])) {
std::cout << "input = " << producer_input[i]
<< " expected: " << ConsumerWork(producer_input[i])
<< " got: " << consumer_output[i] << "\n";
std::cout << "FAILED: The results are incorrect\n";
return 1;
}
}
std::cout << "PASSED: The results are correct\n";
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/scheduler_target_fmax/src/scheduler_target_fmax.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "exception_handler.hpp"
using namespace sycl;
constexpr unsigned kSeed = 1313;
// Forward declare the kernel names in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class Default;
class Fmax480;
class Fmax240;
class Fmax240II;
// Runs the Kernel
void KernelRun(size_t size, const std::vector<char> &input_data,
std::vector<unsigned> &output_data) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
try {
// create the SYCL device queue
queue q(selector, fpga_tools::exception_handler,
property::queue::enable_profiling{});
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
buffer input_buffer(input_data);
buffer output_buffer(output_data);
q.submit([&](handler &h) {
accessor input_a(input_buffer, h, read_only);
accessor output_a(output_buffer, h, write_only, no_init);
h.single_task<Default>([=]() [[intel::kernel_args_restrict]] {
unsigned hash = 0;
for (size_t i = 0; i < size; i++) {
hash = (hash * kSeed) + input_a[i];
}
output_a[0] = hash;
});
});
q.submit([&](handler &h) {
accessor input_a(input_buffer, h, read_only);
accessor output_a(output_buffer, h, write_only, no_init);
h.single_task<Fmax480>([=]() [[intel::kernel_args_restrict,
intel::scheduler_target_fmax_mhz(480)]] {
unsigned hash = 0;
for (size_t i = 0; i < size; i++) {
hash = (hash * kSeed) + input_a[i];
}
output_a[1] = hash;
});
});
q.submit([&](handler &h) {
accessor input_a(input_buffer, h, read_only);
accessor output_a(output_buffer, h, write_only, no_init);
h.single_task<Fmax240>([=]() [[intel::kernel_args_restrict,
intel::scheduler_target_fmax_mhz(240)]] {
unsigned hash = 0;
for (size_t i = 0; i < size; i++) {
hash = (hash * kSeed) + input_a[i];
}
output_a[2] = hash;
});
});
q.submit([&](handler &h) {
accessor input_a(input_buffer, h, read_only);
accessor output_a(output_buffer, h, write_only, no_init);
h.single_task<Fmax240II>([=]() [[intel::kernel_args_restrict,
intel::scheduler_target_fmax_mhz(240)]] {
unsigned hash = 0;
[[intel::initiation_interval(1)]] // NO-FORMAT: Attribute
for (size_t i = 0; i < size; i++) {
hash = (hash * kSeed) + input_a[i];
}
output_a[3] = hash;
});
});
} catch (exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
}
inline unsigned BKDRHashGolden(std::vector<char> input_data) {
unsigned hash = 0;
for (int i = 0; i < input_data.size(); ++i) {
hash = (hash * kSeed) + input_data[i];
}
return hash;
}
int main() {
// input string "qr6KUBBmLtVUlX9"
std::vector<char> input_data = {'q', 'r', '6', 'K', 'U', 'B', 'B', 'm',
'L', 't', 'V', 'U', 'l', 'X', '9'};
std::vector<unsigned> output_data(4);
KernelRun(input_data.size(), input_data, output_data);
bool passed = true;
unsigned golden = BKDRHashGolden(input_data);
if (output_data[0] != golden) {
std::cout << "Kernel Default Output Mismatch: \n"
<< "output = " << output_data[0] << ", golden = " << golden
<< "\n";
passed = false;
}
if (output_data[1] != golden) {
std::cout << "Kernel Fmax480 Output Mismatch: \n"
<< "output = " << output_data[1] << ", golden = " << golden
<< "\n";
passed = false;
}
if (output_data[2] != golden) {
std::cout << "Kernel Fmax240 Output Mismatch: \n"
<< "output = " << output_data[2] << ", golden = " << golden
<< "\n";
passed = false;
}
if (output_data[3] != golden) {
std::cout << "Kernel Fmax240II Output Mismatch: \n"
<< "output = " << output_data[3] << ", golden = " << golden
<< "\n";
passed = false;
}
if (passed) {
std::cout << "PASSED: all kernel results are correct.\n";
} else {
std::cout << "FAILED\n";
}
return passed ? 0 : 1;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/loop_initiation_interval/src/loop_initiation_interval.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <vector>
#include "exception_handler.hpp"
using namespace sycl;
// short initialization loop trip count
constexpr size_t kInitLoopSize = 10;
// long-running loop trip count
#if defined(FPGA_SIMULATOR)
constexpr size_t kLongLoopSize = 100;
#else
constexpr size_t kLongLoopSize = 10000;
#endif
// problem input size
#if defined(FPGA_EMULATOR)
constexpr size_t kInputSize = 10000;
#elif defined(FPGA_SIMULATOR)
constexpr size_t kInputSize = 1;
#else
constexpr size_t kInputSize = 1000000;
#endif
// Forward declare the kernel name in the global scope
// This FPGA best practice reduces name mangling in the optimization reports
class SimpleMath;
int SomethingComplicated(int x) { return (int)sycl::sqrt((float)x); }
// The function the kernel will compute
// The golden result will be computed on the host to check the kernel result
int GoldenResult(int num) {
for (size_t i = 0; i < kInitLoopSize; i++) {
num += 1;
num ^= 1;
num += 1;
num ^= 1;
num += 1;
num ^= 1;
num += 1;
num ^= 1;
num += 1;
num ^= 1;
}
int sum = 0;
for (size_t j = 0; j < kLongLoopSize; j++) {
sum += SomethingComplicated(num + j);
}
return sum;
}
// Return the execution time of the event, in seconds
double GetExecutionTime(const event &e) {
double start_k = e.get_profiling_info<info::event_profiling::command_start>();
double end_k = e.get_profiling_info<info::event_profiling::command_end>();
double kernel_time = (end_k - start_k) * 1e-9; // ns to s
return kernel_time;
}
void RunKernel(std::vector<int> &in, std::vector<int> &out) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
try {
// create the SYCL device queue
queue q(selector, fpga_tools::exception_handler,
property::queue::enable_profiling{});
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
buffer in_buf(in);
buffer out_buf(out);
// submit the kernel
auto e = q.submit([&](handler &h) {
accessor in_acc(in_buf, h, read_only);
accessor out_acc(out_buf, h, write_only, no_init);
// FPGA-optimized kernel
// Using kernel_args_restrict tells the compiler that the input
// and output buffers won't alias.
h.single_task<SimpleMath>([=]() [[intel::kernel_args_restrict]] {
for (size_t i = 0; i < kInputSize; i++) {
int num = in_acc[i];
// All kernels share a common clock domain, thus this design needs to
// be compiled twice to showcase the same design with different fMAX
// If ENABLE_II is defined, the intel::initiation_interval attribute
// will be set for the next loop, the short initialization loop
// Explicitly setting the II for a loop will tell the compiler to
// schedule the loop while enforcing the set II, overriding the
// default heuristic of finding the minimum II * (1/fMAX) Relaxing the
// II on a short loop with a long feedback path will remove the
// bottleneck the loop had on the maximum achievable fMAX of the
// design. The default targeted fMAX is target dependent,
// so different IIs need to be specified so the
// compiler can schedule the loop such that it does not restrict the
// maximum fMAX
#if defined(ENABLE_II)
#if defined(A10)
[[intel::initiation_interval(3)]]
#elif defined(S10)
[[intel::initiation_interval(5)]]
#elif defined(Agilex7)
[[intel::initiation_interval(5)]]
#else
static_assert(false, "Unknown FPGA Architecture!");
#endif
#endif
// ---------------------------
// Short initialization loop
// ---------------------------
// The variable "num" has a loop carried dependency with a long
// feedback path: The first operation on "num" in a given iteration
// depends on the value of "num" calculated in the last operation of a
// previous iteration. This leads to a classic fMAX-II tradeoff
// situation. The compiler can achieve an II of 1 and a low fMAX, or
// it can pipeline the arithmetic logic to improve fMAX at the expense
// of II. By default the compiler will select an II of 1 after
// optimizing for minimum II * (1/fMAX), which is not optimal for
// whole design as fMAX is a system-wide constraint and this loop has
// few iterations.
for (size_t j = 0; j < kInitLoopSize; j++) {
num += 1;
num ^= 1;
num += 1;
num ^= 1;
num += 1;
num ^= 1;
num += 1;
num ^= 1;
num += 1;
num ^= 1;
}
int sum = 0;
// The intel::initiation_interval attribute is added here to "assert"
// that II=1 for this loop. Even though we fully expect the compiler
// to achieve II=1 here by default, some developers find it helpful to
// include the attribute to "document" this expectation. If a future
// code change causes an unexpected II regression, the compiler will
// error out. Without the intel::initiation_interval attribute, an II
// regression may go unnoticed.
#if defined(ENABLE_II)
[[intel::initiation_interval(1)]]
#endif
// ---------------------------
// Long running loop
// ---------------------------
// The variable "sum" has a loop carried dependency with a feedback
// path, although not as long as the feedback path of "num". The first
// operation on "sum" in a given iteration depends on the value of
// "sum" calculated in the last operation of a previous iteration The
// compiler is able to achieve an II of 1 and the default targeted
// fMAX for Arria® 10, but falls a little short on Stratix® 10. The
// intel::initiation_interval attribute should not be used to relax
// the II of this loop as the drop in occupancy of the long loop is
// not worth achieving a slightly higher fMAX
for (size_t k = 0; k < kLongLoopSize; k++) {
sum += SomethingComplicated(num + k);
}
out_acc[i] = sum;
}
});
});
double exec_time = GetExecutionTime(e);
double inputMB = (kInputSize * sizeof(int)) / (double)(1024 * 1024);
#if defined(ENABLE_II)
std::cout << "Kernel_ENABLE_II Throughput: " << (inputMB / exec_time)
<< "MB/s\n";
#else
std::cout << "Kernel Throughput: " << (inputMB / exec_time) << "MB/s\n";
#endif
std::cout << "Exec Time: " << exec_time << "s , InputMB: " << inputMB
<< "MB\n";
} catch (exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
}
int main() {
// seed random number generator
srand(0);
// input/output data
std::vector<int> in(kInputSize);
std::vector<int> out(kInputSize);
// Conservative max to avoid addition overflow
constexpr int kRandMax = 1 << 10;
// generate random input data
for (size_t i = 0; i < kInputSize; i++) {
in[i] = rand() % kRandMax;
}
// Run kernel once. Since fMAX is a global constraint, we cannot run two
// kernels demonstrating the use of the intel::initiation_interval attribute
// since the kernel without the intel::initiation_interval attribute would
// restrict the global fMAX, thus affecting the design with the
// intel::initiation_interval attribute. Rely on the preprocessor defines to
// change the kernel behaviour.
RunKernel(in, out);
// validate results
for (size_t i = 0; i < kInputSize; i++) {
if (out[i] != GoldenResult(in[i])) {
std::cout << "FAILED: mismatch at entry " << i
<< " of 'SimpleMath' kernel output\n";
return 1;
}
}
std::cout << "PASSED\n";
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/max_interleaving/src/max_interleaving.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <array>
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <iomanip>
#include <iostream>
#include "exception_handler.hpp"
using namespace sycl;
#if defined(FPGA_SIMULATOR) || defined(FPGA_EMULATOR)
// Simulator runs too slowly for large array sizes
// Emulator has stack issues for large array sizes -
// (malloc can be used but is out of scope of this tutorial)
constexpr size_t kSize = 32;
#else
constexpr size_t kSize = 512;
#endif
constexpr float kErrorThreshold = 0.5;
constexpr int kTotalOps = 4 * kSize * kSize;
using FloatArray = std::array<float, kSize>;
using TwoDimFloatArray = std::array<float, kSize*kSize>;
using FloatScalar = std::array<float, 1>;
// an example complicated operation that creates a long critical path of
// combinational logic from the use of the parameter values to the result
float SomethingComplicated(float x, float y) { return sycl::sqrt(x) * sycl::sqrt(y); }
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
template <int interleaving>
class KernelCompute;
// Launch a kernel on the device specified by selector.
// The kernel's functionality is designed to show the
// performance impact of the max_interleaving attribute.
template <int interleaving>
void Transform(const TwoDimFloatArray &array_a, FloatArray &array_r) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
double kernel_time = 0.0;
try {
queue q(selector, fpga_tools::exception_handler,
property::queue::enable_profiling{});
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
buffer array_a_buffer(array_a);
buffer array_r_buffer(array_r);
event e = q.submit([&](handler &h) {
accessor array_a_accessor(array_a_buffer, h, read_only);
accessor accessor_array_r(array_r_buffer, h, write_only, no_init);
h.single_task<KernelCompute<interleaving>>([=]()
[[intel::kernel_args_restrict]] {
float temp_a[kSize*kSize];
float temp_r[kSize];
for (size_t i = 0; i < kSize; i++) {
for (size_t j = 0; j < kSize; j++) {
temp_a[i*kSize+j] = array_a_accessor[i*kSize+j];
}
temp_r[i] = 1.0;
}
// A simple row reduction where row i of temp_a is summed and
// stored in temp_r[i].
// Notice how temp_r[i] is a loop carried dependency in the inner loop as it is updated
// every iteration. As a result, the *inner loop II is very high* as a new iteration from
// the *same* outer loop invocation must wait for the previous iteration to finish updating
// temp_r[i].
// However, notice how *no* loop carried memory dependency exists with respect to
// the outer loop - for different i-iterations, the temp_r array is read and written to
// in different locations.
// The lack of outer loop carried memory dependencies and a high inner loop II is what
// allows interleaving to happen - where multiple invocations of the inner loop
// concurrently execute on the same inner loop hardware. This is like pipelining,
// but each iteration executing in the inner loop is from *different* invocations.
outer:
for (int i = kSize - 1; i >= 0; i--) {
// You can explicitly disable interleaving with this attribute by providing `1` as
// a parameter. `0` keeps it enabled, so long as interleaving is possible.
// This may result in area savings at the cost of throughput, which could
// be useful for non-critical data paths in low-area settings.
inner:
[[intel::max_interleaving(interleaving)]]
for (int j = kSize - 1; j >= 0; j--) {
temp_r[i] +=
SomethingComplicated(temp_a[i * kSize + j], temp_r[i]);
}
// One final note - the loop induction variables decrease (i--) instead of increase (i++)
// in these two loops to prevent loop fusion optimizations, which makes it harder to
// keep track of loops in the optimization reports. Interleaving will still occur if
// `i` and `j` were instead incremented.
}
for (size_t i = 0; i < kSize; i++) {
accessor_array_r[i] = temp_r[i];
}
});
});
// SYCL event profiling allows the kernel execution to be timed
double start = e.get_profiling_info<info::event_profiling::command_start>();
double end = e.get_profiling_info<info::event_profiling::command_end>();
kernel_time = (double)(end - start) * 1e-6f;
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:" << '\n' << e.what() << '\n';
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
// The performance of the kernel is measured in GFlops, based on:
// 1) the number of floating-point operations performed by the kernel.
// This can be calculated easily for the simple example kernel.
// 2) the kernel execution time reported by SYCL event profiling.
std::cout << "Max interleaving " << interleaving << " "
<< "kernel time : " << kernel_time << " ms\n";
std::cout << "Throughput for kernel with max_interleaving " << interleaving
<< ": ";
std::cout << std::fixed << std::setprecision(3)
#if defined(FPGA_SIMULATOR)
<< ((double)(kTotalOps) / kernel_time) << " KFlops\n";
#else
<< ((double)(kTotalOps) / kernel_time) / 1e6f << " GFlops\n";
#endif
}
// Calculates the expected results. Used to verify that the kernel
// is functionally correct.
void GoldenResult(const TwoDimFloatArray &A, FloatArray &R) {
outer: for (int i = kSize - 1; i >= 0; i--) {
inner: for (int j = kSize - 1; j >= 0; j--) {
R[i] +=
SomethingComplicated(A[i * kSize + j], R[i]);
}
}
}
int main() {
TwoDimFloatArray indata_A;
FloatArray outdata_R_compute_0;
FloatArray outdata_R_compute_1;
FloatArray outdata_R_golden;
// initialize the input data
srand(7);
for (size_t i = 0; i < kSize; i++) {
for (size_t j = 0; j < kSize; j++) {
indata_A[i*kSize+j] = (float)(rand() % 32);
}
outdata_R_golden[i] = 1.0;
}
// Run the kernel with two different values of the max_interleaving
// attribute:
// Enabled - max_interleaving = 0
// Disabled - max_interleaving = 1
// When interleaving is disabled, runtime performance may decrease while
// hardware resources may increase (see README.md for details
// on confirming this difference in hardware resource usage in
// the reports).
Transform<0>(indata_A, outdata_R_compute_0);
Transform<1>(indata_A, outdata_R_compute_1);
// compute the actual result here
GoldenResult(indata_A, outdata_R_golden);
// error check for Transform<0>
bool failed = false;
for (unsigned i = 0; i < kSize; i++) {
if (std::abs(outdata_R_compute_0[i] - outdata_R_golden[i]) >
kErrorThreshold) {
std::cout << "error at [" << i << "]: " << outdata_R_compute_0[i]
<< " != " << outdata_R_golden[i] << '\n';
failed = true;
}
}
// error check for Transform<1>
for (unsigned i = 0; i < kSize; i++) {
if (std::abs(outdata_R_compute_1[i] - outdata_R_golden[i]) >
kErrorThreshold) {
std::cout << "error at [" << i << "]: " << outdata_R_compute_1[i]
<< " != " << outdata_R_golden[i] << '\n';
failed = true;
}
}
if (failed) {
std::cout << "FAILED: The results are incorrect\n";
return 1;
} else {
std::cout << "PASSED: The results are correct\n";
return 0;
}
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/ip_authoring_interfaces/streaming_data_interfaces/src/streaming_data_interfaces.cpp | #include <iostream>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/ext/intel/prototype/pipes_ext.hpp>
#include <sycl/sycl.hpp>
#include "exception_handler.hpp"
// limit pixel values to this value, or less
constexpr int kThreshold = 200;
// Forward declare the kernel and pipe names
// (this prevents unwanted name mangling in the optimization report)
class InStream;
class OutStream;
class Threshold;
// StreamingBeat struct enables sideband signals in Avalon streaming interface
using StreamingBeatT = sycl::ext::intel::experimental::StreamingBeat<
unsigned short, // type carried over this Avalon streaming interface's data
// signal
true, // enable startofpacket and endofpacket signals
false>; // disable the empty signal
// Pipe properties
using PipePropertiesT = decltype(sycl::ext::oneapi::experimental::properties(
sycl::ext::intel::experimental::ready_latency<0>,
sycl::ext::intel::experimental::bits_per_symbol<16>,
sycl::ext::intel::experimental::uses_valid<true>,
sycl::ext::intel::experimental::first_symbol_in_high_order_bits<true>,
sycl::ext::intel::experimental::protocol_avalon_streaming_uses_ready));
// Image streams
using InPixelPipe = sycl::ext::intel::experimental::pipe<
InStream, // An identifier for the pipe
StreamingBeatT, // The type of data in the pipe
0, // The capacity of the pipe
PipePropertiesT // Customizable pipe properties
>;
using OutPixelPipe = sycl::ext::intel::experimental::pipe<
OutStream, // An identifier for the pipe
StreamingBeatT, // The type of data in the pipe
0, // The capacity of the pipe
PipePropertiesT // Customizable pipe properties
>;
// A kernel that thresholds pixel values in an image over a stream. Uses start
// of packet and end of packet signals on the streams to determine the beginning
// and end of the image.
struct ThresholdKernel {
void operator()() const {
bool start_of_packet = false;
bool end_of_packet = false;
while (!end_of_packet) {
// Read in next pixel
StreamingBeatT in_beat = InPixelPipe::read();
auto pixel = in_beat.data;
start_of_packet = in_beat.sop;
end_of_packet = in_beat.eop;
// Threshold
if (pixel > kThreshold)
pixel = kThreshold;
// Write out result
StreamingBeatT out_beat(pixel, start_of_packet, end_of_packet);
OutPixelPipe::write(out_beat);
}
}
};
int main() {
try {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
sycl::queue q(selector, fpga_tools::exception_handler);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
// Test image dimensions
unsigned int width = 16;
unsigned int height = 16;
// Generate pixel data
for (int i = 0; i < (width * height); ++i) {
bool start_of_packet = (i == 0);
bool end_of_packet = (i == ((width * height) - 1));
StreamingBeatT in_beat(i, start_of_packet, end_of_packet);
InPixelPipe::write(q, in_beat);
}
// Call the kernel
q.single_task<Threshold>(ThresholdKernel{});
// Check that output pixels are below the threshold
bool passed = true;
for (int i = 0; i < (width * height); ++i) {
StreamingBeatT out_beat = OutPixelPipe::read(q);
passed &= (out_beat.data <= kThreshold);
}
std::cout << (passed ? "PASSED" : "FAILED") << std::endl;
return passed ? EXIT_SUCCESS : EXIT_FAILURE;
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
std::terminate();
}
} | cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/ip_authoring_interfaces/invocation_interfaces/src/reg_map_lambda.cpp | // oneAPI headers
#include <sycl/ext/intel/ac_types/ac_int.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include "exception_handler.hpp"
using MyUInt5 = ac_int<5, false>;
// Forward declare the kernel names in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class LambdaRegMap;
/////////////////////////////////////////
void LambdaRegMapKernel(sycl::queue &q, int *input, int *output, MyUInt5 n) {
// A kernel with a register map invocation interface can also independently
// have streaming kernel arguments, when annotated by 'conduit' property.
sycl::ext::oneapi::experimental::annotated_arg<
MyUInt5, decltype(sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::conduit})>
n_annotated = n;
// Without passing a properties object argument, the compiler will infer a
// register-mapped invocation interface.
q.single_task<LambdaRegMap>([=] {
// For annotated_arg of ac_int type, explicitly cast away the annotated_arg
// to prevent compiler error when using methods or accessing members.
for (MyUInt5 i = 0; i < ((MyUInt5)n_annotated).slc<5>(0); i++) {
output[i] = input[i] * (input[i] + 1);
}
}).wait();
std::cout << "\t Done" << std::endl;
}
int main(int argc, char *argv[]) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
bool passed = true;
MyUInt5 count = 16;
if (argc > 1) count = atoi(argv[1]);
if (count <= 0) {
std::cerr << "ERROR: 'count' must be positive" << std::endl;
return 1;
}
try {
// create the device queue
sycl::queue q(selector, fpga_tools::exception_handler);
// make sure the device supports USM host allocations
sycl::device d = q.get_device();
// Print out the device information.
std::cout << "Running on device: "
<< q.get_device().get_info<sycl::info::device::name>().c_str()
<< std::endl;
if (!d.has(sycl::aspect::usm_host_allocations)) {
std::cerr << "ERROR: The selected device does not support USM host"
<< " allocations" << std::endl;
return 1;
}
int *input = sycl::malloc_host<int>(count, q);
int *lambda_register_map_out = sycl::malloc_host<int>(count, q);
int *golden_out = sycl::malloc_host<int>(count, q);
// test that mallocs did not return nullptr
assert(input);
assert(lambda_register_map_out);
assert(golden_out);
// create input and golden output data
for (MyUInt5 i = 0; i < count; i++) {
input[i] = rand() % 77;
golden_out[i] = (int)(input[i] * (input[i] + 1));
lambda_register_map_out[i] = 0;
}
// validation lambda
auto validate = [](int *golden_out, int *lambda_register_map_out,
MyUInt5 count) {
for (MyUInt5 i = 0; i < count; i++) {
if (lambda_register_map_out[i] != golden_out[i]) {
std::cout << "lambda_register_map_out[" << i << "] != golden_out["
<< i << "]"
<< " (" << lambda_register_map_out[i]
<< " != " << golden_out[i] << ")" << std::endl;
return false;
}
}
return true;
};
// Launch the kernel with a register map invocation interface implemented in
// the lambda programming model
std::cout << "Running the kernel with register map invocation interface "
"implemented in the lambda programming model"
<< std::endl;
LambdaRegMapKernel(q, input, lambda_register_map_out, count);
passed &= validate(golden_out, lambda_register_map_out, count);
std::cout << std::endl;
sycl::free(input, q);
sycl::free(lambda_register_map_out, q);
sycl::free(golden_out, q);
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
std::terminate();
}
if (passed) {
std::cout << "PASSED\n";
return 0;
} else {
std::cout << "FAILED\n";
return 1;
}
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/ip_authoring_interfaces/invocation_interfaces/src/stream_functor.cpp | // oneAPI headers
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include "exception_handler.hpp"
// Forward declare the kernel names in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class FunctorStream;
struct Point {
int x;
char y;
};
/////////////////////////////////////////
struct FunctorStreamIP {
// Annotate kernel argument with 'conduit' property
// to specify it to be a streaming kernel argument.
sycl::ext::oneapi::experimental::annotated_arg<
Point, decltype(sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::conduit})>
input;
// A kernel with a streaming invocation interface can also independently
// have register-mapped kernel arguments, when annotated by 'register_map'
// property.
sycl::ext::oneapi::experimental::annotated_arg<
Point *, decltype(sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::register_map})>
output;
// Without the annotation, kernel argument will be inferred to be streaming
// kernel arguments if the kernel invocation interface is streaming, and
// vice-versa.
int n;
// Kernel properties method to configure the kernel to be a kernel with
// streaming invocation interface.
auto get(sycl::ext::oneapi::experimental::properties_tag) {
return sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::
streaming_interface_accept_downstream_stall};
}
void operator()() const {
// For annotated_arg of struct type, explicitly cast away the annotated_arg
// to prevent compiler error.
struct Point ret;
ret.x = 0;
ret.y = ((Point)input).y;
for (int i = 0; i < n; i++) {
ret.x += ((Point)input).x;
ret.y += 1;
}
*output = ret;
}
};
int main(int argc, char *argv[]) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
bool passed = true;
int count = 16;
if (argc > 1) count = atoi(argv[1]);
if (count <= 0) {
std::cerr << "ERROR: 'count' must be positive" << std::endl;
return 1;
}
try {
// create the device queue
sycl::queue q(selector, fpga_tools::exception_handler);
// make sure the device supports USM host allocations
sycl::device d = q.get_device();
// Print out the device information.
std::cout << "Running on device: "
<< q.get_device().get_info<sycl::info::device::name>().c_str()
<< std::endl;
if (!d.has(sycl::aspect::usm_host_allocations)) {
std::cerr << "ERROR: The selected device does not support USM host"
<< " allocations" << std::endl;
return 1;
}
Point input;
input.x = 1;
input.y = 'a';
Point *functor_streaming_out = sycl::malloc_host<Point>(count, q);
Point *golden_out = sycl::malloc_host<Point>(count, q);
// test that mallocs did not return nullptr
assert(functor_streaming_out);
assert(golden_out);
// Compute golden output data
Point ret;
ret.x = 0;
ret.y = input.y;
for (int i = 0; i < (count); i++) {
ret.x += input.x;
ret.y += 1;
}
*golden_out = ret;
// validation lambda
auto validate = [](auto *golden_out, auto *functor_streaming_out) {
if (functor_streaming_out->x != golden_out->x ||
functor_streaming_out->y != golden_out->y) {
std::cout << "Expected: \n";
std::cout << "functor_streaming_out->x = " << golden_out->x << "\n";
std::cout << "functor_streaming_out->y = " << golden_out->y << "\n";
std::cout << "Got: \n";
std::cout << "functor_streaming_out->x = " << functor_streaming_out->x
<< "\n";
std::cout << "functor_streaming_out->y = " << functor_streaming_out->y
<< "\n";
std::cout << "FAILED\n";
return false;
}
return true;
};
// Launch the kernel with a streaming invocation interface implemented in
// the functor programming model
std::cout << "Running the kernel with streaming invocation interface "
"implemented in the "
"functor programming model"
<< std::endl;
q.single_task<FunctorStream>(
FunctorStreamIP{input, functor_streaming_out, count})
.wait();
std::cout << "\t Done" << std::endl;
passed &= validate(golden_out, functor_streaming_out);
std::cout << std::endl;
sycl::free(functor_streaming_out, q);
sycl::free(golden_out, q);
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
std::terminate();
}
if (passed) {
std::cout << "PASSED\n";
return 0;
} else {
std::cout << "FAILED\n";
return 1;
}
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/ip_authoring_interfaces/invocation_interfaces/src/stream_rm_stall.cpp | // oneAPI headers
#include <sycl/ext/intel/ac_types/ac_int.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include "exception_handler.hpp"
// Forward declare the kernel names in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class StreamRmStall;
/////////////////////////////////////////
struct StreamRmStallIP {
// Annotate kernel argument with 'conduit' property
// to specify it to be a streaming kernel argument.
sycl::ext::oneapi::experimental::annotated_arg<
int *, decltype(sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::conduit})>
input;
// A kernel with a streaming invocation interface can also independently have
// register-mapped kernel arguments, when annotated by 'register_map'
// property.
sycl::ext::oneapi::experimental::annotated_arg<
int *, decltype(sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::register_map})>
output;
// Without the annotation, kernel argument will be inferred to be streaming
// kernel arguments if the kernel invocation interface is streaming, and
// vice-versa.
int n;
// Kernel properties method to configure the kernel to be a kernel with
// streaming invocation interface without downstream 'ready_in' interface.
auto get(sycl::ext::oneapi::experimental::properties_tag) {
return sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::
streaming_interface_remove_downstream_stall};
}
void operator()() const {
for (int i = 0; i < n; i++) {
output[i] = (int)(input[i] * (input[i] + 1));
}
}
};
int main(int argc, char *argv[]) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
bool passed = true;
int count = 16;
if (argc > 1) count = atoi(argv[1]);
if (count <= 0) {
std::cerr << "ERROR: 'count' must be positive" << std::endl;
return 1;
}
try {
// create the device queue
sycl::queue q(selector, fpga_tools::exception_handler);
// make sure the device supports USM host allocations
sycl::device d = q.get_device();
// Print out the device information.
std::cout << "Running on device: "
<< q.get_device().get_info<sycl::info::device::name>().c_str()
<< std::endl;
if (!d.has(sycl::aspect::usm_host_allocations)) {
std::cerr << "ERROR: The selected device does not support USM host"
<< " allocations" << std::endl;
return 1;
}
int *input = sycl::malloc_host<int>(count, q);
int *stream_rm_stall_out = sycl::malloc_host<int>(count, q);
int *golden_out = sycl::malloc_host<int>(count, q);
// test that mallocs did not return nullptr
assert(input);
assert(stream_rm_stall_out);
assert(golden_out);
// create input and golden output data
for (int i = 0; i < count; i++) {
input[i] = rand() % 77;
golden_out[i] = (int)(input[i] * (input[i] + 1));
stream_rm_stall_out[i] = 0;
}
// validation lambda
auto validate = [](auto *golden_out, auto *stream_rm_stall_out, int count) {
for (int i = 0; i < count; i++) {
if (stream_rm_stall_out[i] != golden_out[i]) {
std::cout << "stream_rm_stall_out[" << i << "] != golden_out[" << i
<< "]"
<< " (" << stream_rm_stall_out[i] << " != " << golden_out[i]
<< ")" << std::endl;
return false;
}
}
return true;
};
// Launch the kernel with a streaming invocation interface implemented in
// the functor programming model
std::cout << "Running the kernel with streaming invocation interface "
"implemented in the "
"functor programming model"
<< std::endl;
q.single_task<StreamRmStall>(
StreamRmStallIP{input, stream_rm_stall_out, count})
.wait();
std::cout << "\t Done" << std::endl;
passed &= validate(golden_out, stream_rm_stall_out, count);
std::cout << std::endl;
sycl::free(input, q);
sycl::free(stream_rm_stall_out, q);
sycl::free(golden_out, q);
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
std::terminate();
}
if (passed) {
std::cout << "PASSED\n";
return 0;
} else {
std::cout << "FAILED\n";
return 1;
}
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/ip_authoring_interfaces/invocation_interfaces/src/reg_map_functor.cpp | // oneAPI headers
#include <sycl/ext/intel/ac_types/ac_int.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include "exception_handler.hpp"
using MyUInt5 = ac_int<5, false>;
// Forward declare the kernel names in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class FunctorRegMap;
/////////////////////////////////////////
struct FunctorRegMapIP {
// Use an annotated_arg with the 'register_map' property to explicitly specify
// it to be a register-mapped kernel argument.
sycl::ext::oneapi::experimental::annotated_arg<
int *, decltype(sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::register_map})>
input;
// Without the annotation, kernel argument will be inferred to be
// register-mapped kernel arguments if the kernel invocation interface is
// register-mapped, and vice-versa.
int *output;
// A kernel with a register map invocation interface can also independently
// have streaming kernel arguments, when annotated by 'conduit' property.
sycl::ext::oneapi::experimental::annotated_arg<
MyUInt5, decltype(sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::conduit})>
n;
// Without a kernel argument definition, the compiler will infer a
// register-mapped invocation interface.
void operator()() const {
// For annotated_arg of ac_int type, explicitly cast away the annotated_arg
// to prevent compiler error when using methods or accessing members.
for (MyUInt5 i = 0; i < ((MyUInt5)n).slc<5>(0); i++) {
output[i] = input[i] * (input[i] + 1);
}
}
};
int main(int argc, char *argv[]) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
bool passed = true;
MyUInt5 count = 16;
if (argc > 1) count = atoi(argv[1]);
if (count <= 0) {
std::cerr << "ERROR: 'count' must be positive" << std::endl;
return 1;
}
try {
// create the device queue
sycl::queue q(selector, fpga_tools::exception_handler);
// make sure the device supports USM host allocations
sycl::device d = q.get_device();
// Print out the device information.
std::cout << "Running on device: "
<< q.get_device().get_info<sycl::info::device::name>().c_str()
<< std::endl;
if (!d.has(sycl::aspect::usm_host_allocations)) {
std::cerr << "ERROR: The selected device does not support USM host"
<< " allocations" << std::endl;
return 1;
}
int *input = sycl::malloc_host<int>(count, q);
int *functor_register_map_out = sycl::malloc_host<int>(count, q);
int *golden_out = sycl::malloc_host<int>(count, q);
// test that mallocs did not return nullptr
assert(input);
assert(functor_register_map_out);
assert(golden_out);
// create input and golden output data
for (MyUInt5 i = 0; i < count; i++) {
input[i] = rand() % 77;
golden_out[i] = (int)(input[i] * (input[i] + 1));
functor_register_map_out[i] = 0;
}
// validation lambda
auto validate = [](int *golden_out, int *functor_register_map_out,
MyUInt5 count) {
for (MyUInt5 i = 0; i < count; i++) {
if (functor_register_map_out[i] != golden_out[i]) {
std::cout << "functor_register_map_out[" << i << "] != golden_out["
<< i << "]"
<< " (" << functor_register_map_out[i]
<< " != " << golden_out[i] << ")" << std::endl;
return false;
}
}
return true;
};
// Launch the kernel with a register map invocation interface implemented in
// the functor programming model
std::cout << "Running the kernel with register map invocation interface "
"implemented in the functor programming model"
<< std::endl;
q.single_task<FunctorRegMap>(
FunctorRegMapIP{input, functor_register_map_out, count})
.wait();
std::cout << "\t Done" << std::endl;
passed &= validate(golden_out, functor_register_map_out, count);
std::cout << std::endl;
sycl::free(input, q);
sycl::free(functor_register_map_out, q);
sycl::free(golden_out, q);
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
std::terminate();
}
if (passed) {
std::cout << "PASSED\n";
return 0;
} else {
std::cout << "FAILED\n";
return 1;
}
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/ip_authoring_interfaces/invocation_interfaces/src/stream_lambda.cpp | // oneAPI headers
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include "exception_handler.hpp"
// Forward declare the kernel names in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class LambdaStream;
/////////////////////////////////////////
void LambdaStreamKernel(sycl::queue &q, int *input, int *output, int n) {
// Create a properties object containing the kernel invocation interface
// property 'streaming_interface_remove_downstream_stall'.
sycl::ext::oneapi::experimental::properties kernel_properties{
sycl::ext::intel::experimental::
streaming_interface_remove_downstream_stall};
// In the Lambda programming model, pass a properties object argument to
// configure the kernel invocation interface. All kernel arguments will have
// the same interface as the kernel invocation interface.
q.single_task<LambdaStream>(kernel_properties, [=] {
for (int i = 0; i < n; i++) {
output[i] = input[i] * (input[i] + 1);
}
}).wait();
std::cout << "\t Done" << std::endl;
}
int main(int argc, char *argv[]) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
bool passed = true;
int count = 16;
if (argc > 1) count = atoi(argv[1]);
if (count <= 0) {
std::cerr << "ERROR: 'count' must be positive" << std::endl;
return 1;
}
try {
// create the device queue
sycl::queue q(selector, fpga_tools::exception_handler);
// make sure the device supports USM host allocations
sycl::device d = q.get_device();
// Print out the device information.
std::cout << "Running on device: "
<< q.get_device().get_info<sycl::info::device::name>().c_str()
<< std::endl;
if (!d.has(sycl::aspect::usm_host_allocations)) {
std::cerr << "ERROR: The selected device does not support USM host"
<< " allocations" << std::endl;
return 1;
}
int *input = sycl::malloc_host<int>(count, q);
int *lambda_streaming_out = sycl::malloc_host<int>(count, q);
int *golden_out = sycl::malloc_host<int>(count, q);
// test that mallocs did not return nullptr
assert(input);
assert(lambda_streaming_out);
assert(golden_out);
// create input and golden output data
for (int i = 0; i < count; i++) {
input[i] = rand() % 77;
golden_out[i] = (int)(input[i] * (input[i] + 1));
lambda_streaming_out[i] = 0;
}
// validation lambda
auto validate = [](int *golden_out, int *lambda_streaming_out, int count) {
for (int i = 0; i < count; i++) {
if (lambda_streaming_out[i] != golden_out[i]) {
std::cout << "lambda_streaming_out[" << i << "] != golden_out[" << i
<< "]"
<< " (" << lambda_streaming_out[i]
<< " != " << golden_out[i] << ")" << std::endl;
return false;
}
}
return true;
};
// Launch the kernel with a streaming invocation interface implemented in
// the lambda programming model
std::cout << "Running the kernel with streaming invocation interface "
"implemented in the "
"lambda programming model"
<< std::endl;
LambdaStreamKernel(q, input, lambda_streaming_out, count);
passed &= validate(golden_out, lambda_streaming_out, count);
std::cout << std::endl;
sycl::free(input, q);
sycl::free(lambda_streaming_out, q);
sycl::free(golden_out, q);
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
std::terminate();
}
if (passed) {
std::cout << "PASSED\n";
return 0;
} else {
std::cout << "FAILED\n";
return 1;
}
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/ip_authoring_interfaces/invocation_interfaces/src/stream_pipelined.cpp | // oneAPI headers
#include <sycl/ext/intel/ac_types/ac_int.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include "exception_handler.hpp"
// Forward declare the kernel names in the global scope.
// This FPGA best practice reduces name mangling in the optimization reports.
class StreamPipelined;
struct StreamPipelinedIP {
// Kernel arguments will be passed as conduits since the invocation interface
// is configured to be 'streaming', and no annotated_arg wrapper is used.
int *input;
int *output;
// Kernel properties method to configure the kernel to be a kernel with
// streaming pipelined invocation interface.
// The property `sycl::ext::intel::experimental::pipelined` takes an optional
// template parameter that controls whether to pipeline the kernel. Valid
// parameters are: -1: Pipeline the kernel, and automatically infer lowest
// possible II at target fMAX. 0: Do not pipeline the kernel. N (N> 0):
// Pipeline the kernel, and force the II of the kernel to be N. If a parameter
// is not specified, the default behaviour of -1 will be inferred.
auto get(sycl::ext::oneapi::experimental::properties_tag) {
return sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::streaming_interface<>,
sycl::ext::intel::experimental::pipelined<>};
}
void operator()() const {
int val = *input;
*output = (int)(val * (val + 1));
}
};
int main(int argc, char *argv[]) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
bool passed = true;
int count = 16;
if (argc > 1) count = atoi(argv[1]);
if (count <= 0) {
std::cerr << "ERROR: 'count' must be positive" << std::endl;
return 1;
}
try {
// create the device queue
sycl::queue q(selector, fpga_tools::exception_handler);
// make sure the device supports USM host allocations
sycl::device d = q.get_device();
// Print out the device information.
std::cout << "Running on device: "
<< q.get_device().get_info<sycl::info::device::name>().c_str()
<< std::endl;
if (!d.has(sycl::aspect::usm_host_allocations)) {
std::cerr << "ERROR: The selected device does not support USM host"
<< " allocations" << std::endl;
return 1;
}
int *input = sycl::malloc_host<int>(count, q);
int *functor_streaming_pipelined_out = sycl::malloc_host<int>(count, q);
int *golden_out = sycl::malloc_host<int>(count, q);
// test that mallocs did not return nullptr
assert(input);
assert(functor_streaming_pipelined_out);
assert(golden_out);
// create input and golden output data
for (int i = 0; i < count; i++) {
input[i] = rand() % 77;
golden_out[i] = (int)(input[i] * (input[i] + 1));
functor_streaming_pipelined_out[i] = 0;
}
// validation lambda
auto validate = [](auto *golden_out, auto *functor_streaming_pipelined_out,
int count) {
for (int i = 0; i < count; i++) {
if (functor_streaming_pipelined_out[i] != golden_out[i]) {
std::cout << "functor_streaming_pipelined_out[" << i
<< "] != golden_out[" << i << "]"
<< " (" << functor_streaming_pipelined_out[i]
<< " != " << golden_out[i] << ")" << std::endl;
return false;
}
}
return true;
};
std::cout << "Launching streaming pipelined kernels consecutively"
<< std::endl;
for (int i = 0; i < count; i++) {
q.single_task<StreamPipelined>(
StreamPipelinedIP{&input[i], &functor_streaming_pipelined_out[i]});
}
q.wait();
std::cout << "\t Done" << std::endl;
passed &= validate(golden_out, functor_streaming_pipelined_out, count);
std::cout << std::endl;
sycl::free(input, q);
sycl::free(functor_streaming_pipelined_out, q);
sycl::free(golden_out, q);
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
std::terminate();
}
if (passed) {
std::cout << "PASSED\n";
return 0;
} else {
std::cout << "FAILED\n";
return 1;
}
} | cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/ip_authoring_interfaces/mmhost/part3_hosts/src/mmhost.cpp | #include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include "exception_handler.hpp"
constexpr int kBL1 = 1;
constexpr int kBL2 = 2;
constexpr int kBL3 = 3;
constexpr int kAlignment = 4;
struct MultiMMIP {
// Each annotated pointer is configured with a unique `buffer_location`,
// resulting in three unique Avalon memory-mapped host interfaces.
using XProps = decltype(sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::buffer_location<kBL1>,
sycl::ext::intel::experimental::awidth<32>,
sycl::ext::intel::experimental::dwidth<32>,
sycl::ext::intel::experimental::latency<1>,
sycl::ext::oneapi::experimental::alignment<kAlignment>,
sycl::ext::intel::experimental::read_write_mode_read});
using YProps = decltype(sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::buffer_location<kBL2>,
sycl::ext::intel::experimental::awidth<32>,
sycl::ext::intel::experimental::dwidth<32>,
sycl::ext::intel::experimental::latency<1>,
sycl::ext::oneapi::experimental::alignment<kAlignment>,
sycl::ext::intel::experimental::read_write_mode_read});
using ZProps = decltype(sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::buffer_location<kBL3>,
sycl::ext::intel::experimental::awidth<32>,
sycl::ext::intel::experimental::dwidth<32>,
sycl::ext::intel::experimental::latency<1>,
sycl::ext::oneapi::experimental::alignment<kAlignment>,
sycl::ext::intel::experimental::read_write_mode_write});
sycl::ext::oneapi::experimental::annotated_arg<int *, XProps> x;
sycl::ext::oneapi::experimental::annotated_arg<int *, YProps> y;
sycl::ext::oneapi::experimental::annotated_arg<int *, ZProps> z;
int size;
void operator()() const {
for (int i = 0; i < size; i++) {
z[i] = x[i] + y[i];
}
}
};
int main(void) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
bool passed = true;
try {
// create the device queue
sycl::queue q(selector, fpga_tools::exception_handler);
// Print out the device information.
sycl::device device = q.get_device();
std::cout << "Running on device: "
<< q.get_device().get_info<sycl::info::device::name>().c_str()
<< std::endl;
// Create and initialize the host arrays
constexpr int kN = 8;
std::cout << "Elements in vector : " << kN << "\n";
// Host array must share the same buffer location property as defined in the
// kernel. Since we are specifying alignment on the kernel argument, we
// need to also specify that to the allocation call by using
// aligned_alloc_shared API
int *array_a = sycl::aligned_alloc_shared<int>(
kAlignment, kN, q,
sycl::ext::intel::experimental::property::usm::buffer_location(kBL1));
int *array_b = sycl::aligned_alloc_shared<int>(
kAlignment, kN, q,
sycl::ext::intel::experimental::property::usm::buffer_location(kBL2));
int *array_c = sycl::aligned_alloc_shared<int>(
kAlignment, kN, q,
sycl::ext::intel::experimental::property::usm::buffer_location(kBL3));
assert(array_a);
assert(array_b);
assert(array_c);
for (int i = 0; i < kN; i++) {
array_a[i] = i;
array_b[i] = 2 * i;
}
q.single_task(MultiMMIP{array_a, array_b, array_c, kN}).wait();
for (int i = 0; i < kN; i++) {
auto golden = 3 * i;
if (array_c[i] != golden) {
std::cout << "ERROR! At index: " << i << " , expected: " << golden
<< " , found: " << array_c[i] << "\n";
passed = false;
}
}
std::cout << (passed ? "PASSED" : "FAILED") << std::endl;
free(array_a, q);
free(array_b, q);
free(array_c, q);
return passed ? EXIT_SUCCESS : EXIT_FAILURE;
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
} | cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/ip_authoring_interfaces/mmhost/part2_single_host/src/mmhost.cpp | #include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include "exception_handler.hpp"
struct SingleMMIP {
// This kernel has 3 annotated pointers, but since they have no properties
// specified, this kernel will result in the same IP component as Example 1.
sycl::ext::oneapi::experimental::annotated_arg<int *> x;
sycl::ext::oneapi::experimental::annotated_arg<int *> y;
sycl::ext::oneapi::experimental::annotated_arg<int *> z;
int size;
void operator()() const {
for (int i = 0; i < size; ++i) {
z[i] = x[i] + y[i];
}
}
};
int main(void) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
bool passed = true;
try {
// create the device queue
sycl::queue q(selector, fpga_tools::exception_handler);
// Print out the device information.
sycl::device device = q.get_device();
std::cout << "Running on device: "
<< q.get_device().get_info<sycl::info::device::name>().c_str()
<< std::endl;
// Create and initialize the host arrays
constexpr int kN = 8;
std::cout << "Elements in vector : " << kN << "\n";
int *array_a = sycl::malloc_shared<int>(kN, q);
int *array_b = sycl::malloc_shared<int>(kN, q);
int *array_c = sycl::malloc_shared<int>(kN, q);
assert(array_a);
assert(array_b);
assert(array_c);
for (int i = 0; i < kN; i++) {
array_a[i] = i;
array_b[i] = 2 * i;
}
q.single_task(SingleMMIP{array_a, array_b, array_c, kN}).wait();
for (int i = 0; i < kN; i++) {
auto golden = 3 * i;
if (array_c[i] != golden) {
std::cout << "ERROR! At index: " << i << " , expected: " << golden
<< " , found: " << array_c[i] << "\n";
passed = false;
}
}
std::cout << (passed ? "PASSED" : "FAILED") << std::endl;
free(array_a, q);
free(array_b, q);
free(array_c, q);
return passed ? EXIT_SUCCESS : EXIT_FAILURE;
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
} | cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/ip_authoring_interfaces/mmhost/part1_pointers/src/mmhost.cpp | #include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include "exception_handler.hpp"
struct PointerIP {
// Pointer kernel arguments will be passed through the component's CSR. They
// will refer to data accessible through a shared Avalon memory-mapped host
// interface.
int *x;
int *y;
int *z;
int size;
void operator()() const {
for (int i = 0; i < size; ++i) {
z[i] = x[i] + y[i];
}
}
};
int main(void) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
bool passed = true;
try {
// create the device queue
sycl::queue q(selector, fpga_tools::exception_handler);
// Print out the device information.
sycl::device device = q.get_device();
std::cout << "Running on device: "
<< q.get_device().get_info<sycl::info::device::name>().c_str()
<< std::endl;
// Create and initialize the host arrays
constexpr int kN = 8;
std::cout << "Elements in vector : " << kN << "\n";
int *array_a = sycl::malloc_shared<int>(kN, q);
int *array_b = sycl::malloc_shared<int>(kN, q);
int *array_c = sycl::malloc_shared<int>(kN, q);
assert(array_a);
assert(array_b);
assert(array_c);
for (int i = 0; i < kN; i++) {
array_a[i] = i;
array_b[i] = 2 * i;
}
q.single_task(PointerIP{array_a, array_b, array_c, kN}).wait();
for (int i = 0; i < kN; i++) {
auto golden = 3 * i;
if (array_c[i] != golden) {
std::cout << "ERROR! At index: " << i << " , expected: " << golden
<< " , found: " << array_c[i] << "\n";
passed = false;
}
}
std::cout << (passed ? "PASSED" : "FAILED") << std::endl;
free(array_a, q);
free(array_b, q);
free(array_c, q);
return passed ? EXIT_SUCCESS : EXIT_FAILURE;
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
} | cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/ip_authoring_interfaces/mmhost/part4_ddr_hosts/src/mmhost.cpp | #include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include "exception_handler.hpp"
constexpr int kBL1 = 1;
constexpr int kBL2 = 2;
constexpr int kAlignment = 32;
struct DDRIP {
using ParamsBl1 = decltype(sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::buffer_location<kBL1>,
sycl::ext::intel::experimental::maxburst<8>,
sycl::ext::intel::experimental::dwidth<256>,
sycl::ext::oneapi::experimental::alignment<kAlignment>,
sycl::ext::intel::experimental::awidth<32>,
sycl::ext::intel::experimental::latency<0>});
using ParamsBl2 = decltype(sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::buffer_location<kBL2>,
sycl::ext::intel::experimental::maxburst<8>,
sycl::ext::intel::experimental::dwidth<256>,
sycl::ext::oneapi::experimental::alignment<kAlignment>,
sycl::ext::intel::experimental::awidth<32>,
sycl::ext::intel::experimental::latency<0>});
sycl::ext::oneapi::experimental::annotated_arg<int *, ParamsBl1> x;
sycl::ext::oneapi::experimental::annotated_arg<int *, ParamsBl1> y;
sycl::ext::oneapi::experimental::annotated_arg<int *, ParamsBl2> z;
int size;
void operator()() const {
#pragma unroll 8
for (int i = 0; i < size; ++i) {
z[i] = x[i] + y[i];
}
}
};
int main(void) {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
bool passed = true;
try {
// create the device queue
sycl::queue q(selector, fpga_tools::exception_handler);
// Print out the device information.
sycl::device device = q.get_device();
std::cout << "Running on device: "
<< q.get_device().get_info<sycl::info::device::name>().c_str()
<< std::endl;
// Create and initialize the host arrays
constexpr int kN = 8;
std::cout << "Elements in vector : " << kN << "\n";
// Host array must share the same buffer location property as defined in the
// kernel. Since we are specifying alignment on the kernel argument, we
// need to also specify that to the allocation call by using
// aligned_alloc_shared API
int *array_a = sycl::aligned_alloc_shared<int>(
kAlignment, kN, q,
sycl::ext::intel::experimental::property::usm::buffer_location(kBL1));
int *array_b = sycl::aligned_alloc_shared<int>(
kAlignment, kN, q,
sycl::ext::intel::experimental::property::usm::buffer_location(kBL1));
int *array_c = sycl::aligned_alloc_shared<int>(
kAlignment, kN, q,
sycl::ext::intel::experimental::property::usm::buffer_location(kBL2));
assert(array_a);
assert(array_b);
assert(array_c);
for (int i = 0; i < kN; i++) {
array_a[i] = i;
array_b[i] = 2 * i;
}
q.single_task(DDRIP{array_a, array_b, array_c, kN}).wait();
for (int i = 0; i < kN; i++) {
auto golden = 3 * i;
if (array_c[i] != golden) {
std::cout << "ERROR! At index: " << i << " , expected: " << golden
<< " , found: " << array_c[i] << "\n";
passed = false;
}
}
std::cout << (passed ? "PASSED" : "FAILED") << std::endl;
free(array_a, q);
free(array_b, q);
free(array_c, q);
return passed ? EXIT_SUCCESS : EXIT_FAILURE;
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
} | cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/ip_authoring_interfaces/component_interfaces_comparison/streaming-invocation/src/vector_add.cpp | #include <iostream>
// oneAPI headers
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "exception_handler.hpp"
// Forward declare the kernel name in the global scope. This is an FPGA best
// practice that reduces name mangling in the optimization reports.
class IDSimpleVAdd;
struct SimpleVAddKernel {
sycl::ext::oneapi::experimental::annotated_arg<
int *, decltype(sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::conduit})>
a_in;
sycl::ext::oneapi::experimental::annotated_arg<
int *, decltype(sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::conduit})>
b_in;
sycl::ext::oneapi::experimental::annotated_arg<
int *, decltype(sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::conduit})>
c_out;
sycl::ext::oneapi::experimental::annotated_arg<
int, decltype(sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::conduit})>
len;
// kernel property method to config invocation interface
auto get(sycl::ext::oneapi::experimental::properties_tag) {
return sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::streaming_interface<>};
}
void operator()() const {
for (int idx = 0; idx < len; idx++) {
int a_val = a_in[idx];
int b_val = b_in[idx];
int sum = a_val + b_val;
c_out[idx] = sum;
}
}
};
constexpr int kVectorSize = 256;
int main() {
try {
// Use compile-time macros to select either:
// - the FPGA emulator device (CPU emulation of the FPGA)
// - the FPGA device (a real FPGA)
// - the simulator device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
// create the device queue
sycl::queue q(selector, fpga_tools::exception_handler);
int count = kVectorSize; // pass array size by value
// Create USM shared allocations in the specified buffer_location.
// You can also use host allocations with malloc_host(...) API
int *a = sycl::malloc_shared<int>(count, q);
int *b = sycl::malloc_shared<int>(count, q);
int *c = sycl::malloc_shared<int>(count, q);
for (int i = 0; i < count; i++) {
a[i] = i;
b[i] = (count - i);
}
std::cout << "Add two vectors of size " << count << std::endl;
q.single_task<IDSimpleVAdd>(SimpleVAddKernel{a, b, c, count}).wait();
// verify that VC is correct
bool passed = true;
for (int i = 0; i < count; i++) {
int expected = a[i] + b[i];
if (c[i] != expected) {
std::cout << "idx=" << i << ": result " << c[i] << ", expected ("
<< expected << ") A=" << a[i] << " + B=" << b[i] << std::endl;
passed = false;
}
}
std::cout << (passed ? "PASSED" : "FAILED") << std::endl;
sycl::free(a, q);
sycl::free(b, q);
sycl::free(c, q);
return passed ? EXIT_SUCCESS : EXIT_FAILURE;
} catch (sycl::exception const &e) {
std::cerr << "Caught a synchronous SYCL exception: " << e.what()
<< std::endl;
std::cerr << " If you are targeting an FPGA hardware, "
"ensure that your system is plugged to an FPGA board that is "
"set up correctly"
<< std::endl;
std::cerr << " If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR"
<< std::endl;
std::terminate();
}
} | cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/ip_authoring_interfaces/component_interfaces_comparison/csr-pipes/src/vector_add.cpp | #include <iostream>
// oneAPI headers
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "exception_handler.hpp"
// Forward declare the kernel name in the global scope. This is an FPGA best
// practice that reduces name mangling in the optimization reports.
class SimpleVAddPipes;
// Forward declare pipe names to reduce name mangling
class IDPipeA;
class IDPipeB;
class IDPipeC;
constexpr int kVectorSize = 256;
using PipeProps = decltype(sycl::ext::oneapi::experimental::properties(
sycl::ext::intel::experimental::ready_latency<0>));
using InputPipeA =
sycl::ext::intel::experimental::pipe<IDPipeA, int, 0,
PipeProps>;
using InputPipeB =
sycl::ext::intel::experimental::pipe<IDPipeB, int, 0,
PipeProps>;
using CSRPipeProps = decltype(sycl::ext::oneapi::experimental::properties(
sycl::ext::intel::experimental::protocol_avalon_mm_uses_ready));
// this csr pipe will only be read from and written to once
using OutputPipeC =
sycl::ext::intel::experimental::pipe<IDPipeC, int, 0,
CSRPipeProps>;
struct SimpleVAddKernelPipes {
int len;
void operator()() const {
int sum_total = 0;
for (int idx = 0; idx < len; idx++) {
int a_val = InputPipeA::read();
int b_val = InputPipeB::read();
int sum = a_val + b_val;
sum_total += sum;
}
// Write to OutputPipeC only once per kernel invocation
OutputPipeC::write(sum_total);
}
};
int main() {
try {
// Use compile-time macros to select either:
// - the FPGA emulator device (CPU emulation of the FPGA)
// - the FPGA device (a real FPGA)
// - the simulator device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
// create the device queue
sycl::queue q(selector, fpga_tools::exception_handler);
int count = kVectorSize; // pass array size by value
int expected_sum = 0;
// push data into pipes
int *a = new int[count];
int *b = new int[count];
for (int i = 0; i < count; i++) {
a[i] = i;
b[i] = (count - i);
expected_sum += (a[i] + b[i]);
// When writing to a host pipe in non kernel code,
// you must pass the sycl::queue as the first argument
InputPipeA::write(q, a[i]);
InputPipeB::write(q, b[i]);
}
std::cout << "Add two vectors of size " << count << std::endl;
q.single_task<SimpleVAddPipes>(SimpleVAddKernelPipes{count});
// verify that outputs are correct
bool passed = true;
// only need to read from OutputPipeC once, since the kernel only wrote to it once
int calc = OutputPipeC::read(q);
if (calc != expected_sum) {
std::cout << "result " << calc << ", expected (" << expected_sum << ")"
<< std::endl;
passed = false;
}
std::cout << (passed ? "PASSED" : "FAILED") << std::endl;
delete[] a;
delete[] b;
return passed ? EXIT_SUCCESS : EXIT_FAILURE;
} catch (sycl::exception const &e) {
std::cerr << "Caught a synchronous SYCL exception: " << e.what()
<< std::endl;
std::cerr << " If you are targeting an FPGA hardware, "
"ensure that your system is plugged to an FPGA board that is "
"set up correctly"
<< std::endl;
std::terminate();
}
} | cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/ip_authoring_interfaces/component_interfaces_comparison/naive/src/vector_add.cpp | #include <iostream>
// oneAPI headers
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "exception_handler.hpp"
// Forward declare the kernel name in the global scope. This is an FPGA best
// practice that reduces name mangling in the optimization reports.
class IDSimpleVAdd;
struct SimpleVAddKernel {
int *a_in;
int *b_in;
int *c_out;
int len;
void operator()() const {
for (int idx = 0; idx < len; idx++) {
int a_val = a_in[idx];
int b_val = b_in[idx];
int sum = a_val + b_val;
c_out[idx] = sum;
}
}
};
constexpr int kVectorSize = 256;
int main() {
try{
// Use compile-time macros to select either:
// - the FPGA emulator device (CPU emulation of the FPGA)
// - the FPGA device (a real FPGA)
// - the simulator device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
// create the device queue
sycl::queue q(selector, fpga_tools::exception_handler);
int count = kVectorSize; // pass array size by value
// Create USM shared allocations in the specified buffer_location.
// You can also use host allocations with malloc_host(...) API
int *a = sycl::malloc_shared<int>(count, q);
int *b = sycl::malloc_shared<int>(count, q);
int *c = sycl::malloc_shared<int>(count, q);
for (int i = 0; i < count; i++) {
a[i] = i;
b[i] = (count - i);
}
std::cout << "Add two vectors of size " << count << std::endl;
q.single_task<IDSimpleVAdd>(SimpleVAddKernel{a, b, c, count}).wait();
// verify that VC is correct
bool passed = true;
for (int i = 0; i < count; i++) {
int expected = a[i] + b[i];
if (c[i] != expected) {
std::cout << "idx=" << i << ": result " << c[i] << ", expected ("
<< expected << ") A=" << a[i] << " + B=" << b[i] << std::endl;
passed = false;
}
}
std::cout << (passed ? "PASSED" : "FAILED") << std::endl;
sycl::free(a, q);
sycl::free(b, q);
sycl::free(c, q);
return passed ? EXIT_SUCCESS : EXIT_FAILURE;
} catch (sycl::exception const &e) {
std::cerr << "Caught a synchronous SYCL exception: " << e.what()
<< std::endl;
std::cerr << " If you are targeting an FPGA hardware, "
"ensure that your system is plugged to an FPGA board that is "
"set up correctly"
<< std::endl;
std::terminate();
}
} | cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/ip_authoring_interfaces/component_interfaces_comparison/mm-host/src/vector_add.cpp | #include <iostream>
// oneAPI headers
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "exception_handler.hpp"
// Buffer locations for MM Host interfaces
constexpr int kBL1 = 1;
constexpr int kBL2 = 2;
constexpr int kBL3 = 3;
// Forward declare the kernel name in the global scope. This is an FPGA best
// practice that reduces name mangling in the optimization reports.
class SimpleVAdd;
struct SimpleVAddKernel {
sycl::ext::oneapi::experimental::annotated_arg<
int *, decltype(sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::buffer_location<kBL1>,
sycl::ext::intel::experimental::dwidth<32>,
sycl::ext::intel::experimental::latency<0>,
sycl::ext::intel::experimental::read_write_mode_read,
sycl::ext::oneapi::experimental::alignment<4>})>
a_in;
sycl::ext::oneapi::experimental::annotated_arg<
int *, decltype(sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::buffer_location<kBL2>,
sycl::ext::intel::experimental::dwidth<32>,
sycl::ext::intel::experimental::latency<0>,
sycl::ext::intel::experimental::read_write_mode_read,
sycl::ext::oneapi::experimental::alignment<4>})>
b_in;
sycl::ext::oneapi::experimental::annotated_arg<
int *, decltype(sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::buffer_location<kBL3>,
sycl::ext::intel::experimental::dwidth<32>,
sycl::ext::intel::experimental::latency<0>,
sycl::ext::intel::experimental::read_write_mode_write,
sycl::ext::oneapi::experimental::alignment<4>})>
c_out;
int len;
void operator()() const {
for (int idx = 0; idx < len; idx++) {
int a_val = a_in[idx];
int b_val = b_in[idx];
int sum = a_val + b_val;
c_out[idx] = sum;
}
}
};
constexpr int kVectorSize = 256;
int main() {
try {
// Use compile-time macros to select either:
// - the FPGA emulator device (CPU emulation of the FPGA)
// - the FPGA device (a real FPGA)
// - the simulator device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
// create the device queue
sycl::queue q(selector, fpga_tools::exception_handler);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
int count = kVectorSize; // pass array size by value
// declare arrays and fill them
// Create USM shared allocations in the specified buffer_location.
// You can also use host allocations with malloc_host(...) API
int *a = sycl::malloc_shared<int>(
count, q,
sycl::property_list{
sycl::ext::intel::experimental::property::usm::buffer_location(
kBL1)});
int *b = sycl::malloc_shared<int>(
count, q,
sycl::property_list{
sycl::ext::intel::experimental::property::usm::buffer_location(
kBL2)});
int *c = sycl::malloc_shared<int>(
count, q,
sycl::property_list{
sycl::ext::intel::experimental::property::usm::buffer_location(
kBL3)});
for (int i = 0; i < count; i++) {
a[i] = i;
b[i] = (count - i);
}
std::cout << "Add two vectors of size " << count << std::endl;
q.single_task<SimpleVAdd>(SimpleVAddKernel{a, b, c, count}).wait();
// verify that VC is correct
bool passed = true;
for (int i = 0; i < count; i++) {
int expected = a[i] + b[i];
if (c[i] != expected) {
std::cout << "idx=" << i << ": result " << c[i] << ", expected ("
<< expected << ") A=" << a[i] << " + B=" << b[i] << std::endl;
passed = false;
}
}
std::cout << (passed ? "PASSED" : "FAILED") << std::endl;
sycl::free(a, q);
sycl::free(b, q);
sycl::free(c, q);
return passed ? EXIT_SUCCESS : EXIT_FAILURE;
} catch (sycl::exception const &e) {
std::cerr << "Caught a synchronous SYCL exception: " << e.what()
<< std::endl;
std::cerr << " If you are targeting an FPGA hardware, "
"ensure that your system is plugged to an FPGA board that is "
"set up correctly"
<< std::endl;
std::terminate();
}
} | cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/ip_authoring_interfaces/component_interfaces_comparison/pipes/src/vector_add.cpp | #include <iostream>
// oneAPI headers
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "exception_handler.hpp"
constexpr int kVectorSize = 256;
// Forward declare the kernel name in the global scope. This is an FPGA best
// practice that reduces name mangling in the optimization reports.
class IDSimpleVAddPipes;
class IDPipeA;
class IDPipeB;
class IDPipeC;
using PipeProps = decltype(sycl::ext::oneapi::experimental::properties(
sycl::ext::intel::experimental::ready_latency<0>));
using InputPipeA =
sycl::ext::intel::experimental::pipe<IDPipeA, int, 0, PipeProps>;
using InputPipeB =
sycl::ext::intel::experimental::pipe<IDPipeB, int, 0, PipeProps>;
using OutputPipeC =
sycl::ext::intel::experimental::pipe<IDPipeC, int, 0, PipeProps>;
struct SimpleVAddKernelPipes {
int len;
void operator()() const {
for (int idx = 0; idx < len; idx++) {
int a_val = InputPipeA::read();
int b_val = InputPipeB::read();
int sum = a_val + b_val;
OutputPipeC::write(sum);
}
}
};
int main() {
try {
// Use compile-time macros to select either:
// - the FPGA emulator device (CPU emulation of the FPGA)
// - the FPGA device (a real FPGA)
// - the simulator device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
// create the device queue
sycl::queue q(selector, fpga_tools::exception_handler);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
int count = kVectorSize; // pass array size by value
// push data into pipes before invoking kernel
int *a = new int[count];
int *b = new int[count];
for (int i = 0; i < count; i++) {
a[i] = i;
b[i] = (count - i);
// When writing to a host pipe in non kernel code,
// you must pass the sycl::queue as the first argument
InputPipeA::write(q, a[i]);
InputPipeB::write(q, b[i]);
}
std::cout << "Add two vectors of size " << count << std::endl;
q.single_task<IDSimpleVAddPipes>(
SimpleVAddKernelPipes{count});
// verify that VC is correct
bool passed = true;
for (int i = 0; i < count; i++) {
int expected = a[i] + b[i];
int calc = OutputPipeC::read(q);
if (calc != expected) {
std::cout << "idx=" << i << ": result " << calc << ", expected ("
<< expected << ") A=" << a[i] << " + B=" << b[i] << std::endl;
passed = false;
}
}
std::cout << (passed ? "PASSED" : "FAILED") << std::endl;
delete[] a;
delete[] b;
return passed ? EXIT_SUCCESS : EXIT_FAILURE;
} catch (sycl::exception const &e) {
std::cerr << "Caught a synchronous SYCL exception: " << e.what()
<< std::endl;
std::cerr << " If you are targeting an FPGA hardware, "
"ensure that your system is plugged to an FPGA board that is "
"set up correctly"
<< std::endl;
std::terminate();
}
} | cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Features/ac_fixed/src/ac_fixed.cpp | #include <sycl/sycl.hpp>
#include <sycl/ext/intel/ac_types/ac_fixed.hpp>
#include <sycl/ext/intel/ac_types/ac_fixed_math.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <iomanip> // for std::setprecision
#include "exception_handler.hpp"
using namespace sycl;
// Type aliases for ac_fixed types
using fixed_10_3_t = ac_fixed<10, 3, true>;
using fixed_9_2_t = ac_fixed<9, 2, true>;
// Quantization mode `AC_RND`: round towards plus infinity
// Overflow mode `AC_SAT`: saturate to max and min when overflow happens
// For the other quantization and overflow modes, refer to section 2.1 of
// "Algorithmic C (AC) Datatypes" document.
using fixed_20_10_t = ac_fixed<20, 10, true, AC_RND, AC_SAT>;
// Forward declare the kernel name in the global scope.
// This is a FPGA best practice that reduces name mangling in the reports.
class ConstructFromFloat;
class ConstructFromACFixed;
class CalculateWithFloat;
class CalculateWithACFixed;
// Not recommended Usage example:
// Convert dynamic float value inside the kernel
void TestConstructFromFloat(queue &q, const float &x, fixed_20_10_t &ret) {
buffer<float, 1> inp_buffer(&x, 1);
buffer<fixed_20_10_t, 1> ret_buffer(&ret, 1);
q.submit([&](handler &h) {
accessor in_acc{inp_buffer, h, read_only};
accessor out_acc{ret_buffer, h, write_only, no_init};
h.single_task<ConstructFromFloat>([=] {
fixed_20_10_t t(in_acc[0]);
fixed_20_10_t some_offset(0.5f);
out_acc[0] = t + some_offset;
});
});
}
// Recommended Usage example:
// Convert dynamic float value outside the kernel
void TestConstructFromACFixed(queue &q, const fixed_20_10_t &x,
fixed_20_10_t &ret) {
buffer<fixed_20_10_t, 1> inp_buffer(&x, 1);
buffer<fixed_20_10_t, 1> ret_buffer(&ret, 1);
q.submit([&](handler &h) {
accessor in_acc{inp_buffer, h, read_only};
accessor out_acc{ret_buffer, h, write_only};
h.single_task<ConstructFromACFixed>([=] {
fixed_20_10_t t(in_acc[0]);
fixed_20_10_t some_offset(0.5f);
out_acc[0] = t + some_offset;
});
});
}
void TestCalculateWithFloat(queue &q, const float &x, float &ret) {
buffer<float, 1> inp_buffer(&x, 1);
buffer<float, 1> ret_buffer(&ret, 1);
q.submit([&](handler &h) {
accessor x{inp_buffer, h, read_only};
accessor res{ret_buffer, h, write_only, no_init};
h.single_task<CalculateWithFloat>([=] {
float sin_x = sinf(x[0]);
float cos_x = cosf(x[0]);
res[0] = sqrtf(sin_x * sin_x + cos_x * cos_x);
});
});
}
// Please refer to ac_fixed_math.hpp header file for fixed point math
// functions' type deduction rule. In this case, following those rules:
// I, W, S are input type template parameter (ac_fixed<W, I, S>)
// rI, rW, rS are output type template parameter (ac_fixed<rW, rI, rS>)
//* Function Name Type Propagation Rule
//* sqrt_fixed rI = I, rW = W, rS = S
//* sin_fixed For signed (S == true), rI == 2, rW = W - I + 2;
//* For unsigned (S == false), I == 1, rW = W - I + 1
//* cos_fixed For signed (S == true), rI == 2, rW = W - I + 2;
//* For unsigned (S == false), I == 1, rW = W - I + 1
void TestCalculateWithACFixed(queue &q, const fixed_10_3_t &x,
fixed_9_2_t &ret) {
buffer<fixed_10_3_t, 1> inp_buffer(&x, 1);
buffer<fixed_9_2_t, 1> ret_buffer(&ret, 1);
q.submit([&](handler &h) {
accessor x{inp_buffer, h, read_only};
accessor res{ret_buffer, h, write_only, no_init};
h.single_task<CalculateWithACFixed>([=] {
fixed_9_2_t sin_x = sin_fixed(x[0]);
fixed_9_2_t cos_x = cos_fixed(x[0]);
// The RHS expression evaluates to a larger `ac_fixed`, which gets
// truncated to fit in res[0].
res[0] = sqrt_fixed(sin_x * sin_x + cos_x * cos_x);
});
});
}
int main() {
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
try {
// Create the SYCL device queue
queue q(selector, fpga_tools::exception_handler);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
// I. Constructing `ac_fixed` Numbers
std::cout << "1. Testing Constructing ac_fixed from float or ac_fixed:\n";
fixed_20_10_t a;
TestConstructFromFloat(q, 3.1415f, a);
std::cout << "Constructed from float:\t\t" << a << "\n";
fixed_20_10_t b = 3.1415f;
fixed_20_10_t c;
TestConstructFromACFixed(q, b, c);
std::cout << "Constructed from ac_fixed:\t" << c << "\n\n";
// II. Using `ac_fixed` Math Functions
std::cout
<< "2. Testing calculation with float or ac_fixed math functions:\n";
constexpr int kSize = 5;
constexpr float inputs[kSize] = {-0.807991899423f, -2.09982907558f,
-0.742066235466f, -2.33217071676f,
1.14324158042f};
// quantum: the minimum positive value this type can represent
// Quantum is 1 / 2 ^ (W - I), where W and I are the total width and the
// integer width of the ac_fixed number
constexpr fixed_9_2_t quantum = 0.0078125f;
// for fixed point, the error should be less than 1 quantum of data type
// (1 / 2^(W - I))
constexpr fixed_9_2_t epsilon_fixed_9_2 = quantum;
constexpr float epsilon_float = 1.0f / (1.0f * float(1 << 20));
std::cout << "MAX DIFF (quantum) for ac_fixed<10, 3, true>:\t"
<< epsilon_fixed_9_2.to_double()
<< "\nMAX DIFF for float:\t\t\t\t" << epsilon_float << "\n\n";
bool pass = true;
for (int i = 0; i < kSize; i++) {
fixed_10_3_t fixed_type_input = inputs[i];
float float_type_input = inputs[i];
// declare output and diff variable
fixed_9_2_t fixed_type_result;
TestCalculateWithACFixed(q, fixed_type_input, fixed_type_result);
float float_type_result;
TestCalculateWithFloat(q, float_type_input, float_type_result);
// expected result is 1.0 = sqrt(sin^2(x) + cos^2(x))
double fixed_diff = abs(fixed_type_result.to_double() - 1.0);
double float_diff = abs(float_type_result - 1.0);
std::cout << std::setprecision(8);
std::cout << "Input " << i << ":\t\t\t" << inputs[i]
<< "\nresult(fixed point):\t\t" << fixed_type_result.to_double()
<< "\ndifference(fixed point):\t" << fixed_diff
<< "\nresult(float):\t\t\t" << float_type_result
<< "\ndifference(float):\t\t" << float_diff << "\n\n";
// check differences
if (fixed_diff > epsilon_fixed_9_2 || float_diff > epsilon_float) {
pass = false;
}
}
if (pass) {
std::cout << "PASSED: all kernel results are correct.\n";
} else {
std::cout << "ERROR\n";
}
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Tools/system_profiling/src/double_buffering.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <cmath>
#include <iomanip>
#include <random>
#include "exception_handler.hpp"
using namespace sycl;
// For the system_profiling tutorial, we execute the kernel only a few times.
// This makes it easier to examine the generated profiling graphs.
// Note that the performance advantage of double buffering is more apparent on
// FPGA hardware with a larger number of kernel invocations.
// kTimes = # times to execute the kernel. kTimes must be >= 2
// kSize = # of floats to process on each kernel execution.
#if defined(FPGA_EMULATOR)
constexpr int kTimes = 3;
constexpr int kSize = 4096;
#elif defined(FPGA_SIMULATOR)
constexpr int kTimes = 3;
constexpr int kSize = 4096;
#else
constexpr int kTimes = 3; // originally 100
constexpr int kSize = 262144;
#endif
// Kernel executes a power function (base^kPow). Must be
// >= 2. Can increase this to increase kernel execution
// time, but ProcessOutput() time will also increase.
constexpr int kPow = 20;
// Number of iterations through the main loop
constexpr int kNumRuns = 2;
bool pass = true;
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization report.
class SimpleVpow;
/* Kernel function.
Performs buffer_b[i] = buffer_a[i] ** pow
Only supports pow >= 2.
This kernel is not meant to be an optimal implementation of the power
operation -- it's just a sample kernel for this tutorial whose execution time
is easily controlled via the pow parameter. SYCL buffers are created
externally and passed in by reference to control (external to this function)
when the buffers are destructed. The destructor causes a blocking buffer
transfer from device to host and double buffering requires us to not block
here (because we need to launch another kernel). So we only want this
transfer to occur at the end of overall execution, not at the end of each
individual kernel execution.
*/
void SimplePow(sycl::queue &q, buffer<float, 1> &buffer_a,
buffer<float, 1> &buffer_b, event &e) {
// Submit to the queue and execute the kernel
e = q.submit([&](handler &h) {
// Get kernel access to the buffers
accessor accessor_a(buffer_a, h, read_only);
accessor accessor_b(buffer_b, h, write_only, no_init);
const int num = kSize;
assert(kPow >= 2);
const int p = kPow - 1; // Assumes pow >= 2;
h.single_task<SimpleVpow>([=]() [[intel::kernel_args_restrict]] {
for (int j = 0; j < p; j++) {
if (j == 0) {
for (int i = 0; i < num; i++) {
accessor_b[i] = accessor_a[i] * accessor_a[i];
}
} else {
for (int i = 0; i < num; i++) {
accessor_b[i] = accessor_b[i] * accessor_a[i];
}
}
}
});
});
event update_host_event;
update_host_event = q.submit([&](handler &h) {
accessor accessor_b(buffer_b, h, read_only);
/*
Explicitly instruct the SYCL runtime to copy the kernel's output buffer
back to the host upon kernel completion. This is not required for
functionality since the buffer access in ProcessOutput() also implicitly
instructs the runtime to copy the data back. But it should be noted that
this buffer access blocks ProcessOutput() until the kernel is complete
and the data is copied. In contrast, update_host() instructs the runtime
to perform the copy earlier. This allows ProcessOutput() to optionally
perform more useful work *before* making the blocking buffer access. Said
another way, this allows ProcessOutput() to potentially perform more work
in parallel with the runtime's copy operation.
*/
h.update_host(accessor_b);
});
}
// Returns kernel execution time for a given SYCL event from a queue.
unsigned long SyclGetExecTimeNs(event e) {
unsigned long start_time =
e.get_profiling_info<info::event_profiling::command_start>();
unsigned long end_time = e.get_profiling_info<info::event_profiling::command_end>();
return (end_time - start_time);
}
// Local pow function for verifying results
float MyPow(float input, int pow) {
return (pow == 0) ? 1 : input * MyPow(input, pow - 1);
}
/* Compares kernel output against expected output. Only compares part of the
output so that this method completes quickly. This is done
intentionally/artificially keep host-processing time shorter than kernel
execution time. Grabs kernel output data from its SYCL buffer. Reading from
this buffer is a blocking operation that will block on the kernel completing.
Queries and records execution time of the kernel that just completed. This
is a natural place to do this because ProcessOutput() is blocked on kernel
completion.
*/
void ProcessOutput(buffer<float, 1> &input_buf, buffer<float, 1> &output_buf,
int exec_number, event e,
unsigned long &total_kernel_time_per_slot) {
host_accessor input_buf_acc(input_buf, read_only);
host_accessor output_buf_acc(output_buf, read_only);
int num_errors = 0;
int num_errors_to_print = 10;
// Max fractional difference between FPGA pow result and CPU pow result
// Anything greater than this will be considered an error
constexpr double epsilon = 0.01;
/* The use of update_host() in the kernel function allows for additional
host-side operations to be performed here, in parallel with the buffer copy
operation from device to host, before the blocking access to the output
buffer is made via output_buf_acc[]. To be clear, no real operations are
done here and this is just a note that this is the place
where you *could* do it. */
for (int i = 0; i < kSize / 8; i++) {
const double expected_value = MyPow(input_buf_acc[i], kPow);
const bool out_invalid =
std::abs(output_buf_acc[i] - expected_value) / expected_value > epsilon;
if ((num_errors < num_errors_to_print) && out_invalid) {
if (num_errors == 0) {
pass = false;
std::cout << "Verification failed on kernel execution # " << exec_number
<< ". Showing up to " << num_errors_to_print
<< " mismatches.\n";
}
std::cout << "Verification failed on kernel execution # " << exec_number
<< ", at element " << i << ". Expected " << std::fixed
<< std::setprecision(16) << expected_value << " but got "
<< output_buf_acc[i] << "\n";
num_errors++;
}
}
// At this point we know the kernel has completed,
// so can query the profiling data.
total_kernel_time_per_slot += SyclGetExecTimeNs(e);
}
/*
Generates input data for the next kernel execution. Only fills part of the
buffer so that this method completes quickly. This is done
intentionally/artificially keep host-processing time shorter than kernel
execution time. Writes the data into the associated SYCL buffer. The write
will block until the previous kernel execution, that is using this buffer,
completes.
*/
void ProcessInput(buffer<float, 1> &buf) {
// We are generating completely new input data, so can use the no_init property
// here to indicate we don't care about the SYCL buffer's current contents.
host_accessor buf_acc(buf, write_only, no_init);
// RNG seed
auto seed = std::chrono::system_clock::now().time_since_epoch().count();
// RNG engine
std::default_random_engine dre(seed);
// generate random numbers between 1 and 2
std::uniform_real_distribution<float> di(1.0f, 2.0f);
// Randomly generate a start value and increment from there.
// Compared to randomly generating every value, this is done to
// speed up this function a bit.
float start_val = di(dre);
for (int i = 0; i < kSize / 8; i++) {
buf_acc[i] = start_val;
start_val++;
}
}
int main() {
// Create queue, get platform and device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
#ifndef FPGA_HARDWARE
std::cout << "\nEmulator and simulator outputs do not demonstrate "
"true hardware performance. The design may need to run "
"on actual hardware to observe the performance benefit "
"of the optimization exemplified in this tutorial.\n\n";
#endif
try {
auto prop_list = property_list{property::queue::enable_profiling()};
sycl::queue q(selector, fpga_tools::exception_handler, prop_list);
platform platform = q.get_context().get_platform();
device device = q.get_device();
std::cout << "Platform name: "
<< platform.get_info<info::platform::name>().c_str() << "\n";
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
std::cout << "Executing kernel " << kTimes << " times in each round.\n\n";
// Create a vector to store the input/output SYCL buffers
std::vector<buffer<float, 1>> input_buf;
std::vector<buffer<float, 1>> output_buf;
// SYCL events for each kernel launch.
event sycl_events[2];
// In nanoseconds. Total execution time of kernels in a given slot.
unsigned long total_kernel_time_per_slot[2];
// Total execution time of all kernels.
unsigned long total_kernel_time = 0;
// Allocate vectors to store the host-side copies of the input data
// Create and allocate the SYCL buffers
for (int i = 0; i < 2; i++) {
input_buf.push_back(buffer<float, 1>(range<1>(kSize)));
output_buf.push_back(buffer<float, 1>(range<1>(kSize)));
}
/*
Main loop. This loop runs twice to show the performance difference without
and with double buffering.
*/
for (int i = 0; i < kNumRuns; i++) {
for (int i = 0; i < 2; i++) {
total_kernel_time_per_slot[i] = 0; // Initialize timers to zero.
}
switch (i) {
case 0: {
std::cout << "*** Beginning execution, without double buffering\n";
break;
}
case 1: {
std::cout << "*** Beginning execution, with double buffering.\n";
break;
}
default: {
std::cout << "*** Beginning execution.\n";
}
}
// Start the timer. This will include the time to process the input data
// for the first 2 kernel executions.
auto start = std::chrono::steady_clock::now();
if (i == 0) { // Single buffering
for (int i = 0; i < kTimes; i++) {
// Only print every few iterations, just to limit the prints.
if (i % 10 == 0) {
std::cout << "Launching kernel #" << i << "\n";
}
ProcessInput(input_buf[0]);
SimplePow(q, input_buf[0], output_buf[0], sycl_events[0]);
ProcessOutput(input_buf[0], output_buf[0], i, sycl_events[0],
total_kernel_time_per_slot[0]);
}
} else { // Double buffering
// Process input for first 2 kernel launches and queue them. Then block
// on processing the output of the first kernel.
ProcessInput(input_buf[0]);
ProcessInput(input_buf[1]);
std::cout << "Launching kernel #0\n";
SimplePow(q, input_buf[0], output_buf[0], sycl_events[0]);
for (int i = 1; i < kTimes; i++) {
if (i % 10 == 0) {
std::cout << "Launching kernel #" << i << "\n";
} // Only print every few iterations, just to limit the prints.
// Launch the next kernel
SimplePow(q, input_buf[i % 2], output_buf[i % 2], sycl_events[i % 2]);
// Process output from previous kernel. This will block on kernel
// completion.
ProcessOutput(input_buf[(i - 1) % 2], output_buf[(i - 1) % 2], i,
sycl_events[(i - 1) % 2],
total_kernel_time_per_slot[(i - 1) % 2]);
// Generate input for the next kernel.
ProcessInput(input_buf[(i - 1) % 2]);
}
// Process output of the final kernel
ProcessOutput(input_buf[(kTimes - 1) % 2], output_buf[(kTimes - 1) % 2],
i, sycl_events[(kTimes - 1) % 2],
total_kernel_time_per_slot[(kTimes - 1) % 2]);
}
// Add up the overall kernel execution time.
total_kernel_time = 0;
for (int i = 0; i < 2; i++) {
total_kernel_time += total_kernel_time_per_slot[i];
}
// Stop the timer.
auto end = std::chrono::steady_clock::now();
double time_span = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();
std::cout << "\nOverall execution time "
<< ((i == 0) ? "without" : "with")
<< " double buffering = " << (unsigned)(time_span * 1000)
<< " ms\n";
std::cout << "Total kernel-only execution time "
<< ((i == 0) ? "without" : "with") << " double buffering = "
<< (unsigned)(total_kernel_time / 1000000) << " ms\n";
std::cout << "Throughput = " << std::setprecision(8)
<< (float)kSize * (float)kTimes * (float)sizeof(float) /
(float)time_span / 1000000
<< " MB/s\n\n\n";
}
if (pass) {
std::cout << "Verification PASSED\n";
} else {
std::cout << "Verification FAILED\n";
return 1;
}
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Tools/platform_designer/add-oneapi/src/add.cpp | // Copyright (c) 2023 Intel Corporation
// SPDX-License-Identifier: MIT
#include <stdlib.h>
#include <iostream>
// oneAPI headers
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include "exception_handler.hpp"
// use pipes to write into registers in the CSR address space
class OutputPipeID;
using OutputPipeProps = decltype(sycl::ext::oneapi::experimental::properties(
sycl::ext::intel::experimental::protocol<
sycl::ext::intel::experimental::protocol_name::avalon_mm>));
using OutputPipe =
sycl::ext::intel::experimental::pipe<OutputPipeID, int, 0, OutputPipeProps>;
// Forward declare the kernel name in the global scope. This is an FPGA best
// practice that reduces name mangling in the optimization reports.
class IDAdder;
struct AdderKernel {
int a;
int b;
void operator()() const {
int sum = a + b;
OutputPipe::write(sum);
}
};
int main() {
bool passed = false;
try {
// Use compile-time macros to select either:
// - the FPGA emulator device (CPU emulation of the FPGA)
// - the FPGA device (a real FPGA)
// - the simulator device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
// create the device queue
sycl::queue q(selector, fpga_tools::exception_handler);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
int a = 3;
int b = 76;
int expected_sum = a + b;
std::cout << "add two integers using CSR for input." << std::endl;
q.single_task<IDAdder>(AdderKernel{a, b}).wait();
// verify that outputs are correct
passed = true;
std::cout << "collect results." << std::endl;
int calc_add = OutputPipe::read(q);
std::cout << a << " + " << b << " = " << calc_add << ", expected "
<< expected_sum << ". " << std::endl;
if (calc_add != expected_sum) {
passed = false;
}
} catch (sycl::exception const &e) {
// Catches exceptions in the host code.
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
std::cout << (passed ? "PASSED" : "FAILED") << std::endl;
return passed ? EXIT_SUCCESS : EXIT_FAILURE;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Tools/use_library/src/use_library.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/ext/intel/ac_types/ac_int.hpp>
// oneAPI headers
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
#include "lib_rtl.hpp"
// RTL Library will use the Verilog model during hardware generation, and the
// c++ model during emulation.
#include "exception_handler.hpp"
#include <stdint.h>
// Forward declare the kernel name in the global scope.
// This FPGA best practice reduces name mangling in the optimization report.
class KernelCompute;
class KernelComputeRTL;
// Using host pipes to stream data in and out of kernal
// IDPipeA and IDPipeB will be written to by the host, and then read by the kernel (device)
// IDPipeC will be written to by the kernel (device), and then read by the host
class IDPipeA;
using InputPipeA = sycl::ext::intel::experimental::pipe<IDPipeA, uint32_t>;
class IDPipeB;
using InputPipeB = sycl::ext::intel::experimental::pipe<IDPipeB, uint32_t>;
class IDPipeC;
using OutputPipeC = sycl::ext::intel::experimental::pipe<IDPipeC, uint64_t>;
class IDPipeD;
using InputPipeD = sycl::ext::intel::experimental::pipe<IDPipeD, uint32_t>;
class IDPipeE;
using InputPipeE = sycl::ext::intel::experimental::pipe<IDPipeE, uint32_t>;
class IDPipeF;
using OutputPipeF = sycl::ext::intel::experimental::pipe<IDPipeF, uint64_t>;
// This kernel computes multiplier result by using the C++ '*' operator
template <typename PipeIn1, typename PipeIn2, typename PipeOut>
struct NativeMult27x27 {
// use a streaming pipelined invocation interface to minimize hardware
// overhead
auto get(sycl::ext::oneapi::experimental::properties_tag) {
return sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::streaming_interface_accept_downstream_stall,
sycl::ext::intel::experimental::pipelined<1>};
}
void operator()() const {
MyInt27 a_val = PipeIn1::read();
MyInt27 b_val = PipeIn2::read();
MyInt54 res =(MyInt54)a_val * b_val;
PipeOut::write(res);
}
};
// This kernel computes multiplier result by calling RTL function RtlDSPm27x27u
template <typename PipeIn1, typename PipeIn2, typename PipeOut>
struct RtlMult27x27 {
// use a streaming pipelined invocation interface to minimize hardware
// overhead
auto get(sycl::ext::oneapi::experimental::properties_tag) {
return sycl::ext::oneapi::experimental::properties{
sycl::ext::intel::experimental::streaming_interface_accept_downstream_stall,
sycl::ext::intel::experimental::pipelined<1>};
}
void operator()() const {
MyInt27 a_val = PipeIn1::read();
MyInt27 b_val = PipeIn2::read();
MyInt54 res = RtlDSPm27x27u(a_val, b_val);
PipeOut::write(res);
}
};
int main() {
uint64_t result_rtl = 0;
uint64_t result_native = 0;
uint32_t kA = 134217727; // 0x7FFFFFF is the largest possible ac_int<27, false>.
uint32_t kB = 100;
// Select the FPGA emulator (CPU), FPGA simulator, or FPGA device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
#endif
try {
sycl::queue q(selector, fpga_tools::exception_handler);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
{
// write data to host-to-device pipes
InputPipeA::write(q, kA);
InputPipeB::write(q, kB);
// launch kernel that infers a multiplier automatically
q.single_task<KernelCompute>(NativeMult27x27<InputPipeA,InputPipeB,OutputPipeC>{}).wait();
// read data from device-to-host pipe
result_native = OutputPipeC::read(q);
}
{
// write data to host-to-device pipes
InputPipeD::write(q, kA);
InputPipeE::write(q, kB);
// launch a kernel to that uses a multiplier defined in RTL
q.single_task<KernelComputeRTL>(RtlMult27x27<InputPipeD,InputPipeE,OutputPipeF>{}).wait();
// read data from device-to-host pipe
result_rtl = OutputPipeF::read(q);
}
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
// Check the results
uint64_t expected_result = (uint64_t ) kA * kB;
if (result_native != expected_result) {
std::cout << "FAILED: result native (" << result_native << ") is incorrect! Expected " << expected_result << "\n";
return -1;
}
if (result_rtl != expected_result) {
std::cout << "FAILED: result RTL (" << result_rtl << ") is incorrect! Expected " << expected_result << "\n";
return -1;
}
std::cout << "PASSED: result is correct!\n";
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Tools/use_library/src/lib_rtl.hpp | // =============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/ac_types/ac_int.hpp>
using MyInt27 = ac_int<27, false>;
using MyInt54 = ac_int<54, false>;
SYCL_EXTERNAL extern "C" MyInt54 RtlDSPm27x27u(MyInt27 x, MyInt27 y);
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Tools/use_library/src/lib_rtl_model.cpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include "lib_rtl.hpp"
// This emulation model is only used during emulation, so it should functionally
// match the RTL in lib_rtl.v.
SYCL_EXTERNAL extern "C" MyInt54 RtlDSPm27x27u (MyInt27 x, MyInt27 y) {
return (x * y);
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/Tutorials/Tools/dynamic_profiler/src/dynamic_profiler.cpp | /*
Please refer to the README file for information on how and why the
Intel(r) Dynamic Profiler for DPC++ should be used. This code sample
does not explain the tool, rather it is an artificial example that
demonstates the sort of code changes the profiler data can guide.
The main content of this sample is in the README file.
*/
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <cmath>
#include <numeric>
#include "exception_handler.hpp"
using namespace sycl;
// Two identical pipes to demonstrate the behaviour before
// and after the design re-format
using ProducerToConsumerBeforePipe =
ext::intel::pipe< // Defined in the SYCL headers.
class ProducerConsumerBeforePipe, // An identifier for the pipe.
float, // The type of data in the pipe.
20>; // The capacity of the pipe.
using ProducerToConsumerAfterPipe =
ext::intel::pipe<class ProducerConsumerAfterPipe, float, 20>;
// Forward declare the kernel names in the global scope.
// This FPGA best practice reduces name mangling in the optimization report.
class ProducerBeforeKernel;
class ConsumerBeforeKernel;
class ProducerAfterKernel;
class ConsumerAfterKernel;
// kSize = # of floats to process on each kernel execution.
#if defined(FPGA_EMULATOR) or defined(FPGA_SIMULATOR)
constexpr int kSize = 64;
#else
constexpr int kSize = 262144;
#endif
// Number of iterations performed in the consumer kernels
// This controls the amount of work done by the Consumer.
// After the optimization, the Producer and Consumer split the work.
constexpr int kComplexity1 = 1900;
constexpr int kComplexity2 = 2000;
// Perform two stages of processing on the input data.
// The output of ConsumerWork1 needs to go to the input
// of ConsumerWork2, so they cannot be done concurrently.
// These functions are currently doing pointless work, but
// can be replaced with more useful operations.
float ConsumerWork1(float f) {
float output = f;
for (int j = 0; j < kComplexity1; j++) {
output = 20 * f + j - output;
}
return output;
}
float ConsumerWork2(float f) {
auto output = f;
for (int j = 0; j < kComplexity2; j++) {
output = output + f * j;
}
return output;
}
/////////////////////////////////////////////////////////////
// Pre-optimization kernel versions
/////////////////////////////////////////////////////////////
// The Producer kernel reads data from a SYCL buffer and writes it to
// a pipe. This transfers the input data from the host to the Consumer kernel
// that is running concurrently.
// The Consumer kernel reads data from the pipe, performs the two ConsumerWork
// operations on the data, and writes the results to the output buffer.
void ProducerBefore(queue &q, buffer<float, 1> &buffer_a) {
auto e = q.submit([&](handler &h) {
// Get kernel access to the buffers
accessor a(buffer_a, h, read_only);
h.single_task<ProducerBeforeKernel>([=]() {
for (int i = 0; i < kSize; i++) {
ProducerToConsumerBeforePipe::write(a[i]);
}
});
});
}
void ConsumerBefore(queue &q, buffer<float, 1> &buffer_a) {
auto e = q.submit([&](handler &h) {
// Get kernel access to the buffers
accessor a(buffer_a, h, write_only, no_init);
h.single_task<ConsumerBeforeKernel>([=]() {
for (int i = 0; i < kSize; i++) {
auto input = ProducerToConsumerBeforePipe::read();
auto output = ConsumerWork1(input);
output = ConsumerWork2(output);
a[i] = output;
}
});
});
}
/////////////////////////////////////////////////////////////
// Post-optimization kernel versions
/////////////////////////////////////////////////////////////
// The Producer kernel reads data from a SYCL buffer and does
// ConsumerWork1 on it before giving it to the concurrently
// running Consumer kernel.
// The Consumer kernel reads data from the pipe, performs the rest
// of the work (ConsumerWork2), and writes the results
// to the output buffer.
void ProducerAfter(queue &q, buffer<float, 1> &buffer_a) {
auto e = q.submit([&](handler &h) {
// Get kernel access to the buffers
accessor a(buffer_a, h, read_only);
h.single_task<ProducerAfterKernel>([=]() {
for (int i = 0; i < kSize; i++) {
auto input = a[i];
auto output = ConsumerWork1(input);
ProducerToConsumerAfterPipe::write(output);
}
});
});
}
void ConsumerAfter(queue &q, buffer<float, 1> &buffer_a) {
auto e = q.submit([&](handler &h) {
// Get kernel access to the buffers
accessor a(buffer_a, h, write_only, no_init);
h.single_task<ConsumerAfterKernel>([=]() {
for (int i = 0; i < kSize; i++) {
auto buffer1_data = ProducerToConsumerAfterPipe::read();
auto output = ConsumerWork2(buffer1_data);
a[i] = output;
}
});
});
}
/////////////////////////////////////////////////////////////
// Compares kernel output against expected output. Only compares part of the
// output so that this method completes quickly. This is done
// intentionally/artificially to keep host-processing time shorter than kernel
// execution time. Grabs kernel output data from its SYCL buffers.
bool ProcessOutput(buffer<float, 1> &input_buf, buffer<float, 1> &output_buf) {
host_accessor input_buf_acc(input_buf, read_only);
host_accessor output_buf_acc(output_buf, read_only);
int num_errors = 0;
int num_errors_to_print = 5;
bool pass = true;
// Max fractional difference between FPGA result and CPU result
// Anything greater than this will be considered an error
constexpr double epsilon = 0.01;
for (int i = 0; i < kSize / 8; i++) {
auto step1 = ConsumerWork1(input_buf_acc[i]);
auto valid_result = ConsumerWork2(step1);
const bool out_invalid =
std::abs((output_buf_acc[i] - valid_result) / valid_result) > epsilon;
if ((num_errors < num_errors_to_print) && out_invalid) {
if (num_errors == 0) {
pass = false;
std::cout << "Verification failed. Showing up to "
<< num_errors_to_print << " mismatches.\n";
}
std::cout << "Verification failed on the output buffer, "
<< "at element " << i << ". Expected " << valid_result
<< " but got " << output_buf_acc[i] << "\n";
num_errors++;
}
}
return pass;
}
int main() {
// Create queue, get platform and device
#if FPGA_SIMULATOR
auto selector = sycl::ext::intel::fpga_simulator_selector_v;
#elif FPGA_HARDWARE
auto selector = sycl::ext::intel::fpga_selector_v;
#else // #if FPGA_EMULATOR
auto selector = sycl::ext::intel::fpga_emulator_selector_v;
std::cout << "\nThe Dynamic Profiler cannot be used in the emulator "
"flow. Please compile to FPGA hardware or simulator flow "
"to collect dynamic profiling data. \n\n";
#endif
try {
queue q(selector, fpga_tools::exception_handler);
auto device = q.get_device();
std::cout << "Running on device: "
<< device.get_info<sycl::info::device::name>().c_str()
<< std::endl;
std::vector<float> producer_input(kSize, -1);
std::vector<float> consumer_output_before(kSize, -1);
std::vector<float> consumer_output_after(kSize, -1);
// Initialize the input data
std::iota(producer_input.begin(), producer_input.end(), 1);
buffer producer_buffer(producer_input);
buffer consumer_buffer_before(consumer_output_before);
buffer consumer_buffer_after(consumer_output_after);
std::cout << "*** Beginning execution before optimization.\n";
ProducerBefore(q, producer_buffer);
ConsumerBefore(q, consumer_buffer_before);
bool pass_before = ProcessOutput(producer_buffer, consumer_buffer_before);
if (pass_before) {
std::cout << "Verification PASSED for run before optimization\n";
}
std::cout << "*** Beginning execution after optimization.\n";
ProducerAfter(q, producer_buffer);
ConsumerAfter(q, consumer_buffer_after);
bool pass_after = ProcessOutput(producer_buffer, consumer_buffer_after);
if (pass_after) {
std::cout << "Verification PASSED for run after optimization\n";
}
if (pass_before && pass_after) {
std::cout << "Verification PASSED\n";
} else {
std::cout << "Verification FAILED\n";
return 1;
}
} catch (sycl::exception const &e) {
// Catches exceptions in the host code
std::cerr << "Caught a SYCL host exception:\n" << e.what() << "\n";
// Most likely the runtime couldn't find FPGA hardware!
if (e.code().value() == CL_DEVICE_NOT_FOUND) {
std::cerr << "If you are targeting an FPGA, please ensure that your "
"system has a correctly configured FPGA board.\n";
std::cerr << "Run sys_check in the oneAPI root directory to verify.\n";
std::cerr << "If you are targeting the FPGA emulator, compile with "
"-DFPGA_EMULATOR.\n";
}
std::terminate();
}
return 0;
}
| cpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/include/streaming_eigen.hpp | #ifndef __STREAMING_QRD_HPP__
#define __STREAMING_QRD_HPP__
#include <sycl/ext/intel/ac_types/ac_int.hpp>
#include "constexpr_math.hpp"
#include "tuple.hpp"
#include "unrolled_loop.hpp"
namespace fpga_linalg {
/*
Computes 1e-Is as a constexpr
*/
template <typename T, std::size_t... Is>
constexpr T negPow10(std::index_sequence<Is...> const &) {
using unused = std::size_t[];
T ret{1};
(void)unused{0U, (ret /= 10, Is)...};
return ret;
}
/*
This function implements the QR iteration method to find the Eigen values
and vectors of the input square matrices.
In order to reduce the number of iterations to perform, the Wilkinson shift
is applied at each iteration.
Each matrix (input and output) are represented in a column wise (transposed).
Then input and output matrices are consumed/produced from/to pipes.
*/
template <typename T, // The datatype for the computation
int size, // Number of rows/columns in the A matrices
int raw_latency, // Read after write latency (in iterations) of
// the triangular loop of this function.
// This value depends on the FPGA target, the
// datatype, the target frequency, etc.
// This value will have to be tuned for optimal
// performance. Refer to the Triangular Loop
// design pattern tutorial.
// In general, find a high value for which the
// compiler is able to achieve an II of 1 and
// go down from there.
int pipe_size, // Number of elements read/write per pipe
// operation
int zero_threshold_1e, // Threshold from which we consider a
// floating point value to be 0 (e.g. -4 ->
// 10e-4)
typename AIn, // A matrix input pipe, receive pipe_size
// elements from the pipe with each read
typename EigenValuesOut, // Eigen values output pipe, send 1
// element to the pipe with each write
typename EigenVectorsOut, // Eigen vectors output pipe, send
// pipe_size elements to the pipe with each
// write.
typename RankDeficientOut // Outputs a 1 bit value per Eigen vector
// matrix that is 1 if the input matrix
// is considered rank deficient. In this
// case, an Eigen value is 0, and the
// associated Eigen vector is forced to 0.
>
struct StreamingEigen {
void operator()() const {
// Functional limitations
// static_assert(size >= 4,
// "only matrices of size 4x4 and over are supported");
static_assert(zero_threshold_1e < 0,
"k_zero_threshold_1e must be negative");
constexpr float k_zero_threshold =
negPow10<float>(std::make_index_sequence<-zero_threshold_1e>{});
// Type used to store the matrices in the QR decomposition compute loop
using column_tuple = fpga_tools::NTuple<T, size>;
// Fanout reduction factor for signals that fanout to size compute cores
constexpr int kFanoutReduction = 8;
// Number of signal replication required to cover all the size compute cores
// given a kFanoutReduction factor
constexpr int kBanksForFanout = (size % kFanoutReduction)
? (size / kFanoutReduction) + 1
: size / kFanoutReduction;
// Number of iterations performed without any dummy work added for the
// triangular loop optimization
constexpr int kVariableIterations = size - raw_latency;
// Total number of dummy iterations
static constexpr int kDummyIterations =
raw_latency > size ? (size - 1) * size / 2 + (raw_latency - size) * size
: raw_latency * (raw_latency - 1) / 2;
// Total number of iterations (including dummy iterations)
static constexpr int kIterations =
size + size * (size + 1) / 2 + kDummyIterations;
// Size in bits of the "i" loop variable in the triangular loop
// i starts from -1 as we are doing a full copy of the matrix read from the
// pipe to a "compute" matrix before starting the decomposition
constexpr int kIBitSize = fpga_tools::BitsForMaxValue<size + 1>() + 1;
// j starts from i, so from -1 and goes up to size
// So we need:
// -> enough bits to encode size+1 for the positive iterations and
// the exit condition
// -> one extra bit for the -1
// But j may start below -1 if we perform more dummy iterations than the
// number of size in the matrix.
// In that case, we need:
// -> enough bits to encode size+1 for the positive iterations and
// the exit condition
// -> enough bits to encode the maximum number of negative iterations
static constexpr int kJNegativeIterations =
kVariableIterations < 0 ? -kVariableIterations : 1;
static constexpr int kJBitSize =
fpga_tools::BitsForMaxValue<size + 1>() +
fpga_tools::BitsForMaxValue<kJNegativeIterations>();
// Compute Eigen values and vectors as long as matrices are given as inputs
while (1) {
// ---------------------------------
// -------- Load the matrix from DDR
//----------------------------------
// Break memories up to store 4 complex numbers (32 bytes) per bank
constexpr short kBankwidth = pipe_size * sizeof(T);
constexpr unsigned short kNumBanks = size / pipe_size;
// When specifying numbanks for a memory, it must be a power of 2.
// Unused banks will be automatically optimized away.
constexpr short kNumBanksNextPow2 =
fpga_tools::Pow2(fpga_tools::CeilLog2(kNumBanks));
[[intel::numbanks(kNumBanksNextPow2)]] // NO-FORMAT: Attribute
[[intel::bankwidth(kBankwidth)]] // NO-FORMAT: Attribute
[[intel::private_copies(4)]] // NO-FORMAT: Attribute
[[intel::max_replicates(1)]] // NO-FORMAT: Attribute
column_tuple a_load[size];
// Copy a matrix from the pipe to a local memory
// Number of pipe reads of pipe_size required to read a full column
constexpr int kExtraIteration = (size % pipe_size) != 0 ? 1 : 0;
constexpr int kLoopIterPerColumn = size / pipe_size + kExtraIteration;
// Number of pipe reads of pipe_size to read all the matrices
constexpr int kLoopIter = kLoopIterPerColumn * size;
// Size in bits of the loop iterator over kLoopIter iterations
constexpr int kLoopIterBitSize =
fpga_tools::BitsForMaxValue<kLoopIter + 1>();
[[intel::initiation_interval(1)]] // NO-FORMAT: Attribute
for (ac_int<kLoopIterBitSize, false> li = 0; li < kLoopIter; li++) {
fpga_tools::NTuple<T, pipe_size> pipe_read = AIn::read();
int write_idx = li % kLoopIterPerColumn;
int a_col_index = li / kLoopIterPerColumn;
fpga_tools::UnrolledLoop<kLoopIterPerColumn>([&](auto k) {
fpga_tools::UnrolledLoop<pipe_size>([&](auto t) {
if (write_idx == k) {
if constexpr (k * pipe_size + t < size) {
a_load[a_col_index].template get<k * pipe_size + t>() =
pipe_read.template get<t>();
}
}
// Delay data signals to create a vine-based data distribution
// to lower signal fanout.
pipe_read.template get<t>() =
sycl::ext::intel::fpga_reg(pipe_read.template get<t>());
});
write_idx = sycl::ext::intel::fpga_reg(write_idx);
});
}
// ------------------------------------------------
// -------- Initialize matrices for the iteration
//-------------------------------------------------
T rq_matrix[size][size];
T eigen_vectors_matrix[size][size];
T eigen_vectors_matrix_output[size][size];
// Vector to hold the computed Eigen values
T eigen_values[size];
// Initialize shift values
// Compute the shift value of the current matrix
T shift_value = 0;
// First find where the shift should be applied
// Start from the last submatrix
int shift_row = size - 2;
// At each iteration we are going to compute the shift as follows:
// Take the submatrix:
// [a b]
// [b c]
// where a and c are diagonal elements, and [a b] is on row shift_row
// and compute the shift such as
// mu = c - (sign(d)* b*b)/(abs(d) + sqrt(d*d + b*b))
// where d = (a - c)/2
T a = 0, b = 0, c = 0;
// Because we won't know the actual shift_row location at the time of
// retrieving these a b and c data, we will also collect the
// submatrix one row above
T a_above = 0, b_above = 0, c_above = 0;
// ---------------------------------
// -------- Start the QR iteration
//----------------------------------
bool continue_iterating = true;
int iteration_count = 0;
bool input_matrix_is_rank_deficient = false;
while (continue_iterating) {
// ---------------------------------------
// -------- Compute the QR decomposition
//----------------------------------------
/*
This code implements a OneAPI optimized variation of the following
algorithm
for i=0:n
for j=max(i,1):n
if(j==i)
Q_i = a_i*ir
else
if(i>=0)
a_j = a_j - s[j]*a_i
if j=i+1
pip1 = <a_{i+1},a_{i+1}>
ir = 1/sqrt(pip1)
R_{i+1,i+1} = sqrt(pip1)
else
p = <a_{i+1}, a_j>
s[j] = p/pip1
R_{i+1,j} = p*ir
Where:
-> X_i represents the column i of the matrix X
-> <x,y> represents the dot product of the vectors x and y
*/
// Matrices used by the QR algorithm to:
// - store intermediate results
// - store the Q matrix
[[intel::numbanks(kNumBanksNextPow2)]] // NO-FORMAT: Attribute
[[intel::bankwidth(kBankwidth)]] // NO-FORMAT: Attribute
[[intel::private_copies(4)]] // NO-FORMAT: Attribute
[[intel::max_replicates(1)]] // NO-FORMAT: Attribute
column_tuple a_compute[size],
q_matrix[size];
// Matrix to hold the R matrix
[[intel::private_copies(4)]] // NO-FORMAT: Attribute
T r_matrix[size][size];
// a local copy of a_{i+1} that is used across multiple j iterations
// for the computation of pip1 and p
T a_ip1[size];
// a local copy of a_ip1 that is used across multiple j iterations
// for the computation of a_j
T a_i[size];
// Depending on the context, will contain:
// -> -s[j]: for all the iterations to compute a_j
// -> ir: for one iteration per j iterations to compute Q_i
[[intel::fpga_memory]] // NO-FORMAT: Attribute
[[intel::private_copies(2)]] // NO-FORMAT: Attribute
T s_or_ir[size];
T pip1, ir;
// Initialization of the i and j variables for the triangular loop
ac_int<kIBitSize, true> i = -1;
ac_int<kJBitSize, true> j = 0;
// We keep track of the value of the current column
// If it's a 0 vector, then we need to skip the iteration
// This will result in size in Q being set to 0
// This occurs when the input matrix have linearly dependent columns
bool projection_is_zero = false;
[[intel::initiation_interval(1)]] // NO-FORMAT: Attribute
[[intel::ivdep(raw_latency)]] // NO-FORMAT: Attribute
for (int s = 0; s < kIterations; s++) {
// Pre-compute the next values of i and j
ac_int<kIBitSize, true> next_i;
ac_int<kJBitSize, true> next_j;
if (j == size - 1) {
// If i reached an index at which the j inner loop don't have
// enough time to write its result for the next i iteration,
// some "dummy" iterations are introduced
next_j = (kVariableIterations > i)
? ac_int<kJBitSize, true>{i + 1}
: ac_int<kJBitSize, true>{kVariableIterations};
next_i = i + 1;
} else {
next_j = j + 1;
next_i = i;
}
// Two matrix size for partial results.
T col[size];
T col1[size];
// Current value of s_or_ir depending on the value of j
// It is replicated kFanoutReduction times to reduce fanout
T s_or_ir_j[kBanksForFanout];
// All the control signals are precomputed and replicated
// kFanoutReduction times to reduce fanout
bool j_eq_i[kBanksForFanout], i_gt_0[kBanksForFanout],
i_ge_0_j_ge_i[kBanksForFanout], j_eq_i_plus_1[kBanksForFanout],
i_lt_0[kBanksForFanout], j_ge_0[kBanksForFanout];
fpga_tools::UnrolledLoop<kBanksForFanout>([&](auto k) {
i_gt_0[k] = sycl::ext::intel::fpga_reg(i > 0);
i_lt_0[k] = sycl::ext::intel::fpga_reg(i < 0);
j_eq_i[k] = sycl::ext::intel::fpga_reg(j == i);
j_ge_0[k] = sycl::ext::intel::fpga_reg(j >= 0);
i_ge_0_j_ge_i[k] = sycl::ext::intel::fpga_reg(i >= 0 && j >= i);
j_eq_i_plus_1[k] = sycl::ext::intel::fpga_reg(j == i + 1);
if (j >= 0) {
s_or_ir_j[k] = sycl::ext::intel::fpga_reg(s_or_ir[j]);
}
});
// Preload col and a_i with the correct data for the current iteration
// These are going to be use to compute the dot product of two
// different size of the input matrix.
fpga_tools::UnrolledLoop<size>([&](auto k) {
// find which fanout bank this unrolled iteration is going to use
constexpr auto fanout_bank_idx = k / kFanoutReduction;
// Load col with the current column of matrix A.
// At least one iteration of the outer loop i is required
// for the "working copy" a_compute to contain data.
// If no i iteration elapsed, we must read the column of
// matrix A directly from the a_load; col then contains a_j
if (i_gt_0[fanout_bank_idx] && j_ge_0[fanout_bank_idx]) {
col[k] = a_compute[j].template get<k>();
}
// Using an else statement makes the compiler throw an
// inexplicable warning when using non complex types:
// "Compiler Warning: Memory instruction with unresolved
// pointer may lead to bad QoR."
if (!i_gt_0[fanout_bank_idx] && j_ge_0[fanout_bank_idx]) {
if (iteration_count == 0) {
col[k] = a_load[j].template get<k>();
} else {
T to_sub = k == j ? shift_value : T{0};
col[k] = rq_matrix[j][k] - to_sub;
}
}
// Load a_i for reuse across j iterations
if (i_lt_0[fanout_bank_idx]) {
a_i[k] = 0;
} else if (j_eq_i[fanout_bank_idx]) {
a_i[k] = col[k];
}
});
fpga_tools::UnrolledLoop<size>([&](auto k) {
// find which fanout bank this unrolled iteration is going to use
constexpr auto fanout_bank_idx = k / kFanoutReduction;
// Depending on the iteration this code will compute either:
// -> If i=j, a column of Q: Q_i = a_i*ir
// In that case, no term is added to the mult_add construct
// -> If i!=j, an updated column of a: a_j - s[j]*a_i
// There is a special case if i<0 where a_j is unmodified
// but the i iteration is still required to fill ir and s
// for subsequent iterations
auto prod_lhs = a_i[k];
auto prod_rhs =
i_lt_0[fanout_bank_idx] ? T{0.0} : s_or_ir_j[fanout_bank_idx];
auto add = j_eq_i[fanout_bank_idx] ? T{0.0} : col[k];
col1[k] = prod_lhs * prod_rhs + add;
// Store Q_i in q_matrix and the modified a_j in a_compute
// To reduce the amount of control, q_matrix and a_compute
// are both written to for each iteration of i>=0 && j>=i
// In fact:
// -> q_matrix could only be written to at iterations i==j
// -> a_compute could only be written to at iterations
// j!=i && i>=0
// The extra writes are harmless as the locations written to
// are either going to be:
// -> overwritten for the matrix Q (q_matrix)
// -> unused for the a_compute
if (i_ge_0_j_ge_i[fanout_bank_idx] && j_ge_0[fanout_bank_idx]) {
q_matrix[j].template get<k>() = col1[k];
a_compute[j].template get<k>() = col1[k];
}
// Store a_{i+1} for subsequent iterations of j
if (j_eq_i_plus_1[fanout_bank_idx]) {
a_ip1[k] = col1[k];
}
});
// Perform the dot product <a_{i+1},a_{i+1}> or <a_{i+1}, a_j>
T p_ij{0.0};
fpga_tools::UnrolledLoop<size>(
[&](auto k) { p_ij += col1[k] * a_ip1[k]; });
bool projection_is_zero_local = false;
// Compute pip1 and ir based on the results of the dot product
if (j == i + 1) {
// If the projection is 0, we won't be able to divide by pip1 (=p_ij)
projection_is_zero_local = p_ij < k_zero_threshold*k_zero_threshold;
projection_is_zero |= projection_is_zero_local;
ir = sycl::rsqrt(p_ij);
pip1 = p_ij;
}
// Compute the value of -s[j]
T s_j;
if (projection_is_zero_local) {
s_j = T{0};
} else {
s_j = -p_ij / pip1;
}
// j may be negative if the number of "dummy" iterations is
// larger than the matrix size
if (j >= 0) {
s_or_ir[j] = j == i + 1 ? ir : s_j;
}
// Compute the R_{i+1,i+1} or R_{i+1,j}
T r_ip1j = j == i + 1 ? sycl::sqrt(pip1) : ir * p_ij;
// Write the computed R value when j is not a "dummy" iteration
if ((j >= i + 1) && (i + 1 < size)) {
r_matrix[i + 1][j] = r_ip1j;
}
// Update loop indexes
if (j == (size - 1)) {
// If i reached an index at which the j inner loop doesn't have
// enough time to write its result for the next i iteration,
// some "dummy" iterations are introduced
j = (kVariableIterations > i)
? ac_int<kJBitSize, true>{i + 1}
: ac_int<kJBitSize, true>{kVariableIterations};
i = i + 1;
} else {
j = j + 1;
}
} // end of for:s
// ---------------------------------------------------
// -------- Compute R*Q and update the Eigen vectors
//----------------------------------------------------
bool row_is_zero = true;
T rq_matrix_copy[size][size];
for (int row = size-1; row >= 0; row--) {
T eigen_vectors_row[size];
fpga_tools::UnrolledLoop<size>([&](auto t) {
if (iteration_count == 0) {
eigen_vectors_row[t] = t == row ? 1 : 0;
} else {
eigen_vectors_row[t] = eigen_vectors_matrix[row][t];
}
});
for (int column = 0; column < size; column++) {
T dot_product_rq = 0;
T dot_product_eigen_vectors = 0;
fpga_tools::UnrolledLoop<size>([&](auto t) {
T r_elem = r_matrix[row][t];
T r = row > t ? T{0} : r_elem;
dot_product_rq += r * q_matrix[column].template get<t>();
dot_product_eigen_vectors +=
eigen_vectors_row[t] * q_matrix[column].template get<t>();
});
T rq_value =
row == column ? dot_product_rq + shift_value : dot_product_rq;
if (column > row) {
rq_matrix[row][column] = rq_matrix_copy[column][row];
} else if (row <= (shift_row + 1) && column <= (shift_row + 1)) {
rq_matrix[row][column] = rq_value;
rq_matrix_copy[row][column] = rq_value;
}
eigen_vectors_matrix[row][column] = dot_product_eigen_vectors;
eigen_vectors_matrix_output[column][row] =
dot_product_eigen_vectors;
if ((row == shift_row) && (column == shift_row)) {
a = rq_value;
c_above = rq_value;
} else if ((row == shift_row - 1) && (column == (shift_row - 1))) {
a_above = rq_value;
} else if ((row == shift_row) && (column == (shift_row + 1))) {
b = rq_value;
} else if ((row == shift_row - 1) && (column == shift_row)) {
b_above = rq_value;
} else if ((row == shift_row + 1) && (column == shift_row + 1)) {
c = rq_value;
}
if ((row > column) && (row == shift_row + 1)) {
row_is_zero &= fabs(rq_value) < k_zero_threshold;
}
if (row == column) {
eigen_values[row] = rq_value;
}
}
}
// Compute the shift value
T d = (a - c) / 2;
T b_squared = b * b;
T d_squared = d * d;
T b_squared_signed = d < 0 ? -b_squared : b_squared;
T shift_value_current_shift_row =
c - b_squared_signed / (abs(d) + sqrt(d_squared + b_squared));
T d_above = (a_above - c_above) / 2;
T b_squared_above = b_above * b_above;
T d_squared_above = d_above * d_above;
T b_squared_signed_above =
d_above < 0 ? -b_squared_above : b_squared_above;
T shift_value_above =
c_above -
b_squared_signed_above /
(abs(d_above) + sqrt(d_squared_above + b_squared_above));
if ((shift_row < 0) || (row_is_zero && (shift_row == 0))) {
shift_value = 0;
} else {
shift_value =
row_is_zero ? shift_value_above : shift_value_current_shift_row;
}
shift_value *= 0.99;
if (row_is_zero) {
shift_row--;
}
input_matrix_is_rank_deficient |= projection_is_zero;
if (shift_row == -2) {
continue_iterating = false;
}
iteration_count++;
} // end if while(continue_iterating)
// -----------------------------------------------------------------
// -------- Sort the Eigen Values/Vectors by weight
//------------------------------------------------------------------
// Instead of sorting the values and vectors, we sort the order in which
// we are going to traverse the outputs when writing to the pipe
int sorted_indexes[size];
// We are going to traverse the Eigen values to find the current maximum
// value. We use a mask to remember which values have already been used.
ac_int<size, false> mask = 0;
for (int current_index = 0; current_index < size; current_index++) {
int sorted_index = 0;
T max_value = -1;
for (int k = size - 1; k >= 0; k--) {
// Make sure the current Eigen value was not used already
if (mask[k] == 0) {
// Get the Eigen value
T eigen_value = eigen_values[k];
// Get its absolute value
T absolute_value = eigen_value < 0 ? -eigen_value : eigen_value;
// Check if the current Eigen value is larger (in absolute terms)
// than the current max
if (absolute_value > max_value) {
max_value = absolute_value;
sorted_index = k;
}
}
}
sorted_indexes[current_index] = sorted_index;
mask[sorted_index] = 0b1;
}
// -----------------------------------------------------------------
// -------- Write the Eigen values and vectors to the output pipes
//------------------------------------------------------------------
[[intel::initiation_interval(1)]] // NO-FORMAT: Attribute
for (int k = 0; k < size; k++) {
EigenValuesOut::write(eigen_values[sorted_indexes[k]]);
}
ac_int<1, false> to_pipe = input_matrix_is_rank_deficient ? 1 : 0;
RankDeficientOut::write(to_pipe);
[[intel::initiation_interval(1)]] // NO-FORMAT: Attribute
for (ac_int<kLoopIterBitSize, false> li = 0; li < kLoopIter; li++) {
int column_iter = li % kLoopIterPerColumn;
bool get[kLoopIterPerColumn];
fpga_tools::UnrolledLoop<kLoopIterPerColumn>([&](auto k) {
get[k] = column_iter == k;
column_iter = sycl::ext::intel::fpga_reg(column_iter);
});
fpga_tools::NTuple<T, pipe_size> pipe_write;
fpga_tools::UnrolledLoop<kLoopIterPerColumn>([&](auto t) {
fpga_tools::UnrolledLoop<pipe_size>([&](auto k) {
if constexpr (t * pipe_size + k < size) {
pipe_write.template get<k>() =
get[t] ? eigen_vectors_matrix_output
[sorted_indexes[li / kLoopIterPerColumn]]
[t * pipe_size + k]
: sycl::ext::intel::fpga_reg(
pipe_write.template get<k>());
}
});
});
EigenVectorsOut::write(pipe_write);
} // end for:li
} // end of while(1)
} // end of operator
}; // end of struct
} // namespace fpga_linalg
#endif /* __STREAMING_QRD_HPP__ */ | hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/include/onchip_memory_with_cache.hpp | #ifndef __ONCHIP_MEMORY_WITH_CACHE_HPP__
#define __ONCHIP_MEMORY_WITH_CACHE_HPP__
#include <sycl/ext/intel/ac_types/ac_int.hpp>
#include "constexpr_math.hpp" // DirectProgramming/C++SYCL_FPGA/include
#include "unrolled_loop.hpp" // DirectProgramming/C++SYCL_FPGA/include
namespace fpga_tools {
template <typename T, // type to store in the memory
size_t k_mem_depth, // depth of the memory
size_t k_cache_depth // number of elements in the cache
>
class OnchipMemoryWithCache {
public:
static constexpr int kNumAddrBits = fpga_tools::CeilLog2(k_mem_depth);
using addr_t = ac_int<kNumAddrBits, false>;
OnchipMemoryWithCache() {
UnrolledLoop<k_cache_depth>([&](auto i) {
cache_valid_[i] = false;
});
}
OnchipMemoryWithCache(T init_val) { init(init_val); }
void init(T init_val) {
for (int i = 0; i < k_mem_depth; i++) {
data_[i] = init_val;
}
UnrolledLoop<k_cache_depth>([&](auto i) {
cache_valid_[i] = false;
});
}
OnchipMemoryWithCache(const OnchipMemoryWithCache&) = delete;
OnchipMemoryWithCache& operator=(const OnchipMemoryWithCache&) = delete;
// explicitly communicate to developers that we don't want to support a
// square bracket operator that returns a reference, as it would allow
// modification of the memory without updating the cache
template <typename I>
T& operator[](I addr) = delete;
// we can support the square bracket operator that returns a const ref
const T& operator[](addr_t addr) const { return read(addr); }
void write(addr_t addr, T val) {
// write the value from the end of the cache into the memory
if (cache_valid_[0]) {
data_[cache_addr_[0]] = cache_val_[0];
}
// Shift the values in the cache
UnrolledLoop<k_cache_depth - 1>([&](auto i) {
if (cache_addr_[i + 1] == addr) {
cache_valid_[i] = false; // invalidate old cache entry at same addr
} else {
cache_valid_[i] = cache_valid_[i + 1];
}
cache_val_[i] = cache_val_[i + 1];
cache_addr_[i] = cache_addr_[i + 1];
});
// write the new value into the cache
cache_val_[k_cache_depth - 1] = val;
cache_addr_[k_cache_depth - 1] = addr;
cache_valid_[k_cache_depth - 1] = true;
}
T read(addr_t addr) {
T return_val;
bool in_cache = false;
// check the cache, newest value will take precedence
UnrolledLoop<k_cache_depth>([&](auto i) {
if ((cache_addr_[i] == addr) && (cache_valid_[i])) {
return_val = cache_val_[i];
in_cache = true;
}
});
// if not in the cache, fetch from memory
if (!in_cache) {
return_val = data_[addr];
}
return return_val;
}
private:
T data_[k_mem_depth];
T cache_val_[k_cache_depth];
addr_t cache_addr_[k_cache_depth];
bool cache_valid_[k_cache_depth];
}; // class OnchipMemoryWithCache
// specialization for cache size 0 (no cache)
template <typename T, // type to store in the memory
size_t k_mem_depth // depth of the memory
>
class OnchipMemoryWithCache<T, k_mem_depth, 0> {
public:
static constexpr int kNumAddrBits = fpga_tools::CeilLog2(k_mem_depth);
using addr_t = ac_int<kNumAddrBits, false>;
OnchipMemoryWithCache() {}
OnchipMemoryWithCache(T init_val) {
for (int i = 0; i < k_mem_depth; i++) {
data_[i] = init_val;
}
}
OnchipMemoryWithCache(const OnchipMemoryWithCache&) = delete;
OnchipMemoryWithCache& operator=(const OnchipMemoryWithCache&) = delete;
template <typename I>
T& operator[](I addr) = delete;
const T& operator[](addr_t addr) const { return read(addr); }
void write(addr_t addr, T val) { data_[addr] = val; }
T read(addr_t addr) { return data_[addr]; }
private:
T data_[k_mem_depth];
}; // class OnchipMemoryWithCache<T, k_mem_depth, 0>
} // namespace fpga_tools
#endif // __ONCHIP_MEMORY_WITH_CACHE_HPP__
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/include/metaprogramming_utils.hpp | #ifndef __METAPROGRAMMING_UTILS_HPP__
#define __METAPROGRAMMING_UTILS_HPP__
#include <type_traits>
namespace fpga_tools {
//
// The code below creates the constexprs 'make_integer_range'
// and 'make_index_range' these are akin to 'std::make_integer_sequence'
// and 'std::make_index_sequence', respectively.
// However they allow you to specificy a range and can either increment
// or decrement, rather than a strict increasing sequence
//
template <typename T, typename, T begin, bool increase>
struct integer_range_impl;
// incrementing case
template <typename T, T... N, T begin>
struct integer_range_impl<T, std::integer_sequence<T, N...>, begin, true> {
using type = std::integer_sequence<T, N + begin...>;
};
// decrementing case
template <typename T, T... N, T begin>
struct integer_range_impl<T, std::integer_sequence<T, N...>, begin, false> {
using type = std::integer_sequence<T, begin - N...>;
};
// integer_range
template <typename T, T begin, T end>
using integer_range = typename integer_range_impl<
T, std::make_integer_sequence<T, (begin < end) ? end - begin : begin - end>,
begin, (begin < end)>::type;
//
// make_integer_range
//
// USAGE:
// make_integer_range<int,1,10>{} ==> 1,2,...,9
// make_integer_range<int,10,1>{} ==> 10,9,...,2
//
template <class T, T begin, T end>
using make_integer_range = integer_range<T, begin, end>;
//
// make_index_range
//
// USAGE:
// make_index_range<1,10>{} ==> 1,2,...,9
// make_index_range<10,1>{} ==> 10,9,...,2
//
template <std::size_t begin, std::size_t end>
using make_index_range = integer_range<std::size_t, begin, end>;
//
// The code below creates the constexprs 'make_integer_pow2_sequence'
// and 'make_index_pow2_sequence'. These generate the sequence
// 2^0, 2^1, 2^2, ... , 2^(N-1) = 1,2,4,...,2^(N-1)
//
template <typename T, typename>
struct integer_pow2_sequence_impl;
template <typename T, T... Pows>
struct integer_pow2_sequence_impl<T, std::integer_sequence<T, Pows...>> {
using type = std::integer_sequence<T, (T(1) << Pows)...>;
};
// integer_pow2_sequence
template <typename T, T N>
using integer_pow2_sequence =
typename integer_pow2_sequence_impl<T,
std::make_integer_sequence<T, N>>::type;
//
// make_integer_pow2_sequence
//
// USAGE:
// make_integer_pow2_sequence<int,5>{} ==> 1,2,4,8,16
//
template <class T, T N>
using make_integer_pow2_sequence = integer_pow2_sequence<T, N>;
//
// make_index_pow2_sequence
//
// USAGE:
// make_index_pow2_sequence<5>{} ==> 1,2,4,8,16
//
template <std::size_t N>
using make_index_pow2_sequence = integer_pow2_sequence<std::size_t, N>;
//
// Checks for existence of subscript operator
//
namespace detail {
template <typename... >
using void_t = void;
template<class T, typename = void>
struct has_subscript_impl : std::false_type { };
template<typename T>
struct has_subscript_impl<T, void_t<decltype(std::declval<T>()[1])>>
: std::true_type { };
} // namespace detail
template <typename T>
struct has_subscript {
static constexpr bool value =
std::is_same_v<typename detail::has_subscript_impl<T>::type, std::true_type>;
};
template <typename T>
inline constexpr bool has_subscript_v = has_subscript<T>::value;
//
// checks if a type is any instance of SYCL pipe
//
namespace detail {
template<typename T>
struct is_sycl_pipe_impl : std::false_type {};
template<typename Id, typename T, std::size_t N>
struct is_sycl_pipe_impl<sycl::ext::intel::pipe<Id, T, N>> : std::true_type {};
} // namespace detail
template <typename T>
struct is_sycl_pipe {
static constexpr bool value = detail::is_sycl_pipe_impl<T>{};
};
template <typename T>
inline constexpr bool is_sycl_pipe_v = is_sycl_pipe<T>::value;
} // namespace fpga_tools
#endif /* __METAPROGRAMMING_UTILS_HPP__ */ | hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/include/pipe_utils.hpp | //==============================================================
// Copyright Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#ifndef __PIPE_UTILS_HPP__
#define __PIPE_UTILS_HPP__
#include <sycl/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include <utility>
/*
This header defines the following utilities for use with pipes in SYCL FPGA
designs.
1. PipeArray
Create a collection of pipes that can be indexed like an array.
template <class Id, // identifier for the pipe array
typename BaseTy, // type to write/read for each pipe
size_t min_depth, // minimum capacity of each pipe
size_t... dims // depth of each dimension in the array
// any number of dimensions are supported
>
struct PipeArray
Example usage:
class PipeArrayId;
constexpr int min_depth = 0;
constexpr int num_pipes = 4;
using MyPipeArray = PipeArray<PipeArrayId, int, min_depth, num_pipes>;
...
constexpr int pipe_idx = 1;
MyPipeArray::PipeAt<pipe_idx>::read();
2. PipeDuplicator
Fan-out a single pipe write to multiple pipe instances,
each of which will receive the same data.
A blocking write will perform a blocking write to each pipe.
A non-blocking write will perform a non-blocking write to each pipe,
and set success to true only if ALL writes were successful.
Note that the special case of 0 pipe instances is supported, which can
be useful as a stub for writes to pipes that are not needed in your particular
design.
template <class Id, // name of this PipeDuplicator
typename T, // data type to transfer
typename... Pipes // all pipes to send duplicated writes to
>
struct PipeDuplicator
Example usage:
class PipeID1;
class PipeID2;
using MyPipe1 = sycl::ext::intel::pipe<PipeID1, int>;
using MyPipe2 = sycl::ext::intel::pipe<PipeID2, int>;
class PipeDuplicatorID;
using MyPipeDuplicator = PipeDuplicator<PipeDuplicatorID, int, MyPipe1, MyPipe2>;
...
MyPipeDuplicator::write(1); // write the value 1 to both MyPipe1 and MyPipe2
*/
// =============================================================
// Internal Helper Functions/Structs
// =============================================================
namespace fpga_tools {
namespace detail {
// Templated classes for verifying dimensions when accessing elements in the
// pipe array.
template <size_t dim1, size_t... dims>
struct VerifierDimLayer {
template <size_t idx1, size_t... idxs>
struct VerifierIdxLayer {
static constexpr bool IsValid() {
return idx1 < dim1 &&
(VerifierDimLayer<dims...>::template VerifierIdxLayer<
idxs...>::IsValid());
}
};
};
template <size_t dim>
struct VerifierDimLayer<dim> {
template <size_t idx>
struct VerifierIdxLayer {
static constexpr bool IsValid() { return idx < dim; }
};
};
// Templated classes to perform 'currying' write to all pipes in the array
// Primary template, dummy
template <template <std::size_t...> class WriteFunc, typename BaseTy,
typename PartialSequence, typename... RemainingSequences>
struct write_currying {};
// Induction case
template <template <std::size_t...> class WriteFunc, typename BaseTy,
std::size_t... I, std::size_t... J, typename... RemainingSequences>
struct write_currying<WriteFunc, BaseTy, std::index_sequence<I...>,
std::index_sequence<J...>, RemainingSequences...> {
void operator()(const BaseTy &data, bool &success) const {
(write_currying<WriteFunc, BaseTy, std::index_sequence<I..., J>,
RemainingSequences...>()(data, success),
...);
}
};
// Base case
template <template <std::size_t...> class WriteFunc, typename BaseTy,
std::size_t... I>
struct write_currying<WriteFunc, BaseTy, std::index_sequence<I...>> {
void operator()(const BaseTy &data, bool &success) const {
WriteFunc<I...>()(data, success);
}
};
} // namespace detail
// =============================================================
// PipeArray
// =============================================================
template <class Id, // identifier for the pipe array
typename BaseTy, // type to write/read for each pipe
size_t min_depth, // minimum capacity of each pipe
size_t... dims // depth of each dimension in the array
// any number of dimensions are supported
>
struct PipeArray {
PipeArray() = delete; // ensure we cannot create an instance
template <size_t... idxs>
struct StructId; // the ID of each pipe in the array
// VerifyIndices checks that we only access pipe indicies that are in range
template <size_t... idxs>
struct VerifyIndices {
static_assert(sizeof...(idxs) == sizeof...(dims),
"Indexing into a PipeArray requires as many indices as "
"dimensions of the PipeArray.");
static_assert(fpga_tools::detail::VerifierDimLayer<dims...>::template
VerifierIdxLayer<idxs...>::IsValid(),
"Index out of bounds");
using VerifiedPipe =
sycl::ext::intel::pipe<StructId<idxs...>, BaseTy, min_depth>;
};
// helpers for accessing the dimensions of the pipe array
// usage:
// MyPipeArray::GetNumDims() - number of dimensions in this pipe array
// MyPipeArray::GetDimSize<3>() - size of dimension 3 in this pipe array
static constexpr size_t GetNumDims() { return (sizeof...(dims)); }
template <int dim_num>
static constexpr size_t GetDimSize() {
return std::get<dim_num>(dims...);
}
// PipeAt<idxs...> is used to reference a pipe at a particular index
template <size_t... idxs>
using PipeAt = typename VerifyIndices<idxs...>::VerifiedPipe;
// functor to impllement blocking write to all pipes in the array
template <std::size_t... I>
struct BlockingWriteFunc {
void operator()(const BaseTy &data, bool &success) const {
PipeAt<I...>::write(data);
}
};
// functor to impllement non-blocking write to all pipes in the array
template <std::size_t... I>
struct NonBlockingWriteFunc {
void operator()(const BaseTy &data, bool &success) const {
PipeAt<I...>::write(data, success);
}
};
// helper function for implementing write() call to all pipes in the array
template <template <std::size_t...> class WriteFunc,
typename... IndexSequences>
static void write_currying_helper(const BaseTy &data, bool &success,
IndexSequences...) {
fpga_tools::detail::write_currying<WriteFunc, BaseTy,
std::index_sequence<>, IndexSequences...>()(data, success);
}
// blocking write
// write the same data to all pipes in the array using blocking writes
static void write(const BaseTy &data) {
bool success; // temporary variable, ignored in BlockingWriteFunc
write_currying_helper<BlockingWriteFunc>(
data, success, std::make_index_sequence<dims>()...);
}
// non-blocking write
// write the same data to all pipes in the array using non-blocking writes
static void write(const BaseTy &data, bool &success) {
write_currying_helper<NonBlockingWriteFunc>(
data, success, std::make_index_sequence<dims>()...);
}
}; // end of struct PipeArray
// =============================================================
// PipeDuplicator
// =============================================================
// Connect a kernel that writes to a single pipe to multiple pipe instances,
// each of which will receive the same data.
// A blocking write will perform a blocking write to each pipe. A non-blocking
// write will perform a non-blocking write to each pipe, and set success to
// true only if ALL writes were successful.
// primary template, dummy
template <class Id, // name of this PipeDuplicator
typename T, // data type to transfer
typename... Pipes // all pipes to send duplicated writes to
>
struct PipeDuplicator {};
// recursive case, write to each pipe
template <class Id, // name of this PipeDuplicator
typename T, // data type to transfer
typename FirstPipe, // at least one output pipe
typename... RemainingPipes // additional copies of the output pipe
>
struct PipeDuplicator<Id, T, FirstPipe, RemainingPipes...> {
PipeDuplicator() = delete; // ensure we cannot create an instance
// Non-blocking write
static void write(const T &data, bool &success) {
bool local_success;
FirstPipe::write(data, local_success);
success = local_success;
PipeDuplicator<Id, T, RemainingPipes...>::write(data, local_success);
success &= local_success;
}
// Blocking write
static void write(const T &data) {
FirstPipe::write(data);
PipeDuplicator<Id, T, RemainingPipes...>::write(data);
}
};
// base case for recursion, no pipes to write to
// also useful as a 'null' pipe, writes don't do anything
template <class Id, // name of this PipeDuplicator
typename T // data type to transfer
>
struct PipeDuplicator<Id, T> {
PipeDuplicator() = delete; // ensure we cannot create an instance
// Non-blocking write
static void write(const T & /*data*/, bool &success) { success = true; }
// Blocking write
static void write(const T & /*data*/) {
// do nothing
}
};
} // namespace fpga_tools
#endif /* __PIPE_UTILS_HPP__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/include/streaming_qrd.hpp | #ifndef __STREAMING_QRD_HPP__
#define __STREAMING_QRD_HPP__
#include "constexpr_math.hpp"
#include "tuple.hpp"
#include "unrolled_loop.hpp"
namespace fpga_linalg {
/*
QRD (QR decomposition) - Computes Q and R matrices such that A=QR where:
- A is the input matrix
- Q is a unitary/orthogonal matrix
- R is an upper triangular matrix
This function implements a OneAPI optimized version of the "High performance
QR Decomposition for FPGAs" FPGA'18 paper by Martin Langhammer and Bogdan
Pasca.
Each matrix (input and output) are represented in a column wise (transposed).
Then input and output matrices are consumed/produced from/to pipes.
*/
template <typename T, // The datatype for the computation
bool is_complex, // True if T is ac_complex<X>
int rows, // Number of rows in the A matrices
int columns, // Number of columns in the A matrices
// , must be <= rows
int raw_latency, // Read after write latency (in iterations) of
// the triangular loop of this function.
// This value depends on the FPGA target, the
// datatype, the target frequency, etc.
// This value will have to be tuned for optimal
// performance. Refer to the Triangular Loop
// design pattern tutorial.
// In general, find a high value for which the
// compiler is able to achieve an II of 1 and
// go down from there.
int pipe_size, // Number of elements read/write per pipe
// operation
typename AIn, // A matrix input pipe, receive pipe_size
// elements from the pipe with each read
typename QOut, // Q matrix output pipe, send pipe_size
// elements to the pipe with each write
typename ROut, // R matrix output pipe, send pipe_size
// elements to the pipe with each write.
// Only upper-right elements of R are
// sent in row order, starting with row 0.
bool k_column_order =
true // Default value is true for standard matrix input reads
// (reads the matrix one column at a time). False if read
// order by rows (sweeps the rows by pipe size). Each read
// contains pipe_size samples from the same column, then the
// next read contains samples from the next column.
>
struct StreamingQRD {
void operator()() const {
// Functional limitations
static_assert(rows >= columns,
"only rectangular matrices with rows>=columns are supported");
static_assert(columns >= 4,
"only matrices of size 4x4 and over are supported");
/*
This code implements a OneAPI optimized variation of the following
algorithm
for i=0:n
for j=max(i,1):n
if(j==i)
Q_i = a_i*ir
else
if(i>=0)
a_j = a_j - s[j]*a_i
if j=i+1
pip1 = <a_{i+1},a_{i+1}>
ir = 1/sqrt(pip1)
R_{i+1,i+1} = sqrt(pip1)
else
p = <a_{i+1}, a_j>
s[j] = p/pip1
R_{i+1,j} = p*ir
Where:
-> X_i represents the column i of the matrix X
-> <x,y> represents the dot product of the vectors x and y
*/
// Set the computation type to T or ac_complex<T> depending on the value
// of is_complex
using TT = std::conditional_t<is_complex, ac_complex<T>, T>;
// Type used to store the matrices in the compute loop
using column_tuple = fpga_tools::NTuple<TT, rows>;
// Number of upper-right elements in the R output matrix
constexpr int kRMatrixSize = columns * (columns + 1) / 2;
// Fanout reduction factor for signals that fanout to rows compute cores
constexpr int kFanoutReduction = 8;
// Number of signal replication required to cover all the rows compute cores
// given a kFanoutReduction factor
constexpr int kBanksForFanout = (rows % kFanoutReduction)
? (rows / kFanoutReduction) + 1
: rows / kFanoutReduction;
// Number of iterations performed without any dummy work added for the
// triangular loop optimization
constexpr int kVariableIterations = columns - raw_latency;
// Total number of dummy iterations
static constexpr int kDummyIterations =
raw_latency > columns
? (columns - 1) * columns / 2 + (raw_latency - columns) * columns
: raw_latency * (raw_latency - 1) / 2;
// Total number of iterations (including dummy iterations)
static constexpr int kIterations =
columns + columns * (columns + 1) / 2 + kDummyIterations;
// Size in bits of the "i" loop variable in the triangular loop
// i starts from -1 as we are doing a full copy of the matrix read from the
// pipe to a "compute" matrix before starting the decomposition
constexpr int kIBitSize = fpga_tools::BitsForMaxValue<rows + 1>() + 1;
// j starts from i, so from -1 and goes up to columns
// So we need:
// -> enough bits to encode columns+1 for the positive iterations and
// the exit condition
// -> one extra bit for the -1
// But j may start below -1 if we perform more dummy iterations than the
// number of columns in the matrix.
// In that case, we need:
// -> enough bits to encode columns+1 for the positive iterations and
// the exit condition
// -> enough bits to encode the maximum number of negative iterations
static constexpr int kJNegativeIterations =
kVariableIterations < 0 ? -kVariableIterations : 1;
static constexpr int kJBitSize =
fpga_tools::BitsForMaxValue<columns + 1>() +
fpga_tools::BitsForMaxValue<kJNegativeIterations>();
// Compute QRDs as long as matrices are given as inputs
while (1) {
// Three copies of the full matrix, so that each matrix has a single
// load and a single store.
// a_load is the initial matrix received from the pipe
// a_compute is used and modified during calculations
// q_result is a copy of a_compute and is used to send the final output
// Break memories up to store 4 complex numbers (32 bytes) per bank
constexpr short kBankwidth = pipe_size * sizeof(TT);
constexpr unsigned short kNumBanks = rows / pipe_size;
// When specifying numbanks for a memory, it must be a power of 2.
// Unused banks will be automatically optimized away.
constexpr short kNumBanksNextPow2 =
fpga_tools::Pow2(fpga_tools::CeilLog2(kNumBanks));
[[intel::numbanks(kNumBanksNextPow2)]] // NO-FORMAT: Attribute
[[intel::bankwidth(kBankwidth)]] // NO-FORMAT: Attribute
[[intel::private_copies(4)]] // NO-FORMAT: Attribute
[[intel::max_replicates(1)]] // NO-FORMAT: Attribute
column_tuple a_load[columns],
a_compute[columns], q_result[columns];
// Contains the values of the upper-right part of R in a row by row
// fashion, starting by row 0
[[intel::private_copies(4)]] // NO-FORMAT: Attribute
TT r_result[kRMatrixSize];
// Copy a matrix from the pipe to a local memory
// Number of pipe reads of pipe_size required to read a full column
constexpr int kExtraIteration = (rows % pipe_size) != 0 ? 1 : 0;
constexpr int kLoopIterPerColumn = rows / pipe_size + kExtraIteration;
// Number of pipe reads of pipe_size to read all the matrices
constexpr int kLoopIter = kLoopIterPerColumn * columns;
// Size in bits of the loop iterator over kLoopIter iterations
constexpr int kLoopIterBitSize =
fpga_tools::BitsForMaxValue<kLoopIter + 1>();
[[intel::initiation_interval(1)]] // NO-FORMAT: Attribute
for (ac_int<kLoopIterBitSize, false> li = 0; li < kLoopIter; li++) {
fpga_tools::NTuple<TT, pipe_size> pipe_read = AIn::read();
int write_idx;
int a_col_index;
if constexpr (k_column_order) {
write_idx = li % kLoopIterPerColumn;
a_col_index = li / kLoopIterPerColumn;
} else {
write_idx = li / columns;
a_col_index = li % columns;
}
// int write_idx = li / columns;
fpga_tools::UnrolledLoop<kLoopIterPerColumn>([&](auto k) {
fpga_tools::UnrolledLoop<pipe_size>([&](auto t) {
if (write_idx == k) {
if constexpr (k * pipe_size + t < rows) {
a_load[a_col_index].template get<k * pipe_size + t>() =
pipe_read.template get<t>();
}
}
// Delay data signals to create a vine-based data distribution
// to lower signal fanout.
pipe_read.template get<t>() =
sycl::ext::intel::fpga_reg(pipe_read.template get<t>());
});
write_idx = sycl::ext::intel::fpga_reg(write_idx);
});
}
// Compute the QR Decomposition
// r_result write index
int r_element_index = 0;
// a local copy of a_{i+1} that is used across multiple j iterations
// for the computation of pip1 and p
TT a_ip1[rows];
// a local copy of a_ip1 that is used across multiple j iterations
// for the computation of a_j
TT a_i[rows];
// Depending on the context, will contain:
// -> -s[j]: for all the iterations to compute a_j
// -> ir: for one iteration per j iterations to compute Q_i
[[intel::fpga_memory]] // NO-FORMAT: Attribute
[[intel::private_copies(2)]] // NO-FORMAT: Attribute
TT s_or_ir[columns];
T pip1, ir;
// Initialization of the i and j variables for the triangular loop
ac_int<kIBitSize, true> i = -1;
ac_int<kJBitSize, true> j = 0;
// We keep track of the value of the current column
// If it's a 0 vector, then we need to skip the iteration
// This will result in columns in Q being set to 0
// This occurs when the input matrix have linearly dependent columns
bool projection_is_zero = false;
[[intel::initiation_interval(1)]] // NO-FORMAT: Attribute
[[intel::ivdep(raw_latency)]] // NO-FORMAT: Attribute
for (int s = 0; s < kIterations; s++) {
// Pre-compute the next values of i and j
ac_int<kIBitSize, true> next_i;
ac_int<kJBitSize, true> next_j;
if (j == columns - 1) {
// If i reached an index at which the j inner loop don't have
// enough time to write its result for the next i iteration,
// some "dummy" iterations are introduced
next_j = (kVariableIterations > i)
? ac_int<kJBitSize, true>{i + 1}
: ac_int<kJBitSize, true>{kVariableIterations};
next_i = i + 1;
} else {
next_j = j + 1;
next_i = i;
}
// Two matrix columns for partial results.
TT col[rows];
TT col1[rows];
// Current value of s_or_ir depending on the value of j
// It is replicated kFanoutReduction times to reduce fanout
TT s_or_ir_j[kBanksForFanout];
// All the control signals are precomputed and replicated
// kFanoutReduction times to reduce fanout
bool j_eq_i[kBanksForFanout], i_gt_0[kBanksForFanout],
i_ge_0_j_ge_i[kBanksForFanout], j_eq_i_plus_1[kBanksForFanout],
i_lt_0[kBanksForFanout], j_ge_0[kBanksForFanout];
fpga_tools::UnrolledLoop<kBanksForFanout>([&](auto k) {
i_gt_0[k] = sycl::ext::intel::fpga_reg(i > 0);
i_lt_0[k] = sycl::ext::intel::fpga_reg(i < 0);
j_eq_i[k] = sycl::ext::intel::fpga_reg(j == i);
j_ge_0[k] = sycl::ext::intel::fpga_reg(j >= 0);
i_ge_0_j_ge_i[k] = sycl::ext::intel::fpga_reg(i >= 0 && j >= i);
j_eq_i_plus_1[k] = sycl::ext::intel::fpga_reg(j == i + 1);
if (j >= 0) {
s_or_ir_j[k] = sycl::ext::intel::fpga_reg(s_or_ir[j]);
}
});
// Preload col and a_i with the correct data for the current iteration
// These are going to be use to compute the dot product of two
// different columns of the input matrix.
fpga_tools::UnrolledLoop<rows>([&](auto k) {
// find which fanout bank this unrolled iteration is going to use
constexpr auto fanout_bank_idx = k / kFanoutReduction;
// Load col with the current column of matrix A.
// At least one iteration of the outer loop i is required
// for the "working copy" a_compute to contain data.
// If no i iteration elapsed, we must read the column of
// matrix A directly from the a_load; col then contains a_j
if (i_gt_0[fanout_bank_idx] && j_ge_0[fanout_bank_idx]) {
col[k] = a_compute[j].template get<k>();
}
if (!i_gt_0[fanout_bank_idx] && j_ge_0[fanout_bank_idx]) {
col[k] = a_load[j].template get<k>();
}
// Load a_i for reuse across j iterations
if (i_lt_0[fanout_bank_idx]) {
a_i[k] = 0;
} else if (j_eq_i[fanout_bank_idx]) {
a_i[k] = col[k];
}
});
fpga_tools::UnrolledLoop<rows>([&](auto k) {
// find which fanout bank this unrolled iteration is going to use
constexpr auto fanout_bank_idx = k / kFanoutReduction;
// Depending on the iteration this code will compute either:
// -> If i=j, a column of Q: Q_i = a_i*ir
// In that case, no term is added to the mult_add construct
// -> If i!=j, an updated column of a: a_j - s[j]*a_i
// There is a special case if i<0 where a_j is unmodified
// but the i iteration is still required to fill ir and s
// for subsequent iterations
auto prod_lhs = a_i[k];
auto prod_rhs =
i_lt_0[fanout_bank_idx] ? TT{0.0} : s_or_ir_j[fanout_bank_idx];
auto add = j_eq_i[fanout_bank_idx] ? TT{0.0} : col[k];
if constexpr (is_complex) {
col1[k] = prod_lhs * prod_rhs.conj() + add;
} else {
col1[k] = prod_lhs * prod_rhs + add;
}
// Store Q_i in q_result and the modified a_j in a_compute
// To reduce the amount of control, q_result and a_compute
// are both written to for each iteration of i>=0 && j>=i
// In fact:
// -> q_result could only be written to at iterations i==j
// -> a_compute could only be written to at iterations
// j!=i && i>=0
// The extra writes are harmless as the locations written to
// are either going to be:
// -> overwritten for the matrix Q (q_result)
// -> unused for the a_compute
if (i_ge_0_j_ge_i[fanout_bank_idx] && j_ge_0[fanout_bank_idx]) {
q_result[j].template get<k>() = col1[k];
a_compute[j].template get<k>() = col1[k];
}
// Store a_{i+1} for subsequent iterations of j
if (j_eq_i_plus_1[fanout_bank_idx]) {
a_ip1[k] = col1[k];
}
});
// Perform the dot product <a_{i+1},a_{i+1}> or <a_{i+1}, a_j>
TT p_ij{0.0};
fpga_tools::UnrolledLoop<rows>([&](auto k) {
if constexpr (is_complex) {
p_ij = p_ij + col1[k] * a_ip1[k].conj();
} else {
p_ij = p_ij + col1[k] * a_ip1[k];
}
});
// Compute pip1 and ir based on the results of the dot product
if (j == i + 1) {
// Check if the projection of the current columns is the 0 vector
projection_is_zero = (i >= 0) && (p_ij == 0);
if constexpr (is_complex) {
pip1 = p_ij.r();
} else {
pip1 = p_ij;
}
// If the projection is 0, we set ir to 1 to be a no-op in the next
// iteration when computing Q_i = a_i*ir
if (projection_is_zero) {
ir = 1;
} else {
if constexpr (is_complex) {
ir = sycl::rsqrt(p_ij.r());
} else {
ir = sycl::rsqrt(p_ij);
}
}
}
// Compute the value of -s[j]
TT s_j;
if(projection_is_zero){
s_j = TT{0};
}
else{
if constexpr (is_complex) {
s_j = TT{0.0f - (p_ij.r()) / pip1, p_ij.i() / pip1};
} else {
s_j = -p_ij / pip1;
}
}
// j may be negative if the number of "dummy" iterations is
// larger than the matrix size
if (j >= 0) {
if constexpr (is_complex) {
s_or_ir[j] =
TT{j == i + 1 ? ir : s_j.r(), j == i + 1 ? 0.0f : s_j.i()};
} else {
s_or_ir[j] = j == i + 1 ? ir : s_j;
}
}
// Compute the R_{i+1,i+1} or R_{i+1,j}
TT r_ip1j;
if constexpr (is_complex) {
r_ip1j = j == i + 1 ? TT{sycl::sqrt(pip1), 0.0}
: TT{ir * p_ij.r(), ir * p_ij.i()};
} else {
r_ip1j = j == i + 1 ? sycl::sqrt(pip1) : ir * p_ij;
}
// Write the computed R value when j is not a "dummy" iteration
if ((j >= i + 1) && (i + 1 < columns)) {
r_result[r_element_index] = r_ip1j;
r_element_index++;
}
// Update loop indexes
if (j == (columns - 1)) {
// If i reached an index at which the j inner loop doesn't have
// enough time to write its result for the next i iteration,
// some "dummy" iterations are introduced
j = (kVariableIterations > i)
? ac_int<kJBitSize, true>{i + 1}
: ac_int<kJBitSize, true>{kVariableIterations};
i = i + 1;
} else {
j = j + 1;
}
} // end of s
// Number of upper-right elements in the R output matrix
constexpr int kRMatrixSize = columns * (columns + 1) / 2;
[[intel::initiation_interval(1)]] // NO-FORMAT: Attribute
for (int r_idx = 0; r_idx < kRMatrixSize; r_idx++) {
ROut::write(r_result[r_idx]);
}
[[intel::initiation_interval(1)]] // NO-FORMAT: Attribute
for (ac_int<kLoopIterBitSize, false> li = 0; li < kLoopIter; li++) {
int column_iter = li % kLoopIterPerColumn;
bool get[kLoopIterPerColumn];
fpga_tools::UnrolledLoop<kLoopIterPerColumn>([&](auto k) {
get[k] = column_iter == k;
column_iter = sycl::ext::intel::fpga_reg(column_iter);
});
fpga_tools::NTuple<TT, pipe_size> pipe_write;
fpga_tools::UnrolledLoop<kLoopIterPerColumn>([&](auto t) {
fpga_tools::UnrolledLoop<pipe_size>([&](auto k) {
if constexpr (t * pipe_size + k < rows) {
pipe_write.template get<k>() =
get[t] ? q_result[li / kLoopIterPerColumn]
.template get<t * pipe_size + k>()
: sycl::ext::intel::fpga_reg(
pipe_write.template get<k>());
}
});
});
QOut::write(pipe_write);
}
} // end of while(1)
} // end of operator
}; // end of struct
} // namespace fpga_linalg
#endif /* __STREAMING_QRD_HPP__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/include/rom_base.hpp | #ifndef __ROM_BASE_HPP__
#define __ROM_BASE_HPP__
#include <type_traits>
//
// A base class for creating a constexpr ROM.
//
// TEMPLATE PARAMETERS
// T: the datatype stored in the ROM
// _depth: the depth of the ROM
//
// EXAMPLE USAGE
// To use the ROM, you must create a class that inherits from this class and
// provides a constexpr functor to the constructor which determines how the
// ROM is initialized. The following examples show two methods for creating
// a ROM that stores x^2, where 'x' is the index into the ROM.
//
// USING A FUNCTOR
// struct SquareFunctor {
// constexpr float operator () (int x) const { return x * x }
// constexpr SquareFunctor() = default;
// };
//
// constexpr int lut_depth = 1024;
// struct SquareLUT : ROMBase<int, lut_depth> {
// constexpr SquareLUT() : ROMBase<int, lut_depth>(SquareFunctor()) {}
// };
//
// USING A LAMBDA
// constexpr int lut_depth = 1024;
// struct SquareLUT : ROMBase<int, lut_depth> {
// constexpr SquareLUT() : ROMBase<int, lut_depth>(
// [](int x) { return x * x; }) {}
// };
//
namespace fpga_tools {
template<typename T, int rom_depth>
struct ROMBase {
// ensure a positive depth
static_assert(rom_depth > 0);
// allows the depth of the ROM to be queried
static constexpr int depth = rom_depth;
// allows the type stored in the ROM to be queried
using ValType = T;
// constexpr constructor that initializes the contents of the ROM
// using a user specified Functor. NOTE: the functor must be constexpr,
// which can be achieved with a lambda or by marking the operator() function
// as constexpr.
template<typename InitFunctor>
constexpr ROMBase(const InitFunctor& func) : data_() {
static_assert(std::is_invocable_r_v<T, InitFunctor, int>);
for (int i = 0; i < rom_depth; i++) {
data_[i] = func(i);
}
}
// only define a const operator[], since this is a ROM
const T& operator[](int i) const { return data_[i]; }
protected:
T data_[rom_depth];
};
} // namespace fpga_tools
#endif /* __ROM_BASE_HPP__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/include/streaming_qri.hpp | #ifndef __STREAMING_QRI_HPP__
#define __STREAMING_QRI_HPP__
#include "constexpr_math.hpp"
#include "tuple.hpp"
#include "unrolled_loop.hpp"
namespace fpga_linalg {
/*
QRI (QR inversion) - Given two matrices Q and R from the QR decomposition
of a matrix A such that A=QR, this function computes the inverse of A.
- Input matrix Q (unitary/orthogonal)
- Input matrix R (upper triangular)
- Output matrix I, the inverse of A such that A=QR
Then input and output matrices are consumed/produced from/to pipes.
*/
template <typename T, // The datatype for the computation
bool is_complex, // True if T is ac_complex<T>
int rows, // Number of rows in the input matrices
int columns, // Number of columns in the input matrices
int raw_latency, // Read after write latency (in iterations) of
// the triangular loop of this function.
// This value depends on the FPGA target, the
// datatype, the target frequency, etc.
// This value will have to be tuned for optimal
// performance. Refer to the Triangular Loop
// design pattern tutorial.
// In general, find a high value for which the
// compiler is able to achieve an II of 1 and
// go down from there.
int pipe_size, // Number of elements read/write per pipe
// operation
typename QIn, // Q input pipe, receive a full column with each
// read.
typename RIn, // R input pipe. Receive one element per read.
// Only upper-right elements of R are sent.
// Sent in row order, starting with row 0.
typename IOut // Inverse matrix output pipe.
// The output is written column by column
>
struct StreamingQRI {
void operator()() const {
// Functional limitations
static_assert(rows == columns,
"only square matrices with rows==columns are supported");
static_assert(columns >= 4,
"only matrices of size 4x4 and upper are supported");
// Set the computation type to T or ac_complex<T> depending on the value
// of is_complex
using TT = std::conditional_t<is_complex, ac_complex<T>, T>;
// Continue to compute as long as matrices are given as inputs
while (1) {
// Q matrix read from pipe
[[intel::private_copies(4)]] // NO-FORMAT: Attribute
[[intel::max_replicates(1)]] // NO-FORMAT: Attribute
TT q_matrix[rows][columns];
// Transpose of Q matrix
[[intel::private_copies(4)]] // NO-FORMAT: Attribute
[[intel::max_replicates(1)]] // NO-FORMAT: Attribute
TT qt_matrix[rows][columns];
// Transpose of R matrix
[[intel::private_copies(4)]] // NO-FORMAT: Attribute
[[intel::max_replicates(1)]] // NO-FORMAT: Attribute
TT rt_matrix[rows][columns];
// Inverse of R matrix
[[intel::private_copies(4)]] // NO-FORMAT: Attribute
[[intel::max_replicates(1)]] // NO-FORMAT: Attribute
TT ri_matrix[rows][columns];
[[intel::private_copies(2)]] // NO-FORMAT: Attribute
[[intel::max_replicates(1)]] // NO-FORMAT: Attribute
TT ri_matrix_compute[rows][columns];
// Inverse matrix of A=QR
[[intel::private_copies(4)]] // NO-FORMAT: Attribute
[[intel::max_replicates(1)]] // NO-FORMAT: Attribute
TT i_matrix[rows][columns];
// Transpose the R matrix
[[intel::loop_coalesce(2)]] // NO-FORMAT: Attribute
for (int row = 0; row < rows; row++) {
for (int col = 0; col < columns; col++) {
rt_matrix[col][row] = col < row ? TT{0} : RIn::read();
}
}
// Copy a Q matrix from the pipe to a local memory
// Number of pipe reads of pipe_size required to read a full
// column
constexpr int kExtraIteration = (rows % pipe_size) != 0 ? 1 : 0;
constexpr int kLoopIterPerColumn = rows / pipe_size + kExtraIteration;
// Number of pipe reads of pipe_size to read all the matrices
constexpr int kLoopIter = kLoopIterPerColumn * columns;
// Size in bits of the loop iterator over kLoopIter iterations
constexpr int kLoopIterBitSize =
fpga_tools::BitsForMaxValue<kLoopIter + 1>();
[[intel::initiation_interval(1)]] // NO-FORMAT: Attribute
for (ac_int<kLoopIterBitSize, false> li = 0; li < kLoopIter; li++) {
fpga_tools::NTuple<TT, pipe_size> pipe_read = QIn::read();
int write_idx = li % kLoopIterPerColumn;
fpga_tools::UnrolledLoop<kLoopIterPerColumn>([&](auto k) {
fpga_tools::UnrolledLoop<pipe_size>([&](auto t) {
if (write_idx == k) {
if constexpr (k * pipe_size + t < rows) {
q_matrix[li / kLoopIterPerColumn][k * pipe_size + t] =
pipe_read.template get<t>();
}
}
// Delay data signals to create a vine-based data distribution
// to lower signal fanout.
pipe_read.template get<t>() =
sycl::ext::intel::fpga_reg(pipe_read.template get<t>());
});
write_idx = sycl::ext::intel::fpga_reg(write_idx);
});
}
/*
Compute the inverse of R
The inverse of R is computed using the following algorithm:
RInverse = 0 // matrix initialized to 0
for col=1:n
for row=1:col-n
// Because Id[row][col] = R[row:] * RInverse[:col], we have:
// RInverse[row][col] = (Id[row][col] - R[row:] * RInverse[:col])
/R[col][col]
for k=1:n
dp = R[col][k] * ri_matrix[row][k]
RInverse[row][col] = (Id[row][col] - dp)/R[col][col]
*/
// Count the total number of loop iterations, using the triangular loop
// optimization (refer to the triangular loop optimization tutorial)
constexpr int kNormalIterations = columns * (columns + 1) / 2;
constexpr int kExtraIterations =
raw_latency > rows
? (rows - 1) * (raw_latency - rows) + (rows - 2) * (rows - 1) / 2
: (raw_latency - 2) * (raw_latency - 2 + 1) / 2;
constexpr int kTotalIterations = kNormalIterations + kExtraIterations;
constexpr bool kThereAreExtraInitIterations = rows - 1 < raw_latency - 1;
constexpr int kInitExtraIterations =
kThereAreExtraInitIterations ? raw_latency - 1 : rows - 1;
constexpr int kInitIterations =
(rows - 2) * (rows - 1) / 2 + kInitExtraIterations;
// All the loop control variables with all the requirements to apply
// some shannonization (refer to the shannonization tutorial)
int row = rows - 1;
int row_plus_1 = rows;
int col = 0;
int col_plus_1 = 1;
int row_limit = rows - 1;
int diag_size = 1;
int next_diag_size = 2;
int diag_iteration = 0;
int diag_iteration_plus_1 = 1;
int start_row = rows - 2;
int start_row_plus_1 = rows - 1;
int start_col = 0;
int start_col_plus_1 = 1;
int next_row_limit = rows - 1;
[[intel::ivdep(raw_latency)]] // NO-FORMAT: Attribute
for (int it = 0; it < kTotalIterations + kInitIterations; it++) {
// Only perform work when in not dummy iterations
if (row < rows & col < columns) {
qt_matrix[row][col] = q_matrix[col][row];
TT current_sum = row == col ? TT{1} : TT{0};
TT div_val;
fpga_tools::UnrolledLoop<columns>([&](auto k) {
auto lhs = rt_matrix[col][k];
auto rhs =
(k >= col) || (col < row) ? TT{0} : ri_matrix_compute[row][k];
if (k == col) {
div_val = lhs;
}
current_sum -= lhs * rhs;
});
TT result = current_sum / div_val;
// Write the result to both the working copy and the final matrix
// This is done to only have matrices with a single read and a
// single write.
ri_matrix_compute[row][col] = result;
ri_matrix[row][col] = result;
}
// Update loop indexes
if (row == row_limit) {
row_limit = next_row_limit;
if constexpr (kThereAreExtraInitIterations) {
next_row_limit = (diag_iteration + 2) >= (rows - 2)
? sycl::max(next_diag_size, raw_latency - 1)
: rows - 1;
} else {
next_row_limit =
(diag_iteration + 2) >= rows
? sycl::max(next_diag_size - 2, raw_latency - 1)
: rows - 1;
}
diag_size = next_diag_size;
int to_sum = diag_iteration >= rows - 2 ? -1 : 1;
next_diag_size = diag_size + to_sum;
row = start_row;
row_plus_1 = start_row_plus_1;
col = start_col;
col_plus_1 = start_col_plus_1;
int start = diag_iteration + 1 - rows + 2;
start_col = start < 0 ? 0 : start;
start_col_plus_1 = start_col + 1;
start_row = start >= 0 ? 0 : -start;
start_row_plus_1 = start_row + 1;
diag_iteration = diag_iteration_plus_1;
diag_iteration_plus_1 = diag_iteration_plus_1 + 1;
} else {
row = row_plus_1;
row_plus_1++;
col = col_plus_1;
col_plus_1++;
}
}
// Multiply the inverse of R by the transposition of Q
[[intel::loop_coalesce(2)]] // NO-FORMAT: Attribute
for (int row = 0; row < rows; row++) {
for (int col = 0; col < columns; col++) {
TT dot_product = {0.0};
fpga_tools::UnrolledLoop<rows>([&](auto k) {
if constexpr (is_complex) {
dot_product += ri_matrix[row][k] * qt_matrix[col][k].conj();
} else {
dot_product += ri_matrix[row][k] * qt_matrix[col][k];
}
});
i_matrix[row][col] = dot_product;
} // end of col
} // end of row
// Copy the inverse matrix result to the output pipe
[[intel::initiation_interval(1)]] // NO-FORMAT: Attribute
for (ac_int<kLoopIterBitSize, false> li = 0; li < kLoopIter; li++) {
int column_iter = li % kLoopIterPerColumn;
bool get[kLoopIterPerColumn];
fpga_tools::UnrolledLoop<kLoopIterPerColumn>([&](auto k) {
get[k] = column_iter == k;
column_iter = sycl::ext::intel::fpga_reg(column_iter);
});
fpga_tools::NTuple<TT, pipe_size> pipe_write;
fpga_tools::UnrolledLoop<kLoopIterPerColumn>([&](auto t) {
fpga_tools::UnrolledLoop<pipe_size>([&](auto k) {
if constexpr (t * pipe_size + k < rows) {
pipe_write.template get<k>() =
get[t] ? i_matrix[li / kLoopIterPerColumn][(t * pipe_size) + k]
: sycl::ext::intel::fpga_reg(
pipe_write.template get<k>());
}
});
});
IOut::write(pipe_write);
}
} // end of while (1)
} // end of operator
}; // end of struct
} // namespace fpga_linalg
#endif /* __STREAMING_QRI_HPP__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/include/streaming_cholesky_inversion.hpp | #ifndef __STREAMING_CHOLESKY_INVERSION_HPP__
#define __STREAMING_CHOLESKY_INVERSION_HPP__
#include "constexpr_math.hpp"
#include "tuple.hpp"
#include "unrolled_loop.hpp"
namespace fpga_linalg {
/*
Cholesky decomposition - Computes L such that A=LL* where:
- A is the input matrix (hermitian, positive definite)
- L is a lower triangular matrix
- L* is the conjugate transpose of L
This function implements a modified version of the Cholesky–Banachiewicz
algorithm.
Pseudo code:
int row_size = 0;
for (column = 0; column <= row_size; column++) {
for (row = column; row < rows; row++) {
float sum = 0;
for (k = 0; k < column; k++)
sum += L[row][k] * L[column][k];
if (row == column)
L[row][column] = sqrt(A[row][row] - sum);
else
L[row][column] = (A[row][column] - sum) / L[column][column];
}
}
The input and output matrices are consumed/produced from/to pipes.
*/
template <typename T, // The datatype for the computation
bool is_complex, // True if T is ac_complex<X>
int rows, // Number of rows==columns in the A matrices
int raw_latency, // Read after write (RAW) latency (in iterations) of
// the triangular loop of this function.
// This value depends on the FPGA target, the
// datatype, the target frequency, etc.
// This value will have to be tuned for optimal
// performance. Refer to the Triangular Loop
// design pattern tutorial.
// In general, find a high value for which the
// compiler is able to achieve an II of 1 and
// go down from there.
int pipe_size, // Number of elements read/write per pipe operation
// to read the input matrix
typename LIn, // A matrix input pipe, receive pipe_size
// elements from the pipe with each read
typename IOut // L matrix output pipe, send one elements to the
// pipe with each write.
// Only lower-left elements of L are
// sent in row order, starting with row 0.
>
struct StreamingCholeskyInversion {
void operator()() const {
// Functional assertions
static_assert(rows >= 4,
"Only matrices of size 4x4 and over are supported");
static_assert(pipe_size >= 1,
"The pipe must be able to contain at least one element");
// Set the computation type to T or ac_complex<T> depending on the value
// of is_complex
using TT = std::conditional_t<is_complex, ac_complex<T>, T>;
constexpr int kColumns = rows;
// Compute Cholesky-based inversions as long as L input matrices are given
while (1) {
// The compiler has difficulty automatically figuring out an optimal
// configuration for these memories, so force all relevant parameters.
// The number of private copies ensures the compiler will schedule
// as many overlapping loop iterations as possible
// The code is written so that each memory is single read/single write
// so there is no need for any replicate.
// L matrix read from pipe
[[intel::private_copies(4)]] // NO-FORMAT: Attribute
[[intel::max_replicates(1)]] // NO-FORMAT: Attribute
TT l_matrix[rows][kColumns];
// L inverse matrix for the compute
[[intel::private_copies(4)]] // NO-FORMAT: Attribute
[[intel::max_replicates(1)]] // NO-FORMAT: Attribute
TT li_matrix_compute[rows][kColumns];
// L inverse matrix
[[intel::private_copies(4)]] // NO-FORMAT: Attribute
[[intel::max_replicates(1)]] // NO-FORMAT: Attribute
TT li_matrix[rows][kColumns];
// Final inverse matrix (only the triangular elements)
[[intel::private_copies(4)]] // NO-FORMAT: Attribute
[[intel::max_replicates(1)]] // NO-FORMAT: Attribute
TT i_matrix[kColumns * (kColumns + 1) / 2];
for (int row = 0; row < rows; row++) {
for (int col = 0; col <= row; col++) {
TT element = LIn::read();
if constexpr (is_complex) {
l_matrix[row][col] = element.conj();
} else {
l_matrix[row][col] = element;
}
}
}
/*
Compute the inverse of L
The inverse of L is computed using the following algorithm:
LInverse = 0 // matrix initialized to 0
for col=1:n
for row=1:col-n
// Because Id[row][col] = R[row:] * LInverse[:col], we have:
// LInverse[row][col] = (Id[row][col] - L[row:] * LInverse[:col])
/L[col][col]
for k=1:n
dp = L[col][k] * LInverse[row][k]
LInverse[row][col] = (Id[row][col] - dp)/R[col][col]
*/
// Count the total number of loop iterations, using the triangular loop
// optimization (refer to the Triangular Loop design pattern tutorial)
constexpr int kNormalIterations = kColumns * (kColumns + 1) / 2;
constexpr int kExtraIterations =
(raw_latency > rows) ? ((rows - 1) * (raw_latency - rows)) +
((rows - 2) * (rows - 1)) / 2
: (raw_latency - 2) * (raw_latency - 2 + 1) / 2;
constexpr int kTotalIterations = kNormalIterations + kExtraIterations;
constexpr int kInitIterations = 0;
// All the loop control variables with all the requirements to apply
// some shannonization (refer to the Shannonization tutorial)
/*
This is what the original triangle loop looks like before the
transformation
for(int diag_number = 0; diag_number < kColumns; diag_number++){
int diag_size = std::max(kColumns - diag_number, raw_latency);
if(diag_number == kColumns-1){
diag_size = 1;
}
int col = diag_number;
for(int row = 0; row < diag_size; row++, col++){
if(row<rows && col<kColumns){
//compute
}
}
}
*/
int diagonal_number = 0;
int next_diagonal_number = 1;
int diagonal_size = (kColumns > raw_latency ? kColumns : raw_latency) - 1;
int col = diagonal_number;
int row = 0;
[[intel::ivdep(raw_latency)]] // NO-FORMAT: Attribute
for (int it = 0; it < kTotalIterations + kInitIterations; it++) {
// Only perform work when in not dummy iterations
if ((row < rows) & (col < kColumns)) {
TT current_sum = (row == col) ? TT{1} : TT{0};
TT div_val;
fpga_tools::UnrolledLoop<kColumns>([&](auto k) {
auto li_loaded = l_matrix[col][k];
TT lhs;
if (k > col) {
lhs = TT{0};
} else {
lhs = li_loaded;
}
auto li_compute_load = li_matrix_compute[row][k];
TT rhs;
if ((k >= row) && (k < col)) {
rhs = li_compute_load;
} else {
rhs = TT{0};
}
if (k == col) {
div_val = lhs;
}
current_sum -= lhs * rhs;
});
TT result = current_sum / div_val;
// Write the result to both the working copy and the final matrix
// This is done to only have matrices with a single read and a
// single write.
li_matrix_compute[row][col] = result;
li_matrix[row][col] = result;
}
if (row == diagonal_size) {
diagonal_number = next_diagonal_number;
diagonal_size =
std::max(kColumns - next_diagonal_number, raw_latency) - 1;
col = next_diagonal_number;
row = 0;
next_diagonal_number++;
} else {
row++;
col++;
}
}
int inverse_matrix_write_idx = 0;
// Compute inv(A) = inv(L)*trans(inv(L))
for (int col = 0; col < rows; col++) {
TT col_of_transpose_matrix[rows];
int row_index;
for (int row = col; row < rows; row++) {
if (row >= rows) {
row_index = row - rows;
} else {
row_index = row;
}
TT elem{0};
fpga_tools::UnrolledLoop<kColumns>([&](auto k) {
auto li_load = li_matrix[row_index][k];
if (row_index == col) {
col_of_transpose_matrix[k] = li_load;
}
auto lhs = (k < row_index) ? TT{0} : li_load;
auto rhs = (k < col) ? TT{0} : col_of_transpose_matrix[k];
if constexpr (is_complex) {
elem += lhs * rhs.conj();
} else {
elem += lhs * rhs;
}
});
i_matrix[inverse_matrix_write_idx] = elem;
inverse_matrix_write_idx++;
}
}
int inverse_matrix_read_idx = 0;
for (int loop_count = 0; loop_count < kNormalIterations; loop_count++) {
IOut::write(i_matrix[inverse_matrix_read_idx]);
inverse_matrix_read_idx++;
}
} // end of while(1)
} // end of operator
}; // end of struct
} // namespace fpga_linalg
#endif /* __STREAMING_CHOLESKY_INVERSION_HPP__ */ | hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/include/streaming_matmul.hpp | #ifndef __STREAMING_MATMUL_HPP__
#define __STREAMING_MATMUL_HPP__
#include "constexpr_math.hpp"
#include "tuple.hpp"
#include "unrolled_loop.hpp"
namespace fpga_linalg {
/**
* Matrix multiply kernel.
*
* Repeatedly reads matrix tiles of A and B from input pipes and computes A * B
* using a systolic array of PEs. Writes result matrix tile of C to output pipe.
*
*/
template <typename TT, // Datatype of the elements of the matrix
int common, // Columns of matrix A / rows of matrix B
int tile_a, // Tile size for matrix A
int tile_b, // Tile size for matrix B
typename PipeA, // Input pipe for matrix A
typename PipeB, // Input pipe for matrix B
typename PipeC, // Output pipe for matrix C
typename PipeDone> // Pipe to receive signal to stop reading inputs
class StreamingMatmul {
public:
void operator()() const {
// An array of registers to accumulate the dot products which form the
// output matrix C; one register per PE; initialized to 0 in order to infer
// the FP accumulator
[[intel::fpga_register]] // NO-FORMAT: Attribute
TT accum[tile_a][tile_b];
fpga_tools::UnrolledLoop<tile_a>([&](auto row) {
fpga_tools::UnrolledLoop<tile_b>([&](auto col) {
accum[row][col] = 0;
});
});
// Matrix is flushed out to a secondary register storage when it is fully
// computed, from where it is streamed out to the pipe
[[intel::fpga_register]] // NO-FORMAT: Attribute
TT results[tile_a][tile_b];
constexpr int kCommonBitSize = fpga_tools::BitsForMaxValue<common + 1>();
ac_int<kCommonBitSize, false> counter = 0;
bool write_flag = false;
bool last_pipe_read = false;
// Compute matrix multiplications as long as matrices are given as inputs
[[intel::initiation_interval(1)]] // NO-FORMAT: Attribute
while (1) {
// Between matrices and/or matrix tiles, reset the accumulators to 0
if (counter == 0) {
fpga_tools::UnrolledLoop<tile_a>([&](auto row) {
fpga_tools::UnrolledLoop<tile_b>([&](auto col) {
accum[row][col] = 0;
});
});
}
// Read matrices A and B from the two input pipes; feeder A will send a
// signal when there are no more matrices to compute, at which point we
// should stop reading inputs
fpga_tools::NTuple<TT, tile_a> pipe_read_a;
fpga_tools::NTuple<TT, tile_b> pipe_read_b;
fpga_tools::UnrolledLoop<tile_a>([&](auto row) {
pipe_read_a.template get<row>() = 0;
});
fpga_tools::UnrolledLoop<tile_b>([&](auto col) {
pipe_read_b.template get<col>() = 0;
});
if (!last_pipe_read) {
pipe_read_a = PipeA::read();
pipe_read_b = PipeB::read();
last_pipe_read = PipeDone::read();
}
// Compute the matrix product; fully unrolled loop to describe an array of
// processing elements
fpga_tools::UnrolledLoop<tile_a>([&](auto row) {
fpga_tools::UnrolledLoop<tile_b>([&](auto col) {
pipe_read_a.template get<row>() =
sycl::ext::intel::fpga_reg(pipe_read_a.template get<row>());
pipe_read_b.template get<col>() =
sycl::ext::intel::fpga_reg(pipe_read_b.template get<col>());
TT result = pipe_read_a.template get<row>() *
pipe_read_b.template get<col>() + accum[row][col];
accum[row][col] = result;
// Flush matrix to results array if finished computing
if (counter == (common - 1)) {
results[row][col] = result;
write_flag = true;
}
});
});
if (counter == common - 1) {
counter = 0;
} else {
counter++;
}
// Stop writing while we wait for the next matrix to finish computing
// (only necessary if common > tile_b, i.e., when it takes strictly longer
// to compute than to write to pipe)
if constexpr (common > tile_b) {
if ((counter == tile_b) & write_flag) {
write_flag = false;
}
}
// Write the result matrix C from the registers to the output pipe
if (write_flag) {
fpga_tools::NTuple<TT, tile_a> pipe_write;
fpga_tools::UnrolledLoop<tile_a>([&](auto row) {
pipe_write.template get<row>() = results[row][0];
fpga_tools::UnrolledLoop<tile_b - 1>([&](auto k) {
results[row][k] = results[row][k + 1];
});
});
PipeC::write(pipe_write);
}
} // end of while (1)
} // end of operator
};
} // namespace fpga_linalg
#endif /* __STREAMING_MATMUL_HPP__ */ | hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/include/memory_utils.hpp | #ifndef __MEMORY_UTILS_HPP__
#define __MEMORY_UTILS_HPP__
#include <type_traits>
#include "metaprogramming_utils.hpp"
//
// The utilities in this file are used for converting streaming data to/from
// memory from/to a pipe.
//
namespace fpga_tools {
namespace detail {
//
// Helper to check if a SYCL pipe and pointer have the same base type
//
template <typename PipeT, typename PtrT>
struct pipe_and_pointer_have_same_base {
using PipeBaseT =
std::conditional_t<fpga_tools::has_subscript_v<PipeT>,
std::decay_t<decltype(std::declval<PipeT>()[0])>,
PipeT>;
using PtrBaseT = std::decay_t<decltype(std::declval<PtrT>()[0])>;
static constexpr bool value = std::is_same_v<PipeBaseT, PtrBaseT>;
};
template <typename PipeT, typename PtrT>
inline constexpr bool pipe_and_pointer_have_same_base_v =
pipe_and_pointer_have_same_base<PipeT, PtrT>::value;
//
// Streams data from 'in_ptr' into 'Pipe', 'elements_per_cycle' elements at a
// time
//
template <typename Pipe, int elements_per_cycle, typename PtrT>
void MemoryToPipeRemainder(PtrT in_ptr, size_t full_count,
size_t remainder_count) {
static_assert(fpga_tools::is_sycl_pipe_v<Pipe>);
using PipeT = decltype(Pipe::read());
static_assert(fpga_tools::has_subscript_v<PipeT>);
static_assert(fpga_tools::has_subscript_v<PtrT>);
static_assert(PipeT::size == elements_per_cycle);
static_assert(pipe_and_pointer_have_same_base_v<PipeT, PtrT>);
for (size_t i = 0; i < full_count; i++) {
PipeT pipe_data;
#pragma unroll
for (int j = 0; j < elements_per_cycle; j++) {
pipe_data[j] = in_ptr[i * elements_per_cycle + j];
}
Pipe::write(pipe_data);
}
PipeT pipe_data;
for (size_t i = 0; i < remainder_count; i++) {
pipe_data[i] = in_ptr[full_count * elements_per_cycle + i];
}
Pipe::write(pipe_data);
}
//
// Streams data from 'in_ptr' into 'Pipe', 'elements_per_cycle' elements at a
// time with the guarantee that 'elements_per_cycle' is a multiple of 'count'
//
template <typename Pipe, int elements_per_cycle, typename PtrT>
void MemoryToPipeNoRemainder(PtrT in_ptr, size_t count) {
static_assert(fpga_tools::is_sycl_pipe_v<Pipe>);
using PipeT = decltype(Pipe::read());
static_assert(fpga_tools::has_subscript_v<PipeT>);
static_assert(fpga_tools::has_subscript_v<PtrT>);
static_assert(PipeT::size == elements_per_cycle);
static_assert(pipe_and_pointer_have_same_base_v<PipeT, PtrT>);
for (size_t i = 0; i < count; i++) {
PipeT pipe_data;
#pragma unroll
for (int j = 0; j < elements_per_cycle; j++) {
pipe_data[j] = in_ptr[i * elements_per_cycle + j];
}
Pipe::write(pipe_data);
}
}
//
// Streams data from 'Pipe' to 'out_ptr', 'elements_per_cycle' elements at a
// time
//
template <typename Pipe, int elements_per_cycle, typename PtrT>
void PipeToMemoryRemainder(PtrT out_ptr, size_t full_count,
size_t remainder_count) {
static_assert(fpga_tools::is_sycl_pipe_v<Pipe>);
using PipeT = decltype(Pipe::read());
static_assert(fpga_tools::has_subscript_v<PipeT>);
static_assert(fpga_tools::has_subscript_v<PtrT>);
static_assert(PipeT::size == elements_per_cycle);
static_assert(pipe_and_pointer_have_same_base_v<PipeT, PtrT>);
for (size_t i = 0; i < full_count; i++) {
auto pipe_data = Pipe::read();
#pragma unroll
for (int j = 0; j < elements_per_cycle; j++) {
out_ptr[i * elements_per_cycle + j] = pipe_data[j];
}
}
auto pipe_data = Pipe::read();
for (size_t i = 0; i < remainder_count; i++) {
out_ptr[full_count * elements_per_cycle + i] = pipe_data[i];
}
}
//
// Streams data from 'Pipe' to 'out_ptr', 'elements_per_cycle' elements at a
// time with the guarantee that 'elements_per_cycle' is a multiple of 'count'
//
template <typename Pipe, int elements_per_cycle, typename PtrT>
void PipeToMemoryNoRemainder(PtrT out_ptr, size_t count) {
static_assert(fpga_tools::is_sycl_pipe_v<Pipe>);
using PipeT = decltype(Pipe::read());
static_assert(fpga_tools::has_subscript_v<PipeT>);
static_assert(fpga_tools::has_subscript_v<PtrT>);
static_assert(PipeT::size == elements_per_cycle);
static_assert(pipe_and_pointer_have_same_base_v<PipeT, PtrT>);
for (size_t i = 0; i < count; i++) {
auto pipe_data = Pipe::read();
#pragma unroll
for (int j = 0; j < elements_per_cycle; j++) {
out_ptr[i * elements_per_cycle + j] = pipe_data[j];
}
}
}
} // namespace detail
//
// Streams data from memory to a SYCL pipe 1 element a time
//
template <typename Pipe, typename PtrT>
void MemoryToPipe(PtrT in_ptr, size_t count) {
static_assert(fpga_tools::is_sycl_pipe_v<Pipe>);
using PipeT = decltype(Pipe::read());
static_assert(fpga_tools::has_subscript_v<PtrT>);
static_assert(detail::pipe_and_pointer_have_same_base_v<PipeT, PtrT>);
for (size_t i = 0; i < count; i++) {
Pipe::write(in_ptr[i]);
}
}
//
// Streams data from memory to a SYCL pipe 'elements_per_cycle' elements a time
//
template <typename Pipe, int elements_per_cycle, bool remainder, typename PtrT>
void MemoryToPipe(PtrT in_ptr, size_t count) {
if constexpr (!remainder) {
// user promises there is not remainder
detail::MemoryToPipeNoRemainder<Pipe, elements_per_cycle>(in_ptr, count);
} else {
// might have a remainder and it was not specified, so calculate it
auto full_count = (count / elements_per_cycle) * elements_per_cycle;
auto remainder_count = count % elements_per_cycle;
detail::MemoryToPipeRemainder<Pipe, elements_per_cycle>(in_ptr, full_count,
remainder_count);
}
}
//
// Streams data from memory to a SYCL pipe 'elements_per_cycle' elements a time
// In this version, the user has specified a the amount of remainder
//
template <typename Pipe, int elements_per_cycle, bool remainder, typename PtrT>
void MemoryToPipe(PtrT in_ptr, size_t full_count, size_t remainder_count) {
if constexpr (!remainder) {
// user promises there is not remainder
detail::MemoryToPipeNoRemainder<Pipe, elements_per_cycle>(in_ptr,
full_count);
} else {
// might have a remainder that was specified by the user
detail::MemoryToPipeRemainder<Pipe, elements_per_cycle>(in_ptr, full_count,
remainder_count);
}
}
//
// Streams data from a SYCL pipe to memory 1 element a time
//
template <typename Pipe, typename PtrT>
void PipeToMemory(PtrT out_ptr, size_t count) {
using PipeT = decltype(Pipe::read());
static_assert(fpga_tools::has_subscript_v<PtrT>);
static_assert(detail::pipe_and_pointer_have_same_base_v<PipeT, PtrT>);
for (size_t i = 0; i < count; i++) {
out_ptr[i] = Pipe::read();
}
}
//
// Streams data from a SYCL pipe to memory 'elements_per_cycle' elements a time
//
template <typename Pipe, int elements_per_cycle, bool remainder, typename PtrT>
void PipeToMemory(PtrT out_ptr, size_t count) {
if constexpr (!remainder) {
detail::PipeToMemoryNoRemainder<Pipe, elements_per_cycle>(out_ptr, count);
} else {
auto full_count = (count / elements_per_cycle) * elements_per_cycle;
auto remainder_count = count % elements_per_cycle;
detail::PipeToMemoryRemainder<Pipe, elements_per_cycle>(out_ptr, full_count,
remainder_count);
}
}
//
// Streams data from a SYCL pipe to memory 'elements_per_cycle' elements a time
// In this version, the user has specified a the amount of remainder
//
template <typename Pipe, int elements_per_cycle, bool remainder, typename PtrT>
void PipeToMemory(PtrT out_ptr, size_t full_count, size_t remainder_count) {
if constexpr (!remainder) {
detail::PipeToMemoryNoRemainder<Pipe, elements_per_cycle>(out_ptr,
full_count);
} else {
detail::PipeToMemoryRemainder<Pipe, elements_per_cycle>(out_ptr, full_count,
remainder_count);
}
}
} // namespace fpga_tools
#endif /* __MEMORY_UTILS_HPP__ */ | hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/include/streaming_cholesky.hpp | #ifndef __STREAMING_CHOLESKY_HPP__
#define __STREAMING_CHOLESKY_HPP__
#include "constexpr_math.hpp"
#include "tuple.hpp"
#include "unrolled_loop.hpp"
namespace fpga_linalg {
/*
Cholesky decomposition - Computes L such that A=LL* where:
- A is the input matrix (hermitian, positive definite)
- L is a lower triangular matrix
- L* is the conjugate transpose of L
This function implements a modified version of the Cholesky–Banachiewicz
algorithm.
Pseudo code:
int row_size = 0;
for (column = 0; column <= row_size; column++) {
for (row = column; row < rows; row++) {
float sum = 0;
for (k = 0; k < column; k++)
sum += L[row][k] * L[column][k];
if (row == column)
L[row][column] = sqrt(A[row][row] - sum);
else
L[row][column] = (A[row][column] - sum) / L[column][column];
}
}
The input and output matrices are consumed/produced from/to pipes.
*/
template <typename T, // The datatype for the computation
bool is_complex, // True if T is ac_complex<X>
int rows, // Number of rows==columns in the A matrices
int raw_latency, // Read after write (RAW) latency (in iterations) of
// the triangular loop of this function.
// This value depends on the FPGA target, the
// datatype, the target frequency, etc.
// This value will have to be tuned for optimal
// performance. Refer to the Triangular Loop
// design pattern tutorial.
// In general, find a high value for which the
// compiler is able to achieve an II of 1 and
// go down from there.
int pipe_size, // Number of elements read/write per pipe operation
// to read the input matrix
typename AIn, // A matrix input pipe, receive pipe_size
// elements from the pipe with each read
typename LOut // L matrix output pipe, send one element to the
// pipe with each write.
// Only lower-left elements of L are
// sent in row order, starting with row 0.
>
struct StreamingCholesky {
void operator()() const {
// Functional assertions
static_assert(rows >= 4,
"Only matrices of size 4x4 and over are supported");
static_assert(pipe_size >= 1,
"The pipe must be able to contain at least one element");
// Set the computation type to T or ac_complex<T> depending on the value
// of is_complex
using TT = std::conditional_t<is_complex, ac_complex<T>, T>;
constexpr int kColumns = rows;
// Number of lower-left elements in the L output matrix
constexpr int kLMatrixSize = kColumns * (kColumns + 1) / 2;
// Compute Cholesky decompositions as long as matrices are given as inputs
while (1) {
// Break memories up to store pipe_size elements per bank
constexpr short kBankwidth = pipe_size * sizeof(TT);
constexpr unsigned short kNumBanks = rows / pipe_size;
// When specifying numbanks for a memory, it must be a power of 2.
// Unused banks will be automatically optimized away.
constexpr short kNumBanksNextPow2 =
fpga_tools::Pow2(fpga_tools::CeilLog2(kNumBanks));
[[intel::numbanks(kNumBanksNextPow2)]] // NO-FORMAT: Attribute
[[intel::bankwidth(kBankwidth)]] // NO-FORMAT: Attribute
[[intel::private_copies(4)]] // NO-FORMAT: Attribute
[[intel::max_replicates(1)]] // NO-FORMAT: Attribute
TT a_load[rows][kColumns];
// Two copies of L to be able to load two complete rows per iteration
// Multiple private copies to be able to overlap multiple loop
// iterations
[[intel::private_copies(4)]] // NO-FORMAT: Attribute
TT l_result_compute[rows][kColumns];
[[intel::private_copies(4)]] // NO-FORMAT: Attribute
TT l_result_compute_copy[rows][kColumns];
[[intel::private_copies(2)]] // NO-FORMAT: Attribute
TT l_result[kLMatrixSize];
// Copy a matrix from the pipe to a local memory
// Number of pipe reads of pipe_size required to read a full column
constexpr int kExtraIteration = ((rows % pipe_size) != 0) ? 1 : 0;
constexpr int kLoopIterPerColumn = (rows / pipe_size) + kExtraIteration;
// Number of pipe reads of pipe_size to read all the matrices
constexpr int kLoopIter = kLoopIterPerColumn * kColumns;
// Size in bits of the loop iterator over kLoopIter iterations
constexpr int kLoopIterBitSize =
fpga_tools::BitsForMaxValue<kLoopIter + 1>();
[[intel::initiation_interval(1)]] // NO-FORMAT: Attribute
for (ac_int<kLoopIterBitSize, false> li = 0; li < kLoopIter; li++) {
fpga_tools::NTuple<TT, pipe_size> pipe_read = AIn::read();
int write_idx = li % kLoopIterPerColumn;
fpga_tools::UnrolledLoop<kLoopIterPerColumn>([&](auto k) {
fpga_tools::UnrolledLoop<pipe_size>([&](auto t) {
if constexpr (k * pipe_size + t < kColumns) {
if (write_idx == k) {
a_load[li / kLoopIterPerColumn][k * pipe_size + t] =
pipe_read.template get<t>();
}
}
// Delay data signals to create a vine-based data distribution
// to lower signal fanout.
pipe_read.template get<t>() =
sycl::ext::intel::fpga_reg(pipe_read.template get<t>());
});
write_idx = sycl::ext::intel::fpga_reg(write_idx);
});
}
// Computation of the number of iterations required for the triangular
// loop. Refer to the triangular_loop tutorial for details on how
// to compute these.
constexpr int kRegularIterations = kColumns * (kColumns + 1) / 2;
constexpr int kExtraIterations = (raw_latency - 1) * raw_latency / 2;
constexpr int kExtraIterationsToRemove =
kColumns >= raw_latency
? 0
: (raw_latency - kColumns) * (raw_latency - kColumns + 1) / 2;
constexpr int kTotalIterations =
kRegularIterations + kExtraIterations - kExtraIterationsToRemove;
// Compute the L matrix
int column = 0;
int row = 0;
TT div_term{0};
[[intel::ivdep(raw_latency)]] // NO-FORMAT: Attribute
for (int iteration = 0; iteration < kTotalIterations; iteration++) {
// Perform the dot product of the elements of the two rows indexed by
// row and column from element 0 to column
TT sum = 0;
fpga_tools::UnrolledLoop<kColumns>([&](auto k) {
TT to_add;
bool should_compute = k < column;
TT mul_lhs = should_compute ? l_result_compute[row][k] : T{0};
TT mul_rhs = should_compute ? l_result_compute_copy[column][k] : T{0};
if constexpr (is_complex) {
to_add = mul_lhs * mul_rhs.conj();
} else {
to_add = mul_lhs * mul_rhs;
}
sum += to_add;
});
TT a_loaded = (row < rows) ? a_load[row][column] : TT{0};
TT diff = a_loaded - sum;
// Only do useful work for meaningful iterations
TT to_store;
if (row == column) {
// Perform the reciprocal sqrt rather than the sqrt because:
// - it has a shorter latency and will reduce the RAW latency
// of the loop
// - the result of the sqrt is used as a divisor which is also
// a long operation, so replacing x/sqrt by x*rsqrt will save
// latency
// - the diagonal elements will need to be inverted later, but we
// can do that while outside this loop when we transfer the L
// matrix to the pipe
if constexpr (is_complex) {
div_term = {sycl::rsqrt(diff.r()), 0};
} else {
div_term = sycl::rsqrt(diff);
}
to_store = div_term;
} else {
to_store = diff * div_term;
}
if (column <= row) {
// Store the results to two working copies of L to be able to read
// two complete rows at each iteration
l_result_compute[row][column] = to_store;
l_result_compute_copy[row][column] = to_store;
// Store the result to the output matrix
if constexpr (is_complex) {
l_result[row * (row + 1) / 2 + column] = to_store.conj();
} else {
l_result[row * (row + 1) / 2 + column] = to_store;
}
}
// Update loop indexes
if (row == (rows - 1)) {
column = column + 1;
row = sycl::min(column, rows - raw_latency);
} else {
row = row + 1;
}
} // end of iteration
// Go over the L matrix and write each element to the pipe
int l_idx = 0;
[[intel::loop_coalesce(2)]] // NO-FORMAT: Attribute
for (int row = 0; row < rows; row++) {
for (int column = 0; column <= row; column++) {
TT to_write;
TT current_l_value = l_result[l_idx];
// The diagonal elements need to be inverted as the
// inversion was removed from the above compute loop
// to reduce the RAW latency
if (row == column) {
if constexpr (is_complex) {
to_write = {1 / current_l_value.r(), 0};
}
else{
to_write = 1 / current_l_value;
}
} else {
to_write = current_l_value;
}
LOut::write(to_write);
l_idx++;
}
}
} // end of while(1)
} // end of operator
}; // end of struct
} // namespace fpga_linalg
#endif /* __STREAMING_CHOLESKY_HPP__ */ | hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/include/unrolled_loop.hpp | #ifndef __UNROLLEDLOOP_HPP__
#define __UNROLLEDLOOP_HPP__
#include <type_traits>
#include <utility>
#include "metaprogramming_utils.hpp"
namespace fpga_tools {
///////////////////////////////////////////////////////////////////////////////
//
// Example usage for UnrolledLoop constexpr:
//
// Base
// UnrolledLoop(std::integer_sequence<int,5,2,7,8>{},[&](auto i) {
// /* i = 5,2,7,8 */
// });
//
// Case A
// UnrolledLoop<10>([&](auto i) {
// /* i = 0,1,...,9 */
// });
//
// Case B
// UnrolledLoop<10>([&](auto i) {
// /* i = 0,1,...,9 */
// });
//
// Case C
// UnrolledLoop<char, 1, 10>([&](auto i) {
// /* i = 1,2,...,9 */
// });
// UnrolledLoop<char, 10, 1>([&](auto i) {
// /* i = 10,9,...,2 */
// });
//
// Case D
// UnrolledLoop<1, 10>([&](auto i) {
// /* i = 1,2,...,9 */
// });
// UnrolledLoop<10, 1>([&](auto i) {
// /* i = 10,9,...,2 */
// });
//
///////////////////////////////////////////////////////////////////////////////
//
// Base implementation
// Templated on:
// ItType - the type of the iterator (size_t, int, char, ...)
// ItType... - the indices to iterate on
// F - the function to run for each index (i.e. the lambda)
//
template <class ItType, ItType... inds, class F>
constexpr void UnrolledLoop(std::integer_sequence<ItType, inds...>, F&& f) {
(f(std::integral_constant<ItType, inds>{}), ...);
}
//
// Convience implementation (A)
// performs UnrolledLoop in range [0,n) with iterator of type ItType
//
template <class ItType, ItType n, class F>
constexpr void UnrolledLoop(F&& f) {
UnrolledLoop(std::make_integer_sequence<ItType, n>{}, std::forward<F>(f));
}
//
// Convenience implementation (B)
// performs UnrolledLoop in range [0,n) with an iterator of type std::size_t
//
template <std::size_t n, class F>
constexpr void UnrolledLoop(F&& f) {
UnrolledLoop(std::make_index_sequence<n>{}, std::forward<F>(f));
}
//
// Convenience implementation (C)
// performs UnrolledLoop from start...end with an iterator of type ItType
// NOTE: start is INCLUSIVE, end is EXCLUSIVE
// NOTE: if start<=end, sequence is start,start+1,...,end-1
// if end<=start, sequence is start,start-1,...,end+1
//
template <class ItType, ItType start, ItType end, class F>
constexpr void UnrolledLoop(F&& f) {
UnrolledLoop(make_integer_range<ItType, start, end>{}, std::forward<F>(f));
}
//
// Convenience implementation (D)
// performs UnrolledLoop from start...end with an iterator of type size_t
// NOTE: start is INCLUSIVE, end is EXCLUSIVE
// NOTE: if start<=end, sequence is start,start+1,...,end-1
// if end<=start, sequence is start,start-1,...,end+1
//
template <std::size_t start, std::size_t end, class F>
constexpr void UnrolledLoop(F&& f) {
UnrolledLoop(make_index_range<start, end>{}, std::forward<F>(f));
}
} // namespace fpga_tools
#endif /* __UNROLLEDLOOP_HPP__ */ | hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/include/streaming_covariance_matrix.hpp | #ifndef __STREAMING_COVARIANCE_MATRIX_HPP__
#define __STREAMING_COVARIANCE_MATRIX_HPP__
namespace fpga_linalg {
// This functor computes the columns x columns covariance matrix of a rows x
// columns input matrix A
// It uses the following formula:
// COV[i][j] = (T[i][j] - rows*mean[i]*mean[j]) /
// (sqrt(T[i][i] - rows*mean[i]*mean[i]) *
// sqrt(T[j][j] - rows*mean[j]*mean[j]))
// Where T is transpose(A)*A and mean[k] is the mean of the column k of the A
// matrix
template <typename T, // The datatype for the computation
unsigned rows, // Number of rows in the A matrices
unsigned columns, // Number of columns in the A matrices
unsigned pipe_size, // Number of elements read/write per pipe
// operation, the matrix is received through the
// pipe
// by blocks of size columns*columns.
typename InputPipe, // A matrix input pipe, receive pipe_size
// elements from the pipe with each read
typename OutputPipe // Q matrix output pipe, send pipe_size
// elements to the pipe with each write
>
struct StreamingCovarianceMatrix {
void operator()() const {
static_assert(rows % columns == 0,
"The feature count must be a multiple of the samples count."
"This can be artificially achieved by increasing the number"
"of samples with no data.");
// Type used to store the matrices in the compute loop
using row_tuple = fpga_tools::NTuple<T, columns>;
// Number of matrix blocks to read from the pipe
constexpr int block_count = rows / columns;
// Break memories up to store 8 float numbers (32 bytes) per bank
constexpr short kBankwidth = pipe_size * sizeof(T);
constexpr unsigned short kNumBanks = columns / pipe_size;
// When specifying numbanks for a memory, it must be a power of 2.
// Unused banks will be automatically optimized away.
constexpr short kNumBanksNextPow2 =
fpga_tools::Pow2(fpga_tools::CeilLog2(kNumBanks));
// Copy a matrix from the pipe to a local memory
// Number of pipe reads of pipe_size required to read a full column
constexpr int kExtraIteration = (columns % pipe_size) != 0 ? 1 : 0;
constexpr int kLoopIterationPerRow = columns / pipe_size + kExtraIteration;
// Number of pipe reads of pipe_size to read all the matrices
constexpr int kLoopIterations = kLoopIterationPerRow * columns;
// We keep a replicate of the diagonal of T for improved memory access
// pattern over T
T t_matrix_diagonal_replicate[columns];
// Array to keep the means of all the A matrix columns
T means[columns];
// Array to keep the T matrix
[[intel::max_replicates(1)]] // NO-FORMAT: Attribute
[[intel::private_copies(4)]] // NO-FORMAT: Attribute
T t_matrix[columns * columns];
// We keep count of the current block number
int block = 0;
while (1) {
// Read the next matrix block into the a_load local memory
[[intel::numbanks(kNumBanksNextPow2)]] // NO-FORMAT: Attribute
[[intel::bankwidth(kBankwidth)]] // NO-FORMAT: Attribute
[[intel::max_replicates(1)]] // NO-FORMAT: Attribute
[[intel::private_copies(2)]] // NO-FORMAT: Attribute
row_tuple a_load[columns];
[[intel::initiation_interval(1)]] // NO-FORMAT: Attribute
for (int li = 0; li < kLoopIterations; li++) {
fpga_tools::NTuple<T, pipe_size> pipe_read = InputPipe::read();
int write_idx = li % kLoopIterationPerRow;
int a_col_index = li / kLoopIterationPerRow;
fpga_tools::UnrolledLoop<kLoopIterationPerRow>([&](auto k) {
fpga_tools::UnrolledLoop<pipe_size>([&](auto t) {
if (write_idx == k) {
if constexpr (k * pipe_size + t < columns) {
a_load[a_col_index].template get<k * pipe_size + t>() =
pipe_read.template get<t>();
}
}
// Delay data signals to create a vine-based data distribution
// to lower signal fanout.
pipe_read.template get<t>() =
sycl::ext::intel::fpga_reg(pipe_read.template get<t>());
});
write_idx = sycl::ext::intel::fpga_reg(write_idx);
});
} // for:li
// We are going to reuse the same column of the matrix multiple
// iterations in a row, so we keep it locally
row_tuple current_base_column;
row_tuple next_base_column;
// Compute the block T matrix and the partial means
// Arrays to keep all the data of the current block being computed
[[intel::max_replicates(1)]] // NO-FORMAT: Attribute
[[intel::private_copies(2)]] // NO-FORMAT: Attribute
T t_matrix_compute[columns * columns];
T t_matrix_diagonal_replicate_partial[columns];
T means_partial[columns];
int row = 0;
int column = 0;
for (int it = 0; it < columns * columns; it++) {
// Load the current column of the block
row_tuple current_column = a_load[column];
// Keep the current column in the local cache for future reuse
if (column == 0) {
if (column == row) {
current_base_column = current_column;
} else {
current_base_column = next_base_column;
}
} else if (column == (row + 1)) {
next_base_column = current_column;
}
// Compute the partial T value and the partial mean
T dot_product = 0;
T mean = 0;
fpga_tools::UnrolledLoop<columns>([&](auto t) {
dot_product += current_column.template get<t>() *
current_base_column.template get<t>();
mean += current_column.template get<t>();
});
// Update the partial result T matrix
t_matrix_compute[it] = dot_product;
// Adjust the mean as we only need to compute it once
if (row != 0) {
mean = 0;
}
mean /= rows;
// Update the partial means results
if (row == 0) {
means_partial[column] = mean;
}
// Update the partial diagonal replicates results
if (row == column) {
t_matrix_diagonal_replicate_partial[column] = dot_product;
}
// Update the current row and column indexes
if (column == columns - 1) {
column = 0;
row++;
} else {
column++;
}
}
// Update the global mean array and the diagonal replicates array with the
// partial results
fpga_tools::UnrolledLoop<columns>([&](auto t) {
T mean_to_add = block == 0 ? 0 : means[t];
means[t] = means_partial[t] + mean_to_add;
T t_matrix_diagonal_replicate_to_add =
block == 0 ? 0 : t_matrix_diagonal_replicate[t];
t_matrix_diagonal_replicate[t] =
t_matrix_diagonal_replicate_partial[t] +
t_matrix_diagonal_replicate_to_add;
});
// For the computation of COV
[[intel::max_replicates(1)]] // NO-FORMAT: Attribute
[[intel::private_copies(2)]] // NO-FORMAT: Attribute
T t_matrix_consume[columns][columns];
// Update the global T matrix with the partial results and copy the result
// to the t_matrix_consume array for better memory structure in the
// computation of COV
for (row = 0; row < columns; row++) {
fpga_tools::UnrolledLoop<columns>([&](auto column) {
T t_matrix_to_add = block == 0 ? 0 : t_matrix[row * columns + column];
T sum = t_matrix_compute[row * columns + column] + t_matrix_to_add;
t_matrix[row * columns + column] = sum;
t_matrix_consume[row][column] = sum;
});
}
// t_matrix_consume now contains the full matrix product of the transpose
// of A times A. mean now contains the mean of all the columns of A. We
// now need to compose all of these results to get the covariance matrix
[[intel::numbanks(kNumBanksNextPow2)]] // NO-FORMAT: Attribute
[[intel::bankwidth(kBankwidth)]] // NO-FORMAT: Attribute
[[intel::max_replicates(1)]] // NO-FORMAT: Attribute
[[intel::private_copies(2)]] // NO-FORMAT: Attribute
T cov_matrix[columns][columns];
{
int row = 0;
int column = 0;
for (int it = 0; it < columns * columns; it++) {
T numerator = t_matrix_consume[row][column] -
(rows * means[row] * means[column]);
T denominator = std::sqrt((t_matrix_diagonal_replicate[row] -
(rows * means[row] * means[row])) *
(t_matrix_diagonal_replicate[column] -
(rows * means[column] * means[column])));
cov_matrix[row][column] = numerator / denominator;
if (column == columns - 1) {
column = 0;
row++;
} else {
column++;
}
}
}
// Write the standardized covariance matrix to the output pipe
// [[intel::initiation_interval(1)]] // NO-FORMAT: Attribute
for (int li = 0; li < kLoopIterations; li++) {
int column_iter = li % kLoopIterationPerRow;
bool get[kLoopIterationPerRow];
fpga_tools::UnrolledLoop<kLoopIterationPerRow>([&](auto k) {
get[k] = column_iter == k;
column_iter = sycl::ext::intel::fpga_reg(column_iter);
});
fpga_tools::NTuple<T, pipe_size> pipe_write;
fpga_tools::UnrolledLoop<kLoopIterationPerRow>([&](auto t) {
fpga_tools::UnrolledLoop<pipe_size>([&](auto k) {
if constexpr (t * pipe_size + k < columns) {
pipe_write.template get<k>() =
get[t]
? cov_matrix[li / kLoopIterationPerRow][t * pipe_size + k]
: sycl::ext::intel::fpga_reg(
pipe_write.template get<k>());
}
});
});
if (block == block_count - 1) {
OutputPipe::write(pipe_write);
}
}
if (block == block_count - 1) {
block = 0;
} else {
block++;
}
} // end of while
}; // end of operator()
}; // end of struct{}
} // namespace fpga_linalg
#endif /* __STREAMING_COVARIANCE_MATRIX_HPP__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/include/exception_handler.hpp | #ifndef __EXCEPTIONHANDLER_HPP__
#define __EXCEPTIONHANDLER_HPP__
#include <sycl/sycl.hpp>
#include <exception>
#include <iostream>
namespace fpga_tools {
void exception_handler(sycl::exception_list exceptions) {
for (std::exception_ptr const &e : exceptions) {
try {
std::rethrow_exception(e);
} catch (sycl::exception const &e) {
std::cout << "Caught asynchronous SYCL exception:\n"
<< e.what() << std::endl;
}
}
}
} // namespace fpga_tools
#endif //__EXCEPTIONHANDLER_HPP__
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/include/tuple.hpp | #ifndef __TUPLE_HPP__
#define __TUPLE_HPP__
#include <type_traits>
namespace fpga_tools {
//
// Generic tuple
//
// USAGE EXAMPLE:
// Tuple<char,short,int,long> my_tuple;
// char a = my_tuple.get<0>();
// short b = my_tuple.get<1>();
// int c = my_tuple.get<2>();
// long d = my_tuple.get<3>();
//
template <typename... Tys>
struct Tuple {
Tuple(Tys... Args) : values(Args...) {}
Tuple() {}
//
// get the index'th item in the tuple of values
//
template <int index>
auto& get() {
static_assert(index < NumTys, "index out of bounds");
return get_impl<index, Tys...>(values);
}
//
// helper to get the first element in the tuple
//
auto& first() { return get<0>(); }
//
// helper to get the last element in the tuple
//
auto& last() { return get<NumTys - 1>(); }
private:
//
// generic tuple implementation: recursive case
//
template <typename CurrentTy, typename... OtherTys>
struct tuple_impl {
tuple_impl(CurrentTy& current, OtherTys... others)
: value(current), other_values(others...) {}
tuple_impl() {}
using ValueTy = CurrentTy;
ValueTy value;
tuple_impl<OtherTys...> other_values;
};
//
// generic tuple implementation: base case
//
template <typename FinalTy>
struct tuple_impl<FinalTy> {
tuple_impl(FinalTy& current) : value(current) {}
tuple_impl() {}
using ValueTy = FinalTy;
ValueTy value;
};
// the tuple values
tuple_impl<Tys...> values;
// the number of tuple values
constexpr static auto NumTys = sizeof...(Tys);
//
// implementation of 'get' for general tuple
//
template <int index, typename HeadTy, typename... TailTys>
static auto& get_impl(tuple_impl<HeadTy, TailTys...>& sub_tuple) {
if constexpr (index == 0) {
// base case
return sub_tuple.value;
} else {
// recursive case
return get_impl<index - 1, TailTys...>(sub_tuple.other_values);
}
}
};
//
// NTuple implementation
// This is convenient way to have N elements of the same type
// somewhat like an std::array
//
template <int, typename Type>
using NTupleElem = Type;
template <typename Type, std::size_t... Idx>
static auto make_NTupleImpl(std::index_sequence<Idx...>)
-> Tuple<NTupleElem<Idx, Type>...>;
template <int N, typename Type>
using make_NTuple =
decltype(make_NTupleImpl<Type>(std::make_index_sequence<N>()));
//
// convenience alias for a tuple of N elements of the same type
// NOTE: for this alias, typename comes FIRST (to match std::array)
//
// USAGE EXAMPLE:
// NTuple<int, 10> elements;
// elements.get<3>() = 17;
//
template <typename Type, int N>
using NTuple = make_NTuple<N, Type>;
} // namespace fpga_tools
#endif /* __TUPLE_HPP__ */ | hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/include/constexpr_math.hpp | #ifndef __CONSTEXPR_MATH__
#define __CONSTEXPR_MATH__
//
// This file contains various helper C++ metaprogramming math functions that
// are useful across various designs.
//
#include <limits>
namespace fpga_tools {
// returns the absolute value of 'x'
template <typename T>
constexpr T Abs(T x) { return (x < 0) ? -x : x; }
// returns the minimum of 'a' and 'b'.
// The type, 'T', must have an operator<
template <typename T>
constexpr T Min(T a, T b) { return (a < b) ? a : b; }
// returns the maximum of 'a' and 'b'.
// The type, 'T', must have an operator>
template <typename T>
constexpr T Max(T a, T b) { return (a > b) ? a : b; }
// rounds up to the nearest multiple of of 'multiple'
// only works for positive numbers
template <typename T>
constexpr T RoundUpToMultiple(T num, T multiple) {
static_assert(std::is_integral_v<T>);
static_assert(std::is_unsigned_v<T>);
if (multiple == 0) {
return num;
}
int remainder = num % multiple;
if (remainder == 0) {
return num;
} else {
return num + multiple - remainder;
}
}
// returns n^2
template <typename T>
constexpr T Pow2(T n) {
static_assert(std::is_integral_v<T>);
return (n < 0) ? (T(1) << (-n)) : (T(1) << n);
}
// returns whether abs(n) is a power of 2
template <typename T>
constexpr bool IsPow2(T n) {
static_assert(std::is_integral_v<T>);
if (n < 0) n = -n;
return (n != 0) && ((n & (n - 1)) == 0);
}
// returns log2(n) rounding down
template <typename T>
constexpr T Log2(T n) {
static_assert(std::is_integral_v<T>);
if (n < 2) {
return T(0);
} else {
T ret = 0;
while (n >= 2) {
ret++;
n /= 2;
}
return ret;
}
}
// returns log(2) rounded up
template <typename T>
static constexpr T CeilLog2(T n) {
return ((n == 1) ? T(0) : Log2(n - 1) + T(1));
}
// returns the number of bits required to encode all the values between 0 and N
template <unsigned int n>
static constexpr unsigned int BitsForMaxValue() {
return CeilLog2(n + 1);
}
// return 'n' rounded up to the nearest power of 2
template <typename T>
constexpr T RoundUpPow2(T n) {
static_assert(std::is_integral_v<T>);
static_assert(std::is_unsigned_v<T>);
if (n == 0) {
return 2;
} else if (IsPow2(n)) {
return n;
} else {
return T(1) << (Log2(n) + 1);
}
}
// computes x^y where y must be an integer (positive or negative)
constexpr double Pow(double x, int y) {
if (y == 0) {
// x^0 = 1
return 1.0;
} else {
// handle both y < 0 and y > 0 by changing loop bound and multiply value
bool y_is_negative = (y < 0);
double mult_val = y_is_negative ? (1/x) : x;
int loop_bound = y_is_negative ? -y : y;
double ret = 1.0;
for (int i = 0; i < loop_bound; i++) {
ret *= mult_val;
}
return ret;
}
}
// estimates e^(x) for x >= 0 using a taylor series expansion
// https://en.wikipedia.org/wiki/Taylor_series
constexpr double Exp(double x, unsigned taylor_terms=32) {
double factorial = 1.0;
double power = 1.0;
double answer = 1.0;
for(int i = 1; i < taylor_terms-1; i++) {
power *= x;
factorial *= i;
answer += power / factorial;
}
return answer;
}
// Scale significand using floating-point base exponent
// see: http://www.cplusplus.com/reference/cmath/scalbn/
constexpr float Scalbn(float value, int exponent) {
if (exponent == 0) {
return value;
} else {
float ret = value;
while(exponent != 0) {
if (exponent > 0) {
ret *= 2;
exponent--;
} else {
ret /= 2;
exponent++;
}
}
return ret;
}
}
// extract the exponent from a 32-bit float
constexpr int FP32ExtractExponent(float x) {
if (x == 0) {
return 0;
} else {
float ret = 0;
float abs_x = Abs(x);
while (abs_x >= 2 || abs_x < 1) {
bool abs_x_gte_2 = (abs_x >= 2);
ret += (abs_x_gte_2 ? 1 : -1);
x = (abs_x_gte_2 ? (x/2) : (x*2));
abs_x = Abs(x);
}
return ret;
}
}
// extract the mantissa from a 32-bit float
constexpr int FP32ExtractMantissa(float x) {
// remove hidden 1 and bias the exponent to get integer
//#pragma clang fp contract(off)
//return (Abs(x) < std::numeric_limits<float>::infinity()) ?
// Scalbn(Scalbn(Abs(x),-FP32ExtractExponent(x))-1,23) : 0;
return Scalbn(Scalbn(Abs(x),-FP32ExtractExponent(x))-1,23);
}
} // namespace fpga_tools
#endif /* __CONSTEXPR_MATH__ */
| hpp |
oneAPI-samples | data/projects/oneAPI-samples/DirectProgramming/C++SYCL_FPGA/ReferenceDesigns/board_test/src/usm_speed.hpp | #include <sycl/ext/intel/fpga_extensions.hpp>
#include <sycl/sycl.hpp>
// NOTE: sycl::ulong8 was picked for this test because it is 64 bytes in size
// and that is the width of the interconnect to global memory.
// Arbitrary value used for testing/initialization
#define TEST_VAL 5
// Forward declare the kernel names
class USMMemCopy;
class USMMemRead;
class USMMemWrite;
// Available tests to be run
enum USMTest { MEMCOPY, READ, WRITE };
// MEMCOPY test: launches a kernel to copy data from one USM pointer to another.
sycl::event memcopy_kernel(sycl::queue &q, sycl::ulong8 *in, sycl::ulong8 *out,
size_t num_items) {
return q.single_task<USMMemCopy>([=]() [[intel::kernel_args_restrict]] {
sycl::host_ptr<sycl::ulong8> in_h(in);
sycl::host_ptr<sycl::ulong8> out_h(out);
for (size_t i = 0; i < num_items; i++) {
out_h[i] = in_h[i];
}
});
}
// READ test: launches a kernel to read data from a USM pointer, sum it up, and
// store to an output pointer.
sycl::event read_kernel(sycl::queue &q, sycl::ulong8 *in, sycl::ulong8 *out,
size_t num_items) {
return q.single_task<USMMemRead>([=]() {
sycl::host_ptr<sycl::ulong8> in_h(in);
sycl::host_ptr<sycl::ulong8> out_h(out);
sycl::ulong8 sum{0};
for (size_t i = 0; i < num_items; i++) {
sum += in_h[i];
}
// This prevents the reads from being optimized away
out_h[0] = sum;
});
}
// WRITE test: launches a kernel to write data to a USM pointer.
sycl::event write_kernel(sycl::queue &q, sycl::ulong8 *in, sycl::ulong8 *out,
size_t num_items) {
return q.single_task<USMMemWrite>([=]() {
sycl::host_ptr<sycl::ulong8> out_h(out);
sycl::ulong8 answer{TEST_VAL};
for (size_t i = 0; i < num_items; i++) {
out_h[i] = answer;
}
});
}
// Function to check output against expected answer.
bool verify(sycl::ulong8 *actual, sycl::ulong8 *expected, size_t num_items) {
// Verify all values are equal
for (int i = 0; i < num_items; i++) {
for (int j = 0; j < 8; j++) {
if (actual[i][j] != expected[i][j]) {
std::cerr << "ERROR: Values do not match, "
<< "out[" << i << "][" << j << "] = " << actual[i][j]
<< "; expected " << expected[i][j] << std::endl;
return false;
}
}
}
return true;
}
// Parameterized function to perform one of the tests defined above. Allocates
// and initializes host USM, runs the test, then verifies the answer. Then
// re-runs the test several times to measure bandwidth.
int run_test(sycl::queue &q, USMTest test) {
size_t iterations = 1;
size_t num_bytes = 1024 * 1024 * 1024;
size_t num_items = num_bytes / sizeof(sycl::ulong8);
size_t num_bytes_GB = num_bytes / kGB;
std::cout << "Iterations: " << iterations << std::endl;
std::cout << "Data size: " << num_bytes / kMB << " MB" << std::endl;
std::cout << "Data type size: " << sizeof(sycl::ulong8) << " bytes"
<< std::endl;
// USM host allocation
sycl::ulong8 *in = sycl::malloc_host<sycl::ulong8>(num_items, q);
sycl::ulong8 *out = sycl::malloc_host<sycl::ulong8>(num_items, q);
if (in == nullptr || out == nullptr) {
std::cerr << "Error: Out of memory, can't allocate " << num_bytes
<< " bytes" << std::endl;
return 1;
}
// Initialize the input with random values and output with zero.
for (int i = 0; i < num_items; i++) {
in[i] = rand();
out[i] = 0;
}
std::function<sycl::event(sycl::queue &, sycl::ulong8 *, sycl::ulong8 *,
size_t)>
kernel;
sycl::ulong8 *expected = new sycl::ulong8[num_items];
// Test selection: set the test function that will be run, and fill the
// "expected" array with the expected answer.
switch (test) {
case MEMCOPY: {
std::cout << "Case: Full Duplex" << std::endl;
kernel = memcopy_kernel;
// Full duplex transfers twice the amount of data
num_bytes_GB *= 2;
// When verifying, the output pointer should match the input pointer.
for (int i = 0; i < num_items; i++) {
expected[i] = in[i];
}
break;
}
case READ: {
std::cout << "Case: From Host to Device" << std::endl;
kernel = read_kernel;
// When verifying, the first index of the output pointer should contain
// the expected answer (sum of all values at the input pointer); at all
// other indices it should contain zero.
sycl::ulong8 read_answer{0};
for (int i = 0; i < num_items; i++) {
read_answer += in[i];
}
for (int i = 0; i < num_items; i++) {
expected[i] = (i == 0) ? read_answer : (sycl::ulong8)(0);
}
break;
}
case WRITE: {
std::cout << "Case: From Device to Host" << std::endl;
kernel = write_kernel;
// When verifying, each index of the output pointer should contain the
// known answer that was written.
for (int i = 0; i < num_items; i++) {
expected[i] = TEST_VAL;
}
break;
}
default:
std::cout << "Error: Failed to launch test" << std::endl;
sycl::free(in, q);
sycl::free(out, q);
delete[] expected;
return 1;
}
// The first iteration is slow due to one time tasks like buffer creation,
// program creation and device programming, bandwidth measured in subsequent
// iterations.
kernel(q, in, out, num_items).wait();
if (!verify(out, expected, num_items)) {
std::cerr << "FAILED" << std::endl << std::endl;
sycl::free(in, q);
sycl::free(out, q);
delete[] expected;
return 1;
}
float time = 0;
for (int i = 0; i < iterations; i++) {
sycl::event e = kernel(q, in, out, num_items);
e.wait();
time += SyclGetQStExecTimeNs(e);
}
sycl::free(in, q);
sycl::free(out, q);
delete[] expected;
// Report throughput
time /= iterations;
std::cout << "Average Time: " << time / 1000.0 << " ns\t" << std::endl;
std::cout << "Average Throughput: "
<< (num_bytes_GB / (time / (1000.0 * 1000.0 * 1000.0))) << " GB/s\t"
<< std::endl
<< std::endl;
return 0;
} | hpp |
Subsets and Splits