API Documentation

C++ Documentation

namespace Spyker

Typedefs

using I8 = int8_t

8-bit signed integer data type.

using I16 = int16_t

16-bit signed integer data type.

using I32 = int32_t

32-bit signed integer data type.

using I64 = int64_t

64-bit signed integer data type.

using U8 = uint8_t

8-bit unsigned integer data type.

using U16 = uint16_t

16-bit unsigned integer data type.

using U32 = uint32_t

32-bit unsigned integer data type.

using U64 = uint64_t

64-bit unsigned integer data type.

using F16 = half_float::half

half percision floating point data type

using F32 = float

single percision floating point data type.

using F64 = double

double percision floating point data type.

using Size = int64_t

Size type of the library.

using Shape = std::vector<Size>

Shape container of the library.

using Winners = std::vector<std::vector<Winner>>

List of list of ‘Winner’s.

Enums

enum class Type : I32

Data type enumeration of the library.

Values:

enumerator I8

8-bit signed integer.

enumerator I16

16-bit signed integer.

enumerator I32

32-bit signed integer.

enumerator I64

64-bit signed integer.

enumerator U8

8-bit unsigned integer.

enumerator U16

16-bit unsigned integer.

enumerator U32

32-bit unsigned integer.

enumerator U64

64-bit unsigned integer.

enumerator F16

half percision floating point.

enumerator F32

single percision floating point.

enumerator F64

double percision floating point.

enum class Code : I32

Values:

enumerator Rank

Rank coding.

enumerator Rate

Rate coding.

enum class Kind : I32

Kind of the device.

Values:

enumerator CPU

CPU device.

enumerator CUDA

CUDA GPU device.

Functions

template<typename T>
Type TypeName()

Get the name of the templated data type.

Size TypeSize(Type type)

Get the size of the type in bytes.

std::ostream &operator<<(std::ostream &os, Type type)
std::ostream &operator<<(std::ostream &os, Kind kind)
std::ostream &operator<<(std::ostream &os, Device device)
std::ostream &operator<<(std::ostream &os, Shape shape)
std::ostream &operator<<(std::ostream &os, Tensor tensor)
std::ostream &operator<<(std::ostream &os, Scalar scalar)
void randomSeed(Size seed)

Set the seed of the random generator of the library.

Parameters:

seed – random seed value.

bool cudaAvailable()

Check if CUDA is available.

Size cudaDeviceCount()

Get number of available CUDA devices.

void cudaSetDevice(Size index)

Set the current CUDA device.

Size cudaCurrentDevice()

Get the current CUDA device.

std::vector<Size> cudaArchList()

Get supported CUDA architectures.

std::vector<Size> cudaDeviceArch()

Get current CUDA architectures.

Size cudaMemoryTotal()

Get CUDA memory capacity for current device.

Size cudaMemoryFree()

Get CUDA free memory for current device.

Size cudaMemoryTaken(Size device = -1)

Get CUDA cached memory for current device.

Size cudaMemoryUsed(Size device = -1)

Get CUDA used memory for current device.

bool cudaCacheEnabled(Size device = -1)

Check if CUDA cache is enabled.

void cudaCacheEnable(bool enable, Size device = -1)

Enable/Disable CUDA memory caching.

void cudaCacheClear(Size device = -1)

Clear CUDA memory cache.

void clearContext()

Clear all reserved data.

void cudaCachePrint(Size device = -1)

Print a list of allocated pointers in CUDA memory cache.

void cudaConvLight(bool light)

Set light convolution mode.

When CUDNN is enabled and light convolution is active, newely created convolution descriptors (not cached ones) use algorithms that take up less memory. Enabling this might decrease performance in some cases. This is disabled by default.

Parameters:

light – light convolution mode.

void cudaConvHeuristic(bool heuristic)

Set heuristic convolution algorithm finding mode.

When CUDNN is enabled and heuristic algorithm finding is active, newely created convolution descriptors (not cached ones) will use heuristics to find the fastest convolution algorithms instead of running samples. Enabling this might decrease performance in some cases. This is enabled by default.

Parameters:

heuristic – heuristic convolution mode.

void cudaConvForce(bool force)

Set heuristic convolution algorithm finding mode.

When CUDNN is enabled and force mode is active, the algorithm will try to force the usage of tensor cores.

Parameters:

force – force tensor cores.

std::vector<Device> allDevices()

Get a list of all the available devices that the library can use.

Returns:

a list of available devices.

Size maxThreads()

Get the maximum number of threads used

Returns:

maximum number of threads used

void setMaxThreads(Size threads = -1)

Set the maximum number of threads

Parameters:

threads – maximum number of threads used

Tensor canny(Tensor input, Scalar low, Scalar high)

Apply Canny edge detection.

Parameters:
  • input[in] edge detection input dense tensor.

  • low – threshold for weak edges.

  • high – threshold for strong edges.

Returns:

edge detection output dense tensor.

Tensor canny(Tensor input, Tensor output, Scalar low, Scalar high)

Apply Canny edge detection.

Parameters:
  • input[in] edge detection input dense tensor.

  • output[out] edge detection output dense tensor.

  • low – threshold for weak edges.

  • high – threshold for strong edges.

Returns:

the output tensor.

Tensor conv(Tensor input, Tensor kernel, Expand2 stride = 1, Expand4 pad = 0)

Apply 2D convolution.

Parameters:
  • input[in] convolution input dense tensor.

  • kernel[in] convolution kernel dense tensor.

  • stride – convolution stride (default 1).

  • pad – input padding (default 0).

Returns:

convolution output dense tensor.

Tensor conv(Tensor input, Tensor kernel, Tensor output, Expand2 stride = 1, Expand4 pad = 0)

Apply 2D convolution.

Parameters:
  • input[in] convolution input dense tensor.

  • kernel[in] convolution kernel dense tensor.

  • output[out] convolution output dense tensor.

  • stride – convolution stride (default 1).

  • pad – input padding (default 0).

Returns:

the output tensor.

Tensor fc(Tensor input, Tensor kernel, bool sign = false)

Apply fully connected.

Parameters:
  • input[in] fully connected input dense tensor.

  • kernel[in] fully connected kernel dense tensor.

  • sign[in] convert the kernel to sign before performing the operation.

Returns:

fully connected output dense tensor.

Tensor fc(Tensor input, Tensor kernel, Tensor output, bool sign = false)

Apply fully connected.

Parameters:
  • input[in] fully connected input dense tensor.

  • kernel[in] fully connected kernel dense tensor.

  • output[out] fully connected output dense tensor.

  • sign[in] convert the kernel to sign before performing the operation.

Returns:

the output tensor.

Tensor pad(Tensor input, Expand4 pad, Scalar value = 0)

Apply 2D padding.

Parameters:
  • input[in] input dense tensor.

  • pad – input padding (1D->S, 2D->VH, 4D->TLBR).

  • value – padding value (default 0).

Returns:

padding output dense tensor.

Tensor pad(Tensor input, Tensor output, Expand4 pad, Scalar value = 0)

2D padding.

Parameters:
  • input[in] input dense tensor.

  • output[out] output dense tensor.

  • pad – input padding (1D->S, 2D->VH, 4D->TLBR).

  • value – padding value (default 0).

Returns:

the output tensor.

Tensor threshold(Tensor input, Scalar threshold, Scalar value = 0, bool inplace = true)

Apply thresholding.

Parameters:
  • input[inout] input dense tensor.

  • threshold – the threshold value.

  • value – value to replace (default 0).

  • inplace – override the input or not (default true).

Returns:

if inplace input tensor, otherwise output tensor.

Tensor quantize(Tensor input, Scalar lower, Scalar middle, Scalar upper, bool inplace = true)

Quantize input.

If values are lower than middle then it is set to lower and set to upper otherwise.

Parameters:
  • input[inout] input dense tensor to be quantized.

  • lower – lower bound value.

  • middle – middle value to be compared.

  • upper – upper bound value.

  • inplace – override the input or not (default true).

Returns:

if inplace input tensor, otherwise output tensor.

Tensor code(Tensor input, Size time, bool sort = true, Type type = Type::U8, Code code = Code::Rank)

Apply rank coding.

