PHPackages                             ghostjat/pml - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. ghostjat/pml

ActiveLibrary[Framework](/categories/framework)

ghostjat/pml
============

High-performance Tensor library for PHP utilizing FFI, OpenBLAS, and zero-copy memory operations.

1.0.0(1mo ago)28MITPHPPHP ^8.1CI failing

Since Apr 22Pushed 1mo agoCompare

[ Source](https://github.com/ghostjat/pml)[ Packagist](https://packagist.org/packages/ghostjat/pml)[ GitHub Sponsors](https://github.com/ghostjat)[ RSS](/packages/ghostjat-pml/feed)WikiDiscussions main Synced 3w ago

READMEChangelog (5)Dependencies (2)Versions (6)Used By (0)

PML — PHP Machine Learning
==========================

[](#pml--php-machine-learning)

**A production-grade CPU-first AI runtime and machine learning infrastructure framework for PHP.**

[![License: MIT](https://camo.githubusercontent.com/08cef40a9105b6526ca22088bc514fbfdbc9aac1ddbf8d4e6c750e3a88a44dca/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d626c75652e737667)](LICENSE)[![PHP](https://camo.githubusercontent.com/88b464e5614cf654f181925115d47b523dc429fcfe41d59565e42e757f306f29/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344382e312d3838393242462e737667)](https://php.net)[![Build](https://camo.githubusercontent.com/fe871dc75a9c1f44a6a9d1d900c308a75a6bbbc1447c7a79faf58b588327ee69/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f67686f73746a61742f706d6c2f63692e796d6c3f6c6162656c3d4349)](https://github.com/ghostjat/pml/actions)[![Packagist](https://camo.githubusercontent.com/615b5de0f9e28979c0b90fcb15792a4d0ff192b3148a272166d186ef1df623d2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f67686f73746a61742f706d6c)](https://packagist.org/packages/ghostjat/pml)[![Stars](https://camo.githubusercontent.com/0b81864fcb9c26f2c30dbd60b9ae004f53aa14ac2f2886d67e8b6150ab2962b4/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f67686f73746a61742f706d6c3f7374796c653d736f6369616c)](https://github.com/ghostjat/pml/stargazers)[![Sponsor](https://camo.githubusercontent.com/f2fe9cdbd7c6be97a6dc45033c90391817fd31004a202ce278b2ead8ac5f755e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f53706f6e736f722d2545322539442541342d6561346161612e737667)](https://github.com/sponsors/ghostjat)

---

> PML is to PHP what llama.cpp is to C++ — a high-performance native runtime that brings serious AI computation into an ecosystem the rest of the industry ignores.

---

What is PML?
------------

[](#what-is-pml)

PML is a **native-accelerated machine learning and AI inference runtime** built for PHP. It combines a hand-optimized C tensor engine with a clean PHP orchestration layer, delivering production-grade ML without Python, without CUDA, and without sacrificing throughput.

The architecture is built on a single philosophy: **PHP orchestrates, C computes**.

```
Your PHP Application
        │
        ▼
   Pml\Tensor / Pml\Dataset      ← zero-copy PHP wrappers
        │
        ▼  PHP FFI (single boundary crossing per op)
   libtensor.so                  ← C tensor engine
        │
        ├── OpenBLAS              ← BLAS / LAPACK kernels
        ├── LAPACKE               ← eigendecomposition, SVD
        ├── OpenMP                ← multi-threaded batch ops
        └── AVX2                  ← SIMD acceleration

```

Every tensor lives as a `TensorC*` in C memory. PHP holds a reference pointer — never a copy. There are no PHP arrays in any hot path.

---

Why PML Exists
--------------

[](#why-pml-exists)

Modern ML stacks assume Python. This assumption carries hidden costs in PHP-first environments:

Pain PointPython StackPMLCold-start overhead200–800 ms (interpreter + runtime imports)&lt; 5 ms (PHP + FFI)Memory per inference150–400 MB baseline8–20 MB baselineDeployment surfacePython runtime + venv + pipPHP + one `.so` filePHP integrationIPC, REST, or subprocessNative function callCPU parallelismGIL-constrainedOpenMP, zero-GILIf you run PHP backends, PML lets you **embed ML directly** — same process, same memory space, same request lifecycle.

---

Technical Highlights
--------------------

[](#technical-highlights)

### Zero-Copy Tensor Architecture

[](#zero-copy-tensor-architecture)

```
// CSV loaded via mmap into C memory — no PHP arrays
$ds = Dataset::fromCSV('/data/train.csv');

// Tensor wraps TensorC* — no PHP-side copy
$X  = $ds->samples();  // Pml\Tensor → TensorC* view

// All math crosses FFI exactly once per operation
$out = $X->matmul($W)->add($b)->relu();
```

`Tensor` is a thin PHP object holding a `\FFI\CData` pointer. Slices, views, and column extractions reuse the same memory buffer with reference counts tracked entirely inside C.

### Native C Tensor Engine

[](#native-c-tensor-engine)

`libtensor.so` provides:

- **500+ exported C functions** across tensor ops, dataset I/O, inference, autograd, graph execution, and tokenization
- **Fused kernels**: `addRelu`, `fusedAdamStep`, `fusedBceLoss`, `qw_dot_group` (INT8 + fp32 scale)
- **AVX2 SIMD** sigmoid, tanh, exp, INT8 dot product
- **OpenBLAS SGEMM** for all matmul on contiguous float32 tensors
- **OpenMP** threaded batch operations, tree predictions, image pipelines
- **mmap CSV loader**: ingests multi-GB datasets without touching PHP memory

### LLM Inference Engine

[](#llm-inference-engine)

```
$tok     = Tokenizer::fromJson('/models/llama3-8b/tokenizer.json');
$session = InferenceSession::load('/models/llama3-8b', tok: $tok);

// GQA forward pass, KV-cache, streaming tokens
foreach ($session->generate("Explain AVX2:", maxNewTokens: 200) as $token) {
    echo $token;
}
```

- LLaMA / Mistral / Phi architecture support
- **GQA** (Grouped Query Attention) natively in C
- **Multi-layer KV-cache** (`MultiKVCache`) — eliminates O(T²) decode cost
- Milakov online-softmax: O(head\_dim) working memory
- SafeTensors mmap weight loading — zero-copy model ingestion
- **INT8 block quantization** (Q8\_0-class): 4× memory reduction, AVX2 fused kernel

### Classical ML at Native Speed

[](#classical-ml-at-native-speed)

```
$pipeline = new Pipeline(
    transformers: [new StandardScaler(), new PolynomialExpander(degree: 2)],
    estimator:    new GBDTClassifier(trees: 500, maxDepth: 6)
);

$pipeline->train($dataset);
echo $pipeline->score($test);  // accuracy, AUC, F1
```

GBDT with histogram subtraction + PQ leaf-wise growth. All split-finding runs in C.

---

Feature Matrix
--------------

[](#feature-matrix)

ModuleDescription**Tensor**200+ ops: creation, arithmetic, linear algebra, shape, reductions, fused kernels**Dataset**Zero-copy mmap CSV, ETL/DataFrame mode, stratified splits, DataLoader, streaming**Estimators**19 classifiers, 15 regressors, 6 anomaly detectors, 5 clusterers, decomposition**Transformers**Scalers, encoders, NLP vectorizers, image transforms, feature selection, imputers**Neural Networks**29 layer types, 9 optimizers, 5 losses, early stopping, callbacks, mixed precision**Quantization**INT8 block quantization, QuantizedTensor, Dense::quantize(), Sequential::quantize()**Inference**LLM forward pass, GQA, KV-cache, BPE tokenizer, SafeTensors I/O, streaming**Vision**106 C functions: image I/O, augmentation, MobileNetV3, YOLO11n, NanoDet, FastSAM**Pipeline**Transformer composition, 6 CV strategies, GridSearch, ensemble, BootstrapAggregator**Autograd**Reverse-mode AD, compute graph, Variable API---

Installation
------------

[](#installation)

### Requirements

[](#requirements)

DependencyVersionPurposePHP≥ 8.1Runtimeext-ffianyC bridgeGCC≥ 11Compile backendlibopenblas-devanyBLAS kernelsliblapacke-devanyLinear algebraLinux x86\_64—AVX2 / OpenMP```
# Ubuntu / Debian
sudo apt install gcc libopenblas-dev liblapacke-dev

# Install PHP library
composer require ghostjat/pml

# Build the C backend (once per machine)
cd vendor/ghostjat/pml/src/Lib
gcc -O3 -march=native -mfma -fopenmp -funroll-loops -fomit-frame-pointer \
    -D_GNU_SOURCE -shared -fPIC -funsafe-math-optimizations \
    -o libtensor.so.7 tensor.c dataset_io.c inference.c autograd.c graph.c tokenizer.c \
    -lopenblas -llapacke -lm
ln -sf libtensor.so.7 libtensor.so
```

**`php.ini` settings:**

```
ffi.enable        = true
memory_limit      = 2G
opcache.jit       = tracing
opcache.jit_buffer_size = 128M
```

---

Quick Start
-----------

[](#quick-start)

### Classical Classification

[](#classical-classification)

```
