Examples

20 complete programs, from a first XOR network to a restartable pipeline that trains, chat-tunes, exports and serves a model. Filter by difficulty level, topic category, or keyword.

Difficulty Level
Categories & Topics
Showing 20 of 20 examples
Beginner

1. Your first network: XOR with a dense stack

Build a small fully-connected network with the fluent builder, train it and read the prediction back. Every sample is a 1 x N "row": inputs[i][0] is the input vector and targets[i][0] the expected output.

01_hello_xor.cpp · C++20
#include "Jacobit.hpp"
#include <iostream>
using namespace JBit;

int main() {
    std::vector<std::vector<std::vector<real_t>>> inputs, targets;
    auto add = [&](real_t a, real_t b, real_t y) { inputs.push_back({{a, b}}); targets.push_back({{y}}); };
    add(0, 0, 0); add(0, 1, 1); add(1, 0, 1); add(1, 1, 0);

    // createTrainingModel(learningRate, optimizer, lossFunction) returns a builder; build() returns the model
    auto &model = Jacobit::createTrainingModel(0.05f, TrainingModel::ADAM, TrainingModel::MEAN_SQUARED_ERROR)
        .withDataset(inputs, targets)
        .input(2)              // 2 input nodes
        .denseTanh(8)          // hidden layer: 8 nodes, tanh
        .denseSigmoid(1)       // output layer: 1 node, sigmoid
        .build();

    model.setMonitorEnabled(true);      // live progress line (loss, ETA)
    model.setPrintLossEnabled(true);
    model.train(2000);                  // 2000 epochs

    // Inference: InferenceModel is the lean forward-only copy of a trained model
    InferenceModel inf(model);
    for (auto in : std::vector<std::vector<real_t>>{{0, 0}, {0, 1}, {1, 0}, {1, 1}})
        std::cout << in[0] << " xor " << in[1] << " -> " << inf.predict(in).toString() << "\n";
    return 0;
}
Beginner

2. Save, load and resume from a checkpoint

save() writes weights and optimizer state, so a model can be loaded for inference or training can continue where it stopped. The builder can start from a checkpoint with fromCheckpoint.

02_save_load.cpp · C++20
#include "Jacobit.hpp"
#include <iostream>
using namespace JBit;

int main() {
    // A decoder-only language model, assembled directly: (blocks, vocab, d_model, d_ff, heads, context, typeVocab, lr, optimizer)
    TrainingDecoderOnlyModel model(2, /*vocab*/ 512, /*d*/ 64, /*ff*/ 256, /*heads*/ 4, /*context*/ 128, /*types*/ 2,
                                   3e-4f, TrainingModel::ADAM_W);
    model.save("model.bin");                         // weights + optimizer moments + global step

    TrainingDecoderOnlyModel again(2, 512, 64, 256, 4, 128, 2, 3e-4f, TrainingModel::ADAM_W);
    again.load("model.bin");                         // same architecture required
    std::cout << "global step after load: " << again.getGlobalStep() << "\n";

    // Or through the builder (architecture is read from the file):
    auto &resumed = Jacobit::createTrainingDecoderOnlyModel("resumed")
                        .fromCheckpoint("model.bin")
                        .build();
    (void)resumed;
    return 0;
}
Beginner

3. Optimizers, losses and learning-rate schedules

The optimizer and the loss are enum values given when the model is created (or changed later); the learning-rate schedule is selected with learningRateScheduler. All schedules start with a linear warm-up.

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

int main() {
    auto &model = Jacobit::createTrainingDecoderOnlyModel("lm", /*lr*/ 3e-4f, TrainingModel::ADAM_W, TrainingModel::CROSS_ENTROPY)
        .vocabularySize(512).modelDimension(64).feedForwardDimension(256).headCount(4)
        .decoderBlock(2).contextWindow(128)
        .learningRateScheduler(Model::COSINE_ANNEALING)   // others: LINEAR_DECAY, WARMUP_STABLE_DECAY, ONE_CYCLE,
                                                          // INVERSE_SQRT_DECAY, COSINE_WITH_RESTARTS, STEP_DECAY, ...
        .warmupSteps(100)                                 // linear warm-up, then decay
        .minLearningRate(3e-5f)                           // floor of the decay
        .gradientClipping(1.0f)                           // clip the global gradient norm
        .weightDecay(0.1f)                                // AdamW decoupled decay
        .build();
    (void)model;
    return 0;
}
Intermediate