Parameters:
  • input[in] input dense tensor.

  • time – number of time steps.

  • sort – whether to sort the values or not. Sorting might increase accuracy but it deceases performance (default true).

  • type – data type of the created output tensor (default Type::U8).

  • code – neural coding type (default Code::Rank).

Returns:

rank coding output dense tensor.

Tensor code(Tensor input, Tensor output, Size time, bool sort = true, Code code = Code::Rank)

Apply rank coding.

Parameters:
  • input[in] input dense tensor.

  • output[out] output dense tensor.

  • time – number of time steps.

  • sort – whether to sort the values or not. Sorting might increase accuracy but it deceases performance (default true).

  • code – neural coding type (default Code::Rank).

Returns:

the output tensor.

Tensor infinite(Tensor input, Scalar value = 0, bool inplace = true)

Apply infinite thresholding.

Parameters:
  • input[inout] input dense tensor.

  • value – value to replace (default 0).

  • inplace – override the input or not (default true).

Returns:

if inplace input tensor, otherwise output tensor.

Tensor fire(Tensor input, Scalar threshold = 0, Type type = Type::U8, Code code = Code::Rank)

Apply integrate-and-fire mechanism.

If the input is already thresholded then there is no need to pass threshold to this function.

Parameters:
  • input[in] input dense tensor.

  • threshold – threshold of firing (default 0).

  • type – data type of the created output tensor (default Type::U8).

  • code – neural coding type (default Code::Rank).

Returns:

integrate-and-fire output dense tensor.

Tensor fire(Tensor input, Tensor output, Scalar threshold = 0, Code code = Code::Rank)

Apply integrate-and-fire mechanism.

If the input is already thresholded then there is no need to pass threshold to this function.

Parameters:
  • input[in] input dense tensor.

  • output[out] output dense tensor.

  • threshold – threshold of firing (default 0).

  • code – neural coding type (default Code::Rank).

Returns:

the output tensor.

Tensor gather(Tensor input, Scalar threshold = 0, Type type = Type::U8, Code code = Code::Rank)

Gather temporal information.

If the input is already thresholded then there is no need to pass threshold to this function.

Parameters:
  • input[in] input dense tensor.

  • threshold – threshold of integrate-and-fire layer (default 0).

  • type – data type of the created output tensor (default Type::U8).

  • code – neural coding type (default Code::Rank).

Returns:

gathered output dense tensor.

Tensor gather(Tensor input, Tensor output, Scalar threshold = 0, Code code = Code::Rank)

Gather temporal information.

If the input is already thresholded then there is no need to pass threshold to this function.

Parameters:
  • input[in] input dense tensor.

  • output[out] output dense tensor.

  • threshold – threshold of integrate-and-fire layer (default 0).

  • code – neural coding type (default Code::Rank).

Returns:

the output tensor.

Tensor scatter(Tensor input, Size time, Type type = Type::U8)

Scatter gathered temporal information.

Parameters:
  • input[in] input dense tensor.

  • time – number of time steps of the output.

  • type – data type of the created output tensor (default Type::U8).

Returns:

scattered output tensor.

Tensor scatter(Tensor input, Tensor output)

Scatter gathered temporal information.

Parameters:
  • input[in] input dense tensor.

  • output[out] output dense tensor.

Returns:

the output tensor.

Tensor pool(Tensor input, Expand2 kernel, Expand2 stride = 0, Expand4 pad = 0, Tensor rates = {})

Apply 2D pooling.

Parameters:
  • input[in] pooling input dense tensor.

  • kernel[in] pooling kernel dense tensor.

  • stride – convolution stride. Zero stride means same as kernel (default 0).

  • pad – input padding (default 0).

  • rates – firing rates of the input tensor, if empty, rank coding will be used.

Returns:

pooling output dense tensor.

Tensor pool(Tensor input, Tensor output, Expand2 kernel, Expand2 stride = 0, Expand4 pad = 0, Tensor rates = {})

Apply 2D pooling.

Parameters:
  • input[in] pooling input dense tensor.

  • output[out] pooling output dense tensor.

  • kernel – pooling kernel size.

  • stride – convolution stride. Zero stride means same as kernel (default 0).

  • pad – input padding (default 0).

  • rates – firing rates of the input tensor, if empty, rank coding will be used.

Returns:

the output tensor.

Tensor inhibit(Tensor input, Scalar threshold = 0, bool inplace = true)

Apply lateral Inhibition (inplace).

If the input is already thresholded then there is no need to pass threshold to this function.

Parameters:
  • input[inout] input dense tensor.

  • threshold – threshold of integrate-and-fire layer (default 0).

  • inplace – override the input or not (default true).

Returns:

if inplace input tensor, otherwise output tensor.

Winners fcwta(Tensor input, Size radius, Size count, Scalar threshold = 0)

Select winner neurons from fully connected output.

If the input is already thresholded then there is no need to pass threshold to this function.

Parameters:
  • input[in] input dense tensor.

  • radius – radius of inhibition.

  • threshold – threshold of integrate-and-fire layer (default 0).

  • count – number of neurons that will be selected.

Returns:

winner neurons.

Winners convwta(Tensor input, Expand2 radius, Size count, Scalar threshold = 0)

Select winner neurons from convolution output.

If the input is already thresholded then there is no need to pass threshold to this function.

Parameters:
  • input[in] input dense tensor.

  • radius – radius of inhibition.

  • count – number of neurons that will be selected.

  • threshold – threshold of integrate-and-fire layer (default 0).

Returns:

winner neurons.

Tensor backward(Tensor input, Tensor target, Size time, Scalar gamma)
Tensor backward(Tensor input, Tensor output, Tensor target, Size time, Scalar gamma)
Tensor labelize(Tensor input, Scalar threshold)
Tensor labelize(Tensor input, Tensor output, Scalar threshold)
class Device
#include <utils.h>

Device to use for allocations and computations.

Public Functions

Device(Kind kind = Kind::CPU, I32 index = -1)
Parameters:
  • kind – kind of the device.

  • index – index of the device.

inline Kind kind() const

Get the kind of the device.

inline I32 index() const

Get the index of the device.

bool operator==(Kind kind) const

Equality operator of the device.

Parameters:

kind – kind of the device to be compared to.

bool operator!=(Kind kind) const

Non-equality operator of the device.

Parameters:

kind – kind of the device to be compared to.

bool operator==(Device other) const

Equality operator of the device.

Parameters:

other – device to be compared to.

bool operator!=(Device other) const

Non-equality operator of the device.

Parameters:

other – device to be compared to.

class Tensor
#include <utils.h>

N-dimensional container of the data buffers on different devices.

Public Types

using Deleter = std::function<void(void*)>

Data buffer deleter function.

Public Functions

Tensor()

Initialize empty tensor.

Tensor(Type type, const Shape &shape, bool pinned = false, bool unified = false)
Parameters:
  • type – type of the tensor.

  • shape – shape of the tensor.

  • pinned – whether the tensor is pinned (CUDA pinned memory) or not.

  • unified – whether the tensor is unified (CUDA unified memory) or not.

Tensor(Shared data, Type type, const Shape &shape, bool pinned = false, bool unified = false)
Parameters:
  • data – user raw data to be held.

  • type – type of the tensor.

  • shape – shape of the tensor.

  • pinned – whether the tensor is pinned (CUDA pinned memory) or not.

  • unified – whether the tensor is unified (CUDA unified memory) or not.

Tensor(Device device, Type type, const Shape &shape, bool pinned = false, bool unified = false)
Parameters:
  • device – device of the tensor.

  • type – type of the tensor.

  • shape – shape of the tensor.

  • pinned – whether the tensor is pinned (CUDA pinned memory) or not.

  • unified – whether the tensor is unified (CUDA unified memory) or not.

Tensor(Shared data, Device device, Type type, const Shape &shape, bool pinned = false, bool unified = false)
Parameters:
  • data – user raw data to be held.

  • device – device of the tensor.

  • type – type of the tensor.

  • shape – shape of the tensor.

  • pinned – whether the tensor is pinned (CUDA pinned memory) or not.

  • unified – whether the tensor is unified (CUDA unified memory) or not.

bool pinned() const

Check whether the tensor is pinned (CUDA pinned memory).

bool unified() const

Check whether the tensor is unified (CUDA unified memory).

