XU XUv0.16.0
--- ---

AI development and local inference

Build pure-Xu AI systems end-to-end without external C/C++ inference bindings: low-precision #tensor storage & numerical primitives, compiler MIR SIMD tensor fusion (ARM64 NEON/SDOT & x86-64 SSE2/SSSE3), modularized multi-threaded examples/llm_engine (GGUF / SafeTensors / VLM / GBNF / LoRA / DPO / GRPO / RLVR / Distill + OpenAI/Anthropic/Ollama serving), multi-backend GPU compute (gpu / llm_metal / metal / cuda_native / vulkan_native), and 50 official pure-Xu packages for LLM clients, gateways, Agent/MCP/A2A, GraphRAG, guardrails, and evaluation.

4-Layer Pure-Xu AI Architecture
From low-precision primitives and compiler MIR fusion kernels to multi-threaded local serving and multi-backend GPU
1
#tensor Storage & Primitives
F16 / BF16 / FP8, GGML Q4_0–Q8_K blocks, strided TensorView, and 47 pure-Xu inference & backward training ops
2
Compiler MIR Tensor Fusion
--tensor-fusion lowers pure-Xu loops directly to ARM64 NEON/SDOT & x86-64 SSE2/SSSE3 kernels (including K-quant SIMD)
3
llm_engine Multi-Threaded Engine & serve
--threads N CPU inference, VLM (mmproj.gguf / SafeTensors), GBNF/Schema, LoRA/RLVR training & OpenAI/Anthropic/Ollama HTTP serving
4
Multi-Backend GPU & packages v1.17.0
Unified gpu / llm_metal / cuda_native / vulkan_native plus openai, gateway, mcp, a2a, agent, rag, guardrails, and eval

Build and run the local LLM engine (llm_engine)

examples/llm_engine/main.xu modularizes model loaders, vision projectors, GBNF grammars, and quantization into pure-stdlib subpackages (models, vision, gbnf, quantize) while preserving all MIR tensor-fusion kernels in main.xu. Since Xu v0.14.3+ embeds Mach-O LC_CODE_SIGNATURE ad-hoc signing directly on Apple Silicon builds, no manual codesign step is required.

1. Model Formats, Architectures & Quantization

AreaSupported ScopeKey Capabilities
GGUF v2/v3F32, F16, BF16, FP8 E4M3, Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, Q2_K, Q3_K, Q4_K, Q5_K, Q6_K, Q4_K_M, Q5_K_MStreaming p4k4 packing, K-quant SIMD kernels with --q8k-act integer activation dots, and zero-copy #tensor layout
HuggingFace / SafeTensorsSingle model.safetensors or sharded model.safetensors.index.json + config.json + tokenizer.jsonF32 / F16 / BF16 / F8_E4M3 loading plus offline quantize export to GGUF
Model Families & AttentionLlama / Qwen / Gemma-2 / Mistral / DeepSeek-V2/V3/R1 MLA / MoE / Mamba SSM / Hybrid Attention+SSMYaRN NTK-by-parts RoPE, ChatML/Llama-3/Gemma/Mistral templates, multi-turn tool formatting, and paged KV caches

2. Inference, VLM & Constrained Decoding

SubsystemKey Flags / ComponentsNotes
Multi-threaded CPU--threads <N>, --kv-dtype <f32|f16|bf16|fp8_*>Parallelizes CPU GEMV/GEMM execution over Xu's M:N scheduler with FP16/BF16/FP8 paged KV compression
Multimodal VLM--mmproj <path>, --image <path|url|data_uri|rgb:...>Supports both native mmproj.gguf (F32/F16/BF16) and SafeTensors ViT+MLP projectors, PNG/JPEG/PPM/BMP decoding, bilinear resize & inline <image>
GBNF & JSON Schema--grammar, --json-schema, --gbnf-max-branches <N>VocabIndex Trie + GbnfMaskCache acceleration; JSON Schema supports $ref/$defs, allOf, regex pattern & additionalProperties: false
Speculative Decoding--draft <model>, --draft-k <N>Lossless target verification with exact KV-cache rollback across greedy and stochastic sampling

3. Fine-Tuning, Alignment & Model Utilities