4. Convolutional network (conv2d + pooling + dense)

The same fluent builder stacks convolution, pooling and dense layers. nodeCount describes the spatial size, channelCount the number of channels. This one learns to reproduce an 8x8 image (an auto-encoder warm-up).

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

int main() {
    std::vector<std::vector<std::vector<real_t>>> inputs, targets;
    for (int level = 1; level <= 10; ++level) {
        std::vector<real_t> img(8 * 8, static_cast<real_t>(level));
        inputs.push_back({img});
        targets.push_back({img});
    }

    auto &cnn = Jacobit::createTrainingModel(0.0015f, TrainingModel::ADAM, TrainingModel::MEAN_SQUARED_ERROR)
        .withDataset(inputs, targets)
        .input(/*nodeCount*/ {8, 8})
        .conv2d(/*channels*/ 1, /*nodeCount*/ {8, 8}, /*kernel*/ {3, 3}, /*stride*/ {1, 1}, /*padding*/ {1, 1})
        .maxPooling2d(/*pool*/ {3, 3}, /*stride*/ {1, 1}, /*padding*/ {1, 1})
        .denseLeakyRelu(8 * 8)
        .build();

    cnn.setMonitorEnabled(true);
    cnn.train(500);
    return 0;
}
Intermediate

5. Recurrent network (LSTM) on sequences

createTrainingRnnModel builds RNN / LSTM / GRU stacks (also bidirectional). returnSequences decides whether a layer outputs every time step or only the last one. Here: predict the next value of a ramp.

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

int main() {
    const size_t T = 6;                                    // time steps per sample
    std::vector<std::vector<std::vector<real_t>>> inputs, targets;
    for (int start = 0; start < 40; ++start) {
        std::vector<std::vector<real_t>> seq;              // T rows of 1 feature
        for (size_t t = 0; t < T; ++t) seq.push_back({static_cast<real_t>(start + t) / 50.0f});
        inputs.push_back(seq);
        targets.push_back({{static_cast<real_t>(start + T) / 50.0f}});   // next value
    }

    auto &rnn = Jacobit::createTrainingRnnModel(0.01f, TrainingModel::ADAM, TrainingModel::MEAN_SQUARED_ERROR)
        .withDataset(inputs, targets)
        .input(/*sequenceLength*/ T, /*featureSize*/ 1)
        .lstm(/*hidden*/ 16, /*returnSequences*/ false)
        .dense(1, Model::LINEAR)
        .build();

    rnn.setMonitorEnabled(true);
    rnn.train(300);

    Tensor1D next = rnn.predict(std::vector<real_t>{0.10f, 0.12f, 0.14f, 0.16f, 0.18f, 0.20f});
    (void)next;
    return 0;
}
Intermediate

6. Train, use and save a byte-level BPE tokenizer

The tokenizer family is compatible with Hugging Face tokenizer.json (GPT-2 / RoBERTa / Llama-3 / T5 style). Train from sentences or straight from a file, encode/decode, add special tokens, save and reload.

06_tokenizer.cpp · C++20
#include "Jacobit.hpp"
#include <iostream>
using namespace JBit;

int main() {
    std::vector<std::string> corpus = {
        "the cat sat on the mat", "the dog chased the cat", "a bird sang in the tree",
        "the quick brown fox jumps over the lazy dog", "cats and dogs are friends"};

    // BPE: target vocabulary of 300 pieces, merge pairs seen at least twice
    ByteLevelBPETokenizer tok = Jacobit::trainBBPETokenizer(corpus, 300, 2, /*saveJsonPath*/ "tokenizer.json");

    std::vector<int> ids = tok.encodeSingleString("the cat sat");
    std::cout << tok.decode(ids) << "  (" << ids.size() << " tokens, vocab " << tok.getVocabSize() << ")\n";

    // Larger corpora: stream the training from a file
    // ByteLevelBPETokenizer big; big.trainFromFile("corpus.txt", 32000, 2);

    // SentencePiece-style Unigram model instead of BPE
    ByteLevelBPETokenizer uni = Jacobit::trainUnigramTokenizer(corpus, 200);

    // Reload later (also loads tokenizers exported by Hugging Face)
    ByteLevelBPETokenizer reloaded = Jacobit::loadTokenizerJson("tokenizer.json");
    std::cout << "special <|endoftext|> id: " << reloaded.specialTokenId("endoftext") << "\n";
    (void)uni;
    return 0;
}
Intermediate

