1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
//! **Stability tier**: Experimental
//!
//! This is a pure ML inference kernel with high churn, 153 `unsafe` blocks, and 22
//! `dead_code_allows`. It is NOT intended for direct use by platform or feature crates.
//! Consumers should go through `lattice-embed`. The unsafe blocks are documented in
//! `foundation/STABILITY.md §Tech Debt`. Tracking issue: #1306.
//! See `foundation/STABILITY.md` for the full policy.
//!
// ML inference kernels: many functions have >7 args by necessity (BLAS-style APIs
// where grouping into structs would require heap allocation in hot paths), and many
// loops use the index to access multiple arrays simultaneously so the
// needless_range_loop suggestion does not apply.
//! lattice-inference: pure Rust transformer inference for embedding models.
//!
//! Supports two architectures:
//! - **BERT/BGE** (encoder-only): bidirectional attention, mean pooling
//! - **Qwen3** (decoder-only): causal GQA with RoPE, SwiGLU, last-token pooling
//!
//! ## Module Organization
//!
//! - [`model`] — Model configs and loaders (BERT, Qwen, Qwen3.5, BitNet)
//! - [`tokenizer`] — Tokenizers (WordPiece, SentencePiece, BPE)
//! - [`weights`] — Weight storage formats (f32, f16, Q8)
//! - [`attention`] — Attention mechanisms (standard, GQA, flash, GDN)
//! - [`forward`] — Compute backends (CPU, NEON, Metal GPU, batched prefill)
// Grouped modules
/// Attention kernel variants (standard, GQA, flash, GDN, sparse, differential) and the
/// [`attention::AttentionTag`] used to dispatch between them. Called from [`forward`] and [`model`].
/// Compute backends: scalar CPU, NEON, Metal GPU, WGPU, Q8/f16 kernels, and batched prefill.
/// Consumes kernels from [`attention`] and tensors from [`weights`].
/// Model configs and loaders (BERT, Qwen, Qwen3.5, BitNet). Each submodule owns its
/// safetensors load path and forward-pass dispatch; see [`weights`], [`tokenizer`], and [`forward`].
/// Canonical model-directory format detector (`ModelFormat`/`detect_format`) shared by
/// the `lattice`, `lattice_serve`, and `chat_metal` binaries (ADR-080 amendment, #829).
/// **Unstable, internal-binaries-only** -- see the module's own doc comment.
/// Tokenizer implementations (`WordPiece`, `SentencePiece`, byte-level BPE) behind the
/// [`Tokenizer`] trait, plus the [`load_tokenizer`] auto-detect helper. See [`model`].
/// Qwen3-VL vision encoder path: patch preprocessing, ViT forward pass, and MLP merger.
/// See [`model`] and [`weights`].
/// Safetensors-backed tensor storage and weight formats (f32, f16, Q8, Q4). See [`model`]
/// and [`forward`].
// Standalone modules
/// Continuous batching and scheduler support for multi-sequence inference. See [`kv_cache`]
/// and [`model`].
/// Model-file cache and conditional download helpers. See [`model`] and [`weights`].
/// Crate error taxonomy; see [`InferenceError`].
/// Grammar-constrained decoding and logit masking. See [`model`] and [`sampling`].
/// Flat and paged key/value cache implementations. See [`model`] and [`forward`].
/// LoRA adapter hook called from inference forward paths. See [`model`] and [`forward`].
/// Repository-internal guards shared by Metal tests and measurement targets.
///
/// This module is hidden from generated documentation and is not a supported
/// production API. It is exported because Cargo builds repository integration
/// tests, benches, examples, and binaries as separate crates.
/// Inference metrics and entropy accumulation. See [`model`].
/// Adapter routing and mixture support built on top of [`lora_hook`] and [`sampling`].
/// Requires the `mixture` feature.
/// Offline MoE expert-cache admission-policy simulator (issue #682 Stage 3):
/// replays a JSONL routing trace against [`forward::moe_expert_cache`]'s
/// shipped LRU policy plus challenger policies (ARC, sequence-local
/// frequency admission) to measure hit-rate deltas before any engine
/// eviction-policy change. See [`moe_admission`]'s module doc comment.
/// Embedding pooling helpers (mean, CLS, last-token) including [`BertPooling`]. Used by
/// [`model::BertModel`] and [`model::QwenModel`].
/// ShortGPT-style block influence scoring. See [`model`].
/// Quantization and pre-transform primitives. See [`weights`] and [`forward`].
/// Rotary position embedding tables and application helpers. See [`model`] and [`forward`].
/// Sampling configuration and token selection helpers. See [`model`] and [`speculative`].
/// Shared HTTP serving contract (error envelope, `finish_reason`, `max_tokens`
/// zero-rejection, `/v1/models` body) consumed by both the `lattice` unified
/// server and the `lattice_serve` daemon binaries (ADR-080 cluster C2).
/// Requires the `serve` feature (axum/tokio/futures).
/// N-gram prompt lookup speculative decoding. See [`sampling`] and [`model`].
/// Generation stop reason taxonomy; see [`StopReason`] and [`model`].
/// Cross-path sweep (#613): every CPU-family `generate*` entry point agrees on
/// the stop-token contract (excluded from `token_ids`/`text`). The Metal-family
/// entry points are covered in `forward::metal_qwen35`'s own test module; see
/// this module's doc comment for the full manifest and rationale.
/// Backward-pass support for training and LoRA workflows, built on [`lora_hook`] and
/// [`model`]. Requires the `train-backward` feature.
use PathBuf;
/// Default model cache directory.
pub
// Re-exports for public API backward compatibility
/// Root error type for inference, tokenizer, model loading, and runtime failures. See [`error`].
pub use crateInferenceError;
/// BERT encoder configuration. See [`BertModel`] and [`model`].
pub use crateBertConfig;
/// BERT/BGE encoder model. See [`BertConfig`], [`Tokenizer`], and [`BertPooling`].
pub use crateBertModel;
/// BERT-style cross-encoder/reranker model. See [`BertModel`] and [`model`].
pub use crateCrossEncoderModel;
/// Per-layer profiling data collected during Qwen embedding inference. See [`ProfileTimings`]
/// and [`QwenModel`].
pub use crateLayerTimings;
/// Aggregate profiling report for Qwen inference. See [`LayerTimings`] and [`QwenModel`].
pub use crateProfileTimings;
/// Qwen embedding model configuration. See [`QwenModel`] and [`weights`].
pub use crateQwenConfig;
/// Qwen embedding model exposing `encode` for producing embeddings. See [`QwenConfig`],
/// [`Tokenizer`], and [`weights`].
pub use crateQwenModel;
/// BERT pooling strategy selector (mean or CLS). See [`pool`] and [`BertModel`].
pub use crateBertPooling;
/// Reason a generation request stopped (e.g. EOS, max tokens). See [`stop_reason`] and
/// [`model`].
pub use crateStopReason;
/// Byte-level BPE tokenizer used by Qwen-family models. See [`Tokenizer`] and [`TokenizedInput`].
pub use crateBpeTokenizer;
/// Additive Gemma-family BPE tokenizer (literal-space `Split` + `▁` metaspace normalizer),
/// explicitly selected — never reached via [`load_tokenizer`]'s model-type sniffing. See
/// [`Tokenizer`] and ADR-082 G17.
pub use crateGemmaBpeTokenizer;
/// `SentencePiece` tokenizer implementation. See [`Tokenizer`] and [`TokenizedInput`].
pub use crateSentencePieceTokenizer;
/// Padded token IDs and the real (unpadded) sequence length returned by tokenizers. See
/// [`Tokenizer`] and [`tokenizer`].
pub use crateTokenizedInput;
/// Object-safe tokenizer trait implemented by every tokenizer in [`tokenizer`]. See
/// [`load_tokenizer`].
pub use crateTokenizer;
/// `WordPiece` tokenizer used by BERT-family models. See [`Tokenizer`] and [`BertModel`].
pub use crateWordPieceTokenizer;
/// Model-directory tokenizer auto-loader. See [`Tokenizer`] and [`tokenizer`].
pub use crateload_tokenizer;
/// `tokenizer.json`-text tokenizer loader (no filesystem access). See
/// [`Tokenizer`], [`tokenizer`], and [`BertModel::from_bytes`].
pub use cratetokenizer_from_json_str;
/// Stage-1 marker-expansion arithmetic (ADR-082 G11/G15/G17): `<|image|>`/`<|audio|>`
/// placeholder-to-soft-token-count contract, independent of the in-sequence scatter itself.
pub use crate;