operator bool() const

Check whether the tensor is valid (not empty).

void *data() const

Get the raw data pointer.

Size dims() const

Get the number of dimensions.

Size numel() const

Get the number of elements in tensor.

Size bytes() const

Get the sie of data buffer in bytes.

Shape shape() const

Get the shape of the tensor.

Size shape(Size index) const

Get the shape element in index.

Parameters:

index – index of the element to be returned.

Type type() const

Get the data type of the tensor.

Device device() const

Get the device of the tensor.

Tensor copy() const

Get a deep copy of the tensor.

Tensor to(Type type) const

Return a copy of the tensor with converted data type.

Tensor to(Device device) const

Return a copy of the tensor with converted device.

void to(Tensor other) const

Copy the tensor into the other.

Parameters:

other – tensor to be copied into.

void from(Tensor tensor) const

Copy the other tensor into this.

Parameters:

tensor – tensor to copy from.

Tensor reshape(Shape shape) const

Reshape the tensor.

Parameters:

shape – new shape of the tensor.

Tensor &fill(Scalar value)

Fill the tensor with value.

Parameters:

value – value to fill the tensor with.

Tensor operator[](Size index) const

Get subtensor.

template<typename T>
inline T *data() const

Get the templated data pointer.

inline Tensor i8() const

Return a copy of this tensor with data type converted to 8-bit signed integer.

inline Tensor i16() const

Return a copy of this tensor with data type converted to 16-bit signed integer.

inline Tensor i32() const

Return a copy of this tensor with data type converted to 32-bit signed integer.

inline Tensor i64() const

Return a copy of this tensor with data type converted to 64-bit signed integer.

inline Tensor u8() const

Return a copy of this tensor with data type converted to 8-bit unsigned integer.

inline Tensor u16() const

Return a copy of this tensor with data type converted to 16-bit unsigned integer.

inline Tensor u32() const

Return a copy of this tensor with data type converted to 32-bit unsigned integer.

inline Tensor u64() const

Return a copy of this tensor with data type converted to 64-bit unsigned integer.

inline Tensor f16() const

Return a copy of this tensor with data type converted to half percision floating point.

inline Tensor f32() const

Return a copy of this tensor with data type converted to single percision floating point.

inline Tensor f64() const

Return a copy of this tensor with data type converted to double percision floating point.

inline Tensor cpu() const

Return a copy of this tensor with device converted to CPU.

inline Tensor cuda() const

Return a copy of this tensor with device converted to CUDA.

class SparseTensor
#include <utils.h>

5-dimentional container of sparse binary spikes on the CPU

Public Functions

SparseTensor()

Initialize empty tensor.

SparseTensor(Shape shape)
Parameters:

shape – shape of the tensor

explicit SparseTensor(Tensor tensor, F64 threshold = 0)

Initialize from a dense tensor

Parameters:
  • tensor – dense tensor

  • threshold – the threshold used to turn dense tensor into spikes

operator bool() const

Check whether the tensor is valid (not empty).

Size dims() const

Get the number of dimensions.

Size numel() const

Get the number of elements in tensor.

void *data() const

Get the raw data pointer. This points to a internal data structure and should not be used.

Shape shape() const

Get the shape of the tensor.

Size shape(Size index) const

Get the shape element in index.

Parameters:

index – index of the element to be returned.

Size bytes() const

Get the sie of data buffer in bytes.

F64 sparsity() const

Get the ratio of non-zero elements in the range of zero to one.

SparseTensor copy() const

Get a deep copy of the tensor.

Tensor dense() const

Convert the sparse tensor into a dense tensor.

class Scalar
#include <utils.h>

Non-templated basic data type container.

Public Functions

inline Scalar()

Initialize empty scalar.

inline Type type() const

Get the data type of the scalar.

inline operator bool() const

Check if the scalar is valid (not empty).

template<typename T>
inline Scalar(T value)
Parameters:

value – value to be assigned to the scalar.

template<typename T>
inline Scalar &operator=(T value)

Assign a new value to the scalar.

template<typename T>
inline T value() const

Return the templated data type.

template<typename T>
inline operator T() const

Cast operator to basic types.

Scalar to(Type type) const

Get a copy of the scalar with the requested data type.

struct Winner
#include <utils.h>

Winner neuron representation.

Public Members

Size c

Index of the STDP configuration.

Size t

Index in time (used in sparse).

Size z

Index in signal channel.

Size y

Index in signal height.

Size x

Index in signal width.

struct STDPConfig
#include <utils.h>

STDP configuration parameters container.

Public Members

F64 positive

Positive learning rate.

F64 negative

Negative learning rate.

bool stabilize

Stabilization.

F64 lower

Lower bound of the weights.

F64 upper

Upper bound of the weights.

struct BPConfig
#include <utils.h>

Backpropagation configuration parameters container.

Public Members

F32 sfactor

Scaling factor.

F32 lrate

Learning rate.

F32 lrf

Learning rate of scaling factor.

F32 lambda

Weight regularization term.

class Expand2
#include <opers.h>

2D shape container.

This class broadcasts shapes to 2D.

class Expand4
#include <opers.h>

4D shape container.

This class broadcasts shapes to 4D.

struct DoGFilter
#include <opers.h>

Difference of Gaussian filter parameter container.

Public Functions

inline DoGFilter(F64 std1, F64 std2)

Initialize Filter with parameters.

Public Members

F64 std1

Standard deviation of the first gaussian filter.

F64 std2

Standard deviation of the second gaussian filter.

struct GaborFilter
#include <opers.h>

Gabor filter parameter container.

Public Members

F64 sigma

Standard deviation

Width of the strips of the filter.

F64 theta

Orientation

Orientation of the filter (unit degrees).

F64 gamma

Spatial aspect ratio

Height of the stripes, reverse relation.

F64 lambda

Wavelength

Spacing between strips, reverse relation.

F64 psi

Phase offset

Spacial shift of the strips.

class DoG
#include <opers.h>

2D difference of Gaussian (DoG) filter module.

Public Functions

DoG()

Filter can’t be used when initialized this way.

DoG(Size size, const std::vector<DoGFilter> &filters, Expand4 pad = 0, Type type = Type::F32)
Parameters:
  • size – half size of the window. full size of the window is 2 * size + 1.

  • filters – list of ‘DoGFilter’s to be applied.

  • pad – padding size of the input (default 0).

  • type – data type for the kernel and thus the convolution operation, floating point types are allowed.

DoG(Device device, Size size, const std::vector<DoGFilter> &filters, Expand4 pad = 0, Type type = Type::F32)
Parameters:
  • device – device of the filter to be run on.

  • size – half size of the window. full size of the window is 2 * size + 1.

  • filters – list of ‘DoGFilter’s to be applied.

  • pad – padding size of the input (default 0).

  • type – data type for the kernel and thus the convolution operation, floating point types are allowed.

Tensor operator()(Tensor input, Tensor output)

Apply the filter on the input.

Parameters:
  • input[in] input dense tensor to be processed.

  • output[out] dense tensor to be written to.

Tensor operator()(Tensor input)

Apply the filter on the input.

Parameters:

input[in] input dense tensor to be processed.

Returns:

filtered output dense tensor.

Device device() const

Get the device of this module.

Public Members

Tensor kernel

Kernel of the filter.

class Gabor
#include <opers.h>

2D Gabor filter module.

Public Functions

Gabor()

Filter can’t be used when initialized this way.

Gabor(Size size, const std::vector<GaborFilter> &filters, Expand4 pad = 0, Type type = Type::F32)
Parameters:
  • size – half size of the window. full size of the window is 2 * size + 1.

  • filters – list of ‘GaborFilter’s to be applied.

  • pad – padding size of the input (TBLR) (default 0).

  • type – data type for the kernel and thus the convolution operation, floating point types are allowed.

Gabor(Device device, Size size, const std::vector<GaborFilter> &filters, Expand4 pad = 0, Type type = Type::F32)
Parameters:
  • device – device of the filter to be run on.

  • size – half size of the window. full size of the window is 2 * size + 1.

  • filters – list of ‘GaborFilter’s to be applied.

  • pad – padding size of the input (TBLR) (default 0).

  • type – data type for the kernel and thus the convolution operation, floating point types are allowed.

