Browse documentation
aner.gen

Native generative research

Build and train a causal language model from scratch, evaluate and resume it, fine tune with LoRA, and explore conditional scientific generators with tested physical constraints.

Released in Aner 0.1.0Aner 0.1.0 or newer

Read the generative parameter reference for every model/configuration argument, its actual default, accepted shape/range, effect and persistence contract. Neural networks and the model directory connect the technique specific guides.

aner.gen provides native decoder construction, training, evaluation, checkpoint/resume, generation, full fine tuning, parameter freezing and LoRA. It also groups conditional scientific time series generation and small field diffusion in the same module. It uses aner.token for language corpora and the existing aner.nn and aner.tensor numerical foundations.

The from scratch LLM guide walks through the complete research process with executable source and checks. Use an Aner runtime with aner.token and aner.gen support.

For fitted lexical evidence memory, whole document context budgets and source aware token batches, use aner.nlp. The decoder's managed parameters, training continuation and KV cache remain in aner.gen; retrieved evidence is a separate input snapshot.

A reference architecture researchers can change

The built in decoder starts with new seeded weights. It combines learned token/position embeddings, pre normalized causal multihead attention, residual connections, GELU feed forward blocks, a final LayerNorm and a tied vocabulary projection.

Native decoder: learned embeddings and positions enter repeated causal attention and feed-forward blocks; the vocabulary projection shares the token table.

This is one working representation of Aner's capabilities. Its example dimensions are chosen for a quick reproducible run. Researchers can build different supported blocks and larger compositions with native functions and classes. The built in gen trainer/checkpoint schema handles its declared decoder families; custom class architectures own their parameter enumeration, training loop and serialization. See the custom decoder source and sequence primitives.

API reference

This minimal native program initializes new weights and performs one update. Use the complete guide for partitioning, validation and artifact handling.

aner
import aner.token
import aner.gen

let codec = token.byte_tokenizer()
let training = token.corpus(codec, List("ababa", "babab"), role: "training")
let initial = gen.decoder(codec, context: 8, width: 8,
    heads: 2, layers: 1, seed: 42, dropout: 0.0)
let trained = initial.train(training, steps: 1, batch: 2, rate: 0.001, seed: 99)
print(trained.loss(training))
TaskNative calls
Construct from new weightsgen.decoder(codec, context, width, heads, layers, seed, dropout)
Inspect and initializemodel.summary(), model.parameter_names(), model.parameter(name), model.with_parameter(name,value) before training
Trainmodel.train(training, steps, batch, rate, seed); extended form also supplies clip_norm, warmup_steps, weight_decay
Evaluatemodel.loss(corpus), model.perplexity(corpus), gen.scored_tokens(corpus), model.baseline()
Checkpoint and continuemodel.save(path), gen.load(path), model.resume(training, steps)
Begin a new training runmodel.fine_tune(training, steps, batch, rate, seed); same extended optimizer arguments as train
Choose trainable weightsmodel.freeze(names), model.unfreeze(names), model.trainable_parameters()
Add adaptersmodel.lora(targets, rank, alpha, seed), model.save_adapter(path), gen.load_adapter(base,path), model.merge_lora()
Use a custom objectivemodel.logits(ids, batch, length, training) with nn.backward and nn.grad
Batch samplemodel.generate_batch(prompts, max_new_tokens, temperature, top_k, top_p, seeds); optional use_cache Bool defaults to true, then cuda_graph Bool defaults to false
Samplemodel.generate(prompt, max_new_tokens, temperature, top_k, top_p, seed); optional trailing use_cache Bool defaults to true
Inspect execution and admissionmodel.device(), model.dtype(), model.memory_estimate(batch,length,training), model.memory_summary(batch,length,training)
Change execution explicitlygen.device_supported(device,dtype), gen.to(model,device,dtype)
Import the supported pretrained familygen.import_gpt2(directory,context)

Module functions and typed instance methods represent the same model operations. Names in freezing and adapter targets are exact registered parameter names, rather than patterns.

Training, evaluation and continuation

A step is one optimizer update. The trainer constructs shifted next token targets within each document, excludes padding from attention/loss and scores each document transition once per epoch. It shuffles windows with explicit deterministic seeds. The reference model uses Adam; the extended policy controls global clipping, linear warmup and decoupled matrix weight decay. Dropout is enabled only for training.

loss evaluates all actual targets without dropout and combines window losses by token count. last_loss() is the last batch's pre update objective; use loss for a measured post update value. Compare perplexities only with matching tokenizer and evaluation policies. A uniform vocabulary baseline checks correctness and is not a competitive language quality benchmark.

.anergen is the conventional file extension for a native binary generative model checkpoint. Create one with model.save("model.anergen") and restore it with gen.load("model.anergen"). It retains the architecture configuration, embedded tokenizer, named weights and any optimizer state and training progress. A full training checkpoint includes Adam moments, training policy, counters, data lineage and execution identity.

The tokenizer is embedded, so gen.load needs no separate .anertoken file. Original training documents remain separate. The checkpoint file guide compares .aner program source, .anergen model checkpoints and .anertoken tokenizer files. Saving and loading validate the checkpoint contents rather than requiring the filename suffix.

Exact resume requires the original corpus/order, backend, precision and runtime implementation. Changing data or training policy starts an explicit fine_tune run. Cross backend inference is supported subject to numerical differences; it does not establish exact cross backend continuation.

Artifact paths must be new. Checkpoints are bounded numeric data with integrity validation, not executable model code. A saved adapter contains its factors and exact base identity; use a full model checkpoint to retain optimizer state for resume.

Fine tuning and generation

Full fine tuning updates all currently trainable parameters. Freezing excludes selected parameters from gradients, optimizer moments and decay, while retaining their storage. Freezing the token embedding also freezes its tied output projection. LoRA freezes the base and learns low rank factors for selected block.i.qkv, block.i.attention.output, block.i.ff.in or block.i.ff.out matrices. Its factor rank is bounded to 1..64 and must fit the target dimensions.

Generation returns newly generated IDs, including EOS if selected. Temperature zero is greedy; positive temperature uses local seeded sampling with optional top-k/top-p filters. Native byte/BPE generation excludes BOS and PAD; the supported GPT 2 shared BOS/EOS ID remains an admissible stop token. Prompt plus requested output must fit the declared context. Generation uses a new call local KV cache by default. Optional use_cache: false recomputes the full prefix with the same sampler for comparison. Context and output limits remain explicit.

The fine tuning example exercises BPE, full updates, freezing, LoRA, adapter publication and exact full checkpoint resume.

Read LLM inference execution and optimization for execution choices, measured results and their limits.

Native inference KV cache

aner
let cached = model.generate(prompt, max_new_tokens: 8,
    temperature: 0.0, top_k: 0, top_p: 1.0, seed: 7)
let reference = model.generate(prompt, max_new_tokens: 8,
    temperature: 0.0, top_k: 0, top_p: 1.0, seed: 7, use_cache: false)

Prefill processes the prompt once. Each later step adds the new token's keys and values, uses the correct absolute position and attends its query to retained history. The final new position alone produces vocabulary logits. Native and supported GPT 2 decoders, including LoRA, use the same inference mechanism. It supports CPU Float64/Float32, native Metal/MPS Float32 and native CUDA Float64/Float32 within the declared sequence contract.

The cache is detached, resident and local to one generation call. It is released on completion or failure and is absent from model checkpoints and training graphs. Generating does not change the model fingerprint or training state. A new call starts with an empty cache; the public API does not expose a persistent streaming session.

K/V contain 2 * layers * cached_tokens * width committed values in a generation only typed arena. CPU and CUDA Float64 use eight bytes per value; CPU, Metal and CUDA Float32 use four. CPU Float32 K/V no longer retain a widened Double copy. Generic CPU Float32 Tensor values and model weights use authoritative four byte buffers and can lazily retain an additional eight byte per element host cache. Gradients, optimizer state and workspace add separate allocations; see Float32 storage. The measurements below describe their recorded source and builds.

For a positive output budget, generate lazily reserves the known horizon: effective prompt length plus max_new_tokens - 1. An empty prompt first inserts BOS. EOS may stop before the reserved capacity is filled; zero output performs no forward pass or cache allocation. Internal append sessions with an unknown horizon grow capacity geometrically and copy only committed history. Reserved capacity can therefore exceed the accepted prefix. Accepted position advances only after a complete successful forward pass; a failed tail stays invisible to attention and is overwritten on retry, although allocated capacity can remain until the session ends.

The native inference kernel appends raw QKV projections and performs causal attention without separate per head copies, prefix concatenation or full score/probability matrices. The retained primitive Metal reference uses two compute encoders for append and attention per layer. Cached Metal generation encodes the complete decoder forward in one command buffer, including these stages, as described below. The differentiable training path is unchanged. Prefill arithmetic remains quadratic, and a new token attends to its retained history. Weights, projection buffers, untracked temporary scratch and provider allocations are additional to K/V capacity. Cached decoding does not expand context, guarantee a speedup, or supply distributed serving.

The native cache example compares every generated ID for default/explicit cached and uncached greedy/seeded runs, independent calls and unchanged model identity. Native tests additionally compare forced token logits within precision tolerances and verify cleanup. Seeded fixture equality and numerical logit agreement are separate from a universal bitwise guarantee near sampling boundaries.

Cached prefill projects only its final vocabulary row. Some prompt/vocabulary combinations therefore fit cached admission while full prefix uncached projection exceeds a tensor/work budget; use_cache: false can reject such a request. The performance comparisons use shapes admitted by both policies. They include both retained K/V reuse and the final row projection optimization.

Metal decoder plans

Cached generation for the bounded native decoder and supported GPT2 import selects a whole decoder Metal Float32 plan automatically. The plan binds detached effective weights once, reuses private numeric workspace, and encodes embedding, normalization, QKV, causal attention, residual/MLP stages and the selected final vocabulary projection into one command buffer. MPS matrix operations and Metal compute encoders remain distinct device operations inside that submission.

Single and ragged batch appends keep activations and packed vocabulary outputs resident. Batch rows retain independent horizons and absolute positions; empty chunks skip rows, and selected final rows are gathered on the device rather than downloaded and repacked on the host. Each returned Tensor owns fresh output storage and remains immutable after workspace reuse, trimming, regrowth or plan destruction. A failed numeric append commits no accepted position; dirty suffix rows stay outside the accepted prefix and are overwritten on retry.

Each admitted plan forward submits one command buffer and reads its completion/status flag once. Private per plan diagnostics count actual submitted forwards, command buffers, status reads, encoded matrix/compute work and projected rows. Submitted numeric failures count; admission failures before submission do not. These are host submission observations, not GPU instruction counts or timings. A separate KV growth copy can add commands outside the plan forward; the public known horizon reservation avoids repeated prefix movement.

The Metal plan keeps a sticky finite error flag across the complete forward. It explicitly rejects intermediate Float32 variance overflow even when inverse zero or a later zero gain could conceal it in finite output. LayerNorm retains the prior affine expression and its rounding: regression tests detected and corrected a one ULP ranking change rather than adding approximate ties. Independent CPU Float64 full prefix checks, the retained Metal primitive reference, exact seeded/greedy fixtures, late row failure/retry, concurrent plans and unread held outputs qualify the implementation. Generic differentiable Tensor execution and the existing sampling stream are unchanged.

The stepwise append plans can release substantially oversized prefill workspace before decode with an explicit checked sizing hint that changes no KV capacity or accepted position. Later larger appends can regrow it. The resident greedy request described next retains its bounded prefill workspace for the complete request rather than invoking this trim hint automatically. Replacement in the stepwise path allocates a complete new workspace before publishing it, so owned peaks can include old and new buffers together. Device allocation counters exclude allocator, driver, command buffer and other untracked overhead.

The whole forward plan supports the bounded reference families and supplies the forward stages for resident Metal greedy execution. A persistent serving scheduler remains separate work. Sampled and uncached execution retain their existing host selection policies. Optional pretrained LibTorch training and llama.cpp local inference retain their separate implementations. The whole forward measurements below describe their original Mac only qualification.

See the Metal decoder evidence, measurement source and LLM inference optimization guide for protocol, exact scope and validation. Historical measurements below describe the source and builds recorded in their reports.

Resident Metal greedy requests

