Skip to main content

adk_vision/cloud/
normalized.rs

1//! [`Normalized1000`]: boxes fixed by the prompt to `[x_min, y_min, x_max, y_max]` on 0–1000.
2
3use adk_core::GenerateContentConfig;
4use serde_json::{Value, json};
5
6use super::adapter::{RegionAdapter, boxed, image_index, quad};
7use crate::budget::ImageTokens;
8use crate::geometry::{AxisOrder, CoordFrame};
9use crate::traits::ImageRegion;
10
11/// A vision-language model whose box format the prompt fixes: `[x_min, y_min, x_max,
12/// y_max]` on 0–1000, origin top-left, independent of the aspect ratio
13/// ([`CoordFrame::Normalized`] with [`AxisOrder::Xy`]).
14///
15/// Models left to choose answer in different frames for different aspect ratios, so the
16/// frame is stated in the prompt (versioned as
17/// [`PROMPT_VERSION`](super::PROMPT_VERSION)) and answers are parsed defensively: the box
18/// may be under `bbox`, `bbox_2d`, `box_2d` or `box`.
19///
20/// | Constructor | Models | Image tokens | Request options |
21/// |-------------|--------|--------------|-----------------|
22/// | [`nemotron`](Self::nemotron) | `nvidia/nemotron-3.5-super-vl-120b-a12b`, `nvidia/nemotron-3-nano-omni-30b-a3b-reasoning` | `⌈w/32⌉ × ⌈h/32⌉` | `chat_template_kwargs.enable_thinking: false` |
23/// | [`gemma4`](Self::gemma4) | `google/gemma-4-31b-it` | 260 per image | — |
24/// | [`muse`](Self::muse) | `muse-*` | `⌈w/32⌉ × ⌈h/32⌉` | — |
25/// | [`qwen3_vl`](Self::qwen3_vl) | `Qwen/Qwen3-VL-*`, in process through mistral.rs or behind an OpenAI-compatible server | `⌈w/32⌉ × ⌈h/32⌉` | no response schema; the prompt fixes the shape |
26///
27/// The NVIDIA token counts were measured from `usage.prompt_tokens` on build.nvidia.com:
28/// 960×540 costs 510 tokens and 1600×1600 costs 2,500 on Super VL and Nano Omni; Gemma 4
29/// spends about 260 on any size. Qwen3-VL answers `bbox_2d` on 0–1000, x first, natively —
30/// Qwen's own grounding cookbook converts with `value / 1000 × width` — so for it the prompt
31/// restates the frame the model was trained on; one image token covers a 32×32 tile
32/// (patch 16, merge 2).
33///
34/// # Example
35///
36/// ```
37/// use adk_vision::cloud::{Normalized1000, RegionAdapter};
38///
39/// let super_vl = Normalized1000::nemotron("nvidia/nemotron-3.5-super-vl-120b-a12b");
40/// assert_eq!(super_vl.image_tokens().tokens((960, 540)), 510);
41/// ```
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct Normalized1000 {
44    tokens: ImageTokens,
45    thinking_off: bool,
46    vendor: Option<&'static str>,
47    structured: bool,
48}
49
50const FRAME: CoordFrame = CoordFrame::Normalized { scale: 1000, order: AxisOrder::Xy };
51
52impl Normalized1000 {
53    /// An adapter counting image tokens with `tokens`.
54    pub fn new(tokens: ImageTokens) -> Self {
55        Self { tokens, thinking_off: false, vendor: None, structured: true }
56    }
57
58    /// NVIDIA's Nemotron vision-language models. Their reasoning counts toward
59    /// `max_tokens` and can leave the answer empty, so perception calls turn it off.
60    pub fn nemotron(_model: &str) -> Self {
61        Self {
62            tokens: ImageTokens::Tiles { side: 32 },
63            thinking_off: true,
64            vendor: Some("nvidia"),
65            structured: true,
66        }
67    }
68
69    /// Google's Gemma 4 as NVIDIA hosts it.
70    pub fn gemma4(_model: &str) -> Self {
71        Self {
72            tokens: ImageTokens::Fixed { tokens: 260 },
73            thinking_off: false,
74            vendor: Some("nvidia"),
75            structured: true,
76        }
77    }
78
79    /// Meta's Muse models through the Meta Model API.
80    pub fn muse(_model: &str) -> Self {
81        Self {
82            tokens: ImageTokens::Tiles { side: 32 },
83            thinking_off: false,
84            vendor: None,
85            structured: true,
86        }
87    }
88
89    /// Qwen3-VL, whose native grounding frame this is. `adk-mistralrs` passes no response
90    /// schema to the model, so the answer's shape is fixed by the prompt and parsed
91    /// defensively: a bare list of `{"bbox_2d": [...], "label": ...}`, Qwen's own form, is
92    /// read too.
93    ///
94    /// # Example
95    ///
96    /// ```
97    /// use adk_vision::cloud::{Normalized1000, RegionAdapter};
98    ///
99    /// let qwen = Normalized1000::qwen3_vl("Qwen/Qwen3-VL-2B-Instruct");
100    /// assert!(!qwen.structured_output());
101    /// assert_eq!(qwen.image_tokens().tokens((640, 400)), 260);
102    /// ```
103    pub fn qwen3_vl(_model: &str) -> Self {
104        Self {
105            tokens: ImageTokens::Tiles { side: 32 },
106            thinking_off: false,
107            vendor: None,
108            structured: false,
109        }
110    }
111}
112
113impl RegionAdapter for Normalized1000 {
114    fn name(&self) -> &str {
115        "normalized-1000"
116    }
117
118    fn frame(&self) -> CoordFrame {
119        FRAME
120    }
121
122    fn image_tokens(&self) -> ImageTokens {
123        self.tokens
124    }
125
126    fn region_schema(&self) -> Value {
127        json!({
128            "type": "object",
129            "properties": {
130                "label": {"type": "string"},
131                "bbox": {
132                    "type": "array",
133                    "items": {"type": "integer"},
134                    "description": "[x_min, y_min, x_max, y_max] normalized to 0-1000."
135                }
136            },
137            "required": ["label", "bbox"],
138            "additionalProperties": false
139        })
140    }
141
142    fn instructions(&self, sizes: &[(u32, u32)]) -> String {
143        let mut text = String::from(
144            "Give each region's `bbox` as [x_min, y_min, x_max, y_max] normalised to 0-1000 \
145             (0,0 is the top-left corner, 1000,1000 the bottom-right corner, independent of \
146             the image's aspect ratio).",
147        );
148        if sizes.len() > 1 {
149            text.push_str(" Name the image each region is in by its index, from 0.");
150        }
151        text
152    }
153
154    fn parse_region(
155        &self,
156        item: &Value,
157        sizes: &[(u32, u32)],
158    ) -> Result<Option<ImageRegion>, String> {
159        let image = image_index(item, sizes)?;
160        let Some(raw) = quad(item, &["bbox", "bbox_2d", "box_2d", "box"])? else {
161            return Ok(None);
162        };
163        Ok(Some(boxed(FRAME, raw, item, image)))
164    }
165
166    fn configure(&self, config: &mut GenerateContentConfig) {
167        if self.thinking_off {
168            let openai = config.extensions.entry("openai").or_insert_with(|| json!({}));
169            if let Some(fields) = openai.as_object_mut() {
170                fields.insert("chat_template_kwargs".into(), json!({"enable_thinking": false}));
171            }
172        }
173    }
174
175    fn vendor(&self) -> Option<&str> {
176        self.vendor
177    }
178
179    fn structured_output(&self) -> bool {
180        self.structured
181    }
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187    use crate::geometry::{BBox, Shape};
188
189    #[test]
190    fn nvidia_token_counts_match_the_recorded_usage() {
191        let super_vl = Normalized1000::nemotron("nvidia/nemotron-3.5-super-vl-120b-a12b");
192        for (size, tokens) in [
193            ((960, 540), 510),
194            ((512, 512), 256),
195            ((800, 800), 625),
196            ((900, 900), 841),
197            ((1000, 1300), 1312),
198            ((1600, 1600), 2500),
199        ] {
200            assert_eq!(super_vl.image_tokens().tokens(size), tokens, "{size:?}");
201        }
202        assert_eq!(
203            Normalized1000::gemma4("google/gemma-4-31b-it").image_tokens().tokens((960, 540)),
204            260
205        );
206    }
207
208    #[test]
209    fn every_documented_key_is_read_x_first() {
210        let adapter = Normalized1000::nemotron("nvidia/nemotron-3.5-super-vl-120b-a12b");
211        for key in ["bbox", "bbox_2d", "box_2d", "box"] {
212            let item = json!({"label": "red", key: [78, 108, 335, 400]});
213            let found = adapter.parse_region(&item, &[(960, 540)]).unwrap().unwrap();
214            assert_eq!(found.region.shape, Shape::Box(BBox::new(78.0, 108.0, 335.0, 400.0)));
215        }
216    }
217
218    #[test]
219    fn nemotron_turns_reasoning_off() {
220        let mut config = GenerateContentConfig::default();
221        Normalized1000::nemotron("nvidia/nemotron-3.5-super-vl-120b-a12b").configure(&mut config);
222        assert_eq!(
223            config.extensions["openai"]["chat_template_kwargs"],
224            json!({"enable_thinking": false})
225        );
226        let mut config = GenerateContentConfig::default();
227        Normalized1000::gemma4("google/gemma-4-31b-it").configure(&mut config);
228        assert!(config.extensions.is_empty());
229    }
230}