7. Let the advisor size your model from your data

After training a tokenizer, recommendModel turns the corpus statistics and your hardware limits into a model shape (layers, width, heads), a vocabulary size, epochs, learning rate and batch size. These are heuristics from the scaling-law literature, not guarantees: validate with a short pilot run.

07_tokenizer_advisor.cpp · C++20
#include "Jacobit.hpp"
#include <iostream>
using namespace JBit;

int main() {
    ByteLevelBPETokenizer tok;
    tok.trainFromFile("corpus.txt", 8000, 2);

    AdvisorOptions opt;
    opt.architecture = AdvisorOptions::DECODER_ONLY;
    opt.preLayerNorm = true;
    opt.memoryBytes = 8ull << 30;                 // 8 GiB of GPU memory
    opt.sustainedFlopsPerSecond = 5e12;           // measured, not the marketing number
    opt.computeBudgetFlops = 5e17;                // what you are willing to spend

    tok.printTrainingAdvice(std::cout, opt);      // human-readable report

    ModelRecommendation rec = tok.recommendModel(opt);
    auto &model = Jacobit::createTrainingDecoderOnlyModel("advised", 3e-4f)
        .bbpeTokenizer(tok)
        .modelDimension(rec.modelDimension)
        .feedForwardDimension(rec.feedForwardDimension)
        .headCount(rec.heads)
        .decoderBlock(rec.layers)
        .contextWindow(512)
        .preLayerNorm()
        .build();
    (void)model;
    return 0;
}
Intermediate

8. Pre-train a small language model and stream generated text

mergedPreTraining packs several short sentences into each sequence (with isolated attention segments) which is much faster than one sentence per sample. testPreTrain generates text and can write tokens to any std::ostream as they appear.

08_decoder_pretrain_generate.cpp · C++20
#include "Jacobit.hpp"
#include <iostream>
using namespace JBit;

int main() {
    std::vector<std::string> sentences = {
        "the cat sat on the mat", "the dog chased the cat", "a bird sang in the tree",
        "the cat and the dog are friends", "the bird flew over the mat"};
    ByteLevelBPETokenizer tok = Jacobit::trainBBPETokenizer(sentences, 300, 2);

    const size_t ctx = 32;
    TrainingDecoderOnlyModel model(2, tok.getVocabSize(), 64, 256, 4, ctx, 2, 3e-3f, TrainingModel::ADAM_W);
    model.setMonitorEnabled(true);

    // tokenize -> payload tensors, then train
    auto batches = TrainingDecoderOnlyModel::tokenize(sentences, tok, ctx, /*modelDimension*/ 64);
    model.mergedPreTraining(batches, ctx, /*epochs*/ 200);

    PayloadTensor1D prompt = model.tokenize("the cat", tok, ctx, 64);
    model.setBBPETokenizer(tok);
    model.inference(prompt, /*max_len*/ 24, &std::cout);       // tokens are printed as they are generated
    return 0;
}
Advanced

9. A realistic decoder-only configuration (builder)

The settings that matter for a language model of a few tens of millions of parameters: pre-LayerNorm, mean loss gradient, global gradient clipping, AdamW with decoupled weight decay, warm-up + cosine schedule, gradient accumulation for a large effective batch, flash attention for long windows.

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

int main() {
    ByteLevelBPETokenizer tok = Jacobit::loadTokenizerJson("tokenizer.json");

    auto &model = Jacobit::createTrainingDecoderOnlyModel("lm-30m", /*lr*/ 6e-4f, TrainingModel::ADAM_W)
        .bbpeTokenizer(tok)                       // vocabulary size is taken from the tokenizer
        .modelDimension(512).feedForwardDimension(2048).headCount(8).decoderBlock(8)
        .contextWindow(1024)
        .preLayerNorm()                           // stable at depth; post-LN is the original (default) layout
        .flashAttention()                         // O(L) attention memory
        .learningRateScheduler(Model::COSINE_ANNEALING)
        .warmupSteps(500).minLearningRate(6e-5f)
        .gradientClipping(1.0f)
        .weightDecay(0.1f)
        .effectiveBatchSize(64, /*micro-batch*/ 8) // 8 accumulation steps of 8 samples
        .cudaIfAvailable()                        // falls back to the CPU when no GPU / CUDA build
        .build();

    model.setLossGradientMean(true);              // average (not sum) the loss gradient over tokens
    model.setMonitorEnabled(true);
    model.setProgressReportInterval(200);
    (void)model;
    return 0;
}
Advanced

