コード例 #1
0
ファイル: scan_dim.hpp プロジェクト: klemmster/arrayfire
static void scan_dim_launcher(Param &out,
                              Param &tmp,
                              const Param &in,
                              const uint groups_all[4])
{
    try {
        Kernel* ker = get_scan_dim_kernels<Ti, To, op, dim, isFinalPass, threads_y>(0);

        NDRange local(THREADS_X, threads_y);
        NDRange global(groups_all[0] * groups_all[2] * local[0],
                       groups_all[1] * groups_all[3] * local[1]);

        uint lim = divup(out.info.dims[dim], (threads_y * groups_all[dim]));

        auto scanOp = make_kernel<Buffer, KParam,
             Buffer, KParam,
             Buffer, KParam,
             uint, uint,
             uint, uint>(*ker);


        scanOp(EnqueueArgs(getQueue(), global, local),
               *out.data, out.info, *tmp.data, tmp.info, *in.data, in.info,
               groups_all[0], groups_all[1], groups_all[dim], lim);

        CL_DEBUG_FINISH(getQueue());
    } catch (cl::Error err) {
        CL_TO_AF_ERROR(err);
        throw;
    }
}
コード例 #2
0
void convolve2(Param out, const Param signal, const Param filter)
{
    try {
        static std::once_flag  compileFlags[DeviceManager::MAX_DEVICES];
        static std::map<int, Program*>   convProgs;
        static std::map<int, Kernel*>  convKernels;

        int device = getActiveDeviceId();

        std::call_once( compileFlags[device], [device] () {
                const size_t C0_SIZE  = (THREADS_X+2*(fLen-1))* THREADS_Y;
                const size_t C1_SIZE  = (THREADS_Y+2*(fLen-1))* THREADS_X;

                size_t locSize = (conv_dim==0 ? C0_SIZE : C1_SIZE);

                    std::ostringstream options;
                    options << " -D T=" << dtype_traits<T>::getName()
                            << " -D accType="<< dtype_traits<accType>::getName()
                            << " -D CONV_DIM="<< conv_dim
                            << " -D EXPAND="<< expand
                            << " -D FLEN="<< fLen
                            << " -D LOCAL_MEM_SIZE="<<locSize;
                    if (std::is_same<T, double>::value ||
                        std::is_same<T, cdouble>::value) {
                        options << " -D USE_DOUBLE";
                    }
                    Program prog;
                    buildProgram(prog, convolve_separable_cl, convolve_separable_cl_len, options.str());
                    convProgs[device]   = new Program(prog);
                    convKernels[device] = new Kernel(*convProgs[device], "convolve");
                });

        auto convOp = make_kernel<Buffer, KParam, Buffer, KParam, Buffer,
                                  int, int>(*convKernels[device]);

        NDRange local(THREADS_X, THREADS_Y);

        int blk_x = divup(out.info.dims[0], THREADS_X);
        int blk_y = divup(out.info.dims[1], THREADS_Y);

        NDRange global(blk_x*signal.info.dims[2]*THREADS_X,
                       blk_y*signal.info.dims[3]*THREADS_Y);

        cl::Buffer *mBuff = bufferAlloc(fLen*sizeof(accType));
        // FIX ME: if the filter array is strided, direct might cause issues
        getQueue().enqueueCopyBuffer(*filter.data, *mBuff, 0, 0, fLen*sizeof(accType));

        convOp(EnqueueArgs(getQueue(), global, local),
               *out.data, out.info, *signal.data, signal.info, *mBuff, blk_x, blk_y);

        bufferFree(mBuff);
    } catch (cl::Error err) {
        CL_TO_AF_ERROR(err);
        throw;
    }
}
コード例 #3
0
ファイル: memcopy.hpp プロジェクト: shehzan10/arrayfire
    void memcopy(cl::Buffer out, const dim_t *ostrides,
                 const cl::Buffer in, const dim_t *idims,
                 const dim_t *istrides, int offset, uint ndims)
    {
        try {
            static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
            static std::map<int, Program*>    cpyProgs;
            static std::map<int, Kernel*>   cpyKernels;

            int device = getActiveDeviceId();

            std::call_once(compileFlags[device], [&]() {
                std::ostringstream options;
                options << " -D T=" << dtype_traits<T>::getName();
                if (std::is_same<T, double>::value ||
                    std::is_same<T, cdouble>::value) {
                    options << " -D USE_DOUBLE";
                }
                Program prog;
                buildProgram(prog, memcopy_cl, memcopy_cl_len, options.str());
                cpyProgs[device]   = new Program(prog);
                cpyKernels[device] = new Kernel(*cpyProgs[device], "memcopy_kernel");
            });

            dims_t _ostrides = {{ostrides[0], ostrides[1], ostrides[2], ostrides[3]}};
            dims_t _istrides = {{istrides[0], istrides[1], istrides[2], istrides[3]}};
            dims_t _idims = {{idims[0], idims[1], idims[2], idims[3]}};

            size_t local_size[2] = {DIM0, DIM1};
            if (ndims == 1) {
                local_size[0] *= local_size[1];
                local_size[1]  = 1;
            }

            int groups_0 = divup(idims[0], local_size[0]);
            int groups_1 = divup(idims[1], local_size[1]);

            NDRange local(local_size[0], local_size[1]);
            NDRange global(groups_0 * idims[2] * local_size[0],
                           groups_1 * idims[3] * local_size[1]);

            auto memcopy_kernel = KernelFunctor< Buffer, dims_t,
                                               Buffer, dims_t,
                                               dims_t, int,
                                               int, int >(*cpyKernels[device]);

            memcopy_kernel(EnqueueArgs(getQueue(), global, local),
                out, _ostrides, in, _idims, _istrides, offset, groups_0, groups_1);
            CL_DEBUG_FINISH(getQueue());
        }
        catch (cl::Error err) {
            CL_TO_AF_ERROR(err);
            throw;
        }
    }
コード例 #4
0
void matchTemplate(Param out, const Param srch, const Param tmplt)
{
    try {
        static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
        static std::map<int, Program*>  mtProgs;
        static std::map<int, Kernel*> mtKernels;

        int device = getActiveDeviceId();

        std::call_once( compileFlags[device], [device] () {

                std::ostringstream options;
                options << " -D inType="  << dtype_traits<inType>::getName()
                        << " -D outType=" << dtype_traits<outType>::getName()
                        << " -D MATCH_T=" << mType
                        << " -D NEEDMEAN="<< needMean
                        << " -D AF_SAD="  << AF_SAD
                        << " -D AF_ZSAD=" << AF_ZSAD
                        << " -D AF_LSAD=" << AF_LSAD
                        << " -D AF_SSD="  << AF_SSD
                        << " -D AF_ZSSD=" << AF_ZSSD
                        << " -D AF_LSSD=" << AF_LSSD
                        << " -D AF_NCC="  << AF_NCC
                        << " -D AF_ZNCC=" << AF_ZNCC
                        << " -D AF_SHD="  << AF_SHD;
                if (std::is_same<outType, double>::value) {
                    options << " -D USE_DOUBLE";
                }
                Program prog;
                buildProgram(prog, matchTemplate_cl, matchTemplate_cl_len, options.str());
                mtProgs[device]   = new Program(prog);
                mtKernels[device] = new Kernel(*mtProgs[device], "matchTemplate");
            });

        NDRange local(THREADS_X, THREADS_Y);

        int blk_x = divup(srch.info.dims[0], THREADS_X);
        int blk_y = divup(srch.info.dims[1], THREADS_Y);

        NDRange global(blk_x * srch.info.dims[2] * THREADS_X, blk_y * srch.info.dims[3] * THREADS_Y);

        auto matchImgOp = make_kernel<Buffer, KParam,
                                       Buffer, KParam,
                                       Buffer, KParam,
                                       int, int> (*mtKernels[device]);

        matchImgOp(EnqueueArgs(getQueue(), global, local),
                    *out.data, out.info, *srch.data, srch.info, *tmplt.data, tmplt.info, blk_x, blk_y);

        CL_DEBUG_FINISH(getQueue());
    } catch (cl::Error err) {
        CL_TO_AF_ERROR(err);
        throw;
    }
}
コード例 #5
0
ファイル: histogram.hpp プロジェクト: EmergentOrder/arrayfire
void histogram(Param out, const Param in, const Param minmax, dim_type nbins)
{
    try {
        static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
        static std::map<int, Program*> histProgs;
        static std::map<int, Kernel *> histKernels;

        int device = getActiveDeviceId();

        std::call_once( compileFlags[device], [device] () {
                    std::ostringstream options;
                    options << " -D inType=" << dtype_traits<inType>::getName()
                            << " -D outType=" << dtype_traits<outType>::getName()
                            << " -D THRD_LOAD=" << THRD_LOAD;

                    if (std::is_same<inType, double>::value ||
                        std::is_same<inType, cdouble>::value) {
                        options << " -D USE_DOUBLE";
                    }

                    Program prog;
                    buildProgram(prog, histogram_cl, histogram_cl_len, options.str());
                    histProgs[device]   = new Program(prog);
                    histKernels[device] = new Kernel(*histProgs[device], "histogram");
                });

        auto histogramOp = make_kernel<Buffer, KParam, Buffer, KParam,
                                       Buffer, cl::LocalSpaceArg,
                                       dim_type, dim_type, dim_type
                                      >(*histKernels[device]);

        NDRange local(THREADS_X, 1);

        dim_type numElements = in.info.dims[0]*in.info.dims[1];

        dim_type blk_x       = divup(numElements, THRD_LOAD*THREADS_X);

        dim_type batchCount  = in.info.dims[2];

        NDRange global(blk_x*THREADS_X, batchCount);

        dim_type locSize = nbins * sizeof(outType);

        histogramOp(EnqueueArgs(getQueue(), global, local),
                *out.data, out.info, *in.data, in.info, *minmax.data,
                cl::Local(locSize), numElements, nbins, blk_x);

        CL_DEBUG_FINISH(getQueue());
    } catch (cl::Error err) {
        CL_TO_AF_ERROR(err);
        throw;
    }
}
コード例 #6
0
ファイル: gradient.hpp プロジェクト: EmergentOrder/arrayfire
        void gradient(Param grad0, Param grad1, const Param in)
        {
            try {
                static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
                static std::map<int, Program*>  gradProgs;
                static std::map<int, Kernel*> gradKernels;

                int device = getActiveDeviceId();

                std::call_once( compileFlags[device], [device] () {
                    std::ostringstream options;
                    options << " -D T=" << dtype_traits<T>::getName()
                            << " -D TX=" << TX
                            << " -D TY=" << TY;

                    if((af_dtype) dtype_traits<T>::af_type == c32 ||
                       (af_dtype) dtype_traits<T>::af_type == c64) {
                        options << " -D CPLX=1";
                    } else {
                        options << " -D CPLX=0";
                    }
                    if (std::is_same<T, double>::value ||
                        std::is_same<T, cdouble>::value) {
                        options << " -D USE_DOUBLE";
                    }
                    Program prog;
                    buildProgram(prog, gradient_cl, gradient_cl_len, options.str());
                    gradProgs[device]   = new Program(prog);
                    gradKernels[device] = new Kernel(*gradProgs[device], "gradient_kernel");
                });

                auto gradOp = make_kernel<Buffer, const KParam, Buffer, const KParam,
                                    const Buffer, const KParam, const dim_type, const dim_type>
                                        (*gradKernels[device]);

                NDRange local(TX, TY, 1);

                dim_type blocksPerMatX = divup(in.info.dims[0], TX);
                dim_type blocksPerMatY = divup(in.info.dims[1], TY);
                NDRange global(local[0] * blocksPerMatX * in.info.dims[2],
                               local[1] * blocksPerMatY * in.info.dims[3],
                               1);

                gradOp(EnqueueArgs(getQueue(), global, local),
                        *grad0.data, grad0.info, *grad1.data, grad1.info,
                        *in.data, in.info, blocksPerMatX, blocksPerMatY);

                CL_DEBUG_FINISH(getQueue());
            } catch (cl::Error err) {
                CL_TO_AF_ERROR(err);
                throw;
            }
        }
