ReferenceReference

API reference

Look up C++ APIs, ABI 2.8 model and optimizer surfaces, checkpoints, and model interchange.

docs/API_REFERENCE.md

This page indexes the supported public surfaces of Riftco Transformer 0.6.1. It is a navigation reference, not generated Doxygen: signatures are shortened where that improves scanning, and the linked headers remain authoritative. See Architecture for subsystem boundaries and Project structure for implementation ownership.

Package targets#

Installed consumers use CMake 3.24 or newer and C++20:

cmakefind_package(riftco_transformer 0.6 CONFIG REQUIRED)
target_link_libraries(app PRIVATE riftco_transformer::library)
Imported targetPublic surfaceDependency boundary
riftco_transformer::libraryTensor, autograd, neural modules, model, optimizer, artifacts, native servingCore runtime
riftco_transformer::compilerCajal types, AST, evaluator, encoding, compilerStandard library only
riftco_transformer::analysisMatrices, representation traces, PCA, interventions, ablationsStandard library only
riftco_transformer::loweringCajal/multilinear-map to neural modulesCompiler + runtime
riftco_transformer::programmedProgrammed sequence cores, placement, and task-neutral learned/programmed model compositionAnalysis + lowering
riftco_transformer::c_apiStable C ABI 2.8 shared libraryRuntime and programmed composition behind opaque handles

The exported target definitions live in CMakeLists.txt and RiftcoTransformerInstall.cmake. The installed CMake package uses same-minor version compatibility. Only the C surface carries an explicit binary ABI version; C++ consumers should rebuild against the selected package release.

C++ core runtime#

All names below are in riftco_transformer unless another namespace is shown.

HeaderPrincipal APIContract and ownership
core/backend.hppExecutionBackend, execution_backend_available, set_execution_backend, ScopedExecutionBackendThe construction default is thread-local. Existing tensors retain their intrinsic backend. A scope guard is non-copyable, non-movable, and must die on its creating thread.
core/tensor.hppTensor(shape, values, backend), zeros, full, reshape, to, shape, strides, dataOwns contiguous row-major FP32 storage. Copying performs a deep backend allocation; moving transfers it. to() returns an independent copy.
core/tensor_ops.hppElementwise arithmetic, matmul, layout, reductions, math, softmaxPure tensor operations validate shapes and preserve input backend identity. Mixed-backend numerical inputs are rejected.
core/autograd.hppVariable(Tensor, requires_gradient), backward, differentiable operators, custom_gradient, checkpointA Variable copy shares its graph node. Scalar outputs may use implicit seed 1; non-scalars require a same-shape seed.
core/quantized_weight.hppQuantizedWeight::quantize_nf4, quantize_nf4_double_quantized, from_packed_nf4, dequantize, to, memory_usageCopies share immutable packed storage. Readback copies packed payload; dequantize() is the explicit FP32 materialization boundary.

Representative tensor and autograd signatures:

cppTensor tensor({2, 3}, values, ExecutionBackend::Cpu);
Tensor product = tensor_ops::matmul(left, right);

Variable x(Tensor({2}, {2.0F, 3.0F}));
Variable loss = sum(x * x);
loss.backward();

See Tensor, Tensor operations, and Autograd for behavioral detail.

Modules, models, and optimization#

HeaderPrincipal APIContract and ownership
nn/parameter.hppParameter, ParameterHandle, NamedParameter, ParameterList, move_parameters_to, parameter_countHandles retain canonical parameter state; copied lists remain valid independently of the originating wrapper.
nn/module.hppModule::parameters, Module::to, ModuleListModules are non-copyable and non-movable. Registered child links are non-owning; ModuleList owns repeated children.
nn/linear.hppLinear::forward, LoRA attachment/merge, NF4 conversionOwns dense parameters or an immutable packed base weight, never both as trainable base state.
nn/embedding.hppEmbedding::forwardGathers rows from a registered embedding table.
nn/layer_norm.hppLayerNorm::forwardRegistered scale and bias; differentiable normalization.
nn/rms_norm.hppRMSNorm::forward, rms_normScale-only root-mean-square normalization with a fully differentiable reference composition.
nn/low_rank_adapter.hppLowRankAdapter::forward, weight_deltaOwns floating-point A/B adapter parameters.
nn/activations.hpp and nn/loss.hppgelu, relu, softmax, cross_entropy, cross_entropy_time_rangeDifferentiable operations over Variable; loss returns a scalar mean over all positions or one contiguous per-batch time range.
model/feed_forward.hppFeedForward, FeedForwardActivationPosition-wise expand/activate/project module with GELU or ReLU.
model/causal_self_attention.hppCausalSelfAttention, FullSequenceAttentionKind, head split/merge, diagnostic materialized attentionFull-sequence materialized/Flash policy is independent of incremental decode.
model/transformer_block.hppTransformerBlock::forwardPre-normalized attention and feed-forward residual composition.
model/decoder_kv_cache.hppDecoderKeyValueCacheAbstract, caller-owned per-request cache mutated transactionally by token decode.
model/decoder_only_transformer.hppDecoderOnlyTransformer::forward, decode_token, to, NF4/LoRA lifecycle, parametersModel is non-copyable/non-movable. Full forward builds an autograd graph; token decode returns detached logits and mutates a caller-owned cache.
model/llama_mistral_transformer.hppLlamaMistralConfig, LlamaMistralTransformer::forwardExperimental native C++ dense full-context RMSNorm/RoPE/GQA/SwiGLU runtime. Narrow sliding windows and external checkpoint/tokenizer reinterpretation are rejected.
optim/adam.hppAdam(ParameterList, AdamOptions), step, zero_gradients, state, load_stateRetains parameter handles and owns first/second moments. Updates and logical-state restoration are transactional across the registered list.

