Update README.md
Browse files12345---license: otherlicense_name: dosl-iie-1.0license_link: LICENSE---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400# Cognexis**A Compute-Adaptive Recurrent-Depth Large Language Model**Cognexis is a decoder-only language model architecture that separates *reasoning depth* from *parameter count*. Instead of scaling depth exclusively by stacking more transformer layers, Cognexis reuses a shared recurrent transformer block for a configurable number of iterations at inference time. The same checkpoint serves requests at different quality, latency, and compute budgets β making loop count a runtime control knob rather than a fixed architectural constant.---## Table of Contents1. [Core Idea](#core-idea)2. [Architecture](#architecture)3. [Loop Modes](#loop-modes)4. [Model Configurations](#model-configurations)5. [Evaluation Metrics](#evaluation-metrics)6. [Quick Start](#quick-start)7. [Project Structure](#project-structure)8. [Specification](#specification)9. [Safety and Observability](#safety-and-observability)10. [Known Limitations](#known-limitations)11. [License](#license)---## Core IdeaIn a standard transformer, reasoning depth is hard-coupled to parameter count β deeper models need more unique weights. Cognexis decouples these by routing every sequence through:1. A **Prelude** of conventional transformer blocks (unique parameters).2. A **shared recurrent core** applied *N* times (one shared parameter set, reused across all *N* iterations).3. A **Coda** of conventional transformer blocks (unique parameters).```input_text-> tokenizer.encode-> token_ids-> embedding(token_ids)-> prelude(hidden) # unique params, runs once-> recurrent_core(hidden) # shared params, runs N times-> coda(hidden) # unique params, runs once-> lm_head(hidden)-> logits```The **effective depth** is:```effective_depth = num_prelude_blocks + N * num_recurrent_blocks + num_coda_blocks```Increasing `N` deepens the computation without adding new parameters. The compute-adaptive scheduler can then decide *at runtime* how much depth each request actually needs.---## ArchitectureCognexis follows a five-stage pipeline. Each stage is a separate, testable module.### TokenizerConverts raw text into token IDs using a subword tokenizer (SentencePiece Unigram by default). The tokenizer is part of the model contract β it is bundled with every checkpoint and validated by checksum. Required special tokens: `BOS`, `EOS`, `PAD`, `UNK`, `EOD`. Instruction-tuned deployments add role markers: `<|system|>`, `<|user|>`, `<|assistant|>`, `<|tool|>`, `<|end|>`.### EmbeddingMaps token IDs to dense vectors of size `hidden_dim`. Uses **rotary positional encoding (RoPE)** applied inside attention, not learned absolute positions. Embedding weights are **weight-tied** with the LM head by default, reducing parameter count and keeping input/output token representations aligned.### PreludeA stack of conventional transformer blocks with unique parameters. It builds stable, contextual token representations before recurrence begins. Without a capable Prelude, the recurrent core would need to simultaneously handle early lexical processing and deep iterative refinement, increasing instability and weakening depth generalization.### Recurrent CoreThe defining Cognexis component: **one shared transformer block** applied repeatedly. Each iteration refines the hidden state under the same causal mask. Shared parameters mean:- Gradients accumulate from all loop unrolls into the same weights.- Checkpoints store exactly one recurrent block β never one copy per loop.- Stability controls (residual scaling, gating, spectral monitoring) are required.Optional input injection anchors recurrence to the original Prelude output `h0`, preventing drift toward generic fixed points at high loop counts.### CodaA final stack of conventional transformer blocks with unique parameters. Integrates the refined recurrent state, performs cross-token mixing, and prepares representations for the LM head. If `num_coda_blocks = 0`, recurrent output flows directly to final norm and logits β valid but quality-affecting.### LM HeadLinear projection from hidden states to vocabulary logits. Weight-tied to the token embedding by default. Loss is standard next-token cross-entropy, with masking for PAD tokens, non-assistant prompt tokens in SFT, and packed-document boundaries.---## Loop ModesCognexis supports three loop execution modes, selectable at request time:| Mode | Description ||------|-------------|| `fixed` | Every sequence runs the configured loop count. Baseline for training, debugging, and deterministic production. || `adaptive_sequence` | A scheduler decides when to halt for the whole sequence. Simpler execution model than token-wise. || `adaptive_token` | Each token position may halt independently while others continue. More compute-efficient for heterogeneous sequences; more complex cache/masking implementation. |All modes enforce hard bounds: the scheduler may stop early, but **never exceeds `max_loops`** or the request compute budget.### Scheduler ModesThe adaptive scheduler can be:- **rule-based** β halts using thresholds on hidden-state delta, confidence, entropy, or budgets.- **value-head** β halts using a small learned head predicting marginal improvement per loop.- **hybrid** β combines rule-based hard stops with value-head gain-per-cost predictions.- **oracle** β research-only; uses unavailable future information for analysis only.**Recommended for production:** conservative `hybrid` with hard bounds and `min_loops` enforced before any halt decision.---## Model Configurations| Model | Hidden Size | Attention Heads | Prelude Blocks | Recurrent Blocks | Coda Blocks | Max Loops (train) | Parameters ||-------|------------|----------------|---------------|-----------------|-------------|-------------------|-----------|| Cognexis-8B | 4096 | 32 | 8 | 1 | 8 | 12 | ~8 B || Cognexis-64B | 8192 | 64 | 10 | 1 | 10 | 16 | ~64 B || Cognexis-256B | 12288 | 96 | 12 | 1 | 12 | 20 | ~256 B || Cognexis-1.28T | 16384 | 128 | 16 | 1 | 16 | 24 | ~1.28 T |The recurrent core always uses a single shared block. Larger models increase `hidden_dim`, head counts, block counts, and training loop budgets. Effective depth is tunable at inference independently of parameter count.---## Evaluation MetricsCognexis evaluation reports both **quality** and **compute** together.### Quality Metrics- Perplexity and negative log-likelihood- Exact match and multiple-choice accuracy- Pass@k for code generation- Task-specific generation metrics (BLEU, ROUGE, rubric scores)### Compute Metrics- Loops executed per request (mean, median, p90, p99)- Prefill and decode latency- Approximate FLOPs by stage- Peak memory and KV cache memory- Scheduler overhead### Depth-Aware Metrics| Metric | Formula | Interpretation ||--------|---------|----------------|| **DEI** (Depth Efficiency Index) | `(M(Nβ) - M(Nβ)) / (C(Nβ) - C(Nβ))` | Quality gain per extra unit of compute. Higher = better returns from additional loops. || **LSP** (Loop Saturation Point) | `argmax_N DEI(N)` | Depth where marginal returns peak. Preferred default loop budget. || **OT** (Overthinking Threshold) | `min { d : M(d+1) < M(d) - tolerance }` | First depth where extra loops harm quality. Scheduler must stop before this. || **DGR** (Depth Gain Ratio) | `(M(N_max) - M(N_min)) / |M(N_min)|` | Total improvement from shallow to maximum depth. |DEI, LSP, OT, and DGR are task-dependent β different tasks saturate and overthink at different depths.---## Quick Start### Tokenize```rustuse cognexis::tokenizer::Tokenizer;let tokenizer = Tokenizer::from_artifact("tokenizer.json")?;let ids = tokenizer.encode("The recurrent core", EncodeOptions::default())?;let text = tokenizer.decode(&ids, DecodeOptions::default())?;```### Generate (Fixed Loop Mode)```rustuse cognexis::{CognexisModel, GenerationRequest, LoopMode, SamplingOptions};let model = CognexisModel::from_checkpoint("checkpoint/", &ServeConfig::load("serve.yaml")?)?;let request = GenerationRequest {input_ids: tokenizer.encode("Explain transformers", EncodeOptions::default())?,max_new_tokens: 128,loop_options: LoopOptions {mode: LoopMode::Fixed(8),..Default::default()},sampling: SamplingOptions::default().with_temperature(0.7).with_top_p(0.9),};for event in model.generate_streaming(request)? {println!("{}", event.text_delta);}```### Generate (Adaptive Loop Mode)```rustlet request = GenerationRequest {input_ids: ids,max_new_tokens: 128,loop_options: LoopOptions {mode: LoopMode::Adaptive {min_loops: 2,max_loops: 16,},..Default::default()},sampling: SamplingOptions::default(),};// Scheduler halts when confidence is high and predicted marginal gain is low.```### Training```bashcognexis train --config configs/train.yaml```### Evaluation```bashcognexis eval --config configs/eval.yaml --checkpoint checkpoint/# Loop scaling studycognexis eval loop-scaling --config configs/eval.yaml --depths 1,2,4,8,12```---## Project Structure```cognexis/βββ cognexis-spec/ # Full engineering specification (28 documents)β βββ spec01_overview.mdβ βββ spec02_tokenizer.mdβ βββ spec03_embedding.mdβ βββ spec04_attention.mdβ βββ spec05_feedforward.mdβ βββ spec06_transformer_block.mdβ βββ spec07_prelude.mdβ βββ spec08_recurrent_core.mdβ βββ spec09_coda.mdβ βββ spec10_lm_head.mdβ βββ spec11_config.mdβ βββ spec12_data_loading.mdβ βββ spec13_curriculum.mdβ βββ spec14_distributed_training.mdβ βββ spec15_stability_normalization.mdβ βββ spec16_prefill_decode.mdβ βββ spec17_scheduler_design.mdβ βββ spec18_tokenwise_scheduling.mdβ βββ spec19_value_head.mdβ βββ spec20_evaluation_metrics.mdβ βββ spec21_loop_scaling.mdβ βββ spec22_ablation.mdβ βββ spec23_instruction_tuning.mdβ βββ spec24_safety_monitoring.mdβ βββ spec25_glossary.mdβ βββ spec26_implementation_outline.mdβ βββ spec27_limitations_future.mdβ βββ spec28_conclusion.mdβ βββ cognexis_white_paper.md # High-level narrativeβ βββ white_paper_references.mdββββ cognexis/ # Rust implementationβββ Cargo.tomlβββ src/tokenizer.rs # Subword encoding/decoding, special tokens, chat templatesembedding.rs # Token embeddings, RoPE position IDsattention.rs # MHA, GQA, MQA, sliding-window, KV cachefeedforward.rs # SwiGLU, GeGLU, GELU, ReLU MLPstransformer_block.rs# Pre-norm composition, residual scaling, gatingprelude.rs # Prelude stage (multiple unique blocks)recurrent_core.rs # Shared recurrent block, input injection, loop executioncoda.rs # Coda stage (multiple unique blocks)lm_head.rs # Vocabulary projection, weight tying, cross-entropy lossstability.rs # RMSNorm, LayerNorm, residual scaling, spectral monitoringscheduler.rs # Fixed, rule-based, value-head, hybrid schedulerstokenwise.rs # Token-wise loop allocation and active maskingvalue_head.rs # Learned gain predictor for adaptive schedulingprefill_decode.rs # Autoregressive inference: prefill, decode, cache managementconfig.rs # Typed YAML/JSON config with validationdata_loading.rs # Sharded dataset streaming, document packing, shufflingcurriculum.rs # Loop curriculum: warm-up, depth ramp, sampling distributionsdistributed_training.rs # FSDP, tensor parallelism, pipeline stagingevaluation.rs # Evaluation harness, task traits, metric computationloop_scaling.rs # Loop scaling experiment runnerablation.rs # Ablation study framework and config managementinstruction_tuning.rs # SFT data formats, chat templates, assistant-only loss maskingsafety.rs # Input/output filtering, policy enforcement, compute budgetslib.rs # Top-level exports and public APIattention.rs # Attention variantsfeedforward.rs # FFN activationsstability.rs # Normalizationtokenizer.rs # Tokenizationconfig.rs # Configurationprefill_decode.rs # Inferencescheduler.rs # Schedulingdata_loading.rs # Data loadingcurriculum.rs # Loop curriculumdistributed_training.rs # Distributed trainingevaluation.rs # Evaluationloop_scaling.rs # Loop scalingablation.rs # Ablationsinstruction_tuning.rs # Instruction tuningsafety.rs # Safetytransformer_block.rsembedding.rsprelude.rsrecurrent_core.rscoda.rslm_head.rstokenwise.rsvalue_head.rslib.rs```---## SpecificationThe `cognexis-spec/` directory contains the complete engineering specification for Cognexis, written as 28 focused documents. It is the authoritative implementation contract β all conforming implementations must satisfy the requirements documented there.Documents are divided into five groups:| Group | Documents | Coverage ||-------|-----------|----------|| Core Components | spec01βspec10 | Tokenizer, embedding, attention, FFN, transformer block, Prelude, recurrent core, Coda, LM head || System Stack | spec11βspec16 | Configuration, data loading, curriculum, distributed training, stability/normalization, prefill/decode || Scheduling | spec17βspec19 | Adaptive scheduler design, token-wise allocation, value head || Evaluation & Ops | spec20βspec24 | Evaluation metrics/protocols, loop scaling, ablation, instruction tuning, safety/monitoring || Project | spec25βspec28 | Glossary, implementation outline, limitations/future work, conclusion |Key invariants every implementation must preserve:- Token IDs are identical between training and inference for the same tokenizer and normalization settings.- Recurrent core weights are shared across all loop iterations (one checkpoint tensor, not N copies).- Causal masking is enforced in every attention path at every loop.- `min_loops` and `max_loops` are enforced as hard bounds regardless of scheduler mode.- Evaluation reports quality and compute together; quality alone is incomplete.- Safety policies wrap generation regardless of loop mode.---## Safety and Observability**Cognexis inherits all standard LLM safety concerns and adds recurrent-specific risks.**### Required Safety Controls- Input policy checks and prompt injection detection before prefill.- Output policy checks after generation.- Special-token injection prevention.- Hard compute budget limits: max prompt tokens, max generated tokens, max loops, wall-clock timeout.- Safety risk signals in scheduler halt decisions.- Safety metrics measured across loop counts (depth can affect refusal accuracy).### Required ObservabilityStructured logs must include (without raw prompt/output text by default):- Request ID, checkpoint ID, tokenizer checksum.- Prompt and generation token counts.- Loop mode, loop count distribution, halt reasons.- Prefill and decode latency.- Safety filter actions, error/stop reason.Exposed metrics: requests/sec, tokens/sec, mean loops, loop histogram, halt reason counts, refusal rate, budget exhaustion rate, non-finite activation count, error rate by category.Tracing spans: tokenization, prefill, each recurrent loop, scheduler observation, Coda, LM head, sampling, safety filtering, streaming emission.---## Known LimitationsSee `cognexis-spec/spec27_limitations_future.md` for the full list. Key items:- **Stability at high loop counts.** Repeated application can explode norms, collapse to uninformative fixed points, or oscillate. Requires residual scaling, gating, spectral monitoring, and gradient clipping.- **Latency variability.** Adaptive scheduling produces variable response times, which complicates SLA-driven serving.- **Scheduler generalization.** Learned schedulers may halt incorrectly on out-of-distribution prompts. Conservative fallback policies are required.- **Overthinking.** Quality can degrade beyond a threshold depth. The Overthinking Threshold varies by task and must be measured empirically.- **KV cache subtlety.** Recurrent hidden states change with loop index, making cache reuse more error-prone than standard transformers. Correctness-first recomputation may be necessary.- **Token-wise efficiency.** Masked dense token-wise execution is simple and correct but saves little compute. Hardware-appropriate sparse kernels are future work.- **Training complexity.** Loop curricula, recurrent gradient handling, and scheduler training add overhead not present in standard decoder-only training.Cognexis does not make deeper reasoning free. It makes compute cost *explicit, measurable, and controllable*. Implementations must preserve stability, report depth efficiency honestly, and enforce runtime budgets and safety policies.---## LicenseSee `LICENSE` file.---license: otherlicense_name: dosl-iie-1.0license_link: LICENSE---
README.md+400-5