Alx-1-400M

A 405M-parameter GPT trained completely from scratch for Python code generation, on a single free Kaggle T4.

405M params · 28 layers · 1024 context · 3 precisions: FP32 / FP16 / FP8 · safetensors


Highlights

  • Trained from scratch. No base model, no fine-tuning of someone else's weights. Random initialization to final checkpoint, in one notebook.
  • Python-focused. Instruction-style data (Task: ... Code: ...) mixed with 100M tokens of real-world GitHub Python.
  • Three weight formats, from 1.62 GB down to about 0.4 GB, with FP8 verified against FP32 (see Quantization).
  • Tiny and hackable. The whole architecture is about 100 lines of PyTorch in alx_model.py. No trust_remote_code, no custom framework.
  • Reproducible on free hardware. Total training budget was about 9 hours on one Kaggle T4 (16 GB).

Model summary

Developer alexjmt1
Architecture Decoder-only Transformer (GPT-2 style, pre-LayerNorm)
Parameters about 405M (embedding and output head are tied)
Layers / Heads / Width 28 / 16 / 1024
MLP 4x expansion (4096), GELU
Context length 1024 tokens
Positional encoding Learned absolute embeddings
Tokenizer GPT-2 BPE via tiktoken, vocab padded 50,257 to 50,304
Attention PyTorch SDPA (FlashAttention kernels when available), causal
Language English prompts, Python code
Precision (training) Mixed precision, fp16 autocast with GradScaler
License other; see License

Quick start

pip install torch safetensors tiktoken huggingface_hub

Load the FP16 weights (recommended default)

import sys
from huggingface_hub import snapshot_download

path = snapshot_download("alexjmt1/Alx-1-400M")
sys.path.insert(0, path)

from alx_model import load_alx1, ask

model = load_alx1(path, device="cuda", weights="model-fp16.safetensors").half()
print(ask(model, "Write a Python function to check if a number is prime.", device="cuda"))

Load the FP8 weights (smallest download)

from alx_model import load_alx1_fp8, ask

model = load_alx1_fp8(path, device="cuda")      # dequantized to fp16 on load
print(ask(model, "Write a Python function to merge two sorted lists.", device="cuda", max_new_tokens=300))

Load the FP32 weights (reference)

model = load_alx1(path, device="cuda", weights="model.safetensors")

Runs on CPU too

model = load_alx1(path, device="cpu", weights="model.safetensors")
print(ask(model, "Create a class for a stack with push and pop methods.", device="cpu"))

Prompt format

The model was trained on a fixed template. Use it, or quality drops sharply:

Task:
<your instruction>
Code:

ask() applies this template for you. If you call generate directly:

import tiktoken, torch
enc = tiktoken.get_encoding("gpt2")
ids = torch.tensor([enc.encode_ordinary("Task:\nReverse a linked list.\nCode:\n")], device="cuda")
out = model.generate(ids, max_new_tokens=300, temperature=0.3, top_k=20)
print(enc.decode(out[0].tolist()[ids.shape[1]:]))

Recommended sampling: temperature 0.2 to 0.4, top_k 20. Higher temperatures make a small model wander quickly. Generation stops at the GPT-2 end-of-text token (id 50256).

Example outputs

Real, unedited samples (FP8 weights, temperature 0.3, top_k 20, seed 0). The FP32 model produced token-for-token identical text for the same prompts and seed.

Prompt: Write a Python function to reverse a string.

def reverse_string(string):
    reversed_string = ""
    for i in range(len(string)-1, -1, -1):
        reversed_string += string[i]
    return reversed_string

Prompt: Write a Python function to merge two sorted lists.

def merge_sorted_lists(list1, list2):
    merged_list = []
    i = 0
    j = 0
    while i < len(list1) and j < len(list2):
        if list1[i] < list2[j]:
            merged_list.append(list1[i])
            i += 1
        else:
            merged_list.append(list2[j])
            j += 1
    while i < len(list1):
        merged_list.append(list1[i])
        i += 1
    while j < len(list2):
        merged_list.append(list2[j])
        j += 1
    return merged_list

Prompt: Write a Python function to check if a number is prime.

def is_prime(num):
    if num <= 1:
        return False
    for i in range(2,num):
        if num % i == 0:
            return False
    return True

These are simple, common tasks where the model does well. See Limitations for where it fails.

Files in this repository

File Size Description
model.safetensors 1.62 GB FP32 weights, the training-precision reference
model-fp16.safetensors 0.81 GB FP16 weights, best quality-to-size trade-off
model-fp8.safetensors about 0.4 GB FP8 (e4m3) weights with per-row scales; needs load_alx1_fp8
config.json 116 B Architecture hyperparameters
alx_model.py Model definition, loaders (load_alx1, load_alx1_fp8) and ask() helper

Training

Data

Source Role
iamtarun/python_code_instructions_18k_alpaca Instruction to code
flytech/python-codes-25k Instruction to code
Vezora/Tested-143k-Python-Alpaca Instruction to code (tested solutions)
codeparrot/codeparrot-clean 100M tokens of raw GitHub Python

Instruction samples were formatted as Task:\n{instruction + input}\nCode:\n{output}\n, tokenized once with GPT-2 BPE, stored as uint16 binaries, and shuffled by document. 0.5% of documents were held out for validation.

