Text Generation
PyTorch
English
jl_code_python
code
python
python-code
code-generation
code-completion
causal-language-modeling
decoder-only
programming-language-model
small-language-model
from-scratch
random-initialization
custom-architecture
custom-pytorch
byte-level-bpe
rope
rmsnorm
swiglu
consumer-gpu
rtx-3060
research
jumplander
jl-code
Upload jumplander_python_100m.py
Browse files- jumplander_python_100m.py +1446 -0
jumplander_python_100m.py
ADDED
|
@@ -0,0 +1,1446 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
JumpLander Python Decoder 100M
|
| 3 |
+
================================
|
| 4 |
+
A single-file, from-scratch Python code language model project.
|
| 5 |
+
|
| 6 |
+
- Randomly initialized decoder-only Transformer (~97.5M parameters)
|
| 7 |
+
- Custom Byte-Level BPE tokenizer trained from local JSONL files
|
| 8 |
+
- Local train/validation/test datasets beside this script
|
| 9 |
+
- Optional Hugging Face streaming preparation from Python-Edu + MBPP
|
| 10 |
+
- Smoke training, full training, resume, generation, and local web UI
|
| 11 |
+
- No pretrained model weights are loaded
|
| 12 |
+
|
| 13 |
+
This is an experimental research model. Training 100M parameters from scratch
|
| 14 |
+
requires substantial data and compute even though it fits on an RTX 3060 12GB.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import ast
|
| 21 |
+
import contextlib
|
| 22 |
+
import dataclasses
|
| 23 |
+
from dataclasses import dataclass
|
| 24 |
+
import hashlib
|
| 25 |
+
import html
|
| 26 |
+
import io
|
| 27 |
+
import json
|
| 28 |
+
import math
|
| 29 |
+
import os
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
import random
|
| 32 |
+
import re
|
| 33 |
+
import secrets
|
| 34 |
+
import sys
|
| 35 |
+
import threading
|
| 36 |
+
import time
|
| 37 |
+
import traceback
|
| 38 |
+
from typing import Any, Iterable, Iterator, Optional
|
| 39 |
+
import webbrowser
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
import numpy as np
|
| 43 |
+
except ImportError as exc:
|
| 44 |
+
raise SystemExit("Missing dependency: numpy. Run: pip install -r requirements.txt") from exc
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
import torch
|
| 48 |
+
import torch.nn as nn
|
| 49 |
+
import torch.nn.functional as F
|
| 50 |
+
from torch.utils.data import DataLoader, Dataset
|
| 51 |
+
from torch.utils.checkpoint import checkpoint as activation_checkpoint
|
| 52 |
+
except ImportError as exc:
|
| 53 |
+
raise SystemExit("Missing dependency: torch. Run: pip install -r requirements.txt") from exc
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# -----------------------------------------------------------------------------
|
| 57 |
+
# Paths: all generated files remain beside this single Python source file.
|
| 58 |
+
# -----------------------------------------------------------------------------
|
| 59 |
+
ROOT = Path(__file__).resolve().parent
|
| 60 |
+
TRAIN_JSONL = ROOT / "train.jsonl"
|
| 61 |
+
VALIDATION_JSONL = ROOT / "validation.jsonl"
|
| 62 |
+
TEST_JSONL = ROOT / "test.jsonl"
|
| 63 |
+
TOKENIZER_JSON = ROOT / "tokenizer.json"
|
| 64 |
+
TRAIN_BIN = ROOT / "train_tokens.bin"
|
| 65 |
+
VALIDATION_BIN = ROOT / "validation_tokens.bin"
|
| 66 |
+
SMOKE_CHECKPOINT = ROOT / "smoke_checkpoint.pt"
|
| 67 |
+
MODEL_CHECKPOINT = ROOT / "jumplander_python_100m.pt"
|
| 68 |
+
|
| 69 |
+
MODEL_NAME = "JumpLander Python Decoder 100M"
|
| 70 |
+
MODEL_ID = "jumplander-python-decoder-100m"
|
| 71 |
+
|
| 72 |
+
SPECIAL_TOKENS = [
|
| 73 |
+
"<pad>",
|
| 74 |
+
"<unk>",
|
| 75 |
+
"<bos>",
|
| 76 |
+
"<eos>",
|
| 77 |
+
"<file_start>",
|
| 78 |
+
"<file_end>",
|
| 79 |
+
"<fim_prefix>",
|
| 80 |
+
"<fim_suffix>",
|
| 81 |
+
"<fim_middle>",
|
| 82 |
+
"<instruction>",
|
| 83 |
+
"<response>",
|
| 84 |
+
]
|
| 85 |
+
|
| 86 |
+
SECRET_PATTERNS = [
|
| 87 |
+
re.compile(r"AKIA[0-9A-Z]{16}"),
|
| 88 |
+
re.compile(r"sk-[A-Za-z0-9_-]{20,}"),
|
| 89 |
+
re.compile(r"gh[pousr]_[A-Za-z0-9]{20,}"),
|
| 90 |
+
re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----"),
|
| 91 |
+
re.compile(r"(?i)(?:api[_-]?key|secret|password)\s*=\s*['\"][^'\"]{8,}['\"]"),
|
| 92 |
+
]
|
| 93 |
+
|
| 94 |
+
GENERATED_MARKERS = (
|
| 95 |
+
"generated file",
|
| 96 |
+
"auto-generated",
|
| 97 |
+
"autogenerated",
|
| 98 |
+
"do not edit",
|
| 99 |
+
"generated by",
|
| 100 |
+
"this file was generated",
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
# -----------------------------------------------------------------------------
|
| 105 |
+
# Configuration
|
| 106 |
+
# -----------------------------------------------------------------------------
|
| 107 |
+
@dataclass
|
| 108 |
+
class ModelConfig:
|
| 109 |
+
name: str = MODEL_NAME
|
| 110 |
+
vocab_size: int = 16_384
|
| 111 |
+
max_seq_len: int = 1_024
|
| 112 |
+
n_layers: int = 12
|
| 113 |
+
d_model: int = 768
|
| 114 |
+
n_heads: int = 12
|
| 115 |
+
d_ff: int = 2_048
|
| 116 |
+
rope_theta: float = 10_000.0
|
| 117 |
+
norm_eps: float = 1e-5
|
| 118 |
+
dropout: float = 0.0
|
| 119 |
+
tie_embeddings: bool = True
|
| 120 |
+
gradient_checkpointing: bool = True
|
| 121 |
+
|
| 122 |
+
def validate(self) -> None:
|
| 123 |
+
if self.d_model % self.n_heads != 0:
|
| 124 |
+
raise ValueError("d_model must be divisible by n_heads")
|
| 125 |
+
if (self.d_model // self.n_heads) % 2 != 0:
|
| 126 |
+
raise ValueError("attention head dimension must be even for RoPE")
|
| 127 |
+
if self.vocab_size > np.iinfo(np.uint16).max:
|
| 128 |
+
raise ValueError("This project stores token IDs as uint16; vocab is too large")
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
@dataclass
|
| 132 |
+
class TrainConfig:
|
| 133 |
+
batch_size: int = 1
|
| 134 |
+
gradient_accumulation: int = 32
|
| 135 |
+
learning_rate: float = 3e-4
|
| 136 |
+
min_learning_rate: float = 3e-5
|
| 137 |
+
weight_decay: float = 0.1
|
| 138 |
+
warmup_steps: int = 200
|
| 139 |
+
total_steps: int = 10_000
|
| 140 |
+
eval_interval: int = 250
|
| 141 |
+
eval_batches: int = 20
|
| 142 |
+
save_interval: int = 500
|
| 143 |
+
log_interval: int = 10
|
| 144 |
+
grad_clip: float = 1.0
|
| 145 |
+
seed: int = 1337
|
| 146 |
+
num_workers: int = 0
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
FULL_MODEL_CONFIG = ModelConfig()
|
| 150 |
+
SMOKE_MODEL_CONFIG = ModelConfig(
|
| 151 |
+
name="JumpLander Python Decoder Smoke",
|
| 152 |
+
max_seq_len=256,
|
| 153 |
+
n_layers=4,
|
| 154 |
+
d_model=256,
|
| 155 |
+
n_heads=4,
|
| 156 |
+
d_ff=768,
|
| 157 |
+
gradient_checkpointing=False,
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
# -----------------------------------------------------------------------------
|
| 162 |
+
# Utility functions
|
| 163 |
+
# -----------------------------------------------------------------------------
|
| 164 |
+
def require_optional(package: str, install_name: Optional[str] = None) -> Any:
|
| 165 |
+
try:
|
| 166 |
+
return __import__(package)
|
| 167 |
+
except ImportError as exc:
|
| 168 |
+
target = install_name or package
|
| 169 |
+
raise SystemExit(
|
| 170 |
+
f"Missing optional dependency: {target}. Run: pip install -r requirements.txt"
|
| 171 |
+
) from exc
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def seed_everything(seed: int) -> None:
|
| 175 |
+
random.seed(seed)
|
| 176 |
+
np.random.seed(seed)
|
| 177 |
+
torch.manual_seed(seed)
|
| 178 |
+
if torch.cuda.is_available():
|
| 179 |
+
torch.cuda.manual_seed_all(seed)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def atomic_write_jsonl(path: Path, rows: Iterable[dict[str, Any]]) -> int:
|
| 183 |
+
temp = path.with_suffix(path.suffix + ".tmp")
|
| 184 |
+
count = 0
|
| 185 |
+
with temp.open("w", encoding="utf-8", newline="\n") as handle:
|
| 186 |
+
for row in rows:
|
| 187 |
+
handle.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 188 |
+
count += 1
|
| 189 |
+
temp.replace(path)
|
| 190 |
+
return count
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def append_jsonl(path: Path, row: dict[str, Any]) -> None:
|
| 194 |
+
with path.open("a", encoding="utf-8", newline="\n") as handle:
|
| 195 |
+
handle.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def iter_jsonl(path: Path) -> Iterator[dict[str, Any]]:
|
| 199 |
+
if not path.exists():
|
| 200 |
+
raise FileNotFoundError(f"Dataset file not found: {path}")
|
| 201 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 202 |
+
for line_number, line in enumerate(handle, start=1):
|
| 203 |
+
line = line.strip()
|
| 204 |
+
if not line:
|
| 205 |
+
continue
|
| 206 |
+
try:
|
| 207 |
+
value = json.loads(line)
|
| 208 |
+
except json.JSONDecodeError as exc:
|
| 209 |
+
raise ValueError(f"Invalid JSON at {path.name}:{line_number}: {exc}") from exc
|
| 210 |
+
if not isinstance(value, dict):
|
| 211 |
+
raise ValueError(f"Expected a JSON object at {path.name}:{line_number}")
|
| 212 |
+
yield value
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def sha256_text(text: str) -> str:
|
| 216 |
+
return hashlib.sha256(text.encode("utf-8", errors="ignore")).hexdigest()
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def normalize_code(code: str) -> str:
|
| 220 |
+
code = code.replace("\r\n", "\n").replace("\r", "\n").replace("\x00", "")
|
| 221 |
+
lines = [line.rstrip() for line in code.splitlines()]
|
| 222 |
+
return "\n".join(lines).strip() + "\n"
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def contains_secret(code: str) -> bool:
|
| 226 |
+
return any(pattern.search(code) for pattern in SECRET_PATTERNS)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def looks_generated(code: str) -> bool:
|
| 230 |
+
head = code[:2_000].lower()
|
| 231 |
+
return any(marker in head for marker in GENERATED_MARKERS)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def looks_minified(code: str) -> bool:
|
| 235 |
+
lines = code.splitlines()
|
| 236 |
+
if not lines:
|
| 237 |
+
return True
|
| 238 |
+
longest = max(len(line) for line in lines)
|
| 239 |
+
average = sum(len(line) for line in lines) / len(lines)
|
| 240 |
+
return longest > 1_000 or average > 240
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def is_valid_python(code: str) -> tuple[bool, str]:
|
| 244 |
+
try:
|
| 245 |
+
ast.parse(code)
|
| 246 |
+
return True, "ok"
|
| 247 |
+
except SyntaxError:
|
| 248 |
+
return False, "syntax"
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def basic_code_filter(code: str, min_chars: int = 120, max_chars: int = 50_000) -> tuple[bool, str]:
|
| 252 |
+
if not isinstance(code, str):
|
| 253 |
+
return False, "not_string"
|
| 254 |
+
code = normalize_code(code)
|
| 255 |
+
if len(code) < min_chars:
|
| 256 |
+
return False, "too_short"
|
| 257 |
+
if len(code) > max_chars:
|
| 258 |
+
return False, "too_large"
|
| 259 |
+
if contains_secret(code):
|
| 260 |
+
return False, "secret"
|
| 261 |
+
if looks_generated(code):
|
| 262 |
+
return False, "generated"
|
| 263 |
+
if looks_minified(code):
|
| 264 |
+
return False, "minified"
|
| 265 |
+
valid, reason = is_valid_python(code)
|
| 266 |
+
if not valid:
|
| 267 |
+
return False, reason
|
| 268 |
+
return True, "ok"
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def likely_english(text: str) -> bool:
|
| 272 |
+
if not text or len(text.split()) < 4:
|
| 273 |
+
return False
|
| 274 |
+
ascii_letters = sum(ch.isascii() and ch.isalpha() for ch in text)
|
| 275 |
+
letters = sum(ch.isalpha() for ch in text)
|
| 276 |
+
if letters == 0:
|
| 277 |
+
return False
|
| 278 |
+
return ascii_letters / letters >= 0.90
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def extract_instruction_rows(code: str, source: str) -> list[dict[str, Any]]:
|
| 282 |
+
"""Extract function/class docstrings and their source as English->Python rows."""
|
| 283 |
+
rows: list[dict[str, Any]] = []
|
| 284 |
+
try:
|
| 285 |
+
tree = ast.parse(code)
|
| 286 |
+
source_lines = code.splitlines()
|
| 287 |
+
except SyntaxError:
|
| 288 |
+
return rows
|
| 289 |
+
|
| 290 |
+
for node in ast.walk(tree):
|
| 291 |
+
if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
| 292 |
+
continue
|
| 293 |
+
doc = ast.get_docstring(node, clean=True)
|
| 294 |
+
if not doc or not likely_english(doc):
|
| 295 |
+
continue
|
| 296 |
+
first_line = doc.strip().splitlines()[0].strip()
|
| 297 |
+
if len(first_line) < 20 or len(first_line) > 320:
|
| 298 |
+
continue
|
| 299 |
+
if first_line.lower().startswith(("todo", "fixme", "deprecated")):
|
| 300 |
+
continue
|
| 301 |
+
if not hasattr(node, "end_lineno") or node.end_lineno is None:
|
| 302 |
+
continue
|
| 303 |
+
start = max(0, node.lineno - 1)
|
| 304 |
+
end = min(len(source_lines), node.end_lineno)
|
| 305 |
+
function_source = "\n".join(source_lines[start:end]).strip()
|
| 306 |
+
if len(function_source) < 80 or len(function_source) > 8_000:
|
| 307 |
+
continue
|
| 308 |
+
valid, _ = is_valid_python(function_source)
|
| 309 |
+
if not valid:
|
| 310 |
+
continue
|
| 311 |
+
rows.append(
|
| 312 |
+
{
|
| 313 |
+
"type": "instruct",
|
| 314 |
+
"instruction": first_line,
|
| 315 |
+
"response": function_source + "\n",
|
| 316 |
+
"source": source,
|
| 317 |
+
"tests": [],
|
| 318 |
+
}
|
| 319 |
+
)
|
| 320 |
+
if len(rows) >= 8:
|
| 321 |
+
break
|
| 322 |
+
return rows
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def split_python_code(code: str, max_chars: int = 12_000) -> list[str]:
|
| 326 |
+
"""Keep small files whole; split large valid files at top-level AST boundaries."""
|
| 327 |
+
code = normalize_code(code)
|
| 328 |
+
if len(code) <= max_chars:
|
| 329 |
+
return [code]
|
| 330 |
+
try:
|
| 331 |
+
tree = ast.parse(code)
|
| 332 |
+
except SyntaxError:
|
| 333 |
+
return []
|
| 334 |
+
lines = code.splitlines()
|
| 335 |
+
imports: list[str] = []
|
| 336 |
+
chunks: list[str] = []
|
| 337 |
+
for node in tree.body:
|
| 338 |
+
if not hasattr(node, "end_lineno") or node.end_lineno is None:
|
| 339 |
+
continue
|
| 340 |
+
segment = "\n".join(lines[node.lineno - 1 : node.end_lineno]).strip()
|
| 341 |
+
if isinstance(node, (ast.Import, ast.ImportFrom)):
|
| 342 |
+
imports.append(segment)
|
| 343 |
+
continue
|
| 344 |
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
| 345 |
+
prefix = "\n".join(imports[-20:])
|
| 346 |
+
candidate = (prefix + "\n\n" + segment).strip() + "\n"
|
| 347 |
+
if 120 <= len(candidate) <= max_chars:
|
| 348 |
+
valid, _ = is_valid_python(candidate)
|
| 349 |
+
if valid:
|
| 350 |
+
chunks.append(candidate)
|
| 351 |
+
return chunks
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def serialize_training_row(row: dict[str, Any]) -> str:
|
| 355 |
+
row_type = row.get("type", "base")
|
| 356 |
+
if row_type == "instruct":
|
| 357 |
+
instruction = str(row.get("instruction", "")).strip()
|
| 358 |
+
response = str(row.get("response", "")).strip()
|
| 359 |
+
return f"<bos><instruction>\n{instruction}\n<response>\n{response}\n<eos>"
|
| 360 |
+
text = str(row.get("text", "")).strip()
|
| 361 |
+
return f"<bos><file_start>\n{text}\n<file_end><eos>"
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def make_fim_variant(text: str) -> Optional[str]:
|
| 365 |
+
if len(text) < 300:
|
| 366 |
+
return None
|
| 367 |
+
digest = int(hashlib.sha256(text.encode("utf-8")).hexdigest()[:8], 16)
|
| 368 |
+
rng = random.Random(digest)
|
| 369 |
+
low = max(50, len(text) // 5)
|
| 370 |
+
high = min(len(text) - 50, (len(text) * 4) // 5)
|
| 371 |
+
if high <= low:
|
| 372 |
+
return None
|
| 373 |
+
start = rng.randint(low // 2, low)
|
| 374 |
+
end = rng.randint(max(start + 20, high - low), high)
|
| 375 |
+
if end <= start:
|
| 376 |
+
return None
|
| 377 |
+
prefix, middle, suffix = text[:start], text[start:end], text[end:]
|
| 378 |
+
return (
|
| 379 |
+
"<bos><fim_prefix>" + prefix + "<fim_suffix>" + suffix + "<fim_middle>" + middle + "<eos>"
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
# -----------------------------------------------------------------------------
|
| 384 |
+
# Dataset preparation and checks
|
| 385 |
+
# -----------------------------------------------------------------------------
|
| 386 |
+
def dataset_preview(limit: int) -> None:
|
| 387 |
+
datasets = require_optional("datasets")
|
| 388 |
+
print("Connecting to Hugging Face: codeparrot/codeparrot-clean [Python source code]")
|
| 389 |
+
stream = datasets.load_dataset(
|
| 390 |
+
"codeparrot/codeparrot-clean",
|
| 391 |
+
split="train",
|
| 392 |
+
streaming=True,
|
| 393 |
+
)
|
| 394 |
+
for index, sample in enumerate(stream):
|
| 395 |
+
code = str(sample.get("content") or sample.get("code") or sample.get("text") or "")
|
| 396 |
+
print("\n" + "=" * 88)
|
| 397 |
+
print(f"SAMPLE {index + 1}")
|
| 398 |
+
print("source:", sample.get("repo_name") or sample.get("repo") or sample.get("repository_name") or "unknown")
|
| 399 |
+
print("path:", sample.get("path") or "unknown")
|
| 400 |
+
print("score:", sample.get("int_score") or sample.get("score") or "unknown")
|
| 401 |
+
print("-" * 88)
|
| 402 |
+
print(code[:2_500])
|
| 403 |
+
if index + 1 >= limit:
|
| 404 |
+
break
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def prepare_remote_dataset(max_base: int, test_mode: bool, min_score: int) -> None:
|
| 408 |
+
datasets = require_optional("datasets")
|
| 409 |
+
target_base = min(max_base, 2_000) if test_mode else max_base
|
| 410 |
+
print(f"Preparing {'test' if test_mode else 'full'} local dataset from Hugging Face")
|
| 411 |
+
print(f"Target accepted Python base samples: {target_base:,}")
|
| 412 |
+
|
| 413 |
+
counters: dict[str, int] = {}
|
| 414 |
+
train_rows: list[dict[str, Any]] = []
|
| 415 |
+
validation_rows: list[dict[str, Any]] = []
|
| 416 |
+
test_rows: list[dict[str, Any]] = []
|
| 417 |
+
seen: set[str] = set()
|
| 418 |
+
|
| 419 |
+
def count(reason: str) -> None:
|
| 420 |
+
counters[reason] = counters.get(reason, 0) + 1
|
| 421 |
+
|
| 422 |
+
stream = datasets.load_dataset(
|
| 423 |
+
"codeparrot/codeparrot-clean",
|
| 424 |
+
split="train",
|
| 425 |
+
streaming=True,
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
for raw in stream:
|
| 429 |
+
count("read")
|
| 430 |
+
score_value = raw.get("int_score", raw.get("score"))
|
| 431 |
+
if score_value is not None:
|
| 432 |
+
with contextlib.suppress(TypeError, ValueError):
|
| 433 |
+
if int(float(score_value)) < min_score:
|
| 434 |
+
count("low_score")
|
| 435 |
+
continue
|
| 436 |
+
code = normalize_code(str(raw.get("content") or raw.get("code") or raw.get("text") or ""))
|
| 437 |
+
accepted, reason = basic_code_filter(code)
|
| 438 |
+
if not accepted:
|
| 439 |
+
count(reason)
|
| 440 |
+
continue
|
| 441 |
+
source = str(raw.get("repo_name") or raw.get("repo") or raw.get("repository_name") or "codeparrot-clean")
|
| 442 |
+
path = str(raw.get("path") or "unknown.py")
|
| 443 |
+
for chunk in split_python_code(code):
|
| 444 |
+
digest = sha256_text(chunk)
|
| 445 |
+
if digest in seen:
|
| 446 |
+
count("duplicate")
|
| 447 |
+
continue
|
| 448 |
+
seen.add(digest)
|
| 449 |
+
split_bucket = int(digest[:8], 16) % 1000
|
| 450 |
+
base_row = {
|
| 451 |
+
"type": "base",
|
| 452 |
+
"text": chunk,
|
| 453 |
+
"source": f"codeparrot-clean:{source}:{path}",
|
| 454 |
+
"sha256": digest,
|
| 455 |
+
}
|
| 456 |
+
destination = train_rows
|
| 457 |
+
if split_bucket < 15:
|
| 458 |
+
destination = test_rows
|
| 459 |
+
elif split_bucket < 30:
|
| 460 |
+
destination = validation_rows
|
| 461 |
+
destination.append(base_row)
|
| 462 |
+
if destination is train_rows:
|
| 463 |
+
for instruction_row in extract_instruction_rows(chunk, base_row["source"]):
|
| 464 |
+
train_rows.append(instruction_row)
|
| 465 |
+
count("accepted")
|
| 466 |
+
if counters["accepted"] >= target_base:
|
| 467 |
+
break
|
| 468 |
+
if counters.get("accepted", 0) >= target_base:
|
| 469 |
+
break
|
| 470 |
+
if counters.get("read", 0) % 2_000 == 0:
|
| 471 |
+
print(
|
| 472 |
+
f"read={counters['read']:,} accepted={counters.get('accepted', 0):,} "
|
| 473 |
+
f"syntax={counters.get('syntax', 0):,} duplicate={counters.get('duplicate', 0):,}"
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
print("Adding MBPP English-to-Python examples and held-out tests...")
|
| 477 |
+
mbpp_loaded = False
|
| 478 |
+
mbpp_error = ""
|
| 479 |
+
for repo, config in [
|
| 480 |
+
("google-research-datasets/mbpp", "full"),
|
| 481 |
+
("RLAIF/mbpp", None),
|
| 482 |
+
("Muennighoff/mbpp", None),
|
| 483 |
+
]:
|
| 484 |
+
try:
|
| 485 |
+
kwargs: dict[str, Any] = {}
|
| 486 |
+
if config:
|
| 487 |
+
kwargs["name"] = config
|
| 488 |
+
mbpp = datasets.load_dataset(repo, **kwargs)
|
| 489 |
+
mbpp_loaded = True
|
| 490 |
+
for split_name in mbpp.keys():
|
| 491 |
+
split = mbpp[split_name]
|
| 492 |
+
for sample in split:
|
| 493 |
+
instruction = str(sample.get("text", "")).strip()
|
| 494 |
+
response = normalize_code(str(sample.get("code", "")))
|
| 495 |
+
tests = list(sample.get("test_list") or [])
|
| 496 |
+
valid, _ = is_valid_python(response)
|
| 497 |
+
if not instruction or not valid:
|
| 498 |
+
continue
|
| 499 |
+
row = {
|
| 500 |
+
"type": "instruct",
|
| 501 |
+
"instruction": instruction,
|
| 502 |
+
"response": response,
|
| 503 |
+
"tests": tests,
|
| 504 |
+
"source": f"{repo}:{split_name}:{sample.get('task_id', '')}",
|
| 505 |
+
}
|
| 506 |
+
split_lower = split_name.lower()
|
| 507 |
+
if split_lower in {"test", "prompt"}:
|
| 508 |
+
test_rows.append(row)
|
| 509 |
+
elif split_lower in {"validation", "valid"}:
|
| 510 |
+
validation_rows.append(row)
|
| 511 |
+
else:
|
| 512 |
+
train_rows.append(row)
|
| 513 |
+
break
|
| 514 |
+
except Exception as exc: # network/schema fallback
|
| 515 |
+
mbpp_error = f"{type(exc).__name__}: {exc}"
|
| 516 |
+
if not mbpp_loaded:
|
| 517 |
+
print("Warning: MBPP could not be loaded; continuing with CodeParrot Python data only.")
|
| 518 |
+
print("Last MBPP error:", mbpp_error)
|
| 519 |
+
|
| 520 |
+
random.Random(1337).shuffle(train_rows)
|
| 521 |
+
random.Random(7331).shuffle(validation_rows)
|
| 522 |
+
random.Random(31337).shuffle(test_rows)
|
| 523 |
+
|
| 524 |
+
atomic_write_jsonl(TRAIN_JSONL, train_rows)
|
| 525 |
+
atomic_write_jsonl(VALIDATION_JSONL, validation_rows)
|
| 526 |
+
atomic_write_jsonl(TEST_JSONL, test_rows)
|
| 527 |
+
|
| 528 |
+
print("\nDataset preparation complete")
|
| 529 |
+
print(f" train.jsonl: {len(train_rows):,} rows")
|
| 530 |
+
print(f" validation.jsonl: {len(validation_rows):,} rows")
|
| 531 |
+
print(f" test.jsonl: {len(test_rows):,} rows")
|
| 532 |
+
for key in sorted(counters):
|
| 533 |
+
print(f" {key:18s}: {counters[key]:,}")
|
| 534 |
+
print("Run `check-data` before tokenizer training.")
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def inspect_dataset_file(path: Path, show_samples: int = 3) -> dict[str, Any]:
|
| 538 |
+
stats: dict[str, Any] = {
|
| 539 |
+
"rows": 0,
|
| 540 |
+
"base": 0,
|
| 541 |
+
"instruct": 0,
|
| 542 |
+
"invalid": 0,
|
| 543 |
+
"duplicates": 0,
|
| 544 |
+
"chars": 0,
|
| 545 |
+
"with_tests": 0,
|
| 546 |
+
}
|
| 547 |
+
hashes: set[str] = set()
|
| 548 |
+
previews: list[dict[str, Any]] = []
|
| 549 |
+
for row in iter_jsonl(path):
|
| 550 |
+
stats["rows"] += 1
|
| 551 |
+
row_type = str(row.get("type", "base"))
|
| 552 |
+
if row_type == "instruct":
|
| 553 |
+
stats["instruct"] += 1
|
| 554 |
+
code = str(row.get("response", ""))
|
| 555 |
+
stats["with_tests"] += int(bool(row.get("tests")))
|
| 556 |
+
else:
|
| 557 |
+
stats["base"] += 1
|
| 558 |
+
code = str(row.get("text", ""))
|
| 559 |
+
stats["chars"] += len(code)
|
| 560 |
+
valid, _ = is_valid_python(code)
|
| 561 |
+
if not valid:
|
| 562 |
+
stats["invalid"] += 1
|
| 563 |
+
digest = sha256_text(serialize_training_row(row))
|
| 564 |
+
if digest in hashes:
|
| 565 |
+
stats["duplicates"] += 1
|
| 566 |
+
hashes.add(digest)
|
| 567 |
+
if len(previews) < show_samples:
|
| 568 |
+
previews.append(row)
|
| 569 |
+
stats["average_chars"] = round(stats["chars"] / max(1, stats["rows"]), 1)
|
| 570 |
+
stats["previews"] = previews
|
| 571 |
+
return stats
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
def check_data(show_samples: int = 2) -> None:
|
| 575 |
+
all_good = True
|
| 576 |
+
for path in (TRAIN_JSONL, VALIDATION_JSONL, TEST_JSONL):
|
| 577 |
+
print("\n" + "=" * 88)
|
| 578 |
+
print(path.name)
|
| 579 |
+
stats = inspect_dataset_file(path, show_samples=show_samples)
|
| 580 |
+
for key, value in stats.items():
|
| 581 |
+
if key != "previews":
|
| 582 |
+
print(f" {key:16s}: {value}")
|
| 583 |
+
if stats["invalid"]:
|
| 584 |
+
all_good = False
|
| 585 |
+
for index, row in enumerate(stats["previews"], start=1):
|
| 586 |
+
print(f"\n Preview {index}: type={row.get('type', 'base')} source={row.get('source', '')}")
|
| 587 |
+
print(" " + serialize_training_row(row)[:700].replace("\n", "\n "))
|
| 588 |
+
print("\nDATASET STATUS:", "PASS" if all_good else "FAIL - invalid Python found")
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
# -----------------------------------------------------------------------------
|
| 592 |
+
# Tokenizer and binary token corpus
|
| 593 |
+
# -----------------------------------------------------------------------------
|
| 594 |
+
def load_tokenizer() -> Any:
|
| 595 |
+
tokenizers = require_optional("tokenizers")
|
| 596 |
+
if not TOKENIZER_JSON.exists():
|
| 597 |
+
raise SystemExit("tokenizer.json not found. Run: python jumplander_python_100m.py tokenizer")
|
| 598 |
+
return tokenizers.Tokenizer.from_file(str(TOKENIZER_JSON))
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
def train_tokenizer(vocab_size: int = 16_384) -> None:
|
| 602 |
+
tokenizers = require_optional("tokenizers")
|
| 603 |
+
from tokenizers import Tokenizer, decoders, models, normalizers, pre_tokenizers, processors, trainers
|
| 604 |
+
|
| 605 |
+
if not TRAIN_JSONL.exists():
|
| 606 |
+
raise SystemExit("train.jsonl not found")
|
| 607 |
+
|
| 608 |
+
tokenizer = Tokenizer(models.BPE(unk_token="<unk>", byte_fallback=True))
|
| 609 |
+
tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False, use_regex=True)
|
| 610 |
+
tokenizer.decoder = decoders.ByteLevel()
|
| 611 |
+
trainer = trainers.BpeTrainer(
|
| 612 |
+
vocab_size=vocab_size,
|
| 613 |
+
min_frequency=2,
|
| 614 |
+
show_progress=True,
|
| 615 |
+
special_tokens=SPECIAL_TOKENS,
|
| 616 |
+
initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),
|
| 617 |
+
)
|
| 618 |
+
|
| 619 |
+
def corpus() -> Iterator[str]:
|
| 620 |
+
for row in iter_jsonl(TRAIN_JSONL):
|
| 621 |
+
yield serialize_training_row(row)
|
| 622 |
+
|
| 623 |
+
print(f"Training JumpLander Byte-Level BPE tokenizer (target vocab={vocab_size:,})")
|
| 624 |
+
tokenizer.train_from_iterator(corpus(), trainer=trainer, length=None)
|
| 625 |
+
tokenizer.save(str(TOKENIZER_JSON))
|
| 626 |
+
print(f"Saved: {TOKENIZER_JSON}")
|
| 627 |
+
print("Actual tokenizer vocabulary:", tokenizer.get_vocab_size())
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def build_token_file(jsonl_path: Path, output_path: Path, add_fim: bool) -> int:
|
| 631 |
+
tokenizer = load_tokenizer()
|
| 632 |
+
actual_vocab = tokenizer.get_vocab_size()
|
| 633 |
+
if actual_vocab > FULL_MODEL_CONFIG.vocab_size:
|
| 634 |
+
raise SystemExit(
|
| 635 |
+
f"Tokenizer vocab {actual_vocab} exceeds model vocab {FULL_MODEL_CONFIG.vocab_size}"
|
| 636 |
+
)
|
| 637 |
+
temp = output_path.with_suffix(output_path.suffix + ".tmp")
|
| 638 |
+
total = 0
|
| 639 |
+
with temp.open("wb") as handle:
|
| 640 |
+
for row in iter_jsonl(jsonl_path):
|
| 641 |
+
text = serialize_training_row(row)
|
| 642 |
+
ids = tokenizer.encode(text, add_special_tokens=False).ids
|
| 643 |
+
if ids:
|
| 644 |
+
array = np.asarray(ids, dtype=np.uint16)
|
| 645 |
+
array.tofile(handle)
|
| 646 |
+
total += len(ids)
|
| 647 |
+
if add_fim and row.get("type", "base") == "base":
|
| 648 |
+
code = str(row.get("text", ""))
|
| 649 |
+
variant = make_fim_variant(code)
|
| 650 |
+
if variant:
|
| 651 |
+
fim_ids = tokenizer.encode(variant, add_special_tokens=False).ids
|
| 652 |
+
np.asarray(fim_ids, dtype=np.uint16).tofile(handle)
|
| 653 |
+
total += len(fim_ids)
|
| 654 |
+
temp.replace(output_path)
|
| 655 |
+
print(f"Built {output_path.name}: {total:,} tokens")
|
| 656 |
+
return total
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def build_tokens() -> None:
|
| 660 |
+
if not TOKENIZER_JSON.exists():
|
| 661 |
+
train_tokenizer(FULL_MODEL_CONFIG.vocab_size)
|
| 662 |
+
train_count = build_token_file(TRAIN_JSONL, TRAIN_BIN, add_fim=True)
|
| 663 |
+
validation_count = build_token_file(VALIDATION_JSONL, VALIDATION_BIN, add_fim=False)
|
| 664 |
+
if train_count < 10_000:
|
| 665 |
+
print("Warning: training corpus is tiny. It is suitable only for a pipeline smoke test.")
|
| 666 |
+
if validation_count < 1_000:
|
| 667 |
+
print("Warning: validation corpus is very small.")
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
# -----------------------------------------------------------------------------
|
| 671 |
+
# Model architecture: random initialization, no pretrained checkpoint.
|
| 672 |
+
# -----------------------------------------------------------------------------
|
| 673 |
+
class RMSNorm(nn.Module):
|
| 674 |
+
def __init__(self, size: int, eps: float) -> None:
|
| 675 |
+
super().__init__()
|
| 676 |
+
self.weight = nn.Parameter(torch.ones(size))
|
| 677 |
+
self.eps = eps
|
| 678 |
+
|
| 679 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 680 |
+
input_dtype = x.dtype
|
| 681 |
+
x_float = x.float()
|
| 682 |
+
variance = x_float.pow(2).mean(dim=-1, keepdim=True)
|
| 683 |
+
normalized = x_float * torch.rsqrt(variance + self.eps)
|
| 684 |
+
return (normalized.to(input_dtype) * self.weight)
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
def rotate_half(x: torch.Tensor) -> torch.Tensor:
|
| 688 |
+
x1 = x[..., ::2]
|
| 689 |
+
x2 = x[..., 1::2]
|
| 690 |
+
return torch.stack((-x2, x1), dim=-1).flatten(-2)
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
def rope_cos_sin(
|
| 694 |
+
seq_len: int,
|
| 695 |
+
head_dim: int,
|
| 696 |
+
theta: float,
|
| 697 |
+
device: torch.device,
|
| 698 |
+
dtype: torch.dtype,
|
| 699 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 700 |
+
inv_freq = 1.0 / (
|
| 701 |
+
theta ** (torch.arange(0, head_dim, 2, device=device, dtype=torch.float32) / head_dim)
|
| 702 |
+
)
|
| 703 |
+
positions = torch.arange(seq_len, device=device, dtype=torch.float32)
|
| 704 |
+
frequencies = torch.outer(positions, inv_freq)
|
| 705 |
+
emb = torch.repeat_interleave(frequencies, 2, dim=-1)
|
| 706 |
+
cos = emb.cos().to(dtype=dtype)[None, None, :, :]
|
| 707 |
+
sin = emb.sin().to(dtype=dtype)[None, None, :, :]
|
| 708 |
+
return cos, sin
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
class CausalSelfAttention(nn.Module):
|
| 712 |
+
def __init__(self, config: ModelConfig) -> None:
|
| 713 |
+
super().__init__()
|
| 714 |
+
self.n_heads = config.n_heads
|
| 715 |
+
self.head_dim = config.d_model // config.n_heads
|
| 716 |
+
self.rope_theta = config.rope_theta
|
| 717 |
+
self.dropout = config.dropout
|
| 718 |
+
self.qkv = nn.Linear(config.d_model, 3 * config.d_model, bias=False)
|
| 719 |
+
self.out = nn.Linear(config.d_model, config.d_model, bias=False)
|
| 720 |
+
|
| 721 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 722 |
+
batch, seq_len, width = x.shape
|
| 723 |
+
qkv = self.qkv(x)
|
| 724 |
+
q, k, v = qkv.chunk(3, dim=-1)
|
| 725 |
+
q = q.view(batch, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
|
| 726 |
+
k = k.view(batch, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
|
| 727 |
+
v = v.view(batch, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
|
| 728 |
+
cos, sin = rope_cos_sin(seq_len, self.head_dim, self.rope_theta, x.device, q.dtype)
|
| 729 |
+
q = (q * cos) + (rotate_half(q) * sin)
|
| 730 |
+
k = (k * cos) + (rotate_half(k) * sin)
|
| 731 |
+
attended = F.scaled_dot_product_attention(
|
| 732 |
+
q,
|
| 733 |
+
k,
|
| 734 |
+
v,
|
| 735 |
+
attn_mask=None,
|
| 736 |
+
dropout_p=self.dropout if self.training else 0.0,
|
| 737 |
+
is_causal=True,
|
| 738 |
+
)
|
| 739 |
+
attended = attended.transpose(1, 2).contiguous().view(batch, seq_len, width)
|
| 740 |
+
return self.out(attended)
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
class SwiGLU(nn.Module):
|
| 744 |
+
def __init__(self, config: ModelConfig) -> None:
|
| 745 |
+
super().__init__()
|
| 746 |
+
self.gate = nn.Linear(config.d_model, config.d_ff, bias=False)
|
| 747 |
+
self.up = nn.Linear(config.d_model, config.d_ff, bias=False)
|
| 748 |
+
self.down = nn.Linear(config.d_ff, config.d_model, bias=False)
|
| 749 |
+
|
| 750 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 751 |
+
return self.down(F.silu(self.gate(x)) * self.up(x))
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
class TransformerBlock(nn.Module):
|
| 755 |
+
def __init__(self, config: ModelConfig) -> None:
|
| 756 |
+
super().__init__()
|
| 757 |
+
self.attn_norm = RMSNorm(config.d_model, config.norm_eps)
|
| 758 |
+
self.attn = CausalSelfAttention(config)
|
| 759 |
+
self.ffn_norm = RMSNorm(config.d_model, config.norm_eps)
|
| 760 |
+
self.ffn = SwiGLU(config)
|
| 761 |
+
|
| 762 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 763 |
+
x = x + self.attn(self.attn_norm(x))
|
| 764 |
+
x = x + self.ffn(self.ffn_norm(x))
|
| 765 |
+
return x
|
| 766 |
+
|
| 767 |
+
|
| 768 |
+
class JumpLanderPythonModel(nn.Module):
|
| 769 |
+
def __init__(self, config: ModelConfig) -> None:
|
| 770 |
+
super().__init__()
|
| 771 |
+
config.validate()
|
| 772 |
+
self.config = config
|
| 773 |
+
self.token_embedding = nn.Embedding(config.vocab_size, config.d_model)
|
| 774 |
+
self.blocks = nn.ModuleList([TransformerBlock(config) for _ in range(config.n_layers)])
|
| 775 |
+
self.final_norm = RMSNorm(config.d_model, config.norm_eps)
|
| 776 |
+
if not config.tie_embeddings:
|
| 777 |
+
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
| 778 |
+
else:
|
| 779 |
+
self.lm_head = None
|
| 780 |
+
self.apply(self._init_weights)
|
| 781 |
+
|
| 782 |
+
@staticmethod
|
| 783 |
+
def _init_weights(module: nn.Module) -> None:
|
| 784 |
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
| 785 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 786 |
+
|
| 787 |
+
def forward(
|
| 788 |
+
self,
|
| 789 |
+
input_ids: torch.Tensor,
|
| 790 |
+
targets: Optional[torch.Tensor] = None,
|
| 791 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 792 |
+
if input_ids.ndim != 2:
|
| 793 |
+
raise ValueError("input_ids must have shape [batch, sequence]")
|
| 794 |
+
if input_ids.size(1) > self.config.max_seq_len:
|
| 795 |
+
raise ValueError("Sequence exceeds configured context length")
|
| 796 |
+
x = self.token_embedding(input_ids)
|
| 797 |
+
for block in self.blocks:
|
| 798 |
+
if self.config.gradient_checkpointing and self.training:
|
| 799 |
+
x = activation_checkpoint(block, x, use_reentrant=False)
|
| 800 |
+
else:
|
| 801 |
+
x = block(x)
|
| 802 |
+
x = self.final_norm(x)
|
| 803 |
+
if self.lm_head is None:
|
| 804 |
+
logits = F.linear(x, self.token_embedding.weight)
|
| 805 |
+
else:
|
| 806 |
+
logits = self.lm_head(x)
|
| 807 |
+
loss: Optional[torch.Tensor] = None
|
| 808 |
+
if targets is not None:
|
| 809 |
+
loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)), targets.reshape(-1))
|
| 810 |
+
return logits, loss
|
| 811 |
+
|
| 812 |
+
|
| 813 |
+
def parameter_report(config: ModelConfig) -> dict[str, int]:
|
| 814 |
+
model = JumpLanderPythonModel(config)
|
| 815 |
+
total = sum(parameter.numel() for parameter in model.parameters())
|
| 816 |
+
trainable = sum(parameter.numel() for parameter in model.parameters() if parameter.requires_grad)
|
| 817 |
+
del model
|
| 818 |
+
return {"total": total, "trainable": trainable}
|
| 819 |
+
|
| 820 |
+
|
| 821 |
+
# -----------------------------------------------------------------------------
|
| 822 |
+
# Training
|
| 823 |
+
# -----------------------------------------------------------------------------
|
| 824 |
+
class TokenBlockDataset(Dataset[tuple[torch.Tensor, torch.Tensor]]):
|
| 825 |
+
def __init__(self, path: Path, block_size: int) -> None:
|
| 826 |
+
if not path.exists():
|
| 827 |
+
raise FileNotFoundError(f"Token file not found: {path}. Run build-tokens first.")
|
| 828 |
+
self.tokens = np.memmap(path, dtype=np.uint16, mode="r")
|
| 829 |
+
self.block_size = block_size
|
| 830 |
+
if len(self.tokens) < block_size + 1:
|
| 831 |
+
raise ValueError(
|
| 832 |
+
f"{path.name} contains only {len(self.tokens):,} tokens; need at least {block_size + 1:,}"
|
| 833 |
+
)
|
| 834 |
+
self.examples = (len(self.tokens) - 1) // block_size
|
| 835 |
+
|
| 836 |
+
def __len__(self) -> int:
|
| 837 |
+
return self.examples
|
| 838 |
+
|
| 839 |
+
def __getitem__(self, index: int) -> tuple[torch.Tensor, torch.Tensor]:
|
| 840 |
+
start = index * self.block_size
|
| 841 |
+
chunk = np.asarray(self.tokens[start : start + self.block_size + 1], dtype=np.int64)
|
| 842 |
+
x = torch.from_numpy(chunk[:-1].copy())
|
| 843 |
+
y = torch.from_numpy(chunk[1:].copy())
|
| 844 |
+
return x, y
|
| 845 |
+
|
| 846 |
+
|
| 847 |
+
def cosine_lr(step: int, config: TrainConfig) -> float:
|
| 848 |
+
if step < config.warmup_steps:
|
| 849 |
+
return config.learning_rate * (step + 1) / max(1, config.warmup_steps)
|
| 850 |
+
progress = (step - config.warmup_steps) / max(1, config.total_steps - config.warmup_steps)
|
| 851 |
+
progress = min(max(progress, 0.0), 1.0)
|
| 852 |
+
coefficient = 0.5 * (1.0 + math.cos(math.pi * progress))
|
| 853 |
+
return config.min_learning_rate + coefficient * (
|
| 854 |
+
config.learning_rate - config.min_learning_rate
|
| 855 |
+
)
|
| 856 |
+
|
| 857 |
+
|
| 858 |
+
def choose_precision(device: torch.device) -> tuple[torch.dtype, bool]:
|
| 859 |
+
if device.type != "cuda":
|
| 860 |
+
return torch.float32, False
|
| 861 |
+
if torch.cuda.is_bf16_supported():
|
| 862 |
+
return torch.bfloat16, True
|
| 863 |
+
return torch.float16, True
|
| 864 |
+
|
| 865 |
+
|
| 866 |
+
def make_optimizer(model: nn.Module, train_config: TrainConfig, device: torch.device) -> torch.optim.Optimizer:
|
| 867 |
+
kwargs: dict[str, Any] = {
|
| 868 |
+
"lr": train_config.learning_rate,
|
| 869 |
+
"betas": (0.9, 0.95),
|
| 870 |
+
"eps": 1e-8,
|
| 871 |
+
"weight_decay": train_config.weight_decay,
|
| 872 |
+
}
|
| 873 |
+
if device.type == "cuda":
|
| 874 |
+
try:
|
| 875 |
+
return torch.optim.AdamW(model.parameters(), fused=True, **kwargs)
|
| 876 |
+
except (TypeError, RuntimeError):
|
| 877 |
+
pass
|
| 878 |
+
return torch.optim.AdamW(model.parameters(), **kwargs)
|
| 879 |
+
|
| 880 |
+
|
| 881 |
+
@torch.no_grad()
|
| 882 |
+
def evaluate(
|
| 883 |
+
model: JumpLanderPythonModel,
|
| 884 |
+
loader: DataLoader[Any],
|
| 885 |
+
device: torch.device,
|
| 886 |
+
dtype: torch.dtype,
|
| 887 |
+
batches: int,
|
| 888 |
+
) -> float:
|
| 889 |
+
model.eval()
|
| 890 |
+
losses: list[float] = []
|
| 891 |
+
iterator = iter(loader)
|
| 892 |
+
amp_enabled = device.type == "cuda"
|
| 893 |
+
for _ in range(batches):
|
| 894 |
+
try:
|
| 895 |
+
x, y = next(iterator)
|
| 896 |
+
except StopIteration:
|
| 897 |
+
break
|
| 898 |
+
x, y = x.to(device, non_blocking=True), y.to(device, non_blocking=True)
|
| 899 |
+
with torch.autocast(device_type=device.type, dtype=dtype, enabled=amp_enabled):
|
| 900 |
+
_, loss = model(x, y)
|
| 901 |
+
if loss is not None:
|
| 902 |
+
losses.append(float(loss.item()))
|
| 903 |
+
model.train()
|
| 904 |
+
return float(sum(losses) / max(1, len(losses)))
|
| 905 |
+
|
| 906 |
+
|
| 907 |
+
def save_checkpoint(
|
| 908 |
+
path: Path,
|
| 909 |
+
model: JumpLanderPythonModel,
|
| 910 |
+
optimizer: torch.optim.Optimizer,
|
| 911 |
+
step: int,
|
| 912 |
+
tokens_seen: int,
|
| 913 |
+
train_config: TrainConfig,
|
| 914 |
+
) -> None:
|
| 915 |
+
payload = {
|
| 916 |
+
"model_name": model.config.name,
|
| 917 |
+
"model_config": dataclasses.asdict(model.config),
|
| 918 |
+
"train_config": dataclasses.asdict(train_config),
|
| 919 |
+
"model_state": model.state_dict(),
|
| 920 |
+
"optimizer_state": optimizer.state_dict(),
|
| 921 |
+
"step": step,
|
| 922 |
+
"tokens_seen": tokens_seen,
|
| 923 |
+
"saved_at": time.time(),
|
| 924 |
+
"format_version": 1,
|
| 925 |
+
}
|
| 926 |
+
temp = path.with_suffix(path.suffix + ".tmp")
|
| 927 |
+
torch.save(payload, temp)
|
| 928 |
+
temp.replace(path)
|
| 929 |
+
|
| 930 |
+
|
| 931 |
+
def load_checkpoint_payload(path: Path, device: torch.device) -> dict[str, Any]:
|
| 932 |
+
if not path.exists():
|
| 933 |
+
raise FileNotFoundError(f"Checkpoint not found: {path}")
|
| 934 |
+
try:
|
| 935 |
+
return torch.load(path, map_location=device, weights_only=False)
|
| 936 |
+
except TypeError:
|
| 937 |
+
return torch.load(path, map_location=device)
|
| 938 |
+
|
| 939 |
+
|
| 940 |
+
def train_model(
|
| 941 |
+
smoke: bool,
|
| 942 |
+
resume: bool,
|
| 943 |
+
total_steps: Optional[int],
|
| 944 |
+
batch_size: Optional[int],
|
| 945 |
+
accumulation: Optional[int],
|
| 946 |
+
) -> None:
|
| 947 |
+
if not TRAIN_BIN.exists() or not VALIDATION_BIN.exists():
|
| 948 |
+
print("Token files are missing; building them now.")
|
| 949 |
+
build_tokens()
|
| 950 |
+
|
| 951 |
+
model_config = dataclasses.replace(SMOKE_MODEL_CONFIG if smoke else FULL_MODEL_CONFIG)
|
| 952 |
+
if smoke:
|
| 953 |
+
train_config = TrainConfig(
|
| 954 |
+
batch_size=batch_size or 2,
|
| 955 |
+
gradient_accumulation=accumulation or 4,
|
| 956 |
+
learning_rate=5e-4,
|
| 957 |
+
min_learning_rate=5e-5,
|
| 958 |
+
warmup_steps=20,
|
| 959 |
+
total_steps=total_steps or 300,
|
| 960 |
+
eval_interval=50,
|
| 961 |
+
eval_batches=10,
|
| 962 |
+
save_interval=100,
|
| 963 |
+
log_interval=5,
|
| 964 |
+
)
|
| 965 |
+
checkpoint_path = SMOKE_CHECKPOINT
|
| 966 |
+
else:
|
| 967 |
+
train_config = TrainConfig(
|
| 968 |
+
batch_size=batch_size or 1,
|
| 969 |
+
gradient_accumulation=accumulation or 32,
|
| 970 |
+
total_steps=total_steps or 10_000,
|
| 971 |
+
)
|
| 972 |
+
checkpoint_path = MODEL_CHECKPOINT
|
| 973 |
+
|
| 974 |
+
seed_everything(train_config.seed)
|
| 975 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 976 |
+
dtype, amp_enabled = choose_precision(device)
|
| 977 |
+
print(f"Device: {device}; precision: {dtype}; AMP: {amp_enabled}")
|
| 978 |
+
if device.type != "cuda":
|
| 979 |
+
print("Warning: CUDA is not available. Full 100M training on CPU is impractical.")
|
| 980 |
+
|
| 981 |
+
train_dataset = TokenBlockDataset(TRAIN_BIN, model_config.max_seq_len)
|
| 982 |
+
validation_dataset = TokenBlockDataset(VALIDATION_BIN, model_config.max_seq_len)
|
| 983 |
+
train_loader = DataLoader(
|
| 984 |
+
train_dataset,
|
| 985 |
+
batch_size=train_config.batch_size,
|
| 986 |
+
shuffle=True,
|
| 987 |
+
num_workers=train_config.num_workers,
|
| 988 |
+
pin_memory=device.type == "cuda",
|
| 989 |
+
drop_last=True,
|
| 990 |
+
)
|
| 991 |
+
validation_loader = DataLoader(
|
| 992 |
+
validation_dataset,
|
| 993 |
+
batch_size=train_config.batch_size,
|
| 994 |
+
shuffle=False,
|
| 995 |
+
num_workers=0,
|
| 996 |
+
pin_memory=device.type == "cuda",
|
| 997 |
+
drop_last=False,
|
| 998 |
+
)
|
| 999 |
+
|
| 1000 |
+
model = JumpLanderPythonModel(model_config).to(device)
|
| 1001 |
+
report = parameter_report(model_config)
|
| 1002 |
+
print(f"Model parameters: {report['total']:,}")
|
| 1003 |
+
optimizer = make_optimizer(model, train_config, device)
|
| 1004 |
+
scaler = torch.amp.GradScaler("cuda", enabled=(device.type == "cuda" and dtype == torch.float16))
|
| 1005 |
+
|
| 1006 |
+
start_step = 0
|
| 1007 |
+
tokens_seen = 0
|
| 1008 |
+
if resume:
|
| 1009 |
+
payload = load_checkpoint_payload(checkpoint_path, device)
|
| 1010 |
+
model.load_state_dict(payload["model_state"])
|
| 1011 |
+
optimizer.load_state_dict(payload["optimizer_state"])
|
| 1012 |
+
start_step = int(payload.get("step", 0))
|
| 1013 |
+
tokens_seen = int(payload.get("tokens_seen", 0))
|
| 1014 |
+
print(f"Resumed {checkpoint_path.name} at step {start_step:,}")
|
| 1015 |
+
|
| 1016 |
+
model.train()
|
| 1017 |
+
iterator = iter(train_loader)
|
| 1018 |
+
optimizer.zero_grad(set_to_none=True)
|
| 1019 |
+
last_log_time = time.time()
|
| 1020 |
+
running_loss = 0.0
|
| 1021 |
+
micro_steps = 0
|
| 1022 |
+
|
| 1023 |
+
for step in range(start_step, train_config.total_steps):
|
| 1024 |
+
lr = cosine_lr(step, train_config)
|
| 1025 |
+
for group in optimizer.param_groups:
|
| 1026 |
+
group["lr"] = lr
|
| 1027 |
+
|
| 1028 |
+
for _ in range(train_config.gradient_accumulation):
|
| 1029 |
+
try:
|
| 1030 |
+
x, y = next(iterator)
|
| 1031 |
+
except StopIteration:
|
| 1032 |
+
iterator = iter(train_loader)
|
| 1033 |
+
x, y = next(iterator)
|
| 1034 |
+
x, y = x.to(device, non_blocking=True), y.to(device, non_blocking=True)
|
| 1035 |
+
with torch.autocast(device_type=device.type, dtype=dtype, enabled=amp_enabled):
|
| 1036 |
+
_, loss = model(x, y)
|
| 1037 |
+
if loss is None:
|
| 1038 |
+
raise RuntimeError("Training loss was not produced")
|
| 1039 |
+
scaled_loss = loss / train_config.gradient_accumulation
|
| 1040 |
+
scaler.scale(scaled_loss).backward()
|
| 1041 |
+
running_loss += float(loss.detach().item())
|
| 1042 |
+
micro_steps += 1
|
| 1043 |
+
tokens_seen += x.numel()
|
| 1044 |
+
|
| 1045 |
+
scaler.unscale_(optimizer)
|
| 1046 |
+
gradient_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), train_config.grad_clip)
|
| 1047 |
+
scaler.step(optimizer)
|
| 1048 |
+
scaler.update()
|
| 1049 |
+
optimizer.zero_grad(set_to_none=True)
|
| 1050 |
+
|
| 1051 |
+
completed_step = step + 1
|
| 1052 |
+
if completed_step % train_config.log_interval == 0:
|
| 1053 |
+
now = time.time()
|
| 1054 |
+
elapsed = max(now - last_log_time, 1e-6)
|
| 1055 |
+
recent_tokens = (
|
| 1056 |
+
train_config.log_interval
|
| 1057 |
+
* train_config.gradient_accumulation
|
| 1058 |
+
* train_config.batch_size
|
| 1059 |
+
* model_config.max_seq_len
|
| 1060 |
+
)
|
| 1061 |
+
tokens_per_second = recent_tokens / elapsed
|
| 1062 |
+
average_loss = running_loss / max(1, micro_steps)
|
| 1063 |
+
memory = ""
|
| 1064 |
+
if device.type == "cuda":
|
| 1065 |
+
allocated = torch.cuda.max_memory_allocated() / (1024**3)
|
| 1066 |
+
memory = f" vram={allocated:.2f}GB"
|
| 1067 |
+
torch.cuda.reset_peak_memory_stats()
|
| 1068 |
+
print(
|
| 1069 |
+
f"step={completed_step:,}/{train_config.total_steps:,} "
|
| 1070 |
+
f"loss={average_loss:.4f} lr={lr:.2e} grad={float(gradient_norm):.3f} "
|
| 1071 |
+
f"tok/s={tokens_per_second:,.0f}{memory}"
|
| 1072 |
+
)
|
| 1073 |
+
running_loss = 0.0
|
| 1074 |
+
micro_steps = 0
|
| 1075 |
+
last_log_time = now
|
| 1076 |
+
|
| 1077 |
+
if completed_step % train_config.eval_interval == 0:
|
| 1078 |
+
validation_loss = evaluate(
|
| 1079 |
+
model, validation_loader, device, dtype, train_config.eval_batches
|
| 1080 |
+
)
|
| 1081 |
+
print(f"validation_loss={validation_loss:.4f}")
|
| 1082 |
+
|
| 1083 |
+
if completed_step % train_config.save_interval == 0:
|
| 1084 |
+
save_checkpoint(
|
| 1085 |
+
checkpoint_path,
|
| 1086 |
+
model,
|
| 1087 |
+
optimizer,
|
| 1088 |
+
completed_step,
|
| 1089 |
+
tokens_seen,
|
| 1090 |
+
train_config,
|
| 1091 |
+
)
|
| 1092 |
+
print(f"Saved checkpoint: {checkpoint_path.name}")
|
| 1093 |
+
|
| 1094 |
+
save_checkpoint(
|
| 1095 |
+
checkpoint_path,
|
| 1096 |
+
model,
|
| 1097 |
+
optimizer,
|
| 1098 |
+
train_config.total_steps,
|
| 1099 |
+
tokens_seen,
|
| 1100 |
+
train_config,
|
| 1101 |
+
)
|
| 1102 |
+
print(f"Training complete. Saved: {checkpoint_path}")
|
| 1103 |
+
|
| 1104 |
+
|
| 1105 |
+
# -----------------------------------------------------------------------------
|
| 1106 |
+
# Inference and web UI
|
| 1107 |
+
# -----------------------------------------------------------------------------
|
| 1108 |
+
def load_model_for_inference(checkpoint_path: Path) -> tuple[JumpLanderPythonModel, Any, torch.device]:
|
| 1109 |
+
tokenizer = load_tokenizer()
|
| 1110 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 1111 |
+
payload = load_checkpoint_payload(checkpoint_path, device)
|
| 1112 |
+
config = ModelConfig(**payload["model_config"])
|
| 1113 |
+
config.gradient_checkpointing = False
|
| 1114 |
+
model = JumpLanderPythonModel(config)
|
| 1115 |
+
model.load_state_dict(payload["model_state"])
|
| 1116 |
+
model.to(device)
|
| 1117 |
+
model.eval()
|
| 1118 |
+
return model, tokenizer, device
|
| 1119 |
+
|
| 1120 |
+
|
| 1121 |
+
def top_p_sample(logits: torch.Tensor, temperature: float, top_p: float) -> torch.Tensor:
|
| 1122 |
+
if temperature <= 0:
|
| 1123 |
+
return torch.argmax(logits, dim=-1, keepdim=True)
|
| 1124 |
+
logits = logits / max(temperature, 1e-5)
|
| 1125 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
| 1126 |
+
probabilities = F.softmax(sorted_logits, dim=-1)
|
| 1127 |
+
cumulative = torch.cumsum(probabilities, dim=-1)
|
| 1128 |
+
remove = cumulative > top_p
|
| 1129 |
+
remove[..., 1:] = remove[..., :-1].clone()
|
| 1130 |
+
remove[..., 0] = False
|
| 1131 |
+
sorted_logits = sorted_logits.masked_fill(remove, float("-inf"))
|
| 1132 |
+
probabilities = F.softmax(sorted_logits, dim=-1)
|
| 1133 |
+
selected = torch.multinomial(probabilities, num_samples=1)
|
| 1134 |
+
return sorted_indices.gather(-1, selected)
|
| 1135 |
+
|
| 1136 |
+
|
| 1137 |
+
@torch.inference_mode()
|
| 1138 |
+
def generate_text(
|
| 1139 |
+
model: JumpLanderPythonModel,
|
| 1140 |
+
tokenizer: Any,
|
| 1141 |
+
device: torch.device,
|
| 1142 |
+
prompt: str,
|
| 1143 |
+
mode: str,
|
| 1144 |
+
max_new_tokens: int,
|
| 1145 |
+
temperature: float,
|
| 1146 |
+
top_p: float,
|
| 1147 |
+
) -> str:
|
| 1148 |
+
if mode == "instruction":
|
| 1149 |
+
formatted = f"<bos><instruction>\n{prompt.strip()}\n<response>\n"
|
| 1150 |
+
else:
|
| 1151 |
+
formatted = f"<bos><file_start>\n{prompt}"
|
| 1152 |
+
encoded = tokenizer.encode(formatted, add_special_tokens=False).ids
|
| 1153 |
+
if not encoded:
|
| 1154 |
+
raise ValueError("Prompt produced no tokens")
|
| 1155 |
+
max_context = model.config.max_seq_len
|
| 1156 |
+
encoded = encoded[-max_context:]
|
| 1157 |
+
ids = torch.tensor([encoded], dtype=torch.long, device=device)
|
| 1158 |
+
eos_id = tokenizer.token_to_id("<eos>")
|
| 1159 |
+
file_end_id = tokenizer.token_to_id("<file_end>")
|
| 1160 |
+
actual_vocab = tokenizer.get_vocab_size()
|
| 1161 |
+
|
| 1162 |
+
for _ in range(max_new_tokens):
|
| 1163 |
+
context = ids[:, -max_context:]
|
| 1164 |
+
logits, _ = model(context)
|
| 1165 |
+
next_logits = logits[:, -1, :]
|
| 1166 |
+
if actual_vocab < next_logits.size(-1):
|
| 1167 |
+
next_logits[:, actual_vocab:] = float("-inf")
|
| 1168 |
+
next_id = top_p_sample(next_logits, temperature, top_p)
|
| 1169 |
+
ids = torch.cat([ids, next_id], dim=1)
|
| 1170 |
+
token_value = int(next_id.item())
|
| 1171 |
+
if token_value in {value for value in (eos_id, file_end_id) if value is not None}:
|
| 1172 |
+
break
|
| 1173 |
+
|
| 1174 |
+
generated_ids = ids[0, len(encoded) :].tolist()
|
| 1175 |
+
output = tokenizer.decode(generated_ids, skip_special_tokens=True)
|
| 1176 |
+
return output.strip()
|
| 1177 |
+
|
| 1178 |
+
|
| 1179 |
+
def resolve_checkpoint(use_smoke: bool) -> Path:
|
| 1180 |
+
selected = SMOKE_CHECKPOINT if use_smoke else MODEL_CHECKPOINT
|
| 1181 |
+
if not selected.exists() and not use_smoke and SMOKE_CHECKPOINT.exists():
|
| 1182 |
+
print("Full model checkpoint not found; using smoke checkpoint.")
|
| 1183 |
+
return SMOKE_CHECKPOINT
|
| 1184 |
+
return selected
|
| 1185 |
+
|
| 1186 |
+
|
| 1187 |
+
def terminal_generate(args: argparse.Namespace) -> None:
|
| 1188 |
+
checkpoint_path = resolve_checkpoint(args.smoke)
|
| 1189 |
+
model, tokenizer, device = load_model_for_inference(checkpoint_path)
|
| 1190 |
+
result = generate_text(
|
| 1191 |
+
model,
|
| 1192 |
+
tokenizer,
|
| 1193 |
+
device,
|
| 1194 |
+
args.prompt,
|
| 1195 |
+
args.mode,
|
| 1196 |
+
args.max_new_tokens,
|
| 1197 |
+
args.temperature,
|
| 1198 |
+
args.top_p,
|
| 1199 |
+
)
|
| 1200 |
+
print(result)
|
| 1201 |
+
|
| 1202 |
+
|
| 1203 |
+
WEB_PAGE = """<!doctype html>
|
| 1204 |
+
<html lang="en">
|
| 1205 |
+
<head>
|
| 1206 |
+
<meta charset="utf-8">
|
| 1207 |
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
| 1208 |
+
<title>JumpLander Python Decoder 100M</title>
|
| 1209 |
+
<style>
|
| 1210 |
+
:root{color-scheme:dark;--bg:#0c0c0e;--panel:#151719;--line:#28392b;--accent:#819e2e;--text:#f9f9f9;--muted:#a7aaa4}
|
| 1211 |
+
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:15px/1.55 Inter,Segoe UI,Arial,sans-serif}
|
| 1212 |
+
main{max-width:980px;margin:34px auto;padding:0 18px}.brand{display:flex;align-items:center;gap:12px;margin-bottom:20px}
|
| 1213 |
+
.logo{width:42px;height:42px;border-radius:14px;background:linear-gradient(145deg,#819e2e,#4b5d2a);display:grid;place-items:center;font-weight:800;color:#0c0c0e}
|
| 1214 |
+
h1{font-size:22px;margin:0}.sub{color:var(--muted);font-size:13px}.card{background:var(--panel);border:1px solid var(--line);border-radius:22px;padding:18px}
|
| 1215 |
+
.controls{display:grid;grid-template-columns:1fr 140px 120px 120px;gap:10px;margin-bottom:12px}select,input,button,textarea{border:1px solid #303430;background:#101210;color:var(--text);border-radius:12px;padding:11px;font:inherit}
|
| 1216 |
+
textarea{width:100%;min-height:190px;resize:vertical;font-family:Consolas,monospace}button{background:var(--accent);color:#0c0c0e;border:0;font-weight:700;cursor:pointer}button:disabled{opacity:.55;cursor:wait}
|
| 1217 |
+
pre{white-space:pre-wrap;min-height:220px;background:#0d0f0d;border:1px solid #252a25;border-radius:14px;padding:16px;overflow:auto;font-family:Consolas,monospace}
|
| 1218 |
+
.status{color:var(--muted);font-size:13px;margin:10px 2px}.note{margin-top:14px;color:var(--muted);font-size:13px}@media(max-width:760px){.controls{grid-template-columns:1fr 1fr}.controls button{grid-column:1/-1}}
|
| 1219 |
+
</style>
|
| 1220 |
+
</head>
|
| 1221 |
+
<body><main>
|
| 1222 |
+
<div class="brand"><div class="logo">JL</div><div><h1>JumpLander Python Decoder 100M</h1><div class="sub">Local from-scratch Python model test console</div></div></div>
|
| 1223 |
+
<div class="card">
|
| 1224 |
+
<div class="controls">
|
| 1225 |
+
<select id="mode"><option value="instruction">English instruction → Python</option><option value="completion">Python code completion</option></select>
|
| 1226 |
+
<input id="tokens" type="number" min="1" max="512" value="160" title="Max new tokens">
|
| 1227 |
+
<input id="temp" type="number" min="0" max="2" step="0.05" value="0.20" title="Temperature">
|
| 1228 |
+
<button id="run">Generate</button>
|
| 1229 |
+
</div>
|
| 1230 |
+
<textarea id="prompt" spellcheck="false">Write a Python function that removes duplicate items while preserving their original order.</textarea>
|
| 1231 |
+
<div id="status" class="status">Ready</div>
|
| 1232 |
+
<pre id="output"></pre>
|
| 1233 |
+
<div class="note">This is a small research model. The smoke checkpoint validates the pipeline; useful quality requires a much larger clean corpus and longer training.</div>
|
| 1234 |
+
</div></main>
|
| 1235 |
+
<script>
|
| 1236 |
+
const run=document.getElementById('run'),status=document.getElementById('status'),output=document.getElementById('output');
|
| 1237 |
+
run.onclick=async()=>{run.disabled=true;status.textContent='Generating…';output.textContent='';const started=performance.now();
|
| 1238 |
+
try{const response=await fetch('/generate',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({prompt:document.getElementById('prompt').value,mode:document.getElementById('mode').value,max_new_tokens:Number(document.getElementById('tokens').value),temperature:Number(document.getElementById('temp').value),top_p:.95})});const data=await response.json();if(!response.ok)throw new Error(data.error||'Generation failed');output.textContent=data.output;status.textContent=`Done in ${((performance.now()-started)/1000).toFixed(2)}s`}
|
| 1239 |
+
catch(error){status.textContent='Error';output.textContent=String(error)}finally{run.disabled=false}};
|
| 1240 |
+
</script></body></html>"""
|
| 1241 |
+
|
| 1242 |
+
|
| 1243 |
+
def run_web_chat(args: argparse.Namespace) -> None:
|
| 1244 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 1245 |
+
|
| 1246 |
+
checkpoint_path = resolve_checkpoint(args.smoke)
|
| 1247 |
+
model, tokenizer, device = load_model_for_inference(checkpoint_path)
|
| 1248 |
+
generation_lock = threading.Lock()
|
| 1249 |
+
|
| 1250 |
+
class Handler(BaseHTTPRequestHandler):
|
| 1251 |
+
def log_message(self, format_string: str, *values: Any) -> None:
|
| 1252 |
+
print("[web]", format_string % values)
|
| 1253 |
+
|
| 1254 |
+
def send_bytes(self, status: int, content_type: str, body: bytes) -> None:
|
| 1255 |
+
self.send_response(status)
|
| 1256 |
+
self.send_header("Content-Type", content_type)
|
| 1257 |
+
self.send_header("Content-Length", str(len(body)))
|
| 1258 |
+
self.send_header("Cache-Control", "no-store")
|
| 1259 |
+
self.end_headers()
|
| 1260 |
+
self.wfile.write(body)
|
| 1261 |
+
|
| 1262 |
+
def do_GET(self) -> None: # noqa: N802
|
| 1263 |
+
if self.path == "/":
|
| 1264 |
+
self.send_bytes(200, "text/html; charset=utf-8", WEB_PAGE.encode("utf-8"))
|
| 1265 |
+
else:
|
| 1266 |
+
self.send_bytes(404, "text/plain; charset=utf-8", b"Not found")
|
| 1267 |
+
|
| 1268 |
+
def do_POST(self) -> None: # noqa: N802
|
| 1269 |
+
if self.path != "/generate":
|
| 1270 |
+
self.send_bytes(404, "application/json", b'{"error":"Not found"}')
|
| 1271 |
+
return
|
| 1272 |
+
try:
|
| 1273 |
+
length = int(self.headers.get("Content-Length", "0"))
|
| 1274 |
+
if length <= 0 or length > 100_000:
|
| 1275 |
+
raise ValueError("Invalid request body")
|
| 1276 |
+
payload = json.loads(self.rfile.read(length))
|
| 1277 |
+
prompt = str(payload.get("prompt", ""))
|
| 1278 |
+
if not prompt.strip() or len(prompt) > 20_000:
|
| 1279 |
+
raise ValueError("Prompt is empty or too long")
|
| 1280 |
+
mode = str(payload.get("mode", "instruction"))
|
| 1281 |
+
if mode not in {"instruction", "completion"}:
|
| 1282 |
+
raise ValueError("Invalid mode")
|
| 1283 |
+
max_new_tokens = min(max(int(payload.get("max_new_tokens", 160)), 1), 512)
|
| 1284 |
+
temperature = min(max(float(payload.get("temperature", 0.2)), 0.0), 2.0)
|
| 1285 |
+
top_p = min(max(float(payload.get("top_p", 0.95)), 0.05), 1.0)
|
| 1286 |
+
with generation_lock:
|
| 1287 |
+
result = generate_text(
|
| 1288 |
+
model,
|
| 1289 |
+
tokenizer,
|
| 1290 |
+
device,
|
| 1291 |
+
prompt,
|
| 1292 |
+
mode,
|
| 1293 |
+
max_new_tokens,
|
| 1294 |
+
temperature,
|
| 1295 |
+
top_p,
|
| 1296 |
+
)
|
| 1297 |
+
body = json.dumps({"output": result}, ensure_ascii=False).encode("utf-8")
|
| 1298 |
+
self.send_bytes(200, "application/json; charset=utf-8", body)
|
| 1299 |
+
except Exception as exc:
|
| 1300 |
+
body = json.dumps({"error": str(exc)}, ensure_ascii=False).encode("utf-8")
|
| 1301 |
+
self.send_bytes(400, "application/json; charset=utf-8", body)
|
| 1302 |
+
|
| 1303 |
+
address = (args.host, args.port)
|
| 1304 |
+
server = ThreadingHTTPServer(address, Handler)
|
| 1305 |
+
url = f"http://{args.host}:{args.port}"
|
| 1306 |
+
print(f"Loaded checkpoint: {checkpoint_path.name}")
|
| 1307 |
+
print(f"Web UI: {url}")
|
| 1308 |
+
if not args.no_browser:
|
| 1309 |
+
threading.Timer(0.8, lambda: webbrowser.open(url)).start()
|
| 1310 |
+
try:
|
| 1311 |
+
server.serve_forever()
|
| 1312 |
+
except KeyboardInterrupt:
|
| 1313 |
+
print("\nStopping web server")
|
| 1314 |
+
finally:
|
| 1315 |
+
server.server_close()
|
| 1316 |
+
|
| 1317 |
+
|
| 1318 |
+
# -----------------------------------------------------------------------------
|
| 1319 |
+
# Diagnostics and CLI
|
| 1320 |
+
# -----------------------------------------------------------------------------
|
| 1321 |
+
def system_check() -> None:
|
| 1322 |
+
print(MODEL_NAME)
|
| 1323 |
+
print("Python:", sys.version.replace("\n", " "))
|
| 1324 |
+
print("PyTorch:", torch.__version__)
|
| 1325 |
+
print("CUDA available:", torch.cuda.is_available())
|
| 1326 |
+
if torch.cuda.is_available():
|
| 1327 |
+
print("GPU:", torch.cuda.get_device_name(0))
|
| 1328 |
+
print("VRAM GB:", round(torch.cuda.get_device_properties(0).total_memory / 1024**3, 2))
|
| 1329 |
+
print("BF16 supported:", torch.cuda.is_bf16_supported())
|
| 1330 |
+
for package in ("datasets", "tokenizers"):
|
| 1331 |
+
try:
|
| 1332 |
+
module = __import__(package)
|
| 1333 |
+
print(f"{package}:", getattr(module, "__version__", "installed"))
|
| 1334 |
+
except ImportError:
|
| 1335 |
+
print(f"{package}: MISSING")
|
| 1336 |
+
for path in (TRAIN_JSONL, VALIDATION_JSONL, TEST_JSONL, TOKENIZER_JSON):
|
| 1337 |
+
print(f"{path.name}:", "present" if path.exists() else "missing")
|
| 1338 |
+
|
| 1339 |
+
|
| 1340 |
+
def model_info() -> None:
|
| 1341 |
+
for config in (FULL_MODEL_CONFIG, SMOKE_MODEL_CONFIG):
|
| 1342 |
+
report = parameter_report(config)
|
| 1343 |
+
print("\n" + config.name)
|
| 1344 |
+
print(json.dumps(dataclasses.asdict(config), indent=2))
|
| 1345 |
+
print(f"parameters: {report['total']:,}")
|
| 1346 |
+
print(f"estimated FP16 weights: {report['total'] * 2 / 1024**2:.1f} MiB")
|
| 1347 |
+
|
| 1348 |
+
|
| 1349 |
+
def build_parser() -> argparse.ArgumentParser:
|
| 1350 |
+
parser = argparse.ArgumentParser(
|
| 1351 |
+
description="JumpLander Python Decoder 100M — one-file from-scratch model project"
|
| 1352 |
+
)
|
| 1353 |
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
| 1354 |
+
|
| 1355 |
+
subparsers.add_parser("check", help="Check Python, PyTorch, CUDA, and local files")
|
| 1356 |
+
subparsers.add_parser("info", help="Show architecture and exact parameter count")
|
| 1357 |
+
|
| 1358 |
+
preview = subparsers.add_parser("dataset-preview", help="Stream and display Python-Edu rows")
|
| 1359 |
+
preview.add_argument("--limit", type=int, default=5)
|
| 1360 |
+
|
| 1361 |
+
prepare_test = subparsers.add_parser("prepare-test", help="Build a small remote test dataset")
|
| 1362 |
+
prepare_test.add_argument("--max-base", type=int, default=2_000)
|
| 1363 |
+
prepare_test.add_argument("--min-score", type=int, default=3)
|
| 1364 |
+
|
| 1365 |
+
prepare = subparsers.add_parser("prepare", help="Build/replace the local dataset from Hugging Face")
|
| 1366 |
+
prepare.add_argument("--max-base", type=int, default=50_000)
|
| 1367 |
+
prepare.add_argument("--min-score", type=int, default=3)
|
| 1368 |
+
|
| 1369 |
+
check_data_parser = subparsers.add_parser("check-data", help="Validate and preview local JSONL files")
|
| 1370 |
+
check_data_parser.add_argument("--show", type=int, default=2)
|
| 1371 |
+
|
| 1372 |
+
tokenizer_parser = subparsers.add_parser("tokenizer", help="Train tokenizer.json from train.jsonl")
|
| 1373 |
+
tokenizer_parser.add_argument("--vocab-size", type=int, default=16_384)
|
| 1374 |
+
|
| 1375 |
+
subparsers.add_parser("build-tokens", help="Create flat uint16 train/validation token files")
|
| 1376 |
+
|
| 1377 |
+
smoke = subparsers.add_parser("smoke", help="Train the small pipeline-validation model")
|
| 1378 |
+
smoke.add_argument("--steps", type=int, default=300)
|
| 1379 |
+
smoke.add_argument("--batch-size", type=int, default=None)
|
| 1380 |
+
smoke.add_argument("--accumulation", type=int, default=None)
|
| 1381 |
+
smoke.add_argument("--resume", action="store_true")
|
| 1382 |
+
|
| 1383 |
+
train = subparsers.add_parser("train", help="Train the ~97.5M parameter model")
|
| 1384 |
+
train.add_argument("--steps", type=int, default=10_000)
|
| 1385 |
+
train.add_argument("--batch-size", type=int, default=None)
|
| 1386 |
+
train.add_argument("--accumulation", type=int, default=None)
|
| 1387 |
+
train.add_argument("--resume", action="store_true")
|
| 1388 |
+
|
| 1389 |
+
generate = subparsers.add_parser("generate", help="Generate code in the terminal")
|
| 1390 |
+
generate.add_argument("prompt")
|
| 1391 |
+
generate.add_argument("--mode", choices=["instruction", "completion"], default="instruction")
|
| 1392 |
+
generate.add_argument("--max-new-tokens", type=int, default=160)
|
| 1393 |
+
generate.add_argument("--temperature", type=float, default=0.2)
|
| 1394 |
+
generate.add_argument("--top-p", type=float, default=0.95)
|
| 1395 |
+
generate.add_argument("--smoke", action="store_true")
|
| 1396 |
+
|
| 1397 |
+
chat = subparsers.add_parser("chat", help="Launch the local browser UI")
|
| 1398 |
+
chat.add_argument("--host", default="127.0.0.1")
|
| 1399 |
+
chat.add_argument("--port", type=int, default=7860)
|
| 1400 |
+
chat.add_argument("--smoke", action="store_true")
|
| 1401 |
+
chat.add_argument("--no-browser", action="store_true")
|
| 1402 |
+
|
| 1403 |
+
return parser
|
| 1404 |
+
|
| 1405 |
+
|
| 1406 |
+
def main() -> None:
|
| 1407 |
+
parser = build_parser()
|
| 1408 |
+
args = parser.parse_args()
|
| 1409 |
+
try:
|
| 1410 |
+
if args.command == "check":
|
| 1411 |
+
system_check()
|
| 1412 |
+
elif args.command == "info":
|
| 1413 |
+
model_info()
|
| 1414 |
+
elif args.command == "dataset-preview":
|
| 1415 |
+
dataset_preview(args.limit)
|
| 1416 |
+
elif args.command == "prepare-test":
|
| 1417 |
+
prepare_remote_dataset(args.max_base, test_mode=True, min_score=args.min_score)
|
| 1418 |
+
elif args.command == "prepare":
|
| 1419 |
+
prepare_remote_dataset(args.max_base, test_mode=False, min_score=args.min_score)
|
| 1420 |
+
elif args.command == "check-data":
|
| 1421 |
+
check_data(args.show)
|
| 1422 |
+
elif args.command == "tokenizer":
|
| 1423 |
+
train_tokenizer(args.vocab_size)
|
| 1424 |
+
elif args.command == "build-tokens":
|
| 1425 |
+
build_tokens()
|
| 1426 |
+
elif args.command == "smoke":
|
| 1427 |
+
train_model(True, args.resume, args.steps, args.batch_size, args.accumulation)
|
| 1428 |
+
elif args.command == "train":
|
| 1429 |
+
train_model(False, args.resume, args.steps, args.batch_size, args.accumulation)
|
| 1430 |
+
elif args.command == "generate":
|
| 1431 |
+
terminal_generate(args)
|
| 1432 |
+
elif args.command == "chat":
|
| 1433 |
+
run_web_chat(args)
|
| 1434 |
+
else:
|
| 1435 |
+
parser.error("Unknown command")
|
| 1436 |
+
except KeyboardInterrupt:
|
| 1437 |
+
print("\nCancelled")
|
| 1438 |
+
except Exception as exc:
|
| 1439 |
+
print(f"ERROR: {type(exc).__name__}: {exc}", file=sys.stderr)
|
| 1440 |
+
if os.environ.get("JL_DEBUG") == "1":
|
| 1441 |
+
traceback.print_exc()
|
| 1442 |
+
raise SystemExit(1) from exc
|
| 1443 |
+
|
| 1444 |
+
|
| 1445 |
+
if __name__ == "__main__":
|
| 1446 |
+
main()
|