From 5630a84abc71ead5f8bc0c53dda38c9616f16c65 Mon Sep 17 00:00:00 2001 From: psv666 <2693925048@qq.com> Date: Mon, 23 Nov 2026 13:32:30 +0800 Subject: [PATCH] Add experimental Intern-Decision-4B text worker --- Cargo.lock | 16 + Cargo.toml | 2 +- recipe/intern/README.md | 94 +++++ src/models/intern/LICENSE | 201 +++++++++++ src/models/intern/README.md | 44 +++ src/models/intern/native/Cargo.toml | 26 ++ src/models/intern/native/src/engine.rs | 53 +++ src/models/intern/native/src/executor.rs | 182 ++++++++++ src/models/intern/native/src/finishing.rs | 141 ++++++++ src/models/intern/native/src/lib.rs | 4 + src/models/intern/native/src/main.rs | 96 ++++++ src/models/intern/native/src/processing.rs | 384 +++++++++++++++++++++ src/models/qwen3_5/native/src/model.rs | 118 +++++++ tests/intern/contract.rs | 102 ++++++ tests/intern/prefill.rs | 104 ++++++ tests/qwen3_5/readout.rs | 52 +++ 16 files changed, 1618 insertions(+), 1 deletion(-) create mode 100644 recipe/intern/README.md create mode 100644 src/models/intern/LICENSE create mode 100644 src/models/intern/README.md create mode 100644 src/models/intern/native/Cargo.toml create mode 100644 src/models/intern/native/src/engine.rs create mode 100644 src/models/intern/native/src/executor.rs create mode 100644 src/models/intern/native/src/finishing.rs create mode 100644 src/models/intern/native/src/lib.rs create mode 100644 src/models/intern/native/src/main.rs create mode 100644 src/models/intern/native/src/processing.rs create mode 100644 tests/intern/contract.rs create mode 100644 tests/intern/prefill.rs diff --git a/Cargo.lock b/Cargo.lock index 2d985b1c..d36033f2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1216,6 +1216,22 @@ dependencies = [ "tokio", ] +[[package]] +name = "omni-intern-native" +version = "0.2.2" +dependencies = [ + "anyhow", + "axum", + "half", + "memmap2", + "omni-qwen3-5-native", + "omni-runtime", + "safetensors 0.8.0", + "serde_json", + "tokenizers 0.22.2", + "tokio", +] + [[package]] name = "omni-jemm-native" version = "0.2.2" diff --git a/Cargo.toml b/Cargo.toml index 1ebf8e22..d3391fd3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,3 +1,3 @@ [workspace] -members = ["src/frontend", "src/runtime", "src/models/clm", "src/models/cua_s1/native", "src/models/qwen3_5/native", "src/models/open_jev/native", "src/models/jev_vl/native", "src/models/omnijev/native", "src/models/laya", "src/backends/cuda", "src/models/decider/native", "src/models/jemm/native", "src/models/startlux/native", "src/models/clef/native", "src/models/kev/native"] +members = ["src/frontend", "src/runtime", "src/models/clm", "src/models/cua_s1/native", "src/models/qwen3_5/native", "src/models/open_jev/native", "src/models/jev_vl/native", "src/models/omnijev/native", "src/models/laya", "src/backends/cuda", "src/models/decider/native", "src/models/jemm/native", "src/models/startlux/native", "src/models/clef/native", "src/models/kev/native", "src/models/intern/native"] resolver = "3" diff --git a/recipe/intern/README.md b/recipe/intern/README.md new file mode 100644 index 00000000..7f03aaae --- /dev/null +++ b/recipe/intern/README.md @@ -0,0 +1,94 @@ +# Intern-Decision-4B native text candidate + +The draft implements Choice, Noul and Score for text and ordered JSON state. +On one NVIDIA L20 (sm_89), all 23 frozen text decisions agreed with the fixed +checkpoint HF oracle. Two fields exceeded the approved probability and +confidence error of `0.01`. Keep this worker experimental until the full +numerical gate passes. + +## Run the candidate locally + +Run from the repository root on Linux with Rust, CUDA 12.8 and a compatible +NVIDIA GPU. The checkpoint requires several GiB of storage and the worker +loads both the full 4B language weights and a separate BF16 vocabulary matrix. +The commands below assume a downloaded, immutable +[`internlm/Intern-Decision-4B@38c9dafbbef52dd04bae943c0c6ac918419adfd5`](https://huggingface.co/internlm/Intern-Decision-4B/tree/38c9dafbbef52dd04bae943c0c6ac918419adfd5) +snapshot. The worker reads the original safetensors and tokenizer directly. + +```sh +hf download internlm/Intern-Decision-4B \ + --revision 38c9dafbbef52dd04bae943c0c6ac918419adfd5 \ + --local-dir "$PWD/checkpoints/intern-decision-4b" +cargo build --release --locked -p omni-intern-native -p omni-jev +bash src/backends/cuda/qwen3_5/build.sh "$PWD/target/intern-cuda" 89 + +INTERN_CHECKPOINT="$PWD/checkpoints/intern-decision-4b" \ +INTERN_CUDA_LIB="$PWD/target/intern-cuda/libqwen3_5_cuda.so" \ +INTERN_LISTEN=127.0.0.1:8000 \ + ./target/release/omni-intern-native +``` + +Start the [Rust frontend](../../src/frontend/README.md) in a second shell in +the repository root. + +```sh +OMNI_JEV_BIND=127.0.0.1:8080 OMNI_JEV_BACKEND_URL=http://127.0.0.1:8000 \ + ./target/release/omni-jev + +curl -fsS http://127.0.0.1:8080/health +curl -fsS http://127.0.0.1:8080/v1/systemone \ + -H 'Content-Type: application/json' \ + --data-binary '{ + "state": {"message": "I was billed twice. Please refund the duplicate charge."}, + "questions": { + "route": {"type": "choice", "criteria": {"billing": "Billing", "technical": "Technical support"}}, + "refund": {"type": "noul", "instructions": "Is a refund requested?"}, + "urgency": {"type": "score", "criteria": {"0": "Low", "2": "Medium", "10": "High"}} + } + }' +``` + +Readiness follows a completed warmup. The worker accepts 1–16 ordered +questions and 1–62 options for Choice and Score. Score array criteria assign +levels `0..N-1`. The processor rejects nonempty media and inputs with more +than 8192 final tokens, and the worker limits JSON bodies to 2 MiB. Malformed +JSON returns 400, invalid decision or media inputs return 422, and length +overflow returns 413. The response carries field-count usage and a native +`rust-cuda` backend identity. + +## Validation + +```sh +cargo test --locked -p omni-intern-native +# With the immutable oracle text export, the pinned checkpoint and the library +INTERN_FROZEN_INPUTS=/path/to/frozen-text.json \ +INTERN_PREFILL_OUT=/path/to/native-prefill.json \ +INTERN_CHECKPOINT="$PWD/checkpoints/intern-decision-4b" \ +INTERN_CUDA_LIB="$PWD/target/intern-cuda/libqwen3_5_cuda.so" \ + cargo test --locked --release -p omni-intern-native --test prefill frozen_prefill -- --ignored +``` + +The opt-in test expects a JSON array of records with `id`, `request`, +`prompt`, `ids`, `readout` and `fields` from the fixed HF capture. Each +field lists `field`, ordered `values` and `symbol_ids`. It checks all six +frozen text inputs exactly and writes the selected hidden rows plus the +62 symbol logits per row. Compare only the legal symbols per field against +the captured raw logits, and compare each typed result against the fixed +HF response. The uncalibrated reference is the official CUDA finishing +replay of the saved logits. + +| L20 comparison, 6 requests / 23 fields | Default fixed prefill control | Eager framework-style candidate | Limit | +| --- | ---: | ---: | ---: | +| Maximum absolute selected-logit difference | 0.1875 | 0.125 | 0.125 | +| Maximum absolute calibrated probability difference | 0.013008 | 0.011571 | 0.01 | +| Maximum absolute confidence difference | 0.013008 | 0.011193 | 0.01 | +| Maximum absolute Noul difference | 0.004976 | 0.004976 | 0.01 | +| Exact categorical decisions | 23/23 | 23/23 | 23/23 | + +Continuous Score met the per-field 1%-of-legend-range gate. The candidate +missed both probability and confidence gates for `field_10` and `field_13` +in the 16-field request. Neither run found a calibrated top-two margin of +0.02 or less. Real-weight near ties, extreme levels, image/video execution, +other checkpoint sizes, other hardware and performance remain outside this +qualification. See the [model contract](../../src/models/intern/README.md) +for execution and profile details. diff --git a/src/models/intern/LICENSE b/src/models/intern/LICENSE new file mode 100644 index 00000000..ec12195b --- /dev/null +++ b/src/models/intern/LICENSE @@ -0,0 +1,201 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026-2027 Shanghai AI Laboratory + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/src/models/intern/README.md b/src/models/intern/README.md new file mode 100644 index 00000000..292a2eae --- /dev/null +++ b/src/models/intern/README.md @@ -0,0 +1,44 @@ +# Intern-Decision-4B text candidate + +This native Rust/CUDA worker implements the text decision contract of +[`internlm/Intern-Decision-4B`](https://huggingface.co/internlm/Intern-Decision-4B/tree/38c9dafbbef52dd04bae943c0c6ac918419adfd5). +The worker is experimental. Its frozen-corpus L20 qualification is blocked by +calibrated probability and confidence drift. See the [recipe and measured +limits](../../../recipe/intern/README.md). + +- `processing.rs` renders ordered JSON state and the Choice, Noul and Score + schema using the pinned checkpoint's text template. It assigns the 62 + one-token symbols `A–Z a–z 0–9` and takes the position immediately before + each `` marker. It rejects requests beyond 8192 complete input + tokens and rejects nonempty media before dispatch. +- `executor.rs` runs one causal prefill over the whole prompt. The shared + Qwen executor returns selected final-norm BF16 rows widened losslessly + to FP32. A model-owned full vocabulary CUDA projection reuses the + checkpoint's tied BF16 `[248320, 2560]` embedding. Only the legal + symbol logits for each field enter response finishing. The tied weight + is presently uploaded a second time for the vocabulary head. +- `finishing.rs` applies restricted FP32 softmax, then the release's FP64 + log-probability temperature scaling at `1.99241824`. It keeps field and + option order, uses lexical order for exact maxima ties and computes Noul + as `P(yes)` and Score as a probability-weighted expectation. Both + `usage.output_tokens` and `usage.decision_count` count scored fields. + Each request generates zero tokens. +- The shared FIFO scheduler serializes access to one executor and all its + device buffers. The executor completes device work before releasing + admission, including when a client disconnects after dispatch. Hidden + rows and responses are owned by the request. Each request has one batch-one + execution and no retained prefix or generation state. + +The candidate uses the shared merged 4B eager causal profile and existing +CUDA framework-style norms, attention and FLA-style GDN. The fixed reference +used Torch 2.9.1+cu128, Transformers 5.14.1, BF16/SDPA, FLA/fla-core +0.4.2, Triton 3.5.1 and Torch convolution. The candidate's GDN has not been +established to reproduce that FLA build on sm_89. + +Prompt and calibration behavior are derived from the pinned checkpoint's +[`inference.py`](https://huggingface.co/internlm/Intern-Decision-4B/blob/38c9dafbbef52dd04bae943c0c6ac918419adfd5/inference.py) +and its bundled [Apache-2.0 license](https://huggingface.co/internlm/Intern-Decision-4B/blob/38c9dafbbef52dd04bae943c0c6ac918419adfd5/LICENSE). +The upstream [InternLM source](https://github.com/InternLM/Intern-Decision/tree/a7b01e276cd5e18bae640be925e685ba6f5159ad) +and [Qwen license](https://huggingface.co/internlm/Intern-Decision-4B/blob/38c9dafbbef52dd04bae943c0c6ac918419adfd5/LICENSE-QWEN) +apply to their respective components. Checkpoint files are loaded from the +user-supplied snapshot and are distributed by the upstream publisher. diff --git a/src/models/intern/native/Cargo.toml b/src/models/intern/native/Cargo.toml new file mode 100644 index 00000000..35b86c3b --- /dev/null +++ b/src/models/intern/native/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "omni-intern-native" +version = "0.2.2" +edition = "2024" +publish = false +description = "Native text decision worker for Intern-Decision-4B" + +[dependencies] +anyhow = "1.0.100" +axum = "0.8.8" +half = "2.7.1" +memmap2 = "0.9.9" +omni-qwen3-5-native = { path = "../../qwen3_5/native" } +omni-runtime = { path = "../../../runtime" } +safetensors = "0.8.0" +serde_json = { version = "1.0.149", features = ["float_roundtrip", "preserve_order"] } +tokenizers = { version = "=0.22.2", default-features = false, features = ["onig"] } +tokio = { version = "1.49.0", features = ["macros", "net", "rt-multi-thread"] } + +[[test]] +name = "contract" +path = "../../../../tests/intern/contract.rs" + +[[test]] +name = "prefill" +path = "../../../../tests/intern/prefill.rs" diff --git a/src/models/intern/native/src/engine.rs b/src/models/intern/native/src/engine.rs new file mode 100644 index 00000000..ba738c3e --- /dev/null +++ b/src/models/intern/native/src/engine.rs @@ -0,0 +1,53 @@ +use std::{ + path::Path, + sync::{Arc, Mutex}, + time::Instant, +}; + +use anyhow::{Result, anyhow}; +use omni_runtime::SerialScheduler; +use serde_json::Value; + +use crate::{executor::Executor, finishing, processing::Processor}; + +pub struct Engine { + processor: Processor, + scheduler: SerialScheduler, + executor: Arc>, +} + +impl Engine { + pub async fn load(checkpoint: &Path, library: &Path) -> Result { + let checkpoint = checkpoint.to_path_buf(); + let library = library.to_path_buf(); + let (processor, executor) = tokio::task::spawn_blocking(move || { + let processor = Processor::load(&checkpoint.join("tokenizer.json"))?; + let executor = Executor::load(&checkpoint, &library)?; + Ok::<_, anyhow::Error>((processor, executor)) + }) + .await??; + Ok(Self { + processor, + executor: Arc::new(Mutex::new(executor)), + scheduler: SerialScheduler::default(), + }) + } + + pub async fn decide(&self, body: &[u8]) -> Result { + let prepared = self.processor.prepare(body)?; + let symbols = self.processor.symbol_ids.clone(); + let executor = Arc::clone(&self.executor); + self.scheduler + .run(move || { + let mut executor = executor + .lock() + .map_err(|_| anyhow!("Intern executor is poisoned"))?; + let start = Instant::now(); + let hidden = executor.hidden(&prepared.ids, &prepared.readout)?; + let logits = executor.project(&hidden, &symbols)?; + let inference_ms = start.elapsed().as_secs_f64() * 1000.0; + finishing::finish(&prepared.fields, &logits, prepared.ids.len(), inference_ms) + }) + .await + } +} diff --git a/src/models/intern/native/src/executor.rs b/src/models/intern/native/src/executor.rs new file mode 100644 index 00000000..bda8190a --- /dev/null +++ b/src/models/intern/native/src/executor.rs @@ -0,0 +1,182 @@ +//! One full causal Qwen prefill, then the checkpoint's tied BF16 vocabulary head. + +use std::{ffi::c_void, fs::File, path::Path, ptr::NonNull}; + +use anyhow::{Context, Result, ensure}; +use half::bf16; +use omni_qwen3_5_native::{ + cuda::{self, DeviceBuffer, Stream}, + model::Model, +}; +use serde_json::Value; + +const EMBED: &str = "model.language_model.embed_tokens.weight"; +const HIDDEN: usize = 2560; +const VOCAB: usize = 248_320; +const MAX_FIELDS: usize = 16; + +pub struct Executor { + model: Model, + head: VocabularyHead, +} + +impl Executor { + pub fn load(checkpoint: &Path, library: &Path) -> Result { + let mut model = Model::load_with_graph(checkpoint, library, false)?; + ensure!( + model.cfg.image_token_id == Some(248056), + "checkpoint does not match Intern-Decision-4B" + ); + model.enable_framework_text_4b()?; + Ok(Self { + model, + head: VocabularyHead::load(checkpoint)?, + }) + } + + pub fn hidden(&mut self, ids: &[u32], rows: &[usize]) -> Result>> { + self.model.forward_framework_text_readout(ids, rows) + } + + pub fn project(&mut self, hidden: &[Vec], symbol_ids: &[u32]) -> Result>> { + self.head.project(hidden, symbol_ids) + } +} + +struct Gemm(NonNull); + +// SAFETY: the handle moves between threads with its owner and is never used +// concurrently. Its work is completed before the owner releases admission. +unsafe impl Send for Gemm {} + +impl Drop for Gemm { + fn drop(&mut self) { + // SAFETY: this handle belongs exclusively to the head. + unsafe { (cuda::api().cs1_gemm_destroy)(self.0.as_ptr()) } + } +} + +struct VocabularyHead { + gemm: Gemm, + stream: HeadStream, + weight: DeviceBuffer, + hidden: DeviceBuffer, + output: DeviceBuffer, +} + +struct HeadStream(Stream); + +impl Drop for HeadStream { + fn drop(&mut self) { + // SAFETY: the head owns this idle stream. + unsafe { (cuda::api().cs1_stream_destroy)(self.0) }; + } +} + +impl VocabularyHead { + fn load(checkpoint: &Path) -> Result { + let config: Value = serde_json::from_reader(File::open(checkpoint.join("config.json"))?)?; + ensure!( + config["tie_word_embeddings"] == true + && config["text_config"]["tie_word_embeddings"] == true + && config["text_config"]["vocab_size"] == VOCAB, + "expected the tied Intern vocabulary head" + ); + let index: Value = + serde_json::from_reader(File::open(checkpoint.join("model.safetensors.index.json"))?)?; + let weights = index["weight_map"] + .as_object() + .context("missing checkpoint weight map")?; + ensure!( + !weights.keys().any(|name| name.ends_with("lm_head.weight")), + "unexpected independent vocabulary head" + ); + let shard = weights.get(EMBED).and_then(Value::as_str).context(EMBED)?; + let file = File::open(checkpoint.join(shard))?; + // SAFETY: the checkpoint is immutable for the duration of loading. + let map = unsafe { memmap2::Mmap::map(&file)? }; + let tensors = safetensors::SafeTensors::deserialize(&map)?; + let embedding = tensors.tensor(EMBED)?; + ensure!( + embedding.dtype() == safetensors::Dtype::BF16 && embedding.shape() == [VOCAB, HIDDEN], + "expected BF16 embedding [{VOCAB}, {HIDDEN}]" + ); + let stream = HeadStream(cuda::new_stream()?); + let weight = DeviceBuffer::new(embedding.data().len())?; + // SAFETY: the exact-size buffer remains live, and upload synchronizes the source. + unsafe { cuda::upload(weight.at(0), embedding.data(), stream.0)? }; + let reference = cuda::api().language_reference()?; + // SAFETY: the new handle and workspace are private to this head. + let gemm = Gemm( + NonNull::new(unsafe { (reference.gemm_create)(32 << 20) }) + .context("reference vocabulary GEMM allocation failed")?, + ); + Ok(Self { + gemm, + stream, + weight, + hidden: DeviceBuffer::new(MAX_FIELDS * HIDDEN * 2)?, + output: DeviceBuffer::new(MAX_FIELDS * VOCAB * 2)?, + }) + } + + fn project(&mut self, hidden: &[Vec], symbol_ids: &[u32]) -> Result>> { + ensure!( + (1..=MAX_FIELDS).contains(&hidden.len()), + "invalid field count" + ); + ensure!( + hidden.iter().all(|row| row.len() == HIDDEN), + "invalid hidden width" + ); + ensure!( + symbol_ids.iter().all(|&id| (id as usize) < VOCAB), + "symbol ID outside vocabulary" + ); + cuda::set_device(0)?; + let inputs: Vec = hidden + .iter() + .flatten() + .flat_map(|&value| bf16::from_f32(value).to_le_bytes()) + .collect(); + let mut logits = vec![0; hidden.len() * VOCAB * 2]; + let stream = self.stream.0; + // SAFETY: all matrix sizes fit the model-owned allocations and share the stream. + let result = unsafe { + cuda::upload(self.hidden.at(0), &inputs, stream)?; + cuda::check( + (cuda::api().cs1_gemm)( + self.gemm.0.as_ptr(), + self.hidden.at(0), + self.weight.at(0), + self.output.at(0), + hidden.len() as i32, + VOCAB as i32, + HIDDEN as i32, + VOCAB as i32, + stream, + ), + "Intern vocabulary GEMM", + ) + .and_then(|()| cuda::download(&mut logits, self.output.at(0), stream)) + }; + if result.is_err() { + let _ = cuda::synchronize(stream); + } + result?; + Ok(logits + .as_chunks::<{ VOCAB * 2 }>() + .0 + .iter() + .map(|row| { + symbol_ids + .iter() + .map(|&id| { + let index = 2 * id as usize; + bf16::from_le_bytes([row[index], row[index + 1]]).to_f32() + }) + .collect() + }) + .collect()) + } +} diff --git a/src/models/intern/native/src/finishing.rs b/src/models/intern/native/src/finishing.rs new file mode 100644 index 00000000..26eeded1 --- /dev/null +++ b/src/models/intern/native/src/finishing.rs @@ -0,0 +1,141 @@ +//! Restricted FP32 softmax and the released FP64 temperature calibration. + +use anyhow::{Context, Result, ensure}; +use serde_json::{Map, Value, json}; + +use crate::processing::{Field, Kind, score_level}; + +pub const TEMPERATURE: f64 = 1.99241824; +pub const MODEL_NAME: &str = "Intern-Decision-4B"; +pub const BACKEND: &str = "rust-cuda"; + +pub fn probabilities(logits: &[f32]) -> Result<(Vec, Vec)> { + ensure!( + !logits.is_empty() && logits.iter().all(|v| v.is_finite()), + "invalid logits" + ); + let max = logits.iter().copied().reduce(f32::max).unwrap(); + let weights: Vec = logits.iter().map(|&x| (x - max).exp()).collect(); + let sum: f32 = weights.iter().sum(); + let raw: Vec = weights.into_iter().map(|w| f64::from(w / sum)).collect(); + let logs: Vec = raw.iter().map(|p| p.ln()).collect(); + let max = logs.iter().copied().reduce(f64::max).unwrap(); + let weights: Vec = logs + .into_iter() + .map(|p| ((p - max) / TEMPERATURE).exp()) + .collect(); + let sum: f64 = weights.iter().sum(); + Ok((raw, weights.into_iter().map(|w| w / sum).collect())) +} + +pub fn finish( + fields: &[Field], + rows: &[Vec], + input_tokens: usize, + inference_ms: f64, +) -> Result { + ensure!( + fields.len() == rows.len(), + "field and readout counts differ" + ); + ensure!( + inference_ms.is_finite() && inference_ms >= 0.0, + "invalid inference timing" + ); + let mut answers = Map::new(); + for (field, row) in fields.iter().zip(rows) { + let logits = row + .get(..field.options.len()) + .context("missing legal logits")?; + let (raw, calibrated) = probabilities(logits)?; + let decision = |probabilities: &[f64]| { + field + .options + .iter() + .zip(probabilities) + .enumerate() + .min_by(|(_, ((left, _), lp)), (_, ((right, _), rp))| { + rp.total_cmp(lp).then_with(|| left.cmp(right)) + }) + .map(|(index, _)| index) + .unwrap() + }; + let best = decision(&calibrated); + ensure!( + best == decision(&raw), + "temperature calibration changed the decision" + ); + let value = &field.options[best].0; + let probabilities: Map = field + .options + .iter() + .zip(&calibrated) + .map(|((label, _), &p)| (label.clone(), json!(p))) + .collect(); + let mut answer = Map::new(); + let kind = match field.kind { + Kind::Choice => "choice", + Kind::Noul => "noul", + Kind::Score => "score", + }; + answer.insert("type".into(), json!(kind)); + answer.insert("probabilities".into(), Value::Object(probabilities)); + answer.insert("confidence".into(), json!(calibrated[best])); + match field.kind { + Kind::Choice => { + answer.insert("choice".into(), json!(value)); + } + Kind::Noul => { + answer.insert("noul".into(), json!(calibrated[1])); + } + Kind::Score => { + let levels = field + .options + .iter() + .map(|(label, _)| score_level(label).context("malformed Score level")) + .collect::>>()?; + let legend: Map<_, _> = field + .options + .iter() + .map(|(label, description)| (label.clone(), json!(description))) + .collect(); + answer.insert("score".into(), json!(expectation(&levels, &calibrated))); + answer.insert("legend".into(), Value::Object(legend)); + } + } + answer.insert("source".into(), json!("local")); + answer.insert("decision".into(), json!(value)); + answers.insert(field.name.clone(), Value::Object(answer)); + } + Ok(json!({ + "answers": answers, + "usage": {"input_tokens": input_tokens, "output_tokens": fields.len(), "decision_count": fields.len()}, + "timing": {"inference_ms": (inference_ms * 100.0).round() / 100.0}, + "calibration": {"method": "temperature-scaling", "temperature": TEMPERATURE}, + "model": MODEL_NAME, + "backend": BACKEND + })) +} + +fn expectation(levels: &[f64], probabilities: &[f64]) -> f64 { + if let [level] = levels { + return *level; + } + let min = levels.iter().copied().reduce(f64::min).unwrap(); + let max = levels.iter().copied().reduce(f64::max).unwrap(); + let ordered: f64 = levels + .iter() + .zip(probabilities) + .map(|(level, p)| level * p) + .sum(); + if ordered.is_finite() { + return ordered.clamp(min, max); + } + let scale = min.abs().max(max.abs()); + let scaled: f64 = levels + .iter() + .zip(probabilities) + .map(|(level, p)| (level / scale) * p) + .sum(); + scaled.clamp(min / scale, max / scale) * scale +} diff --git a/src/models/intern/native/src/lib.rs b/src/models/intern/native/src/lib.rs new file mode 100644 index 00000000..b8ca7638 --- /dev/null +++ b/src/models/intern/native/src/lib.rs @@ -0,0 +1,4 @@ +pub mod engine; +pub mod executor; +pub mod finishing; +pub mod processing; diff --git a/src/models/intern/native/src/main.rs b/src/models/intern/native/src/main.rs new file mode 100644 index 00000000..8a1536e1 --- /dev/null +++ b/src/models/intern/native/src/main.rs @@ -0,0 +1,96 @@ +use std::{net::SocketAddr, path::PathBuf, sync::Arc}; + +use anyhow::{Context, Result}; +use axum::{ + Json, Router, + body::Bytes, + extract::{DefaultBodyLimit, State, rejection::BytesRejection}, + http::{HeaderMap, StatusCode}, + response::{IntoResponse, Response}, + routing::{get, post}, +}; +use omni_intern_native::{ + engine::Engine, + finishing::{BACKEND, MODEL_NAME}, + processing::RequestError, +}; +use omni_qwen3_5_native::cuda; +use serde_json::json; + +const WARMUP: &[u8] = br#"{"state":"The light is red.","questions":{"color":{"type":"choice","instructions":"Which color?","criteria":{"red":"Red","blue":"Blue"}}}}"#; +const MAX_BODY: usize = 2 << 20; + +fn error(status: StatusCode, message: &str) -> Response { + (status, Json(json!({"error": message}))).into_response() +} + +async fn systemone( + State(engine): State>, + headers: HeaderMap, + body: Result, +) -> Response { + let content_type = headers + .get("content-type") + .and_then(|value| value.to_str().ok()) + .unwrap_or_default() + .split(';') + .next() + .unwrap_or_default() + .trim(); + if !content_type.eq_ignore_ascii_case("application/json") { + return error( + StatusCode::UNSUPPORTED_MEDIA_TYPE, + "Content-Type must be application/json", + ); + } + let body = match body { + Ok(body) => body, + Err(err) => return error(err.status(), &err.body_text()), + }; + match engine.decide(&body).await { + Ok(result) => Json(result).into_response(), + Err(err) => { + if let Some(request) = err.downcast_ref::() { + return error( + StatusCode::from_u16(request.status).unwrap(), + &request.to_string(), + ); + } + eprintln!("Intern inference failed: {err:#}"); + error(StatusCode::INTERNAL_SERVER_ERROR, "model inference failed") + } + } +} + +#[tokio::main] +async fn main() -> Result<()> { + let checkpoint = std::env::var_os("INTERN_CHECKPOINT") + .map(PathBuf::from) + .context("set INTERN_CHECKPOINT to the pinned Intern-Decision-4B snapshot")?; + let library = std::env::var_os("INTERN_CUDA_LIB") + .map(PathBuf::from) + .map_or_else(cuda::default_library, Ok)?; + let address: SocketAddr = std::env::var("INTERN_LISTEN") + .unwrap_or_else(|_| "127.0.0.1:8000".into()) + .parse() + .context("invalid INTERN_LISTEN")?; + let engine = Arc::new(Engine::load(&checkpoint, &library).await?); + engine + .decide(WARMUP) + .await + .context("Intern warmup failed")?; + let app = Router::new() + .route( + "/health", + get(|| async { + Json(json!({"status": "ready", "model": MODEL_NAME, "backend": BACKEND})) + }), + ) + .route("/v1/systemone", post(systemone)) + .layer(DefaultBodyLimit::max(MAX_BODY)) + .with_state(engine); + let listener = tokio::net::TcpListener::bind(address).await?; + eprintln!("Intern listening on {address}"); + axum::serve(listener, app).await?; + Ok(()) +} diff --git a/src/models/intern/native/src/processing.rs b/src/models/intern/native/src/processing.rs new file mode 100644 index 00000000..a1183fb8 --- /dev/null +++ b/src/models/intern/native/src/processing.rs @@ -0,0 +1,384 @@ +//! Text-only specialization of the published Intern-Decision-4B prompt. + +use std::{fmt, path::Path}; + +use anyhow::{Result, anyhow, ensure}; +use omni_qwen3_5_native::json; +use serde_json::{Map, Value}; +use tokenizers::Tokenizer; + +pub const MAX_INPUT_TOKENS: usize = 8192; +pub const SYMBOLS: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; +const MARKER: &str = ""; +const MARKER_ID: u32 = 248077; +const SYSTEM: &str = "You are a careful decision assistant. Use the state and decision schema in the user message to make the requested decisions. For every field, choose exactly one answer symbol (e.g. A, B, C, ...) from its listed options and return one valid JSON object mapping each field name to its chosen symbol. Use the field names and symbols exactly as given. Do not include explanations, Markdown, or extra text."; +const RESERVED: [&str; 10] = [ + MARKER, + "<|im_start|>", + "<|im_end|>", + "<|vision_start|>", + "<|vision_end|>", + "<|image_pad|>", + "<|video_pad|>", + "<|endoftext|>", + "", + "", +]; + +#[derive(Debug)] +pub struct RequestError { + pub status: u16, + message: String, +} + +impl fmt::Display for RequestError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for RequestError {} + +fn invalid(message: impl Into) -> RequestError { + RequestError { + status: 422, + message: message.into(), + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Choice, + Noul, + Score, +} + +#[derive(Debug)] +pub struct Field { + pub name: String, + pub kind: Kind, + pub options: Vec<(String, String)>, +} + +pub struct Prepared { + pub prompt: String, + pub ids: Vec, + pub readout: Vec, + pub fields: Vec, +} + +pub struct Processor { + tokenizer: Tokenizer, + pub symbol_ids: Vec, +} + +impl Processor { + pub fn load(tokenizer: &Path) -> Result { + let tokenizer = Tokenizer::from_file(tokenizer).map_err(|e| anyhow!("{e}"))?; + ensure!( + tokenizer.token_to_id(MARKER) == Some(MARKER_ID), + "wrong Intern marker ID" + ); + let symbol_ids = SYMBOLS + .chars() + .map(|symbol| { + let ids = tokenizer + .encode(symbol.to_string(), false) + .map_err(|e| anyhow!("{e}"))?; + ensure!( + ids.len() == 1, + "answer symbol {symbol} must encode to one token" + ); + Ok(ids.get_ids()[0]) + }) + .collect::>>()?; + ensure!( + symbol_ids + .iter() + .copied() + .eq((32..58).chain(64..90).chain(15..25)), + "wrong Intern symbol IDs" + ); + Ok(Self { + tokenizer, + symbol_ids, + }) + } + + pub fn prepare(&self, raw: &[u8]) -> Result { + let request = json::parse(raw).map_err(|message| RequestError { + status: 400, + message, + })?; + let (prompt, fields) = compile(&request)?; + let encoded = self + .tokenizer + .encode(prompt.as_str(), false) + .map_err(|e| anyhow!("{e}"))?; + let ids = encoded.get_ids(); + if ids.len() > MAX_INPUT_TOKENS { + return Err(RequestError { + status: 413, + message: format!( + "input has {} tokens; limit is {MAX_INPUT_TOKENS}", + ids.len() + ), + } + .into()); + } + let readout = ids + .iter() + .enumerate() + .filter(|&(_, &id)| id == MARKER_ID) + .map(|(row, _)| row.checked_sub(1)) + .collect::>>() + .filter(|rows| rows.len() == fields.len()) + .ok_or_else(|| invalid("decision marker count or position mismatch"))?; + Ok(Prepared { + prompt, + ids: ids.to_vec(), + readout, + fields, + }) + } +} + +pub fn compile(request: &Map) -> Result<(String, Vec), RequestError> { + let state = request + .get("state") + .ok_or_else(|| invalid("state is required"))?; + for key in ["images", "image", "videos", "video", "media"] { + if request.get(key).is_some_and(nonempty) { + return Err(invalid("the Intern text worker does not accept media")); + } + } + let questions = request + .get("questions") + .and_then(Value::as_object) + .filter(|questions| (1..=16).contains(&questions.len())) + .ok_or_else(|| invalid("supply 1–16 questions"))?; + let mut fields = Vec::with_capacity(questions.len()); + let mut schema = Vec::new(); + let mut skeleton = Map::new(); + for (name, question) in questions { + if name.is_empty() { + return Err(invalid("question names must be nonempty")); + } + let kind = match question["type"].as_str() { + Some("choice") => Kind::Choice, + Some("noul") => Kind::Noul, + Some("score") => Kind::Score, + _ => return Err(invalid("question type must be choice, noul, or score")), + }; + let options = options(kind, &question["criteria"])?; + let instructions = question + .get("instructions") + .map(py_string) + .unwrap_or_default(); + schema.push(format!("{name}: {instructions}")); + for (symbol, (value, description)) in SYMBOLS.chars().zip(&options) { + schema.push(format!(" {symbol} = {value}: {description}")); + } + fields.push(Field { + name: name.clone(), + kind, + options, + }); + skeleton.insert(name.clone(), Value::String(MARKER.into())); + } + let state = pretty(state, 2, 0); + let schema = schema.join("\n"); + if RESERVED + .iter() + .any(|marker| state.contains(marker) || schema.contains(marker)) + { + return Err(invalid("reserved control marker in input")); + } + let skeleton = pretty(&Value::Object(skeleton), 4, 0); + let prompt = format!( + "<|im_start|>system\n{SYSTEM}<|im_end|>\n<|im_start|>user\nReturn one answer for every field using the supplied answer symbols.\n\n## State\n{state}\n## Decision schema\n{schema}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n{skeleton}<|im_end|>\n" + ); + Ok((prompt, fields)) +} + +fn nonempty(value: &Value) -> bool { + match value { + Value::Null => false, + Value::Bool(value) => *value, + Value::String(value) => !value.is_empty(), + Value::Array(value) => !value.is_empty(), + Value::Object(value) => !value.is_empty(), + Value::Number(value) => value.as_f64() != Some(0.0), + } +} + +fn options(kind: Kind, criteria: &Value) -> Result, RequestError> { + if kind == Kind::Noul { + let description = |aliases: &[&str], default: &str| { + criteria + .as_object() + .and_then(|map| { + map.iter() + .find(|(key, _)| aliases.contains(&key.to_lowercase().as_str())) + }) + .map(|(_, value)| py_string(value)) + .unwrap_or_else(|| default.to_owned()) + }; + return Ok(vec![ + ( + "no".into(), + description( + &["no", "false", "0"], + "The answer is no (negative, or disagree with the claim).", + ), + ), + ( + "yes".into(), + description( + &["yes", "true", "1"], + "The answer is yes (affirmative, or align with the claim).", + ), + ), + ]); + } + let options: Vec<_> = match criteria { + Value::Object(map) => { + if kind == Kind::Score && map.keys().any(|level| score_level(level).is_none()) { + return Err(invalid("Score option keys must be finite numbers")); + } + map.iter() + .map(|(name, value)| (name.clone(), py_string(value))) + .collect() + } + Value::Array(array) if kind == Kind::Score => array + .iter() + .enumerate() + .map(|(index, value)| (index.to_string(), py_string(value))) + .collect(), + _ => { + return Err(invalid( + "Choice criteria must be an object and Score criteria a list or object", + )); + } + }; + if !(1..=SYMBOLS.len()).contains(&options.len()) { + return Err(invalid("supply 1–62 options")); + } + Ok(options) +} + +pub fn score_level(label: &str) -> Option { + let label = label.trim(); + if label.as_bytes().iter().enumerate().any(|(index, &byte)| { + byte == b'_' + && !(index > 0 + && label.as_bytes()[index - 1].is_ascii_digit() + && label + .as_bytes() + .get(index + 1) + .is_some_and(u8::is_ascii_digit)) + }) { + return None; + } + label + .replace('_', "") + .parse::() + .ok() + .filter(|level| level.is_finite()) +} + +fn py_string(value: &Value) -> String { + match value { + Value::String(text) => text.clone(), + _ => py_repr(value), + } +} + +fn py_repr(value: &Value) -> String { + match value { + Value::Null => "None".into(), + Value::Bool(false) => "False".into(), + Value::Bool(true) => "True".into(), + Value::String(text) => { + let quote = if text.contains('\'') && !text.contains('"') { + '"' + } else { + '\'' + }; + let mut out = String::from(quote); + for ch in text.chars() { + match ch { + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + '\\' => out.push_str("\\\\"), + ch if ch == quote => { + out.push('\\'); + out.push(ch); + } + ch if ch.is_control() || (ch.is_whitespace() && ch != ' ') => { + use fmt::Write; + let code = u32::from(ch); + if code <= 0xff { + write!(out, "\\x{code:02x}").unwrap(); + } else if code <= 0xffff { + write!(out, "\\u{code:04x}").unwrap(); + } else { + write!(out, "\\U{code:08x}").unwrap(); + } + } + ch => out.push(ch), + } + } + out.push(quote); + out + } + Value::Array(items) => format!( + "[{}]", + items.iter().map(py_repr).collect::>().join(", ") + ), + Value::Object(items) => format!( + "{{{}}}", + items + .iter() + .map(|(key, value)| { + format!( + "{}: {}", + py_repr(&Value::String(key.clone())), + py_repr(value) + ) + }) + .collect::>() + .join(", ") + ), + Value::Number(_) => json::dumps(value), + } +} + +fn pretty(value: &Value, indent: usize, depth: usize) -> String { + let (open, entries, close) = match value { + Value::Array(items) if !items.is_empty() => ( + '[', + items + .iter() + .map(|v| pretty(v, indent, depth + 1)) + .collect::>(), + ']', + ), + Value::Object(items) if !items.is_empty() => ( + '{', + items + .iter() + .map(|(name, v)| format!("{}: {}", json::quote(name), pretty(v, indent, depth + 1))) + .collect(), + '}', + ), + _ => return json::dumps(value), + }; + let next = " ".repeat(indent * (depth + 1)); + let current = " ".repeat(indent * depth); + format!( + "{open}\n{next}{}\n{current}{close}", + entries.join(&format!(",\n{next}")) + ) +} diff --git a/src/models/qwen3_5/native/src/model.rs b/src/models/qwen3_5/native/src/model.rs index c86e8d9f..8e007750 100644 --- a/src/models/qwen3_5/native/src/model.rs +++ b/src/models/qwen3_5/native/src/model.rs @@ -15,6 +15,7 @@ mod matched; mod window_graph; +use std::cell::Cell; use std::collections::{HashMap, VecDeque}; use std::ffi::c_void; use std::path::Path; @@ -857,6 +858,7 @@ fn runs(prompts: &SharedPrompts) -> Runs { pub struct Model { pub cfg: Config, prefix_owner: Arc<()>, + prefix_allocated: Cell, /// Allocation capacity only: state is invalidated and fully recaptured per request. text_prefix_workspace: Option<(usize, PrefixState)>, _weights: Weights, @@ -871,6 +873,7 @@ pub struct Model { matched_ref: usize, matched_handles: HashMap, reference: Option<&'static cuda::Reference>, + framework_text_4b: bool, fp32_gdn: Option, batched_gdn: Option, packed_gemm: Option, @@ -1042,6 +1045,7 @@ impl Model { let model = Self { cfg, prefix_owner: Arc::new(()), + prefix_allocated: Cell::new(false), text_prefix_workspace: None, _weights: weights, embed, @@ -1054,6 +1058,7 @@ impl Model { matched_ref: 0, matched_handles: HashMap::new(), reference: None, + framework_text_4b: false, fp32_gdn: None, batched_gdn: None, packed_gemm: None, @@ -1193,6 +1198,97 @@ impl Model { Ok(()) } + /// Opt into the existing framework-style operations for eager, causal, + /// merged 4B text. Select at startup, before allocating any request state. + /// The profile does not guarantee parity with any particular framework build. + pub fn enable_framework_text_4b(&mut self) -> Result<()> { + let cfg = &self.cfg; + ensure!( + cfg.hidden == 2560 + && cfg.intermediate == 9216 + && cfg.heads == 16 + && cfg.kv_heads == 4 + && cfg.head_dim == 256 + && cfg.lin_k_heads == 16 + && cfg.lin_v_heads == 32 + && cfg.lin_k_dim == 128 + && cfg.lin_v_dim == 128 + && cfg + .full_attention + .iter() + .copied() + .eq((0..32).map(|i| i % 4 == 3)) + && cfg.rotary_half == 32 + && cfg.rope_theta == 10_000_000.0 + && cfg.mrope_section == [11, 11, 10], + "framework text requires the merged 4B geometry" + ); + ensure!( + !self.graph_enabled + && self.scratch.is_none() + && !self.prefix_allocated.get() + && self.fixed_gemm.is_null() + && self.matched_handles.is_empty() + && self.reference.is_none() + && self.lora.is_none() + && self.fp32_gdn.is_none() + && self.packed_gemm.is_none() + && self.batched_gdn.is_none(), + "select framework text on an eager merged model before allocating request state" + ); + cuda::set_device(0)?; + let reference = cuda::api().language_reference()?; + cuda::synchronize(self.stream)?; + // SAFETY: the model owns both handles, with no pending work or captures. + let gemm = unsafe { (reference.gemm_create)(GEMM_WORKSPACE) }; + ensure!(!gemm.is_null(), "framework text cuBLASLt setup failed"); + unsafe { (cuda::api().cs1_gemm_destroy)(self.gemm) }; + self.gemm = gemm; + self.reference = Some(reference); + self.framework_text_4b = true; + Ok(()) + } + + /// Prefill one complete text sequence and return the requested final-norm + /// rows in caller order. Each owned row widens the BF16 values to f32 + /// without changing their bits. All queued work retires before return. + pub fn forward_framework_text_readout( + &mut self, + ids: &[u32], + rows: &[usize], + ) -> Result>> { + ensure!(self.framework_text_4b, "enable framework text first"); + ensure!( + !ids.is_empty() + && ids.len() <= self.cfg.max_positions + && ids.len() <= i32::MAX as usize, + "empty or oversized prompt" + ); + ensure!( + ids.iter() + .all(|&id| (id as usize) < self.embed.shape[0] + && self.cfg.image_token_id != Some(id)), + "token outside the text vocabulary" + ); + ensure!( + !rows.is_empty() && rows.iter().all(|&row| row < ids.len()), + "readout row outside the prompt" + ); + let result = (|| { + self.prepare_scratch(ids.len())?; + let scratch = self.scratch.as_ref().unwrap(); + self.embed_tokens(scratch, ids)?; + self.run(scratch, &[ids.len()], false, false)?; + rows.iter() + .map(|&row| self.hidden_row(scratch, row)) + .collect::>() + })(); + if result.is_err() { + let _ = cuda::synchronize(self.stream); + } + result + } + fn gemm(&self, s: &Scratch, x: usize, w: &Tensor, y: usize, m: usize) -> Result<()> { self.gemm_with(self.gemm, s, x, w, y, m) } @@ -1550,6 +1646,7 @@ impl Model { inputs: &[&[u32]], original_rows: Option<&[usize]>, ) -> Result>> { + ensure!(!self.framework_text_4b, "use the framework text readout"); ensure!(!inputs.is_empty(), "empty batch"); ensure!( inputs @@ -1907,6 +2004,10 @@ impl Model { /// explicit `[3, 1, sequence]` T/H/W positions. No vision tower runs here. /// Load a checkpoint with the matching multimodal language adapter merged. pub fn forward_multimodal(&mut self, input: &MultimodalInput<'_>) -> Result> { + ensure!( + !self.framework_text_4b, + "framework text does not support multimodal input" + ); let image_token = self .cfg .image_token_id @@ -2246,6 +2347,10 @@ impl Model { &mut self, input: &DeviceMultimodalInput<'_>, ) -> Result> { + ensure!( + !self.framework_text_4b, + "framework text does not support multimodal input" + ); let result = (|| { cuda::set_device(0)?; let image_token = self @@ -2358,6 +2463,10 @@ impl Model { /// Allocate an uninitialized prefix of `len` tokens (a multiple of 64). /// Capture must finish successfully on this model before continuation. pub fn alloc_prefix(&self, len: usize) -> Result { + ensure!( + !self.framework_text_4b, + "framework text does not support prefix caching" + ); ensure!( self.fp32_gdn.is_none(), "FP32 GDN does not support prefix caching" @@ -2374,6 +2483,7 @@ impl Model { len <= self.cfg.max_positions, "cached prefix exceeds the configured maximum length" ); + self.prefix_allocated.set(true); let (kvrow, nfull, ngdn, state_bytes, tail_bytes) = self.prefix_layout(); let mut attn_kv = Vec::with_capacity(nfull); for _ in 0..nfull { @@ -2427,6 +2537,10 @@ impl Model { input: &MultimodalInput<'_>, state: &mut PrefixState, ) -> Result<()> { + ensure!( + !self.framework_text_4b, + "framework text does not support prefix capture" + ); ensure!( Arc::ptr_eq(&self.prefix_owner, &state.owner), "prefix state belongs to a different model instance" @@ -2475,6 +2589,10 @@ impl Model { input: &MultimodalInput<'_>, prefix: &PrefixState, ) -> Result> { + ensure!( + !self.framework_text_4b, + "framework text does not support prefix continuation" + ); ensure!( Arc::ptr_eq(&self.prefix_owner, &prefix.owner), "prefix state belongs to a different model instance" diff --git a/tests/intern/contract.rs b/tests/intern/contract.rs new file mode 100644 index 00000000..25bf4733 --- /dev/null +++ b/tests/intern/contract.rs @@ -0,0 +1,102 @@ +use anyhow::Result; +use omni_intern_native::{ + finishing::{finish, probabilities}, + processing::{Kind, compile}, +}; +use serde_json::{Value, json}; + +#[test] +fn ordered_schema_and_typed_answers() -> Result<()> { + let body = json!({ + "state": {"路线": ["重複", null], "flags": {"on": true}}, + "questions": { + "route": {"type": "choice", "criteria": {"z": 1.0, "a": null}}, + "refund": {"type": "noul", "criteria": {"TRUE": "Affirmative", "false": "Negative"}}, + "severity": {"type": "score", "criteria": {"2.0": "low", "1e1": "high"}}, + "single": {"type": "score", "criteria": ["zero"]} + } + }); + let (prompt, fields) = compile(body.as_object().unwrap())?; + assert!(prompt.contains( + "{\n \"路线\": [\n \"重複\",\n null\n ],\n \"flags\": {\n \"on\": true\n }\n}" + )); + assert!(prompt.contains(" A = z: 1.0\n B = a: None")); + assert!(prompt.contains(" A = no: Negative\n B = yes: Affirmative")); + assert!(prompt.contains("{\n \"route\": \"\",\n \"refund\": \"\",\n \"severity\": \"\",\n \"single\": \"\"\n}")); + assert_eq!( + fields.iter().map(|field| field.kind).collect::>(), + [Kind::Choice, Kind::Noul, Kind::Score, Kind::Score] + ); + let output = finish( + &fields, + &[vec![0.0, 0.0], vec![2.0, -2.0], vec![0.0, 0.0], vec![8.0]], + 183, + 1.23, + )?; + let answers = &output["answers"]; + assert_eq!(answers["route"]["decision"], "a"); + assert_eq!(answers["route"]["choice"], "a"); + assert_eq!( + answers["route"]["probabilities"] + .as_object() + .unwrap() + .keys() + .map(String::as_str) + .collect::>(), + ["z", "a"] + ); + assert_eq!(answers["refund"]["decision"], "no"); + assert_eq!( + answers["refund"]["noul"], + answers["refund"]["probabilities"]["yes"] + ); + assert_eq!( + answers["refund"]["confidence"], + answers["refund"]["probabilities"]["no"] + ); + assert_eq!(answers["severity"]["score"], 6.0); + assert_eq!(answers["severity"]["decision"], "1e1"); + assert_eq!(answers["single"]["score"], 0.0); + assert_eq!( + output["usage"], + json!({"input_tokens": 183, "output_tokens": 4, "decision_count": 4}) + ); + Ok(()) +} + +#[test] +fn rejects_semantic_errors_before_tokenization() { + let question = json!({"type": "choice", "criteria": {"a": "yes"}}); + for body in [ + json!({"questions": {"q": question}}), + json!({"state": "hello", "images": ["image.jpg"], "questions": {"q": question}}), + json!({"state": {"text": ""}, "questions": {"q": question}}), + json!({"state": "hello", "questions": {"": question}}), + json!({"state": "hello", "questions": {"q": {"type":"choice","criteria":{}}}}), + json!({"state": "hello", "questions": {"q": {"type":"score","criteria":{"NaN":"no"}}}}), + json!({"state": "hello", "questions": {}}), + ] { + assert_eq!(compile(body.as_object().unwrap()).unwrap_err().status, 422); + } +} + +#[test] +fn probabilities_and_extreme_scores_remain_finite() -> Result<()> { + let (raw, scaled) = probabilities(&[1000.0, 999.0, -1000.0])?; + assert_eq!(raw[2], 0.0); + assert_eq!(scaled[2], 0.0); + assert!((scaled.iter().sum::() - 1.0).abs() <= 1e-6); + let request = json!({"state": "", "questions": { + "extreme": {"type": "score", "criteria": {"-1.7976931348623157e308": "low", "1.7976931348623157e308": "high"}}, + "aliases": {"type": "score", "criteria": {"1": "low", "1.0": "middle", "1e0": "high"}} + }}); + let (_, fields) = compile(request.as_object().unwrap())?; + let response = finish(&fields, &[vec![0.0, 0.0], vec![1.0, 2.0, 3.0]], 100, 0.0)?; + assert_eq!(response["answers"]["extreme"]["score"], 0.0); + assert_eq!(response["answers"]["aliases"]["score"], 1.0); + assert!(matches!( + response["answers"]["aliases"]["score"], + Value::Number(..) + )); + Ok(()) +} diff --git a/tests/intern/prefill.rs b/tests/intern/prefill.rs new file mode 100644 index 00000000..66fc10fe --- /dev/null +++ b/tests/intern/prefill.rs @@ -0,0 +1,104 @@ +use std::{fs, path::PathBuf}; + +use anyhow::{Result, ensure}; +use omni_intern_native::{executor::Executor, finishing, processing::Processor}; +use serde_json::{Value, json}; + +#[test] +#[ignore = "requires the frozen Intern oracle inputs and tokenizer"] +fn frozen_processing() -> Result<()> { + let (_, cases) = frozen_inputs()?; + ensure!(cases.len() == 6, "expected all six text fixtures"); + Ok(()) +} + +#[test] +#[ignore = "requires the frozen Intern checkpoint and sm_89 device library"] +fn frozen_prefill() -> Result<()> { + let (processor, cases) = frozen_inputs()?; + let checkpoint = PathBuf::from(std::env::var("INTERN_CHECKPOINT")?); + let library = PathBuf::from(std::env::var("INTERN_CUDA_LIB")?); + let mut executor = Executor::load(&checkpoint, &library)?; + let mut outputs = Vec::with_capacity(cases.len()); + for (id, prepared) in cases { + let hidden = executor.hidden(&prepared.ids, &prepared.readout)?; + let logits = executor.project(&hidden, &processor.symbol_ids)?; + outputs.push(json!({"id": id, "logits": logits, "hidden": hidden})); + } + fs::write( + std::env::var("INTERN_PREFILL_OUT")?, + serde_json::to_vec(&outputs)?, + )?; + Ok(()) +} + +#[test] +#[ignore = "replays saved native logits with the frozen tokenizer and requests"] +fn frozen_finishing_replay() -> Result<()> { + let (_, cases) = frozen_inputs()?; + let logits = fs::read(std::env::var("INTERN_PREFILL_OUT")?)?; + let logits: Vec = serde_json::from_slice(&logits)?; + assert_eq!(cases.len(), logits.len()); + let mut outputs = Vec::with_capacity(cases.len()); + for ((id, prepared), recorded) in cases.into_iter().zip(logits) { + assert_eq!(json!(id), recorded["id"]); + let rows: Vec> = serde_json::from_value(recorded["logits"].clone())?; + assert_eq!(rows.len(), prepared.fields.len()); + let raw = rows + .iter() + .zip(&prepared.fields) + .map(|(row, field)| { + let (raw, _) = finishing::probabilities(&row[..field.options.len()])?; + Ok((field.name.clone(), json!(raw))) + }) + .collect::>>()?; + let response = finishing::finish(&prepared.fields, &rows, prepared.ids.len(), 0.0)?; + outputs.push(json!({"id": id, "uncalibrated": raw, "response": response})); + } + fs::write( + std::env::var("INTERN_FINISHING_OUT")?, + serde_json::to_vec(&outputs)?, + )?; + Ok(()) +} + +fn frozen_inputs() -> Result<( + Processor, + Vec<(String, omni_intern_native::processing::Prepared)>, +)> { + let input = PathBuf::from(std::env::var("INTERN_FROZEN_INPUTS")?); + let checkpoint = PathBuf::from(std::env::var("INTERN_CHECKPOINT")?); + let processor = Processor::load(&checkpoint.join("tokenizer.json"))?; + let fixtures: Vec = serde_json::from_slice(&fs::read(input)?)?; + let mut cases = Vec::new(); + for fixture in fixtures { + let id = fixture["id"].as_str().unwrap(); + let prepared = processor.prepare(&serde_json::to_vec(&fixture["request"])?)?; + assert_eq!(json!(prepared.prompt), fixture["prompt"], "{id} prompt"); + assert_eq!(json!(prepared.ids), fixture["ids"], "{id} tokens"); + assert_eq!(json!(prepared.readout), fixture["readout"], "{id} readout"); + for (field, expected) in prepared + .fields + .iter() + .zip(fixture["fields"].as_array().unwrap()) + { + assert_eq!(json!(field.name), expected["field"]); + assert_eq!( + json!( + field + .options + .iter() + .map(|(name, _)| name) + .collect::>() + ), + expected["values"] + ); + assert_eq!( + json!(&processor.symbol_ids[..field.options.len()]), + expected["symbol_ids"] + ); + } + cases.push((id.to_owned(), prepared)); + } + Ok((processor, cases)) +} diff --git a/tests/qwen3_5/readout.rs b/tests/qwen3_5/readout.rs index d0ccdf37..9034c91a 100644 --- a/tests/qwen3_5/readout.rs +++ b/tests/qwen3_5/readout.rs @@ -23,6 +23,58 @@ fn model() -> Model { Model::load(&checkpoint(), &library).unwrap() } +#[test] +#[ignore = "requires the merged Qwen3.5 4B checkpoint and sm_89 device library"] +fn framework_text_profile_rejects_incompatible_entry_points() -> anyhow::Result<()> { + let library = PathBuf::from(std::env::var_os("CUA_S1_CUDA_LIB").expect("set CUA_S1_CUDA_LIB")); + let mut graph = Model::load_with_graph(&checkpoint(), &library, true)?; + assert!(graph.enable_framework_text_4b().is_err()); + drop(graph); + + let mut used = Model::load_with_graph(&checkpoint(), &library, false)?; + assert!(used.forward_framework_text_readout(&[1], &[0]).is_err()); + drop(used.alloc_prefix(64)?); + assert!(used.enable_framework_text_4b().is_err()); + drop(used); + + let mut model = Model::load_with_graph(&checkpoint(), &library, false)?; + model.enable_framework_text_4b()?; + assert!(model.enable_framework_text_4b().is_err()); + assert!(model.forward_framework_text_readout(&[], &[0]).is_err()); + assert!(model.forward_framework_text_readout(&[1], &[]).is_err()); + assert!(model.forward_framework_text_readout(&[1], &[1]).is_err()); + assert!( + model + .forward_framework_text_readout(&[u32::MAX], &[0]) + .is_err() + ); + let image = model.cfg.image_token_id.expect("merged multimodal 4B"); + assert!( + model + .forward_framework_text_readout(&[image], &[0]) + .is_err() + ); + let input = MultimodalInput { + token_ids: &[1], + image_token_indices: &[], + image_embeddings: &[], + position_ids: [&[0]; 3], + }; + assert!(model.forward_multimodal(&input).is_err()); + assert!(model.forward_batch(&[&[1]]).is_err()); + assert!(model.forward_fixed(&[1]).is_err()); + assert!(model.forward_multimodal_readout(&input, &[0], &[]).is_err()); + assert!(model.try_forward_shared_prefix(&[&[1]], 0).is_err()); + assert!(model.alloc_prefix(64).is_err()); + assert!(model.require_prompt_bidirectional().is_err()); + assert!(model.require_prompt_prefix_bidirectional().is_err()); + assert!(model.enable_packed_projections().is_err()); + assert!(model.enable_batched_gdn().is_err()); + assert!(model.enable_reference_text_numerics().is_err()); + assert!(!model.graph_stats().enabled); + Ok(()) +} + /// Token ids in [1000, 100000) from a fixed seed. fn tokens(n: usize, seed: u64) -> Vec { let mut x = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1;