Hyperparameters

Optimizer AdamW (fused), betas (0.9, 0.95), weight decay 0.1 on matrices only
LR schedule Linear warmup 200 steps, then decay from 3e-4 to 3e-5
Batch size 16 sequences x 1024 tokens = 16,384 tokens / step (micro-batch 2, 8 accumulation steps)
Steps 9,495
Tokens seen about 156M
Precision fp16 autocast + GradScaler
Init GPT-2 style, with residual projections scaled by 1/sqrt(2 * n_layer)
Hardware 1x NVIDIA T4 (16 GB) on Kaggle, about 9 hours (time-budgeted run)
Throughput about 4.4k to 4.7k tokens/s

The learning-rate schedule is driven by max(step / max_steps, elapsed / time_budget), so the cosine-style decay always completes inside Kaggle's session limit.

Results

Split Loss (nats/token) Perplexity
Train 1.198 3.31
Validation 1.333 3.79

Loss is next-token cross-entropy on the GPT-2 tokenizer over the held-out mixture of instruction data and raw Python. It is not comparable to loss figures from models with different tokenizers or data.

No standard code benchmarks yet. HumanEval, MBPP and similar pass@k results have not been run for this model. Do not infer benchmark performance from the loss above.

Quantization (FP32 / FP16 / FP8)

Format Size Notes
FP32 1.62 GB Reference
FP16 0.81 GB Practically lossless (KL to FP32 about 2e-6)
FP8 about 0.4 GB e4m3, per-row scale, about 4x smaller than FP32

How the FP8 file is built: every 2-D weight matrix (attention, MLP, embeddings) is stored as float8_e4m3fn with one fp32 scale per row (w ~ q * scale, scale = max|row| / 448). LayerNorm weights and biases stay in fp16. The tied output head is stored once.

How it was checked. On a 60-token test sequence, FP8 agreed with FP32 on the top-1 next token at 100% of positions, with a KL divergence from FP32 of about 3.6e-4 (FP16: 2e-6). On four test prompts the FP8 model produced text identical to FP32. This is a sanity check on a small sample, not a full evaluation.

Important: this is FP8 storage. GPUs without FP8 compute (T4, V100, and older) cannot run it natively, so load_alx1_fp8 dequantizes to fp16 on load. You save disk space and download time; you only gain inference speed on hardware with FP8 support (Hopper, Ada, Blackwell) and a runtime that uses it.

Intended use

  • Learning and research on training small code LMs from scratch
  • A lightweight local Python snippet generator for simple tasks
  • A baseline for fine-tuning, distillation, quantization and interpretability experiments
  • A compact model for low-resource and edge-style demos

Limitations and known issues

Please read this before using the model for anything real.

  • It is a small model with a small training budget. About 156M tokens is far below a compute-optimal run for 405M parameters. Expect plausible-looking code that is sometimes wrong or incomplete.
  • Logic slips are common. For example, in testing it wrote a Stack.peek() that returns None in both branches, and a primality test that loops to n instead of sqrt(n).
  • Style drift. Some prompts (for example, Fibonacci) triggered a chatty "Here is a Python function that..." explanation instead of bare code, because of chat-style samples in the instruction data.
  • Naive algorithms. It often prefers the simplest solution, such as exponential recursion for Fibonacci, over an efficient one.
  • Short context. 1024 tokens total (prompt plus output). It cannot work with large files or repositories.
  • Python only. Other languages are weak or absent.
  • Not an instruction-tuned assistant. It follows the Task / Code template for short coding tasks. It is not a general chat model, and it does not reliably follow long, multi-requirement specifications.
  • No safety tuning. It has no RLHF, refusal training or content filter.
  • Always review, run and test generated code before you use it. Never run model output with elevated privileges or on untrusted inputs.

Bias, risks and licensing of training data

  • Training data includes public GitHub code under various licenses (via codeparrot-clean) and several community instruction datasets. The model may reproduce memorized snippets, including code under copyleft or restrictive licenses. Check the licenses of the source datasets before any commercial use.
  • Generated code may contain bugs, insecure patterns (injection, unsafe deserialization, hard-coded secrets) and outdated APIs.
  • Training text is overwhelmingly English; comments and identifiers reflect that.

License

Released under the license tag other. The model weights are trained on third-party datasets with their own terms (see Bias, risks and licensing). Review the licenses of the listed datasets before commercial use. If you need a specific license for your use case, open a discussion on this repo.

Reproducing

The full training notebook (data prep, training, safetensors export, FP8 export and upload) ran end to end on a free Kaggle T4. The architecture in alx_model.py is small enough to read in a few minutes and adapt.

Citation

@misc{alx1_400m_2026,
  title        = {Alx-1-400M: a 405M-parameter Python code language model trained from scratch},
  author       = {alexjmt1},
  year         = {2026},
  howpublished = {\url{https://huggingface.co/alexjmt1/Alx-1-400M}}
}

Acknowledgements

Architecture follows the GPT-2 lineage and the nanoGPT-style training recipe. Thanks to the authors of codeparrot/codeparrot-clean and the three Python instruction datasets, and to Kaggle for the free GPU time.

Downloads last month
57
Safetensors
Model size
0.4B params
Tensor type
F32
·
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Datasets used to train alexjmt1/Alx-1-400M