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.
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.
-
enumerator I8
Functions
-
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.
-
void clearContext()
Clear all reserved data.
-
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.
-
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.
-
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.
-
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.
-
Device(Kind kind = Kind::CPU, I32 index = -1)
-
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.
- 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.
- 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 shape(Size index) const
Get the shape element in index.
- Parameters:
index – index of the element to be returned.
-
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 &fill(Scalar value)
Fill the tensor with value.
- Parameters:
value – value to fill the tensor with.
-
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.
-
using Deleter = std::function<void(void*)>
-
class SparseTensor
- #include <utils.h>
5-dimentional container of sparse binary spikes on the CPU
Public Functions
-
SparseTensor()
Initialize empty 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).
-
void *data() const
Get the raw data pointer. This points to a internal data structure and should not be used.
-
Size shape(Size index) const
Get the shape element in index.
- Parameters:
index – index of the element to be returned.
-
SparseTensor copy() const
Get a deep copy of the tensor.
-
SparseTensor()
-
class Scalar
- #include <utils.h>
Non-templated basic data type container.
-
struct STDPConfig
- #include <utils.h>
STDP configuration parameters container.
-
struct BPConfig
- #include <utils.h>
Backpropagation configuration parameters container.
-
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.
-
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.
-
DoG()
-
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.
-
Gabor()
-
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.
-
LoG()
-
class ZCA
- #include <opers.h>
ZCA whitening transformation module.
Public Functions
-
ZCA()
Empty initialization.
Public Members
-
ZCA()
-
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.
Public Members
-
std::vector<STDPConfig> stdpconfig
List of STDP configurations.
-
Conv()
-
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, Tensor next)
Backpropagate and return the gradient.
-
FC()
-
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.
-
class CSV
- #include <csv.h>
CSV file reader.
Public Functions
-
CSV(const std::string &path, const std::string &delim = ", ")
-
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.
-
CSV(const std::string &path, const std::string &delim = ", ")
-
Tensor readImage(const std::string &path, std::string mode = "", Shape size = {-1, -1})
-
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.
-
SparseTensor conv(SparseTensor input, Tensor kernel, Scalar threshold, Expand2 stride = 1, Expand4 pad = 0)
-
using I8 = int8_t
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++
BPConfigand 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
outputis provided, both inputs are wrapped withwrap_arrayto 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 withwrap_array(zero-copy when possible).
- load(path: str) None
Load a fitted ZCA model from a
.npzfile.Parameters
- pathstr
Input file path pointing to a NumPy
.npzarchive containing keysmeanandtransform.
- save(path: str) None
Save the fitted ZCA model to a
.npzfile.Parameters
- pathstr
Output file path. A NumPy
.npzarchive is written with keysmeanandtransform.
- 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_splitand materializes an appropriately-typed/placed output usingcreate_arraybefore invokingimpl.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
timesteps (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.codeand dtypedtype.
Notes
The output shape is obtained via
impl.shape.code(input.shape, time)and allocated withcreate_arrayto 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
strideviaexpand2andpadviaexpand4, computes the output shape withimpl.shape.conv, allocates viacreate_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.
cuda_cache_clear(arg0: typing.SupportsInt) -> None
cuda_cache_clear() -> None
- spyker.cuda_cache_enable(*args, **kwargs)
Overloaded function.
cuda_cache_enable(arg0: bool, arg1: typing.SupportsInt) -> None
cuda_cache_enable(arg0: bool) -> None
- spyker.cuda_cache_enabled(*args, **kwargs)
Overloaded function.
cuda_cache_enabled(arg0: typing.SupportsInt) -> bool
cuda_cache_enabled() -> bool
- spyker.cuda_cache_print(*args, **kwargs)
Overloaded function.
cuda_cache_print(arg0: typing.SupportsInt) -> None
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.
cuda_memory_taken(arg0: typing.SupportsInt) -> int
cuda_memory_taken() -> int
- spyker.cuda_memory_total() int
- spyker.cuda_memory_used(*args, **kwargs)
Overloaded function.
cuda_memory_used(arg0: typing.SupportsInt) -> int
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 @ xover 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.fccontract.- 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 viacreate_arrayto 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,
thresholdcan 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_arrayto 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
least3before 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_sizewith dtypeint64(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 viacreate_arraywith 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
kernelandstrideare expanded viaexpand2;padviaexpand4.Output allocation is done with
create_arrayto 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-ubyteor gzipped counterpart).- train_labelsstr
Path to training labels (e.g.,
train-labels-idx1-ubyteor 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
timeaccording 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.
set_max_threads(arg0: typing.SupportsInt) -> None
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