Model construction and forward:

cppstd::mt19937 random(42);
DecoderOnlyTransformer model(
    TransformerDimensions{256, 16, 32, 4, 2, 64}, random
);
Variable logits = model.forward(token_ids, {batch, time});

forward() returns [batch, time, vocabulary]. Training parameters come from model.parameters(); after LoRA attachment, adapter parameters come from model.lora_parameters(). Quantized frozen weights deliberately do not appear in either optimizer list. See Modules, Transformer, LoRA, QLoRA, and Adam. The distinct dense family topology and its current non-goals are listed in Dense Llama and Mistral runtime boundary.

Data, native serving, and artifacts#

HeaderPrincipal APILifetime notes
data/tokenizer.hppTokenizerStrategy, ByteTokenizer, BytePairTokenizer, make_tokenizerTokenizers own immutable vocabulary state and return owned token vectors/strings.
data/token_batch.hppTokenBatch, make_next_token_batch, sample_next_token_batchBatch owns rectangular input and target token arrays. Caller owns the seeded RNG.
stages/serving/stack.hppServingStack(snapshot, config), generateRestores model/tokenizer inference state and owns its cache factory.
artifacts/state.hppModelSnapshot, capture_snapshot, load_model_state, restore_tokenizerIn-memory, backend-neutral value handoff; no optimizer state, lineage, or persistence.

The stage umbrella is stages/stages.hpp. Configuration defaults are listed in Configuration reference.

Compiler, lowering, and interpretation#

Namespace and headerPrincipal API
compiler::cajalImmutable Type, Expression, and Value; type_check, evaluate, encode, decode, compile; CompiledProgram and MultilinearMap
loweringNeuralLoweringConfig, LoweringRegistry, analyze_neural_lowering, lower_to_neural, LoweredMultilinearModule
programmed/sequence_placement.hppProgrammedSequenceCore, ProgrammedSequenceAdapter, projection sharing, placement, steering, and batch-roll ablation options
programmed/program_augmented_model.hppProgramAugmentedModelConfig, move-only ProgramBranch, ProgramAugmentedForwardOptions, ProgramAugmentedModel
analysisMatrix, RepresentationTrace, fit_pca, transform_pca, apply_intervention, summarize_ablation

The compiler and analysis libraries do not depend on the tensor runtime. Lowering is the explicit one-way bridge into differentiable modules. Cajal is a finite, first-order language constructed through C++ APIs; it is not a text parser or a general lambda-calculus implementation. See Compiling to transformers.

Program-augmented composition#

ProgramAugmentedModel is a fixed-context, task-neutral composition. For token-plus-position state \(x\), residual width \(D\), and \(N\geq1\) independently parameterized causal-attention branches, its learned path is

\[ \begin{aligned} r_1 &= x + \mathrm{FFN}_{\mathrm{ReLU}}(x),\\ h &= W_A[\mathrm{Attn}_1(r_1);\ldots; \mathrm{Attn}_N(r_1)] + b_A. \end{aligned} \]

Without a program, \(r_2=r_1+h\). With a ProgramBranch, the model selects the configured source span, runs ProgrammedSequenceCore, places the raw program output at the arbitrary configured target offset with zeros elsewhere, and computes

\[ r_2=r_1+W_M[h;\mathrm{place}(p)]+b_M. \]

A final learned projection produces vocabulary logits. The branch config owns source/target offsets, core input layouts and shared projection groups, a lowered module, and optional merge bias. Forward options support affine program-input steering and one shared positive batch-roll shift for learned attention, selected program inputs, and/or raw program output. These are graph interventions: gradients still flow through placement and the selected model paths.