Cached Metal Float32 generate and generate_batch at temperature: 0.0 use a resident request when the largest output budget is greater than one, or a one token request has at least 65,536 packed logits across positive budget rows. Current token IDs, row positions, live masks, per row output counts and generated IDs stay in private device state. Prefill and the first selection share one command buffer. Decode commands start with one step, then two, then four, and grow to a maximum of eight steps before the host observes completion status and the remaining active count. An admitted remaining budget can shorten the final command. The CPU encodes these commands; the device does not generate its own command graph. The private C++ qualification seam accepts maximum chunk sizes 1..32, including one token requests. Public calls whose budgets are all at most one and whose total positive budget row count times vocabulary is below 65,536 retain the existing one step host scan. Larger one token outputs retain fused resident selection, avoiding a separate helper reduction command.

The startup policy follows measured evidence: the initial fixed eight plan made a controlled two output EOS request more than twice as slow, and a one token single request was about 10% slower in the first capture. Those observations are retained separately from the final gradual startup study. Increasing chunk sizes preserves a quick second token boundary; the public small output one token guard avoids resident setup when there is no multi step work in the measured host scan regime.

Rows with a zero output budget are validated and excluded from device execution. Positive budget rows keep their initial fixed decode lanes for the entire request, including later chunk boundaries. Ended lanes are not compacted; one surviving row still uses the original matrix row count with zeroed slots for ended rows. EOS and exhausted budgets mask subsequent embedding, normalization, bias, activation, attention and KV stages for that lane. If every row ends during a command, its already encoded remaining stages are masked; the host stops at the next boundary. Immediate EOS in prefill avoids a decode command entirely. The selected EOS and the unused final budget token are returned without being forwarded into KV.

The request retains its bounded prefill workspace together with private integer state and budget sized device ID output storage until it ends. It does not automatically apply the stepwise prefill to decode workspace trim hint. Fewer boundary observations do not imply lower retained memory.

At successful completion, the host copies exactly four bytes per emitted token from the device's uint32 ID output prefixes, then produces ordinary caller owned integer vectors in caller row order. There is no per step host token observation or Tensor logit mirror on this path. Metal uses shared unified memory: these diagnostic byte counts describe ID values exposed to the host, rather than measured hardware transfer traffic. Boundary status/active reads and final counts/positions are separate metadata observations. Vocabulary projection and score buffers still exist on the device.

The backend mutex is held for the complete resident request; concurrent tests verify isolation, rather than overlapping execution or fair interleaving. The entire fresh request commits positions together after complete numeric success. A failure in a late command exposes no partial IDs or accepted positions; its uncommitted KV suffix can be overwritten by a valid retry. An already used private cache rejects a resident request before submission. Per plan diagnostics distinguish scheduled forwards, submitted chunks, boundary reads, final result readbacks and emitted IDs; masked tail stages can make scheduled forward counts exceed useful live work.

The contract tests retain the one step Metal implementation and independent full prefix CPU Float64 scores from exact placed Float32 weights. They exercise strict ties, BOS/PAD exclusions, shared GPT2 BOS/EOS, first/mid/chunk-boundary EOS, poisonous EOS and final budget embeddings, ragged and duplicate prompts, zero/mixed budgets, exact context limits, late numeric failure and retry, ended lane attention/variance/GELU overflow witnesses, adapters and independent concurrent requests. Numerical score tolerances are separate from exact ID comparisons. Positive temperature seeded sampling, uncached references, CPU and CUDA retain their existing paths.

The final Mac natural request study retains both gains and regressions: the eight row, sixty four output reference case changes from 24.751 to 15.017 ms (1.648x), while controlled eight row EOS at output five changes from 4.124 to 4.989 ms (0.827x). All 31 profiles and process paired intervals are retained in the linked evidence and optimization guide. Fewer status boundaries and ID only observation do not establish a universal latency improvement. Masked/unmasked pipeline specialization creates seven additional pipeline states during initialization; their cold start cost and opaque memory are outside this warm study.

Final gradual startup Mac Metal qualification passes 11,990,172 assertions in the dedicated resident request suite, including large one token GPT2 batches, with maximum observed scaled full prefix score error 5.78247e-8, using abs(actual - expected) / (1 + abs(expected)). The existing MPS single cache suite separately passes 2,392,539 assertions, and the generic GPU/direct-provider suite passes 267. These overlapping suites are not added into a count of independent experiments. The final Mac regression campaign executes 283 normal test groups: 274 pass, nine unavailable platform or live service groups skip, and none fail; six separate research campaigns are excluded from that normal run. AddressSanitizer/UndefinedBehaviorSanitizer pass the final resident, direct provider and CPU Float32 cache suites. The actual final resident Metal suite also passes with Metal API and shader validation confirmed enabled. Timings from these instrumented runs are excluded from performance claims. The initial fixed chunk campaign passed 11,143,784 resident assertions; that historical count belongs to its separately retained rejected policy experiment. The sealed evidence report retains the exact source/build identities and logs.

Separate V100 32 GB qualification passes 13 native CUDA Float64/Float32 regression groups and three Compute Sanitizer memcheck cases with zero reported errors; cache/batch producer smoke checks also pass in both precisions. The final follow up changes only the Metal file, which is not compiled in the Linux CUDA build, and every recorded compiled shared/CUDA source hash matches the accepted final source. These checks qualify CUDA correctness regressions, rather than Metal performance or a cross hardware speed comparison.

See the resident greedy evidence, measurement source and LLM inference optimization guide for the measured workloads, correctness scope and separate CUDA regression qualification. This mechanism alone does not establish a speedup for another model, context or provider. Streaming, cancellation, dynamic request batching and pretrained architecture expansion remain separate work.

Measured compact cache comparison

This is an earlier typed arena and fused attention study, before whole decoder Metal plans. Its “current” labels name the candidate captured in that report; all tables and observations below remain historical evidence.

This separate before/after study reruns the preserved original cached executable and the current typed-arena/fused-attention executable on the same Apple M2 Max. It uses the same two layer, four head byte decoders, new weights, seeds, prompts and forced IDs as the historical workloads below. The 48 matched records cover six profiles and eight outer process pairs per profile, with alternating version order and rotating profile order. Each process excludes two warmups per cache policy, then records two native timing pairs. The complete report retains all 192 native pair records, 96 per implementation. The CPU thread environment request is one; actual provider thread counts remain unqueryable.

Each table entry is the median of eight process cluster medians. The 95% intervals resample complete matched process pairs 5,000 times; the two inner trials are not independent uncertainty units. Timings include native session preparation, allocation, validation, execution and release after equal warmup. Model construction/placement, correctness readback, process startup and compilation are outside timing. Both versions use the same compiler, Release/floating-point flags and backend configuration. No trial was discarded.

WorkloadProfileOriginal cached msCurrent cached msOriginal / current, 95% interval
ShortCPU Float645.4623.0481.792 [1.773, 1.825]
ShortCPU Float326.1793.4321.800 [1.715, 1.838]
ShortMetal Float32291.516145.8591.999 [1.800, 2.078]
LongCPU Float6441.43819.4802.127 [2.070, 2.183]
LongCPU Float3243.96921.1442.079 [2.045, 2.107]
LongMetal Float32604.712287.5302.103 [1.940, 2.449]

These are complete forced token scans: a prompt plus N forced appends produces N+1 next logit rows, without EOS or sampling. The report also retains preparation, prefill and decode phases separately. Natural generation is timed separately and uses at most N−1 decode appends for N output tokens; all recorded requests produce their full 32 or 64 token budget. For those EOS aware natural requests, Metal's original/current ratios are 1.946 [1.816, 2.025] for short and 2.102 [2.050, 2.152] for long. The report retains the current cached/uncached control and every CPU and Metal timing as well as the before/after comparison. These results describe these workloads on one host, not universal model or accelerator performance.

CPU Float32 fixed scan K/V owned capacity falls from 98,304 to 32,768 bytes for short and from 589,824 to 196,608 bytes for long: twelve to four bytes per value at the same capacity. CPU Float64 and Metal Float32 K/V byte capacities are unchanged. Every current fixed scan reserves its known horizon once with no committed prefix copies. Other peak changes depend on workload: Metal's tracked fixed scan peak increment is 100,768 to 98,304 bytes for short, and 1,114,624 to 720,896 bytes for long. These are tracked tensor/index/GPU buffer capacities, excluding ordinary untracked scratch, allocator, driver, BLAS and command buffer overhead or process RSS; they do not imply a halving of total Metal memory.

Each native process passes an untimed cached/uncached forced logit check, with maximum scaled error 1.595e-7 across the captured checks. All 192 native timing pairs retain identical cached/uncached generated IDs; corresponding original/current IDs also match. Every fixed and natural run releases tracked numeric buffers to its baseline, and fixed scans perform no activation readback. Precision thresholds are unchanged. No speed threshold decides correctness.

Matched original over current cached timing ratios for complete forced-token requests and decode phases on CPU Float64, CPU Float32 and Metal Float32; intervals resample eight paired processes with inner trials clustered.

The complete before/after evidence preserves both executable/source/build identities, all 48 matched outer records, all 192 native timing pairs, buffer counters and clustered statistics. The earlier cache introduction evidence below remains unchanged.

Supplemental portability validation ran on CPU Float64 and CPU Float32 on a separate Linux host with GCC 15.2 and a V100 installed: 2,771,396 native checks and 32 native CPU benchmark pairs passed. This CPU validation is separate from the matched M2 Max study. This historical study predates native CUDA sequence support. Its V100 host results are CPU observations; no V100 GPU generation or V100 accelerator timing is reported in that study.

Historical cache introduction comparison

This original cache introduction study retains its recorded implementation and all measurements. It predates the typed arena and fused inference attention described above; its buffer capacities and timings describe that earlier build.

The recorded study uses two common admissible fixed token workloads on one Apple M2 Max host: a 32 token prompt plus 32 forced single token appends at width 32, and a 128 token prompt plus 64 appends at width 64. Both have two layers, four heads, a fixed byte vocabulary and newly initialized weights. Each CPU Float64, CPU Float32 and Metal Float32 profile retains two excluded warmups per policy and eight paired repetitions with alternating execution order. The CPU thread environment request is one; provider identity, reported thread availability, OS, compiler, floating point flags and build/source identities are retained with the results.

Forced token scans perform the same inputs without sampling or EOS: one prompt prefill plus N forced appends produces N+1 next logit rows. A natural N output generation request needs at most N−1 decode appends after prefill; the recorded natural runs all produce their full 32 or 64 token budget. The fixed scans retain prompt prefill, session preparation, decode and complete request timing separately. Full request timing includes allocation, finite checks, preparation and release. Model placement, correctness readback and hashing are outside timing. Separate EOS aware greedy generation measurements retain actual token counts and equal output IDs; they are not substituted for the fixed work comparison.

WorkloadProfileUncached median msCached median msUncached / cached
ShortCPU Float6432.4045.3046.110
ShortCPU Float3235.5005.6706.261
ShortMetal Float32274.456290.3650.945
LongCPU Float64448.69039.69611.303
LongCPU Float32486.15942.63011.404
LongMetal Float32700.648639.4451.096

Ratios above one favor caching. The short Metal request is slower with caching in this recorded workload; its ratio is 0.945. The long Metal ratio is 1.096. CPU ratios and all slower samples remain in the same complete report. This result measures these shapes and this build, including final row vocabulary projection, rather than a universal accelerator or cache speedup.

All six profiles pass untimed forced logit checks, and all 48 paired timing trials return identical generated IDs. The maximum scaled forced logit error is 1.411e-7, within the declared precision thresholds. Every fixed scan returns tracked numeric buffers to its baseline and performs no activation readback; generated sampling separately reads its final vocabulary row. K/V capacities and peak increments measure tracked tensor/index/GPU buffer capacities, excluding ordinary untracked temporary scratch, allocator, driver and BLAS overhead or OS RSS. The earlier implementation's concatenation replacement buffers contribute to these historical peaks.

The chart shows complete request and forced decode ratios with 95% paired bootstrap timing intervals. The intervals describe repeated timings on this host, not variation across machines or model families. No timing threshold determines correctness.

Measured uncached over cached timing ratios for complete forced-token requests and decode phases on CPU Float64, CPU Float32 and Metal Float32; the short Metal case is slower with cache.

The complete paired measurements retain all raw timings, protocol settings, numerical/resource checks and reproducible summary statistics.