SubcommandKey FlagsCapabilities
models / inspect / perplexitypull hf://..., list, rm, --models-dir, --strideLocal HuggingFace model cache management, tensor/KV-footprint diagnostics, and sliding-window perplexity evaluation
quantize / merge-lora--type q4_0|q8_0|q4_k|q5_k|q6_k|q4_k_m|q5_k_mOffline SafeTensors/GGUF requantization and PEFT LoRA merging (q/k/v/o/w1/w2/w3/lm_head) in F32/F16/BF16
train-lora--dataset, --grad-accum, --warmup-steps, --lr-schedule cosine, --save-ckpt / --resume-ckptPure-Xu CPU f32 SFT fine-tuning with assistant-only loss masking, grad clipping, and AdamW checkpoints
train-dpo / train-grpo / train-rlvr / train-distill--dpo-beta, --clip-eps, --kl-beta, --verifier, --group-size, --teacherPreference alignment, clipped GRPO, online verifiable-reward rollouts (contains|exact|json|math), and logit distillation

4. Serving Endpoints (serve)

API FamilyEndpointsFeatures
OpenAI-compatiblePOST /v1/completions, /v1/chat/completions, /v1/responses, /v1/embeddings, GET /v1/modelsContinuous batching (--max-slots N), Bearer --api-key, SSE streaming, delta.tool_calls, <think> reasoning_content, and HTTP response_format/grammar
Anthropic & OllamaPOST /v1/messages, GET /api/tags, POST /api/generate, POST /api/chatClaude Messages API compatibility plus Ollama sync & application/x-ndjson streaming
Health & TelemetryGET /health, GET /metricsUnauthenticated health check and Prometheus latency/KV/throughput metrics
./bin/xu build --tensor-fusion --tensor-fast-math examples/llm_engine/main.xu -o llm_engine
# Xu v0.14.3+ embeds Mach-O ad-hoc signatures automatically on Apple Silicon

# Manage cached local models, inspect architecture & KV footprint, and compute perplexity
./llm_engine models pull hf://Qwen/Qwen2.5-0.5B-Instruct-GGUF/qwen2.5-0.5b-instruct-q4_k_m.gguf qwen.gguf
./llm_engine inspect qwen.gguf
./llm_engine perplexity qwen.gguf "ids:1,2,3,4,5,6" --stride 2

# Multi-threaded CPU inference (--threads), GBNF/JSON Schema, VLM (mmproj.gguf), and speculative decode
./llm_engine generate qwen.gguf "Hi Paris" 64 700 40 --threads 4 --kv-dtype f16 --top-p 900 --min-p 50 --seed 42
./llm_engine generate qwen.gguf "Reply JSON" 64 0 40 --json-schema '{"type":"object","properties":{"ok":{"type":"boolean"}},"required":["ok"]}'
./llm_engine generate vlm.gguf "Describe <image>" 32 0 40 --mmproj ./mmproj.gguf --image ./photo.png --threads 4
./llm_engine generate qwen.gguf "Hi Paris" 64 0 40 --lora ./lora_adapter --draft ./draft.gguf --draft-k 4

# Pure-Xu SFT LoRA (with checkpoints), offline merge, and offline quantize
./llm_engine train-lora model.safetensors ./out_lora --dataset sft.jsonl --lora-rank 4 --steps 20 --lr 0.05 --save-ckpt sft.ckpt.safetensors
./llm_engine merge-lora model.safetensors ./out_lora ./merged_f32.safetensors
./llm_engine quantize ./merged_f32.safetensors ./merged_q4k.gguf --type q4_k

# Start HTTP server (/health, /metrics, OpenAI /v1/*, Anthropic /v1/messages, Ollama /api/*)
./llm_engine serve qwen.gguf 127.0.0.1:8080 --threads 4 --kv-dtype bf16 --max-slots 4 --api-key secret

Common CLI flags across modes:

#tensor module & numerical primitives

The standard library module #tensor provides safe, pure-Xu low-precision scalar types, strided views, GGML block decoders, and 47 canonical compute & training primitives in src/tensor/ops.xu:

