IncliArray
Loading...
Searching...
No Matches
NDArray Class Reference

#include <NDArray.h>

Public Types

enum class  PrintType { Data , Grad }
 

Public Member Functions

 NDArray (std::vector< int > shape, std::string label="", std::string op="", std::vector< std::reference_wrapper< NDArray > > prev={})
 Construct an owning, contiguous NDArray of given shape.
 
void metadata (bool shapeInfo=true, bool stridesInfo=false, bool ndimInfo=false, bool sizeInfo=false, bool ownsDataInfo=false)
 Print selected metadata fields.
 
float get (std::vector< int > indices, PrintType type=PrintType::Data) const
 Read an element by multi‑dimensional indices.
 
float get (int index, PrintType type=PrintType::Data) const
 Read an element by flat index.
 
void set (std::vector< int > indices, float value)
 Write an element by multi‑dimensional indices.
 
void set (int index, float value)
 Write an element by flat index.
 
NDArray slice (std::vector< std::tuple< int, int > > indices)
 Return a non‑owning view restricted by per‑axis [start, stop) slices.
 
bool isContiguous () const
 Whether the logical layout matches standard row‑major contiguous strides for the current shape.
 
void reshape (std::vector< int > newShape)
 Reshape this array to a new shape with the same number of elements.
 
void print (PrintType type=PrintType::Data)
 Pretty‑print the data or gradients.
 
void fillSequential ()
 Fill with sequential values 0, 1, 2, ... (for demos/testing).
 
void fill (float value)
 Fill with a constant value.
 
void zeros ()
 Set all elements to 0.
 
void ones ()
 Set all elements to 1.
 
void randint (int low, int high)
 Fill with uniform integer values in [low, high).
 
void rand ()
 Fill with uniform real values in [0, 1).
 
void rand (float low, float high)
 Fill with uniform real values in [low, high).
 
NDArray operator+ (NDArray &other)
 Broadcasted element‑wise addition (this + other).
 
NDArray operator+ (float value)
 Scalar addition (this + value), shape‑preserving.
 
NDArray operator- (NDArray &other)
 Broadcasted element‑wise subtraction (this - other).
 
NDArray operator- (float value)
 Scalar subtraction (this - value), shape‑preserving.
 
NDArray operator* (NDArray &other)
 2D matrix multiplication (no broadcasting).
 
NDArray operator* (float value)
 Scalar element wise multiplication (no broadcasting).
 
NDArray operator/ (NDArray &other)
 Broadcasted element‑wise division (this / other).
 
NDArray operator/ (float value)
 Scalar division (this / value), shape‑preserving, warns on zero.
 
NDArray operator^ (float value)
 Scalar element-wise power (this ^ value).
 
NDArray element_wise_multiply (NDArray &other)
 Broadcasted element‑wise multiplication.
 
NDArray element_wise_multiply (float value)
 Scalar element‑wise multiplication (this * value).
 
NDArray sum ()
 Reduce all elements to a scalar sum.
 
NDArray sum (int axis)
 Sum along a specified axis (keep dimension as size 1).
 
void backward ()
 Reverse‑mode backprop: accumulate gradients into all reachable parents from this node.
 
NDArray clone ()
 Materialize a contiguous, owning copy. Detached from autograd.
 

Public Attributes

float * data
 
std::vector< int > shape
 
std::vector< int > strides
 
int ndim
 
int size = 0
 
bool ownsData
 
float * grad
 
std::string op
 
std::string label
 
std::vector< std::reference_wrapper< NDArray > > prev
 
std::function< void()> _backward
 

Private Member Functions

 NDArray (std::vector< int > shape, std::vector< int > strides, float *data, bool ownsData, std::string label="", std::string op="", std::vector< std::reference_wrapper< NDArray > > prev={})
 Internal constructor used for creating non-owning views or wrapping existing memory with specific strides.
 
void build_topo (std::unordered_set< NDArray * > &visited, NDArray *arr, std::vector< std::reference_wrapper< NDArray > > &topo)
 Build a topological ordering of nodes reachable from arr.
 

Member Enumeration Documentation

◆ PrintType

enum class NDArray::PrintType
strong

Select between printing data or gradient buffers.

Enumerator
Data 
Grad 

Constructor & Destructor Documentation

◆ NDArray() [1/2]

NDArray::NDArray ( std::vector< int >  shape,
std::vector< int >  strides,
float *  data,
bool  ownsData,
std::string  label = "",
std::string  op = "",
std::vector< std::reference_wrapper< NDArray > >  prev = {} 
)
private

Internal constructor used for creating non-owning views or wrapping existing memory with specific strides.

This does not allocate memory. When ownsData == false, the lifetime of the provided data pointer must outlive the NDArray instance.

Autograd: callers decide whether to pass graph metadata. Slice uses this constructor but returns a detached view (prev empty, op empty).

◆ NDArray() [2/2]

