Search by

skein / std

frodeborli

Building blocks for designing neural networks by hand in PHP on top of ext-buffers and libskein (php-skein): composites (norms, activations, rotary embeddings, attention), safetensors, tokenizers, quantised weights, model builders (Llama, Qwen3.5) and a generation loop.

0.1.0-beta1 2026-11-30 06:04 UTC

This package is auto-updated.

Last update: 2026-11-30 07:54:19 UTC


README

Building blocks for designing neural networks by hand in PHP, on top of libskein's PHP extension (../, namespace Skein\) and ext-buffers (Buffers\: tensors and dtypes), with any of libskein's backends underneath (reference, ggml, pjrt). Package skein/std (composer require skein/std; the extensions: pie install frodeborli/ext-buffers, then pie install skein/ext-skein; see docs/install.md). What works today, measured, and what is missing: STATUS.md. PHP 8.3 or later; ext-mbstring is required. Licence: MIT OR Apache-2.0 (LICENSE-MIT, LICENSE-APACHE).

The goal is not "run this model". It is that the library has what it takes for you to write the model yourself: every layer in src/models/ is ordinary PHP over the primitives (MatMul, Where, Sum, Take, ...), and loading a checkpoint is only a consumer that proves the building blocks are complete. What had to exist, and why it is a composite and not a new primitive, is in docs/feature-ledger.md.

$model = Skein\models\load('/models/Qwen3.5-0.8B', Buffers\DType::Float32);     // config.json + safetensors (sharded or not), text only
$tok   = Skein\tokenizers\load('/models/Qwen3.5-0.8B');
$gen   = new Skein\models\Generator($model, maxLen: 2048);                       // owns the caches; one fixed-shape graph for every token
foreach ($gen->generate($tok->encode($prompt), 100, ['temperature' => 0.7, 'top_p' => 0.9]) as $id) {
    echo $tok->decode([$id]);
}