コード例 #7
0
ファイル: transpose.hpp プロジェクト: PenguinHeart/arrayfire
void transpose(Param out, const Param in)
{
    try {
        static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
        static std::map<int, Program*>  trsProgs;
        static std::map<int, Kernel*> trsKernels;

        int device = getActiveDeviceId();

        std::call_once(compileFlags[device], [device] () {

                std::ostringstream options;
                options << " -D TILE_DIM=" << TILE_DIM
                        << " -D THREADS_Y=" << THREADS_Y
                        << " -D IS32MULTIPLE=" << IS32MULTIPLE
                        << " -D DOCONJUGATE=" << (conjugate && af::iscplx<T>())
                        << " -D T=" << dtype_traits<T>::getName();

                if (std::is_same<T, double>::value ||
                    std::is_same<T, cdouble>::value) {
                    options << " -D USE_DOUBLE";
                }

                cl::Program prog;
                buildProgram(prog, transpose_cl, transpose_cl_len, options.str());
                trsProgs[device] = new Program(prog);

                trsKernels[device] = new Kernel(*trsProgs[device], "transpose");
            });


        NDRange local(THREADS_X, THREADS_Y);

        dim_type blk_x = divup(in.info.dims[0], TILE_DIM);
        dim_type blk_y = divup(in.info.dims[1], TILE_DIM);

        // launch batch * blk_x blocks along x dimension
        NDRange global(blk_x * local[0] * in.info.dims[2],
                       blk_y * local[1]);

        auto transposeOp = make_kernel<Buffer, const KParam,
                                       const Buffer, const KParam,
                                       const dim_type> (*trsKernels[device]);

        transposeOp(EnqueueArgs(getQueue(), global, local),
                    *out.data, out.info, *in.data, in.info, blk_x);

        CL_DEBUG_FINISH(getQueue());
    } catch (cl::Error err) {
        CL_TO_AF_ERROR(err);
        throw;
    }
}
コード例 #8
0
ファイル: diff.hpp プロジェクト: EmergentOrder/arrayfire
        void diff(Param out, const Param in, const unsigned indims)
        {
            try {
                static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
                static std::map<int, Program*>   diffProgs;
                static std::map<int, Kernel*>  diffKernels;

                int device = getActiveDeviceId();

                std::call_once( compileFlags[device], [device] () {
                    std::ostringstream options;
                    options << " -D T="        << dtype_traits<T>::getName()
                            << " -D DIM="      << dim
                            << " -D isDiff2=" << isDiff2;
                    if (std::is_same<T, double>::value ||
                        std::is_same<T, cdouble>::value) {
                        options << " -D USE_DOUBLE";
                    }
                    Program prog;
                    buildProgram(prog, diff_cl, diff_cl_len, options.str());
                    diffProgs[device]   = new Program(prog);
                    diffKernels[device] = new Kernel(*diffProgs[device], "diff_kernel");
                });

                auto diffOp = make_kernel<Buffer, const Buffer, const KParam, const KParam,
                                          const dim_type, const dim_type, const dim_type>
                                          (*diffKernels[device]);

                NDRange local(TX, TY, 1);
                if(dim == 0 && indims == 1) {
                    local = NDRange(TX * TY, 1, 1);
                }

                dim_type blocksPerMatX = divup(out.info.dims[0], local[0]);
                dim_type blocksPerMatY = divup(out.info.dims[1], local[1]);
                NDRange global(local[0] * blocksPerMatX * out.info.dims[2],
                               local[1] * blocksPerMatY * out.info.dims[3],
                               1);

                const dim_type oElem = out.info.dims[0] * out.info.dims[1]
                                     * out.info.dims[2] * out.info.dims[3];

                diffOp(EnqueueArgs(getQueue(), global, local),
                       *out.data, *in.data, out.info, in.info,
                       oElem, blocksPerMatX, blocksPerMatY);

                CL_DEBUG_FINISH(getQueue());
            } catch (cl::Error err) {
                CL_TO_AF_ERROR(err);
                throw;
            }
        }
コード例 #9
0
ファイル: join.hpp プロジェクト: EmergentOrder/arrayfire
        void join(Param out, const Param X, const Param Y)
        {
            try {
                static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
                static std::map<int, Program*>   joinProgs;
                static std::map<int, Kernel *> joinKernels;

                int device = getActiveDeviceId();

                std::call_once( compileFlags[device], [device] () {
                    std::ostringstream options;
                    options << " -D Tx=" << dtype_traits<Tx>::getName()
                            << " -D Ty=" << dtype_traits<Ty>::getName()
                            << " -D dim=" << dim;

                    if (std::is_same<Tx, double>::value ||
                        std::is_same<Tx, cdouble>::value) {
                        options << " -D USE_DOUBLE";
                    } else if (std::is_same<Tx, double>::value ||
                        std::is_same<Tx, cdouble>::value) {
                        options << " -D USE_DOUBLE";
                    }

                    Program prog;
                    buildProgram(prog, join_cl, join_cl_len, options.str());
                    joinProgs[device] = new Program(prog);
                    joinKernels[device] = new Kernel(*joinProgs[device], "join_kernel");
                });

                auto joinOp = make_kernel<Buffer, const KParam, const Buffer, const KParam,
                              const Buffer, const KParam, const dim_type, const dim_type> (*joinKernels[device]);

                NDRange local(TX, TY, 1);

                dim_type blocksPerMatX = divup(out.info.dims[0], TILEX);
                dim_type blocksPerMatY = divup(out.info.dims[1], TILEY);
                NDRange global(local[0] * blocksPerMatX * out.info.dims[2],
                               local[1] * blocksPerMatY * out.info.dims[3],
                               1);

                joinOp(EnqueueArgs(getQueue(), global, local), *out.data, out.info,
                       *X.data, X.info, *Y.data, Y.info, blocksPerMatX, blocksPerMatY);

                CL_DEBUG_FINISH(getQueue());
            } catch (cl::Error err) {
                CL_TO_AF_ERROR(err);
                throw;
            }
        }
