由 Rowan E. 出售

Train GPT-2 and GPT-3 class language models in pure C and CUDA with no PyTorch or Python runtime required. Designed for researchers and engineers who want fast, readable, low-dependency LLM pretraining from scratch.
This block provides a pure C and CUDA implementation of GPT-2 and GPT-3 pretraining and fine-tuning, with no dependency on PyTorch or Python at runtime. It targets backend engineers and ML infrastructure teams who need a minimal, auditable, high-performance training loop they can embed in a C/CUDA build pipeline or invoke as a subprocess from a Node.js orchestration layer. The CPU path runs in ~1,000 lines of C; the CUDA path is faster than PyTorch Nightly on single-GPU benchmarks.
.github/ - CI workflow definitions for CPU, GPU, and test pipelinesdev/ - Developer utilities: data downloaders, CUDA benchmarks, evaluation scriptsdoc/ - Documentation and worked examples (e.g. layernorm derivation in C/Python)llmc/ - Core header-only C/CUDA library: dataloader, tokenizer, sampler, schedulers, logger, CUDA/cuDNN helpersscripts/ - Shell scripts for launching single- and multi-node GPT-2/GPT-3 training runsLICENSE - MIT licenseREADME.md - Project overview, quick-start instructions, and architecture notesprofile_gpt2cu.py - Python profiling harness for the CUDA training binaryrequirements.txt - Python dependencies for data preparation and evaluation scriptstest_gpt2.c - Unit test for the GPT-2 C implementationtrain_gpt2.c - CPU fp32 reference training implementation (~1,000 lines)train_gpt2.py - PyTorch reference implementation (nanoGPT-derived)train_llama3.py - PyTorch reference implementation for LLaMA-3 variantThis is a native C/CUDA project. There are no npm packages to install. The build toolchain requirements are:
# No npm install required - this is a native C/CUDA build
# Ensure the following native tools are available:
# Ubuntu / Debian
sudo apt-get install build-essential libgomp1 cuda-toolkit-12-x
# macOS (CPU only)
xcode-select --install
# Python deps for data prep and evaluation only
pip install -r source/requirements.txt
Native build steps required:
make -C source train_gpt2make -C source train_gpt2cu (requires CUDA toolkit ≥ 12.0)启动隔离沙箱并在服务器端直接运行 — 无需本地配置。
此版本的 Tetrees AI Review
This Python, C library / package completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
管道 avcp-2026-08-04.1 · SHA-256 fbe03545857abf19…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
审查日期 2026年8月4日
将此产品直接导入你的 AI IDE、网页构建器或云端 IDE。
将 Tetrees 连接到兼容的 AI IDE,列出你拥有的产品并获取已验证 ZIP,同时不会开放卖家上传权限。
暂无评价。
Sign in to join the discussion
Loading discussion…
make -C source train_gpt2fp32cunpx expo prebuild - this is a pure backend/native target.Copy the source/ directory into your project root, e.g. vendor/llmc/.
Download starter data and model weights:
chmod u+x vendor/llmc/dev/download_starter_pack.sh
./vendor/llmc/dev/download_starter_pack.sh
Build the binary you need from vendor/llmc/:
cd vendor/llmc
make train_gpt2 # CPU fp32
make train_gpt2cu # CUDA bf16/fp32 mixed
make train_gpt2fp32cu # CUDA fp32 only (simpler)
Set environment variables for OpenMP thread count:
export OMP_NUM_THREADS=8
From your Node.js/TypeScript project, invoke the compiled binary as a child process. No tsconfig path aliases are needed since this is a native subprocess integration, not a JS module import.
Place any .bin data files (tokenized datasets, model checkpoints) in a directory accessible to the binary. Default paths expected by the binary are relative to its working directory.
Because llm.c is a C/CUDA native project with no JavaScript/TypeScript exports, the "public API" from a Node.js perspective is the subprocess interface and the header-only C modules in llmc/. The following documents the key C-level interfaces you would call if embedding directly, and the Node.js subprocess wrappers you write around the binary.
import { spawn, ChildProcess } from "child_process";
function trainGpt2(options: {
binaryPath: string; // path to compiled train_gpt2 or train_gpt2cu
dataPath: string; // path to tokenized .bin dataset
ompThreads?: number; // OMP_NUM_THREADS, default 8
extraArgs?: string[]; // additional CLI flags passed to binary
}): ChildProcess;
Spawns the training binary as a managed child process. Use when you need to orchestrate training from a Node.js service, capture stdout loss logs, or integrate with a job queue.
function evaluateGpt2(options: {
binaryPath: string;
checkpointPath: string;
evalScript: string; // path to dev/eval/run_eval.sh
}): Promise<{ hellaswag?: number; mmlu?: number }>;
Runs the evaluation shell script against a saved checkpoint and parses the output. Use after a training run to record benchmark scores in your experiment-tracking database.
function dataPrep(options: {
pythonBin: string; // e.g. "python3"
script: string; // e.g. "vendor/llmc/dev/data/tinyshakespeare.py"
outputDir: string;
}): Promise<void>;
Invokes one of the Python data-preparation scripts under dev/data/ to tokenize and shard a dataset into .bin files. Use during pipeline setup before the training binary is invoked.
A backend service receives a training job request and spawns the CPU binary, streaming loss values to a WebSocket client.
import { spawn } from "child_process";
import * as path from "path";
const binaryPath = path.resolve("vendor/llmc/train_gpt2");
const proc = spawn(binaryPath, [], {
cwd: path.resolve("vendor/llmc"),
env: { ...process.env, OMP_NUM_THREADS: "8" },
});
proc.stdout.on("data", (chunk: Buffer) => {
const line = chunk.toString();
// Parse loss lines, e.g.: "step 10: loss 3.821147 (took 1234.56 ms)"
const match = line.match(/step (\d+): loss ([0-9.]+)/);
if (match) {
console.log(`Step ${match[1]}, Loss: ${match[2]}`);
}
});
proc.stderr.on("data", (chunk: Buffer) => {
console.error("stderr:", chunk.toString());
});
proc.on("exit", (code) => {
console.log("Training exited with code", code);
});
A setup script ensures tokenized data exists before the training binary is launched.
import { execFile, ExecFileException } from "child_process";
import * as path from "path";
import * as util from "util";
const execFileAsync = util.promisify(execFile);
async function prepareData(): Promise<void> {
const script = path.resolve("vendor/llmc/dev/data/tinyshakespeare.py");
const { stdout, stderr } = await execFileAsync("python3", [script]);
if (stdout) console.log(stdout);
if (stderr) console.error(stderr);
console.log("Data preparation complete. .bin files written.");
}
prepareData().catch(console.error);
After training completes and a checkpoint is written, invoke the evaluation pipeline and capture the score.
import { exec } from "child_process";
import * as path from "path";
import * as util from "util";
const execAsync = util.promisify(exec);
async function runEval(checkpointDir: string): Promise<void> {
const evalScript = path.resolve("vendor/llmc/dev/eval/run_eval.sh");
const cmd = `bash ${evalScript} ${checkpointDir}`;
const { stdout, stderr } = await execAsync(cmd, {
cwd: path.resolve("vendor/llmc"),
});
// dev/eval/summarize_eval.py format: "hellaswag: 0.2941"
const match = stdout.match(/hellaswag:\s*([0-9.]+)/i);
if (match) {
console.log("HellaSwag accuracy:", parseFloat(match[1]));
} else {
console.log("Raw eval output:", stdout);
}
if (stderr) console.error(stderr);
}
runEval("./checkpoints/gpt2_124M").catch(console.error);
.github/workflows/ - CI pipelines: ci.yml (general), ci_gpu.yml (GPU runners), ci_tests.yml (unit tests)dev/cpu/ - CPU-only development kernels, e.g. matmul_forward.c for reference matmuldev/cuda/ - CUDA kernel development files, common header, Modal benchmark runnerdev/data/ - Python scripts to download and tokenize datasets: FineWeb, TinyShakespeare, TinyStories, HellaSwag, MMLUdev/eval/ - Evaluation pipeline: export to HuggingFace format, run evals, summarize resultsdoc/layernorm/ - Derivation and reference implementation of layer normalization in C and Pythonllmc/ - Header-only C/CUDA library modules: dataloader.h, tokenizer.h, sampler.h, schedulers.h, logger.h, rand.h, mfu.h, outlier_detector.h, cuda_common.h, cublas_common.h, cudnn_att.hscripts/ - Turnkey shell scripts for launching GPT-2 (124M–1558M) and GPT-3 125M training, including multi-node MPI varianttrain_gpt2.c - ~1,000-line single-file CPU fp32 GPT-2 training reference implementationtest_gpt2.c - Unit tests validating forward/backward pass numerics against saved debug statestrain_gpt2.py / train_llama3.py - PyTorch reference implementations for cross-validationprofile_gpt2cu.py - Python script for profiling the CUDA binary with Nsight/py-spyrequirements.txt - Python packages needed for data prep and eval (not for the C binary itself)train_gpt2cu requires CUDA ≥ 12.0; check with nvcc --version and update via cuda-toolkit-12-x package..bin data files at binary startup: The binary expects tokenized .bin files in its working directory; always run download_starter_pack.sh or a data-prep script before launching.OMP_NUM_THREADS not set: Without this env var, OpenMP may spawn too many threads and thrash on small machines; always set it explicitly before invoking the binary.make must be run from vendor/llmc/ (where the Makefile lives), not from your project root; use make -C vendor/llmc train_gpt2.requirements.txt into the same Python environment used to run dev/eval/ and dev/data/ scripts; a separate venv is recommended.scripts/multi_node/run_gpt2_124M_mpi.sh requires mpirun and all nodes to share a filesystem for checkpoints; confirm NFS mount and mpirun version compatibility before use.I have purchased the "llm.c: LLM Training in Pure C/CUDA" source block.
The source is located at vendor/llmc/ in my project.
There is a USAGE.md at vendor/llmc/USAGE.md with full integration instructions.
My project is a Node.js/TypeScript backend service (Express, TypeScript 5, Node 20).
Please help me integrate llm.c step by step:
1. Read USAGE.md and the file listing under vendor/llmc/ to understand
the structure. Do not invent any APIs or filenames not listed there.
2. Add a build step in my package.json scripts section that runs
`make -C vendor/llmc train_gpt2` for CPU and optionally
`make -C vendor/llmc train_gpt2cu` for CUDA.
3. Create a TypeScript module at src/llmc/runner.ts that exports functions
to: (a) prepare data by spawning the relevant dev/data Python script,
(b) launch a training run via the compiled binary with configurable
OMP_NUM_THREADS and working directory, and (c) run post-training evaluation
via dev/eval/run_eval.sh and return parsed accuracy metrics.
4. Wire error handling so non-zero exit codes from child processes throw
typed errors in TypeScript.
5. Add a route in my Express app at POST /api/train that accepts a JSON body
with { dataset, threads, cuda } and kicks off a training job, streaming
stdout loss lines back to the client via Server-Sent Events.
Use only the real file paths and binary names from USAGE.md and the file listing.
The upstream project is llm.c (https://github.com/karpathy/llm.c).
llm.c is released under the MIT License. See source/LICENSE for the full text. The project is authored by Andrej Karpathy and contributors. Upstream repository: https://github.com/karpathy/llm.c. The PyTorch reference implementation (train_gpt2.py) is derived from nanoGPT, also MIT licensed.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完整安装指南与集成提示词将在购买后解锁。
SaaS, AI & Subscription Products
免费