Tensor operator()(Tensor input, Tensor output)

Apply the filter on the input.

Parameters:
  • input[in] input dense tensor to be processed.

  • output[out] dense tensor to be written to.

Tensor operator()(Tensor input)

Apply the filter on the input.

Parameters:

input[in] input dense tensor to be processed.

Returns:

filtered output dense tensor.

Device device() const

Get the device of this module.

Public Members

Tensor kernel

Kernel of the filter.

class LoG
#include <opers.h>

2D Laplacian of Gaussian (LoG) filter module.

Public Functions

LoG()

Filter can’t be used when initialized this way.

LoG(Size size, const std::vector<F64> &stds, Expand4 pad = 0, Type type = Type::F32)
Parameters:
  • size – half size of the window. full size of the window is 2 * size + 1.

  • stds – list of stds for the LoG filters to be applied.

  • pad – padding size of the input (TBLR) (default 0).

  • type – data type for the kernel and thus the convolution operation, floating point types are allowed.

LoG(Device device, Size size, const std::vector<F64> &stds, Expand4 pad = 0, Type type = Type::F32)
Parameters:
  • device – device of the filter to be run on.

  • size – half size of the window. full size of the window is 2 * size + 1.

  • stds – list of stds for the LoG filters to be applied.

  • pad – padding size of the input (TBLR) (default 0).

  • type – data type for the kernel and thus the convolution operation, floating point types are allowed.

Tensor operator()(Tensor input, Tensor output)

Apply the filter on the input.

Parameters:
  • input[in] input dense tensor to be processed.

  • output[out] dense tensor to be written to.

Tensor operator()(Tensor input)

Apply the filter on the input.

Parameters:

input[in] input dense tensor to be processed.

Returns:

filtered output dense tensor.

Device device() const

Get the device of this module.

Public Members

Tensor kernel

Kernel of the filter.

class ZCA
#include <opers.h>

ZCA whitening transformation module.

Public Functions

ZCA()

Empty initialization.

ZCA &fit(Tensor input, Scalar epsilon, bool transform = false)

Fit the input data

Parameters:
  • input[inout] input data to be fitted to.

  • epsilon – epsilon parameter of the trnasformation.

  • transform – whether to transform the input inplace or not (default false).

Returns:

reference to this class

Tensor operator()(Tensor input, bool inplace = true)

Transform the input data

Parameters:
  • input[inout] input data to be transformed.

  • inplace – whether to transform the input inplace or not (default true).

Returns:

transformed data

Public Members

Tensor mean

Mean values of features.

Tensor transform

Whitening transformation matrix.

Public Static Functions

static Tensor split(Tensor input, Tensor output)

Split ZCA transformed data into two positive and negative channels.

Parameters:
  • input[in] input data to be splitted.

  • output[out] output tensor.

Returns:

the output tensor.

static Tensor split(Tensor input)

Split ZCA transformed data into two positive and negative channels.

Parameters:

input[in] input data to be splitted.

Returns:

splitted data.

class Conv
#include <opers.h>

2D convolution module.

Public Functions

Conv()

Module can’t be used when initialized this way.

Conv(Size input, Size output, Expand2 kernel, Expand2 stride = 1, Expand4 pad = 0, F64 mean = .5, F64 std = .02, Type type = Type::F32)
Parameters:
  • input – channels of the input signal.

  • output – channels of the output signal.

  • kernel – kernel size of the convolution.

  • stride – stride size of the convolution (default 1).

  • pad – padding size of the convolution (default 0).

  • mean – mean of the random normal variable that initializes the kernel (default 0.5).

  • std – standard deviation of the random normal variable that initializes the kernel (default 0.02).

  • type – data type for the kernel and thus the convolution operation, floating point types are allowed.

Conv(Device device, Size input, Size output, Expand2 kernel, Expand2 stride = 1, Expand4 pad = 0, F64 mean = .5, F64 std = .02, Type type = Type::F32)
Parameters:
  • device – device of the module to be run on.

  • input – channels of the input signal.

  • output – channels of the output signal.

  • kernel – kernel size of the convolution.

  • stride – size of the convolution (default 1).

  • pad – padding size of the convolution (default 0).

  • mean – mean of the random normal variable that initializes the kernel (default 0.5).

  • std – standard deviation of the random normal variable that initializes the kernel (default 0.02).

  • type – data type for the kernel and thus the convolution operation, floating point types are allowed.

Tensor operator()(Tensor input, Tensor output)

Apply the convolution on the input.

Parameters:
  • input[in] input dense tensor to be processed.

  • output[out] dense tensor to be written to.

Tensor operator()(Tensor input)

Apply the convolution on the input.

Parameters:

input[in] input dense tensor to be processed.

Returns:

convolved output dense tensor.

SparseTensor operator()(SparseTensor input, Scalar threshold)

Apply 2D Convolution

Parameters:
  • input – input sparse tensor to be convolved.

  • threshold – threshold to be applied to potentials.

Returns:

convolution and intergreate-and-fire output spikes.

void stdp(Tensor input, const Winners &winners, Tensor output)

Apply the STDP on the convolution.

Parameters:
  • input[in] convolution input dense tensor.

  • winners – winner neurons that are selected for updating.

  • output[in] convolution output dense tensor.

void stdp(SparseTensor input, const Winners &winners)

Apply the STDP on the convolution.

Parameters:
  • input – convolution input sparse tensor.

  • winners – winner neurons that are selected for updating.

Device device() const

Get the device of this module.

Public Members

Tensor kernel

Kernel of the module.

std::vector<STDPConfig> stdpconfig

List of STDP configurations.

class FC
#include <opers.h>

Fully connected module.

Public Functions

FC()

Module can’t be used when initialized this way.

FC(Size input, Size output, F64 mean = .5, F64 std = .02, Type type = Type::F32)
Parameters:
  • input – dimensions of the input signal.

  • output – dimensions of the output signal.

  • mean – mean of the random normal variable that initializes the kernel (default 0.5).

  • std – standard deviation of the random normal variable that initializes the kernel (default 0.02).

  • type – data type for the kernel and thus the fc operation, floating point types are allowed.

FC(Device device, Size input, Size output, F64 mean = .5, F64 std = .02, Type type = Type::F32)
Parameters:
  • device – device of the module to be run on.

  • input – dimensions of the input signal.

  • output – dimensions of the output signal.

  • mean – mean of the random normal variable that initializes the kernel (default 0.5).

  • std – standard deviation of the random normal variable that initializes the kernel (default 0.02).

  • type – data type for the kernel and thus the fc operation, floating point types are allowed.

Tensor operator()(Tensor input, Tensor output, bool sign = false)

Apply the fully connected on the input.

Parameters:
  • input[in] input dense tensor to be processed.

  • output[out] dense tensor to be written to.

  • sign[in] convert the kernel to sign before performing the operation.

Tensor operator()(Tensor input, bool sign = false)

Apply the fully connected on the input.

Parameters:
  • input[in] input dense tensor to be processed.

  • sign[in] convert the kernel to sign before performing the operation.

Returns:

fully connected output dense tensor.

Tensor backward(Tensor input, Tensor output, Tensor grad)

Backpropagate and return the gradient.

Tensor backward(Tensor input, Tensor output, Tensor grad, Tensor next)

Backpropagate and return the gradient.

void stdp(Tensor input, const Winners &winners, Tensor output)

Apply the STDP on the fully connected.

Parameters:
  • input[in] fully connected input dense tensor.

  • winners – winner neurons that are selected for updating.

  • output[in] fully connected output dense tensor.

Device device() const

Get the device of this module.

Public Members

Tensor kernel

Kernel of the module.

std::vector<STDPConfig> stdpconfig

List of STDP configurations.

BPConfig bpconfig

Backpropagation configutation.

namespace Helper

Functions

Tensor readImage(const std::string &path, std::string mode = "", Shape size = {-1, -1})

Read Image from file.

Parameters:
  • path – path of the file that will be read.

  • mode – channel mode of reading. values can be ‘Y’, ‘YA’, ‘RGB’, ‘RGBA’ or empty string for the original channels (default empty).

  • size – width and height of the output image to be scaled. pass {-1, -1} for original size (default {-1, -1}).

Returns:

