PyTensorForge is a Python-based deep learning and model experimentation framework focused on neural networks, transformer architectures, and efficient inference workflows. The project combines foundational tensor operations with modern training, tokenization, export, and serving capabilities for research-oriented AI development.
The framework is designed for developers and researchers who want to explore machine learning concepts in a modular environment while also supporting practical LM workloads such as training, checkpointing, tokenization, generation, and deployment of OpenAI-compatible model servers.
PyTensorForge includes:
- Core tensor and numerical primitives
- Neural network layers and parameter management
- Activation functions and optimizer logic
- Model training and validation workflows
- GPT-style transformer implementations
- Tokenization, dataset preparation, and context extension
- Inference runtime and HTTP model serving
- Tensor, scalar, vector, and matrix abstractions
- Dense network layers and parameter-driven computation
- Basic activation functions including ReLU, Sigmoid, Tanh, ELU, and SELU
- Optimizers such as SGD
- Loss functions for regression and classification tasks
- Decoder-only GPT model architecture
- Tokenizer training and BPE byte-level tokenization
- Streaming dataset preparation and sharded corpora
- Checkpoint-based training and resumption
- Model export for inference use cases
- Generation runtime with KV-cache support and context length extension
- OpenAI-compatible server interface for deployment
- CLI tooling for training, evaluation, export, generation, and serving
- Model inspection and validation utilities
- Config-driven execution for reproducible setups
- Support for chat templates and assistant-style supervised finetuning patterns
pip install pytensorforgefrom pytensorforge.core.Tensor import Tensor
from pytensorforge.models.seq.Sequential import Sequential
from pytensorforge.neural.Dense import Dense
X = Tensor([[0,0],[0,1],[1,0],[1,1]], requires_grad=False)
y = Tensor([[0],[1],[1],[0]], requires_grad=False)
model = Sequential()
model.add(Dense(8, activation="relu"))
model.add(Dense(1, activation="sigmoid"))
model.compile(optimizer="adam", loss="binary_crossentropy")
model.fit(X, y, epochs=2000)
print(model.predict(X).data)from pytensorforge.core.Tensor import Tensor
from pytensorforge.models.seq.Sequential import Sequential
from pytensorforge.neural.Dense import Dense
X = Tensor([[1],[2],[3],[4],[5]], requires_grad=False)
y = Tensor([[2],[4],[6],[8],[10]], requires_grad=False)
model = Sequential()
model.add(Dense(16, activation="relu"))
model.add(Dense(1))
model.compile(optimizer="adam", loss="mse")
model.fit(X, y, epochs=3000)
print(model.predict(Tensor([[6]], requires_grad=False)).data)from pytensorforge.inference.runtime import load_model
gen = load_model("exports/my-gpt")
print(gen.generate("Once upon a time", max_new_tokens=50).text)
gen.stop()src/core/– tensor and numeric primitivessrc/neural/– neural layers and parameterssrc/activations/– activation implementationssrc/optimizers/– optimization routinessrc/loss/– loss functionssrc/initializers/– initialization strategiessrc/models/– model definitions, including transformer and regression codesrc/tokenization/– tokenizer implementations and training utilitiessrc/data/– corpus, sharding, streaming, validation, and dataset utilitiessrc/training/– training pipeline and checkpoint managementsrc/inference/– generation runtime, cache handling, and model executionsrc/serving/– HTTP serving infrastructure and API configurationsrc/scaling/– scaling utilitiesconfigs/– model and training configuration filespredict/– prediction utilities and sample datatest/– project-level examples and validation scriptsweb/– frontend assets for model interaction
- Python 3.10+
- NumPy
- PyYAML
Clone the repository and install it in editable mode:
git clone https://github.com/philipszdavido/PyTensorForge.git
cd PyTensorForge
pip install -e .This installs the pytensorforge CLI, which provides commands for training, evaluation, dataset preparation, generation, export, and serving.
pytensorforge train configs/train.yamlpytensorforge resume latest --config configs/train.yamlpytensorforge evaluate checkpoints/latest --config configs/train.yamlpytensorforge prepare-dataset data/corpus --tokenizer tokenizer.json --output data/shardspytensorforge export checkpoints/latest --output exports/my-gpt --tokenizer tokenizer.jsonpytensorforge generate exports/my-gpt --prompt "Once upon a time" --max-new-tokens 128pytensorforge serve exports/my-gpt --name my-gpt --host 127.0.0.1 --port 8000The server exposes an OpenAI-compatible interface at the configured host and port, allowing local or remote clients to interact with the model in a familiar API format.
A typical PyTensorForge workflow consists of:
- Training or preparing a tokenizer
- Building a dataset or sharded corpus
- Training a model with checkpoints enabled
- Exporting optimized checkpoints for inference
- Serving the model via the built-in API or generating responses directly
Options for reproducing the GPT-2/GPT-3 recipe. All are off by default, and with the defaults the model, the
optimizer and old checkpoints behave exactly as before (the first test in tests/test_gpt3_options.py pins
logits, parameter counts and three AdamW steps to the original numbers).
Model (model: in the training YAML, also fields of GPTConfig):
| Key | Default | What it does |
|---|---|---|
attention_bias |
false |
Adds biases to the q/k/v/output projections (+4 x d_model parameters per layer). |
attention_pattern |
dense |
alternating_local: even layers (0, 2, ...) are dense, odd layers see only the last local_window tokens, as in GPT-3's alternating dense and locally banded layers. |
local_window |
256 |
Tokens visible to a local layer, the current one included. The GPT-3 paper does not give a value; 256 is GPT-Neo's. |
init_std |
unset | Weights drawn from N(0, init_std) instead of Glorot-uniform. GPT-2/3 use 0.02 (positions get half of it, 0.01). |
residual_scaling |
false |
Scales the init of the attention output and fc2 by 1 / sqrt(2 x n_layers). Needs init_std. |
Training (training:):
| Key | Default | What it does |
|---|---|---|
adam_beta1, adam_beta2, adam_eps |
0.9, 0.999, 1e-8 |
AdamW constants. GPT-3 used beta2 = 0.95. |
no_decay_1d_params |
false |
Skip weight decay on biases and LayerNorm gains (all 1-D parameters). |
model:
attention_bias: true
attention_pattern: alternating_local
local_window: 256
init_std: 0.02
residual_scaling: true
training:
adam_beta2: 0.95
no_decay_1d_params: trueA local layer is computed as dense attention with a band mask. The maths and the learned behaviour are those of
banded attention, but there is no speed or memory saving. Training, evaluation and the KV-cache inference engine
(generate, serve) all honour the options, and the model options are checkpoint architecture fields, so a
checkpoint cannot be resumed or fine-tuned into a model with different ones. Run python -m unittest discover -s tests.
Contributions are welcome. Developers are encouraged to open issues, propose enhancements, or submit pull requests for bug fixes, feature additions, performance improvements, and documentation updates.
This repository does not currently include a dedicated LICENSE file in the root directory. Please consult the repository owner or project documentation for the applicable licensing terms before commercial or redistribution use.
PyTensorForge is a research-driven and experimentation-focused framework with support for both foundational ML primitives and modern transformer-based model workflows. It is best suited for learning, iterative development, and custom AI experimentation in a compact Python codebase.