NDArray::NDArray ( std::vector< int >  shape,
std::string  label = "",
std::string  op = "",
std::vector< std::reference_wrapper< NDArray > >  prev = {} 
)

Construct an owning, contiguous NDArray of given shape.

Allocates data and grad, computes row‑major strides, and sets ownsData = true. This constructor creates a base tensor that can participate in autograd.

Member Function Documentation

◆ backward()

void NDArray::backward ( )

Reverse‑mode backprop: accumulate gradients into all reachable parents from this node.

Sets this->grad to ones (dOut/dOut = 1) and walks the graph in reverse topological order, invoking each node’s _backward closure.

◆ build_topo()

void NDArray::build_topo ( std::unordered_set< NDArray * > &  visited,
NDArray arr,
std::vector< std::reference_wrapper< NDArray > > &  topo 
)
private

Build a topological ordering of nodes reachable from arr.

DFS that collects unique nodes (by pointer) into topo such that parents appear before children, enabling reverse‑mode backprop from outputs to inputs.

◆ clone()

NDArray NDArray::clone ( )

Materialize a contiguous, owning copy. Detached from autograd.

If the source is contiguous, performs a fast contiguous copy; otherwise uses a stride‑aware copy. The returned tensor has no graph linkage.

◆ element_wise_multiply() [1/2]

NDArray NDArray::element_wise_multiply ( float  value)

Scalar element‑wise multiplication (this * value).

◆ element_wise_multiply() [2/2]

NDArray NDArray::element_wise_multiply ( NDArray other)

Broadcasted element‑wise multiplication.

Autograd: dA += other * dOut; dB += this * dOut.

◆ fill()

void NDArray::fill ( float  value)

Fill with a constant value.

Exceptions
std::runtime_errorif the array does not own its memory

◆ fillSequential()

void NDArray::fillSequential ( )

Fill with sequential values 0, 1, 2, ... (for demos/testing).

Exceptions
std::runtime_errorif the array does not own its memory

◆ get() [1/2]

float NDArray::get ( int  index,
NDArray::PrintType  type = PrintType::Data 
) const

Read an element by flat index.

Valid only for contiguous, owning arrays. Treats memory as a flat buffer regardless of shape, primarily for debugging and demos.

Parameters
indexFlat position in [0, size)
typeWhether to read data or grad
Returns
The element value
Exceptions
std::out_of_rangeif index is outside [0, size)
std::runtime_errorif the array is not contiguous or not owning

◆ get() [2/2]

float NDArray::get ( std::vector< int >  indices,
NDArray::PrintType  type = PrintType::Data 
) const

Read an element by multi‑dimensional indices.

Parameters
indicesA vector of length ndim specifying the coordinate
typeWhether to read from data or grad buffer
Returns
The element value
Exceptions
std::invalid_argumentif indices.size() != ndim

◆ isContiguous()

bool NDArray::isContiguous ( ) const

Whether the logical layout matches standard row‑major contiguous strides for the current shape.

◆ metadata()

void NDArray::metadata ( bool  shapeInfo = true,
bool  stridesInfo = false,
bool  ndimInfo = false,
bool  sizeInfo = false,
bool  ownsDataInfo = false 
)

Print selected metadata fields.

Parameters
shapeInfoWhether to print shape
stridesInfoWhether to print strides (row‑major steps)
ndimInfoWhether to print number of dimensions
sizeInfoWhether to print total size (elements)
ownsDataInfoWhether to print ownership flag

◆ ones()

void NDArray::ones ( )

Set all elements to 1.

◆ operator*() [1/2]

NDArray NDArray::operator* ( float  value)

Scalar element wise multiplication (no broadcasting).

Parameters
valueValue to multiply array with.

◆ operator*() [2/2]

NDArray NDArray::operator* ( NDArray other)

2D matrix multiplication (no broadcasting).

Exceptions
std::invalid_argumentif either input is not 2D or dims mismatch Autograd: implements dA = dC * B^T and dB = A^T * dC.

◆ operator+() [1/2]

NDArray NDArray::operator+ ( float  value)

Scalar addition (this + value), shape‑preserving.

◆ operator+() [2/2]

NDArray NDArray::operator+ ( NDArray other)

Broadcasted element‑wise addition (this + other).

Autograd: result records graph metadata and accumulates dA += dOut and dB += dOut with broadcasting.

◆ operator-() [1/2]

NDArray NDArray::operator- ( float  value)

Scalar subtraction (this - value), shape‑preserving.

◆ operator-() [2/2]

NDArray NDArray::operator- ( NDArray other)

Broadcasted element‑wise subtraction (this - other).

Autograd: dA += dOut, dB += -dOut with broadcasting.

◆ operator/() [1/2]

NDArray NDArray::operator/ ( float  value)

Scalar division (this / value), shape‑preserving, warns on zero.

◆ operator/() [2/2]

NDArray NDArray::operator/ ( NDArray other)

Broadcasted element‑wise division (this / other).

Warns on division by zero. Autograd: dA += dOut / other, dB += -(this / other^2) * dOut.