image read as a tensor. failure to read returns empty tensor.

bool readImage(Tensor output, const std::string &path, std::string mode = "", Shape size = {-1, -1})

Read Image from file.

Parameters:
  • output[out] tensor that will be written to.

  • path – path of the file that will be read.

  • mode – channel mode of reading. values are ‘Y’, ‘YA’, ‘RGB’, ‘RGBA’ or empty string for the original channels (default empty).

  • size – width and height of the output image to be scaled. pass {-1, -1} for original size (default {-1, -1}).

Returns:

success or failure to read.

bool writeImage(Tensor input, const std::string &path, std::string format = "PNG")

Write image to file.

Parameters:
  • input – input tensor that will be written to file.

  • path – path of the file that will be written.

  • format – format of the image file. values can be ‘PNG’, ‘BMP’, ‘TGA’, ‘JPG’.

Returns:

success or failure to write.

Tensor mnistLabel(const std::string &path)

Read MNIST binary label file.

Parameters:

path – path of the file to be read.

Returns:

labels read as a tensor. failure to read returns empty tensor.

Tensor mnistData(const std::string &path)

Read MNIST binary image file.

Parameters:

path – path of the file to be read.

Returns:

images read as a tensor. failure to read returns empty tensor.

class CSV
#include <csv.h>

CSV file reader.

Public Functions

CSV(const std::string &path, const std::string &delim = ", ")
Parameters:
  • path – path of the CSV file to be read.

  • delim – delimiter of the CSV file that separates values.

bool readline(std::vector<std::string> &row)

Read next line from the CSV file.

If the line is empty, it is skipped until a non-empty line is read.

Parameters:

row[out] vector of strings that will be filled with values from the line.

Returns:

success or failure to read. False value indicates end of the file or read error.

Size skip(Size lines)

Skip the specified number of lines.

Parameters:

lines – number of lines to be skipped.

namespace Sparse

Functions

SparseTensor conv(SparseTensor input, Tensor kernel, Scalar threshold, Expand2 stride = 1, Expand4 pad = 0)

Apply 2D Convolution

Parameters:
  • input – input sparse tensor to be convolved.

  • kernel – convolution kernel dense tensor.

  • threshold – threshold to be applied to potentials.

  • stride – convolution stride (default 1).

  • pad – input padding (default 0).

Returns:

convolution and intergreate-and-fire output sparse spikes.

SparseTensor pad(SparseTensor input, Expand4 pad)

Apply 2D padding.

Parameters:
  • input – input sparse tensor.

  • pad – input padding (1D->S, 2D->VH, 4D->TLBR).

Returns:

padding output sparse tensor.

SparseTensor code(Tensor input, Size time, bool sort = true)

Apply rank coding.

Parameters:
  • input – input sparse tensor.

  • time – number of time steps.

  • sort – whether to sort the values or not. Sorting might increase accuracy but it deceases performance (default true).

Returns:

rank coding output sparse tensor.

Tensor gather(SparseTensor input, Type type = Type::U8)

Gather temporal information.

Parameters:
  • input – input sparse tensor.

  • type – data type of the created output tensor (default Type::U8).

Returns:

gathered output dense tensor.

Tensor gather(SparseTensor input, Tensor output)

Gather temporal information.

Parameters:
  • input – input sparse tensor.

  • output[out] output dense tensor.

Returns:

the output tensor.

SparseTensor pool(SparseTensor input, Expand2 kernel, Expand2 stride = 0, Expand4 pad = 0)

Apply 2D pooling.

Parameters:
  • input – pooling input sparse tensor.

  • kernel[in] pooling kernel dense tensor.

  • stride – convolution stride. Zero stride means same as kernel (default 0).

  • pad – input padding (default 0).

Returns:

pooling output sparse tensor.

SparseTensor inhibit(SparseTensor input)

Apply lateral Inhibition.

Parameters:

input – input sparse tensor.

Returns:

output inhibites sparse tensor.

Winners convwta(SparseTensor input, Expand2 radius, Size count)

Select winner neurons from convolution output.

Parameters:
  • input – input sparse tensor.

  • radius – radius of inhibition.

  • count – number of neurons that will be selected.

Returns:

winner neurons.

Python Documentation

class spyker.BPConfig(sfactor: float, lrate: float, lrf: float, lamda: float)

Backpropagation (BP) configuration.

Holds scalar hyperparameters used by Spyker’s backprop-based learners.

Parameters

sfactorfloat

Scaling factor applied to the loss/gradients (implementation-dependent).

lratefloat

Base learning rate.

lrffloat

Learning-rate falloff/decay factor (e.g., multiplicative schedule).

lamdafloat

Regularization coefficient (e.g., L2 weight decay).

Notes

This class mirrors the underlying C++ BPConfig and is a thin parameter wrapper.

class spyker.Conv(insize: int, outsize: int, kernel: int | Sequence[int], stride: int | Sequence[int] = 1, pad: int | Sequence[int] = 0, mean: float = 0.5, std: float = 0.02, device: impl.Device | None = None, dtype: DataType = 'f32')

2D convolution module.

Wraps the C++ convolution operator and manages kernel/stride/padding normalization, device/dtype placement, and zero-copy interop with NumPy/PyTorch/Spyker tensors.

Attributes

kernelspyker.Tensor

Convolution kernel bank (read-only from Python).

devicespyker.Device

Device where the module resides (e.g., CPU or CUDA device).

stdp(array: TensorLike, winners: Sequence[Sequence[impl.Winner]], output: TensorLike | None = None) None

Apply STDP weight updates to the convolution layer.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Convolution input tensor provided to the forward pass.

winnerssequence of sequence of spyker.Winner

Selected winner neurons per sample/channel for updating.

outputtorch.Tensor or numpy.ndarray or spyker.Tensor or None, default=None

Convolution output tensor. If omitted, the backend may recompute or use internal state as needed.

Notes

If output is provided, both inputs are wrapped with wrap_array to enable zero-copy views before invoking the C++ _stdp.

class spyker.DoG(size: int, filters: DoGFilter | Sequence[DoGFilter], pad: int | Sequence[int] = 0, device: impl.Device | None = None, dtype: DataType = 'f32')

2D Difference-of-Gaussians (DoG) filtering module.

Wraps the C++ DoG operator and manages padding, device/dtype placement, and zero-copy interop with NumPy/PyTorch/Spyker tensors.

Attributes

kernelspyker.Tensor

The assembled convolution kernel bank (read-only from Python).

devicespyker.Device

Device where the module’s parameters reside (e.g., CPU or CUDA device).

class spyker.DoGFilter(std1: float, std2: float)

Difference-of-Gaussians (DoG) filter parameters.

A lightweight parameter holder that mirrors the C++ DoG filter config.

Attributes

std1float

Standard deviation of the first Gaussian.

std2float

Standard deviation of the second Gaussian.

class spyker.FC(insize: int, outsize: int, mean: float = 0.5, std: float = 0.02, device: impl.Device | None = None, dtype: DataType = 'f32')

Fully connected (dense) module.

Wraps the C++ dense layer and supports forward, STDP updates, and backpropagation, while preserving device/dtype and cross-ecosystem interop.

Attributes

kernelspyker.Tensor

Weight matrix of shape (out_features, in_features) (backend-specific layout).

devicespyker.Device

Device where parameters reside (e.g., CPU or CUDA device).

backward(array: TensorLike, output: TensorLike, grad: TensorLike) TensorLike

Backpropagate gradients through the fully connected layer.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Dense input tensor provided to the forward pass.

outputtorch.Tensor or numpy.ndarray or spyker.Tensor

Dense output tensor from the forward pass (used for context if needed).

gradtorch.Tensor or numpy.ndarray or spyker.Tensor

Gradient of the loss w.r.t. the output tensor.

Returns

torch.Tensor or numpy.ndarray or spyker.Tensor

Gradient of the loss w.r.t. the input tensor (next gradient), allocated in the same ecosystem and with the same shape as the normalized input.

stdp(array: TensorLike, winners: Sequence[Sequence[impl.Winner]], output: TensorLike) None

Apply STDP-based weight updates to the fully connected layer.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Dense input tensor provided to the forward pass.

winnerssequence of sequence of spyker.Winner

Selected winner neurons per sample/channel for updating.