10. Pre-train on a file larger than RAM, with checkpoint and resume

smartPreTraining streams the file (constant memory), tokenizes and packs on the fly, and writes a checkpoint every N steps containing weights, optimizer state, global step and the position in the corpus. Re-running the same program after a crash continues where it stopped.

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

int main() {
    ByteLevelBPETokenizer tok = Jacobit::loadTokenizerJson("tokenizer.json");

    TrainingDecoderOnlyModel model(6, tok.getVocabSize(), 384, 1536, 6, 512, 2, 6e-4f, TrainingModel::ADAM_W);
    model.setPreLayerNorm(true);
    model.setMaxGlobalStep(50000);                    // the learning-rate schedule follows this length
    model.setEffectiveBatchSize(32, 4);
    model.setMonitorEnabled(true);

    // documents in corpus.txt are separated by "<|endoftext|>"
    model.smartPreTraining("corpus.txt", "<|endoftext|>", tok,
                           /*max_len*/ 0,              // 0 = the model's context window
                           /*epochs*/ 1,
                           /*checkpoint*/ "pretrain.ckpt",
                           /*every*/ 500);             // steps between checkpoints
    model.save("final.bin");
    return 0;
}
Advanced

11. Fine-tune on question/answer pairs

Three ways, from simplest to most scalable: tokenized batches (fineTune), packed in-memory strings (mergedFineTune) or a streamed file with a Q/A separator (smartFineTuning).

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

int main() {
    ByteLevelBPETokenizer tok = Jacobit::loadTokenizerJson("tokenizer.json");
    TrainingDecoderOnlyModel model(6, tok.getVocabSize(), 384, 1536, 6, 512, 2, 1e-4f, TrainingModel::ADAM_W);
    model.load("final.bin");
    model.setMonitorEnabled(true);

    std::vector<std::string> questions = {"what is the capital of france", "what is two plus two"};
    std::vector<std::string> answers   = {"paris", "four"};

    // 1) explicit batches
    auto q = TrainingDecoderOnlyModel::tokenize(questions, tok, 64, 384);
    auto a = TrainingDecoderOnlyModel::tokenize(answers,   tok, 64, 384);
    model.fineTune(q, a, /*max_len*/ 64, /*epochs*/ 3);

    // 2) several pairs per sequence (faster on short pairs)
    model.mergedFineTune(q, a, /*max_len*/ 64, /*epochs*/ 3, /*requireGlobalStepReset*/ false);

    // 3) streamed from a file: records separated by "<|endoftext|>", question and answer by "<|answer|>"
    model.smartFineTuning("qa.txt", "<|endoftext|>", "<|answer|>", tok,
                          0, 2, "finetune.ckpt", 200);
    return 0;
}
Advanced

12. Chat (multi-turn) fine-tuning

Conversations are trained as one sequence with the loss on assistant turns only (and the end-of-turn token, so the model learns to stop). Works for decoder-only and encoder-decoder. Details: CHAT_FINE_TUNING.md.

12_chat_finetune.cpp · C++20
#include "Jacobit.hpp"
#include <iostream>
using namespace JBit;

int main() {
    ByteLevelBPETokenizer tok = Jacobit::loadTokenizerJson("tokenizer.json");   // needs the chat special tokens (default catalogue)
    TrainingDecoderOnlyModel model(6, tok.getVocabSize(), 384, 1536, 6, 512, 2, 1e-4f, TrainingModel::ADAM_W);
    model.load("final.bin");

    ChatConversation c;
    c.system("You are a helpful assistant.")
     .user("What is 2+2?").assistant("4")
     .user("And 3+3?").assistant("6");
    std::vector<ChatConversation> data = {c};

    ChatOptions opt;                       // defaults: loss on assistant + end-of-turn, long chats are split in windows
    opt.defaultSystemPrompt = "You are a helpful assistant.";

    model.chatFineTune(data, tok, opt, /*max_len*/ 0, /*epochs*/ 3);
    model.mergedChatFineTune(data, tok, opt, 0, 3);                    // pack windows into long sequences (decoder-only)

    // Large datasets: JSON lines / ShareGPT / Alpaca / tagged text, streamed with checkpoint + resume
    model.smartChatFineTune("chats.jsonl", "\n", tok, ChatFormat(), opt, 0, 1, "chat.ckpt", 200);

    // Talk to it; the same template is used as in training
    ChatConversation q;
    q.user("What is 5+5?");
    model.chatInference(q, tok, opt, /*maxLen*/ 64, &std::cout);
    return 0;
}
Advanced

