Menu
Learn
Overview Introduction 50 Dimensions Tutorial Snippets vs Other Languages
Build
Editor Playground Compiler API
Docs
Language Spec Formats u keyword Dataframe Python AI Library Feature Status Packages What's Implemented
Platform
Server About Transpilation Web & Templates
Safebox
Why U Analysis Engine Comparison Possibilities

AI in U — Inference, Training, Optimization, and Cache Management

U compiles ML pipelines to native binaries and WebAssembly. No Python, no pip, no CUDA toolkit. One language for data loading, model inference, training, adaptation, and deployment — with a compiler that proves what the resulting binary can and cannot do. The Safebox runner compiles to a 34 KB static binary — pure executable code (C compiled with -O2), statically linked against libc and libm.

The ML runtime is 22,700+ lines of C across 45 headers in runtime/ml/, plus multimodal encoders and diffusion in runtime/multimodal/. Everything described below is implemented and tested — 69 tests pass under ASan+UBSan with zero leaks.

U source  →  u2c (Python compiler)  →  C  →  gcc  →  native binary + .u.meta
                                       ↑
                              runtime/*.h  (50k lines, 54 headers)
                              runtime/ml/*.h (22.7k lines, 45 files)

The .u.meta section of the binary records the capability surface the compiler proved. A runner compiled with no Network capability provably cannot exfiltrate a prompt — the capability does not exist in the emitted code, so there is no sandbox to escape. Neither vLLM nor llama.cpp can make that claim.

How It Fits Together

U is a language that transpiles to C. The ML work lives in the C runtime as a set of single-purpose headers that U code calls through import. There is no separate ML framework to install: the tensor ops, the transformer forward pass, the loaders, and the caches are part of the runtime the compiler links against.

There are two inference paths. The R64 path (UTensor, double) carries LoRA, steering vectors, soft prompts, a Q8 KV cache, KV grafting and ONNX weight extraction. The F32 path (UTensorF32, quantized matmul) carries all the performance work — SIMD dispatch, flash attention, the thread pool, batch prefill, the prefix cache, the diffusion caches. Most remaining work is porting between them rather than writing anything new.

The u Keyword — AI Writes Code, the Compiler Verifies It

The u prefix on a function means the LLM generates the body. The human writes the signature, types, modifiers and intent comments. The compiler sends that context to a model, receives a body, type-checks it against the declared signature and modifiers, and compiles it.

/// Calculate the nth Fibonacci number recursively.
u f fibonacci(nth: I) -> I

f main() -> I
    result = fibonacci(10)
    r => result

u2c --ai=anthropic generates the body, caches it in .gen.u, injects it, type-checks, compiles, and the binary prints 55. Verified.

Remove the u and the generated body inlines into your source, frozen. The AI never touches it again. The point is that a generated body still has to satisfy the capability modifiers the human declared — an LLM cannot quietly add a network call to a function declared -C.

What U Can Do Today

Load any major model format

FormatStatusNotes
GGUF — F32, F16, BF16verifiedConformance-tested against the official gguf package
GGUF — Q4_0, Q8_0verifiedFixed 2026-09-30; conformance-verified
GGUF — K-quants (Q4_K, Q6_K)verifiedLoad and match official reference vectors exactly
Safetensors — F16/BF16/F32/F64implementedAuto-converts to double
ONNX — weight extractionimplementedHand-written protobuf initializer reader
BitNet ternaryimplementedfloat → 2-bit ternary, add/sub matmul
import Safetensors
import GGUF

// HuggingFace models (safetensors):
weights = Safetensors.load("model.safetensors")
ww = Safetensors.get(weights, "model.layers.0.self_attn.q_proj.weight")

// llama.cpp models (GGUF):
model = GGUF.parse(buffer)
ww = GGUF.get(model, "blk.0.attn_q.weight")
arch = GGUF.get_str(model, "general.architecture")  // "llama"

Run transformer inference (Llama / Nemotron / Mistral / Qwen / Gemma 2)

Llama-class is tested. The forward pass: embedding → per-layer (RMSNorm → Q/K/V → RoPE with optional Linear/NTK/YaRN scaling → GQA attention with causal mask or sliding window → KV cache → output projection → residual → RMSNorm → SwiGLU FFN → residual) → final norm → LM head → composable sampler chain.

import NN
import Safetensors
import Tokenizer
import KVCache

f main()
    sf = Safetensors.load("nemotron-nano-4b.safetensors")
    model = llama_load(sf, 32, 32, 3072, 9216, 131072)
    tok = Tokenizer.load(vocab_text)
    tokens = Tokenizer.encode(tok, "What is the capital of France?")
    output = llama_generate(model, tokens, tokens.length, 128, 0.7, 0.9)
    print(Tokenizer.decode(tok, output))

Train models (XOR — verified, trains to 4/4 accuracy)

import NN
import Tensor
import Autograd

f main()
    xx = Tensor.from_data([0,0, 0,1, 1,0, 1,1], [4, 2])
    yy = Tensor.from_data([0, 1, 1, 0], [4, 1])
    w1 = Tensor.he_normal([8, 2])
    b1 = Tensor.zeros([8])
    w2 = Tensor.he_normal([1, 8])
    b2 = Tensor.zeros([1])
    adam = NN.adam_new(4, 0.01, 0.9, 0.999, 1e-8, 0.0)
    [0..2000].on(epoch => (
        hidden = Tensor.relu(NN.linear(xx, w1, b1))
        pred = Tensor.sigmoid(NN.linear(hidden, w2, b2))
        loss = NN.mse_loss(pred, yy)
    ))
    // Result: [0.016, 0.992, 0.993, 0.007] — 4/4 correct

Flash Attention

FlashAttention-2: tiled QKV in SRAM-sized blocks, online softmax, no materialisation of the full attention matrix.

// Decode — single new token against the full KV cache:
u_flash_attention_decode(Q, K, V, n_heads, head_dim, seq_len, out)
// Prefill — multiple query tokens with a causal mask:
u_flash_attention_prefill(Q, K, V, n_heads, head_dim, n_queries, kv_len, out)

Tile size is tuned for L1 cache. Prefill is O(n·d) memory instead of O(n²).

SIMD-accelerated inference

The SIMD layer (u_simd.h, 695 lines) dispatches at compile time to AVX-512, AVX2, or ARM NEON. Quantized matmul is SIMD-accelerated — Q4_0, Q8_0, Q4_K, Q6_K matrix multiplications directly on compressed blocks, no dequantisation pass:

// A [4096,4096] weight matrix:
// F32 = 64 MB    Q8_0 = 18 MB (3.6x)    Q4_0 = 9 MB (7.1x)
// Q4_K = 9.2 MB  Q6_K = 13.4 MB
// Results match the dequant-then-multiply path exactly.

GPU dispatch — WebGPU / WGSL

U's +V modifier tags data for GPU residency. The runtime emits WGSL compute shaders for WebGPU, which runs on any GPU (not just NVIDIA). Nine kernels ship today:

KernelWhat it does
u_gpu_linear_f32Dense linear layer (f32)
u_gpu_linear_q8_0Quantised linear (Q8_0 weights)
u_gpu_linear_q4_0Quantised linear (Q4_0 weights)
u_gpu_matmul16×16 tiled matrix multiply
u_gpu_rmsnormRMS normalisation
u_gpu_softmax_rowsRow-wise softmax
u_gpu_ropeRotary position embeddings
u_gpu_silu_mulSiLU activation × gate
u_gpu_attn_decodeSingle-query attention decode

Distributed inference

Tensor parallelism (u_tp.h). Column-parallel and row-parallel matmul sharding across GPUs with ring all-reduce. Supports 2–8 way parallelism.

Pipeline parallelism (u_pipeline.h). Assigns ranges of transformer layers to different devices with micro-batching. The pipeline bubble is (P-1)/M of total compute for P stages and M micro-batches.

Placement strategy (u_placement.h). Memory-proportional, latency-optimized, and custom placement maps.

Transport (u_transport.h, u_transport_rdma.h). TCP sockets for commodity networking, RDMA for InfiniBand/RoCE with zero-copy transfers.

Composable sampler chain

u_sampler.h implements the full sampling pipeline used by SOTA runners, in fixed order:

  1. Repetition penalty (CTRL-style, multiplicative)
  2. Frequency penalty (OpenAI-style): subtracts penalty × count
  3. Presence penalty (OpenAI-style): flat subtraction
  4. Temperature: scales logits by 1/T
  5. Softmax: converts to probabilities
  6. Top-k: keeps only the k highest-probability tokens
  7. Top-p / nucleus: smallest set with cumulative probability ≥ p
  8. Min-p: discards tokens below min_p × max_probability
  9. Weighted random sample from survivors

Temperature ≤ 0 short-circuits to greedy argmax. Ring-buffer history (default 256) tracks tokens for penalty computation.

RoPE scaling — extended context

Three methods for extending context length beyond training, all verified:

Linear scaling. Divides all RoPE frequencies by a factor. Effective for 2–4× extensions.

NTK-aware scaling. Scales base theta by factor^(d/(d-2)), preserving high-frequency position information while extending low-frequency capacity.

YaRN. Dimension-dependent blending: low-frequency dimensions get full NTK scaling, high-frequency stay at original scale. Best quality for 8–32× extensions.

Sliding window attention

u_swa.h implements sliding window attention for models like Mistral and Gemma 2/3. O(n·W) instead of O(n²) — linear in sequence length. Per-layer configuration supports Gemma 2-style alternation between windowed and full-attention layers. Verified with 6 tests.

Grammar-constrained decoding

u_grammar.h implements GBNF-style grammar enforcement that guarantees model output conforms to a user-supplied grammar — the mechanism behind structured output (guaranteed valid JSON, function-call schemas, or any context-free grammar).

How it works. A grammar is a set of rules composed of elements: CHAR, CHAR_RANGE, CHAR_ALT, CHAR_NOT (character matching), RULE_REF (call another rule), and END (terminate). The grammar state is a set of stacks — each stack is a chain of frames (rule, element_index). Multiple stacks form an NFA-like set of possible parse positions.

At each decoding step, u_grammar_apply_mask() iterates the vocabulary: tokens that would leave the grammar in an invalid state get their logits zeroed. Grammar masking runs before the sampler chain, composing cleanly with all sampling strategies.

Built-in grammars. u_grammar_json() returns a 17-rule grammar covering all of JSON. u_grammar_json_object() and u_grammar_json_array() constrain to object-only or array-only roots.

Verified with 11 tests under ASan+UBSan. Zero memory leaks.

Adapt models without retraining

LoRA hot-swap — load a 10–50 MB adapter, apply per-request, no model reload:

import LoRA
import Safetensors

adapter = Safetensors.load("formal-voice-lora.safetensors")
lora = LoRA.load(adapter, 32, 8, 16.0)
logits = llama_forward_lora(tokens, n_tok, model, kv, lora)
// Switch voice by swapping adapter — same base model

Steering vectors — shift behavior with a ~1 MB vector, adjustable strength:

import Steering
steer = Steering.load(sf, "formal_direction", 2.0, 15)
// Adds a direction to hidden states at layer 15

Soft prompts — per-user tuning at ~1 KB:

soft = SoftPrompt.load(sf, "user_alice_prefix")
combined = SoftPrompt.apply(token_embeddings, soft)
// Prepends 4 learned embedding vectors

KV cache grafting — document memory without re-reading:

// Process a 50-page document once:
doc_kv = process_document(model, document_tokens)
KVCache.save(doc_kv, "/srv/kv-caches/doc-123.bin")

// Every future question about this document:
conv_kv = KVCache.new(32, 8192, 4096)
KVCache.graft(conv_kv, doc_kv, 0, 0, doc_kv.cur_len)
logits = llama_forward(question_tokens, n, model, conv_kv)
// Model "remembers" the document — no re-reading, no RAG chunking

BitNet — 10x cheaper inference

import BitNet

bw = BitNet.quantize(weight)  // float → 2-bit ternary (-1, 0, +1)
result = BitNet.matmul(input, bw)  // add/sub only, no float multiply
// 4B model: 8 GB at F16 → 1 GB at BitNet. CPU-viable.

Speculative decoding

Draft-then-verify with configurable draft length and acceptance threshold. A small draft model proposes tokens; the large model verifies them in a single forward pass, accepting correct ones and resampling from the first mismatch.

MoE routing

Top-k expert gating with optional expert parallelism. Supports Mixtral-style MoE architectures where only 2 of 8 experts activate per token.

Diffusion models

ComponentStatusNotes
Conv2d / Conv2d transposeimplemented2D convolution with stride/padding
GroupNorm / LayerNormimplementedNormalisation layers
GELU / SiLUimplementedActivations
Multi-head + cross attentionverifiedTiled online softmax
VAE decoderimplementedResidual blocks + upsample stages
Vision encoder / ViTimplementedPatch embed, 2D pos embed, blocks
Flash attentionverifiedOnline softmax tiled over KV
Diffusion cacheverifiedCross-attn K/V, conditioning, trajectory

Multimodal — Vision, Audio

Vision (ViT encoder). Patch embedding, learnable position embeddings, bidirectional self-attention, CLS or mean pooling. Cross-attention module (u_cross_attn.h, 493 lines) with tiled online softmax.

Audio (Whisper-style encoder). STFT → mel filterbank → log-mel spectrogram → Conv1d → sinusoidal position embeddings → transformer encoder. Whisper weights load via the multimodal GGUF loader.

Server-side inference vs. client-side WASM

Server-side — the u-runner binary loads the model, listens on a Unix socket, speaks the Safebox Protocol.LLM.Local wire format:

// Server: load model, serve inference
./u-runner model.safetensors /run/safebox/services/u-llm.sock

// Client (Safebots/LLM.js, unchanged):
resp = await safebots.llm({
    model: 'local/nemotron-nano',
    system: systemPrompt,
    userInput: userMessage
})

Client-side WASM (for small models): U compiles to WebAssembly. A classifier, sentiment model, or embedding model can run in the browser with zero server roundtrip.

Performance, Measured

All numbers from a 2-core Xeon at ~5.2 GB/s memory bandwidth. The ratios transfer to other hardware.

MeasurementValue
7B Q4_0 decode, end-to-end1.20 tok/s
Memory bandwidth achieved86%
Q4_0 matmul (4096×4096)5.81 GB/s, 20.6 GFLOP/s
Q8_0 matmul (4096×4096)11.7 GB/s
Prefill, batch 2560.94 ms/token
Flash attention decode, 512 ctx0.91 ms/layer
Model load RSS, 59M-param Q4_034 MB

Decode at 86% of memory bandwidth means the kernel is close to done. Every remaining speedup is reading fewer bytes (better quantization) or getting more tokens per byte read (speculative decoding, continuous batching).

U vs. vLLM vs. llama.cpp

UvLLMllama.cpp
Weight formatsGGUF + safetensors + ONNX + BitNetsafetensorsGGUF
QuantizationQ4_0, Q8_0, K-quants, BitNetAWQ, GPTQ, FP8Q2–Q8, IQ, BitNet
GPUWGSL shaders, tensor parallelismCUDA, ROCmCUDA, Metal, Vulkan
ParallelismTensor + pipeline, ring all-reduceTensor parallelismTensor (limited)
Multi-userfork() CoW + session pool + continuous batchingInternal batchingServer mode
KV cachePage-level CoW, paged, ZFS-backed, persistentPagedAttention, volatileIn-process, volatile
Prefix reuseRadix tree, exact, automaticPagedAttention + prefix cachingPartial
Speculative decodeDraft-then-verifyYesYes
MoETop-k gating, expert parallelismYesYes
RoPE scalingLinear, NTK, YaRNYesYes
SWAPer-layer + Gemma 2 alternationYesYes
Sampler chainRep/freq/pres → temp → top-k/p → min-pYesYes
Grammar / structured outputGBNF-style + built-in JSONYes (outlines)Yes (GBNF)
Diffusion cachingCross-attn hoist + conditioning + trajectoryNoneNone
AdaptersLoRA hot-swap per requestLoRA, restart requiredLoRA, restart required
TrainingAutograd + Adam built-inNoNo
Capability proof.u.meta, compiler-provenNoneNone
WASMCompiles to WASMNoYes, limited

Where U is better

Provably safe inference. The binary's .u.meta section proves its capability surface. No o { Network } = the binary provably cannot exfiltrate prompts.

Persistent KV caches. vLLM and llama.cpp lose all KV caches on restart. U saves them to ZFS. System prompts, document memory, conversation state — all survive reboots.

Per-request adapter swap. Load a different LoRA adapter for each user without restarting the model.

Exact prefix reuse. Bit-identical guarantee: serving from cache produces the same logits as a cold run. Tested with max|diff| = 0.000e+00.

Diffusion-side caching. Cross-attention hoisting, conditioning cache, trajectory resume — neither vLLM nor llama.cpp attempt any of these.

Where U trades off

GPU throughput. vLLM's PagedAttention and continuous batching on CUDA are highly optimized for multi-tenant GPU serving. U's WGSL shaders run on any GPU but don't yet match CUDA-tuned kernels on peak throughput.

Architecture coverage. Llama-class (Llama, Nemotron, Mistral, Qwen, Gemma 2) is tested. Other architectures need an architecture-specific forward loop.

Large-batch prefill. 5–9% behind ggml at large batch. Level at batch 8, ahead at batch 1 (1.45×).

The honest summary

U is the right choice for CPU inference on attested hardware where provable safety, persistent and branchable KV caches, exact prefix reuse, per-request adapters and zero-dependency deployment matter more than peak GPU throughput. The engine now matches SOTA on all core inference features — speculative decoding, MoE, tensor/pipeline parallelism, paged KV, RoPE scaling, sliding window attention, grammar-constrained decoding, and a composable sampler chain. The main remaining gap is GPU kernel maturity.

Cache Management

The governing idea: reuse must be exact. Every claim is tested against a cold path rather than against stored expectations.

Radix-tree prefix cache — the killer feature

The prefix cache (u_prefix_cache.h, 848 lines) indexes cached KV state by the tokens themselves. A compressed-edge radix tree where a 2,000-token system prompt is one edge:

// 1,000 users with the same system prompt:
//
//   root
//    └── [system prompt: 2,000 tokens] ──┬── [user A turn 1] ── ...
//                                        ├── [user B turn 1] ── ...
//                                        └── [user C turn 1] ── ...
//
// The system prompt's KV is stored ONCE. Each user adds only their
// unique suffix. 1,000 × 2,000 tokens of redundant KV → 0.

At 7B dimensions a hit costs 0.31 ms/token of memcpy against 428 ms/token to recompute — 1388× cheaper. Time to first token on turn 10 drops 34×.

Page-level copy-on-write

The CoW cache (u_kv_cow.h) divides KV state into refcounted 64-token pages. Forking a session bumps refcounts — no data copied. Writes trigger copy-on-write at the page level.

UKVCacheCow* child = u_kv_cow_snapshot(parent);
// Cost: bump refcounts on existing pages. No data copied.
// The child diverges only when it appends new tokens.

fork() and ZFS — two tiers

TierMechanismThaw latencySurvives restartIsolation
ThreadUserspace CoW pages (u_kv_cow.h)~0.01 msNoLogical (in-process)
Forkfork() — OS page-table CoW~0.1 msNoProcess-level (OS-enforced)
ZFSSnapshot → mmap~1 msYesAny process on the same ZFS pool

Int8 KV quantization — 3.56x memory reduction

The Q8 KV cache (u_kv_q8.h) quantises cached keys and values to int8, reducing per-value storage from 4 bytes to 1.125 bytes:

u_inference_ctx_enable_kv_q8(ctx)
// From this point, new KV entries are stored at int8.
// Attention code sees dequantised f32, so semantics are unchanged.

Diffusion caching

CachedWhat it avoidsSaving at 50 steps
Text-encoder outputRe-encoding the prompt every step49 full encoder passes (98%)
Cross-attention K/VRe-projecting K/V per layer per step49 × n_layers projection passes
Timestep embeddingsRecomputing sinusoidal embeddingsPrecomputed once for the whole schedule

Trajectory resume caches latents at each denoising step. Exact resume continues an interrupted sample. Approximate resume ("same image, adjusted prompt") starts from a cached intermediate at 30–50% of the schedule — 43% of steps saved.

What you can build with this

What this means in practice

ScenarioWithout U's cachingWith U's caching
1,000 users, same system prompt (2K tokens), 7B~2 TB KV~2 GB shared + per-user deltas
Model weights, 50 sessions, 4B Q4_0~125 GB if separate copies~2.5 GB — one mmap'd region
Cold start after rebootRe-prefill (~50 ms/user)mmap from ZFS (~1 ms) + fork (~0.1 ms/user)
Branch a conversationDeep-copy entire KVRefcount bump or ZFS clone
50-step diffusion, same prompt50 encoder passes1 encoder pass + 49 cached (98%)

Optimizations — Full List

OptimizationStatus
SIMD dispatch (AVX2, AVX-512, NEON, scalar)verified
Quantized in-place matmulverified
Flash attention (online softmax, 64-token tiles)verified
Thread pool (persistent pthreads on barrier)implemented
Batch prefillverified
Fused SiLU×gateimplemented
Precomputed RoPE frequenciesimplemented
Zero-alloc decode (11 scratch buffers)implemented
O(n log n) top-p samplingimplemented
Lazy quantized loadingverified
WGSL compute shadersimplemented
GPU dispatch with occupancy-based sizingimplemented
Tensor parallelism (ring all-reduce)implemented
Pipeline parallelism (micro-batching)implemented
Paged KV cache (256-token pages, CoW fork)implemented
Speculative decodingimplemented
MoE routing (top-k gating)implemented
Fused operations (norm+matmul, attn+softmax+V, etc.)implemented
Computation graph (topo sort, fusion, memory planning)implemented
Continuous batchingimplemented
RoPE scaling (Linear, NTK, YaRN)verified
Sliding window attentionverified
Composable sampler chainverified
Grammar-constrained decoding (GBNF + JSON)implemented

Cache Breakpoint Protocol

U's runner implements a cache breakpoint protocol compatible with Anthropic's API and the Safebots/LLM.js five-block prompt discipline, with unlimited breakpoints where Anthropic's API allows four.

ProviderCache mechanismU equivalent
Anthropiccache_control on content blocks, max 4 breakpointsUnlimited breakpoints, per-bot tenant isolation, LRU eviction
OpenAIAutomatic prefix detection (no explicit control)Explicit prefix hashes — deterministic cache hits
U runnerKV cache snapshots on ZFS, fork()-shared across sessionsSurvives restarts, branchable, graftable

Remaining Gaps (Nice-to-Have, Not Blockers)

  1. Mirostat sampling. Perplexity-targeting adaptive temperature (v1 and v2). Present in llama.cpp.
  2. Logit bias. Per-token logit bias maps passed per-request.
  3. Embedding extraction. Return hidden states instead of logits for RAG pipelines.
  4. Beam search. TensorRT-LLM supports it; U has greedy and stochastic only.
  5. Classifier-free guidance for LLMs. U has CFG for diffusion but not for LLM inference.

None of these are critical. The engine matches SOTA on all core inference features.

Building and Testing

# the runner
gcc -O2 -DU_ML -I runtime -I runtime/ml -o u-runner runtime/ml/u_safebox_runner.c \
    -lm -lpthread -Wno-unused-function
./u-runner --test                       # 12/12 kernel tests

# the full ML suite — unit, GGUF conformance, end-to-end
./run_ml_tests.sh                       # 18/18 across AVX2, scalar, NEON

# gap tests — sampler, RoPE, SWA, grammar (69 tests under ASan+UBSan)
gcc -I runtime/ml -o test_gaps tests/test_gaps.c -lm \
    -Wno-unused-function -fsanitize=address,undefined
./test_gaps                             # 69/69 pass

Deployment

# Build the runner:
gcc -O2 -o u-runner u_safebox_runner.c -I runtime/ -lm
# Result: 34 KB binary

# Deploy alongside existing runners:
cp u-runner /opt/safebox/runners/
./u-runner /srv/safebox/models/<hash>/model.gguf \
           /run/safebox/services/u-llm.sock

# Speaks the same protocol as vLLM:
# Safebots/LLM.js → Protocol.LLM.Local → u-runner
# No code changes in Safebots or Safebox.

Last verified 2026-10-25.