コード例 #10
0
ファイル: scan_dim.hpp プロジェクト: klemmster/arrayfire
static Kernel* get_scan_dim_kernels(int kerIdx)
{
    try {
        static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
        static std::map<int, Program*> scanProgs;
        static std::map<int, Kernel*>  scanKerns;
        static std::map<int, Kernel*>  bcastKerns;

        int device= getActiveDeviceId();

        std::call_once(compileFlags[device], [device] () {

            Binary<To, op> scan;
            ToNum<To> toNum;

            std::ostringstream options;
            options << " -D To=" << dtype_traits<To>::getName()
                    << " -D Ti=" << dtype_traits<Ti>::getName()
                    << " -D T=To"
                    << " -D dim=" << dim
                    << " -D DIMY=" << threads_y
                    << " -D THREADS_X=" << THREADS_X
                    << " -D init=" << toNum(scan.init())
                    << " -D " << binOpName<op>()
                    << " -D CPLX=" << af::iscplx<Ti>()
                    << " -D isFinalPass="******" -D USE_DOUBLE";
            }

            const char *ker_strs[] = {ops_cl, scan_dim_cl};
            const int   ker_lens[] = {ops_cl_len, scan_dim_cl_len};
            cl::Program prog;
            buildProgram(prog, 2, ker_strs, ker_lens, options.str());
            scanProgs[device] = new Program(prog);

            scanKerns[device] = new Kernel(*scanProgs[device],  "scan_dim_kernel");
            bcastKerns[device] = new Kernel(*scanProgs[device],  "bcast_dim_kernel");

        });

        return (kerIdx == 0) ? scanKerns[device] : bcastKerns[device];
    } catch (cl::Error err) {
        CL_TO_AF_ERROR(err);
        throw;
    }
}
コード例 #11
0
ファイル: cholesky.cpp プロジェクト: PierreBizouard/arrayfire
Array<T> cholesky(int *info, const Array<T> &in, const bool is_upper)
{
    try {

        Array<T> out = copyArray<T>(in);
        *info = cholesky_inplace(out, is_upper);

        if (is_upper) triangle<T, true , false>(out, out);
        else          triangle<T, false, false>(out, out);

        return out;

    } catch (cl::Error &err) {
        CL_TO_AF_ERROR(err);
    }
}
コード例 #12
0
ファイル: random.hpp プロジェクト: EmergentOrder/arrayfire
        void random(cl::Buffer out, dim_type elements)
        {
            try {
                static unsigned counter;

                static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
                static Program            ranProgs[DeviceManager::MAX_DEVICES];
                static Kernel           ranKernels[DeviceManager::MAX_DEVICES];

                int device = getActiveDeviceId();

                std::call_once( compileFlags[device], [device] () {
                        Program::Sources setSrc;
                        setSrc.emplace_back(random_cl, random_cl_len);

                        std::ostringstream options;
                        options << " -D T=" << dtype_traits<T>::getName()
                                << " -D repeat="<< REPEAT
                                << " -D " << random_name<T, isRandu>().name();

                        if (std::is_same<T, double>::value) {
                            options << " -D USE_DOUBLE";
                            options << " -D IS_64";
                        }

                        if (std::is_same<T, char>::value) {
                            options << " -D IS_BOOL";
                        }

                        buildProgram(ranProgs[device], random_cl, random_cl_len, options.str());
                        ranKernels[device] = Kernel(ranProgs[device], "random");
                    });

                auto randomOp = make_kernel<cl::Buffer, uint, uint, uint, uint>(ranKernels[device]);

                uint groups = divup(elements, THREADS * REPEAT);
                counter += divup(elements, THREADS * groups);

                NDRange local(THREADS, 1);
                NDRange global(THREADS * groups, 1);

                randomOp(EnqueueArgs(getQueue(), global, local),
                         out, elements, counter, random_seed[0], random_seed[1]);
            } catch(cl::Error ex) {
                CL_TO_AF_ERROR(ex);
            }
        }
コード例 #13
0
ファイル: select.hpp プロジェクト: Brainiarc7/arrayfire
        void select(Param out, Param cond, Param a, Param b, int ndims)
        {
            try {
                bool is_same = true;
                for (int i = 0; i < 4; i++) {
                    is_same &= (a.info.dims[i] == b.info.dims[i]);
                }

                if (is_same) {
                    select_launcher<T, true >(out, cond, a, b, ndims);
                } else {
                    select_launcher<T, false>(out, cond, a, b, ndims);
                }
            } catch (cl::Error err) {
                CL_TO_AF_ERROR(err);
            }
        }
コード例 #14
0
ファイル: transpose.hpp プロジェクト: EasonYi/arrayfire
void transpose(Param out, const Param in)
{
    try {
        static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
        static Program            trsProgs[DeviceManager::MAX_DEVICES];
        static Kernel           trsKernels[DeviceManager::MAX_DEVICES];

        int device = getActiveDeviceId();

        std::call_once( compileFlags[device], [device] () {

                std::ostringstream options;
                options << " -D T=" << dtype_traits<T>::getName()
                        << " -D TILE_DIM=" << TILE_DIM;

                buildProgram(trsProgs[device],
                             transpose_cl,
                             transpose_cl_len,
                             options.str());

                trsKernels[device] = Kernel(trsProgs[device], "transpose");
            });


        NDRange local(THREADS_X, THREADS_Y);

        dim_type blk_x = divup(in.info.dims[0], TILE_DIM);
        dim_type blk_y = divup(in.info.dims[1], TILE_DIM);

        // launch batch * blk_x blocks along x dimension
        NDRange global(blk_x * TILE_DIM * in.info.dims[2], blk_y * TILE_DIM);

        auto transposeOp = make_kernel<Buffer, KParam,
                                       Buffer, KParam,
                                       dim_type> (trsKernels[device]);


        transposeOp(EnqueueArgs(getQueue(), global, local),
                    out.data, out.info, in.data, in.info, blk_x);

        CL_DEBUG_FINISH(getQueue());
    } catch (cl::Error err) {
        CL_TO_AF_ERROR(err);
        throw;
    }
}
コード例 #15
0
ファイル: index.hpp プロジェクト: Brainiarc7/arrayfire
void index(Param out, const Param in, const IndexKernelParam_t& p, Buffer *bPtr[4])
{
    try {
        static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
        static std::map<int, Program*>  idxProgs;
        static std::map<int, Kernel*> idxKernels;

        int device = getActiveDeviceId();

        std::call_once( compileFlags[device], [device] () {
                std::ostringstream options;
                options << " -D T=" << dtype_traits<T>::getName();

                if (std::is_same<T, double>::value ||
                    std::is_same<T, cdouble>::value) {
                options << " -D USE_DOUBLE";
                }

                Program prog;
                buildProgram(prog, index_cl, index_cl_len, options.str());
                idxProgs[device]   = new Program(prog);
                idxKernels[device] = new Kernel(*idxProgs[device], "indexKernel");
                });

        NDRange local(THREADS_X, THREADS_Y);

        int blk_x = divup(out.info.dims[0], THREADS_X);
        int blk_y = divup(out.info.dims[1], THREADS_Y);

        NDRange global(blk_x * out.info.dims[2] * THREADS_X,
                blk_y * out.info.dims[3] * THREADS_Y);

        auto indexOp = make_kernel<Buffer, KParam, Buffer, KParam, IndexKernelParam_t,
             Buffer, Buffer, Buffer, Buffer, int, int>(*idxKernels[device]);

        indexOp(EnqueueArgs(getQueue(), global, local),
                *out.data, out.info, *in.data, in.info, p,
                *bPtr[0], *bPtr[1], *bPtr[2], *bPtr[3], blk_x, blk_y);

        CL_DEBUG_FINISH(getQueue());
    } catch (cl::Error err) {
        CL_TO_AF_ERROR(err);
        throw;
    }
}
コード例 #16
0
ファイル: transform.hpp プロジェクト: EasonYi/arrayfire
        void transform(Param out, const Param in, const Param tf)
        {
            try {
                static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
                static Program      transformProgs[DeviceManager::MAX_DEVICES];
                static Kernel     transformKernels[DeviceManager::MAX_DEVICES];

                int device = getActiveDeviceId();

                std::call_once( compileFlags[device], [device] () {
                    std::ostringstream options;
                    options << " -D T="        << dtype_traits<T>::getName()
                            << " -D INVERSE="  << (isInverse ? 1 : 0);

                    buildProgram(transformProgs[device],
                                 transform_cl,
                                 transform_cl_len,
                                 options.str());

                    transformKernels[device] = Kernel(transformProgs[device], "transform_kernel");
                });

                auto transformOp = make_kernel<Buffer, const KParam,
                                         const Buffer, const KParam, const Buffer, const KParam,
                                         const dim_type, const dim_type>
                                         (transformKernels[device]);

                const dim_type nimages = in.info.dims[2];
                // Multiplied in src/backend/transform.cpp
                const dim_type ntransforms = out.info.dims[2] / in.info.dims[2];
                NDRange local(TX, TY, 1);

                NDRange global(local[0] * divup(out.info.dims[0], local[0]) * nimages,
                               local[1] * divup(out.info.dims[1], local[1]) * ntransforms,
                               1);

                transformOp(EnqueueArgs(getQueue(), global, local),
                         out.data, out.info, in.data, in.info, tf.data, tf.info, nimages, ntransforms);

                CL_DEBUG_FINISH(getQueue());
            } catch (cl::Error err) {
                CL_TO_AF_ERROR(err);
                throw;
            }
        }
