Downloads ยท 30 days
0
DexopT/neuro-symbolic-coder-13M
neuro-symbolic-coder-13M is a text generation model from DexopT. Use it when you need the model to write or continue text. It is set up for pytorch. The card lists the license as mit.
Downloads ยท 30 days
0
Access
Public
Updated Jul 25, 2026
Repo size
54 MB
Likes
0
Public
Click a slice to open those files.
.pt53.4 MB ยท 98%
From the Hugging Face model README

A 13.32M-parameter hybrid neuro-symbolic transformer that learns Python code generation from mathematical representations of Abstract Syntax Trees (ASTs). The model distills knowledge from a 9B-parameter reasoning LLM (Ornith/Qwen3.5-based) into a compact architecture trainable on consumer GPUs with only 6GB VRAM.
๐ Whitepaper: NeuroSymbolicCodeTransformer: A Neuro-Symbolic Transformer for Code Generation via Knowledge Distillation and REINFORCE Policy Gradient (PDF, 12 pages)
๐ GitHub Pages: dexopt.github.io/neuro-symbolic-coder-13M
The NeuroSymbolicCodeTransformer uses a three-phase pipeline: (1) a teacher LLM converts natural language requests into mathematical specifications, (2) a small neuro-symbolic model learns to map those specifications to AST token sequences via supervised learning, and (3) REINFORCE policy-gradient reinforcement learning refines the model using teacher-scored feedback.
The architecture introduces five custom neuron classes (LogicGate, LocalTree, Program, Routing, Memory) organized into MoE-routed transformer blocks. The entire model occupies only 25.4 MiB of VRAM at bfloat16 precision.
NeuroSymbolicCodeTransformer Pipeline
==============================================================
+------------+ +------------------+
User Request (English) ---->| Ornith 9B |-------->| Math Spec JSON |
| (Teacher) | +------------------+
+------------+ |
^ v
| +------------------+
| | Token Encoder |
| | (125+ vocab |
| | tokens) |
| +------------------+
| |
| v
| +------------------+
| | NeuroSymbolic |
| | Code Transformer |
| | (13.32M params) |
| +------------------+
| |
| v
| +------------------+
| | Token Decoder |
| | (AST tokens) |
| +------------------+
| |
| v
| +------------------+
| | ast_to_code |
| | (Python render) |
| +------------------+
| |
+------------+ v
| Validation |<---- Generated Python Code
| (Score) |
+------------+
Training Pipeline (3 Phases)
===========================
Phase 1: Data Generation Phase 2: Supervised Phase 3: REINFORCE RL
------------------------- ----------------------- --------------------------
Prompt --> Ornith 9B math_spec --> token enc random spec generation
| | |
v v v
Code --> MathEncoder NeuroSymbolicTransformer generate 2 candidates
| | |
v v v
MathSpec --> TokenEncoder cross-entropy loss Ornith scores each
| |
v v
Training Dataset best > threshold?
yes --> policy gradient
no --> skip
Input Tensor (B, S, D=320)
|
+-----v------+
| MultiHead | 4 heads, head_dim=80, batch_first
| Attention | dropout=0.1
+-----+------+
|
+-----v------+
| LayerNorm |
+-----+------+
|
+-----v------+
| Routing | Mean-pool --> 2-layer MLP --> 4-way softmax
| Neuron | noise injection during training
+-----+------+
|
+-----v------------------------------------+
| Expert Bank (weighted sum) |
| |
| [LogicGateNeuron] [ProgramNeuron] |
| [LocalTreeNeuron] [Linear Fallback] |
| |
+-----+------------------------------------+
|
+-----v------+
| LayerNorm |
+-----+------+
|
+-----v------+
| Memory | 32-slot differentiable memory
| Neuron | attention read + gated write
+-----+------+
|
Output (B, S, D=320)
| Neuron | Dimensions | Purpose | Mechanism |
|---|---|---|---|
| LogicGateNeuron | d_model -> d_model/2 -> d_model | Conditional AST nodes (if/else, boolean ops) | Projects input into two operand paths, applies AND/OR/XOR/NOT logic with learnable softmax weighting |
| ProgramNeuron | d_model -> d_model; 5 op chunks | Differentiable compute primitives | 5 parallel math operations (sum, product, max, min, mean) per chunk; learnable softmax over operations |
| LocalTreeNeuron | d_model; kernel=3 | Parent-child AST hierarchy | Depthwise Conv1d with sigmoid gating; local windows simulate tree branches |
| RoutingNeuron | d_model -> d_model/4 -> 4 | Expert dispatch | MoE-style gating: mean-pooled representation through 2-layer MLP to 4-way softmax; noise added during training |
| MemoryNeuron | 32 slots x d_model | Long-range dependency memory | Attention-based read over 32-slot memory bank; gated soft-update writes during training (decay=0.99, rate=0.01) |
| Parameter | Value |
|---|---|
| Total parameters | 13,320,345 |
| d_model (hidden dimension) | 320 |
| Number of heads | 4 |
| Head dimension | 80 |
| Number of layers (blocks) | 5 |
| Vocab size | 5,000 |
| Max sequence length | 512 |
| Memory slots per block | 32 |
| Dropout | 0.1 |
| Expert count | 4 (logic, program, tree, linear) |
| Precision | bfloat16 AMP |
| Gradient checkpointing | Yes (use_reentrant=False) |
Teacher Model:
Data Generation:
Supervised Training:
Reinforcement Learning:
RL Performance:
| Metric | Value |
|---|---|
| Best score | 100.00 / 100 |
| Average score | 28.33 / 100 |
| RL training time | ~59 minutes |
| Total training time | ~68 minutes |
VRAM Usage:
| Metric | Value |
|---|---|
| Model memory (bf16) | 25.4 MiB |
| Free VRAM | 4.9 GiB / 6.0 GiB |
Configuration:
Outcome:
Run A (remote server) completed the full training pipeline. Run B (local server) failed during data generation and is documented here for reproducibility reference.
| Component | File | Description |
|---|---|---|
| Configuration | config.py | Typed dataclass config with env presets (dev/training/inference), serialization |
| Math Encoder | math_encoder.py | Python source -> structured math spec via recursive AST traversal, 50+ node types |
| Token Encoder | token_encoder.py | MathSpec -> flat token sequences, 125+ structural markers, deterministic round-trip |
| Neuro-Symbolic Model | small_model.py | 13.32M param transformer with 5 custom neuron classes, gradient checkpointing |
| Training Pipeline | training_pipeline.py | Supervised + REINFORCE RL with LM Studio as teacher, batch training |
| Inference Service | inference_service.py | FastAPI server with /generate, /validate, /batch, /health endpoints |
| Inference CLI | infer.py | Command-line inference script |
| Orchestrator | main.py | Training entry point, device detection, checkpoint management |
| Test Suite | test_suite.py | 27 unit/integration tests |
| Memory Utils | memory_utils.py | VRAM monitoring, gradient accumulation helpers, AMP setup |
| Requirements | requirements.txt | PyTorch 2.0+, FastAPI, openai, uvicorn, pydantic, tqdm |
| Setup | setup.sh | One-command environment setup |
Codebase stats: 12 files, ~4,300 lines of Python, 27 tests (100% pass).
| Resource | Minimum | Recommended |
|---|---|---|
| GPU | NVIDIA RTX 4050 (6GB VRAM) | NVIDIA RTX 4060+ (8GB+ VRAM) |
| VRAM peak | ~500 MiB (bf16 AMP + gradient checkpointing) | ~1 GiB (with safety margin) |
| System RAM | 8 GB | 16 GB |
| CPU | Any modern x86-64 | AMD Ryzen / Intel Core i5+ |
| Storage | 2 GB | 5 GB (checkpoints + logs) |
Software requirements:
# Clone and setup
chmod +x setup.sh
./setup.sh
# Or manually
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
# Verify installation
python test_suite.py
The teacher LLM runs separately in LM Studio. The pipeline communicates with it via the OpenAI-compatible API.
curl http://localhost:1234/v1/models
For Run A, the teacher ran on a remote machine at 192.168.1.102:1234. Update config.py or pass --server to point to your LM Studio instance:
python main.py --server http://192.168.1.102:1234
# Full training pipeline (default: localhost:1234)
python main.py --server http://<lm-studio-host>:1234
# With custom model name
python main.py --server http://localhost:1234 --model ornith-1.0-9b
Training proceeds through three phases:
Checkpoints are saved to ./checkpoints/.
Edit config.py or create a JSON config file:
from config import Config
# Defaults (training env)
cfg = Config()
cfg.model.d_model = 320 # Transformer hidden dimension
cfg.model.n_layers = 5 # Number of blocks
cfg.model.n_heads = 4 # Attention heads
cfg.training.batch_size = 4 # Per-step samples
cfg.training.epochs = 20 # Supervised epochs
cfg.training.gradient_accumulation_steps = 4
cfg.rl.num_iterations = 20 # REINFORCE iterations
cfg.rl.num_candidates = 2 # Candidates per iteration
cfg.rl.score_threshold = 70.0 # Minimum score to trigger update
Start the FastAPI inference server:
python inference_service.py
The API runs on http://localhost:8000.
| Method | Path | Description |
|---|---|---|
POST | /generate | Generate code from natural language specification |
POST | /validate | Validate existing code against a specification |
POST | /batch | Batch code generation |
GET | /health | Service and LM Studio availability check |
Generate code from natural language:
curl -X POST http://localhost:8000/generate \
-H "Content-Type: application/json" \
-d '{
"specification": "Create a function that filters even numbers from a list",
"temperature": 0.7
}'
Validate existing code:
curl -X POST http://localhost:8000/validate \
-H "Content-Type: application/json" \
-d '{
"code": "def f(x): return [i for i in x if i % 2 == 0]",
"specification": "filter even numbers from list"
}'
Health check:
curl http://localhost:8000/health
python infer.py --prompt "Write a function to compute fibonacci numbers" --checkpoint ./checkpoints/best.pt
Instead of learning raw source code text, the model learns from mathematical representations of ASTs. The pipeline:
Each NeuroSymbolicTransformerBlock uses torch.utils.checkpoint.checkpoint with use_reentrant=False to trade compute for memory. This keeps peak VRAM at ~500 MiB despite the full model graph.
Requirements for reproduction:
python main.py --server http://<remote-lmstudio-ip>:1234 --model ornith-1.0-9b
Settings used: supervised epochs=5, patience=3, batch_size=4, grad_accum=4, bf16 AMP. RL iterations=30, candidates=2.
Run B attempted 1,000 examples from 20 cycled prompts on a local LM Studio instance. The server crashed repeatedly after 12 successful examples due to "Engine protocol predict request failed: fetch failed" errors. This appears to be an LM Studio stability issue under sustained chat/completions load. Using a remote server (Run A setup) resolves the problem.
@software{NeuroSymbolicCodeTransformer2026,
author = {},
title = {NeuroSymbolicCodeTransformer: A Neuro-Symbolic Transformer for Code Generation from AST Mathematical Specifications},
year = {2026},
url = {},
note = {13.32M parameters, trained with knowledge distillation from Ornith 9B via REINFORCE RL on RTX 4050},
keywords = {neuro-symbolic, code-generation, transformer, reinforcement-learning, mixture-of-experts, knowledge-distillation}
}
MIT License. See the repository for full terms.