When capture is enabled, the owning host trace uses these stable names:

  • embedding.sum
  • residual.pre_attention
  • learned_attention.merged
  • program.source when a branch exists
  • program.input.N and program.input.N.projected for each logical input
  • program.output.raw and program.output.placed when a branch exists
  • residual.post_merge
  • logits

cross_entropy_time_range(logits, targets, time_offset, time_count) selects the same contiguous time interval independently in every [batch,time,vocab] row before taking mean cross entropy. Ordinary cross_entropy remains the all-position objective.

Stable C ABI#

c_api.h defines C ABI 2.8. It uses fixed-width constants, status returns, versioned value structures, and opaque handles:

crt_context* context = NULL;
rt_status status = rt_context_create(RT_BACKEND_CPU, &context);
/* use context */
rt_context_release(context);
FamilyFunctions
ABI and errorsrt_abi_version, rt_status_string, rt_last_error
Tokenizationrt_tokenizer_options_init, create/restore, vocabulary/merge queries, encode/decode, rt_tokenizer_release
Backend and tensorsrt_backend_is_available, context create/query/release, FP32 tensor create/query/copy/matmul/release
ModelDecoder config initialization, create/transfer/query, attention/checkpointing selection, forward, NF4 conversion, packed-state size/copy/transactional load, LoRA attach/query/merge, memory statistics, release
Dense Llama/Mistralrt_llama_mistral_config_init, create/transfer/backend, full-sequence forward, base-parameter list, release
ServingDecode-session options, create, step, reset, cache queries, release
Multilinear mapsDense or sparse output-major import into rt_multilinear_map, copied ownership, release
Programmed modelVersioned model/branch/lowering/forward configs; create, transfer, query, parameters, forward, release
Representation tracesOwning trace count/name/shape/value queries and release
Parameters and autogradBase/LoRA/programmed parameter lists, shape/value transfer, checkpoint-safe frozen-base restore under the sole adapter Adam, model forward variables, cross-entropy, backward, release
OptimizationAdam options, create, step, zero gradients, state diagnostics, logical state size/copy/load, release

Initialize every versioned structure with its matching rt_*_init function and its actual sizeof(...). Every successful create returns one handle that must be released exactly once. Derived handles retain model state, but a live decode session pins model backend and parameter values. Raw C calls are not internally lifetime-synchronized; callers must serialize operations involving the same state. Variable-size outputs support a null-output/zero-capacity size query. Copy rt_last_error() before the next status-returning call on that thread.

Python API#

Python 3.10+ has no runtime package dependencies. The top-level riftco_transformer module re-exports the native layer:

pythonfrom riftco_transformer import (
    Adam, Context, DecoderOnlyTransformer, LoraConfig, Tensor,
    LlamaMistralConfig, LlamaMistralTransformer, Tokenizer,
    TransformerConfig, Variable, backend_available, cross_entropy,
    cross_entropy_time_range,
)

Native wrappers are closeable context managers and cannot be copied. They retain related state and synchronize operations through shared locks. Important high-level packages are:

PackagePublic entry points
artifactsModelBundle, ModelRuntime, ParameterSpec, TokenizerSpec
checkpointsTrainingCheckpoint.capture, save, load, restore; v2 packed QLoRA plus v1 dense loading; TrainingCheckpointRestore
dataHugging Face HTTP client, dataset adapters, stable splitting, serializers, preparation and verification
interchangeload_model, export_model, convert_model; F32 SafeTensors, Riftco Hugging Face directory, GGUF v3, and strict canonical ONNX interchange
trainingBatch sources, TrainingLoopConfig, CausalLanguageModelTrainer, backend selection
pretrainingPretrainingConfig, pretrain_text, pretrain_splits, pretrain_file, pretrain_files
post_trainingInstruction loading/splits, PostTrainingConfig, post_train, held-out evaluation
programmedMultilinearMap.from_dense/from_sparse, lowering and branch configs, ProgramAugmentedModel, interventions, owning traces
servingSamplers, TextGenerator, ModelService, dependency-free HTTP server

Repository research protocols are intentionally outside this installed API. Top-level labs contains Python-owned fine-tuning, LoRA-rank, and conditional-reversal labs; they compose the public packages above and write ignored runs/ output. In particular, the framework exposes no native F/P/T/I experiment type: conditional-reversal program construction, training, evaluation, PCA policy, and reporting remain in the Python lab.

Python loads the native library from the wheel, recognized source-build directories, the system loader, or the explicit RIFTCO_TRANSFORMER_LIBRARY path. See Troubleshooting for loader and ABI errors.