LayerPublic APIsPurpose
Scalar encodings F16, BF16, Fp8E4M3Fn, Fp8E5M2, Fp8E4M3Fnuz, Fp8E5M2Fnuz, DType, dequant_f16_to_f32, dequant_bf16_to_f32 Bit-exact IEEE/OCP FP16, BF16, and FP8 conversions, bulk half/bf16 dequantization, & runtime dtype_named parsing
Strided views & blocks TensorView (reshape, permute, read_f32_bytes, write_f32_bytes), Q4Block, Q5Block, Q8Block, Q4KBlock, Q5KBlock, Q6KBlock, Q8_K_BYTES, dot_*_bytes_f32, dot_*_row_f32, quantize_q8_k_row, dot_q4_k_q8_k_row_f32, dot_q5_k_q8_k_row_f32, dot_q6_k_q8_k_row_f32 Zero-copy strided reshape/permute & byte-backed views, GGML 32/256-value decoding, integer Q8_K K-quant dot products, and zero-alloc row dot products
Vector & retrieval ops dot_f32, axpy_f32, vadd_f32, vsub_f32, vmul_f32, vscale_f32, l2_normalize_f32, cosine_similarity_f32, topk_cosine_f32, argmax_f32, topk_f32 Offsetted dot products, FMA accumulation, Hadamard add/sub/mul ops, L2 normalization, cosine similarity, Top-K cosine RAG search, and Top-K/argmax
Transformer, SSM, Vision & alignment ops silu_f32, gelu_f32, rmsnorm_f32, add_rmsnorm_f32, layernorm_f32, softmax_f32, log_softmax_f32, swiglu_f32, geglu_f32, moe_router_f32, conv1d_causal_step_f32, ssm_scan_step_f32, linear_attn_step_f32, conv2d_patch_embed_f32, mha_sdpa_f32, avg_pool2d_f32, rope_f32, rope_interleaved_f32, rope_yarn_f32, matvec_f32, matmul_f32, quantize_q8_0, quantize_q5_0_row, quantize_q4_0_row, cross_entropy_grad_f32, adamw_step_f32, lora_add_f32, lora_backward_f32, rmsnorm_backward_f32, layernorm_backward_f32, swiglu_backward_f32, softmax_backward_f32, grad_clip_norm_f32, kl_div_grad_f32, dpo_loss_grad_f32, ppo_clip_grad_f32, grpo_advantages_f32 Activations, SwiGLU/GeGLU, Mamba/RWKV causal conv1d/ssm_scan/linear_attn steps, ViT/SigLIP vision ops, fused add_rmsnorm_f32, LayerNorm, Softmax/LogSoftmax, moe_router_f32, NeoX/interleaved/YaRN RoPE, GEMV/GEMM, quantization, and LoRA/AdamW/DPO/PPO/GRPO/KL training backward ops
@main
#tensor

fn run_block(w &[]f32, x &[]f32) []f32 {
    n := x.len
    $normed := []f32{}
    $out := []f32{}
    for _ in 0:n {
        normed.push(f32(0))
        out.push(f32(0))
    }
    tensor.rmsnorm_f32($&normed, x, w, n, 0.00001)
    tensor.vscale_f32($&normed, f32(0.5), n)
    tensor.softmax_f32($&normed, n, f32(1))
    tensor.vmul_f32($&out, &normed, x, n)
    << out
}

Compiler options & MIR tensor fusion

When building with --tensor-fusion (or XU_TENSOR_FUSION=1), the compiler's MIR tensor-lowering pass pattern-matches idiomatic pure-Xu numerical loops (including the primitives in #tensor and custom user kernels) and lowers them directly into hand-tuned ARM64 NEON / SDOT and x86-64 SSE2 / SSSE3 runtime kernels (including v0.14.3 K-quant SIMD kernels), while keeping the frozen runtime ABI unchanged:

Kernel familyMIR runtime symbol(s)Hardware instructions
Vector ops __xu_tensor_dot_f32, __xu_tensor_axpy_f32, __xu_tensor_vadd_inplace_f32, __xu_tensor_vsub_f32, __xu_tensor_vmul_f32 ARM64 NEON fmul.4s/fmla.4s/fsub.4s; x64 SSE2 mulps/addps/subps
Norms & activation __xu_tensor_add_sqsum_f32, __xu_tensor_norm_f32, __xu_tensor_swiglu_f32, __xu_tensor_softmax_scaled_f32 Vectorized variance/exp reductions across hidden dimensions
Dense & quantized GEMV/GEMM __xu_tensor_gemv4_f32, __xu_tensor_gemm4x4_f32, __xu_tensor_gemv4_q4_0_p4k4_signed_f16_q8_0_f32, __xu_tensor_gemm4x8_q8_0_p4k4_f16_q8_0_f32 + K-quant SIMD 4×8 tiled microkernels with ARM64 sdot.4s & x64 SSE2/SSSE3 parity plus K-quant SIMD dot paths
Paged attention & RoPE __xu_tensor_rope_f32, __xu_tensor_attn_scores_paged_f32, __xu_tensor_attn_vsum_paged_f32 Supports head_dim % 4 == 0 (64, 128, 40, ...) across ARM64 & x64