13. Large effective batches with gradient accumulation

One optimizer step every micro x accumulation samples. Memory is set by the micro-batch, the optimisation behaviour by the effective batch. Works on every model and on the CPU and CUDA backends.

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

int main() {
    TrainingDecoderOnlyModel model(4, 8000, 256, 1024, 8, 256, 2, 6e-4f, TrainingModel::ADAM_W);

    model.setEffectiveBatchSize(64, 4);        // 64 samples per update, micro-batches of 4 (16 accumulation steps)

    // Same thing through the builder
    auto &viaBuilder = Jacobit::createTrainingDecoderOnlyModel("acc")
        .vocabularySize(8000).modelDimension(256).feedForwardDimension(1024).headCount(8).decoderBlock(4)
        .contextWindow(256)
        .effectiveBatchSize(64, 4)
        .build();
    (void)viaBuilder;
    return 0;
}
Advanced

14. Encoder-decoder (sequence-to-sequence)

The encoder reads the source, the decoder writes the target while attending to it through cross-attention. Typical for translation, summarization and structured rewriting. fineTune takes source and target batches.

14_encoder_decoder.cpp · C++20
#include "Jacobit.hpp"
#include <iostream>
using namespace JBit;

int main() {
    std::vector<std::string> source = {"hello world", "good morning", "thank you"};
    std::vector<std::string> target = {"bonjour le monde", "bonjour", "merci"};
    std::vector<std::string> all = source;
    all.insert(all.end(), target.begin(), target.end());
    ByteLevelBPETokenizer tok = Jacobit::trainBBPETokenizer(all, 300, 2);

    const size_t ctx = 24;
    // (encoder blocks, decoder blocks, vocab, d_model, d_ff, heads, context, typeVocab, lr, optimizer)
    TrainingEncoderDecoderModel model(2, 2, tok.getVocabSize(), 64, 256, 4, ctx, 2, 3e-3f, TrainingModel::ADAM_W);
    model.setMonitorEnabled(true);

    auto src = TrainingEncoderDecoderModel::tokenize(source, tok, ctx, 64);
    auto tgt = TrainingEncoderDecoderModel::tokenize(target, tok, ctx, 64);
    model.fineTune(src, tgt, ctx, /*epochs*/ 300);

    model.setBBPETokenizer(tok);
    PayloadTensor1D query = model.tokenize("good morning", tok, ctx, 64);
    model.inference(query, /*max_len*/ 16, &std::cout);
    return 0;
}
Expert

15. CUDA, cuBLAS and multi-GPU

CUDA is chosen at run time per model (a CPU-only build simply ignores it). Multi-GPU can replicate the model for data parallelism, split layers across cards (capacity), or combine both (HYBRID). Build options: -DJACOBIT_ENABLE_CUDA=ON -DJACOBIT_CUDA_CUBLAS=ON. See MULTI_GPU.md.

15_gpu_multigpu.cpp · C++20
#include "Jacobit.hpp"
#include <iostream>
using namespace JBit;