outputtorch.Tensor or numpy.ndarray or spyker.Tensor

Dense output tensor produced by the forward pass.

class spyker.Gabor(size: int, filters: GaborFilter | Sequence[GaborFilter], pad: int | Sequence[int] = 0, device: impl.Device | None = None, dtype: DataType = 'f32')

2D Gabor filtering module.

Wraps the C++ Gabor operator for orientation- and frequency-selective convolution with device/dtype/padding management and cross-ecosystem interop.

Attributes

kernelspyker.Tensor

The assembled convolution kernel bank (read-only from Python).

devicespyker.Device

Device where the module’s parameters reside (e.g., CPU or CUDA device).

class spyker.GaborFilter(sigma: float, theta: float, gamma: float, lambda_: float, psi: float)

Gabor filter parameters.

Encapsulates the 2D Gabor kernel configuration commonly used for orientation- and frequency-selective filtering.

Attributes

sigmafloat

Standard deviation (controls envelope size / bandwidth).

thetafloat

Orientation angle in radians (filter rotation).

gammafloat

Spatial aspect ratio (y/x); controls stripe elongation.

lambda_float

Wavelength (spatial period) of the sinusoidal carrier.

psifloat

Phase offset of the carrier in radians.

class spyker.LoG(size: int, stds: Sequence[float], pad: int | Sequence[int] = 0, device: impl.Device | None = None, dtype: DataType = 'f32')

2D Laplacian-of-Gaussian (LoG) filtering module.

Wraps the C++ LoG operator and manages padding, device/dtype placement, and zero-copy interop with NumPy/PyTorch/Spyker tensors.

Attributes

kernelspyker.Tensor

Convolution kernel bank (read-only from Python).

devicespyker.Device

Device where the module resides (e.g., CPU or CUDA device).

class spyker.STDPConfig(positive: float, negative: float, stabilize: bool = True, lower: float = 0.0, upper: float = 1.0)

Spike-Timing-Dependent Plasticity (STDP) configuration.

Attributes

positivefloat

Potentiation learning rate (pre→post timing).

negativefloat

Depression learning rate (post→pre timing).

stabilizebool

Enable weight stabilization.

lowerfloat

Lower bound for synaptic weights.

upperfloat

Upper bound for synaptic weights.

class spyker.ZCA

ZCA Whitening module.

Learns mean and whitening transform from data and applies the transform in-place or out-of-place across PyTorch, NumPy, or Spyker tensors via zero-copy views.

Attributes

meanspyker.Tensor

Learned feature means.

transformspyker.Tensor

Learned whitening matrix.

fit(array: TensorLike, epsilon: float, transform: bool = False) ZCA

Fit mean and whitening transform to the provided data.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Input samples. Leading dimensions are interpreted as batch/stack; the last dimension typically represents features. Accepted layouts are determined by the backend.

epsilonfloat

Stabilizer added to eigenvalues (or diagonal) to ensure numerical stability.

transformbool, default=False

If True, also transform the input in-place during fitting (when supported).

Returns

ZCA

The fitted instance (for chaining).

Notes

Internally dispatches to the C++ implementation via self._fit(...) after wrapping the input with wrap_array (zero-copy when possible).

load(path: str) None

Load a fitted ZCA model from a .npz file.

Parameters

pathstr

Input file path pointing to a NumPy .npz archive containing keys mean and transform.

save(path: str) None

Save the fitted ZCA model to a .npz file.

Parameters

pathstr

Output file path. A NumPy .npz archive is written with keys mean and transform.

static split(array: TensorLike) TensorLike

Split a ZCA-transformed array into two channels: positive and negative.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Input assumed to be ZCA-transformed. The exact required layout is backend-dependent.

Returns

torch.Tensor or numpy.ndarray or spyker.Tensor

Output with an added/modified channel dimension holding the positive and negative parts, matching the input’s ecosystem (PyTorch/NumPy/Spyker).

Notes

This is a thin wrapper over the C++ static method and associated shape helper: it computes the target shape via impl.shape.zca_split and materializes an appropriately-typed/placed output using create_array before invoking impl.ZCA._split.

spyker.all_devices() list[Spyker::Device]
spyker.backward(array: TensorLike, target: TensorLike, time: int, gamma: float) TensorLike

Temporal backpropagation helper.

Computes the gradient-like signal w.r.t. the input over a time horizon.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Input tensor from the forward pass.

targettorch.Tensor or numpy.ndarray or spyker.Tensor

Target/teaching signal aligned with the forward pass (backend-dependent shape).

timeint

Number of time steps to backpropagate through.

gammafloat

Temporal discount/decay factor (backend semantics apply).

Returns

torch.Tensor or numpy.ndarray or spyker.Tensor

Tensor of the same ecosystem and shape as array containing the propagated signal.

spyker.canny(array: TensorLike, low: float, high: float) TensorLike

Canny edge detection.

Wraps the C++ Canny implementation and preserves the input ecosystem (PyTorch/NumPy/Spyker) for the returned tensor.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Input image or batch. Layout is normalized to 4D internally via to4.

lowfloat

Lower hysteresis threshold for weak edges.

highfloat

Upper hysteresis threshold for strong edges.

Returns

torch.Tensor or numpy.ndarray or spyker.Tensor

Edge map with dtype uint8 (0/255 semantics), shaped like the normalized input.

Notes

The destination is allocated with dtype "u8" to match typical Canny outputs.

spyker.clear_context() None
spyker.code(array: TensorLike, time: int, sort: bool = True, dtype: DataType = 'u8', code: CodingType = 'rank') TensorLike

Spike-time coding.

Encodes static values into a temporal code across time steps (e.g., rank coding), returning an output in the same ecosystem as the input (PyTorch/NumPy/Spyker).

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Input dense tensor. Its layout is normalized to at least 2D internally via least2.

timeint

Number of time steps for the temporal code.

sortbool, default=True

If True, values may be sorted to improve coding fidelity (at the cost of performance).

dtypeDataType, default=”u8”

Scalar dtype code for the output tensor.

codeCodingType, default=”rank”

Coding scheme identifier (e.g., “rank”). Supported values are backend-dependent.

Returns

torch.Tensor or numpy.ndarray or spyker.Tensor

Coded output tensor with shape computed by impl.shape.code and dtype dtype.

Notes

The output shape is obtained via impl.shape.code(input.shape, time) and allocated with create_array to preserve the input ecosystem.

spyker.conv(array: TensorLike, kernel: TensorLike, stride: int | Sequence[int] = 1, pad: int | Sequence[int] = 0) TensorLike

2D convolution.

Wraps the C++ convolution operator, normalizing stride/padding and preserving the input ecosystem (PyTorch/NumPy/Spyker) for the returned tensor.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Convolution input. Layout is normalized to 5D via to5; exact conventions (batch/channels/spatial) are backend-dependent.

kerneltorch.Tensor or numpy.ndarray or spyker.Tensor

Convolution kernel tensor. Must be compatible with the backend’s expected layout.

strideint or sequence of 2 ints, default=1

Convolution stride. An int is expanded to (s, s).

padint or sequence of 2 or 4 ints, default=0

Input padding. An int applies symmetric padding; a sequence of 2 means (width, height), and of 4 means (left, right, top, bottom).

Returns

torch.Tensor or numpy.ndarray or spyker.Tensor

Convolved output in the same ecosystem as array.

Notes

The wrapper expands stride via expand2 and pad via expand4, computes the output shape with impl.shape.conv, allocates via create_array, and then calls the C++ impl.conv.

spyker.convwta(array: TensorLike, radius: int | Sequence[int], count: int, threshold: float = 0.0) List[List[impl.Winner]]

Winner-Take-All (WTA) selection for convolutional activations.

Selects count winners per spatial neighborhood using the backend’s convolutional WTA rule.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Convolutional activation tensor.

radiusint or sequence of 2 ints

Neighborhood radius. If an int, expanded to (r, r).

countint

Number of winners to select per neighborhood.

thresholdfloat, default=0.0

Minimum activation required (used for floating-point inputs).

Returns

list[list[spyker.Winner]]

Nested winner descriptors for each sample/channel as produced by the backend.

spyker.copy_array(source: TensorLike, destin: TensorLike) None