コード例 #17
0
ファイル: solve.cpp プロジェクト: PierreBizouard/arrayfire
Array<T> solve(const Array<T> &a, const Array<T> &b, const af_mat_prop options)
{
    try {
        initBlas();

        if (options & AF_MAT_UPPER ||
            options & AF_MAT_LOWER) {
            return triangleSolve<T>(a, b, options);
        }

        if(a.dims()[0] == a.dims()[1]) {
            return generalSolve<T>(a, b);
        } else {
            return leastSquares<T>(a, b);
        }
    } catch(cl::Error &err) {
        CL_TO_AF_ERROR(err);
    }
}
コード例 #18
0
        void sort0_by_key(Param okey, Param oval)
        {
            try {
                compute::command_queue c_queue(getQueue()());

                compute::buffer okey_buf((*okey.data)());
                compute::buffer oval_buf((*oval.data)());

                for(dim_type w = 0; w < okey.info.dims[3]; w++) {
                    dim_type okeyW = w * okey.info.strides[3];
                    dim_type ovalW = w * oval.info.strides[3];
                    for(dim_type z = 0; z < okey.info.dims[2]; z++) {
                        dim_type okeyWZ = okeyW + z * okey.info.strides[2];
                        dim_type ovalWZ = ovalW + z * oval.info.strides[2];
                        for(dim_type y = 0; y < okey.info.dims[1]; y++) {

                            dim_type okeyOffset = okeyWZ + y * okey.info.strides[1];
                            dim_type ovalOffset = ovalWZ + y * oval.info.strides[1];

                            if(isAscending) {
                                compute::sort_by_key(
                                        compute::make_buffer_iterator<Tk>(okey_buf, okeyOffset),
                                        compute::make_buffer_iterator<Tk>(okey_buf, okeyOffset + okey.info.dims[0]),
                                        compute::make_buffer_iterator<Tv>(oval_buf, ovalOffset),
                                        compute::less<Tk>(), c_queue);
                            } else {
                                compute::sort_by_key(
                                        compute::make_buffer_iterator<Tk>(okey_buf, okeyOffset),
                                        compute::make_buffer_iterator<Tk>(okey_buf, okeyOffset + okey.info.dims[0]),
                                        compute::make_buffer_iterator<Tv>(oval_buf, ovalOffset),
                                        compute::greater<Tk>(), c_queue);
                            }
                        }
                    }
                }

                CL_DEBUG_FINISH(getQueue());
            } catch (cl::Error err) {
                CL_TO_AF_ERROR(err);
                throw;
            }
        }
コード例 #19
0
ファイル: conv_common.hpp プロジェクト: shehzan10/arrayfire
void convNHelper(const conv_kparam_t& param, Param& out, const Param& signal, const Param& filter)
{
    try {
        static std::once_flag  compileFlags[DeviceManager::MAX_DEVICES];
        static std::map<int, Program*> convProgs;
        static std::map<int, Kernel*>  convKernels;

        int device = getActiveDeviceId();

        std::call_once( compileFlags[device], [device] () {
                    std::ostringstream options;
                    options << " -D T=" << dtype_traits<T>::getName()
                            << " -D accType="<< dtype_traits<aT>::getName()
                            << " -D BASE_DIM="<< bDim
                            << " -D EXPAND=" << expand;
                    if (std::is_same<T, double>::value ||
                        std::is_same<T, cdouble>::value) {
                        options << " -D USE_DOUBLE";
                    }
                    Program prog;
                    buildProgram(prog, convolve_cl, convolve_cl_len, options.str());
                    convProgs[device]   = new Program(prog);
                    convKernels[device] = new Kernel(*convProgs[device], "convolve");
                });

        auto convOp = cl::KernelFunctor<Buffer, KParam, Buffer, KParam,
                                        cl::LocalSpaceArg, Buffer, KParam,
                                        int, int,
                                        int, int, int,
                                        int, int, int
                                       >(*convKernels[device]);

        convOp(EnqueueArgs(getQueue(), param.global, param.local),
                *out.data, out.info, *signal.data, signal.info, cl::Local(param.loc_size),
                *param.impulse, filter.info, param.nBBS0, param.nBBS1,
                param.o[0], param.o[1], param.o[2], param.s[0], param.s[1], param.s[2]);

    } catch (cl::Error err) {
        CL_TO_AF_ERROR(err);
        throw;
    }
}
コード例 #20
0
ファイル: cholesky.cpp プロジェクト: PierreBizouard/arrayfire
int cholesky_inplace(Array<T> &in, const bool is_upper)
{
    try {
        initBlas();

        dim4 iDims = in.dims();
        int N = iDims[0];

        magma_uplo_t uplo = is_upper ? MagmaUpper : MagmaLower;

        int info = 0;
        cl::Buffer *in_buf = in.get();
        magma_potrf_gpu<T>(uplo, N,
                           (*in_buf)(), in.getOffset(),  in.strides()[1],
                           getQueue()(), &info);
        return info;
    } catch (cl::Error &err) {
        CL_TO_AF_ERROR(err);
    }
}
コード例 #21
0
ファイル: sort.hpp プロジェクト: rotorliu/arrayfire
        void sort0(Param val)
        {
            try {
                compute::command_queue c_queue(getQueue()());

                compute::buffer val_buf((*val.data)());

                for(int w = 0; w < val.info.dims[3]; w++) {
                    int valW = w * val.info.strides[3];
                    for(int z = 0; z < val.info.dims[2]; z++) {
                        int valWZ = valW + z * val.info.strides[2];
                        for(int y = 0; y < val.info.dims[1]; y++) {

                            int valOffset = valWZ + y * val.info.strides[1];

                            if(isAscending) {
                                compute::stable_sort(
                                        compute::make_buffer_iterator<T>(val_buf, valOffset),
                                        compute::make_buffer_iterator<T>(val_buf, valOffset + val.info.dims[0]),
                                        compute::less<T>(), c_queue);
                            } else {
                                compute::stable_sort(
                                        compute::make_buffer_iterator<T>(val_buf, valOffset),
                                        compute::make_buffer_iterator<T>(val_buf, valOffset + val.info.dims[0]),
                                        compute::greater<T>(), c_queue);
                            }
                        }
                    }
                }

                CL_DEBUG_FINISH(getQueue());
            } catch (cl::Error err) {
                CL_TO_AF_ERROR(err);
                throw;
            }
        }
コード例 #22
0
ファイル: scan_dim.hpp プロジェクト: klemmster/arrayfire
static void scan_dim(Param &out, const Param &in)
{
    try {
        uint threads_y = std::min(THREADS_Y, nextpow2(out.info.dims[dim]));
        uint threads_x = THREADS_X;

        uint groups_all[] = {divup((uint)out.info.dims[0], threads_x),
                             (uint)out.info.dims[1],
                             (uint)out.info.dims[2],
                             (uint)out.info.dims[3]
                            };

        groups_all[dim] = divup(out.info.dims[dim], threads_y * REPEAT);

        if (groups_all[dim] == 1) {

            scan_dim_fn<Ti, To, op, dim, true>(out, out, in,
                                               threads_y,
                                               groups_all);
        } else {

            Param tmp = out;

            tmp.info.dims[dim] = groups_all[dim];
            tmp.info.strides[0] = 1;
            for (int k = 1; k < 4; k++) {
                tmp.info.strides[k] = tmp.info.strides[k - 1] * tmp.info.dims[k - 1];
            }

            int tmp_elements = tmp.info.strides[3] * tmp.info.dims[3];
            // FIXME: Do I need to free this ?
            tmp.data = bufferAlloc(tmp_elements * sizeof(To));

            scan_dim_fn<Ti, To, op, dim, false>(out, tmp, in,
                                                threads_y,
                                                groups_all);

            int gdim = groups_all[dim];
            groups_all[dim] = 1;

            if (op == af_notzero_t) {
                scan_dim_fn<To, To, af_add_t, dim, true>(tmp, tmp, tmp,
                        threads_y,
                        groups_all);
            } else {
                scan_dim_fn<To, To,       op, dim, true>(tmp, tmp, tmp,
                        threads_y,
                        groups_all);
            }

            groups_all[dim] = gdim;
            bcast_dim_fn<To, To, op, dim, true>(out, tmp,
                                                threads_y,
                                                groups_all);
            bufferFree(tmp.data);
        }
    } catch (cl::Error err) {
        CL_TO_AF_ERROR(err);
        throw;
    }
}
コード例 #23
0
void exampleFunc(Param c, const Param a, const Param b, const af_someenum_t p)
{
    try {
        static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
        static std::map<int, Program*>  egProgs;
        static std::map<int, Kernel*> egKernels;

        int device = getActiveDeviceId();

        // std::call_once is used to ensure OpenCL kernels
        // are compiled only once for any given device and combination
        // of template parameters to this kernel wrapper function 'exampleFunc<T>'
        std::call_once( compileFlags[device], [device] () {

                std::ostringstream options;
                options << " -D T=" << dtype_traits<T>::getName();
                // You can pass any template parameters as compile options
                // to kernel the compilation step. This is equivalent of
                // having templated kernels in CUDA

                // The following option is passed to kernel compilation
                // if template parameter T is double or complex double
                // to enable FP64 extension
                if (std::is_same<T, double>::value ||
                    std::is_same<T, cdouble>::value) {
                    options << " -D USE_DOUBLE";
                }

                Program prog;
                // below helper function 'buildProgram' uses the option string
                // we just created and compiles the kernel string
                // 'example_cl' which was created by our opencl kernel code obfuscation
                // stage
                buildProgram(prog, example_cl, example_cl_len, options.str());

                // create a cl::Program object on heap
                egProgs[device]   = new Program(prog);

                // create a cl::Kernel object on heap
                egKernels[device] = new Kernel(*egProgs[device], "example");
            });

        // configure work group parameters
        NDRange local(THREADS_X, THREADS_Y);

        int blk_x = divup(c.info.dims[0], THREADS_X);
        int blk_y = divup(c.info.dims[1], THREADS_Y);

        // configure global launch parameters
        NDRange global(blk_x * THREADS_X, blk_y * THREADS_Y);

        // create a kernel functor from the cl::Kernel object
        // corresponding to the device on which current execution
        // is happending.
        auto exampleFuncOp = KernelFunctor<Buffer, KParam, Buffer, KParam,
                                           Buffer, KParam, int>(*egKernels[device]);

        // launch the kernel
        exampleFuncOp(EnqueueArgs(getQueue(), global, local),
                    *c.data, c.info, *a.data, a.info, *b.data, b.info, (int)p);

        // Below Macro activates validations ONLY in DEBUG
        // mode as its name indicates
        CL_DEBUG_FINISH(getQueue());
    } catch (cl::Error err) { // Catch all cl::Errors and convert them
                              // to appropriate ArrayFire error codes
        CL_TO_AF_ERROR(err);
    }
}
コード例 #24
0
ファイル: memcopy.hpp プロジェクト: shehzan10/arrayfire
    void copy(Param dst, const Param src, int ndims, outType default_value, double factor)
    {
        try {
            static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
            static std::map<int, Program*>    cpyProgs;
            static std::map<int, Kernel*>   cpyKernels;

            int device = getActiveDeviceId();

            std::call_once(compileFlags[device], [&]() {

                        std::ostringstream options;
                        options << " -D inType=" << dtype_traits<inType>::getName()
                            << " -D outType=" << dtype_traits<outType>::getName()
                            << " -D inType_" << dtype_traits<inType>::getName()
                            << " -D outType_" << dtype_traits<outType>::getName()
                            << " -D SAME_DIMS=" << same_dims;
                        if (std::is_same<inType, double>::value  ||
                            std::is_same<inType, cdouble>::value ||
                            std::is_same<outType, double>::value ||
                            std::is_same<outType, cdouble>::value) {
                            options << " -D USE_DOUBLE";
                        }

                        Program prog;
                        buildProgram(prog, copy_cl, copy_cl_len, options.str());
                        cpyProgs[device]   = new Program(prog);
                        cpyKernels[device] = new Kernel(*cpyProgs[device], "copy");
                    });

            NDRange local(DIM0, DIM1);
            size_t local_size[] = {DIM0, DIM1};

            local_size[0] *= local_size[1];
            if (ndims == 1) {
                local_size[1] = 1;
            }

            int blk_x = divup(dst.info.dims[0], local_size[0]);
            int blk_y = divup(dst.info.dims[1], local_size[1]);

            NDRange global(blk_x * dst.info.dims[2] * DIM0,
                    blk_y * dst.info.dims[3] * DIM1);

            dims_t trgt_dims;
            if (same_dims) {
                trgt_dims= {{dst.info.dims[0], dst.info.dims[1], dst.info.dims[2], dst.info.dims[3]}};
            } else {
                dim_t trgt_l = std::min(dst.info.dims[3], src.info.dims[3]);
                dim_t trgt_k = std::min(dst.info.dims[2], src.info.dims[2]);
                dim_t trgt_j = std::min(dst.info.dims[1], src.info.dims[1]);
                dim_t trgt_i = std::min(dst.info.dims[0], src.info.dims[0]);
                trgt_dims= {{trgt_i, trgt_j, trgt_k, trgt_l}};
            }

            auto copyOp = KernelFunctor<Buffer, KParam, Buffer, KParam,
                                      outType, float, dims_t,
                                      int, int
                                     >(*cpyKernels[device]);

            copyOp(EnqueueArgs(getQueue(), global, local),
                   *dst.data, dst.info, *src.data, src.info,
                   default_value, (float)factor, trgt_dims, blk_x, blk_y);
            CL_DEBUG_FINISH(getQueue());
        } catch (cl::Error err) {
            CL_TO_AF_ERROR(err);
            throw;
        }
    }