Pretrained import and execution

The supported import is a bounded GPT2LMHeadModel with local config.json, model.safetensors, vocab.json and merges.txt. It validates the expected architecture, tensor shapes, numerical conventions and tokenizer. The pretrained example expects a separately prepared compatible local directory; it performs no download. Full sized GPT 2 exceeds current parameter bounds. Other external architectures need their own compatibility implementation.

CPU Float64/Float32, complete native Metal/MPS Float32 and native CUDA Float64/Float32 sequence execution are supported where available. gen.to changes placement/precision as an explicit new run; matching placement preserves the current run. Exact same backend continuation is tested separately from tolerance based comparisons between backends.

model.memory_estimate(batch,length,training:false) still estimates full sequence forward with every vocabulary output row; it does not estimate the call local cached generation request. Its fits result is distinct from cached admission, so a full forward estimate can reject a wide vocabulary prefix that final row cached generation admits. The memory estimate counts conservative numeric buffers and checks tensor/work/graph limits. fits is admission to those limits, not a measurement of available RAM or VRAM. Generic full sequence attention workspace grows quadratically with sequence length; the generation only fused path does not allocate that full score matrix.

Native batched KV cached generation

model.generate_batch accepts 1 to 64 ragged prompt lists and returns generated ID lists in original request order. max_new_tokens accepts either one Int64 budget broadcast to every row or one Int64 per row. seeds requires one Int64 per row; repeated seeds are allowed. Temperature, top k and top p are shared sampling settings. Explicit per row seeds keep independent random streams: reordering requests does not mix seed values with row indices, and finishing one row consumes no draws for another.

aner
nn.configure("cuda", "Float32", "preserve")
let codec = token.byte_tokenizer()
let model = gen.decoder(codec, context: 24, width: 16,
    heads: 4, layers: 2, seed: 63, dropout: 0.0)
let first = codec.encode("ab", bos: true, eos: false)
let outputs = model.generate_batch(List(first, List(), first),
    max_new_tokens: List(4, 2, 0), temperature: 0.8,
    top_k: 20, top_p: 0.95, seeds: List(71, 19, 23))

Import aner.token, aner.gen and aner.nn as in the complete executable batch example. The example explicitly requires native CUDA Float32 with no CPU fallback. It checks mixed budgets, zero output, empty prompts, row reordering, scalar budget broadcast, independent single requests and unchanged inference state. The small seeded decoder represents these research mechanisms; users can train and compose more complex supported models and validate their own scientific or language objectives.

An empty prompt uses BOS. All rows are validated before decoder preparation, including zero budget rows. A zero budget row returns an empty list, reserves no K/V and consumes no random draws. EOS is included in its row's output and finishes that row independently; exhausted budgets also finish that row's logical decoding. The final generated token is never forwarded. Every positive row reserves its effective prompt length plus its budget minus one; earlier EOS can leave unused capacity.

CUDA and Metal cached prefill pack ragged token rows without padding; each projection processes the shared packed matrix. Causal attention reads only that request's accepted history and absolute positions. One generation only typed K/V arena holds disjoint row horizons; decoder weights and scratch buffers are shared. Stepwise decode packs unfinished rows. Resident Metal greedy requests retain their initial positive budget lanes and mask ended rows, as described above. Every successful append commits all participating row positions together. A failed append leaves all accepted positions unchanged; its partial suffix stays invisible and is overwritten on retry. Intermediate activations remain on the selected accelerator. Depending on the execution path, selection observes final vocabulary logits on the host or returns produced IDs from device state. The API remains in aner.gen, with private implementation in the existing native neural, Metal and CUDA files.

Native CUDA batch flow: validate ragged requests, pack shared projections, attend within each row's typed KV horizon, finish rows independently and return outputs in original order.

CPU Float64/Float32 retain the sequential reference implementation. Cached Metal Float32 batches use a native packed decoder plan. use_cache: false still evaluates each row's full prefix independently, and the private C++ test seam can select the prior Metal primitive reference. The recorded packed CUDA measurements below describe CUDA execution; Metal results are reported separately. Packed GEMM dimensions can change rounding near tied logits: the numerical contract uses full vector tolerances, and seeded ID equality is checked on the declared fixtures rather than promised for every possible model.

The batch keeps the existing context, width, head, layer, parameter, tensor and work bounds. Additional checks admit the sum of row horizons before allocation: at most 2,097,152 K/V values across the batch, with 2 * layers * width * sum(row_horizons) values. Each ordinary tensor remains at most 1,000,000 elements and each generation matrix operation at most 50,000,000 multiply adds. Packed prefill, per row causal history and active vocabulary projection must also fit these limits. The maximum batch size does not imply every 64 row shape fits. Compared with sequential requests, a packed batch retains all rows' K/V and wider scratch buffers simultaneously, increasing peak live memory. memory_estimate continues to describe full sequence forward/training, not this batch's cache admission.

Reproduce batch correctness and performance

Use a compatible Aner runtime with native CUDA support and the complete batch source. The runtime must support generate_batch. The source uses native CUDA Float32 explicitly and requires no external model service.

sh
aner check generative_batched.aner
aner run generative_batched.aner --dev batch-development-report
aner run generative_batched.aner --prod

The native repository's tests/gen_cache_tests.cpp --suite batched compares every forced next token logit with independent single cached and uncached requests. Tests cover ragged chunk partitions, causal histories, reordered/duplicate rows, BPE, nonzero and merged LoRA, frozen/trained decoders, supported GPT 2 conventions, typed cache accounting, output lifetime, concurrent distinct sessions and whole batch failure recovery. The reproducible native tools are tools/gen_batch_benchmark.cpp, tools/run_gen_batch_benchmark.py and tools/generate_generative_docs.py --cuda-batch-report. Maintainers retain exact build and toolchain recipes with private validation evidence; the linked public report contains anonymous source/build identities and complete measurements.

The collector runs all 12 workload/precision/batch profiles, retains every raw stdout/stderr capture and records source, executable, compiler and build identities. Eight fresh processes per profile each perform two alternating paired trials after two excluded warmups per policy. The paired comparator uses sequential independent optimized single request caches from the same executable and immutable weights. Five timing phases and 5,000 seeded bootstrap resamples retain whole process clusters. Full request time includes preparation, allocations, prefill, finite checks, decode, sampling, vocabulary readback and release; it excludes process startup, initial model construction and device placement. It measures warmed requests, rather than cold CUDA startup.

Fixed token work forces equal prompt/decode work without EOS stopping. Natural generation is measured separately with complete output IDs, actual generated counts and per row EOS outcomes. Aggregate throughput is actual output tokens divided by complete cohort wall time. Batch completion latency is the complete synchronous request wall time for every row; it is never divided by batch size to claim lower individual latency. Sequential measurements separately retain individual service durations and completion offsets from cohort start. These distinctions matter when choosing throughput versus interactive latency for a research workload.

Measured native CUDA batch comparison

This capture uses one Tesla V100 32GB, native CUDA 12.9/cuBLAS and GCC 13.4 in Release mode with strict Float64/Float32 arithmetic. Both policies run in the same executable with identical immutable seeded byte decoder weights: context 96, width 32, four heads, two layers and vocabulary 259. Tiny uses an 8 token prompt and up to 8 generated tokens per row; short uses 32 and up to 32. Each workload includes batch sizes 1, 4 and 8. All measured natural requests emitted their complete budgets; the report still retains actual IDs, token counts and EOS outcomes.

WorkloadPrecisionBatch sizeSequential cohort msPacked cohort msSequential / packed, 95% interval
TinyFloat6411.1251.1630.967 [0.952, 0.994]
TinyFloat6444.5931.6382.804 [2.751, 2.859]
TinyFloat6489.0182.0834.330 [4.248, 4.393]
TinyFloat3211.1141.1310.985 [0.967, 1.001]
TinyFloat3244.6001.5293.008 [2.937, 3.088]
TinyFloat3288.7941.9534.502 [4.386, 4.698]
ShortFloat6414.3504.4290.982 [0.960, 1.008]
ShortFloat64417.4026.1212.843 [2.820, 2.879]
ShortFloat64835.0518.1394.307 [4.231, 4.402]
ShortFloat3214.4004.4060.999 [0.958, 1.022]
ShortFloat32417.2095.8822.926 [2.900, 2.974]
ShortFloat32833.9577.5864.476 [4.351, 4.543]

These are process cluster medians of complete cohort wall time. Batch size 8 reduces cohort time by 4.31 to 4.50 times across these profiles, with measured aggregate throughput of 30,736 to 33,746 generated tokens/second. Batch size one retains overhead: tiny Float64 takes 1.163 ms packed versus 1.125 ms single, with a ratio of 0.967 [0.952, 0.994]. Larger batches also increase individual completion latency relative to an isolated request. For short Float32, all eight packed requests return together in 7.586 ms, compared with 4.400 ms for the single request cohort and 33.957 ms to serve eight sequential requests. This is a throughput/completion tradeoff, not a claim that each request becomes four times faster.

The table and chart use median of two trial times within each process, followed by the median of eight processes. The report additionally retains descriptive individual service durations and completion offsets; its secondary request distribution medians use all retained calls and can differ slightly from these clustered timing medians. The 95% intervals resample whole process clusters and do not treat individual rows or inner trials as independent observations.

Measured V100 packed versus sequential cohort time ratios for every workload, precision and batch size, with whole-process 95 percent intervals and complete packed completion time in milliseconds.

Correctness compares every forced next token vocabulary logit with independent single cached and full prefix uncached execution. All 96 benchmark processes pass the existing scaled tolerances of 1e-10 for Float64 and 5e-4 for Float32, and all 192 natural generation pairs retain identical per row IDs. Separate native verification passes 37 focused V100 regression tests and five Compute Sanitizer runs, with unfiltered memory/initialization checks and all native kernels included for race/synchronization checks. A positive filter control detects an actual invalid write. The exact CUDA batch example passes all eight assertions with identical development/production output. The separate CPU/Metal host passes 23 focused tests and 2,729,269 batch checks for each CPU Float64, CPU Float32 and Metal Float32 profile.

A separate diagnostic confirms actual shared CUDA projections: each two layer packed append uses nine GEMMs, 17 native kernels and one scalar status transfer, compared with nine GEMMs, 17 kernels and one status transfer per active row in the sequential policy. Prefill, decode and compacted ragged/uniform B4/B8 profiles pass in both precisions. These counters establish the execution mechanism and are excluded from formal timing.

Memory accounting retains the cost of batching. In the short fixed work Float64 scan, batch size 8 retains 512 KiB of live K/V versus 64 KiB for one sequential request; Float32 uses 256 KiB versus 32 KiB. Both policies process the same summed horizons. The packed arena allocates once with zero prefix copies, while sequential requests allocate one arena per request and release it before the next. Wider packed scratch buffers increase tracked peaks further. All tracked numeric buffers return to their pre call baseline; fixed forced scans perform no activation readback. The tracked counters exclude driver/cuBLAS allocations and process RSS.

The complete batch evidence retains all 96 fresh process records, 192 native paired trials, 60 independently reproducible phase intervals, output IDs/counts, memory observations, anonymous V100 snapshots and source/build hashes. GPU snapshots show no other compute processes before or after capture; they do not establish exclusive utilization throughout. No jobs, clocks, drivers or services were changed. These small new weight workloads measure native execution, rather than trained language quality or unrestricted model scale. Earlier scientific, cache and CUDA measurements retain their original assets and uncertainty scope.

Ragged batch workspace efficiency

The native batch API also handles different prompt lengths and output budgets without padding or changing request order. CUDA reuses three temporary buffers at their non overlapping lifetimes: hidden values, normalization/attention values, and shared QKV/output/feed-forward projections. For workspace capacity C and model width W, numeric scratch falls from 10 * C * W to 6 * C * W typed values. UInt32 token/position metadata adds 4 * (3 * C + batch_size) bytes, where batch_size is the fixed count of cached rows after zero budget requests are excluded. It does not decrease as those rows finish. Float64 still uses eight bytes per value and Float32 four; this change preserves K/V precision and the exact sum of row horizons.

Native CUDA workspace diagram: unchanged exact-horizon K/V, three buffers with disjoint lifetimes, one-time decode sizing, transactional replacement, and independent held logits.