The dtype given to load() is the dtype the weights are held in (and the key/value caches); the activations are Float32 whatever it is (round 83, llama.cpp's definition of an F16 model): a product reads the narrow weight as it is, ggml's Float16 weight times Float32 activation, XLA's dot of the weight and the activation rounded to its dtype where the matmul precision allows it. A model being trained (trainable(), the Trainer) computes in its dtype.

php examples/generate.php <model-dir> "prompt" [--dtype=float16 --cuda --graph --embed-on-host (deprecated) --tokens=N --temperature=T --chat].

The model's graphs run in a Project (README-PHP.md, "Settings: the Project"): the default project above; a project of your own, with its devices and settings, at load: load($dir, project: new Skein\Project('ggml:ggml-cuda:0'), name: 'chat', rank: 'interactive', slots: 8, settings: ['maxBatch' => 8]) (or $project->load($dir, ...)). A model's settings are given there and do not change. Trainer(project:, settings:) and StableDiffusion($dir, $project) take theirs the same way.

What is in it

src/*.php, src/linalg/, src/fft/, src/nn/functional/ the composites: one class each, extending Expression, built from the extension's operation classes (RmsNorm, LayerNorm, Silu, Gelu, Softplus, Softmax, Rope, Attention, AttentionKv, GatedDeltaRule, CausalConv1d, MatMulNbits are the extension's): L2Normalize, LogSoftmax, Relu, Mean, Abs, Min, Rsqrt, RepeatInterleave, RopeCosSin (->cos, ->sin: the tables of Rope), AddRmsNorm (->norm, ->sum), CacheSet, CacheSetChunk, Iota, TrilMask, Checkpoint, Sort, ... Each is a few lines: they are meant to be read. A multi-result composite names its results as properties ($qr = new linalg\Qr($a); $qr->q, $qr->r). src/linalg/ and src/fft/ are Skein\linalg\* and Skein\fft\* (LuFactor: ->l, ->u, ->perm, ->sign; Fft: ->real, ->imag)
src/functions.php what is not a recipe: seed(), rope_inv_freq() (a table of numbers), random_blocks()
src/quantized.php the loaders of 4-bit weights for MatMulNbits (a named operation: on ggml the weight's blocks with ggml's products, dequantise-and-multiply elsewhere), DequantizeNbits, repack_zero_points()
Skein\safetensors\ wrappers of libskein's Skein\load() / save(): open() (a Weights object: mapped read-only tensors, sharded index, metadata, single rows, converted copies, quantised layouts by name), load() (a Graph with outputs and no inputs), save()
Skein\data\ documents as arrays (reading files is the caller's: plain PHP, or charm/jsonl, charm/csv, charm/parquet), split(), Tokens, Loader (packing with document boundaries, a seeded order, fixed shapes, a resumable position), Prefetch (the next batch made while the device computes). examples/finetune_lora.php: Llama 3.2 1B + LoRA on dolly-15k with validation, checkpoints and resume, exported to GGUF
Skein\gguf\ Weights (a GGUF file's tensors under Hugging Face names, its configuration and tokenizer), save() (a GGUF writer), export() (Llama, Qwen2, Qwen3 as llama.cpp's converter and llama-quantize write them: BF16/F16/F32, Q8_0, Q4_K)
Skein\tokenizers\ load(): byte-level BPE from tokenizer.json (regex Split, Digits, ByteLevel, NFC/NFD/NFKC/NFKD/Lowercase, added tokens, template post-processing); checked against Hugging Face tokenizers on 2 corpora
Skein\models\ llama() (Llama, SmolLM2, Mistral, Qwen2/3 ...), qwen3_5() (hybrid gated delta-rule + gated GQA), load($dir) (dispatch on model_type), Quantized (compressed-tensors int4), Generator (state, computeInto, CUDA graphs, ping-pong state), Sampler
Skein\nn\ layers (docs/glossary.md: a layer is an Expression built with its own Parameters, on its input; each extends Expression, there is no base class; the properties holding them name their Parameters, name: overrides): Linear, Conv1d, Conv2d, ConvTranspose2d, BatchNorm2d, LayerNorm, RMSNorm, GroupNorm, Dropout, Embedding, LSTM, GRU, MultiheadAttention, TransformerBlock, pooling, activations; parameters() (the named Parameters of an Expression, found by walking it), state_dict(), load_state_dict() (Dropout and BatchNorm2d read the Bool Input training); the same computations as classes of their parameters (PyTorch's layouts; torch.nn.functional's counterpart, namespace Skein\nn\functional): Affine, Embedding, Dropout, Conv1d, Conv2d, BatchNorm (->y, ->mean, ->var), Mlp, TransformerBlock, Lstm (->y, ->h, ->c), Gru, the losses; Skein\nn\init\: PyTorch's initialisation formulas (xavier, kaiming, linear_weights, conv2d_weights) from Philox numbers
Skein\train\ Parameters, Lora, the optimizers SGD, Adam, AdamW, Lion, Adafactor, RMSprop, Adagrad (hyperparameters are run inputs; global-norm clipping; gradient accumulation), Schedule, Rng (Philox seed and offset as Parameters of the graph), Trainer (an Expression, a Graph or a CausalLM), Checkpoint (save and resume as safetensors). Checked against PyTorch: tests/ToolkitTest.php

A model is a recipe: $model->decoder($maxLen) returns one Graph over T tokens (tokens of shape [seq], T symbolic and bounded by $maxLen) with the key/value caches and recurrent states as inputs and their new values as outputs (out.<state>), plus the logits of the last token and the greedy next. Prompt processing and decoding run the same graph: a backend that compiles per shape (pjrt, ggml) keeps one plan per T it sees, and the plans share one copy of the weights. Generator feeds a prompt in chunks (option prefillChunk, 512 by default, halved when a chunk does not fit; on pjrt the remainder goes as powers of two, so the number of plans stays small) and decodes with T = 1.

Memory, start-up and the cache directory

Weights::converted() (a weight in the compute dtype) and the repacked zero points are computed once per checkpoint and kept as files in SKEIN_STD_CACHE_DIR (default ~/.cache/skein-std; from 4 KB up; keyed by the checkpoint file's path, size and modification time, the tensor and the conversion) and mapped read-only from there: they are page cache, not anonymous memory (a 27B model: 11 GB less anonymous memory, and a second process does not convert or repack again). Generator option sampleK keeps the top-K selection on the device. The key/value caches are updated in place (AttentionKv, CausalLM::inPlaceStates()).

Verified

All numbers measured on this machine (2 x 14 core Xeon E5-2697v3, RTX 3090). The rows that name onnxruntime were measured with its plugin, which no longer exists.

Model Check Result
tiny Llama and tiny Qwen3.5 (random weights, tests/data, made by transformers) logits of an 11 token sequence, every greedy token match transformers within 2e-4 on the reference backend, 2e-3 on ggml (matmul precision 'high') (run in the test suite)
SmolLM2-135M from its model.safetensors 50 greedy tokens vs transformers identical
Qwen3.5-0.8B (bf16 checkpoint, computed in Float32) logits at the last prompt token, 4 prompts max abs difference 1.4e-5 to 3.5e-5 (logits up to 30); 50 greedy tokens identical for all 4 prompts (measured with onnxruntime); first tokens identical on the reference backend
Qwen3.8-27B AWQ-INT4 (compressed-tensors, group 32), first 4 layers logits vs transformers on dequantised weights 1.8e-5 (CPU, Float32, MatMulNBits), 9.6e-3 (GPU, Float16)
Qwen3.8-27B AWQ-INT4, all 64 layers, RTX 3090 40 greedy tokens x 3 prompts vs vLLM 0.26 (same checkpoint, float16) identical

Speed of the 27B on the 3090 (ggml-cuda, Float16, numerics auto: the 4-bit products as the loader's Q4_1 with Q8_1 activations, sampleK 8, tools/bench-qwen27b.sh): 35.8 tokens/s plain greedy, 61.9 with mtp 3 (acceptance 70%); first token 8.3 s warm, 54 s with a cold page cache. The onnxruntime plugin (removed) did 40.8 and 56 (first token 37.8 s warm). Host memory while the weights are uploaded: one weight at a time is made on the host (the plugin repacks each 4-bit weight into its blocks as it uploads it).

Speculative decoding (Generator option mtp)

Qwen3.5 checkpoints carry a multi-token-prediction layer (mtp.*). new Generator($model, $maxLen, [..., 'mtp' => $k]) drafts $k tokens with it and verifies them in one pass of the model over $k + 1 positions (one graph per verification step, Qwen3_5::speculative()), greedy only. On the 27B (3090, 512 or 4096 tokens of context; measured with onnxruntime; on ggml k = 3 gives 61.9):

k tokens/s drafts accepted tokens per step
0 (plain greedy) 31.4 1
1 40.7 87% 1.87
2 51.6 80% 2.60
3 56.0 70% 3.08
4 49.8 64% 3.56

Identity: the tokens are those of plain greedy decoding except at fp16 ties: where the two highest logits are within two steps of Float16 at that size, the batched verification (other matrix kernels than the single-token step, which sum in another order) may round the other way and pick the other token. On the 27B the first such place in the test prompt is token 134 (the two logits 0.0156 apart, one Float16 step); everything before it is identical for every k, and k = 4 was identical over all 256 tokens. Skein\models\internal\greedy_agrees() compares two runs this way (tests/ModelsTest.php uses it, with Qwen3.5-0.8B: identical for k = 1..3). The same holds for a model split across backends by the placement: SmolLM2 over two backends differs from transformers at one token of one prompt, where float32 transformers has the two logits 0.020 apart.

Not done, and why

See the ledger. In short: sampling beyond argmax runs in PHP; no MoE; only compressed-tensors int4 (not AutoAWQ's or GPTQ's layouts); no vision; the prompt goes through the step graph one token at a time unless prefillChunk is set (chunked prefill is a second graph and so a second set of weights on a GPU).

Tests

tests/run.sh (BUILD: a build of the three extensions by tools/build.sh, default /tmp/skein-build), with SMOL_DIR, QWEN35_DIR, SD_DIR (bk-sdm-tiny) and SKEIN_MODELS (a folder of Hugging Face models, default ~/models) for the tests that use real models. tests/tools/make_tiny_models.py regenerates the transformers reference data.

Licence

Dual-licensed under the MIT licence or the Apache License 2.0, at your option (SPDX-License-Identifier: MIT OR Apache-2.0). MIT so that code can move into projects such as llama.cpp and ggml; Apache-2.0 for its explicit patent grant (there are no patent plans). Vendored third-party files keep their own licences: core/include/dlpack.h and plugins/pjrt/third_party/pjrt_c_api.h are Apache-2.0.

Unless you state otherwise, a contribution you submit for inclusion is dual-licensed in the same way, without further terms. Sign off each commit (git commit -s) to certify the Developer Certificate of Origin.