Multi-Backend GPU Compute & GPU LLM Inference (packages v1.17.0)

The official github.com/xulang-org/packages v1.17.0 release adds multi-backend GPU support across Apple Silicon Metal, NVIDIA CUDA, cross-platform Vulkan (with a pure-Xu SPIR-V 1.0 generator), and CPU fallback, plus end-to-end Apple Silicon GPU Transformer inference in llm_metal:

PackageTarget Hardware / OSBinding / Loader MechanismCore Capabilities
packages/gpuMetal / CUDA / Vulkan / CPU auto-fallbackUnified facade (detect_backends, open_auto, open_backend)Portable BACKEND_METAL / CUDA / VULKAN / CPU Device, F32Matrix & Q4–Q6KMatrix APIs across backends
packages/llm_metalApple Silicon macOS GPUBuilt over metal / metal_nativeEnd-to-end GPU Transformer inference & LoRA training: load_gguf / load_safetensors / load_model, MetalKVCache / MetalPagedKVCache, generate_paged & MetalLoRA (train_lora_step)
packages/metal + metal_nativeApple Silicon macOS GPUDynamic dlopen of libxu_metal.dylib (XU_METAL_LIBRARY override)176 Metal GPU symbols: F32/F16/Q4–Q6KMatrix (up to 262,144 dim), Metal K-quant SIMD GEMV, FlashAttention/FlashDecode, PagedAttention F16, MoE & LoRA backprop
packages/cuda_nativeNVIDIA GPUs (Linux / Windows)Pure-Xu dlopen (libcuda / libnvrtc / libcublas; XU_CUDA_LIBRARY overrides)Direct CUDA Driver API, NVRTC runtime kernel compilation & cuBLAS GEMM with zero C wrapper
packages/vulkan_nativeVulkan 1.1 GPUs (Linux / Windows / MoltenVK)Pure-Xu dlopen (XU_VULKAN_LIBRARY) + spirv.xuGenerates SPIR-V 1.0 compute binaries directly in pure Xu for portable GPU compute without external glslc
@main
gpu #"github.com/xulang-org/packages/gpu"
llm_metal #"github.com/xulang-org/packages/llm_metal"

fn run_gpu_inference(model_path string) {
    println(gpu.detect_backends().join(", "))
    $model := llm_metal.load_model(model_path, 2048) >>>
    $kv := llm_metal.new_paged_kv_cache(&model, 2048, 16) >>>
    tokens := llm_metal.generate_paged(&model, &[1, 2, 3], 32, 16)
    println(llm_metal.decode_tokens(&model, &tokens))
    _ := kv.close()
    _ := model.close()
}

AI, Agent, RAG, Guardrails & Eval Platform (packages v1.17.0 · 50 packages)

Beyond tensor kernels and GPU backends, packages v1.17.0 (50 official pure-Xu packages, incorporating v1.16.0 production hardening) delivers full-stack LLM clients, distributed gateways, agent runtimes, protocols, vector stores, and evaluation suites:

1. LLM Clients, Gateway & Prompt Engineering

PackageRoleKey APIs & v1.16.0+ Enhancements
openaiOpenAI-compatible client11 presets (DeepSeek, OpenRouter, Groq, Qwen, Mistral, MiniMax, etc.), Chat/Responses API, Files/Batches, Whisper/TTS, Images, Rerank
anthropic / gemini / cohereNative provider SDKsAnthropic Messages (Prompt Caching, extended thinking, tool_use), Gemini REST (schema JSON, thinking_budget, batchEmbedContents), Cohere v2 (chat/embed/rerank)
gatewayMulti-provider LLM routerWeighted routing & sync/SSE failover, circuit breakers & RPM limits, Prometheus metrics, cost accounting, semantic cache; v1.16.0 adds Redis distributed state (set_redis_pool / set_redis_url / set_cache_ttl) & ProviderPassthrough
promptTemplates & extractionPromptTemplate / PromptRegistry, #tensor-powered dynamic few-shot selection (select_few_shot), Markdown JSON extraction

2. Agent Orchestration, MCP / A2A Protocols & XACP