Copy data from source into destin, converting/dispatching through Spyker views.

Parameters

sourcetorch.Tensor or numpy.ndarray or spyker.Tensor

Data source.

destintorch.Tensor or numpy.ndarray or spyker.Tensor

Destination buffer. Shape and dtype must be compatible with source after any implicit conversions.

Raises

TypeError

If either input type is unsupported or required dependencies are missing.

ValueError

If shapes/dtypes are incompatible for copy.

Notes

This function wraps both arrays as Spyker tensors (zero-copy views when possible) and performs source_view.to(dest_view) for efficient cross-ecosystem transfers.

spyker.create_tensor(device: impl.Device, dtype: DataType, shape: Sequence[int], pinned: bool = False, unified: bool = False, data: int | None = None) impl.Tensor

Create a Spyker tensor on the given device.

Parameters

devicespyker.Device

Target device (e.g., CPU or CUDA with optional index) returned by Spyker’s device factory.

dtype{“i8”,”i16”,”i32”,”i64”,”u8”,”u16”,”u32”,”u64”,”f16”,”f32”,”f64”}

Spyker scalar data type code.

shapeSequence[int]

Tensor shape (row-major). Must be non-negative; empty sequence creates a scalar.

pinnedbool, default=False

If True and device is CPU, allocate page-locked (pinned) host memory to speed up host↔device transfers.

unifiedbool, default=False

If True and supported, allocate CUDA Unified Memory to allow the same pointer to be accessed by host and device. Ignored if not applicable.

dataint or None, default=None

Optional raw pointer (as an integer) to pre-allocated memory. If provided, Spyker will wrap the buffer instead of allocating new memory. The caller is responsible for lifetime guarantees when wrapping external memory.

Returns

spyker.Tensor

Newly created Spyker tensor view/owner consistent with the provided arguments.

Raises

ValueError

If shape contains negative dimensions.

TypeError

If arguments are incompatible with the target device or data type.

Notes

  • When data is None, memory is allocated by Spyker using pinned/unified hints.

  • When data is not None, Spyker does not copy; it constructs a tensor wrapping the given pointer with the specified dtype/shape/device.

spyker.cuda_arch_list() list[int]
spyker.cuda_available() bool
spyker.cuda_cache_clear(*args, **kwargs)

Overloaded function.

  1. cuda_cache_clear(arg0: typing.SupportsInt) -> None

  2. cuda_cache_clear() -> None

spyker.cuda_cache_enable(*args, **kwargs)

Overloaded function.

  1. cuda_cache_enable(arg0: bool, arg1: typing.SupportsInt) -> None

  2. cuda_cache_enable(arg0: bool) -> None

spyker.cuda_cache_enabled(*args, **kwargs)

Overloaded function.

  1. cuda_cache_enabled(arg0: typing.SupportsInt) -> bool

  2. cuda_cache_enabled() -> bool

spyker.cuda_cache_print(*args, **kwargs)

Overloaded function.

  1. cuda_cache_print(arg0: typing.SupportsInt) -> None

  2. cuda_cache_print() -> None

spyker.cuda_conv_force(arg0: bool) None
spyker.cuda_conv_heuristic(arg0: bool) None
spyker.cuda_conv_light(arg0: bool) None
spyker.cuda_current_device() int
spyker.cuda_device_arch() list[int]
spyker.cuda_device_count() int
spyker.cuda_memory_free() int
spyker.cuda_memory_taken(*args, **kwargs)

Overloaded function.

  1. cuda_memory_taken(arg0: typing.SupportsInt) -> int

  2. cuda_memory_taken() -> int

spyker.cuda_memory_total() int
spyker.cuda_memory_used(*args, **kwargs)

Overloaded function.

  1. cuda_memory_used(arg0: typing.SupportsInt) -> int

  2. cuda_memory_used() -> int

spyker.cuda_set_device(arg0: SupportsInt) None
spyker.fc(array: TensorLike, kernel: TensorLike, sign: bool = False) TensorLike

Fully connected (dense) operation.

Computes y = W @ x over the last dimension (backend-dependent layout), preserving the input ecosystem for the output.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Input dense tensor. Layout is normalized to 3D internally via to3.

kerneltorch.Tensor or numpy.ndarray or spyker.Tensor

Dense weight matrix compatible with the backend’s impl.shape.fc contract.

signbool, default=False

Run the kernel through the sign function before running the operation.

Returns

torch.Tensor or numpy.ndarray or spyker.Tensor

Output dense tensor in the same ecosystem (PyTorch/NumPy/Spyker) as array.

Notes

The output shape is computed with impl.shape.fc; allocation is done via create_array to match dtype/device semantics of the inputs.

spyker.fcwta(array: TensorLike, radius: int, count: int, threshold: float = 0.0) List[List[impl.Winner]]

Winner-Take-All (WTA) selection for fully-connected activations.

Selects count winners per local neighborhood (defined by radius) using the backend’s FC WTA rule.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Dense activation tensor (fully-connected layout).

radiusint

Neighborhood radius for inhibition/competition.

countint

Number of winners to select per neighborhood.

thresholdfloat, default=0.0

Minimum activation required (used for floating-point inputs).

Returns

list[list[spyker.Winner]]

Nested winner descriptors for each sample/channel as produced by the backend.

spyker.fire(array: TensorLike, threshold: float = 0.0, dtype: DataType = 'u8', code: CodingType = 'rank') TensorLike

Integrate-and-fire (IAF) spike generation.

Converts analog inputs into spike events using an integrate-and-fire rule. If the input is already thresholded/quantized, threshold can be left at its default.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Input tensor to convert into spikes.

thresholdfloat, default=0.0

Firing threshold; elements below this may be suppressed (backend-dependent semantics).

dtypeDataType, default=”u8”

Scalar dtype code for the output spike tensor.

codeCodingType, default=”rank”

Coding scheme identifier for spike representation (backend-dependent).

Returns

torch.Tensor or numpy.ndarray or spyker.Tensor

Spike tensor in the same ecosystem as array, with the same shape and dtype dtype.

spyker.gather(array: TensorLike, threshold: float = 0.0, dtype: DataType = 'u8', code: CodingType = 'rank') TensorLike

Gather temporal information into a compact representation.

Aggregates events across the time dimension into a single frame (or reduced temporal structure) using an integrate-and-fire–like rule with an optional threshold.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Input tensor. Its layout is normalized to at least 3D via least3.

thresholdfloat, default=0.0

Firing threshold. If the input is already thresholded/sparse, this can remain 0.

dtypeDataType, default=”u8”

Scalar dtype code for the output tensor.

codeCodingType, default=”rank”

Coding scheme identifier (backend-dependent).

Returns

torch.Tensor or numpy.ndarray or spyker.Tensor

Gathered output tensor in the same ecosystem as array. The shape is determined by impl.shape.gather(input.shape).

Notes

Output allocation is performed via create_array to preserve device/ecosystem.

spyker.infinite(array: TensorLike, value: float = 0.0, inplace: bool = True) TensorLike

Infinite thresholding.

Marks/sets values considered non-finite (implementation-dependent) to value. Can modify the input in-place or return a cloned-and-modified copy.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Input tensor to sanitize.

valuefloat, default=0.0

Replacement value for elements considered infinite/non-finite.

inplacebool, default=True

If True, modify array directly; if False, operate on a deep copy.

Returns

torch.Tensor or numpy.ndarray or spyker.Tensor

The modified tensor (same object if inplace=True).

Notes

The input is normalized to at least 3D internally via least3 before processing.

spyker.inhibit(array: TensorLike, threshold: float = 0.0, inplace: bool = True) TensorLike

Lateral inhibition (optionally in-place).

Suppresses activations within a local neighborhood according to the backend’s inhibition rule. If the input is already thresholded/sparse, you can keep threshold=0.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Input tensor to inhibit.

thresholdfloat, default=0.0

Firing threshold used by the backend (applies to floating-point inputs).

inplacebool, default=True

If True, modify array directly; if False, a cloned copy is modified.

Returns

torch.Tensor or numpy.ndarray or spyker.Tensor

The inhibited tensor (same object if inplace=True).

spyker.labelize(array: TensorLike, threshold: float) TensorLike

Labelize activations into integer class indices.