int main() {
    std::string why;
    if (!TrainingDecoderOnlyModel::isCudaAvailable(&why))
        std::cout << "no CUDA backend: " << why << " (running on the CPU)\n";

    // 1) single GPU
    TrainingDecoderOnlyModel one(6, 32000, 512, 2048, 8, 512, 2, 6e-4f, TrainingModel::ADAM_W);
    one.setCudaTrainingEnabled(true);
    one.setCudaInferenceEnabled(true);
    one.setCudaDevice(0);

    // 2) all usable GPUs, data parallel; AUTO weights shares by measured speed
    auto &many = Jacobit::createTrainingDecoderOnlyModel("big")
        .vocabularySize(32000).modelDimension(1024).feedForwardDimension(4096).headCount(16).decoderBlock(24)
        .contextWindow(1024)
        .cuda()
        .multiGpuAuto()
        .build();
    std::cout << many.getParallelism() << "\n";

    // 3) model too big for one card: 4 GPUs as 2 pipelines of 2 stages
    auto &hybrid = Jacobit::createTrainingDecoderOnlyModel("huge")
        .vocabularySize(32000).modelDimension(2048).feedForwardDimension(8192).headCount(16).decoderBlock(32)
        .contextWindow(1024)
        .cuda()
        .multiGpu("manual;devices=0,1,2,3;policy=hybrid;stages=2")
        .onGpuFailure(gpu::FailurePolicy::CONTINUE, gpu::OomPolicy::DROP)
        .build();
    (void)hybrid;
    return 0;
}
Expert

16. Serve a model through an OpenAI-compatible HTTP API

startJBitServer returns immediately and serves /v1/chat/completions (with SSE streaming), /v1/completions, /v1/models and /health from background threads. Your callback receives the parsed request and writes tokens to the stream it is given. Details: SERVER.md.

16_server.cpp · C++20
#include "Jacobit.hpp"
#include <iostream>
using namespace JBit;

int main() {
    ByteLevelBPETokenizer tok = Jacobit::loadTokenizerJson("tokenizer.json");
    TrainingDecoderOnlyModel model(6, tok.getVocabSize(), 384, 1536, 6, 512, 2, 1e-4f, TrainingModel::ADAM_W);
    model.load("chat-model.bin");

    ServerOptions options;
    options.port = 8080;
    options.modelName = "jbit-chat";
    options.apiKey = "change-me";                 // clients send  Authorization: Bearer change-me

    auto server = Jacobit::startJBitServer([&](const ServerRequest &req, std::ostream &out) {
        ChatConversation conv;                    // rebuild the conversation with the SAME template as training
        for (const auto &m : req.messages) {
            if (m.role == "system") conv.system(m.content);
            else if (m.role == "assistant") conv.assistant(m.content);
            else conv.user(m.content);
        }
        model.chatInference(conv, tok, ChatOptions(), req.maxTokens ? req.maxTokens : 128, &out);
        return std::string();                     // everything was streamed through `out`
    }, options);

    std::cout << "listening on port " << server->port() << "\n";
    server->waitUntilStopped();
    return 0;
}
Expert

17. End to end: tokenizer, sizing, pre-training, chat tuning, export, serve

The whole life cycle in one program, restartable at any point: every stage that has already produced its output is skipped.

17_full_pipeline.cpp · C++20
#include "Jacobit.hpp"
#include <fstream>
#include <iostream>
using namespace JBit;

static bool exists(const char *p) { return std::ifstream(p).good(); }

int main() {
    const std::string SEP = "<|endoftext|>";

    // 1. tokenizer ----------------------------------------------------------------------------
    ByteLevelBPETokenizer tok;
    if (exists("tokenizer.json")) tok = Jacobit::loadTokenizerJson("tokenizer.json");
    else { tok.trainFromFile("corpus.txt", 16000, 2); Jacobit::saveTokenizerJson(tok); }

    // 2. size the model from the data and the hardware ---------------------------------------------
    AdvisorOptions adv;
    adv.preLayerNorm = true;
    adv.memoryBytes = 12ull << 30;
    ModelRecommendation rec = tok.recommendModel(adv);
    tok.printTrainingAdvice(std::cout, adv);

    auto &model = Jacobit::createTrainingDecoderOnlyModel("pipeline", 6e-4f)
        .bbpeTokenizer(tok)
        .modelDimension(rec.modelDimension).feedForwardDimension(rec.feedForwardDimension)
        .headCount(rec.heads).decoderBlock(rec.layers)
        .contextWindow(1024).preLayerNorm().flashAttention()
        .learningRateScheduler(Model::COSINE_ANNEALING).warmupSteps(500)
        .gradientClipping(1.0f).weightDecay(0.1f)
        .effectiveBatchSize(64, 8)
        .cudaIfAvailable()
        .build();
    model.setLossGradientMean(true);
    model.setMonitorEnabled(true);

    // 3. pre-training (resumable) ---------------------------------------------------------------
    if (!exists("base.bin")) {
        model.setMaxGlobalStep(20000);
        model.smartPreTraining("corpus.txt", SEP, tok, 0, 1, "pretrain.ckpt", 500);
        model.save("base.bin");
    } else model.load("base.bin");

    // 4. chat tuning (resumable) ----------------------------------------------------------------
    if (!exists("chat.bin")) {
        model.setMaxGlobalStep(model.getGlobalStep() + 3000);
        model.smartChatFineTune("chats.jsonl", "\n", tok, ChatFormat(), ChatOptions(), 0, 2, "chat.ckpt", 500);
        model.save("chat.bin");
    }

    // 5. export for other runtimes ---------------------------------------------------------------
    Jacobit::exportONNX(model, "model.onnx");

    // 6. serve ----------------------------------------------------------------------------------
    auto server = Jacobit::startJBitServer([&](const ServerRequest &req, std::ostream &out) {
        ChatConversation conv;
        for (const auto &m : req.messages) {
            if (m.role == "system") conv.system(m.content);
            else if (m.role == "assistant") conv.assistant(m.content);
            else conv.user(m.content);
        }
        model.chatInference(conv, tok, ChatOptions(), 256, &out);
        return std::string();
    }, 8080);
    server->waitUntilStopped();
    return 0;
}
Advanced