After the prompt's first logits are sampled, the scheduler counts requests that have another decode step. It can right size the transient workspace once when capacity is at least eight times that count and the typed scratch saving is at least 128 KiB. This threshold was fixed before measurement. All replacements allocate before the old workspace is released; a failed replacement preserves the old workspace and every accepted position. K/V never moves or shrinks, and an already returned logits tensor owns independent storage. Later private chunked appends can grow workspace normally. Requests below either sizing threshold retain their existing workspace. Public generation reuses its row token lists instead of rebuilding them each step; per row seeds, EOS, budgets, validation and output order retain their contract.

Each two layer packed append uses 14 native kernels and nine GEMMs, with the same typed arithmetic and finite checks. The earlier implementation used 17 kernels and nine GEMMs. Embedding plus the first normalization share a launch; each attention residual plus its following normalization also share a launch. Raw projection, bias, residual, variance and GPT 2 activation intermediates retain their checks before all accepted positions commit. Single request and differentiable sequence operations retain their implementation. CPU and Metal keep the same batch API through their sequential reference path.

The complete batch example is unchanged and runs against the improved native implementation. Its development/production assertions still compare ragged calls, independent requests, explicit seeds, mixed/zero budgets and unchanged model state. Native regression tests add non power of two widths, finite extreme values, fused overflow rejection, threshold adjacent workspace sizes, held logits across trimming and regrowth, failed tail recovery and portable operation with no effect hint checks. These reference inputs expose native research mechanisms; trained model quality and larger research designs need their own evaluation.

Reproduce the ragged comparison

This study compares a preserved implementation with the current native implementation using the exact same C++ producer and two immutable CUDA checkpoints, one per precision. Both executables load the same checkpoint files; their loaded model provenance stays unchanged, while the report separately records each compiled runtime identity. Source manifests and strict compiler/toolchain recipes establish that distinction. No tokenizer, model weight, precision or sampling policy is changed to produce the comparison.

All 12 profiles use context 192, width 32, four heads, two layers and vocabulary 259. Each workload runs batch size one and eight with CUDA Float64 and Float32:

WorkloadPrompt lengths for eight rowsOutput budgets for eight rows
Uniform control8, 8, 8, 8, 8, 8, 8, 88, 8, 8, 8, 8, 8, 8, 8
Ragged1, 3, 7, 31, 2, 5, 13, 4732, 1, 16, 2, 24, 3, 8, 4
Larger prefill1, 3, 7, 15, 31, 63, 95, 1271, 2, 3, 4, 2, 3, 4, 8

The batch one control selects the row with the largest declared prompt plus output horizon and retains that row's original token content and seed. Thus the ragged control uses 47 prompt tokens and four outputs; the larger prefill control uses 127 and eight. Forced work mirrors the public forwarding count: prompt prefill plus N - 1 forced decode inputs produces N next token logits per row. It ignores EOS for equal work and records every active row count, accepted position, logical/reserved K/V size, current workspace and peak allocation. This differs from the older batch study's N forced appends. Natural generation is measured separately with actual complete IDs, counts and EOS outcomes.

The native reproduction tools are tools/gen_batch_efficiency_benchmark.cpp, tools/run_gen_batch_efficiency.py and tools/generate_generative_docs.py --cuda-ragged-report. Use the unchanged runnable source with a compatible Aner runtime with native CUDA support:

sh
aner check generative_batched.aner
aner run generative_batched.aner --dev ragged-development-report
aner run generative_batched.aner --prod

Each profile retains eight matched pairs of fresh processes. Baseline/current version order alternates, profile order rotates, and both processes exclude two warmups before two alternating native trials. The five primary phase intervals and the sequential single request control resample whole matched process pairs, with 5,000 fixed seed bootstrap draws. Inner trials and request rows are not independent uncertainty samples. Full natural request time includes validation, preparation, allocations, prefill, finite checks, the sizing hint, decode, sampling, final vocabulary readback and release. Process startup, checkpoint loading and independent correctness checks are outside timing. Forced scan timing additionally includes its stage snapshot collection; natural generation does not collect those snapshots. Warmed request measurements do not estimate cold CUDA startup.

Current retained workspace, peak allocation and reserved K/V are different quantities. Replacement briefly holds old and new workspace together, so trimming cannot erase the prefill peak and its allocations can cost time. The report retains that transient peak and every sizing cost. Tracked memory includes owned typed numeric buffers and UInt32 metadata; it excludes driver/cuBLAS/allocator overhead and process RSS. Aggregate throughput uses actual emitted tokens over complete cohort wall time; individual completion latency is never obtained by dividing wall time by batch size.

Measured ragged batch optimization

On the Tesla V100 PCIE 32GB, all 12 profiles pass full logit checks against sequential cached and uncached references. Across both implementations, the capture checks 3,331,776 logit cells and retains complete generated IDs, EOS outcomes and exact byte counters. CUDA Float64 uses scaled tolerance 1e-10; Float32 uses 5e-4. The final native suite passes 37 CTests, five CUDA sanitizer runs and the unchanged eight assertion batch example in both development and production mode. CPU and Metal pass 23 focused CTests.

WorkloadPrecisionBatchPreserved / current request msTime ratio [95% interval]
UniformFloat6411.189 / 1.1221.060 [1.028, 1.102]
UniformFloat6482.178 / 2.1171.028 [1.003, 1.036]
UniformFloat3211.159 / 1.1031.050 [1.020, 1.126]
UniformFloat3282.066 / 1.9771.045 [1.000, 1.056]
RaggedFloat6410.677 / 0.6441.052 [0.991, 1.076]
RaggedFloat6485.647 / 5.3801.050 [1.030, 1.057]
RaggedFloat3210.636 / 0.5841.089 [1.050, 1.120]
RaggedFloat3285.398 / 5.2331.031 [1.018, 1.071]
Larger prefillFloat6411.284 / 1.2860.999 [0.951, 1.031]
Larger prefillFloat6481.643 / 1.6630.988 [0.980, 1.034]
Larger prefillFloat3211.219 / 1.1301.079 [0.990, 1.134]
Larger prefillFloat3281.579 / 1.5331.030 [1.008, 1.052]

A ratio above one favors the current implementation. Ragged batch eight request time ratios are 1.050× in Float64 and 1.031× in Float32. The larger prefill Float64 cohort is about 1.2% slower at the median and its interval includes no change; its one row control also shows no resolved gain. The larger prefill Float32 one row interval includes no change. These small synthetic decoders establish execution costs, not trained model quality or a speed guarantee for larger architectures.

Batch eight workloadPrecisionWorkspace + metadata before / current prefill / current after hint (bytes)Reserved K/V, unchanged (bytes)Peak tracked device allocation before / current (bytes)
UniformFloat64164,640 / 99,104 / 99,104122,880304,096 / 238,560
UniformFloat3282,720 / 49,952 / 49,95261,440152,448 / 119,680
RaggedFloat64280,380 / 168,764 / 10,868195,584492,540 / 391,792
RaggedFloat32140,860 / 85,052 / 85,05297,792246,940 / 191,132
Larger prefillFloat64879,656 / 529,448 / 10,868369,6641,265,896 / 926,556
Larger prefillFloat32441,896 / 266,792 / 5,492184,832635,016 / 465,404

The three buffer reuse reduces numeric scratch by 40% before any sizing hint. Including metadata, retained workspace for the larger prefill Float64 batch falls from 879,656 to 10,868 bytes (98.8%); its measured peak tracked device allocation falls from 1,265,896 to 926,556 bytes (26.8%). K/V stays at 369,664 bytes. The peak includes temporary overlap while replacement buffers are allocated. The Float32 ragged cohort remains below the 128 KiB savings threshold, so it benefits from buffer reuse without resizing. Byte values are deterministic across all retained trials; timings and their uncertainty are reported separately.

Matched V100 request timings across twelve profiles with whole-process uncertainty, plus batch-eight retained workspace including metadata.

Download the complete ragged measurement report for all raw process records, source/build identities, checkpoint hashes, phase intervals, generated IDs, actual token throughput, completion latency and stage by stage allocation snapshots. The previous batch versus sequential measurements remain available above as a separate historical study.

Larger prefill batch performance

The next native CUDA refinement reduces allocation overhead while retaining the ragged study's memory gains. One private workspace owner contains the same three non overlapping numeric regions plus UInt32 token/position metadata: hidden values C * W, normalization/attention values C * W, projections 4 * C * W, then 4 * (3 * C + batch_size) metadata bytes. Numeric storage remains 6 * C * W typed values. There is no padding or additional mirror. The exact row horizon K/V arena and each returned logits tensor keep independent ownership.

The existing aner.gen batch API and sizing policy are unchanged. After prefill, sufficiently oversized workspace can still shrink once at the fixed eight-times/128 KiB threshold. A complete replacement allocates before publishing its owner; allocation failure leaves accepted positions, live workspace and K/V untouched. On its own allocation failure, the workspace acknowledges CUDA's out of memory status before raising the original error, so a valid retry does not inherit that stale status. Later chunked appends can regrow the workspace. Each logical region retains its existing admission limit even when their combined private allocation is larger than one ordinary tensor. This preserves previously legal model/batch geometries.

For the first two layer packed append of a new cache, after backend/model setup, native allocation calls fall from six to three: K/V, the combined workspace and an independently owned vocabulary result. A qualifying sizing hint replaces four allocation/free pairs with one pair. Both implementations still issue 14 native kernels and nine GEMMs, with the same shapes, typed arithmetic, finite checks and scalar status transfer. Single request generation, uncached references, training and CPU/Metal execution retain their existing implementations. Sampling still reads the final vocabulary results.

Correctness tests cover combined workspace beyond the ordinary tensor limit, odd widths and packed capacities, the metadata suffix, trim/decode/regrowth, unread output lifetime, numeric failures and retry. Separate native API diagnostics inject a failed allocation, check that memory/K/V/cursors stay unchanged, then require successful retry. Diagnostic tracing establishes allocation counts and execution structure; its instrumented timings are excluded from the performance study.

Reproduce the larger prefill comparison

This comparison uses the same native producer tools/gen_batch_efficiency_benchmark.cpp as the preceding study. The existing collector adds --comparison prefill-workspace; its default historical ragged mode remains reproducible. The preserved and current libraries compile that identical producer with matched strict Release/sm70 flags and load two immutable checkpoint files created by this study's preserved implementation. Runtime identity is recorded separately from loaded checkpoint provenance.

All 12 previously declared profiles are retained: uniform, ragged and larger prefill schedules, batch sizes one/eight and CUDA Float64/Float32, with the same context 192, width 32, four heads, two layers and vocabulary 259. The predeclared primary is complete natural generation time for larger prefill Float64 batch eight. Each profile retains 32 matched pairs of fresh processes, with two excluded warmups and two alternating inner trials per process. Version order alternates and profile order rotates. That gives 384 matched pairs and 768 fresh processes; every observation is retained.

The 95% bootstrap intervals resample whole matched process pairs with 5,000 draws and seed 20261016. Five phase intervals and the sequential single request control produce 72 intervals across the 12 profiles. Rows and inner trials are not independent uncertainty samples. Complete request timing includes validation, preparation, allocations, prefill, finite checks, resizing, decode, sampling, readback and release. Process startup, checkpoint loading and correctness checks are outside timing. Forced scans mirror P + N - 1 forwarded inputs per row and additionally collect stage snapshots; natural calls do not. Actual emitted tokens determine aggregate throughput, and completion latency is never obtained by dividing cohort time by batch size.

The complete batch source is unchanged. Run it with a compatible Aner runtime with native CUDA support:

sh
aner check generative_batched.aner
aner run generative_batched.aner --dev prefill-development-report
aner run generative_batched.aner --prod

For the native Float64 variant, change the example's configuration line to:

aner
nn.configure("cuda", "Float64", "preserve")

All eight checks must still print true, followed by batch_checks_passed. Development and production runs must agree on the same backend and precision.

Measured larger prefill comparison

On the Tesla V100 PCIE 32GB, the predeclared larger prefill Float64 batch eight target completes in 1.644 ms preserved / 1.614 ms current, a 1.019× ratio with a paired 95% interval of [1.003, 1.029]. This is a modest improvement for this bounded reference decoder. Its prefill phase improves from 0.256 to 0.250 ms (1.023× [1.005, 1.037]); its complete forced scan improves from 1.130 to 1.102 ms (1.026× [1.013, 1.040]). Preparation alone has an interval spanning one. The primary was declared before measurement; the other intervals are exploratory and are not adjusted for multiple comparisons. All 12 complete request results are shown below; intervals for the uniform and ragged batch eight controls span one, so they do not establish a speed improvement.