Collapses per-sample activations to a single integer label based on the backend’s selection rule and the given threshold.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Activation tensor; first dimension is interpreted as batch.

thresholdfloat

Minimum activation required to assign a label.

Returns

torch.Tensor or numpy.ndarray or spyker.Tensor

1D tensor of length batch_size with dtype int64 (Spyker "i64"), returned in the same ecosystem as array.

spyker.max_threads() int
spyker.pad(array: TensorLike, pad: int | Sequence[int] = 0, value: float = 0.0) TensorLike

Apply 2D spatial padding.

Wraps the C++ padding operator and preserves the input ecosystem (PyTorch/NumPy/Spyker) for the returned tensor.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Input tensor to be padded. Layout is normalized to 5D internally via to5.

padint or sequence of 2 or 4 ints, default=0

Padding specification: - int → symmetric padding on both axes, - 2-tuple → (width, height), - 4-tuple → (left, right, top, bottom).

valuefloat, default=0.0

Fill value for padded regions.

Returns

torch.Tensor or numpy.ndarray or spyker.Tensor

Padded output tensor in the same ecosystem as array.

Notes

The output shape is computed with impl.shape.pad; allocation is done via create_array with the input’s dtype/device semantics.

spyker.pool(array: TensorLike, kernel: int | Sequence[int], stride: int | Sequence[int] | None = None, pad: int | Sequence[int] = 0, rates: TensorLike | None = None) TensorLike

2D max pooling.

Wraps the C++ pooling operator, normalizing kernel/stride/padding and preserving the input ecosystem (PyTorch/NumPy/Spyker) for the returned tensor.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Pooling input tensor. Layout is normalized to 5D internally via to5.

kernelint or sequence of 2 ints

Pooling window size. If an int, expanded to (k, k).

strideNone or int or sequence of 2 ints, default=None

Pooling stride. If None, it defaults to kernel. If an int, expanded to (s, s).

padint or sequence of 2 or 4 ints, default=0

Spatial padding. If an int, symmetric padding; a sequence of 2 means (width, height), and a sequence of 4 means (left, right, top, bottom).

ratestorch.Tensor or numpy.ndarray or spyker.Tensor or None, default=None

Optional per-location rates/weights (backend-dependent). If omitted, an empty Spyker tensor is passed.

Returns

torch.Tensor or numpy.ndarray or spyker.Tensor

Pooled output tensor in the same ecosystem as array. Shape computed with impl.shape.pool(input.shape, kernel, stride, pad).

Notes

  • kernel and stride are expanded via expand2; pad via expand4.

  • Output allocation is done with create_array to preserve dtype/device semantics.

spyker.quantize(array: TensorLike, lower: float, middle: float, upper: float, inplace: bool = True) TensorLike

Quantize values into two levels based on a midpoint.

If element < middle, it is set to lower; otherwise set to upper.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Input tensor to quantize.

lowerfloat

Value to assign when element < middle.

middlefloat

Midpoint threshold for quantization.

upperfloat

Value to assign when element >= middle.

inplacebool, default=True

If True, modifies array directly; if False, a clone is created first.

Returns

torch.Tensor or numpy.ndarray or spyker.Tensor

Quantized tensor (same object if inplace=True).

spyker.random_seed(arg0: SupportsInt) None
spyker.read_mnist(train_images: str, train_labels: str, test_images: str, test_labels: str) Tuple[Tensor, Tensor, Tensor, Tensor]

Load MNIST dataset files into Spyker tensors.

Parameters

train_imagesstr

Path to training images (e.g., train-images-idx3-ubyte or gzipped counterpart).

train_labelsstr

Path to training labels (e.g., train-labels-idx1-ubyte or gzipped counterpart).

test_imagesstr

Path to test images.

test_labelsstr

Path to test labels.

Returns

(TRX, TRY, TEX, TEY)tuple of spyker.Tensor

Training images, training labels, test images, test labels as Spyker tensors.

spyker.scatter(array: TensorLike, time: int, dtype: DataType = 'u8') TensorLike

Scatter a compact representation across a time axis.

Expands static inputs into a temporal sequence of length time according to the backend’s scattering rule.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Input tensor. Normalized to at least 2D via least2.

timeint

Number of time steps in the scattered output.

dtypeDataType, default=”u8”

Scalar dtype code for the output tensor.

Returns

torch.Tensor or numpy.ndarray or spyker.Tensor

Scattered output tensor in the same ecosystem as array. Shape is computed with impl.shape.scatter(input.shape, time).

spyker.set_max_threads(*args, **kwargs)

Overloaded function.

  1. set_max_threads(arg0: typing.SupportsInt) -> None

  2. set_max_threads() -> None

spyker.stdp(conv: impl.Conv, array: TensorLike, winners: Sequence[Sequence[impl.Winner]], output: TensorLike) None

Low-level STDP update helper for convolutional layers.

Dispatches directly to the backend to update conv’s parameters using the provided winners and forward pass tensors.

Parameters

convimpl.Conv

Convolutional module whose weights will be updated.

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Input tensor used for the forward pass.

winnerssequence of sequence of spyker.Winner

Selected winner neurons per sample/channel.

outputtorch.Tensor or numpy.ndarray or spyker.Tensor

Output tensor from the forward pass matching array.

spyker.threshold(array: TensorLike, threshold: float, value: float = 0.0, inplace: bool = True) TensorLike

Apply thresholding.

All values below the threshold are set to value; others remain unchanged. Can operate in-place or return a new array.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Input tensor.

thresholdfloat

Threshold value.

valuefloat, default=0.0

Replacement value for elements below the threshold.

inplacebool, default=True

If True, modifies array directly; if False, a clone is created first.

Returns

torch.Tensor or numpy.ndarray or spyker.Tensor

Thresholded tensor (same object if inplace=True).

spyker.to_numpy(*arrays: impl.Tensor) numpy.ndarray

Convert one or more Spyker tensors to NumPy arrays.

Parameters

arraysspyker.Tensor

One or more Spyker tensors.

Returns

numpy.ndarray or tuple of numpy.ndarray

A single NumPy array if one input is given; otherwise, a tuple in the same order.

Raises

TypeError

If NumPy is not available.

spyker.to_tensor(*arrays: TensorLike, pinned: bool = False, unified: bool = False) impl.Tensor | tuple[impl.Tensor, ...]

Convert one or more arrays (PyTorch/NumPy/Spyker) to new Spyker tensors.

Parameters

arraystorch.Tensor or numpy.ndarray or spyker.Tensor

One or more input arrays to convert.

pinnedbool, default=False

Use pinned host memory for destinations where applicable.

unifiedbool, default=False

Use CUDA Unified Memory for destinations where applicable.

Returns

spyker.Tensor or tuple of spyker.Tensor

A single Spyker tensor if one input is given; otherwise, a tuple in the same order.

Examples

>>> x_spyker = to_tensor(x_numpy)
>>> a_spyker, b_spyker = to_tensor(a_torch, b_numpy, pinned=True)
spyker.to_torch(*arrays: impl.Tensor) torch.Tensor

Convert one or more Spyker tensors to PyTorch tensors.

Parameters

arraysspyker.Tensor

One or more Spyker tensors.

Returns

torch.Tensor or tuple of torch.Tensor

A single PyTorch tensor if one input is given; otherwise, a tuple in the same order.

Raises

TypeError

If PyTorch is not available.

spyker.wrap_array(array: TensorLike, writeable: bool = False) impl.Tensor

Create a zero-copy Spyker tensor view over a PyTorch tensor, NumPy array, or return the same object if it is already a Spyker tensor.

Parameters

arraytorch.Tensor or numpy.ndarray or spyker.Tensor

Source array to wrap. Requires PyTorch/NumPy to be installed if those types are used.

writeablebool, default=False

If the result should be writable and the array is a non-writeable NumPy array, an error will be raised.

Returns

spyker.Tensor

Spyker tensor view referencing the same memory (no data copy).

Raises

TypeError

If array is not a supported type or if the corresponding optional dependency is not available.

TypeError

If writeable is true and array is a read-only NumPy array

Notes

  • This function avoids data copies; changes through either view reflect in the other, subject to backend semantics.

  • If array is a NumPy array with writeable=False and writeable=True is requested, an error may be raised