JBit / Jacobit

A header-oriented C++20 framework for building, training and serving neural networks: dense, convolutional, recurrent, decoder-only & encoder-decoder transformers, BBPE/Unigram tokenizers, streaming corpus pre-training, multi-GPU CUDA, and an OpenAI-compatible HTTP server.

206 Headers 305 Classes 7,233 Members 20 C++20 Examples 19 Modular API Pages

1. What is in the box

AreaMain classesUse it for
Sequential networksTrainingModel, TrainingModelBuilderDense, dropout, conv1d/2d/3d, pooling, mixed stacks; tabular data, images, regression, classification
RecurrentTrainingRnnModelRNN / LSTM / GRU, bidirectional; time series, sequences
Decoder-only transformerTrainingDecoderOnlyModelLanguage models, chat assistants (GPT / Llama style)
Encoder-decoder transformerTrainingEncoderDecoderModelTranslation, summarisation, seq2seq (T5 style)
Legacy transformersTrainingTransformerModel, …MTransformer…, …Modern…Classic single-pass transformer variants
Inference modelsInference*ModelLean, forward-only models loaded from ONNX / GGUF / checkpoints
TokenizersByteLevelBPETokenizer, BertStyleTokenizerBPE / Unigram / WordPiece, tokenizer.json compatible, model-size advisor
Corpus & chatcorpus::*, ChatConversationStreaming pre-training, resumable checkpoints, multi-turn chat tuning
CUDAgpu::*GPU training / inference, cuBLAS, multi-GPU (replicate, layer split, hybrid)
I/OBitmap, AudioPNG / JPEG / BMP, WAV / MP3 / AAC, Log-Mel spectrograms & MFCCs
ServingJBitServerOpenAI-compatible /v1/chat/completions with SSE streaming

2. Build & install — interactive configurator

JBit builds with CMake (C++20). Toggle the model families and options you need to generate a tailored build command.

Model families
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DJACOBIT_MODELS="DECODER_ONLY" -DJACOBIT_MAIN_SOURCE=$PWD/src/my_app.cpp -DJACOBIT_ENABLE_CUDA=AUTO
cmake --build build -j
./build/Jacobit
Without a GPU, build with -DJACOBIT_ENABLE_CUDA=OFF (or leave AUTO: CUDA is used only when a toolkit is found). Whether CUDA is actually used is decided per model at run time (setCudaTrainingEnabled, builder .cuda() / .cudaIfAvailable()).

3. Quick start

The same shape applies to every model: create → configure → train → save → infer. Pick a workflow:

xor_quickstart.cpp · C++20
#include "Jacobit.hpp"
using namespace JBit;

int main() {
    // 1. data: samples of shape 1 x N
    std::vector<std::vector<std::vector<real_t>>> x = {{{0,0}},{{0,1}},{{1,0}},{{1,1}}};
    std::vector<std::vector<std::vector<real_t>>> y = {{{0}},{{1}},{{1}},{{0}}};

    // 2. create + configure
    auto &m = Jacobit::createTrainingModel(0.05f, TrainingModel::ADAM, TrainingModel::MEAN_SQUARED_ERROR)
        .withDataset(x, y).input(2).denseTanh(8).denseSigmoid(1).build();

    // 3. train, 4. save
    m.setMonitorEnabled(true);
    m.train(2000);
    m.save("xor.bin");
}
lm_quickstart.cpp · C++20
#include "Jacobit.hpp"
using namespace JBit;

int main() {
    // 1. tokenizer from your text
    ByteLevelBPETokenizer tok;
    tok.trainFromFile("corpus.txt", 8000, 2);

    // 2. model (or let tok.recommendModel() suggest the shape)
    TrainingDecoderOnlyModel m(4, tok.getVocabSize(), 256, 1024, 8, 256, 2, 6e-4f, TrainingModel::ADAM_W);
    m.setPreLayerNorm(true);
    m.setMaxGlobalStep(5000);

    // 3. stream-train with checkpoints (resumes automatically when re-run)
    m.smartPreTraining("corpus.txt", "<|endoftext|>", tok, 0, 1, "lm.ckpt", 500);
    m.save("lm.bin");

    // 4. generate
    m.setBBPETokenizer(tok);
    m.testPreTrain(tok.getVocabulary(), 64, "Once upon a time", &std::cout);
}
chat_quickstart.cpp · C++20
// start from a pre-trained decoder-only model, then train on conversations
TrainingDecoderOnlyModel m(4, tok.getVocabSize(), 256, 1024, 8, 256, 2, 1e-4f, TrainingModel::ADAM_W);
m.load("lm.bin");