WorkloadPrecisionBatchPreserved / current request (ms)Preserved / current ratio [95% interval]
UniformFloat6411.098 / 1.1000.998 [0.976, 1.018]
UniformFloat6482.140 / 2.1321.004 [0.984, 1.027]
UniformFloat3211.100 / 1.0731.026 [0.998, 1.047]
UniformFloat3282.016 / 2.0190.998 [0.983, 1.018]
RaggedFloat6410.652 / 0.6321.032 [1.006, 1.057]
RaggedFloat6485.410 / 5.3971.003 [0.980, 1.019]
RaggedFloat3210.602 / 0.5931.016 [0.989, 1.051]
RaggedFloat3285.164 / 5.1850.996 [0.978, 1.015]
Larger prefillFloat6411.253 / 1.2221.025 [1.011, 1.034]
Larger prefillFloat6481.644 / 1.6141.019 [1.003, 1.029]
Larger prefillFloat3211.142 / 1.1430.999 [0.984, 1.026]
Larger prefillFloat3281.535 / 1.4911.030 [1.003, 1.046]

Both versions retain identical memory at every measured stage and peak, including transient replacement overlap. For batch eight, each value below applies to both implementations. Workspace includes metadata; the peak is incremental tracked numeric device memory above the loaded model baseline. It excludes CUDA allocator/driver/cuBLAS overhead and process RSS.

WorkloadPrecisionPrefill workspace bytesRetained workspace bytesReserved K/V bytesFixed / natural peak bytes
UniformFloat6499,10499,104122,880238,560 / 238,560
UniformFloat3249,95249,95261,440119,680 / 119,680
RaggedFloat64168,76410,868195,584391,792 / 391,792
RaggedFloat3285,05285,05297,792191,132 / 191,132
Larger prefillFloat64529,44810,868369,664926,556 / 926,556
Larger prefillFloat32266,7925,492184,832465,404 / 465,404

The Float64 larger prefill workspace therefore remains 529,448 bytes during prefill and 10,868 bytes after the hint, with 369,664 reserved K/V bytes and a 926,556 byte peak. The gain comes from fewer allocation operations, while retaining the preceding compact layout and its sizing policy.

The final native source passes 37 V100 CTests and five Compute Sanitizer runs, plus 23 CPU/Metal CTests. Each CUDA precision passes 5,625,030 cache checks. Across this timing study, independent replay verifies 13,327,104 forced logit cells, 20,480 memory snapshots, full natural output IDs and all 72 bootstrap intervals. Separate real CUDA workspace allocation OOM tests pass first retry in Float64 and Float32 while preserving K/V, positions and live bytes. The complete Float32 example and its single line Float64 variant pass all eight checks identically in development and production.

The report records the exact source, producer, executable and checkpoint fingerprints, raw capture hashes, actual emitted counts, service and completion durations, and memory arrays. It uses strict sm70 arithmetic with CUDA 12.9.86, cuBLAS 12.9.1.4 and GCC 13.4. The Ubuntu 26.04 host is newer than the CUDA 12.9 qualification matrix; the private toolchain receipt declares its compatibility setup and successful native/sanitizer probes. No driver, clocks or other jobs were changed. Point in time idle snapshots do not establish exclusive use. These measurements characterize a small warmed decoder; researchers must benchmark their own model, batch geometry and workloads.

V100 complete-request ratios and unchanged retained workspace across all twelve profiles

The chart shows whole process paired uncertainty; ratios above one favor the current implementation. Download the complete measured report.

Batched CUDA launch fusion

The native aner.gen batched decoder now combines each non final feed forward residual addition with the next decoder block's first layer normalization. It reuses the existing typed residual/normalization kernel. The next block consumes that normalized workspace directly, removing one native launch at every inter layer boundary. This applies to packed prefill, ragged continuation chunks and decode, in both Float64 and Float32, including supported imported GPT 2 blocks with projection biases.

The hidden workspace and projected feed forward values occupy distinct regions. Within each packed token block, all threads consume the projected values and publish the residual before a block barrier; normalization then uses the same reduction order and can safely overwrite the old projection output region. The parameter cursor still consumes every block header, including each next normalization gain and bias. Finite value checks and the append's error status remain in place.

When every active row appends exactly one token, all packed tokens are selected final rows, in identity order even when some logical rows are inactive. The last feed forward residual can then share the existing normalization kernel too. Longer chunks retain the separate residual and selective final normalization path. Final normalization still processes only each active row's last token. Normalizing every packed prefix token at that stage would change which numerical failures are observable, so this optimization keeps the existing selective behavior.

Decoder layersPreserved native launchesCurrent longer chunksCurrent one token active rowsGEMM calls in both versions
18875
21413129
320181713
426232217
850434233

These counts describe the native packed append after model/backend setup: 6 * layers + 2 becomes 5 * layers + 3 for longer chunks, or 5 * layers + 2 when all active rows append one token; GEMMs remain 4 * layers + 1. They do not count private kernels scheduled inside cuBLAS. The public batch API, ordinary tensor/work admission, allocation calls, right sizing thresholds and exact K/V row horizons retain their previous behavior. One private workspace still holds 6 * C * W typed scratch values plus 4 * (3 * C + batch_size) metadata bytes. No new activation storage or metadata is introduced. Returned logits retain independent ownership.

Validate and reproduce launch fusion

Correctness tests exercise full vocabulary batched outputs against independent single cache and uncached references across multiple depths, odd widths and wider reductions. They cover ragged chunks, causal isolation, nonzero imported biases, unread output lifetimes, trim/regrowth and failure/retry at inter layer numerical boundaries. Numeric failure preserves accepted positions and prefixes; later valid appends must correctly replace uncommitted tail values. Allocation failure recovery retains the preceding workspace OOM handling.

The complete native batch example remains the runnable API reference. With a compatible Aner runtime with native CUDA support:

sh
aner check generative_batched.aner
aner run generative_batched.aner --dev launch-development-report
aner run generative_batched.aner --prod

The example uses Float32. To test Float64, change its configuration line to nn.configure("cuda", "Float64", "preserve"). Both modes must print eight true checks and batch_checks_passed on the same backend and precision. The small model represents native mechanisms; researchers compose supported architectures and choose independent data, training and evaluation protocols for their applications.

The launch study uses the identical native producer and 12 workload profiles from the preceding compact workspace study: uniform, ragged and larger prefill schedules; batch one/eight; strict CUDA Float64/Float32; context 192, width 32, four heads, two layers and vocabulary 259. Each version loads the same immutable checkpoints freshly created by the preserved implementation. The predeclared primary is complete natural generation time for ragged Float64 batch eight. The one layer correctness case is a control where no inter layer fusion applies; its one token rows still exercise the final residual/normalization fusion.

Each profile retains 32 matched pairs of fresh processes with alternating version order, rotating profile order, two excluded warmups per mode and two alternating inner trials. All 384 matched pairs and 768 process captures are retained. The 95% intervals use 5,000 whole process paired bootstrap draws with seed 20261017; five phases plus a sequential single cache control across 12 profiles produce 72 intervals. Inner trials and rows are not independent uncertainty samples. Secondary intervals are exploratory and unadjusted for multiple comparisons.

Complete request timing includes validation, preparation, allocation, prefill, finite checks, sizing, decode, sampling, readback and release. Startup, checkpoint loading, correctness checks and API tracing are excluded. Forced scans use P + N - 1 forwarded inputs per row and collect memory snapshots separately from natural calls. Throughput uses actual emitted tokens; cohort wall time divided by batch size is not individual completion latency. Exact stage and peak tracked memory must match across preserved and current versions.

Measured launch fusion comparison

On the Tesla V100 PCIE 32GB, the predeclared ragged Float64 batch eight primary completes in 5.431 ms preserved / 5.252 ms current, a 1.034× preserved/current ratio with a paired 95% interval of [0.994, 1.047]. The primary interval includes one, so this run does not establish a complete request improvement. The measured native launch reduction is distinct from whole request speed: GEMMs, sampling, allocation and synchronization remain in the request. These results describe one small warmed reference decoder.

For the primary workload, the separately measured forced decode phase is 3.430 / 3.308 ms, a 1.037× ratio [1.026, 1.046]. This is an exploratory phase result; it does not replace the inconclusive complete request primary. All 12 sequential control intervals include one, and none of the 72 measured intervals lies entirely below one.

WorkloadPrecisionBatchPreserved / current request (ms)Preserved / current ratio [95% interval]
UniformFloat6411.109 / 1.0731.034 [1.003, 1.062]
UniformFloat6482.128 / 2.1281.000 [0.984, 1.021]
UniformFloat3211.088 / 1.0481.038 [1.015, 1.056]
UniformFloat3282.029 / 1.9871.021 [0.999, 1.040]
RaggedFloat6410.642 / 0.6231.030 [1.007, 1.047]
RaggedFloat6485.431 / 5.2521.034 [0.994, 1.047]
RaggedFloat3210.592 / 0.5691.042 [1.009, 1.058]
RaggedFloat3285.283 / 5.1341.029 [1.008, 1.053]
Larger prefillFloat6411.239 / 1.2041.029 [0.996, 1.045]
Larger prefillFloat6481.629 / 1.6021.017 [0.991, 1.040]
Larger prefillFloat3211.161 / 1.1131.043 [1.013, 1.071]
Larger prefillFloat3281.530 / 1.4931.025 [0.999, 1.045]

An earlier complete 384 pair study of inter layer fusion alone produced a ragged Float64 batch eight ratio of 1.011 [0.991, 1.023], which did not establish a complete request gain. That source and every observation remain retained privately as a separate study. The final engineering revision also fuses the final residual and normalization only for one token active rows, then repeats the same originally declared primary, profile set and sampling protocol with fresh processes and checkpoints. The two studies are not pooled.

All measured stage and peak tracked bytes are identical across implementations, including transient trim overlap. Each batch eight value below applies to both versions. Workspace includes metadata; peaks are incremental tracked device bytes above the loaded model baseline. CUDA driver, allocator and cuBLAS overhead and process RSS are outside this accounting.

WorkloadPrecisionPrefill workspace bytesRetained workspace bytesReserved K/V bytesFixed / natural peak bytes
UniformFloat6499,10499,104122,880238,560 / 238,560
UniformFloat3249,95249,95261,440119,680 / 119,680
RaggedFloat64168,76410,868195,584391,792 / 391,792
RaggedFloat3285,05285,05297,792191,132 / 191,132
Larger prefillFloat64529,44810,868369,664926,556 / 926,556
Larger prefillFloat32266,7925,492184,832465,404 / 465,404

The final native source passes 37 V100 CTests, five Compute Sanitizer runs and 23 CPU/Metal CTests. Each CUDA precision passes 8,160,724 cache checks; maximum scaled errors are 3.324e 16 for Float64 and 1.727e 7 for Float32. Untimed native API traces cover 30 model/precision/depth profiles and 90 prefill/decode/regrowth regions per implementation. They verify the table's longer chunk and one token launch counts at all five depths, the unchanged 4 * layers + 1 GEMM counts and shapes, identical allocation calls and exact byte geometry. Native widths three/32 and deterministic local GPT 2 import fixtures with nonzero biases are checked in both precisions. Each implementation's depth probes compare 8,124,000 logit cells against independent references and retain unread output through regrowth and cache destruction. These local import fixtures validate execution structure; they are not pretrained quality evaluations.

Separate workspace allocation tests trigger actual CUDA OOM status in an untimed driver probe, preserve old K/V, accepted positions and live bytes, then require first valid retry in both precisions. The unchanged native Float32 example and its single line Float64 variant pass eight checks identically in development and production. The final timing study verifies 13,327,104 forced logit cells, 20,480 memory snapshots and full natural output IDs. Independent replay recomputes all 72 intervals.