18. Images and audio as tensors

The Jacobit facade loads images and audio straight into tensors (PNG, JPEG, BMP; WAV, MP3, AAC through ffmpeg). Needs the bitmap / audio modules (-DJACOBIT_BUILD_BITMAP=ON -DJACOBIT_BUILD_AUDIO=ON).

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

int main() {
    // image -> flat tensor in [0,1], grayscale, ready for a dense/conv input layer
    Tensor1D pixels = Jacobit::loadBitmapToFlattenedTensor1D("digit.png", /*normalize01*/ true, /*alpha*/ false, /*gray*/ true);

    // small thumbnail first (cheap), then crop
    Bitmap thumb = Jacobit::loadBitmapThumbnail("photo.jpg", 64, 64);
    Jacobit::saveBitmap(thumb, "thumb.png");

    // audio -> log-mel spectrogram [nMels x frames] for a conv / RNN model
    Tensor2D mel = Jacobit::loadAudioToMelSpectrogramTensor2D("speech.wav", 16000, /*nMels*/ 80, /*nFft*/ 400, /*hop*/ 160);
    Tensor2D mfcc = Jacobit::loadAudioToMFCCTensor2D("speech.wav");
    (void)pixels; (void)mel; (void)mfcc;
    return 0;
}
Expert

19. Import and export: ONNX and GGUF

Models can be exported to ONNX (FP32 / FP16 / INT8) and loaded from ONNX or GGUF through the builders, either as trainable or as inference-only models.

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

int main() {
    TrainingDecoderOnlyModel model(2, 512, 64, 256, 4, 128, 2, 3e-4f, TrainingModel::ADAM_W);

    Jacobit::exportONNX(model, "model.onnx");           // FP32
    Jacobit::exportONNXFp16(model, "model_fp16.onnx");  // half the size
    Jacobit::exportONNXInt8(model, "model_int8.onnx");  // quantised

    // inference-only model (no optimizer state, smaller memory footprint)
    auto &inf = Jacobit::loadInferenceDecoderOnlyModelONNX("model.onnx").build();
    // or from a GGUF file, or continue training from either
    // auto &g = Jacobit::loadInferenceDecoderOnlyModelGGUF("model.gguf").build();
    // auto &t = Jacobit::loadTrainingDecoderOnlyModelONNX("model.onnx").build();
    (void)inf;
    return 0;
}
Intermediate

20. Progress reports, ETA and logging

Training prints one live line (loss, learning rate, throughput, ETA) by default; choose how often it reports and whether each report is a new line (good for log files).

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

int main() {
    auto &model = Jacobit::createTrainingDecoderOnlyModel("lm")
        .vocabularySize(512).modelDimension(64).feedForwardDimension(256).headCount(4).decoderBlock(2)
        .contextWindow(128)
        .progressReportFrequency(Model::LOW)                       // LOW ~5 reports, MEDIUM ~10, HIGH ~25 per run
        .progressReportMode(Model::MULTI_LINE_PROGRESS)            // one line per report (CI / log files)
        .build();
    model.setMonitorEnabled(true);
    model.setProgressReportInterval(500);                          // or: a report every 500 steps
    return 0;
}