Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-inference-abi/src/model_dir.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-inference-abi / src / model_dir.rs` 590 lines ยท 22766 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 //! Model description from a Hugging Face model directory. 17 //! 18 //! `config.json` (and `generation_config.json` for the stop set) of a `LlamaForCausalLM` 19 //! checkpoint becomes a [`ModelConfig`]; [`crate::checkpoint::llama_catalog`] turns that into 20 //! the tensor catalog the strict loader checks. Anything this engine does not implement 21 //! (another architecture, biases, another activation, another rope type) is refused with 22 //! an error naming the field, never approximated. 23 24 use aien_abi_core::{Llama3RopeScaling, ModelConfig}; 25 use serde::Deserialize; 26 use std::path::Path; 27 28 /// The Llama architecture this engine runs (also SmolLM2 and Llama 3.x). 29 pub const LLAMA_ARCHITECTURE: &str = "LlamaForCausalLM"; 30 31 /// The Qwen3 dense architecture: Llama plus per-head RMSNorm of Q and K before RoPE, 32 /// `head_dim` set explicitly in `config.json`. 33 pub const QWEN3_ARCHITECTURE: &str = "Qwen3ForCausalLM"; 34 35 /// Every `config.json` key a `Qwen3ForCausalLM` checkpoint may carry. The ones that change 36 /// the maths (`sliding_window`, `use_sliding_window`, `layer_types`, `rope_scaling`, 37 /// `attention_bias`, `hidden_act`) are checked by value below; any key outside this list is 38 /// refused by name, never ignored. 39 const QWEN3_KNOWN_KEYS: &[&str] = &[ 40 "architectures", 41 "attention_bias", 42 "attention_dropout", 43 "bos_token_id", 44 "dtype", 45 "eos_token_id", 46 "head_dim", 47 "hidden_act", 48 "hidden_size", 49 "initializer_range", 50 "intermediate_size", 51 "layer_types", 52 "max_position_embeddings", 53 "max_window_layers", 54 "model_type", 55 "num_attention_heads", 56 "num_hidden_layers", 57 "num_key_value_heads", 58 "pad_token_id", 59 "rms_norm_eps", 60 "rope_scaling", 61 "rope_theta", 62 "sliding_window", 63 "tie_word_embeddings", 64 "torch_dtype", 65 "transformers_version", 66 "use_cache", 67 "use_sliding_window", 68 "vocab_size", 69 ]; 70 71 /// Refusals specific to `Qwen3ForCausalLM`, each naming the field. 72 fn check_qwen3_fields(raw: &serde_json::Value) -> Result<(), String> { 73 let obj = raw.as_object().ok_or("config.json is not an object")?; 74 if let Some(key) = obj.keys().find(|k| !QWEN3_KNOWN_KEYS.contains(&k.as_str())) { 75 return Err(format!("unsupported Qwen3 config field {key:?}")); 76 } 77 match obj.get("model_type").and_then(|v| v.as_str()) { 78 Some("qwen3") => {} 79 other => { 80 return Err(format!( 81 "unsupported model_type {other:?} for Qwen3ForCausalLM (expected \"qwen3\")" 82 )) 83 } 84 } 85 if !obj.get("head_dim").is_some_and(|v| v.is_u64()) { 86 return Err( 87 "Qwen3 config.json must set head_dim (it is not hidden_size / num_attention_heads)" 88 .to_string(), 89 ); 90 } 91 if obj 92 .get("use_sliding_window") 93 .is_some_and(|v| v != &serde_json::Value::Bool(false)) 94 { 95 return Err("unsupported use_sliding_window (supported: false)".to_string()); 96 } 97 if obj.get("sliding_window").is_some_and(|v| !v.is_null()) { 98 return Err("unsupported sliding_window (supported: null)".to_string()); 99 } 100 if let Some(types) = obj.get("layer_types") { 101 let all_full = types 102 .as_array() 103 .is_some_and(|a| a.iter().all(|t| t.as_str() == Some("full_attention"))); 104 if !all_full { 105 return Err( 106 "unsupported layer_types (supported: every layer full_attention)".to_string(), 107 ); 108 } 109 } 110 Ok(()) 111 } 112 113 /// KV page size used for every model loaded from a directory. 114 const BLOCK_SIZE: usize = 16; 115 116 #[derive(Debug, Deserialize)] 117 struct HfLlamaConfig { 118 #[serde(default)] 119 architectures: Vec, 120 hidden_size: usize, 121 intermediate_size: usize, 122 num_hidden_layers: usize, 123 num_attention_heads: usize, 124 num_key_value_heads: Option, 125 head_dim: Option, 126 vocab_size: usize, 127 rms_norm_eps: f32, 128 #[serde(default = "default_rope_theta")] 129 rope_theta: f32, 130 rope_scaling: Option, 131 #[serde(default)] 132 tie_word_embeddings: bool, 133 max_position_embeddings: usize, 134 hidden_act: Option, 135 #[serde(default)] 136 attention_bias: bool, 137 #[serde(default)] 138 mlp_bias: bool, 139 } 140 141 fn default_rope_theta() -> f32 { 142 10000.0 143 } 144 145 /// Reads `rope_scaling`: absent, null or `rope_type: "default"` is plain rope; `"llama3"` 146 /// needs all four llama3 fields. Any other type is refused. 147 fn parse_rope_scaling( 148 value: Option<&serde_json::Value>, 149 ) -> Result, String> { 150 let Some(obj) = value.and_then(|v| v.as_object()) else { 151 return match value { 152 None | Some(serde_json::Value::Null) => Ok(None), 153 Some(other) => Err(format!("rope_scaling must be an object, got {other}")), 154 }; 155 }; 156 let rope_type = obj 157 .get("rope_type") 158 .or_else(|| obj.get("type")) 159 .and_then(|v| v.as_str()) 160 .unwrap_or("default"); 161 match rope_type { 162 "default" => Ok(None), 163 "llama3" => { 164 let num = |key: &str| { 165 obj.get(key) 166 .and_then(|v| v.as_f64()) 167 .ok_or_else(|| format!("rope_scaling (llama3) has no numeric {key}")) 168 }; 169 let scaling = Llama3RopeScaling { 170 factor: num("factor")?, 171 low_freq_factor: num("low_freq_factor")?, 172 high_freq_factor: num("high_freq_factor")?, 173 original_max_position_embeddings: num("original_max_position_embeddings")? as usize, 174 }; 175 if scaling.factor <= 0.0 176 || scaling.high_freq_factor <= scaling.low_freq_factor 177 || scaling.original_max_position_embeddings == 0 178 { 179 return Err(format!("rope_scaling (llama3) is degenerate: {scaling:?}")); 180 } 181 Ok(Some(scaling)) 182 } 183 other => Err(format!( 184 "unsupported rope_scaling rope_type {other:?} (supported: default, llama3)" 185 )), 186 } 187 } 188 189 /// Builds the [`ModelConfig`] of a `LlamaForCausalLM` or `Qwen3ForCausalLM` checkpoint from the text of its 190 /// `config.json` and, when present, its `generation_config.json` (stop set: its 191 /// `eos_token_id`, else the one in `config.json`). 192 pub fn model_config_from_hf_json( 193 model_id: &str, 194 config_json: &str, 195 generation_config_json: Option<&str>, 196 ) -> Result { 197 let raw: serde_json::Value = 198 serde_json::from_str(config_json).map_err(|e| format!("config.json: {e}"))?; 199 let hf: HfLlamaConfig = 200 serde_json::from_value(raw.clone()).map_err(|e| format!("config.json: {e}"))?; 201 let qk_norm = match hf.architectures.as_slice() { 202 [a] if a == LLAMA_ARCHITECTURE => false, 203 [a] if a == QWEN3_ARCHITECTURE => { 204 check_qwen3_fields(&raw)?; 205 true 206 } 207 other => { 208 return Err(format!( 209 "unsupported architectures {other:?}: this engine runs [\"{LLAMA_ARCHITECTURE}\"] or [\"{QWEN3_ARCHITECTURE}\"] only" 210 )) 211 } 212 }; 213 if let Some(act) = hf.hidden_act.as_deref().filter(|a| *a != "silu") { 214 return Err(format!("unsupported hidden_act {act:?} (supported: silu)")); 215 } 216 if hf.attention_bias || hf.mlp_bias { 217 return Err("unsupported attention_bias/mlp_bias = true (no bias tensors)".to_string()); 218 } 219 let num_heads = hf.num_attention_heads; 220 if num_heads == 0 || (!qk_norm && !hf.hidden_size.is_multiple_of(num_heads)) { 221 return Err(format!( 222 "hidden_size {} is not a multiple of num_attention_heads {num_heads}", 223 hf.hidden_size 224 )); 225 } 226 let head_dim = hf.head_dim.unwrap_or(hf.hidden_size / num_heads.max(1)); 227 if !qk_norm && head_dim * num_heads != hf.hidden_size { 228 return Err(format!( 229 "unsupported head_dim {head_dim}: num_attention_heads * head_dim must equal hidden_size {}", 230 hf.hidden_size 231 )); 232 } 233 let rope_scaling = parse_rope_scaling(hf.rope_scaling.as_ref())?; 234 let generation = generation_config_json 235 .map(serde_json::from_str::) 236 .transpose() 237 .map_err(|e| format!("generation_config.json: {e}"))?; 238 let eos_token_ids = generation 239 .as_ref() 240 .and_then(crate::tokenizer::eos_token_ids_from_json) 241 .or_else(|| crate::tokenizer::eos_token_ids_from_json(&raw)) 242 .ok_or("no eos_token_id in generation_config.json or config.json")?; 243 let config = ModelConfig { 244 model_id: model_id.to_string(), 245 max_sequence_length: hf.max_position_embeddings, 246 block_size: BLOCK_SIZE, 247 num_layers: hf.num_hidden_layers, 248 num_heads, 249 head_dim, 250 num_kv_heads: hf.num_key_value_heads.unwrap_or(num_heads), 251 hidden_dim: hf.hidden_size, 252 intermediate_dim: hf.intermediate_size, 253 vocab_size: hf.vocab_size, 254 rms_norm_eps: hf.rms_norm_eps, 255 rope_theta: hf.rope_theta, 256 rope_scaling, 257 tie_word_embeddings: hf.tie_word_embeddings, 258 eos_token_ids, 259 qk_norm, 260 }; 261 config 262 .attention_geometry() 263 .map_err(|e| format!("attention geometry refused: {e:?}"))?; 264 Ok(config) 265 } 266 267 /// A readable model id for a directory: `org/name` for a Hugging Face cache snapshot 268 /// (`.../models--org--name/snapshots/`), else the directory name. 269 pub fn model_id_for_dir(dir: &Path) -> String { 270 let name = |p: &Path| p.file_name().and_then(|n| n.to_str()).map(str::to_string); 271 let cache_repo = dir 272 .parent() 273 .filter(|p| name(p).as_deref() == Some("snapshots")) 274 .and_then(|p| p.parent()) 275 .and_then(name) 276 .and_then(|repo| { 277 repo.strip_prefix("models--") 278 .map(|r| r.replacen("--", "/", 1)) 279 }); 280 cache_repo 281 .or_else(|| name(dir)) 282 .unwrap_or_else(|| "checkpoint".to_string()) 283 } 284 285 /// Reads `/config.json` and `/generation_config.json` into a [`ModelConfig`]. 286 pub fn load_model_config(dir: &Path) -> Result { 287 let config_path = dir.join("config.json"); 288 let config_json = std::fs::read_to_string(&config_path) 289 .map_err(|e| format!("cannot read {}: {e}", config_path.display()))?; 290 let generation_path = dir.join("generation_config.json"); 291 let generation_json = match std::fs::read_to_string(&generation_path) { 292 Ok(text) => Some(text), 293 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, 294 Err(e) => return Err(format!("cannot read {}: {e}", generation_path.display())), 295 }; 296 model_config_from_hf_json( 297 &model_id_for_dir(dir), 298 &config_json, 299 generation_json.as_deref(), 300 ) 301 .map_err(|e| format!("{}: {e}", config_path.display())) 302 } 303 304 #[cfg(test)] 305 mod tests { 306 use super::*; 307 use crate::checkpoint::{llama_catalog, tinyllama_catalog}; 308 309 /// TinyLlama-1.1B-Chat-v1.0 config.json, verbatim. 310 const TINYLLAMA_CONFIG: &str = r#"{ 311 "architectures": ["LlamaForCausalLM"], "attention_bias": false, "bos_token_id": 1, 312 "eos_token_id": 2, "hidden_act": "silu", "hidden_size": 2048, "initializer_range": 0.02, 313 "intermediate_size": 5632, "max_position_embeddings": 2048, "model_type": "llama", 314 "num_attention_heads": 32, "num_hidden_layers": 22, "num_key_value_heads": 4, 315 "pretraining_tp": 1, "rms_norm_eps": 1e-05, "rope_scaling": null, "rope_theta": 10000.0, 316 "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.35.0", 317 "use_cache": true, "vocab_size": 32000 318 }"#; 319 320 /// unsloth/Llama-3.2-1B-Instruct config.json and generation_config.json, verbatim. 321 const LLAMA32_1B_CONFIG: &str = r#"{ 322 "architectures": ["LlamaForCausalLM"], "attention_bias": false, "attention_dropout": 0.0, 323 "bos_token_id": 128000, "eos_token_id": 128009, "head_dim": 64, "hidden_act": "silu", 324 "hidden_size": 2048, "initializer_range": 0.02, "intermediate_size": 8192, 325 "max_position_embeddings": 131072, "mlp_bias": false, "model_type": "llama", 326 "num_attention_heads": 32, "num_hidden_layers": 16, "num_key_value_heads": 8, 327 "pad_token_id": 128004, "pretraining_tp": 1, "rms_norm_eps": 1e-05, 328 "rope_scaling": {"factor": 32.0, "high_freq_factor": 4.0, "low_freq_factor": 1.0, 329 "original_max_position_embeddings": 8192, "rope_type": "llama3"}, 330 "rope_theta": 500000.0, "tie_word_embeddings": true, "torch_dtype": "bfloat16", 331 "transformers_version": "4.52.0.dev0", "unsloth_fixed": true, "use_cache": true, 332 "vocab_size": 128256 333 }"#; 334 const LLAMA32_1B_GENERATION: &str = r#"{"bos_token_id": 128000, "do_sample": true, 335 "eos_token_id": [128001, 128008, 128009], "max_length": 131072, "pad_token_id": 128004, 336 "temperature": 0.6, "top_p": 0.9, "transformers_version": "4.52.0.dev0"}"#; 337 338 #[test] 339 fn tinyllama_config_json_reproduces_the_hard_wired_config_and_catalog() { 340 let from_json = model_config_from_hf_json( 341 "TinyLlama/TinyLlama-1.1B-Chat-v1.0", 342 TINYLLAMA_CONFIG, 343 Some( 344 r#"{"bos_token_id": 1, "eos_token_id": 2, "max_length": 2048, "pad_token_id": 0}"#, 345 ), 346 ) 347 .unwrap(); 348 let wired = ModelConfig::tinyllama_1_1b(); 349 // Every architecture field equal; the stop set comes from the file (EOS 2) where the 350 // hard-wired config keeps the legacy backend set. 351 assert_eq!( 352 ModelConfig { 353 eos_token_ids: Vec::new(), 354 qk_norm: false, 355 ..from_json.clone() 356 }, 357 wired 358 ); 359 assert_eq!(from_json.eos_token_ids, vec![2]); 360 assert_eq!(llama_catalog(&from_json), tinyllama_catalog()); 361 assert_eq!(llama_catalog(&wired), tinyllama_catalog()); 362 assert_eq!(from_json.rope(), aien_abi_core::RopeParams::plain(10000.0)); 363 } 364 365 #[test] 366 fn llama32_1b_config_has_tied_head_llama3_rope_and_three_stop_ids() { 367 let c = 368 model_config_from_hf_json("l", LLAMA32_1B_CONFIG, Some(LLAMA32_1B_GENERATION)).unwrap(); 369 assert_eq!( 370 (c.num_layers, c.num_heads, c.num_kv_heads, c.head_dim), 371 (16, 32, 8, 64) 372 ); 373 assert_eq!( 374 (c.hidden_dim, c.intermediate_dim, c.vocab_size), 375 (2048, 8192, 128256) 376 ); 377 assert!(c.tie_word_embeddings); 378 assert_eq!(c.eos_token_ids, vec![128001, 128008, 128009]); 379 assert_eq!( 380 c.rope_scaling, 381 Some(Llama3RopeScaling { 382 factor: 32.0, 383 low_freq_factor: 1.0, 384 high_freq_factor: 4.0, 385 original_max_position_embeddings: 8192, 386 }) 387 ); 388 let catalog = llama_catalog(&c); 389 assert_eq!(catalog.len(), 2 + 9 * 16); 390 assert!(catalog.iter().all(|(n, _)| n != "lm_head.weight")); 391 let shape = |name: &str| catalog.iter().find(|(n, _)| n == name).unwrap().1.clone(); 392 assert_eq!(shape("model.embed_tokens.weight"), vec![128256, 2048]); 393 assert_eq!( 394 shape("model.layers.15.self_attn.k_proj.weight"), 395 vec![512, 2048] 396 ); 397 assert_eq!( 398 shape("model.layers.0.mlp.down_proj.weight"), 399 vec![2048, 8192] 400 ); 401 // Without generation_config.json the config.json eos is used. 402 let c2 = model_config_from_hf_json("l", LLAMA32_1B_CONFIG, None).unwrap(); 403 assert_eq!(c2.eos_token_ids, vec![128009]); 404 } 405 406 /// Expected inverse frequencies for Llama-3.2-1B (theta 500000, head_dim 64, llama3 407 /// factor 32, low 1, high 4, original 8192), computed independently in f64 outside the 408 /// repository from the transformers `_compute_llama3_parameters` formula. 409 const LLAMA32_1B_INV_FREQ: [f64; 32] = [ 410 1.0, 411 0.`6636012376960885`, 412 0.`44036660267178046`, 413 0.`2922278225730151`, 414 0.`19392274474868576`, 415 0.`12868737343265052`, 416 0.`08539710028576561`, 417 0.`056669621445291044`, 418 0.`03760603093086393`, 419 0.`024955408670558694`, 420 0.`016560440080994446`, 421 0.`010989528534539826`, 422 0.`0072926647372171085`, 423 0.`004839421345719893`, 424 0.`0032114459947525913`, 425 0.`001290547928209264`, 426 0.`00042955679655936815`, 427 9.`70828780262767e`-05, 428 1.`9461638184831125e`-05, 429 1.`291476718704739e`-05, 430 8.`570255489881478e`-06, 431 5.`687232150457046e`-06, 432 3.`7740542941082826e`-06, 433 2.`5044671007024935e`-06, 434 1.`661967467795309e`-06, 435 1.`102883668639601e`-06, 436 7.`318749675440419e`-07, 437 4.`856731343010108e`-07, 438 3.`2229329303788936e`-07, 439 2.`138742281610915e`-07, 440 1.`4192720251899592e`-07, 441 9.`418306725434909e`-08, 442 ]; 443 444 #[test] 445 fn llama3_rope_inv_freq_matches_independent_values() { 446 let c = 447 model_config_from_hf_json("l", LLAMA32_1B_CONFIG, Some(LLAMA32_1B_GENERATION)).unwrap(); 448 let got = c.rope().inv_freqs(64); 449 assert_eq!(got.len(), 32); 450 for (i, (g, want)) in got.iter().zip(LLAMA32_1B_INV_FREQ).enumerate() { 451 assert!( 452 ((g - want) / want).abs() < 1e-12, 453 "inv_freq[{i}] = {g}, expected {want}" 454 ); 455 } 456 // The three bands: high frequencies kept, low divided by 32, the middle smoothed. 457 let plain = aien_abi_core::RopeParams::plain(500000.0).inv_freqs(64); 458 assert_eq!(got[14], plain[14]); 459 assert_eq!(got[31], plain[31] / 32.0); 460 assert!(got[16] < plain[16] && got[16] > plain[16] / 32.0); 461 assert_eq!(got[18], plain[18] / 32.0); 462 } 463 464 #[test] 465 fn unsupported_models_are_refused_by_name() { 466 let qwen = LLAMA32_1B_CONFIG.replace("LlamaForCausalLM", "Qwen2ForCausalLM"); 467 let err = model_config_from_hf_json("q", &qwen, None).unwrap_err(); 468 assert!(err.contains("Qwen2ForCausalLM"), "{err}"); 469 470 let yarn = LLAMA32_1B_CONFIG.replace("\"llama3\"", "\"yarn\""); 471 let err = model_config_from_hf_json("y", &yarn, None).unwrap_err(); 472 assert!(err.contains("yarn"), "{err}"); 473 474 let bias = 475 LLAMA32_1B_CONFIG.replace("\"attention_bias\": false", "\"attention_bias\": true"); 476 assert!(model_config_from_hf_json("b", &bias, None).is_err()); 477 478 let gelu = LLAMA32_1B_CONFIG.replace("\"silu\"", "\"gelu\""); 479 assert!(model_config_from_hf_json("g", &gelu, None) 480 .unwrap_err() 481 .contains("gelu")); 482 483 let default_rope = LLAMA32_1B_CONFIG.replace("\"llama3\"", "\"default\""); 484 let c = model_config_from_hf_json("d", &default_rope, None).unwrap(); 485 assert_eq!(c.rope_scaling, None); 486 } 487 488 /// HuggingFaceTB/SmolLM2-1.7B-Instruct config.json at revision `31b70e2e869a`, verbatim 489 /// (sha256 `994f50b16abb4ae00880baefe03c10260b5bd608d2bf586f7056ca05a534feea`), and its 490 /// generation_config.json (sha256 `87b916ed`...a013). 491 const SMOLLM2_17B_CONFIG: &str = r#"{ 492 "architectures": [ 493 "LlamaForCausalLM" 494 ], 495 "attention_bias": false, 496 "attention_dropout": 0.0, 497 "bos_token_id": 1, 498 "eos_token_id": 2, 499 "hidden_act": "silu", 500 "hidden_size": 2048, 501 "initializer_range": 0.02, 502 "intermediate_size": 8192, 503 "max_position_embeddings": 8192, 504 "mlp_bias": false, 505 "model_type": "llama", 506 "num_attention_heads": 32, 507 "num_hidden_layers": 24, 508 "num_key_value_heads": 32, 509 "pad_token_id": 2, 510 "pretraining_tp": 1, 511 "rms_norm_eps": 1e-05, 512 "rope_scaling": null, 513 "rope_theta": 130000, 514 "tie_word_embeddings": true, 515 "torch_dtype": "bfloat16", 516 "transformers_version": "4.42.3", 517 "transformers.js_config": { 518 "dtype": "q4", 519 "kv_cache_dtype": { 520 "q4f16": "float16", 521 "fp16": "float16" 522 }, 523 "use_external_data_format": { 524 "model.onnx": true, 525 "model_fp16.onnx": true 526 } 527 }, 528 "use_cache": true, 529 "vocab_size": 49152 530 } 531 "#; 532 const SMOLLM2_17B_GENERATION: &str = r#"{ 533 "_from_model_config": true, 534 "bos_token_id": 1, 535 "eos_token_id": 2, 536 "pad_token_id": 2, 537 "transformers_version": "4.42.3" 538 } 539 "#; 540 541 #[test] 542 fn smollm2_config_is_full_mha_tied_plain_rope() { 543 let c = model_config_from_hf_json("s", SMOLLM2_17B_CONFIG, Some(SMOLLM2_17B_GENERATION)) 544 .unwrap(); 545 // 32 KV heads = 32 query heads: no GQA sharing (group size 1). 546 assert_eq!( 547 (c.num_layers, c.num_heads, c.num_kv_heads, c.head_dim), 548 (24, 32, 32, 64) 549 ); 550 assert_eq!( 551 (c.hidden_dim, c.intermediate_dim, c.vocab_size), 552 (2048, 8192, 49152) 553 ); 554 assert_eq!(c.max_sequence_length, 8192); 555 assert_eq!(c.rms_norm_eps, 1e-5); 556 assert!(c.tie_word_embeddings); 557 assert_eq!(c.eos_token_ids, vec![2]); 558 // "rope_theta": 130000 is a JSON integer; rope_scaling null is plain rope. 559 assert_eq!(c.rope_scaling, None); 560 assert_eq!(c.rope(), aien_abi_core::RopeParams::plain(130000.0)); 561 let catalog = llama_catalog(&c); 562 // 218 tensors in the published model.safetensors: embed + norm + 9 per layer. 563 assert_eq!(catalog.len(), 2 + 9 * 24); 564 assert!(catalog.iter().all(|(n, _)| n != "lm_head.weight")); 565 let shape = |name: &str| catalog.iter().find(|(n, _)| n == name).unwrap().1.clone(); 566 assert_eq!(shape("model.embed_tokens.weight"), vec![49152, 2048]); 567 assert_eq!( 568 shape("model.layers.23.self_attn.k_proj.weight"), 569 vec![2048, 2048] 570 ); 571 assert_eq!( 572 shape("model.layers.0.self_attn.v_proj.weight"), 573 vec![2048, 2048] 574 ); 575 assert_eq!( 576 shape("model.layers.0.mlp.down_proj.weight"), 577 vec![2048, 8192] 578 ); 579 } 580 581 #[test] 582 fn hf_cache_snapshot_dirs_get_the_repo_id() { 583 let dir = Path::new("/c/hub/models--unsloth--Llama-3.2-1B-Instruct/snapshots/5a8a"); 584 assert_eq!(model_id_for_dir(dir), "unsloth/Llama-3.2-1B-Instruct"); 585 assert_eq!( 586 model_id_for_dir(Path::new("/m/TinyLlama-1.1B-Chat-v1.0")), 587 "TinyLlama-1.1B-Chat-v1.0" 588 ); 589 } 590 }