The report retains exact runtime/source, executable, shared producer and checkpoint fingerprints; raw capture hashes; complete emitted IDs/counts; service/completion durations; memory arrays; and anonymous host/toolchain details. The strict sm70 build uses CUDA 12.9.86, cuBLAS 12.9.1.4 and GCC 13.4, with no lowered precision or fast math. The private toolchain receipt declares its compatibility setup on Ubuntu 26.04, newer than CUDA 12.9's qualification matrix, and successful native/sanitizer probes. No driver, clocks or other jobs were changed; point in time idle snapshots do not prove exclusive device utilization. Researchers should reproduce complete request measurements for their model and workloads.

V100 batched launch-fusion request ratios with paired uncertainty and unchanged retained workspace

Ratios above one favor the current implementation. The chart retains all 12 workload profiles and shows unchanged retained workspace. Download the complete measured launch fusion report.

Native CUDA graph replay

aner.gen supports explicit CUDA graph replay for cached batched generation. Add cuda_graph: true to either budget overload of model.generate_batch; its existing use_cache default remains true. Positional calls use seeds, use_cache, cuda_graph as their final arguments. The default is cuda_graph: false. Requesting it on CPU, Metal or use_cache: false raises an error, including for an all zero budget request. The option belongs to the inference call and does not change model parameters, checkpoints or training state.

aner
let graph = model.generate_batch(prompts, max_new_tokens: budgets,
    temperature: 0.8, top_k: 20, top_p: 0.95, seeds: seeds,
    cuda_graph: true)
let eager = model.generate_batch(prompts, budgets, 0.8, 20, 0.95,
    seeds, true, false)

The first successful one token step warms the current active row count. A subsequent matching step records the existing decoder blocks and final hidden normalization, then instantiates and launches one private graph when the remaining budget setup policy admits capture. Private calls with unknown remaining work retain the original second step behavior. Further matching steps replay it. Token IDs, absolute positions, logical row masks and KV offsets are uploaded afresh before every call; the graph reads those current values. Equal size masks can change logical rows without rebuilding. Prefill and longer chunks use the existing native eager path.

At most one executable graph is retained per cache. A changed active row count or KV owner replaces the binding; a successful workspace resize or qualifying decode trim invalidates it before releasing old storage. Workspace replacement is staged first, so an allocation failure preserves the previous usable workspace and graph. The graph weakly binds the caller's KV owner and is destroyed before its workspace and weights. It does not keep a second KV arena, activation workspace or logits staging buffer.

The vocabulary projection and final finite check remain outside the graph and write a fresh independently owned result. Retained outputs remain valid across replay, resizing, moves and cache destruction. Finite status is reset and checked on every append, and row cursors are committed only after complete success. Launch or execution errors are raised without an eager retry that could duplicate work. Recognized optional capture/instantiation resource failures disable replay for that cache and continue with native eager CUDA execution; this is an execution optimization with a bounded fallback, rather than an alternative numerical backend.

Capture explicitly disables cuBLAS's default workspace with cublasSetWorkspace(handle, nullptr, 0) and restores the normal workspace policy before ordinary operations. Only kernel and empty nodes are accepted; captured allocation, copy and external storage nodes are rejected. This keeps the existing 6CW typed scratch values plus (3C+B) uint32 metadata values, fixed row horizon KV and fresh output ownership. Here C is workspace token capacity, W is model width, and B is the fixed logical batch size. CUDA graph objects still have opaque driver/runtime memory costs, which are outside Aner's numeric buffer accounting and are reported separately. The mechanism follows NVIDIA's CUDA graph stream capture contract and cuBLAS 12.9 graph/workspace contract.

For L decoder layers, stable replay replaces 5L+1 custom kernel submissions and 4L GEMM submissions in the trunk with one cudaGraphLaunch. The same device computations still execute inside the graph. The remaining tied vocabulary GEMM and one finite check kernel are submitted normally. At two layers, that means one graph launch plus one ordinary kernel and one ordinary GEMM, compared with twelve ordinary custom kernels and nine GEMMs for eager one token decode. Metadata upload, finite status transfers, sampling, synchronization, allocations and graph setup/destruction remain part of the request.

The introduction lifecycle diagram shows the unknown window capture path; the current public call gate is shown in the budget aware diagram below.

Native CUDA graph lifecycle, dynamic metadata, independent outputs and bounded graph ownership

Validate and reproduce graph replay

The complete native CUDA graph example checks graph/eager/full-prefix output parity, empty prompts, zero budget rows, independent seeds, scalar budgets and unchanged model state. It uses small new research weights to represent an execution capability; users can compose more complex models and must validate their own quality, scale and workload. It needs a compatible Aner runtime with native CUDA support containing the graph option.

sh
aner check examples/generative_cuda_graph.aner
aner run examples/generative_cuda_graph.aner --prod
aner run examples/generative_cuda_graph.aner --dev dev-cuda-graph

The source explicitly selects CUDA Float32. Changing only that nn.configure precision literal to Float64 runs the other supported precision. Development and production modes execute the same native inference path.

The graph replay introduction source passed 37 V100 CTests, five Compute Sanitizer runs, and 23 CPU/Metal CTests. The current setup policy validation is reported below. Each V100 precision passes 11,083,312 batched cache checks, with maximum scaled error 3.324e 16 for Float64 and 1.727e 7 for Float32. Tests compare every logit with ordinary cached and independent full prefix references, exercise active mask changes, absolute positions, longer chunks, resize/trim, retained unread outputs, move/destruction, concurrent independent plans, EOS and invalid inputs. Native odd width and multiple depth models, nonzero LoRA factors, and local GPT 2 fixtures with nonzero biases are included; those fixtures test execution and do not establish pretrained quality.

Twenty separate untimed driver probes verify actual capture/replay counts, independent uncached CPU reference logits, and graph lifetimes in both precisions. Their 119,658 CPU reference cells have maximum scaled error 1.475e 7. They trigger genuine capture invalidation, bounded optional setup failures, workspace OOM and rejected launches. Thirty two actual numeric replay failures include first/middle/last rows and imported GPT 2 cubic overflow; same failed row retries use fresh masks without recapture. Launch rejection raises the original error, leaves positions uncommitted and permits the first valid retry. An initial fault probe exposed a stale CUDA last error status on that retry; the final source acknowledges only the matching launch error before raising it, then repeats all native, sanitizer and probe validations. No initial revision timings are pooled into this study.

Unfiltered full leak memcheck runs cover Float64 and Float32, with unfiltered initcheck for Float32. Racecheck and synccheck use the native kernel namespace filter; a separate positive control confirms that the filter detects an invalid write. No sanitizer suppression is used. The complete Float32 example and its precision only Float64 variant each pass eight checks identically in development and production. The smaller local validation also checks unchanged CPU/Metal execution and eager graph counters.

The comparison retains the earlier short, ragged and larger prefill workloads and adds a longer decode workload with an eight token prompt and up to 64 outputs per row. All sixteen workload/precision/batch profiles use the same immutable seeded checkpoints and the same producer in both implementations. The eager checkpoint origin is retained when loading the candidate. Every profile has 32 matched pairs of fresh processes, two inner trials and two excluded warmups per mode; all observations are retained. Version order alternates and profile order rotates. Confidence intervals use 5,000 whole pair bootstrap resamples with seed 20261018. The predeclared primary remains ragged Float64 batch eight complete natural request time. The other 95 intervals are exploratory and unadjusted.

Warmups do not retain a graph for a timed request: every timed call starts a fresh cache and includes its own capture, instantiation, sampling, sizing and destruction costs. Short requests can spend more on setup than they save on replay. Fixed work scans record exact expected capture/launch counters for each active count schedule and reject silent fallback; natural requests retain their actual IDs, EOS outcomes and token counts. A whole cohort's wall time is never divided by batch size to claim individual latency. Tracked stage and peak numeric buffer memory must match eager execution exactly; that does not imply that opaque CUDA graph memory is free.

Measured graph replay comparison

This historical comparison records the original always capture policy against eager execution. Its source fingerprints and assets remain unchanged; the current budget aware policy has a separate comparison below.

On the Tesla V100 PCIE 32GB, the predeclared ragged Float64 batch eight primary takes 5.242 ms eager / 5.287 ms graph, an 0.991× eager/graph ratio with paired 95% interval [0.979, 1.012]. The primary interval includes one, so this study does not establish a complete request improvement. Replay reduces host submissions, while capture, instantiation, metadata, sampling, vocabulary projection and synchronization still cost time. The option remains explicit so researchers can measure their own request lengths and models.

The full comparison contains 512 matched pairs / 1,024 fresh processes and 96 intervals across sixteen profiles. Ratios above one favor graph replay; the predeclared primary and all other profiles are shown.

WorkloadPrecisionBatchEager / graph request (ms)Eager / graph ratio [95% interval]
ShortFloat6411.072 / 1.0770.995 [0.983, 1.008]
ShortFloat6482.118 / 2.0651.025 [1.002, 1.033]
ShortFloat3211.046 / 1.0421.004 [0.994, 1.026]
ShortFloat3281.981 / 1.9471.017 [0.999, 1.034]
RaggedFloat6410.621 / 0.7160.867 [0.852, 0.876]
RaggedFloat6485.242 / 5.2870.991 [0.979, 1.012]
RaggedFloat3210.568 / 0.6430.885 [0.870, 0.896]
RaggedFloat3285.054 / 5.0531.000 [0.985, 1.008]
Larger prefillFloat6411.187 / 1.2150.977 [0.963, 0.985]
Larger prefillFloat6481.588 / 1.6350.971 [0.957, 0.983]
Larger prefillFloat3211.074 / 1.1090.969 [0.957, 0.987]
Larger prefillFloat3281.446 / 1.4930.968 [0.954, 0.979]
Long decodeFloat6418.075 / 7.1271.133 [1.121, 1.140]
Long decodeFloat64815.840 / 14.6561.081 [1.072, 1.094]
Long decodeFloat3218.000 / 7.0051.142 [1.132, 1.166]
Long decodeFloat32815.165 / 13.8961.091 [1.085, 1.101]

All measured stage and peak tracked numeric buffer bytes match eager execution, including transient trim overlap. Each batch eight value below applies to both modes. Workspace includes metadata. Peaks are incremental tracked device bytes above the loaded model baseline; CUDA graph/driver/library bookkeeping and process RSS are outside this accounting.

WorkloadPrecisionPrefill workspace bytesRetained workspace bytesReserved K/V bytesFixed / natural peak bytes
ShortFloat6499,10499,104122,880238,560 / 238,560
ShortFloat3249,95249,95261,440119,680 / 119,680
RaggedFloat64168,76410,868195,584391,792 / 391,792
RaggedFloat3285,05285,05297,792191,132 / 191,132
Larger prefillFloat64529,44810,868369,664926,556 / 926,556
Larger prefillFloat32266,7925,492184,832465,404 / 465,404
Long decodeFloat6499,10499,104581,632697,312 / 697,312
Long decodeFloat3249,95249,952290,816349,056 / 349,056

An untimed, separate lifetime probe runs twelve create/replay/destroy cycles per precision and confirms at most one live executable per plan, destruction of every graph, and restored tracked owner bytes. Device wide cudaMemGetInfo before/live/after observations were unchanged in these samples. Allocator granularity and unrelated activity prevent interpreting that coarse observation as zero graph memory; the opaque cost is not attributed or included in the numeric buffer table.

The report preserves exact runtime/source, executable, producer and checkpoint fingerprints, raw capture hashes, all emitted IDs/counts, memory arrays and anonymous host/toolchain details. The strict sm70 build uses CUDA 12.9.1 (nvcc 12.9.86), cuBLAS 12.9.1.4 and GCC 13.4, without fast math or lowered precision. The private toolchain receipt records the compatibility setup on Ubuntu 26.04, newer than CUDA 12.9’s qualification matrix. No driver, clocks or other jobs were changed. Point in time idle snapshots do not establish exclusive utilization.

Measured V100 complete-request eager to graph ratios with paired uncertainty and unchanged tracked workspace

Download the complete graph replay report.

Budget aware CUDA graph setup

With cuda_graph: true, aner.gen now uses the remaining output budgets to avoid creating a graph for a short active row window. No new public argument or module is required. The native generator takes the minimum remaining budget among rows that will actually append, including the current append. Zero budget rows are omitted, and EOS or exhausted rows leave the next window. EOS may end a row before its budget, so this is an upper bound rather than a guarantee of amortization.