コード例 #25
0
void packDataHelper(Param packed,
                    Param sig,
                    Param filter,
                    const int baseDim,
                    ConvolveBatchKind kind)
{
    try {
        static std::once_flag     compileFlags[DeviceManager::MAX_DEVICES];
        static std::map<int, Program*>  fftconvolveProgs;
        static std::map<int, Kernel*>   pdKernel;
        static std::map<int, Kernel*>   paKernel;

        int device = getActiveDeviceId();

        std::call_once( compileFlags[device], [device] () {

                std::ostringstream options;
                options << " -D T=" << dtype_traits<T>::getName();

                if ((af_dtype) dtype_traits<convT>::af_type == c32) {
                    options << " -D CONVT=float";
                }
                else if ((af_dtype) dtype_traits<convT>::af_type == c64 && isDouble) {
                    options << " -D CONVT=double"
                            << " -D USE_DOUBLE";
                }

                cl::Program prog;
                buildProgram(prog, fftconvolve_pack_cl, fftconvolve_pack_cl_len, options.str());
                fftconvolveProgs[device] = new Program(prog);

                pdKernel[device] = new Kernel(*fftconvolveProgs[device], "pack_data");
                paKernel[device] = new Kernel(*fftconvolveProgs[device], "pad_array");
            });

        Param sig_tmp, filter_tmp;
        calcParamSizes(sig_tmp, filter_tmp, packed, sig, filter, baseDim, kind);

        int sig_packed_elem = sig_tmp.info.strides[3] * sig_tmp.info.dims[3];
        int filter_packed_elem = filter_tmp.info.strides[3] * filter_tmp.info.dims[3];

        // Number of packed complex elements in dimension 0
        int sig_half_d0 = divup(sig.info.dims[0], 2);
        int sig_half_d0_odd = sig.info.dims[0] % 2;

        int blocks = divup(sig_packed_elem, THREADS);

        // Locate features kernel sizes
        NDRange local(THREADS);
        NDRange global(blocks * THREADS);

        // Pack signal in a complex matrix where first dimension is half the input
        // (allows faster FFT computation) and pad array to a power of 2 with 0s
        auto pdOp = make_kernel<Buffer, KParam,
                                Buffer, KParam,
                                const int, const int> (*pdKernel[device]);

        pdOp(EnqueueArgs(getQueue(), global, local),
             *sig_tmp.data, sig_tmp.info, *sig.data, sig.info,
             sig_half_d0, sig_half_d0_odd);
        CL_DEBUG_FINISH(getQueue());

        blocks = divup(filter_packed_elem, THREADS);
        global = NDRange(blocks * THREADS);

        // Pad filter array with 0s
        auto paOp = make_kernel<Buffer, KParam,
                                Buffer, KParam> (*paKernel[device]);

        paOp(EnqueueArgs(getQueue(), global, local),
             *filter_tmp.data, filter_tmp.info,
             *filter.data, filter.info);
        CL_DEBUG_FINISH(getQueue());
    } catch (cl::Error err) {
        CL_TO_AF_ERROR(err);
        throw;
    }
}
コード例 #26
0
void complexMultiplyHelper(Param packed,
                           Param sig,
                           Param filter,
                           const int baseDim,
                           ConvolveBatchKind kind)
{
    try {
        static std::once_flag     compileFlags[DeviceManager::MAX_DEVICES];
        static std::map<int, Program*> fftconvolveProgs;
        static std::map<int, Kernel*>  cmKernel;

        int device = getActiveDeviceId();

        std::call_once( compileFlags[device], [device] () {

                std::ostringstream options;
                options << " -D T=" << dtype_traits<T>::getName()
                        << " -D ONE2ONE=" << (int)ONE2ONE
                        << " -D MANY2ONE=" << (int)MANY2ONE
                        << " -D ONE2MANY=" << (int)ONE2MANY
                        << " -D MANY2MANY=" << (int)MANY2MANY;

                if ((af_dtype) dtype_traits<convT>::af_type == c32) {
                    options << " -D CONVT=float";
                }
                else if ((af_dtype) dtype_traits<convT>::af_type == c64 && isDouble) {
                    options << " -D CONVT=double"
                            << " -D USE_DOUBLE";
                }

                cl::Program prog;
                buildProgram(prog,
                             fftconvolve_multiply_cl,
                             fftconvolve_multiply_cl_len,
                             options.str());
                fftconvolveProgs[device] = new Program(prog);

                cmKernel[device] = new Kernel(*fftconvolveProgs[device], "complex_multiply");
            });

        Param sig_tmp, filter_tmp;
        calcParamSizes(sig_tmp, filter_tmp, packed, sig, filter, baseDim, kind);

        int sig_packed_elem = sig_tmp.info.strides[3] * sig_tmp.info.dims[3];
        int filter_packed_elem = filter_tmp.info.strides[3] * filter_tmp.info.dims[3];
        int mul_elem = (sig_packed_elem < filter_packed_elem) ?
                            filter_packed_elem : sig_packed_elem;

        int blocks = divup(mul_elem, THREADS);

        NDRange local(THREADS);
        NDRange global(blocks * THREADS);

        // Multiply filter and signal FFT arrays
        auto cmOp = make_kernel<Buffer, KParam,
                                Buffer, KParam,
                                Buffer, KParam,
                                const int, const int> (*cmKernel[device]);

        cmOp(EnqueueArgs(getQueue(), global, local),
             *packed.data, packed.info,
             *sig_tmp.data, sig_tmp.info,
             *filter_tmp.data, filter_tmp.info,
             mul_elem, (int)kind);
        CL_DEBUG_FINISH(getQueue());
    } catch (cl::Error err) {
        CL_TO_AF_ERROR(err);
        throw;
    }
}
コード例 #27
0
void reorderOutputHelper(Param out,
                         Param packed,
                         Param sig,
                         Param filter,
                         const int baseDim,
                         ConvolveBatchKind kind)
{
    try {
        static std::once_flag     compileFlags[DeviceManager::MAX_DEVICES];
        static std::map<int, Program*> fftconvolveProgs;
        static std::map<int, Kernel*>  roKernel;

        int device = getActiveDeviceId();

        std::call_once( compileFlags[device], [device] () {

                std::ostringstream options;
                options << " -D T=" << dtype_traits<T>::getName()
                        << " -D ROUND_OUT=" << (int)roundOut
                        << " -D EXPAND=" << (int)expand;

                if ((af_dtype) dtype_traits<convT>::af_type == c32) {
                    options << " -D CONVT=float";
                }
                else if ((af_dtype) dtype_traits<convT>::af_type == c64 && isDouble) {
                    options << " -D CONVT=double"
                            << " -D USE_DOUBLE";
                }

                cl::Program prog;
                buildProgram(prog,
                             fftconvolve_reorder_cl,
                             fftconvolve_reorder_cl_len,
                             options.str());
                fftconvolveProgs[device] = new Program(prog);

                roKernel[device] = new Kernel(*fftconvolveProgs[device], "reorder_output");
            });

        Param sig_tmp, filter_tmp;
        calcParamSizes(sig_tmp, filter_tmp, packed, sig, filter, baseDim, kind);

        // Number of packed complex elements in dimension 0
        int sig_half_d0 = divup(sig.info.dims[0], 2);

        int blocks = divup(out.info.strides[3] * out.info.dims[3], THREADS);

        NDRange local(THREADS);
        NDRange global(blocks * THREADS);

        auto roOp = make_kernel<Buffer, KParam,
                                Buffer, KParam,
                                KParam, const int,
                                const int> (*roKernel[device]);

        if (kind == ONE2MANY) {
            roOp(EnqueueArgs(getQueue(), global, local),
                 *out.data, out.info,
                 *filter_tmp.data, filter_tmp.info,
                 filter.info, sig_half_d0, baseDim);
        }
        else {
            roOp(EnqueueArgs(getQueue(), global, local),
                 *out.data, out.info,
                 *sig_tmp.data, sig_tmp.info,
                 filter.info, sig_half_d0, baseDim);
        }
        CL_DEBUG_FINISH(getQueue());
    } catch (cl::Error err) {
        CL_TO_AF_ERROR(err);
        throw;
    }
}
コード例 #28
0
void nearest_neighbour(Param idx,
                       Param dist,
                       Param query,
                       Param train,
                       const dim_t dist_dim,
                       const unsigned n_dist)
{
    try {
        const unsigned feat_len = query.info.dims[dist_dim];
        const To max_dist = maxval<To>();

        // Determine maximum feat_len capable of using shared memory (faster)
        cl_ulong avail_lmem = getDevice().getInfo<CL_DEVICE_LOCAL_MEM_SIZE>();
        size_t lmem_predef = 2 * THREADS * sizeof(unsigned) + feat_len * sizeof(T);
        size_t ltrain_sz = THREADS * feat_len * sizeof(T);
        bool use_lmem = (avail_lmem >= (lmem_predef + ltrain_sz)) ? true : false;
        size_t lmem_sz = (use_lmem) ? lmem_predef + ltrain_sz : lmem_predef;

        unsigned unroll_len = nextpow2(feat_len);
        if (unroll_len != feat_len) unroll_len = 0;

        std::string ref_name =
            std::string("knn_") +
            std::to_string(dist_type) +
            std::string("_") +
            std::to_string(use_lmem) +
            std::string("_") +
            std::string(dtype_traits<T>::getName()) +
            std::string("_") +
            std::to_string(unroll_len);

        int device = getActiveDeviceId();
        kc_t::iterator cache_idx = kernelCaches[device].find(ref_name);

        kc_entry_t entry;
        if (cache_idx == kernelCaches[device].end()) {

                std::ostringstream options;
                options << " -D T=" << dtype_traits<T>::getName()
                        << " -D To=" << dtype_traits<To>::getName()
                        << " -D THREADS=" << THREADS
                        << " -D FEAT_LEN=" << unroll_len;

                switch(dist_type) {
                    case AF_SAD: options <<" -D DISTOP=_sad_"; break;
                    case AF_SSD: options <<" -D DISTOP=_ssd_"; break;
                    case AF_SHD: options <<" -D DISTOP=_shd_ -D __SHD__";
                                 break;
                    default: break;
                }

                if (std::is_same<T, double>::value ||
                    std::is_same<T, cdouble>::value) {
                    options << " -D USE_DOUBLE";
                }

                if (use_lmem)
                    options << " -D USE_LOCAL_MEM";

                cl::Program prog;
                buildProgram(prog,
                             nearest_neighbour_cl,
                             nearest_neighbour_cl_len,
                             options.str());

                entry.prog = new Program(prog);
                entry.ker = new Kernel[3];

                entry.ker[0] = Kernel(*entry.prog, "nearest_neighbour_unroll");
                entry.ker[1] = Kernel(*entry.prog, "nearest_neighbour");
                entry.ker[2] = Kernel(*entry.prog, "select_matches");

                kernelCaches[device][ref_name] = entry;
        } else {
            entry = cache_idx->second;
        }

        const dim_t sample_dim = (dist_dim == 0) ? 1 : 0;

        const unsigned nquery = query.info.dims[sample_dim];
        const unsigned ntrain = train.info.dims[sample_dim];

        unsigned nblk = divup(ntrain, THREADS);
        const NDRange local(THREADS, 1);
        const NDRange global(nblk * THREADS, 1);

        cl::Buffer *d_blk_idx  = bufferAlloc(nblk * nquery * sizeof(unsigned));
        cl::Buffer *d_blk_dist = bufferAlloc(nblk * nquery * sizeof(To));

        // For each query vector, find training vector with smallest Hamming
        // distance per CUDA block
        if (unroll_len > 0) {
            auto huOp = KernelFunctor<Buffer, Buffer,
                                    Buffer, KParam,
                                    Buffer, KParam,
                                    const To,
                                    LocalSpaceArg> (entry.ker[0]);

            huOp(EnqueueArgs(getQueue(), global, local),
                 *d_blk_idx, *d_blk_dist,
                 *query.data, query.info, *train.data, train.info,
                 max_dist, cl::Local(lmem_sz));
        }
        else {
            auto hmOp = KernelFunctor<Buffer, Buffer,
                                    Buffer, KParam,
                                    Buffer, KParam,
                                    const To, const unsigned,
                                    LocalSpaceArg> (entry.ker[1]);

            hmOp(EnqueueArgs(getQueue(), global, local),
                 *d_blk_idx, *d_blk_dist,
                 *query.data, query.info, *train.data, train.info,
                 max_dist, feat_len, cl::Local(lmem_sz));
        }
        CL_DEBUG_FINISH(getQueue());

        const NDRange local_sm(32, 8);
        const NDRange global_sm(divup(nquery, 32) * 32, 8);

        // Reduce all smallest Hamming distances from each block and store final
        // best match
        auto smOp = KernelFunctor<Buffer, Buffer, Buffer, Buffer,
                                const unsigned, const unsigned,
                                const To> (entry.ker[2]);

        smOp(EnqueueArgs(getQueue(), global_sm, local_sm),
             *idx.data, *dist.data,
             *d_blk_idx, *d_blk_dist,
             nquery, nblk, max_dist);
        CL_DEBUG_FINISH(getQueue());

        bufferFree(d_blk_idx);
        bufferFree(d_blk_dist);
    } catch (cl::Error err) {
        CL_TO_AF_ERROR(err);
        throw;
    }
}
コード例 #29
0
ファイル: orb.hpp プロジェクト: EmergentOrder/arrayfire
void orb(unsigned* out_feat,
         Param& x_out,
         Param& y_out,
         Param& score_out,
         Param& ori_out,
         Param& size_out,
         Param& desc_out,
         Param image,
         const float fast_thr,
         const unsigned max_feat,
         const float scl_fctr,
         const unsigned levels,
         const bool blur_img)
{
    try {
        static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
        static Program            orbProgs[DeviceManager::MAX_DEVICES];
        static Kernel             hrKernel[DeviceManager::MAX_DEVICES];
        static Kernel             kfKernel[DeviceManager::MAX_DEVICES];
        static Kernel             caKernel[DeviceManager::MAX_DEVICES];
        static Kernel             eoKernel[DeviceManager::MAX_DEVICES];

        int device = getActiveDeviceId();

        std::call_once( compileFlags[device], [device] () {

                std::ostringstream options;
                options << " -D T=" << dtype_traits<T>::getName()
                        << " -D BLOCK_SIZE=" << ORB_THREADS_X;

                if (std::is_same<T, double>::value ||
                    std::is_same<T, cdouble>::value) {
                    options << " -D USE_DOUBLE";
                }

                buildProgram(orbProgs[device],
                             orb_cl,
                             orb_cl_len,
                             options.str());

                hrKernel[device] = Kernel(orbProgs[device], "harris_response");
                kfKernel[device] = Kernel(orbProgs[device], "keep_features");
                caKernel[device] = Kernel(orbProgs[device], "centroid_angle");
                eoKernel[device] = Kernel(orbProgs[device], "extract_orb");
            });

        unsigned patch_size = REF_PAT_SIZE;

        unsigned min_side = std::min(image.info.dims[0], image.info.dims[1]);
        unsigned max_levels = 0;
        float scl_sum = 0.f;
        for (unsigned i = 0; i < levels; i++) {
            min_side /= scl_fctr;

            // Minimum image side for a descriptor to be computed
            if (min_side < patch_size || max_levels == levels) break;

            max_levels++;
            scl_sum += 1.f / (float)pow(scl_fctr,(float)i);
        }

        std::vector<cl::Buffer*> d_x_pyr(max_levels);
        std::vector<cl::Buffer*> d_y_pyr(max_levels);
        std::vector<cl::Buffer*> d_score_pyr(max_levels);
        std::vector<cl::Buffer*> d_ori_pyr(max_levels);
        std::vector<cl::Buffer*> d_size_pyr(max_levels);
        std::vector<cl::Buffer*> d_desc_pyr(max_levels);

        std::vector<unsigned> feat_pyr(max_levels);
        unsigned total_feat = 0;

        // Compute number of features to keep for each level
        std::vector<unsigned> lvl_best(max_levels);
        unsigned feat_sum = 0;
        for (unsigned i = 0; i < max_levels-1; i++) {
            float lvl_scl = (float)pow(scl_fctr,(float)i);
            lvl_best[i] = ceil((max_feat / scl_sum) / lvl_scl);
            feat_sum += lvl_best[i];
        }
        lvl_best[max_levels-1] = max_feat - feat_sum;

        // Maintain a reference to previous level image
        Param prev_img;
        Param lvl_img;

        const unsigned gauss_len = 9;
        T* h_gauss = nullptr;
        Param gauss_filter;
        gauss_filter.data = nullptr;

        for (unsigned i = 0; i < max_levels; i++) {
            const float lvl_scl = (float)pow(scl_fctr,(float)i);

            if (i == 0) {
                // First level is used in its original size
                lvl_img = image;

                prev_img = image;
            }
            else if (i > 0) {
                // Resize previous level image to current level dimensions
                lvl_img.info.dims[0] = round(image.info.dims[0] / lvl_scl);
                lvl_img.info.dims[1] = round(image.info.dims[1] / lvl_scl);

                lvl_img.info.strides[0] = 1;
                lvl_img.info.strides[1] = lvl_img.info.dims[0];

                for (int k = 2; k < 4; k++) {
                    lvl_img.info.dims[k] = 1;
                    lvl_img.info.strides[k] = lvl_img.info.dims[k - 1] * lvl_img.info.strides[k - 1];
                }

                lvl_img.info.offset = 0;
                lvl_img.data = bufferAlloc(lvl_img.info.dims[3] * lvl_img.info.strides[3] * sizeof(T));

                resize<T, AF_INTERP_BILINEAR>(lvl_img, prev_img);

                if (i > 1)
                   bufferFree(prev_img.data);
                prev_img = lvl_img;
            }

            unsigned lvl_feat = 0;
            Param d_x_feat, d_y_feat, d_score_feat;

            // Round feature size to nearest odd integer
            float size = 2.f * floor(patch_size / 2.f) + 1.f;

            // Avoid keeping features that might be too wide and might not fit on
            // the image, sqrt(2.f) is the radius when angle is 45 degrees and
            // represents widest case possible
            unsigned edge = ceil(size * sqrt(2.f) / 2.f);

            // Detect FAST features
            fast<T, 9, true>(&lvl_feat, d_x_feat, d_y_feat, d_score_feat,
                             lvl_img, fast_thr, 0.15f, edge);

            if (lvl_feat == 0) {
                feat_pyr[i] = 0;

                if (i > 0 && i == max_levels-1)
                    bufferFree(lvl_img.data);

                continue;
            }

            bufferFree(d_score_feat.data);

            unsigned usable_feat = 0;
            cl::Buffer* d_usable_feat = bufferAlloc(sizeof(unsigned));
            getQueue().enqueueWriteBuffer(*d_usable_feat, CL_TRUE, 0, sizeof(unsigned), &usable_feat);

            cl::Buffer* d_x_harris = bufferAlloc(lvl_feat * sizeof(float));
            cl::Buffer* d_y_harris = bufferAlloc(lvl_feat * sizeof(float));
            cl::Buffer* d_score_harris = bufferAlloc(lvl_feat * sizeof(float));

            // Calculate Harris responses
            // Good block_size >= 7 (must be an odd number)
            const dim_type blk_x = divup(lvl_feat, ORB_THREADS_X);
            const NDRange local(ORB_THREADS_X, ORB_THREADS_Y);
            const NDRange global(blk_x * ORB_THREADS_X, ORB_THREADS_Y);

            unsigned block_size = 7;
            float k_thr = 0.04f;

            auto hrOp = make_kernel<Buffer, Buffer, Buffer,
                                    Buffer, Buffer, const unsigned,
                                    Buffer, Buffer, KParam,
                                    const unsigned, const float, const unsigned> (hrKernel[device]);

            hrOp(EnqueueArgs(getQueue(), global, local),
                 *d_x_harris, *d_y_harris, *d_score_harris,
                 *d_x_feat.data, *d_y_feat.data, lvl_feat,
                 *d_usable_feat, *lvl_img.data, lvl_img.info,
                 block_size, k_thr, patch_size);
            CL_DEBUG_FINISH(getQueue());

            getQueue().enqueueReadBuffer(*d_usable_feat, CL_TRUE, 0, sizeof(unsigned), &usable_feat);

            bufferFree(d_x_feat.data);
            bufferFree(d_y_feat.data);
            bufferFree(d_usable_feat);

            if (usable_feat == 0) {
                feat_pyr[i] = 0;

                bufferFree(d_x_harris);
                bufferFree(d_y_harris);
                bufferFree(d_score_harris);

                if (i > 0 && i == max_levels-1)
                    bufferFree(lvl_img.data);

                continue;
            }

            // Sort features according to Harris responses
            Param d_harris_sorted;
            Param d_harris_idx;

            d_harris_sorted.info.dims[0] = usable_feat;
            d_harris_idx.info.dims[0] = usable_feat;
            d_harris_sorted.info.strides[0] = 1;
            d_harris_idx.info.strides[0] = 1;

            for (int k = 1; k < 4; k++) {
                d_harris_sorted.info.dims[k] = 1;
                d_harris_idx.info.dims[k] = 1;
                d_harris_sorted.info.strides[k] = d_harris_sorted.info.dims[k - 1] * d_harris_sorted.info.strides[k - 1];
                d_harris_idx.info.strides[k] = d_harris_idx.info.dims[k - 1] * d_harris_idx.info.strides[k - 1];
            }

            d_harris_sorted.info.offset = 0;
            d_harris_idx.info.offset = 0;
            d_harris_sorted.data = d_score_harris;
            d_harris_idx.data = bufferAlloc((d_harris_idx.info.dims[0]) * sizeof(unsigned));

            sort0_index<float, false>(d_harris_sorted, d_harris_idx);

            cl::Buffer* d_x_lvl = bufferAlloc(usable_feat * sizeof(float));
            cl::Buffer* d_y_lvl = bufferAlloc(usable_feat * sizeof(float));
            cl::Buffer* d_score_lvl = bufferAlloc(usable_feat * sizeof(float));

            usable_feat = min(usable_feat, lvl_best[i]);

            // Keep only features with higher Harris responses
            const dim_type keep_blk = divup(usable_feat, ORB_THREADS);
            const NDRange local_keep(ORB_THREADS, 1);
            const NDRange global_keep(keep_blk * ORB_THREADS, 1);

            auto kfOp = make_kernel<Buffer, Buffer, Buffer,
                                    Buffer, Buffer, Buffer, Buffer,
                                    const unsigned> (kfKernel[device]);

            kfOp(EnqueueArgs(getQueue(), global_keep, local_keep),
                 *d_x_lvl, *d_y_lvl, *d_score_lvl,
                 *d_x_harris, *d_y_harris, *d_harris_sorted.data, *d_harris_idx.data,
                 usable_feat);
            CL_DEBUG_FINISH(getQueue());

            bufferFree(d_x_harris);
            bufferFree(d_y_harris);
            bufferFree(d_harris_sorted.data);
            bufferFree(d_harris_idx.data);

            cl::Buffer* d_ori_lvl = bufferAlloc(usable_feat * sizeof(float));
            cl::Buffer* d_size_lvl = bufferAlloc(usable_feat * sizeof(float));

            // Compute orientation of features
            const dim_type centroid_blk_x = divup(usable_feat, ORB_THREADS_X);
            const NDRange local_centroid(ORB_THREADS_X, ORB_THREADS_Y);
            const NDRange global_centroid(centroid_blk_x * ORB_THREADS_X, ORB_THREADS_Y);

            auto caOp = make_kernel<Buffer, Buffer, Buffer,
                                    const unsigned, Buffer, KParam,
                                    const unsigned> (caKernel[device]);

            caOp(EnqueueArgs(getQueue(), global_centroid, local_centroid),
                 *d_x_lvl, *d_y_lvl, *d_ori_lvl,
                 usable_feat, *lvl_img.data, lvl_img.info,
                 patch_size);
            CL_DEBUG_FINISH(getQueue());

            Param lvl_filt;
            Param lvl_tmp;

            if (blur_img) {
                lvl_filt = lvl_img;
                lvl_tmp = lvl_img;

                lvl_filt.data = bufferAlloc(lvl_filt.info.dims[0] * lvl_filt.info.dims[1] * sizeof(T));
                lvl_tmp.data = bufferAlloc(lvl_tmp.info.dims[0] * lvl_tmp.info.dims[1] * sizeof(T));

                // Calculate a separable Gaussian kernel
                if (h_gauss == nullptr) {
                    h_gauss = new T[gauss_len];
                    gaussian1D(h_gauss, gauss_len, 2.f);
                    gauss_filter.info.dims[0] = gauss_len;
                    gauss_filter.info.strides[0] = 1;

                    for (int k = 1; k < 4; k++) {
                        gauss_filter.info.dims[k] = 1;
                        gauss_filter.info.strides[k] = gauss_filter.info.dims[k - 1] * gauss_filter.info.strides[k - 1];
                    }

                    dim_type gauss_elem = gauss_filter.info.strides[3] * gauss_filter.info.dims[3];
                    gauss_filter.data = bufferAlloc(gauss_elem * sizeof(T));
                    getQueue().enqueueWriteBuffer(*gauss_filter.data, CL_TRUE, 0, gauss_elem * sizeof(T), h_gauss);
                }

                // Filter level image with Gaussian kernel to reduce noise sensitivity
                convolve2<T, convAccT, 0, false, gauss_len>(lvl_tmp, lvl_img, gauss_filter);
                convolve2<T, convAccT, 1, false, gauss_len>(lvl_filt, lvl_tmp, gauss_filter);

                bufferFree(lvl_tmp.data);
            }

            // Compute ORB descriptors
            cl::Buffer* d_desc_lvl = bufferAlloc(usable_feat * 8 * sizeof(unsigned));
            unsigned* h_desc_lvl = new unsigned[usable_feat * 8];
            for (int j = 0; j < (int)usable_feat * 8; j++)
                h_desc_lvl[j] = 0;
            getQueue().enqueueWriteBuffer(*d_desc_lvl, CL_TRUE, 0, usable_feat * 8 * sizeof(unsigned), h_desc_lvl);
            delete[] h_desc_lvl;

            auto eoOp = make_kernel<Buffer, const unsigned,
                                    Buffer, Buffer, Buffer, Buffer,
                                    Buffer, KParam,
                                    const float, const unsigned> (eoKernel[device]);

            if (blur_img) {
                eoOp(EnqueueArgs(getQueue(), global_centroid, local_centroid),
                     *d_desc_lvl, usable_feat,
                     *d_x_lvl, *d_y_lvl, *d_ori_lvl, *d_size_lvl,
                     *lvl_filt.data, lvl_filt.info,
                     lvl_scl, patch_size);
                CL_DEBUG_FINISH(getQueue());

                bufferFree(lvl_filt.data);
            }
            else {
                eoOp(EnqueueArgs(getQueue(), global_centroid, local_centroid),
                     *d_desc_lvl, usable_feat,
                     *d_x_lvl, *d_y_lvl, *d_ori_lvl, *d_size_lvl,
                     *lvl_img.data, lvl_img.info,
                     lvl_scl, patch_size);
                CL_DEBUG_FINISH(getQueue());
            }

            // Store results to pyramids
            total_feat += usable_feat;
            feat_pyr[i] = usable_feat;
            d_x_pyr[i] = d_x_lvl;
            d_y_pyr[i] = d_y_lvl;
            d_score_pyr[i] = d_score_lvl;
            d_ori_pyr[i] = d_ori_lvl;
            d_size_pyr[i] = d_size_lvl;
            d_desc_pyr[i] = d_desc_lvl;

            if (i > 0 && i == max_levels-1)
                bufferFree(lvl_img.data);
        }

        if (gauss_filter.data != nullptr)
            bufferFree(gauss_filter.data);
        if (h_gauss != nullptr)
            delete[] h_gauss;

        // If no features are found, set found features to 0 and return
        if (total_feat == 0) {
            *out_feat = 0;
            return;
        }

        // Allocate output memory
        x_out.info.dims[0] = total_feat;
        x_out.info.strides[0] = 1;
        y_out.info.dims[0] = total_feat;
        y_out.info.strides[0] = 1;
        score_out.info.dims[0] = total_feat;
        score_out.info.strides[0] = 1;
        ori_out.info.dims[0] = total_feat;
        ori_out.info.strides[0] = 1;
        size_out.info.dims[0] = total_feat;
        size_out.info.strides[0] = 1;

        desc_out.info.dims[0] = 8;
        desc_out.info.strides[0] = 1;
        desc_out.info.dims[1] = total_feat;
        desc_out.info.strides[1] = desc_out.info.dims[0];

        for (int k = 1; k < 4; k++) {
            x_out.info.dims[k] = 1;
            x_out.info.strides[k] = x_out.info.dims[k - 1] * x_out.info.strides[k - 1];
            y_out.info.dims[k] = 1;
            y_out.info.strides[k] = y_out.info.dims[k - 1] * y_out.info.strides[k - 1];
            score_out.info.dims[k] = 1;
            score_out.info.strides[k] = score_out.info.dims[k - 1] * score_out.info.strides[k - 1];
            ori_out.info.dims[k] = 1;
            ori_out.info.strides[k] = ori_out.info.dims[k - 1] * ori_out.info.strides[k - 1];
            size_out.info.dims[k] = 1;
            size_out.info.strides[k] = size_out.info.dims[k - 1] * size_out.info.strides[k - 1];
            if (k > 1) {
                desc_out.info.dims[k] = 1;
                desc_out.info.strides[k] = desc_out.info.dims[k - 1] * desc_out.info.strides[k - 1];
            }
        }

        if (total_feat > 0) {
            size_t out_sz  = total_feat * sizeof(float);
            x_out.data     = bufferAlloc(out_sz);
            y_out.data     = bufferAlloc(out_sz);
            score_out.data = bufferAlloc(out_sz);
            ori_out.data   = bufferAlloc(out_sz);
            size_out.data  = bufferAlloc(out_sz);

            size_t desc_sz = total_feat * 8 * sizeof(unsigned);
            desc_out.data  = bufferAlloc(desc_sz);
        }

        unsigned offset = 0;
        for (unsigned i = 0; i < max_levels; i++) {
            if (feat_pyr[i] == 0)
                continue;

            if (i > 0)
                offset += feat_pyr[i-1];

            getQueue().enqueueCopyBuffer(*d_x_pyr[i], *x_out.data, 0, offset*sizeof(float), feat_pyr[i] * sizeof(float));
            getQueue().enqueueCopyBuffer(*d_y_pyr[i], *y_out.data, 0, offset*sizeof(float), feat_pyr[i] * sizeof(float));
            getQueue().enqueueCopyBuffer(*d_score_pyr[i], *score_out.data, 0, offset*sizeof(float), feat_pyr[i] * sizeof(float));
            getQueue().enqueueCopyBuffer(*d_ori_pyr[i], *ori_out.data, 0, offset*sizeof(float), feat_pyr[i] * sizeof(float));
            getQueue().enqueueCopyBuffer(*d_size_pyr[i], *size_out.data, 0, offset*sizeof(float), feat_pyr[i] * sizeof(float));

            getQueue().enqueueCopyBuffer(*d_desc_pyr[i], *desc_out.data, 0, offset*8*sizeof(unsigned), feat_pyr[i] * 8 * sizeof(unsigned));

            bufferFree(d_x_pyr[i]);
            bufferFree(d_y_pyr[i]);
            bufferFree(d_score_pyr[i]);
            bufferFree(d_ori_pyr[i]);
            bufferFree(d_size_pyr[i]);
            bufferFree(d_desc_pyr[i]);
        }

        // Sets number of output features
        *out_feat = total_feat;
    } catch (cl::Error err) {
        CL_TO_AF_ERROR(err);
        throw;
    }
}
コード例 #30
0
ファイル: morph.hpp プロジェクト: shehzan10/arrayfire
void morph(Param         out,
        const Param      in,
        const Param      mask)
{
    try {
        static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
        static std::map<int, Program*> morProgs;
        static std::map<int, Kernel*> morKernels;

        int device = getActiveDeviceId();

        std::call_once( compileFlags[device], [device] () {
                ToNumStr<T> toNumStr;
                T init = isDilation ? Binary<T, af_max_t>().init() : Binary<T, af_min_t>().init();
                std::ostringstream options;
                options << " -D T=" << dtype_traits<T>::getName()
                        << " -D isDilation="<< isDilation
                        << " -D init=" << toNumStr(init)
                        << " -D windLen=" << windLen;
                if (std::is_same<T, double>::value ||
                    std::is_same<T, cdouble>::value) {
                    options << " -D USE_DOUBLE";
                }
                Program prog;
                buildProgram(prog, morph_cl, morph_cl_len, options.str());
                morProgs[device]   = new Program(prog);
                morKernels[device] = new Kernel(*morProgs[device], "morph");
            });

        auto morphOp = KernelFunctor<Buffer, KParam,
                                   Buffer, KParam,
                                   Buffer, cl::LocalSpaceArg,
                                   int, int
                                  >(*morKernels[device]);

        NDRange local(THREADS_X, THREADS_Y);

        int blk_x = divup(in.info.dims[0], THREADS_X);
        int blk_y = divup(in.info.dims[1], THREADS_Y);
        // launch batch * blk_x blocks along x dimension
        NDRange global(blk_x * THREADS_X * in.info.dims[2],
                       blk_y * THREADS_Y * in.info.dims[3]);

        // copy mask/filter to constant memory
        cl_int se_size   = sizeof(T)*windLen*windLen;
        cl::Buffer *mBuff = bufferAlloc(se_size);
        getQueue().enqueueCopyBuffer(*mask.data, *mBuff, 0, 0, se_size);

        // calculate shared memory size
        const int halo    = windLen/2;
        const int padding = 2*halo;
        const int locLen  = THREADS_X + padding + 1;
        const int locSize = locLen * (THREADS_Y+padding);

        morphOp(EnqueueArgs(getQueue(), global, local),
                *out.data, out.info, *in.data, in.info, *mBuff,
                cl::Local(locSize*sizeof(T)), blk_x, blk_y);

        bufferFree(mBuff);

        CL_DEBUG_FINISH(getQueue());
    } catch (cl::Error err) {
        CL_TO_AF_ERROR(err);
        throw;
    }
}