interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-runtime / src / compute_config.rs

236 lines · 9400 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Binding of the resolved `ModelConfig` to the persistent-KV identity (ADR
17//! 0003 section 1.2 fields 4 to 8 and 14, section 1.2.1, review finding 1), and
18//! the host engine identity (section 1.2.2, sc#504).
19//!
20//! Two config.json files with the same weights but a different `rms_norm_eps`
21//! produce different K/V, and the weights digest does not cover `config.json`.
22//! So every `ModelConfig` field is accounted for in ONE place,
23//! [`ModelBinding::from_model`], which destructures `ModelConfig`
24//! **exhaustively with no `..`**: adding a field to `ModelConfig` is a compile
25//! error here until its author decides "bound" (and where) or "excluded, with a
26//! reason". The reasons for today's exclusions are written next to the pattern.
27//!
28//! The binding is built from the RESOLVED `ModelConfig` (serde defaults
29//! applied), never from raw `config.json` text (ADR 1.2.1: JSON has no
30//! canonical form and raw files carry fields that cannot change a K/V value).
31
32use aien_abi_core::ModelConfig;
33use aien_inference_abi::KV_ARITH_EPOCH;
34use aien_kv_store::{
35 BackendFormat, ComputeConfig, EngineConfig, EngineIdentity, HiddenAct, KvDtype, KvError,
36 LayoutStrides, NamespaceFields, RopeScaling, WeightFormat,
37};
38
39/// Everything a `ModelConfig` contributes to the namespace id: the compute
40/// configuration (field 14, through its digest) and namespace fields 4 to 8.
41#[derive(Debug, Clone, Copy, PartialEq)]
42pub struct ModelBinding<'a> {
43 pub compute: ComputeConfig<'a>,
44 /// Namespace field 4.
45 pub model_id: &'a str,
46 /// Namespace field 5.
47 pub num_layers: u32,
48 pub num_kv_heads: u32,
49 pub head_dim: u32,
50 pub block_size: u32,
51 /// Namespace field 6.
52 pub rope_theta: f32,
53 /// Namespace field 7.
54 pub rope_scaling: Option<RopeScaling>,
55 /// Namespace field 8.
56 pub qk_norm: bool,
57}
58
59/// The namespace inputs that do not come from `ModelConfig`: the weights
60/// identity, the byte layout, the chunking and the sharing scope.
61#[derive(Debug, Clone, Copy, PartialEq)]
62pub struct StoreInputs<'a> {
63 pub model_sha256: [u8; 32],
64 pub model_digest_kind: &'a str,
65 pub dtype: KvDtype,
66 pub layout: LayoutStrides,
67 pub backend_format: BackendFormat,
68 pub chunk_tokens: u32,
69 pub sharing_namespace: &'a str,
70}
71
72fn wire_u32(v: usize) -> Result<u32, KvError> {
73 u32::try_from(v).map_err(|_| KvError::Overflow)
74}
75
76impl<'a> ModelBinding<'a> {
77 /// `arith_id` is `TensorBackend::name()` of the backend that computes the
78 /// K/V; `arith_epoch` is the constant `KV_ARITH_EPOCH`. Refused
79 /// (`KvError::Overflow`) when a count does not fit its wire width.
80 pub fn from_model(cfg: &'a ModelConfig, arith_id: &'a str) -> Result<Self, KvError> {
81 // Exhaustive on purpose: no `..`. Do not add one.
82 let ModelConfig {
83 // Namespace fields 4 to 8: bound by the namespace id itself.
84 model_id,
85 num_layers,
86 num_kv_heads,
87 head_dim,
88 block_size,
89 rope_theta,
90 rope_scaling,
91 qk_norm,
92 // Compute configuration, ADR 1.2.1 table fields 1 to 6.
93 num_heads,
94 hidden_dim,
95 intermediate_dim,
96 vocab_size,
97 rms_norm_eps,
98 tie_word_embeddings,
99 // Excluded, with the reasons of ADR 1.2.1 "Fields not listed":
100 // it caps the context and does not change any K/V value (the cap is
101 // applied to the restorable prefix instead, ADR 6.3);
102 max_sequence_length: _,
103 // it decides when a sequence stops, not what is computed.
104 eos_token_ids: _,
105 } = cfg;
106 Ok(Self {
107 compute: ComputeConfig {
108 num_heads: wire_u32(*num_heads)?,
109 hidden_dim: *hidden_dim as u64,
110 intermediate_dim: *intermediate_dim as u64,
111 vocab_size: *vocab_size as u64,
112 rms_norm_eps: *rms_norm_eps,
113 tie_word_embeddings: *tie_word_embeddings,
114 // The loader refuses everything but silu (model_dir.rs), so the
115 // byte is a constant today; it exists so a future activation
116 // cannot alias.
117 hidden_act: HiddenAct::Silu,
118 arith_id,
119 arith_epoch: KV_ARITH_EPOCH,
120 },
121 model_id,
122 num_layers: wire_u32(*num_layers)?,
123 num_kv_heads: wire_u32(*num_kv_heads)?,
124 head_dim: wire_u32(*head_dim)?,
125 block_size: wire_u32(*block_size)?,
126 rope_theta: *rope_theta,
127 rope_scaling: rope_scaling.map(|s| RopeScaling {
128 factor: s.factor,
129 low_freq_factor: s.low_freq_factor,
130 high_freq_factor: s.high_freq_factor,
131 original_max_position_embeddings: s.original_max_position_embeddings as u64,
132 }),
133 qk_norm: *qk_norm,
134 })
135 }
136
137 /// The full namespace inputs with field 14 filled from this binding's
138 /// compute configuration and the `engine` that computes the K/V (ADR 1.2.2;
139 /// required, there is no default). `NamespaceFields::namespace_id()` does
140 /// the hashing.
141 pub fn namespace_fields(
142 &self,
143 store: &StoreInputs<'a>,
144 engine: &EngineIdentity<'_>,
145 ) -> Result<NamespaceFields<'a>, KvError> {
146 Ok(NamespaceFields {
147 model_sha256: store.model_sha256,
148 model_digest_kind: store.model_digest_kind,
149 model_id: self.model_id,
150 num_layers: self.num_layers,
151 num_kv_heads: self.num_kv_heads,
152 head_dim: self.head_dim,
153 block_size: self.block_size,
154 rope_theta: self.rope_theta,
155 rope_scaling: self.rope_scaling,
156 qk_norm: self.qk_norm,
157 dtype: store.dtype,
158 layout: store.layout,
159 backend_format: store.backend_format,
160 chunk_tokens: store.chunk_tokens,
161 sharing_namespace: store.sharing_namespace,
162 compute_config_digest: self.compute.digest_with_engine(engine)?,
163 })
164 }
165}
166
167/// `ComputeConfig::from(&ModelConfig)` of the ADR text (a free function: both
168/// types are foreign to this crate, so a `From` impl is not allowed).
169pub fn compute_config_from<'a>(
170 cfg: &'a ModelConfig,
171 arith_id: &'a str,
172) -> Result<ComputeConfig<'a>, KvError> {
173 Ok(ModelBinding::from_model(cfg, arith_id)?.compute)
174}
175
176/// The host engine build id: this crate's version and the commit it was built
177/// from (`build.rs`; `unknown` without git or `AIEN_BUILD_COMMIT`).
178pub const HOST_ENGINE_BUILD_ID: &str = concat!(
179 "aien-runtime/",
180 env!("CARGO_PKG_VERSION"),
181 "+git:",
182 env!("AIEN_RUNTIME_GIT_COMMIT")
183);
184
185/// Matrix-multiply path label of the host `TensorBackend` path.
186pub const HOST_MATMUL_PATH: &str = "host-tensor-backend";
187
188/// Owned engine identity of the host reference path (ADR 0003 section 1.2.2,
189/// sc#504): what the daemon binds when the K/V is computed by a host
190/// `TensorBackend` (the CPU reference).
191///
192/// - weight format `as-file`: the host loader computes with the element type
193/// the file stores;
194/// - build id [`HOST_ENGINE_BUILD_ID`];
195/// - rounding class `<arith_id>@kv-arith-epoch-<KV_ARITH_EPOCH>`;
196/// - engine config: dense (no experts), whole-prompt prefill off, device
197/// router off, matmul path [`HOST_MATMUL_PATH`].
198///
199/// An engine with its own build, weight format or switches (the omega engine)
200/// builds its own [`EngineIdentity`] instead.
201#[derive(Debug, Clone, PartialEq, Eq)]
202pub struct HostEngineIdentity {
203 rounding_class: String,
204 engine_config_digest: [u8; 32],
205}
206
207impl HostEngineIdentity {
208 /// `arith_id` is `TensorBackend::name()` of the backend that writes the K/V.
209 pub fn reference(arith_id: &str) -> Result<Self, KvError> {
210 if arith_id.is_empty() {
211 return Err(KvError::FieldEmpty("arith_id"));
212 }
213 let engine_config_digest = EngineConfig {
214 num_experts: 0,
215 experts_per_token: 0,
216 expert_intermediate_dim: 0,
217 whole_prompt_prefill: false,
218 device_router: false,
219 matmul_path: HOST_MATMUL_PATH,
220 }
221 .digest()?;
222 Ok(Self {
223 rounding_class: format!("{arith_id}@kv-arith-epoch-{KV_ARITH_EPOCH}"),
224 engine_config_digest,
225 })
226 }
227
228 pub fn identity(&self) -> EngineIdentity<'_> {
229 EngineIdentity {
230 weight_format: WeightFormat::AsFile,
231 engine_build_id: HOST_ENGINE_BUILD_ID,
232 rounding_class: &self.rounding_class,
233 engine_config_digest: self.engine_config_digest,
234 }
235 }
236}