A warmed one token shape captures only when its known window has at least 8 appends remaining, including the current append. A first successful step still warms a new active count eagerly. Consequently a fresh stable run needs at least nine one token appends to capture; its first step warms the shape and the next step still has eight appends available. A valid existing graph replays even with one append left. Longer chunks and skipped setup execute the same native eager kernels. Deliberate avoidance does not count as a resource failure and does not permanently disable later capture.

The private C++ detail append seam accepts graph_setup_steps = -1 for unknown work, preserving forced capture and existing correctness controls. Any positive int64 value is advisory, without allocation or integer narrowing; zero and values below minus one are rejected before work or state changes. Aner programs continue to use the existing generate_batch API. The fixed threshold belongs to native scheduling, rather than a model or checkpoint option.

This adds a scalar scheduling hint and no device buffer, persistent per row metadata, extra graph or cache arena. The 6CW typed scratch values plus (3C+B) uint32 metadata values, fixed row horizon KV, one executable limit and independent logits ownership remain unchanged. Dynamic masks and absolute positions are uploaded every append; finite checks and atomic cursor commits retain the same behavior. Opaque graph, runtime and library memory remain outside tracked payload accounting.

Native remaining-budget policy for warming, avoiding new setup and reusing existing graphs

Correctness and reproducible setup measurements

The executable graph example still verifies graph/eager/full-prefix IDs, empty prompts, zero budgets, independent seeds, scalar budgets and immutable model state. Its short rows also exercise the adaptive path. These seeded weights demonstrate native research mechanisms; they do not define the architecture, complexity or quality of models users can build from Aner's native operations.

sh
aner check examples/generative_cuda_graph.aner
aner run examples/generative_cuda_graph.aner --prod
aner run examples/generative_cuda_graph.aner --dev dev-cuda-graph

The final source passes 37 V100 CTests, five Compute Sanitizer runs, and 23 CPU/Metal CTests. CUDA Float64 passes 20,339,810 batched checks and Float32 passes 20,339,810; maximum scaled error is 3.324e 16 for Float64 and 1.727e 07 for Float32. Existing forced replay tests remain intact. New tests cover below/at/above the threshold, a countdown through the eager warmup boundary, unknown and largest positive int64 hints, skipped setup followed by capture, existing graph reuse on a one step tail, changed masks and active counts, invalid hint isolation, finite errors and same row retries. Native odd-width/multiple-depth and imported nonzero bias GPT 2 fixtures are included. Controlled EOS/zero-budget/budget-one cases retain an independent CPU output oracle.

Twenty actual driver probes verify the retained launch/error/lifetime behavior and 119,658 independent CPU reference cells. Separate public call traces verify all sixteen profiles in both runtimes: the twelve short/ragged/larger-prefill profiles avoid all new capture in the candidate, while all four long decode profiles still capture once and launch 62 times. These public fixtures exhaust their budgets with zero early EOS; controlled EOS coverage comes from the native tests. Both traces preserve complete IDs and immutable fingerprints. Source and executable graphs are all destroyed, with at most one live executable per plan.

Float64 and Float32 full leak memcheck and Float32 initcheck are unfiltered, including vendor kernels. Racecheck and synccheck use the native kernel namespace filter and a detected invalid write positive control; no suppression is used. The CUDA example and its precision only variant each pass eight identical checks in development and production.

The capture threshold was locked using a separate baseline only diagnostic before executing the candidate on CUDA. Buffered API timings distinguish stream capture, graph inspection, instantiation and steady replay; inclusive diagnostic timings can be perturbed by instrumentation. They are not substituted for complete request timings. Formal measurements use the unchanged shared producer, graphs enabled in both runtimes, fresh call local caches and immutable baseline origin checkpoints. Every timed call includes its own setup, ordinary work, sampling, allocation and destruction.

The separate diagnostic retains 32 matched pairs of complete caches per profile after four excluded warmup pairs, with 32 decode appends per cache. Median capture extra and steady saving below are paired host durations against ordinary appends. The rough four to six stable append break even proxy excludes initial warmup differences and executable destruction; greater profiler bookkeeping on ordinary execution also biases the apparent saving upward. These are diagnostic observations, not candidate speedup estimates.

Diagnostic profileCapture extra (µs)Steady saving (µs)Graph exec destruction (µs)
Float64, batch 183.0736.3413.81
Float64, batch 888.0527.2414.26
Float32, batch 165.5044.1813.91
Float32, batch 881.5835.1414.32

The fixed eight append admission rule was locked before candidate CUDA execution; no formal measurements were used to tune it.

The predeclared primary is short ragged Float64 batch one complete natural request time, selected from the previous short request regression before candidate execution. All sixteen workload/precision/batch profiles and the former ragged Float64 batch eight primary remain visible. Each profile retains 32 matched pairs of fresh processes, two inner trials and two excluded warmups per mode. Version order alternates and profile order rotates. All observations are retained; 5,000 whole pair bootstrap resamples use seed 20261019. The other 95 intervals are exploratory and unadjusted. Sequential controls remain in the report; a batch's completion time is not divided by its size to claim row latency.

Unknown window fixed work scans deliberately retain actual capture and replay in both runtimes. Their old exact counters, every compared logit and all stage/peak tracked memory must match; these scans are controls, not measurements of adaptive avoidance. Separate untimed public call probes verify which short windows skip setup and which long windows actually replay. Natural request rows retain all actual IDs, EOS outcomes and token counts.

The native source guide contains the exact build, matched collector and deterministic renderer commands. Preserve the same strict sm70 CUDA/cuBLAS/GCC toolchain and both source/executable fingerprints when reproducing the report.

Measured graph setup comparison

On the Tesla V100 PCIE 32GB, the predeclared short ragged Float64 batch one primary takes 0.713 ms previous / 0.638 ms adaptive, a 1.117× previous/adaptive ratio with paired 95% interval [1.103, 1.136]. The primary interval is entirely above one, establishing an improvement for this measured request profile. The former ragged Float64 batch eight primary takes 5.303 ms previous / 5.219 ms adaptive, a 1.016× previous/adaptive ratio with paired 95% interval [1.009, 1.024]. Across all sixteen natural request intervals, 10 are entirely above one, 0 entirely below one, and 6 include one. These exploratory intervals are unadjusted and do not establish a universal speedup; all long decode controls and any regressions remain in the table.

WorkloadPrecisionBatchPrevious / adaptive request (ms)Previous / adaptive ratio [95% interval]
ShortFloat6411.078 / 1.0751.002 [0.984, 1.017]
ShortFloat6482.096 / 2.0361.029 [1.010, 1.039]
ShortFloat3211.047 / 1.0600.988 [0.975, 1.002]
ShortFloat3281.965 / 1.9391.013 [1.002, 1.035]
RaggedFloat6410.713 / 0.6381.117 [1.103, 1.136]
RaggedFloat6485.303 / 5.2191.016 [1.009, 1.024]
RaggedFloat3210.653 / 0.5831.120 [1.102, 1.136]
RaggedFloat3285.106 / 5.0101.019 [1.011, 1.030]
Larger prefillFloat6411.226 / 1.1951.026 [1.021, 1.034]
Larger prefillFloat6481.642 / 1.5631.051 [1.038, 1.069]
Larger prefillFloat3211.111 / 1.0961.014 [0.999, 1.031]
Larger prefillFloat3281.517 / 1.4401.054 [1.039, 1.068]
Long decodeFloat6417.199 / 7.1491.007 [0.993, 1.013]
Long decodeFloat64814.683 / 14.5821.007 [1.000, 1.014]
Long decodeFloat3217.007 / 7.0091.000 [0.994, 1.010]
Long decodeFloat32814.014 / 13.8901.009 [0.998, 1.019]

Ratios above one favor the adaptive setup policy. The full report retains 512 matched pairs / 1,024 fresh processes and 96 intervals. All measured stage and peak tracked numeric buffer bytes must match the previous graph implementation exactly, including transient trim overlap. This preserves earlier workspace gains and does not claim zero opaque graph memory.

Each batch eight row below applies to both implementations. Workspace includes metadata; peaks are incremental device payload above the loaded model baseline.

WorkloadPrecisionPrefill workspace bytesRetained workspace bytesReserved K/V bytesFixed / natural peak bytes
ShortFloat6499,10499,104122,880238,560 / 238,560
ShortFloat3249,95249,95261,440119,680 / 119,680
RaggedFloat64168,76410,868195,584391,792 / 391,792
RaggedFloat3285,05285,05297,792191,132 / 191,132
Larger prefillFloat64529,44810,868369,664926,556 / 926,556
Larger prefillFloat32266,7925,492184,832465,404 / 465,404
Long decodeFloat6499,10499,104581,632697,312 / 697,312
Long decodeFloat3249,95249,952290,816349,056 / 349,056

The strict sm70 build uses CUDA 12.9.1 (nvcc 12.9.86), cuBLAS 12.9.1.4 and GCC 13.4, with unchanged precision and no fast math. The private toolchain receipt retains the compatibility setup on Ubuntu 26.04, newer than CUDA 12.9’s qualification matrix. No driver, clocks or other jobs were changed. Point in time idle snapshots do not prove exclusive device utilization. The report retains exact source/runtime, executable, shared producer and checkpoint fingerprints, raw capture hashes, complete IDs and stage/peak memory arrays.

Measured V100 complete-request previous to adaptive setup ratios, paired uncertainty and unchanged tracked workspace

Download the complete graph setup report.

Native CUDA sequence execution

The complete CUDA research example fits BPE using training documents, initializes a native decoder, trains, saves and resumes on CUDA, then compares cached and uncached generation. These dimensions and synthetic inputs expose the mechanisms. Researchers can compose richer supported architectures and establish their own data partitions, baselines and validation protocol.

aner
nn.configure("cuda", "Float32", "preserve")
let model = gen.decoder(codec, context: 32, width: 16,
    heads: 4, layers: 2, seed: 42, dropout: 0.1)
let ids = model.generate(prompt, max_new_tokens: 8,
    temperature: 0.0, top_k: 0, top_p: 1.0, seed: 7, use_cache: true)

The example first requires gen.device_supported("cuda", "Float32"). An unavailable CUDA device or incomplete build fails explicitly with no CPU fallback. Select "Float64" explicitly for native double precision. Native CUDA sequence operations remain grouped in the existing aner.tensor, aner.nn and aner.gen imports: embeddings, shape composition, causal and padding attention, LayerNorm, GELU, integer token loss, gradients, clipping and optimizer updates retain device placement. Broadcast gradients accumulate in batch order and indexed scatter owns each output, without floating point atomic sums.

Cached generation reserves a typed arena on the GPU and copies only committed prefixes when internal capacity grows. Fused append and causal attention read committed history and the current query prefix. A failed tail stays invisible and is overwritten before reuse. This inference mechanism does not change the differentiable training path. Float32 K/V values occupy four bytes each and Float64 values eight. The ordinary tensor, decoder, differentiation and work limits still apply; larger GPU memory does not remove those limits.

Activation and gradient arithmetic remain resident. Host derived token IDs, index metadata and deterministic dropout masks are uploaded. Finite status and reduced loss or gradient norms require small scalar transfers; sampling reads the final vocabulary row. Checkpoint saving and explicit value inspection transfer requested values separately.

Save the CUDA source, use a compatible Aner runtime with native CUDA support and run from a fresh working directory:

sh
aner check generative_cuda.aner
aner generative_cuda.aner --prod

Run the same source with --dev reports/cuda from another fresh directory. Eight executable checks require actual CUDA placement, checkpoint restoration, exact interrupted versus uninterrupted training, update count, greedy and seeded cached/uncached IDs, and unchanged inference state. Each check_... label must print true, followed by cuda_checks_passed. The two checkpoint files and stdout must match across modes on the same backend. Native tests additionally compare every logit against uncached generation and independent CPU references, verify gradients and strict future token causality, and check device buffer lifetime and invalid requests. Different backends can round differently, so this does not guarantee identical samples near every probability boundary.

CUDA cached request execution

Single request cached CUDA generation (model.generate) binds the detached decoder weights once per call and reuses five private buffers for hidden rows, normalization, QKV, attention output and feed forward values. Workspace capacity grows only when an appended chunk needs more rows. A one token decode reuses the prompt workspace. The tied vocabulary projection reads the token table through a cuBLAS transpose view instead of copying that table on each append. Effective LoRA weights are still prepared once per call.