m.smartChatFineTune("chats.jsonl", "\n", tok, ChatFormat(), ChatOptions(), 0, 2, "chat.ckpt", 200);

ChatConversation q; q.user("Hello!");
m.chatInference(q, tok, ChatOptions(), 128, &std::cout);
seq2seq_quickstart.cpp · C++20
TrainingEncoderDecoderModel m(2, 2, tok.getVocabSize(), 128, 512, 4, 64, 2, 1e-3f, TrainingModel::ADAM_W);
auto src = TrainingEncoderDecoderModel::tokenize(sources, tok, 64, 128);
auto tgt = TrainingEncoderDecoderModel::tokenize(targets, tok, 64, 128);
m.fineTune(src, tgt, 64, 50);

m.setBBPETokenizer(tok);
auto q = m.tokenize("good morning", tok, 64, 128);
m.inference(q, 32, &std::cout);
server_quickstart.cpp · C++20
auto server = Jacobit::startJBitServer([&](const ServerRequest &req, std::ostream &out) {
    ChatConversation c;
    for (auto &msg : req.messages) {
        if (msg.role == "system") c.system(msg.content);
        else if (msg.role == "assistant") c.assistant(msg.content);
        else c.user(msg.content);
    }
    model.chatInference(c, tok, ChatOptions(), 128, &out);
    return std::string();
}, 8080);
// curl localhost:8080/v1/chat/completions -d '{"messages":[{"role":"user","content":"hi"}],"stream":true}'
server->waitUntilStopped();

4. Core concepts

Facade & builders
Jacobit::createTraining…Model(name, lr, optimizer, loss) returns a fluent builder; every setter returns the builder; .build() returns the model reference.
Models are objects too
Construct TrainingDecoderOnlyModel(blocks, vocab, d, ff, heads, context, types, lr, optimizer) directly, or assemble step by step.
Global step
Every model counts optimizer steps (getGlobalStep()). The LR schedule follows setMaxGlobalStep(); checkpoints store the step so resuming continues the schedule.
Payload tensors
Text enters transformers as PayloadTensor1D (token ids + attention mask + type ids). Model::tokenize(...) builds them from strings.
Micro-batch & effective batch
Memory is set by the micro-batch, optimisation by the effective batch: setEffectiveBatchSize(64, 8) accumulates 8 micro-batches per update.
Streaming training
smart* functions read files lazily (constant memory), pack sequences, and checkpoint the corpus position so a killed run resumes exactly.
Naming family
preTrain / mergedPreTraining / smartPreTraining, fineTune / mergedFineTune / smartFineTuning, chatFineTune / mergedChatFineTune / smartChatFineTune.
Enums
Optimizers: SGD, ADAM, ADAM_W, RMSPROP… Schedulers: COSINE_ANNEALING, WARMUP_STABLE_DECAY, ONE_CYCLE… Positional encodings: ROPE (default), SINUSOIDAL, LEARNED, ALIBI, YARN…

5. Which model should I use? — interactive chooser

Select your data modality to get a recommended JBit model class, C++20 code snippet, and links to runnable examples.

6. Model size simulator & live C++20 code generator

Exact parameter count of a TrainingDecoderOnlyModel plus training memory (weights + gradients + optimizer moments + backward activations) and compute estimate, with a dynamically updated C++20 builder suggestion.

Quick Model Presets
41.61 M parameters (L=8, d=512, ff=2048, H=8, V=16000, ctx=1024). Adjust inputs to simulate memory, FLOPs, and generate C++ code.

7. More documents shipped with the project

DocumentTopic
TOKENIZER.mdTokenizer formats, training, the model-size advisor and its sources
CORPUS_TRAINING.mdStreaming corpus training, packing, checkpoint / resume
CHAT_FINE_TUNING.mdChat templates, loss masking, formats (JSON / ShareGPT / Alpaca / tagged)
GRADIENT_ACCUMULATION.mdMicro-batching and effective batch sizes
MULTI_GPU.mdReplicate / layer-split / hybrid, failure policies
README_CUDA.mdCUDA backend, cuBLAS, kernels
SERVER.mdHTTP API, options, limits