PackageRoleKey APIs & v1.16.0+ Enhancements
agent4-runtime agent frameworkFull feature parity across OpenAI Chat/Responses, Anthropic, and Gemini; v1.16.0 adds cross-provider AgentSwarm (add_anthropic_member / add_gemini_member / add_responses_member), pluggable set_token_counter, SQLite persistence (save_sqlite / load_session_checkpoint_sqlite / load_graph_checkpoint_sqlite), SKILL.md skills, HITL StateGraph, and OTLP/Prometheus tracing
mcpModel Context ProtocolBidirectional JSON-RPC 2.0 (2025-03-26) stdio & Streamable HTTP servers/clients (tools, resources, resourceTemplates, prompts, completions, logging, SSE negotiation)
a2aAgent-to-Agent protocolAgentCard discovery, JSON-RPC 2.0 tasks/send|get|cancel, live SSE tasks/sendSubscribe; v1.16.0 adds auth (set_api_key / set_auth_hook) and SQLite persistence (set_sqlite_store)
#xacp (stdlib)Desktop app agent controlBuilt-in --xacp / --xacp-port discovery & token-authenticated UI tree inspection, actions, and bounded sampling

3. Hybrid RAG & Vector Databases

PackageRoleKey APIs & v1.16.0+ Enhancements
rag#tensor Hybrid & GraphRAGPooled PgVectorPool (v1.16.0 open_pgvector_pool), PgVectorClient, cached SqliteVectorStore (cached_len / refresh_cache), QdrantVectorStore, automated GraphRAG KnowledgeGraph, Parent-Child/Contextual/HyDE/BM25/RRF/Cohere rerank
postgres / sqliteSQL & storage driversUnbounded #database/sql parameters; pure-Xu sqlite_native dynamic dlopen (built-in winsqlite3.dll on Windows); postgres includes pgvector helpers
qdrant / milvus / chromaVector DB clientsPure-Xu REST v2 / HTTP JSON clients for collection setup, vector upserts, metadata filtering, and ANN search

4. Safety Guardrails, Evaluation & Dataset Synthesis

PackageRoleKey APIs & v1.16.0+ Enhancements
guardrailsAI safety defensesPII/secret redaction, canary leak detection, RAG chunk sanitization, model safety checks; v1.16.0 adds strict_policy, normalize_for_detection & check_input_strict
evalModel & RAG evaluationexact_match, F1, ROUGE, BLEU, pass_at_k, ECE calibration, Ragas Triad, LLM-as-a-Judge; v1.16.0 adds evaluate_json_schema_raw for Draft-style JSON Schema validation & CI regression gating
synthSynthetic data curationgenerate_sft_openai / generate_dpo_pair_openai / distill_dataset_openai, exact & Jaccard deduplication, quality filters, and llm_engine JSONL export

Known Limitations & Engineering Trade-offs

Developer caveat: Xu's AI stack optimizes for zero external C/C++ inference bindings and compact standalone binaries, which carries explicit scope limits:

Verify and measure inference

# Pure-Xu compiler MIR, #tensor & llm_engine suites (xu repository)
python3 scripts/test_tensor_opt.py --compiler bin/xu
python3 scripts/test_tensor_types.py --compiler bin/xu
python3 scripts/test_llm_engine.py --compiler bin/xu

# Packages v1.17.0 GPU backends & v1.4.0–v1.16.0 AI suites (packages repository)
XU_ROOT=../xu python3 metal/native/build.py --target macos-arm64
XU_ROOT=../xu XU=../xu/bin/xu python3 -m unittest \
  tests/test_metal_ai.py tests/test_openai_mcp.py tests/test_anthropic_rag.py tests/test_gemini_rag_agent.py \
  tests/test_v18_ai_ecosystem.py tests/test_v19_ai_ecosystem.py tests/test_v110_ai_platform.py \
  tests/test_v111_ai_workflows.py tests/test_v112_ai_ecosystem.py tests/test_v113_ai_agents_protocols.py \
  tests/test_v114_ai_vlm_synth_swarm.py tests/test_v115_ecosystem_hardening.py \
  tests/test_v116_batch1_hardening.py tests/test_v116_batch2_gateway.py \
  tests/test_v117_llm_metal.py tests/test_v118_gpu_backends.py -v

These suites verify numerical parity against independent Python references, paged KV reclamation, --threads N inference, mmproj.gguf VLM parity, VocabIndex Trie + Schema decoding, train-* checkpoints, OpenAI/Anthropic/Ollama/Prometheus HTTP endpoints, Redis gateway, PgVectorPool, a2a auth+SQLite, cross-provider AgentSwarm, llm_metal, and gpu/cuda_native/vulkan_native parity. Multi-architecture compiler and kernel timings live on Benchmarks.

Key APIs & links