Embedding/position addition, projection postprocessing, residual additions and activations use native CUDA kernels. Strict Float64/Float32 cuBLAS products and the causal attention reductions retain their numerical policy. All queued stages execute on the existing native stream under one append lock. Every intermediate finite check remains active, including GPT 2 gelu_new square/cube overflow; the status is read once after the final vocabulary projection. A failed normalization writes defined scratch values before later queued stages. An append commits its position only after the complete check succeeds. A failure leaves its tail invisible, and a subsequent append overwrites it.

Returned logits own a fresh buffer and remain valid across later appends and session destruction. Separate sessions own separate scratch and K/V. Model checkpoints, optimizer state, training gradients, CPU/Metal execution and use_cache: false retain their existing paths. Public generation still exposes a call local cache, with no extra module or required configuration.

The five workspaces contain 10 * workspace_capacity * width typed values; resident ID metadata adds 4 * workspace_capacity bytes. These tracked capacities are additional to K/V, weights, effective adapters and the independently owned vocabulary result. Workspace capacity can exceed the largest accepted chunk after growth or failure. Provider/driver workspaces and allocator overhead remain outside the numeric buffer accounting. This optimization does not change context or tensor/work admission limits, and memory_estimate continues to describe full sequence execution rather than a cached generation request.

Measured CUDA request optimization

The new matched before/after study uses one V100 32GB and the same benchmark source linked against the preserved original and current native runtimes. Tiny requests use an eight token prompt plus eight forced appends at width 32; short uses 32 plus 32 at width 32; long uses 128 plus 64 at width 64. All use two layers, four heads, a 259 entry byte vocabulary, new seeded weights and unchanged numerical thresholds. Both Float64 and Float32 run natively on CUDA.

Each of six profiles retains eight matched process pairs. Version order alternates, profile order rotates, and each process excludes two warmups per policy before recording two native timing pairs. Complete fixed scans include session preparation, workspace/KV allocation, prefill, finite checks, decode and release. N forced appends produce N+1 final logit rows. Model construction/placement, compilation, process startup and untimed correctness readback are outside timing. These are warmed requests, including a newly created generation session each time. They do not measure cold process latency.

WorkloadCUDA precisionOriginal cached msCurrent cached msOriginal / current, 95% interval
TinyFloat646.3021.1125.667 [5.538, 5.752]
TinyFloat326.1731.0635.808 [5.681, 5.880]
ShortFloat6422.7014.0095.663 [5.552, 5.702]
ShortFloat3222.5513.8095.921 [5.880, 6.026]
LongFloat6446.5869.7294.788 [4.740, 4.825]
LongFloat3247.0579.0985.172 [5.131, 5.207]

Session preparation increases from 7.6 to 12.0 microseconds to 13.3 to 20.3 microseconds across these profiles because the current path binds and validates its decoder plan. This cost is included in the complete request timings.

Ratios above one favor the current implementation. Separate natural generation results, including the sampler and vocabulary readback, are:

WorkloadCUDA precisionOriginal natural msCurrent natural msOriginal / current, 95% interval
TinyFloat646.3881.7973.555 [3.517, 3.654]
TinyFloat326.2491.7183.638 [3.558, 3.695]
ShortFloat6425.3507.1923.525 [3.460, 3.596]
ShortFloat3225.0046.8883.630 [3.582, 3.688]
LongFloat6452.53316.0493.273 [3.239, 3.311]
LongFloat3253.05415.3273.461 [3.395, 3.491]

Both versions return the full declared eight, 32 or 64 output tokens for every measured natural request. Every corresponding generated ID sequence matches across implementations and cache policies in these benchmark fixtures.

Tiny CUDA Float32 tracked fixed scan peak increments are 43,672 bytes originally and 20,536 currently. K/V payload is unchanged at 8,192 bytes. Short CUDA Float32 tracked fixed scan peak increments are 98,304 bytes originally and 75,928 currently. K/V payload is unchanged at 32,768 bytes. Long CUDA Float32 tracked fixed scan peak increments are 720,896 bytes originally and 526,872 currently. K/V payload is unchanged at 196,608 bytes.

These are owned numeric capacities, including the new reusable scratch and resident IDs; they exclude allocator, CUDA driver and cuBLAS workspaces and process RSS. Every measured request returns tracked buffers to baseline. Fixed scans perform no activation readback. GPU snapshots show no other compute processes before or after this capture; there was no exclusive reservation, and snapshots do not prove exclusive utilization throughout. No jobs, drivers, services or clocks were changed.

Independent cross runtime validation loads the same 14 checkpoint files for native, trained, frozen, nonzero LoRA, merged, BPE and supported GPT 2 fixtures. All 4,322,768 vocabulary logit cells pass unchanged precision thresholds; maximum scaled differences between versions are 7.459e-17 for Float64 and 3.954e-8 for Float32. All 56 same policy sampling records are identical across versions. A preexisting GPT 2 Float32 seeded fixture returns different cached and uncached samples in both versions despite close logits; that observation is retained. Sampling equality near a probability boundary is not a universal guarantee. The standard generation fixtures separately retain their expected cached/uncached IDs.

The native regression suites also verify unread resident logit ownership across appends and destruction, mixed chunk/reservation growth, causal positions, intermediate normalization and GPT 2 cubic overflow, failed tail recovery, concurrent distinct sessions, no training gradient changes, exact same backend continuation and cleanup. The published CUDA example remains the executable native training/checkpoint/generation check in both execution modes. The captured build passes 28 focused V100 regression tests and ten Compute Sanitizer runs, with 16 focused CPU/Metal tests on the separate local host. A pinned real tiny GPT2 import additionally preserves all 100,514 logits, selected gradients and greedy output across versions; its CPU Float64 control agrees within the established import tolerances.

The report also retains preparation, prefill and decode separately, along with the current cached/uncached control. Natural generation is measured separately with actual output counts and equal complete generated IDs; N outputs need at most N−1 decode appends. No successful observation is discarded. Each estimate is the median of eight process cluster medians; 95% intervals resample whole matched process pairs 5,000 times, keeping the two inner trials together. These seeded workloads measure execution, not language quality, large model scaling or a universal GPU advantage.

Matched original over current natural cached generation timing on the V100, including sampling and vocabulary readback, for eight, 32 and 64 outputs in Float64 and Float32; intervals resample matched processes with inner trials clustered.

The complete matched CUDA evidence retains all 48 outer records and 192 native timing pairs, executable/source/build hashes, exact shared harness identity, GPU snapshots, typed memory accounting and reproducible statistics. The earlier CUDA sequence study below retains its original implementation, measurements and within process uncertainty scope.

Measured CUDA cache comparison

This capture uses a Tesla V100 32GB with Release native CUDA Float64/Float32 and the portable native CPU provider on the same Intel Xeon Gold 6248 host. CPU controls use one reported native thread with BLAS disabled. The build and toolkit receipt identify GCC 13.4, CUDA 12.9, strict arithmetic and compute capability 7.0. These are two newly initialized byte decoders with vocabulary 259, two layers and four heads: short uses width 32, a 32 token prompt and 32 forced appends; long uses width 64, a 128 token prompt and 64 appends.

Each of eight profiles retains eight alternating cached/uncached paired repeats after two excluded warmups per policy, for 64 complete pairs. The table measures the complete fixed scan, including preparation, prefill, allocation, finite checks, decode and release. N appends produce N+1 next logit rows without EOS or sampling. Ratios above one favor caching.

WorkloadCUDA precisionUncached median msCached median msUncached / cached, 95% interval
ShortFloat64104.46622.8994.562 [4.419, 4.649]
ShortFloat3299.86822.4984.439 [4.371, 4.521]
LongFloat641022.26847.39621.569 [21.249, 21.807]
LongFloat32968.69847.43720.421 [20.071, 20.634]

Natural generation is measured separately, including the sampler and final vocabulary readback. All natural requests produce their complete 32 or 64 token budget; N outputs need at most N−1 decode appends. CUDA's uncached/cached natural request ratios are 3.973 and 4.038 for short Float32/Float64, and 17.938 and 18.808 for long. These observations compare cached and uncached CUDA, rather than establish a universal GPU advantage. The short cached scans favor the portable CPU controls: 5.040/6.146 ms for Float64/Float32 versus CUDA's 22.899/22.498 ms. Long cached medians are comparable: CPU 44.781/47.651 ms and CUDA 47.396/47.437 ms for Float64/Float32.

All eight numerical profiles pass, and every timed pair retains equal generated IDs. Maximum scaled cached/uncached logit errors on CUDA are 2.725e-16 for Float64 and 1.215e-7 for Float32, within the declared 1e-10 and 5e-4 thresholds. Each fixed scan reserves one arena with zero prefix copies and returns tracked buffers to baseline with no activation readback. Fixed scan CUDA K/V capacities are 65,536/32,768 bytes for short Float64/Float32 and 393,216/196,608 bytes for long. These are cache payloads; tracked peaks, model weights, provider workspaces and process memory are separate quantities.

Native verification passes 28 selected regression tests, including both explicit CUDA precisions, and ten Compute Sanitizer runs across memory, race, initialization and synchronization checks. The resident sequence suites pass 141,277 Float64 and 141,275 Float32 assertions; each CUDA cache suite passes 1,385,699. They include independent gradients, amplified Gaussian GELU tails, explicit normalization overflow rejection, chunk causality, dirty tail recovery, supported GPT 2 conventions, adapters and exact continuation. The complete CUDA example passes its eight checks with identical development/production stdout and both checkpoint files.

The complete CUDA benchmark evidence records the fixed model configurations, raw paired timings, native buffer checks, anonymous host/build identity, toolkit receipt and GPU observations. The statistical unit is a paired repeat within one process: 95% intervals describe within process repeat variability, rather than variation across processes, hardware or model families. Every observation is retained; faster timing is not a correctness condition. The shared V100 is observed before and after capture while the existing unrelated workload is preserved.

Native V100 cache measurements compare complete forced-token scans and decode phases for CUDA Float64 and Float32 with paired timing intervals; Linux CPU controls remain in the linked report.

The complete record retains every observation and timing interval. Historical M2 Max timing, Linux CPU portability and scientific calibration evidence above retain their original implementations and values.

Scientific generation in the same module

Conditional time series models use numeric data roles and explicit preprocessing; small field diffusion uses native noise schedules, learned denoising, optional velocity/Sobolev objectives, variance calibration and optional affine condition to mass constraints. Schedule aware inputs and optional EMA retain separate raw optimization and averaged inference weights. Calibration uses training data; physical and statistical diagnostics evaluate generated ensembles.

Scientific validation compares IID-calibrated and refined neural ensemble variance error while preserving physical checks on the three declared PDE systems.

The scientific example demonstrates the native training/calibration/checkpoint process. The verification evidence records the declared study, including all 1,517 criteria and its remaining tighter band variance outlier. These are bounded conditional field ensembles, not a general PDE solver or universal physical fidelity guarantee.

Current scope

The reference decoder admits context 1..512, width 2..256, heads 1..64 dividing width, layers 1..8, at most 1,000,000 parameters, batches up to 64 and runs up to 100,000 updates. Stricter tensor, matrix work and differentiation graph budgets can reject configurations within those individual maxima. Corpora are bounded, in memory snapshots; streaming/distributed language model training and arbitrary pretrained architectures are future work.

These limits describe the current runtime and built in model family. They do not define the complexity of an Aner program or promise that merely increasing dimension limits makes large model execution practical. User compositions can explore richer supported architectures while retaining explicit numerical and resource checks.

aner.llm separately connects to external inference services. A service response does not train these native weights; see language model connections.

Native pretrained models and training jobs

The matching optional development runtime adds pretrained dense Llama training: floating GGUF import, explicit supervised or causal data, full updates or LoRA, standalone exact checkpoint continuation, and merged/adapter export for native local inference. PretrainedModel is separate from the bounded LanguageModel described above. Its first qualified training profile is CPU FP32; legacy decoder accelerator support does not imply GPU pretrained training.

Bounded native training jobs provide inspectable plans, background execution and cooperative stop around the existing bounded models. The pretrained API is synchronous; runtime support depends on the installed native backends and supported model profile. Broader architectures, QLoRA and collaborative distributed training remain future work.

See the complete callable index for the native module and method name catalogue.

Continue with Native model adaptation and NF4 for this specialist contract.

Guides and references for aner.gen

Aner documentation · Reference and guides