# JBit / Jacobit C++20 Machine Learning Framework — Complete AI Reference Canonical Site: https://jbit.dev/docs/index.html Updated: 2026-12-01 Coverage: 206 headers, 305 classes, 7,233 declared members, 20 C++20 examples, 37 best practices. ## API Modules ### Core API (https://jbit.dev/docs/api/core-api.html) Top-level static facade (Jacobit.hpp) for launching the OpenAI-compatible HTTP server, creating model builders, loading images/audio into tensors, training BBPE/Unigram tokenizers, and importing/exporting ONNX and GGUF. #### class Jacobit (Jacobit.hpp) Unified static entry point exposing model builders, OpenAI-compatible HTTP server, Bitmap/Audio tensor adapters, BBPE/Unigram tokenizers, and ONNX/GGUF serialization. - `Jacobit() = default` - `static std::shared_ptr startJBitServer(ServerRequestHandler onRequest, const ServerOptions &options)` — Starts background HTTP server (/v1/chat/completions, /v1/completions, /v1/models, /health, SSE streaming). - `static std::shared_ptr startJBitServer(ServerRequestHandler onRequest, uint16_t port = 8080, const std::string &host = "127.0.0.1")` - `static void stopJBitServer(const std::shared_ptr &server)` - `static TrainingModelBuilder &createTrainingModel(const char* name, real_t learningRate = 0.0015f, TrainingModel::OPTIMIZER optimizer = TrainingModel::ADAM, TrainingModel::LOSS_FUNCTION lossFunction = TrainingModel::CROSS_ENTROPY)` — Creates a Dense/CNN/Sequential training builder. - `static TrainingDecoderOnlyModelBuilder &createTrainingDecoderOnlyModel(const char* name, real_t learningRate = 0.0015f, TrainingModel::OPTIMIZER optimizer = TrainingModel::ADAM_W, TrainingModel::LOSS_FUNCTION lossFunction = TrainingModel::CROSS_ENTROPY)` — Creates a causal Decoder-Only Transformer builder. - `static TrainingEncoderDecoderModelBuilder &createTrainingEncoderDecoderModel(const char* name, real_t learningRate = 0.0015f, TrainingModel::OPTIMIZER optimizer = TrainingModel::ADAM_W, TrainingModel::LOSS_FUNCTION lossFunction = TrainingModel::CROSS_ENTROPY)` — Creates an Encoder-Decoder Transformer builder. - `static TrainingRnnModelBuilder &createTrainingRnnModel(const char* name, real_t learningRate = 0.0015f, TrainingModel::OPTIMIZER optimizer = TrainingModel::ADAM, TrainingModel::LOSS_FUNCTION lossFunction = TrainingModel::CROSS_ENTROPY)` — Creates an RNN/LSTM/GRU training builder. - `static InferenceModelBuilder &createInferenceModel(const char* name = "inference_model")` — Also available: createInferenceDecoderOnlyModel, createInferenceEncoderDecoderModel, createInferenceRnnModel. - `static Bitmap loadBitmap(const std::string &filePath)` — Loads BMP, JPEG, or PNG images; see also loadBitmapThumbnail, loadBitmapCrop, saveBitmap. - `static Tensor1D loadBitmapToFlattenedTensor1D(const std::string &filePath, bool normalize01 = true, bool includeAlpha = false, bool grayscale = false)` — Converts image directly to planar [C, H, W] Tensor1D. - `static Audio loadAudio(const std::string &filePath)` — Loads WAV, MP3, or AAC audio; see also loadAudioSlice, saveAudio. - `static Tensor2D loadAudioToMelSpectrogramTensor2D(const std::string &filePath, uint32_t targetSampleRate = 16000, size_t nMels = 80, size_t nFft = 400, size_t hopLength = 160, bool logScale = true)` — Extracts Whisper/AST-ready [nMels, numFrames] Log-Mel spectrogram. - `static Tensor2D loadAudioToMFCCTensor2D(const std::string &filePath, uint32_t targetSampleRate = 16000, size_t nMfcc = 13, size_t nMels = 40, size_t nFft = 400, size_t hopLength = 160)` - `static ByteLevelBPETokenizer trainBBPETokenizer(const std::vector &corpus, size_t targetVocabSize = 512, size_t minFrequency = 2, const std::string &saveJsonPath = "")` — Trains BBPE vocabulary; see also trainSentencePieceUnigramTokenizer, loadTokenizerJson, saveTokenizerJson. - `static InferenceModelBuilder &loadONNX(const std::string &filePath)` — Also loadInferenceDecoderOnlyModelONNX, loadTrainingDecoderOnlyModelONNX, loadGGUF, loadInferenceDecoderOnlyModelGGUF. - `static void exportONNX(const Model &model, const std::string &filePath, Model::ONNX_DATA_TYPE dataType = Model::ONNX_FLOAT32)` — Exports ONNX; see also exportONNXFp16 and exportONNXInt8. - `static void exportONNXFp16(const Model &model, const std::string &filePath)` - `static void exportONNXInt8(const Model &model, const std::string &filePath)` ### Configuration (https://jbit.dev/docs/api/configuration.html) Global arithmetic precision typedef (real_t in Config/precision.hpp) defaulting to float (FP32) or double (FP64) via -DJACOBIT_REAL_DOUBLE. ### Types (https://jbit.dev/docs/api/types.html) Portable IEEE 754 binary16 half-precision type (real_fp16_t in Type/real_fp16_t.hpp) usable with or without CUDA. #### class real_fp16_t (Type/real_fp16_t.hpp) Portable IEEE 754 binary16 (FP16) scalar type with constexpr conversion, round-to-nearest-even, vectorized array helpers, math overloads, and _fp16 literals. - `real_fp16_t() = default` - `REAL_FP16_CONSTEXPR real_fp16_t(float v) noexcept` — Converts float to binary16 using round-to-nearest-even. - `REAL_FP16_CONSTEXPR real_fp16_t(double v) noexcept` — Single-rounding conversion from double to binary16. - `static constexpr real_fp16_t from_bits(std::uint16_t b) noexcept` - `constexpr std::uint16_t bits() const noexcept` - `REAL_FP16_CONSTEXPR float to_float() const noexcept` - `constexpr bool is_nan() const noexcept / is_inf() / is_finite() / is_zero() / is_subnormal() / is_normal()` — IEEE 754 classification predicates. - `static constexpr real_fp16_t max() noexcept // 65504, min() // 2^-14, epsilon() // 2^-10` - `static void to_float_array(const real_fp16_t* src, float* dst, std::size_t n) noexcept` - `static void from_float_array(const float* src, real_fp16_t* dst, std::size_t n) noexcept` ### Maths (https://jbit.dev/docs/api/maths.html) Contiguous tensor containers (Tensor1D, PayloadTensor1D, Tensor2D, Tensor3D) and thread-local RealStorage checkpoint width guards. #### class Tensor1D (Maths/Tensor1D.hpp) Contiguous 1D tensor of real_t elements with N-D flattenedSizes metadata, vectorized math, spatial padding, and Transformer batch payloads. - `static Tensor1D zeros(size_t size) / ones(size_t size) / fromValues(std::initializer_list values)` - `void setFlattenedSizes(const std::vector &sizes) / const std::vector &getFlattenedSizes() const` - `size_t getSize() const / real_t *getPointer() / std::vector &getData()` - `Tensor1D vMultiply(...) / vPow(real_t p) / vAbs() / vLog() / vExp() / vMax(real_t eps) const` - `size_t maxValueIndex(size_t minIndex = 0, int64_t maxIndex = -1) const / real_t maxValue(...) const` - `Tensor1D padding2D(const std::vector &padding, size_t rows, size_t cols, real_t value = 0.0f) const` - `virtual void save(std::ostream &os) const / virtual void load(std::istream &is)` #### class PayloadTensor1D (Maths/PayloadTensor1D.hpp) Tensor1D carrying BatchPayload (inputIds, attentionMask, tokenTypeIds, labels) for packed Transformer pre-training and SFT. - `PayloadTensor1D *toTrainingDecoderInput()` - `void appendWithEosSos(const PayloadTensor1D &other) / appendWithSep(...) / appendWithPad(...) / appendWithIgnore(...)` - `void segmentBySos()` — Assigns incrementing 1-based segment IDs in attentionMask so packed sequences never attend across [sos]. - `void ensureSosEos() / ensureSos() / ensureEos() / stripOuterSosEos() / toPadding() / toIgnore()` #### class Tensor2D (Maths/Tensor2D.hpp) Row-major 2D matrix with matrix-matrix and matrix-vector operators. - `Tensor2D(size_t rowCount, size_t colCount)` - `Tensor2D operator*(const Tensor2D &other) const / Tensor1D operator*(const Tensor1D &tensor) const` - `size_t getRowCount() const / size_t getColCount() const / size_t getSize() const` #### class Tensor3D (Maths/Tensor3D.hpp) Contiguous 3D [depth, rows, cols] tensor with proxy indexing t[c][r][col]. - `Tensor3D(size_t deeperCount, size_t rowCount, size_t colCount)` - `ChannelProxy operator[](size_t c) / real_t &operator()(size_t c, size_t r, size_t col)` #### class Scope (Maths/RealStorage.hpp) RAII guard setting checkpoint byte width (2 = FP16, 4 = FP32, 8 = FP64) for the current thread and restoring on exit. - `explicit Scope(size_t write, size_t read)` - `~Scope()` ### Utilities (https://jbit.dev/docs/api/utilities.html) Zero-dependency JSON DOM (JSONObject, JSONArray, JSONVariant), tabular Cursor, indexed Map, String, and tagged Variant. #### class JSONObject (Utils/JSON/JSONObject.hpp) DOM JSON object parser/serializer used by tokenizer.json, model configs, and JBitServer. - `static AbstractJSONObject *createFromData(const std::string &data) / createFromFile(const char *filename)` - `void putString/putInt/putDouble/putBool/putNull(const std::string &key, ...)` - `std::string getString/int getInt/double getDouble/bool getBool/JSONObject* getJSONObject/JSONArray* getJSONArray(const std::string &key)` - `std::string toString() override / std::string toFormattedString(...) override / void formattedExportToFile(const char *filename)` #### class JSONArray (Utils/JSON/JSONArray.hpp) DOM JSON array container. - `void putString/putInt/putDouble/putBool(...) & getString/getInt/getJSONObject/getJSONArray(unsigned long long index)` - `unsigned long long size() const` #### class Cursor (Utils/Cursor/Cursor.hpp) In-memory tabular row cursor with typed column getters. - `int addRow() / void put(const std::string &key, const Variant &value) / bool next() / bool prev()` - `int getInt/double getDouble/bool getBool/std::string getStdString(const std::string &key) const` #### class Map (Utils/Map/Map.hpp) Associative container supporting both key lookup and O(1)-cached positional index access. - `void put(const T &k, const Q &v) / Q &get(const T &k) / Q &get(size_type index) / bool contains(const T &k) const` #### class String (Utils/String/String.hpp) Drop-in std::string subclass with split, join, trim, replace, and case utilities. - `std::vector split(const std::string &delimiter) const / static String join(const std::vector &parts, const std::string &delimiter)` - `String trim() const / toLowerCase() const / toUpperCase() const / replace(const String &search, const String &replaceWith) const` #### class Variant (Utils/Variant/Variant.hpp) Compact tagged scalar/string union. - `bool isBoolType() const / isNumericType() const / isStringType() const / int toInt() const / double toDouble() const / std::string toStdString() const` ### File & matrix I/O (https://jbit.dev/docs/api/file-matrix-io.html) File reader/writer, constant-memory streaming corpus reader (File::SeparatorReader) with byte-offset checkpointing, and generic MatrixBase. #### class File (File/File.h) Cross-platform file I/O with sentence/document splitting, sliding-window word chunking, and constant-RAM streaming. - `static SeparatorReader streamFileBySeparator(const std::string &path, const std::string &separator, bool trimEntries = true, bool skipEmpty = true, std::size_t bufferBytes = 1u << 20, std::size_t maxSegmentBytes = 1u << 20)` — Streams multi-gigabyte files with constant memory. - `static std::vector splitFileBySeparator(const std::string &path, const std::string &separator = ".", bool trimEntries = true, bool skipEmpty = true)` - `std::vector splitByWordCount(std::size_t wordsPerChunk, std::size_t overlapWords = 0) const` - `std::vector readAllLines(bool skipEmptyLines = false) const / std::string readAllText() const / std::vector readAllBytes() const` #### class SeparatorReader (File/File.h) Constant-memory delimiter scanner with exact byte position() and seek(offset) for resumable training. - `bool next(std::string &segment)` — Yields the next trimmed non-empty segment; returns false at EOF. - `uint64_t position() const / bool seek(uint64_t offset) / uint64_t size() const` #### class MatrixBase (File/Matrix/MatrixBase.h) Templated 2D matrix backing PixelMatrix (MatrixBase) and Matrix (MatrixBase). - `MatrixBase(const unsigned int rowCount, const unsigned int columnCount, const T defaultValue = T{})` - `Ra operator[](unsigned int i) / T &get(unsigned int i, unsigned int j) / void set(unsigned int i, unsigned int j, const T &value)` ### Bitmap I/O (https://jbit.dev/docs/api/bitmap-io.html) Native BMP, JPEG, and PNG readers/writers, spatial/color transforms, and direct planar [C, H, W] Tensor1D/2D/3D conversions. #### class Bitmap (File/Bitmap/Bitmap.h) In-memory image buffer supporting bilinear resize, crop, flip, rotate, grayscale/contrast transforms, and JBit Tensor conversions. - `Tensor1D toFlattenedTensor1D(bool normalize01 = true, bool includeAlpha = false, bool grayscale = false) const` — Outputs planar [C, H, W] Tensor1D with flattenedSizes={C, H, W}. - `Tensor2D toTensor2D(bool normalize01 = true) const / Tensor3D toTensor3D(bool normalize01 = true, bool includeAlpha = false) const` - `static Bitmap fromFlattenedTensor1D(const Tensor1D &tensor, unsigned int width = 0, unsigned int height = 0, unsigned int channels = 0, bool isNormalized01 = true)` - `Bitmap &resize(unsigned int newWidth, unsigned int newHeight, bool bilinear = true) / Bitmap &crop(unsigned int startRow, unsigned int startCol, unsigned int cropWidth, unsigned int cropHeight)` - `Bitmap &toGrayscale() / toBlackWhite(unsigned char threshold = 128) / flipHorizontal() / flipVertical() / adjustContrast(float factor)` - `void save(const std::string &filePath, unsigned int quality = 95, bool downSampling = false) const` #### class BitmapFactory (File/Bitmap/BitmapFactory.h) Format-detecting image loader/saver backed by BmpImageReader/Writer, JpegImageReader/Writer, and PngImageReader/Writer. - `static Bitmap decodeFile(const std::string &filePath) / decodeThumbnail(const std::string &filePath, unsigned int width, unsigned int height) / decodeCrop(const std::string &filePath, unsigned int width, unsigned int height)` ### Audio I/O (https://jbit.dev/docs/api/audio-io.html) WAV (PCM/Float/ADPCM/u-Law/A-Law), MP3, and AAC audio I/O with FFT/STFT, Log-Mel spectrograms, MFCCs, and Griffin-Lim inversion. #### class Audio (File/Audio/Audio.h) Multi-channel audio buffer with sinc resampling, silence trimming, FFT/STFT spectral transforms, and Whisper/Conformer/CNN tensor adapters. - `Audio &toMono() / resample(uint32_t targetSampleRate, bool sincInterpolation = true) / normalize(float targetPeakDb = 0.0f) / trimSilence(float thresholdDb = -40.0f)` - `Tensor2D toMelSpectrogramTensor2D(size_t nMels = 80, size_t nFft = 400, size_t hopLength = 160, float fMin = 0.0f, float fMax = 0.0f, bool logScale = true, WINDOW_TYPE windowType = WINDOW_HANN) const` — Produces [nMels, numFrames] Log-Mel spectrogram. - `Tensor3D toMelSpectrogramTensor3D(size_t nMels = 80, size_t nFft = 400, size_t hopLength = 160, float fMin = 0.0f, float fMax = 0.0f, bool logScale = true, bool includeDeltas = false, WINDOW_TYPE windowType = WINDOW_HANN) const` — When includeDeltas=true, returns [3, nMels, numFrames] (Static, Delta, Delta-Delta). - `Tensor2D toMFCCTensor2D(size_t nMfcc = 13, size_t nMels = 40, size_t nFft = 400, size_t hopLength = 160, float fMin = 0.0f, float fMax = 0.0f) const` - `static Audio fromMelSpectrogramTensor2D(const Tensor2D &melSpectrogram, uint32_t sampleRate = 16000, size_t nFft = 400, size_t hopLength = 160, float fMin = 0.0f, float fMax = 0.0f, bool isLogScale = true, size_t griffinLimIters = 32, WINDOW_TYPE windowType = WINDOW_HANN)` — Griffin-Lim phase reconstruction back to waveform. #### class AudioFactory (File/Audio/AudioFactory.h) Auto-detecting audio loader/saver supporting WAV, MP3, and AAC codecs. - `static Audio decodeFile(const std::string &filePath) / decodeSlice(const std::string &filePath, double startSeconds, double durationSeconds)` - `static Tensor2D loadToMelSpectrogramTensor2D(const std::string &filePath, uint32_t targetSampleRate = 16000, size_t nMels = 80, size_t nFft = 400, size_t hopLength = 160, bool logScale = true)` ### Audio processing (https://jbit.dev/docs/api/audio-processing.html) Low-level RIFF/WAVE waveform tensor extractor and channel deinterleaver (AudioProcessor.hpp). #### class AudioProcessor (DataProcessor/Audio/AudioProcessor.hpp) Parses PCM, IEEE Float, and Mu-Law WAV streams into normalized float vectors. - `std::vector waveToTensor(const std::string& filename)` - `std::vector> deinterleave(const std::vector& interleavedTensor, uint16_t channels)` - `uint16_t getChannels() const / uint32_t getSampleRate() const / uint16_t getBitDepth() const / std::string getFormatString() const` ### Text & tokenizers (https://jbit.dev/docs/api/text-tokenizers.html) Byte-Level BPE & SentencePiece Unigram tokenizers (Hugging Face tokenizer.json compatible), BERT WordPiece, scaling-law ModelAdvisor, and BatchPayloadArena. #### class ByteLevelBPETokenizer (DataProcessor/Text/ByteLevelBPETokenizer.hpp) GPT-2 / RoBERTa / Llama-3 / GPT-4 (cl100k) / T5 / HuggingFace tokenizer.json compatible BBPE and SentencePiece Unigram tokenizer with built-in scaling-law model advisor. - `explicit ByteLevelBPETokenizer(bool initFullByteAlphabet = true, MODEL_TYPE type = MODEL_BPE)` - `static ByteLevelBPETokenizer fromFile(const std::string &tokenizerJsonPath = "tokenizer.json")` - `ByteLevelBPETokenizer &train(const std::vector &corpus, size_t targetVocabSize = 512, size_t minFrequency = 2, const std::vector &extraSpecialTokens = {}, bool forceFullByteAlphabet = false)` - `ByteLevelBPETokenizer &trainUnigram(const std::vector &corpus, size_t targetVocabSize = 512, ...)` - `ByteLevelBPETokenizer &trainFromFile(const std::string &corpusFilePath, size_t targetVocabSize = 512, size_t minFrequency = 2)` - `std::vector encodeSingleString(const std::string &text) const / std::string decode(const std::vector &tokenIds, bool skipSpecialTokens = true) const` - `BatchPayload encodeBatch(const std::vector &batch, size_t maxLen) const / PayloadTensor1D encodeBatchToPayloadTensor1D(...) const` - `ModelRecommendation recommendModel(const AdvisorOptions &options = AdvisorOptions()) const / void printTrainingAdvice(std::ostream &os, const AdvisorOptions &options = AdvisorOptions()) const` — Computes optimal layers, width, heads, vocab size, LR, and batch size from corpus stats & hardware limits. - `void save(const std::string &filePath = "tokenizer.json", bool formatted = true) const / void load(const std::string &filePath = "tokenizer.json")` #### struct AdvisorOptions & ModelRecommendation (DataProcessor/Text/TokenizerAdvisor.hpp) Hardware/compute budget inputs and Chinchilla/Muennighoff scaling-law model architecture recommendations. - `size_t epochs, contextLength, maxParams, bytesPerValue; double memoryBytes, computeBudgetFlops, sustainedFlopsPerSecond; bool preLayerNorm, flashAttention` - `size_t layers, modelDimension, heads, headDimension, feedForwardDimension, totalParams, suggestedVocab, totalSteps, warmupSteps; double peakLearningRate, parameterBytes, activationBytesPerSequence` #### class BatchPayload & BatchPayloadArena::Scope (DataProcessor/Text/BatchPayloadArena.hpp) Token IDs, attention masks, token type IDs, and labels with thread-local arena allocation preventing long-run corpus memory leaks. - `std::vector> inputIds, attentionMask, tokenTypeIds, labels` ### Model base (https://jbit.dev/docs/api/model-base.html) Base Model interface (context window tracking, RAM/VRAM breakdown, gradient accumulation, multi-GPU config, checkpoints) plus GGUF v3 & ONNX readers/writers. #### class Model (Model/Model.hpp) Abstract base for all JBit training and inference models: global steps, micro-batching, gradient clipping, weight decay, RoPE/ALiBi/YaRN positional encodings, context window checks, RAM/VRAM breakdown, and binary/GGUF/ONNX serialization. - `Model &setMultiGpuAuto(std::vector candidates = {}) / setMultiGpuManual(std::vector devices, std::vector split = {}, int mainDevice = -1) / setParallelPolicy(gpu::ParallelPolicy p, ...)` - `Model &setEffectiveBatchSize(size_t effective, size_t microBatch = 0) / setMicroBatchSize(size_t samples) / setGradientAccumulationSteps(size_t steps)` - `Model &enableGradientClipping(real_t maxNorm, GRADIENT_CLIPPING_MODE mode = CLIP_BY_NORM) / enableWeightDecay(real_t rate)` - `virtual Model &setPositionalEncoding(POSITIONAL_ENCODING encoding) / setRopeThetaBase(real_t thetaBase) / setRopeScalingFactor(real_t scalingFactor)` - `virtual size_t getContextWindow() const / virtual Model &extendContextWindow(size_t newContextWindow, bool autoScaleRope = false)` - `virtual ParameterBreakdown getParameterBreakdown() const / virtual MemoryBreakdown getMemoryBreakdown(bool forTraining, size_t batchSize = 0, size_t sequenceLength = 0, size_t bytesPerElement = sizeof(real_t)) const` - `virtual void save(const std::string &filePath) const / load(const std::string &filePath) / exportGGUF(...) / importGGUF(...) / exportONNX(...) / importONNX(...)` - `void exportONNXFp16(const std::string &filePath) const / void exportONNXInt8(const std::string &filePath) const` #### class GGUFReader & GGUFWriter (Model/GGUF.hpp) Standard GGUF v2/v3 parser and writer supporting F32, F16, Q4_0, Q4_1, Q5_0, Q5_1, and Q8_0 tensors. - `void read(std::istream &is) / bool hasTensor(const std::string &name) const / const std::vector &getTensorData(const std::string &name) const` - `void addTensor1D(...) / addTensor2D(...) / void write(std::ostream &os) const` #### class ONNXReader & ONNXWriter (Model/ONNX.hpp) Zero-dependency ONNX IR v9 / Opset 18 protobuf binary reader and writer supporting FLOAT, FLOAT16, and INT8. - `void read(std::istream &is) / const std::vector &getNodes() const / const std::vector &getTensorData(const std::string &name) const` - `void setTensorDataType(TensorDataType dt) / addNode(...) / void write(std::ostream &os) const` ### Layers, Activations & Losses (https://jbit.dev/docs/api/layers-activations-losses.html) Core layers (Dense, Dropout), Transformer layers (MaskedRoPEMultiHeadSelfAttention, FlashAttention, Pre-LN DecoderOnlyBlock, YaRN, XPos, ALiBi), Conv1D/2D/3D, LSTM/GRU/BidirectionalRnn, 9 activations, and 19 loss functions. #### class DecoderOnlyBlock & MaskedRoPEMultiHeadSelfAttention (Model/Training/Layer/Transformer/DecoderOnlyBlock.hpp) Causal Transformer stack supporting Pre-LN (GPT-2/Llama style) and Post-LN, O(L)-memory FlashAttention, and RoPE/YaRN/XPos/ALiBi positional encodings. - `void setPreLayerNorm(bool enabled) / void setFlashAttentionEnabled(bool enabled)` - `Tensor1D forward(Tensor1D &input) / Tensor1D backward(Tensor1D &backInput) / Tensor1D &updateWeights(Tensor1D &input)` #### class Dense, Conv1D, Conv2D, Conv3D & MaxPooling (Model/Training/Layer/Conv/Conv2D.hpp) Fully connected and 1D/2D/3D spatial convolution and pooling layers with forward, backward, and optimizer state persistence. - `Dense(size_t nodeLinkCount, size_t nodeCount, TrainingModel::ACTIVATION_FUNCTION activationFunction)` - `Conv2D(size_t inChannelCount, size_t outChannelCount, std::vector inNodeCount, std::vector outNodeCount, std::vector kernelSize, std::vector stride, std::vector padding, TrainingModel::ACTIVATION_FUNCTION activationFunction)` #### class LSTM, GRU, SimpleRnn & BidirectionalRnn (Model/Training/Layer/Rnn/LSTM.hpp) Recurrent layers with full Backpropagation Through Time (BPTT), sequence masking, variational RnnDropout, and TimeDistributedDense. - `LSTM(size_t inputSize, size_t hiddenSize, size_t sequenceLength = 1, bool returnSequences = false, ...)` - `GRU(size_t inputSize, size_t hiddenSize, size_t sequenceLength = 1, bool returnSequences = false, ...)` - `BidirectionalRnn(size_t inputSize, size_t unitHiddenSize, size_t sequenceLength = 1, bool returnSequences = false, CELL_TYPE cellType = SIMPLE_RNN, MERGE_MODE mergeMode = CONCAT, ...)` #### class Activation & LossHelper (19 Losses) (Model/Training/Loss/LossHelper.hpp) Dispatcher for 9 activations (Sigmoid, Tanh, ReLU, LeakyReLU, Softmax, StableSoftmax, Linear, Swish, GELU) and 19 losses (CrossEntropy, MeanSquared, BinaryCrossEntropy, HuberLoss, CosineSimilarityLoss, KullbackLeiblerDivergence, TripletLoss, etc.). - `static Tensor1D Activation::activate(TrainingModel::ACTIVATION_FUNCTION targetActivation, const Tensor1D &input)` - `real_t LossHelper::computeLoss(TrainingModel::LOSS_FUNCTION lossFun, const Tensor1D &values, const Tensor1D &correctValues)` ### Optimizers & LR schedules (https://jbit.dev/docs/api/optimizers-schedules.html) 10 optimizers (AdamW, Adam, SGD, RMSprop, Adagrad, Adadelta, Adamax, NAG, Rprop, AdamWithRegularization), global L2 gradient clipping, decoupled weight decay, and 11 learning-rate schedulers. #### class AdamW, Adam, Sgd & OptimizerHelper (Model/Training/Optimizer/AdamW.hpp) Stateful optimizers with checkpointable first/second moments and global-norm gradient clipping. - `AdamW(real_t weightDecay = 0.01)` — Decoupled weight decay applied to 2D weight matrices (not biases or LayerNorm parameters). - `static void GradientClipping::clipByNorm(Tensor2D &grad, real_t maxNorm, real_t eps = real_t(1e-6))` - `static void WeightDecay::applyDecoupled(Tensor2D &weights, real_t learningRate, real_t weightDecayRate)` #### class CosineAnnealing, WarmupStableDecay, OneCycle & LearningRateSchedulerHelper (Model/Training/LearningRate/LearningRateSchedulerHelper.hpp) 11 learning-rate schedules all supporting linear warm-up: CosineAnnealing, LinearDecay, WarmupStableDecay (WSD), OneCycle, InverseSqrtDecay (Noam), ExponentialDecay, PolynomialDecay, CosineWithRestarts, ConstantWithWarmup, and StepDecay. - `CosineAnnealing(real_t max_learning_rate, real_t min_learning_rate, size_t warmup, size_t total)` - `WarmupStableDecay(real_t max_learning_rate, real_t min_learning_rate, size_t warmup, size_t total, real_t decayFraction = real_t(0.2))` - `real_t getLearningRate(int schedulerKind, size_t step)` ### Training models (https://jbit.dev/docs/api/training-models.html) Trainable neural models: TrainingDecoderOnlyModel, TrainingEncoderDecoderModel, TrainingModel, TrainingRnnModel, and CUDA subclasses. #### class TrainingDecoderOnlyModel (Model/Training/TrainingDecoderOnlyModel.hpp) Causal Decoder-Only Transformer supporting pre-training, packed mergedPreTraining, constant-RAM streaming smartPreTraining, Q&A fine-tuning, multi-turn chatFineTuning/smartChatFineTuning, KV-cached generation, and single/multi-GPU CUDA. - `TrainingDecoderOnlyModel(size_t decoderBlockSize, size_t vSize, size_t mDimension, size_t ffDimension, size_t hCount, size_t maxPosEmb, size_t tVocabSize, real_t learningRate = 0.01, TrainingModel::OPTIMIZER optimizer = TrainingModel::OPTIMIZER::ADAM, TrainingModel::LOSS_FUNCTION lossFunction = TrainingModel::LOSS_FUNCTION::CROSS_ENTROPY)` - `TrainingDecoderOnlyModel &setPreLayerNorm(bool enabled) / enableFlashAttention(bool enabled = true) / setCudaEnabled(bool enabled)` - `TrainingDecoderOnlyModel &mergedPreTraining(std::vector &batchs, size_t max_len, size_t max_epoch, bool requireGlobalStepReset = true)` - `TrainingDecoderOnlyModel &smartPreTraining(const std::string &corpusFile, const std::string &separator, const ByteLevelBPETokenizer &tokenizer, size_t max_len = 0, size_t max_epoch = 1, const std::string &checkpointFile = "", size_t checkpointEvery = 0, bool requireGlobalStepReset = true)` - `TrainingDecoderOnlyModel &smartChatFineTuning(const std::string &corpusFile, const std::string &separator, const ByteLevelBPETokenizer &tokenizer, const ChatFormat &format = ChatFormat(), const ChatOptions &options = ChatOptions(), size_t max_len = 0, size_t max_epoch = 1, const std::string &checkpointFile = "", size_t checkpointEvery = 0, bool requireGlobalStepReset = true)` - `std::vector chatInference(const ChatConversation &history, const ByteLevelBPETokenizer &tokenizer, const ChatOptions &options = ChatOptions(), size_t maxLen = 0, std::ostream *outputStream = nullptr, size_t tokensPerWrite = 1)` - `std::vector inference(PayloadTensor1D &batch, size_t max_len, std::ostream *outputStream = nullptr, size_t tokensPerWrite = 1)` #### class TrainingEncoderDecoderModel (Model/Training/TrainingEncoderDecoderModel.hpp) Sequence-to-sequence Encoder-Decoder Transformer with cross-attention, CUDA backend, and chat/seq2seq fine-tuning. - `TrainingEncoderDecoderModel(size_t encoderBlockSize, size_t decoderBlockSize, size_t vSize, size_t mDimension, size_t ffDimension, size_t hCount, size_t maxPosEmb, size_t tVocabSize, real_t learningRate = 0.01, ...)` - `TrainingEncoderDecoderModel &fineTune(std::vector &batchs, std::vector &targetBatchs, size_t max_len, size_t max_epoch = 100, bool requireGlobalStepReset = true)` #### class TrainingModel & TrainingRnnModel (Model/Training/TrainingModel.hpp) Sequential Dense/CNN and RNN/LSTM/GRU training models with CUDA graph acceleration. - `TrainingModel &train(size_t max_epoch = 100, bool requireGlobalStepReset = true)` - `Tensor1D TrainingRnnModel::predict(const std::vector &input)` ### Model builders (https://jbit.dev/docs/api/model-builders.html) Fluent builders for all training and inference model families: TrainingDecoderOnlyModelBuilder, TrainingEncoderDecoderModelBuilder, TrainingModelBuilder, TrainingRnnModelBuilder, and Inference*ModelBuilder. #### class TrainingDecoderOnlyModelBuilder (Model/Training/TrainingDecoderOnlyModelBuilder.hpp) Fluent configurator for TrainingDecoderOnlyModel with checkpoint/GGUF/ONNX restoration, tokenizer binding, RoPE/YaRN/ALiBi selection, FlashAttention, gradient accumulation, and multi-GPU policies. - `static TrainingDecoderOnlyModelBuilder fromCheckpoint(const std::string &filePath) / fromGGUF(...) / fromONNX(...)` - `TrainingDecoderOnlyModelBuilder &bbpeTokenizer(const ByteLevelBPETokenizer &tok) / tokenizerJson(const std::string &filePath)` - `TrainingDecoderOnlyModelBuilder &modelDimension(size_t) / feedForwardDimension(size_t) / headCount(size_t) / decoderBlock(size_t count = 1) / contextWindow(size_t)` - `TrainingDecoderOnlyModelBuilder &preLayerNorm(bool enabled = true) / flashAttention(bool enabled = true) / effectiveBatchSize(size_t effective, size_t microBatch = 0)` - `TrainingDecoderOnlyModelBuilder &cudaIfAvailable() / multiGpuAuto(std::vector candidates = {}) / multiGpu(const std::string &text)` - `TrainingDecoderOnlyModel &build() / TrainingDecoderOnlyModel *buildPointer()` #### class TrainingModelBuilder & InferenceModelBuilder (Model/Training/TrainingModelBuilder.hpp) Fluent builders for Dense, Conv1D/2D/3D, MaxPooling, Dropout, Flatten, and RNN stacks. - `TrainingModelBuilder &withDataset(inputs, targets) / input(...) / denseRelu(size_t) / conv2d(...) / maxPooling2d(...) / build()` ### Inference models (https://jbit.dev/docs/api/inference-models.html) Forward-only inference models with zero gradient or optimizer memory overhead and O(1)-step KV-cache decoding: InferenceDecoderOnlyModel, InferenceEncoderDecoderModel, InferenceModel, InferenceRnnModel. #### class InferenceDecoderOnlyModel (Model/Inference/InferenceDecoderOnlyModel.hpp) Flat contiguous weight storage with zero gradient/Adam buffers and per-layer KV-cache for fast autoregressive token generation. - `explicit InferenceDecoderOnlyModel(const TrainingDecoderOnlyModel &trainedModel)` - `static InferenceDecoderOnlyModel fromCheckpoint(const std::string &filePath) / fromGGUF(...) / fromONNX(...)` - `int predictNextToken(PayloadTensor1D &batch) / std::vector inference(PayloadTensor1D &batch, size_t max_len, std::ostream *outputStream = nullptr, size_t tokensPerWrite = 1)` #### class InferenceModel (Model/Inference/InferenceModel.hpp) Compact forward-only sequential/CNN/RNN inference model. - `explicit InferenceModel(const TrainingModel &trainedModel)` - `Tensor1D predict(const Tensor1D &input) / Tensor1D predict(const std::vector &input) / Tensor2D predictBatch(const Tensor2D &inputs)` ### Corpus, chat & checkpoints (https://jbit.dev/docs/api/corpus-chat-checkpoints.html) Multi-turn ChatConversation/ChatOptions/ChatFormat, resumable streaming packers (LmPacker, QaPacker, ChatPacker, corpus::Cursor), and TrainingProgressMonitor. #### struct ChatConversation & ChatOptions (Model/Training/ChatFineTuning.hpp) Structured multi-turn conversation builder (system, user, assistant, tool) and loss-masking configuration. - `ChatConversation &system(const std::string &text, int train = -1) / user(...) / assistant(...) / tool(...)` - `bool trainOnAssistant = true, trainOnUser = false, trainOnSystem = false, lastAssistantOnly = false, trainOnTurnEnd = true; Overflow overflow = SPLIT` #### class LmPacker, QaPacker & ChatPacker (Model/Training/CorpusPacker.hpp) Constant-memory streaming packers that pack variable-length documents/conversations into context-window sequences and serialize corpus::Cursor byte offsets into checkpoints. - `bool next(LmPack &out) / void save(Cursor &c) const / void restore(const Cursor &c)` #### class TrainingProgressMonitor (Model/Training/TrainingProgressMonitor.hpp) Adaptive progress reporter with rolling-median + EMA ETA estimation, perplexity tracking, and automated anomaly detection (NaN/Inf, explosion, spike, plateau). - `TRAINING_HEALTH_STATUS getHealthStatus() const / real_t getEmaLoss() const / real_t getBestLoss() const` ### CUDA backends (https://jbit.dev/docs/api/cuda-backends.html) Single- and multi-GPU CUDA execution engines (DecoderOnlyCudaBackend, EncoderDecoderCudaBackend, SequentialCudaBackend), CUDA Graph capture, cuBLAS GEMMs, REPLICATE/LAYER_SPLIT/HYBRID policies, and automatic failover. #### struct MultiGpuConfig & GpuGroup (Model/Training/Cuda/MultiGpu.hpp) Multi-GPU orchestration supporting AUTO throughput-proportional splitting, MANUAL tensor-split ratios, REPLICATE data parallelism, LAYER_SPLIT pipeline parallelism, HYBRID mode, and CONTINUE/FAIL_FAST/ASK failure recovery. - `static MultiGpuConfig autoSplit(std::vector candidates = {}) / manual(std::vector devices, std::vector split = {}, int mainDevice = -1) / parse(const std::string &text)` #### class DecoderOnlyCudaBackend (Model/Training/Cuda/DecoderOnlyCudaBackend.hpp) Device-resident CUDA backend with CUDA Graph capture, online-softmax FlashAttention kernels, device-resident LR/optimizer steps, and greedy decoding. - `static bool available(std::string *reason = nullptr) / void setFlashAttention(bool enabled) / std::string parallelism() const` ### Server (https://jbit.dev/docs/api/server.html) Embedded multi-threaded HTTP server (JBitServer in Server/JBitServer.hpp) implementing OpenAI-compatible /v1/chat/completions, /v1/completions, /v1/models, and /health with SSE token streaming. #### class JBitServer (Server/JBitServer.hpp) Non-blocking background HTTP server with Bearer API key authentication, request serialization for thread-unsafe models, CORS headers, and Server-Sent Events streaming. - `JBitServer(ServerRequestHandler handler, ServerOptions options = ServerOptions())` - `void start() / void stop() / bool running() const / uint16_t port() const / std::string url() const / void waitUntilStopped()` #### struct ServerOptions & ServerRequest (Server/JBitServer.hpp) Server binding/security options and parsed OpenAI chat/completion request payload. - `std::string host = "127.0.0.1"; uint16_t port = 8080; std::string modelName = "jbit"; std::string apiKey; bool serializeRequests = true; bool allowCors = false` - `Kind kind; std::vector messages; std::string prompt; bool stream; size_t maxTokens; double temperature, topP` ## Best Practices ### Data & tokenizer - **Train the tokenizer on the data you will train on**: A tokenizer trained on foreign text wastes context on long token sequences. Check the average tokens per word on a sample: well-fitted English BPE is roughly 1.3–1.5. - **Size the vocabulary with the model**: A larger vocabulary shortens sequences but adds d × V parameters twice (embedding and head). For small models (a few million parameters) use 4K–16K; recommendModel() proposes a size from your data and model scale. - **Keep the chat special tokens**: Chat training uses one special token per marker (<|im_start|>, role tokens, <|im_end|>). A tokenizer without them falls back to a text template that works but is less clean. - **Split documents with an explicit separator**: Use one separator (e.g. <|endoftext|>) between documents so packing does not blend unrelated text and attention segments stay isolated. - **Hold out validation data**: Keep a few percent of the corpus outside training and evaluate it regularly: loss on training data alone tells you nothing about generalisation. ### Model shape - **Use pre-LayerNorm for deeper models**: setPreLayerNorm(true) / .preLayerNorm() trains stably at depth and with higher learning rates. Post-LN (the original layout) is the default for compatibility; it needs more careful warm-up. - **Keep d_model divisible by heads, head size 64 or 128**: Head dimension of 64–128 is the usual sweet spot; also friendlier to GPU kernels. - **Feed-forward ≈ 4 × d_model**: The standard ratio; the advisor uses it unless you set a multiplier. - **Match model size to data, not to ambition**: Roughly 20 effective training tokens per non-embedding parameter is a good target; repeating data more than ~4 epochs gives sharply diminishing returns. Use printTrainingAdvice for a data-driven suggestion, then validate with a short pilot. - **Choose the context window deliberately**: Attention cost grows with the square of the window (without flash attention). Train on the window you will serve; extending later is possible (extendContextWindow, RoPE scaling / YaRN) but needs fine-tuning. ### Optimisation - **AdamW + warm-up + cosine decay is the safe default**: ADAM_W, warm-up of about 1–5% of steps, cosine to roughly 10% of the peak. Use WARMUP_STABLE_DECAY when you do not know the final length in advance. - **Clip gradients globally**: gradientClipping(1.0f) clips the norm over the whole model (also across GPUs), which protects against rare loss spikes. - **Average, do not sum, the loss gradient**: setLossGradientMean(true) makes the update independent of the number of tokens in the batch, so the learning rate transfers between batch sizes. - **Learning rate scales down with model size**: Small models (<50M) tolerate 1e-3 to 3e-3; hundreds of millions need ~3e-4 to 6e-4; billions less. Fine-tuning uses 10–30× lower than pre-training. - **Use gradient accumulation instead of tiny batches**: setEffectiveBatchSize(64, 8): the memory of 8, the optimisation of 64. Language models usually want effective batches of tens to hundreds of sequences. - **Weight decay on weights only**: weightDecay(0.1f) with AdamW is typical for transformers; do not apply decay to biases / norms (JBit's AdamW applies it as decoupled decay). ### Training runs - **Always pass a checkpoint file to smart* functions**: smartPreTraining(…, "run.ckpt", 500) stores weights, optimizer state, global step and corpus position: a crashed run restarts with the same command. - **Set the maximum step before the first step**: The LR schedule is derived from setMaxGlobalStep(). Interrupting with a small limit and resuming with a larger one changes the schedule (the data order stays identical). - **Pilot first**: Train a 1% slice for a few hundred steps: the loss must fall smoothly, and a deliberately tiny dataset should be memorised (overfit test). If not, something is wrong with data or settings — fix that before spending hours. - **Watch loss, gradient norm, learning rate and throughput**: The progress monitor prints them; a loss that is NaN or jumps up by orders of magnitude means lower the learning rate, check clipping, or inspect the data. - **Save the tokenizer next to the weights**: A model is useless without the exact tokenizer it was trained with. Keep tokenizer.json with every checkpoint. - **Make runs reproducible**: Same data order is guaranteed by the corpus cursor; dropout masks and GPU reduction order can still differ slightly between CPU and GPU or between GPU counts. ### Fine-tuning & chat - **Pre-train first, then chat-tune**: Chat tuning teaches format and behaviour, not language. Starting from a model that has never seen text rarely works. - **Train on assistant tokens only**: This is the default of ChatOptions (context is masked). Enable trainOnUser only for deliberate experiments. - **Use the same template at inference**: chatInference and training share one template; when serving through JBitServer rebuild a ChatConversation from the request messages instead of concatenating strings. - **Mix in general data**: Fine-tuning only on a narrow set makes the model forget; mix some pre-training text or diverse conversations and use a low learning rate. - **Long conversations are split, not truncated**: The default SPLIT keeps every assistant turn trained exactly once with the system prompt repeated; TRUNCATE drops everything after the first window. - **Encoder-decoder: no packing**: Cross-attention cannot isolate packed samples; use gradient accumulation for throughput instead. ### GPU & performance - **Enable CUDA per model at run time**: .cudaIfAvailable() degrades gracefully to the CPU. Build with -DJACOBIT_CUDA_CUBLAS=ON to use cuBLAS GEMMs. - **Use flash attention for windows ≥ 512**: O(L) attention memory instead of O(L²) per head; allows larger windows or micro-batches. - **Multi-GPU: replicate for speed, layer-split for capacity**: Data-parallel replication (multiGpuAuto) speeds training when the model fits on one card. LAYER_SPLIT lets a bigger model fit but runs stages sequentially; HYBRID combines both. Gradient reduction is staged through host memory, so benefits are largest for big windows. - **Fit memory with micro-batch first**: If you run out of memory, lower the micro-batch (keep the effective batch), then enable flash attention, then reduce the window. - **Reduce build time with module selection**: -DJACOBIT_MODELS=DECODER_ONLY compiles only what you use. - **Test without a GPU**: The CUDA emulator (make -C tests/cuda_emulation verify) runs the real .cu sources on the CPU to check parity with the CPU path. It validates logic, not speed or real-hardware behaviour. ### Code & project hygiene - **Prefer builders for configuration, models for control**: Builders are concise and validate order; for experiments that change settings between phases keep the model reference and call setters. - **Check return values of I/O and log failures**: Audio encoders call ffmpeg: make sure it is on the PATH; a failed encode is reported on stderr. - **One model object is not thread-safe**: Serve with serializeRequests = true (default) or give each worker its own model copy. - **Run behind a reverse proxy in production**: JBitServer has no TLS and uses one thread per connection: bind to 127.0.0.1, put nginx / caddy in front, set an apiKey. - **Version everything that defines a run**: Source revision, tokenizer file, corpus snapshot id, hyper-parameters and the checkpoint: you need all of them to reproduce or resume. ## 20 Runnable C++20 Examples ### 1. Your first network: XOR with a dense stack [Beginner] (01_hello_xor.cpp) 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. ```cpp #include "Jacobit.hpp" #include using namespace JBit; int main() { std::vector>> 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>{{0, 0}, {0, 1}, {1, 0}, {1, 1}}) std::cout << in[0] << " xor " << in[1] << " -> " << inf.predict(in).toString() << "\n"; return 0; } ``` ### 2. Save, load and resume from a checkpoint [Beginner] (02_save_load.cpp) `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`. ```cpp #include "Jacobit.hpp" #include 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; } ``` ### 3. Optimizers, losses and learning-rate schedules [Beginner] (03_optimizers_schedules.cpp) 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. ```cpp #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; } ``` ### 4. Convolutional network (conv2d + pooling + dense) [Intermediate] (04_conv2d.cpp) 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). ```cpp #include "Jacobit.hpp" using namespace JBit; int main() { std::vector>> inputs, targets; for (int level = 1; level <= 10; ++level) { std::vector img(8 * 8, static_cast(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; } ``` ### 5. Recurrent network (LSTM) on sequences [Intermediate] (05_lstm_sequence.cpp) `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. ```cpp #include "Jacobit.hpp" using namespace JBit; int main() { const size_t T = 6; // time steps per sample std::vector>> inputs, targets; for (int start = 0; start < 40; ++start) { std::vector> seq; // T rows of 1 feature for (size_t t = 0; t < T; ++t) seq.push_back({static_cast(start + t) / 50.0f}); inputs.push_back(seq); targets.push_back({{static_cast(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{0.10f, 0.12f, 0.14f, 0.16f, 0.18f, 0.20f}); (void)next; return 0; } ``` ### 6. Train, use and save a byte-level BPE tokenizer [Intermediate] (06_tokenizer.cpp) 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. ```cpp #include "Jacobit.hpp" #include using namespace JBit; int main() { std::vector 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 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; } ``` ### 7. Let the advisor size your model from your data [Intermediate] (07_tokenizer_advisor.cpp) 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. ```cpp #include "Jacobit.hpp" #include 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; } ``` ### 8. Pre-train a small language model and stream generated text [Intermediate] (08_decoder_pretrain_generate.cpp) `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. ```cpp #include "Jacobit.hpp" #include using namespace JBit; int main() { std::vector 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; } ``` ### 9. A realistic decoder-only configuration (builder) [Advanced] (09_decoder_builder_full.cpp) 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. ```cpp #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; } ``` ### 10. Pre-train on a file larger than RAM, with checkpoint and resume [Advanced] (10_smart_pretraining.cpp) `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. ```cpp #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; } ``` ### 11. Fine-tune on question/answer pairs [Advanced] (11_finetune_qa.cpp) 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`). ```cpp #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 questions = {"what is the capital of france", "what is two plus two"}; std::vector 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; } ``` ### 12. Chat (multi-turn) fine-tuning [Advanced] (12_chat_finetune.cpp) 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. ```cpp #include "Jacobit.hpp" #include 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 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; } ``` ### 13. Large effective batches with gradient accumulation [Advanced] (13_gradient_accumulation.cpp) 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. ```cpp #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; } ``` ### 14. Encoder-decoder (sequence-to-sequence) [Advanced] (14_encoder_decoder.cpp) 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. ```cpp #include "Jacobit.hpp" #include using namespace JBit; int main() { std::vector source = {"hello world", "good morning", "thank you"}; std::vector target = {"bonjour le monde", "bonjour", "merci"}; std::vector 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; } ``` ### 15. CUDA, cuBLAS and multi-GPU [Expert] (15_gpu_multigpu.cpp) 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. ```cpp #include "Jacobit.hpp" #include 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; } ``` ### 16. Serve a model through an OpenAI-compatible HTTP API [Expert] (16_server.cpp) `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. ```cpp #include "Jacobit.hpp" #include 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; } ``` ### 17. End to end: tokenizer, sizing, pre-training, chat tuning, export, serve [Expert] (17_full_pipeline.cpp) The whole life cycle in one program, restartable at any point: every stage that has already produced its output is skipped. ```cpp #include "Jacobit.hpp" #include #include 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; } ``` ### 18. Images and audio as tensors [Advanced] (18_images_audio.cpp) 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`). ```cpp #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; } ``` ### 19. Import and export: ONNX and GGUF [Expert] (19_onnx_gguf.cpp) 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. ```cpp #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; } ``` ### 20. Progress reports, ETA and logging [Intermediate] (20_progress_monitoring.cpp) 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). ```cpp #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; } ```