◆ operator^()

NDArray NDArray::operator^ ( float  value)

Scalar element-wise power (this ^ value).

Raises each element to the given scalar power. Autograd: dA += value * A^(value - 1) * dOut.

◆ print()

void NDArray::print ( NDArray::PrintType  type = PrintType::Data)

Pretty‑print the data or gradients.

Prints 1D and 2D arrays in nested list form; higher‑dimensional arrays are printed flattened for brevity.

◆ rand() [1/2]

void NDArray::rand ( )

Fill with uniform real values in [0, 1).

Exceptions
std::runtime_errorif the array does not own its memory

◆ rand() [2/2]

void NDArray::rand ( float  low,
float  high 
)

Fill with uniform real values in [low, high).

Exceptions
std::invalid_argumentif low >= high
std::runtime_errorif the array does not own its memory

◆ randint()

void NDArray::randint ( int  low,
int  high 
)

Fill with uniform integer values in [low, high).

Parameters
lowInclusive lower bound
highExclusive upper bound
Exceptions
std::runtime_errorif the array does not own its memory

◆ reshape()

void NDArray::reshape ( std::vector< int >  newShape)

Reshape this array to a new shape with the same number of elements.

Only allowed for owning, contiguous arrays. Updates shape and recomputes strides to standard row‑major.

Parameters
newShapeTarget shape (product must equal current size)
Exceptions
std::runtime_errorif the array is not owning or not contiguous
std::invalid_argumentif newShape is empty or incompatible in size

◆ set() [1/2]

void NDArray::set ( int  index,
float  value 
)

Write an element by flat index.

Valid only for contiguous, owning arrays. Writes into the underlying memory ignoring shape.

Parameters
indexFlat position in [0, size)
valueValue to write
Exceptions
std::out_of_rangeif index is outside [0, size)
std::runtime_errorif the array is not contiguous or not owning

◆ set() [2/2]

void NDArray::set ( std::vector< int >  indices,
float  value 
)

Write an element by multi‑dimensional indices.

Parameters
indicesCoordinate of the element (length == ndim)
valueValue to write into data buffer
Exceptions
std::invalid_argumentif indices.size() != ndim

◆ slice()

NDArray NDArray::slice ( std::vector< std::tuple< int, int > >  indices)

Return a non‑owning view restricted by per‑axis [start, stop) slices.

The returned NDArray shares data with the base tensor and has updated shape/strides/offset. It is DETACHED from autograd: no graph is recorded and its _backward is a no‑op.

Parameters
indicesA vector (length == ndim) of (start, stop) pairs, inclusive start and exclusive stop for each axis
Returns
A detached view (non‑owning)
Exceptions
std::invalid_argumentif the number of slices != ndim

◆ sum() [1/2]

NDArray NDArray::sum ( )

Reduce all elements to a scalar sum.

Returns a 1-element NDArray holding the total sum. Autograd: distributes the upstream gradient uniformly to every input element (dA += 1 * dOut).

◆ sum() [2/2]

NDArray NDArray::sum ( int  axis)

Sum along a specified axis (keep dimension as size 1).

The output shape matches the input except shape[axis] == 1. Negative axes are supported (Python-style indexing). Autograd: broadcasts upstream gradient across the reduced axis into the input gradient.

Parameters
axisThe axis along which to compute the sum (supports negatives)
Exceptions
std::invalid_argumentif axis is out of range after normalization

◆ zeros()

void NDArray::zeros ( )

Set all elements to 0.

Member Data Documentation

◆ _backward

std::function<void()> NDArray::_backward

Backpropagation closure; invoked during backward(). Node‑local backward function.

◆ data

float* NDArray::data

Raw data pointer in row‑major layout. Points to size floats. Raw data pointer in row‑major layout (length = size).

◆ grad

float* NDArray::grad

Gradient buffer aligned with logical indexing (allocated when constructed). Gradient storage parallel to data.

◆ label

std::string NDArray::label

Optional human‑readable label for this tensor. User/debug label.

◆ ndim

int NDArray::ndim

Number of dimensions (shape.size()). Number of axes.

◆ op

std::string NDArray::op

Operation tag for debug/inspection (e.g. "+", "-", "elem_mul", "*"). Debug op tag.

◆ ownsData

bool NDArray::ownsData

Whether this NDArray owns and manages the memory referenced by data. True if this tensor allocated and owns its memory.

◆ prev

std::vector<std::reference_wrapper<NDArray> > NDArray::prev

Parents in autograd graph. Empty for detached tensors (slice/clone). Graph parents.

◆ shape

std::vector<int> NDArray::shape

Dimensions of the array, e.g. {rows, cols} for 2D. Shape dimensions; product equals size.

◆ size

int NDArray::size = 0

Total number of elements (product of shape). Total element count.

◆ strides

std::vector<int> NDArray::strides

Row‑major strides in elements; stride[i] is step for axis i. Row‑major strides per axis (in elements).


The documentation for this class was generated from the following files: