Core Tensor Engine

The tensor subsystem is the foundation of runtime performance. It exposes a PHP API while delegating numeric workloads to a native C engine through FFI.

Concept

Tensors are multi-dimensional arrays backed by a C TensorC struct. PHP objects are thin wrappers around opaque native pointers.

Key design decisions:

Internal Flow

  1. Tensor::wrap($ptr) creates a PHP wrapper for a native TensorC*.
  2. PHP methods call TensorEngine::get() and invoke FFI functions.
  3. C kernels return new TensorC* pointers, which PHP wraps again.
  4. __destruct() frees owned tensors unless the tensor is a zero-copy view.

Data flow diagram

PHP Tensor object
        │
        │ wrap/unwrap
        ▼
Native TensorC* pointer
        │
        │ FFI boundary
        ▼
 C kernel / BLAS call

Memory semantics

Copy vs zero-copy

API exposure

PHP usage

use Pml\Tensor;

$t = Tensor::zeros(512, 128);
$t = $t->fill(1.0);
$row = $t->row(0);          // zero-copy view
$copy = $row->copy();       // allocate new buffer

Corresponding C-level behavior

Performance implications

When to use

When not to use