KenExp-Coder-113M

KenExp-Coder-113M is a 113.4M-parameter (~37M active parameters per token) Small Language Model (SLM) built from scratch in PyTorch for code generation, debugging, and long-context code comprehension (24,576-token context window).

Inspired by DeepSeek-V4-Flash architectural and optimization efficiency, it combines Manifold-Constrained Hyper-Connections (mHC), Fine-Grained Mixture-of-Experts (MoE) with auxiliary-loss-free load balancing, 5:1 Grouped-Query Attention (GQA), progressive 24K RoPE context extension, and the Muon orthogonalized momentum optimizer.


Model Architecture

Specification Value
Total Parameters 113,360,480 (~113.4M)
Active Parameters / Token ~37M (Dense Spine + Shared Expert + Top-2 Routed Experts)
Checkpoint Precision & Size bfloat16 (226.8 MB in model.safetensors)
Transformer Layers 10 Blocks
Hidden Dimension (d_model) 640
Attention Mechanism Grouped-Query Attention (10 Query Heads, 2 KV Heads, head_dim = 64)
Residual Topology 4-Stream mHC (Sinkhorn-Knopp doubly-stochastic stream mixing)
Feed-Forward / MoE 1 Shared SwiGLU Expert (inter_dim = 640) + 8 Routed SwiGLU Experts (inter_dim = 384, top_k = 2)
Expert Load Balancing Auxiliary-loss-free dynamic router bias adjustment
Positional Encoding Rotary Position Embeddings (RoPE, base = 1,000,000.0)
Maximum Context Window 24,576 tokens (24K)
Tokenizer & Vocabulary tiktoken (gpt2 BPE, 50,304 padded vocabulary)

Key Architectural Highlights

  1. Manifold-Constrained Hyper-Connections (mHC): Replaces the standard single residual stream with 4 parallel residual streams mixed via a 5-iteration Sinkhorn-Knopp doubly-stochastic projection, improving gradient propagation and representational capacity without bloating parameter count.
  2. Fine-Grained MoE with Aux-Loss-Free Routing: Routes every token through 1 dedicated shared expert while dynamically selecting the top 2 out of 8 specialized experts via bias-adjusted sigmoid gating—preventing auxiliary loss interference with next-token cross-entropy.
  3. 5:1 KV-Cache Compression (GQA): Shares 2 key-value heads across 10 query heads, keeping long-context KV-cache memory minimal during 24K inference.
  4. Hybrid Muon + AdamW Optimization: Trained using Newton-Schulz 5-step orthogonalized momentum (Muon) on all 2D hidden matrices and AdamW on embeddings, RMSNorm parameters, routers, and mHC matrices.

Training Pipeline & Datasets

KenExp-Coder-113M was trained from scratch via a 3-stage curriculum designed for fast convergence and stable 24K context generalization:

Stage Objective & Context Dataset(s) Volume & Details
Stage 1: Code & Reasoning Pre-training Base syntax, algorithms, and technical English at 2,048 context (rope_base = 10,000) codeparrot/codeparrot-clean (85%) + HuggingFaceFW/fineweb-edu sample-10BT (15%) ~82M tokens (2,500 steps × 32,768 tokens/step) with cosine LR decay and torch.compile
Stage 1.5: 24K Context Extension Long-range code dependency adaptation at 24,576 context (rope_base = 1,000,000) Mixed Python & technical corpus (codeparrot-clean + fineweb-edu) ~6M long-context tokens (120 steps × 49,152 tokens/step) with activation checkpointing and chunked cross-entropy
Stage 2: Agentic Coding & Debugging SFT Multi-turn bug fixing, step-by-step reasoning, and complete code generation up to 24,576 context DSFFGFG456/fable-5-coding-and-debugging-traces 3,000 length-bucketed trajectories trained with final-assistant-only loss masking (-100 on prior turns) to prevent overfitting on cumulative trajectory prefixes

Training Hardware & Efficiency

  • GPU: 1× NVIDIA GeForce RTX 4090 (24 GB GDDR6X VRAM, CUDA 13.0)
  • CPU & System RAM: 24-core CPU, 30 GB System RAM
  • Precision & Memory Optimizations: Native bfloat16 mixed precision, TF32 tensor cores, selective gradient checkpointing (>4,096 tokens), and 4,096-token chunked cross-entropy computation (reducing 24K logit peak memory from 4.61 GiB to <0.8 GiB)
  • Total Wall-Clock Training Time: ~40 minutes end-to-end
    • Stage 1 Pre-training: 25–28 minutes (50K–80K+ tok/s)
    • Stage 1.5 24K Context Extension: ~8 minutes
    • Stage 2 Agentic SFT (length-bucketed): ~4 minutes

Capabilities & Intended Use

Capabilities

  • Python Code Generation & Algorithms: Writes clean Python functions, data structures, and algorithmic solutions with ultra-low latency.
  • Debugging & Code Repair: Fine-tuned on multi-turn debugging traces to identify edge-case bugs (off-by-one bounds, loop termination issues) and emit complete, non-truncated fixes.
  • 24K Long-Context Ingestion: Processes multi-file prompts and long traces up to 24,576 tokens with minimal KV-cache footprint.
  • Ultra-Low Resource Footprint: Fits in <500 MB VRAM in bfloat16 and runs at high token speeds on consumer GPUs or modern CPUs.

Limitations

  • SLM Scale: With 113.4M total parameters (~37M active) trained from scratch on ~88M pre-training tokens, this model is built for research, architectural experimentation (Muon + mHC + aux-loss-free MoE), and lightweight local coding tasks rather than replacing 7B–70B+ frontier coding models.
  • Language Focus: Primarily trained on Python and technical English; performance on other programming languages will be lower.

Quickstart Usage

pip install torch tiktoken safetensors huggingface_hub
import importlib.util
import tiktoken
import torch
import torch.nn.functional as F
from huggingface_hub import hf_hub_download

REPO_ID = "KenSensei/KenExp-Coder-113M"
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"

# Download and load standalone modeling_kenexp.py architecture
mod_path = hf_hub_download(repo_id=REPO_ID, filename="modeling_kenexp.py")
spec = importlib.util.spec_from_file_location("modeling_kenexp", mod_path)
modeling_kenexp = importlib.util.module_from_spec(spec)
spec.loader.exec_module(modeling_kenexp)

model = modeling_kenexp.load_kenexp_coder(REPO_ID, device=DEVICE)
enc = tiktoken.get_encoding("gpt2")
EOT = enc.eot_token

prompt = "<|user|>\nWrite a Python function to merge overlapping intervals.\n<|assistant|>\n"
ids = enc.encode_ordinary(prompt)
x = torch.tensor([ids], dtype=torch.long, device=DEVICE)

with torch.no_grad():
    for _ in range(256):
        logits = model(x[:, -24576:])[:, -1, :] / 0.25
        v, _ = torch.topk(logits, 40)
        logits[logits < v[:, [-1]]] = -float("inf")
        next_tok = torch.multinomial(F.softmax(logits, dim=-1), num_samples=1)
        x = torch.cat([x, next_tok], dim=1)
        if next_tok.item() == EOT:
            break

print(enc.decode(x[0, len(ids):].tolist()).replace("<|endoftext|>", ""))
Downloads last month
-
Safetensors
Model size
0.1B params
Tensor type
BF16
·
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Datasets used to train KenSensei/KenExp-Coder-113M