Skip to content

Verify Gemma 4 and Mistral chat-template path on real Apple Silicon hardware (follow-up to #1094) #1142

Closed

Description

@malibio

Overview

Manual on-device validation of the chat-template and tool-call paths that landed in PR #1134. Cannot be done in CI because it requires a real GGUF on disk and Metal acceleration, and our embedding integration tests already destabilize the suite when run in parallel.

Problem Statement

PR #1134 made two changes that touch the runtime inference path:

  1. Chat template path changed for both families. Replaced the C-level apply_chat_template (which hand-injected [AVAILABLE_TOOLS]...[/AVAILABLE_TOOLS] into the system prompt) with apply_chat_template_oaicompat (use_jinja: true), which passes tools via tools_json and lets the model's embedded Jinja template format them. Ministral 2512 GGUFs ship with a Jinja template that should produce the same [AVAILABLE_TOOLS] wrapper, but byte-for-byte equivalence to the old hand-injected form was not verified.

  2. Added Gemma 4 E4B and 31B as new model options. Validated end-to-end in ../nodespace-nlp-experiment on llama-cpp-2 v0.1.146, but not re-run against the production code in nodespace-core.

Both paths are believed correct based on the experiment repo and unit-level parser tests, but neither was confirmed against the production code on a real machine.

The previous PR's code reviewer agreed that automated tests for this would be flaky (parallel Metal contention destabilizes integration runs), and the agreed mitigation was a manual smoke test before users see the change. NodeSpace has no users yet, so PR #1134 was merged ahead of verification — but the verification still needs to happen before any release that ships these models.

Proposed Solution

A short, scripted manual session on M2 Pro 16GB (or equivalent Apple Silicon) that exercises both code paths and one regression path.

Verification Approach

Phase 1: Ministral regression check (anti-regression for #1134's chat-template change)

  1. Launch the desktop app with a clean local model directory.
  2. Download Ministral 3B Q4_K_M (ministral-3b-q4km).
  3. Load it.
  4. Send a chat prompt that requires a tool call (any registered tool — e.g. search_nodes with a query).
  5. Confirm:
    • Tokens stream as expected.
    • The streaming parser detects [TOOL_CALLS] and emits a ToolCallStart + ToolCallArgs chunk.
    • The tool's name and arguments parse correctly via the Mistral {name, arguments} schema.

Phase 2: Gemma 4 E4B end-to-end

  1. Without unloading Ministral, download Gemma 4 E4B Q4_K_M (gemma-4-e4b-q4km) — exercises the resumable download flow against the new ggml-org/gemma-4-E4B-it-GGUF URL.
  2. Unload Ministral, load Gemma 4 E4B.
  3. Send a plain chat prompt. Confirm: no ffi error -1 in logs, tokens stream.
  4. Send a tool-using chat prompt. Confirm the parser detects [TOOL_CALLS] and successfully extracts a tool call using the Gemma 4 {tool_name, tool_args} schema (Format C in chat/parser.rs).

Phase 3 (optional, requires 24GB+ machine): Gemma 4 31B

  1. Download gemma-4-31b-q4km (~18.7 GB).
  2. Load.
  3. Single chat round to confirm load + first-token generation succeeds.

Acceptance Criteria

  • Ministral 3B (or 8B) tool-calling parses correctly under the new OAI-compat Jinja path
  • Gemma 4 E4B downloads, loads, and streams without ffi error -1
  • Gemma 4 E4B tool-calling parses correctly via the Format C {tool_name, tool_args} path
  • Results documented as a comment on this issue (parse rates, any errors, tokens/sec for confirmation against the experiment repo's published numbers)
  • If any path fails, file a separate bug issue with the specific failure mode

Technical Specifications

Reference Files

  • Chat template path: packages/nlp-engine/src/chat/mod.rs (the rewritten apply_chat_template function and its OpenAIChatTemplateParams setup)
  • Tool-call parser: packages/nlp-engine/src/chat/parser.rs (Format A/B/C handling; parse_tool_call_object dual-deserialization)
  • Model registry: packages/agent/src/local_agent/model_manager.rs (catalog entries for Ministral 3B/8B + Gemma 4 E4B/31B)
  • UI model manager: packages/desktop-app/src/lib/components/settings/model-manager.svelte

Reference Validation Data

The experiment repo's published numbers for Gemma 4 E4B on M2 Pro 16GB are the comparison target:

  • Tokens/sec: ~20.1
  • TTFT: ~265ms
  • Model load: ~0.67s
  • Combined RSS with nomic-embed-text loaded: ~5.4 GB

If observed numbers diverge significantly, log it on this issue but do not block — the experiment numbers are a smoke check, not an SLA.

Logs to Capture

For each phase: snippet of stdout/stderr around chat-template application and tool-call parsing, plus any tracing::warn! or tracing::error! lines from nodespace-nlp-engine.

Dependencies

Related Issues

Non-Goals

  • Benchmarking on non-Apple-Silicon hardware
  • Multimodal (vision/audio) input — Gemma 4 supports it but NodeSpace has no vision pipeline yet
  • Automated regression coverage — the agreed mitigation is manual; an automated version of this test would require an Ollama-style integration harness which doesn't exist yet

Activity

  1. self-assigned this
    on May 31, 2026
  2. malibio commented on May 31, 2026

    @malibio
    CollaboratorAuthor

    Verification Results — Gemma 4 E4B Only (Ministral skipped per user preference)

    Date: 2026-05-31
    Machine: Apple Silicon M2 Pro 16GB
    Model: Gemma 4 E4B Q4_K_M (gemma-4-e4b-q4km)
    Daemon binary: ~/.nodespace/bin/nodespaced (built 2026-05-31 22:01)


    Phase 2a: Plain chat — ✅ PASS

    • EnsureModelReady → { "eventType": "ready", "engineSwapped": true } — model loaded
    • SendMessage("Hello! What is 2+2? Reply briefly.") — tokens streamed immediately, no ffi error -1
    • 5361 prompt tokens + 18 completion tokens
    • Model load time observed in logs: ~4s (within experiment repo's ~0.67s + context creation)
    • No errors or panics in daemon logs

    Phase 2b: Tool-call parsing — ❌ FAIL (new bug)

    The agent loop log shows tool_calls=0 on a prompt that triggered tool use. The raw response was:

    4<|tool_call>call:search_semantic{query:<|"|>2+2<|"|>}<tool_call|>
    

    Root cause: Gemma 4 E4B uses special tokens for tool calls (<|tool_call> = token 106), not the plain-text [TOOL_CALLS] sentinel the streaming parser expects. The code calls token_to_piece(..., special=false) which silently drops special tokens. The daemon log shows WARN: Failed to decode token 106: Unknown Token Type on every tool call boundary.

    Additionally, the Gemma 4 tool call format after the special token is call:<name>{args} with <|"|> special-token string delimiters — not the {"tool_name": ..., "tool_args": ...} JSON-object format the parser (Format C) was built for.

    The Format C assumption was wrong: the parser was written assuming Gemma 4 would emit [TOOL_CALLS]{"tool_name":...} (same as Mistral sentinel + JSON). The actual model uses a completely different special-token-based encoding.

    Daemon binary verification

    Daemon is the correct binary:

    Summary

    Criterion Result
    Gemma 4 E4B downloads and loads ✅
    No ffi error -1 on first token ✅
    Tokens stream ✅
    Tool-call Format C parser works ❌ Wrong format assumption — model uses special tokens

    Next step

    Filed #1287: Fix Gemma 4 tool-call parser — handle <|tool_call> special token and call:name{args} wire format.

  3. malibio commented on May 31, 2026

    @malibio
    CollaboratorAuthor

    Fix committed — Gemma 4 tool-call parsing (commit 3a4efd6)

    Root cause confirmed: Gemma 4 E4B uses special tokens for tool calls (<|tool_call> = token 106, <|"|> for string delimiters, <tool_call|> as end marker). The old code called token_to_piece(..., special=false) which silently dropped these special tokens, so the [TOOL_CALLS] sentinel was never injected and tool_calls=0 on every response.

    Fix: Replaced the custom sentinel detection with ChatParseStateOaicompat — llama.cpp's own streaming parser, accessible via the llama-cpp-2 Rust binding. Set parse_tool_calls: true in the chat template params so the parser state gets the model's native chat_format + PEG grammar. The generation loop now feeds accumulated text to oai_parser.update(text, is_partial) per token; the C++ layer handles all model-family-specific special tokens.

    This also removes all the detect_tool_calls_token / tool_calls_token_id plumbing that was Mistral-specific. Future model families work automatically if llama.cpp knows them.

    Ready to re-verify — restart the Tauri app (which will install the new daemon binary) then re-run the tool-calling prompt via the chat UI or grpcurl.

  4. malibio commented on May 31, 2026

    @malibio
    CollaboratorAuthor

    Session handoff — WIP commit a6f4a16

    What was fixed this session

    Tool-call parsing now works for Gemma 4 E4B (tool_calls=1 per inference round confirmed in daemon logs).

    Root cause: Gemma 4 emits <|tool_call> as a special token (id 106). The old code used token_to_piece(special=false) which silently dropped it, so the [TOOL_CALLS] sentinel was never injected and tool_calls=0 on every response.

    Fix: replaced StreamingToolCallParser + custom sentinel detection with ChatParseStateOaicompat — llama.cpp's native streaming parser backed by COMMON_CHAT_FORMAT_PEG_GEMMA4 PEG grammar. Handles all model families natively.

    Also fixed: LocalAgentServiceServer was accidentally dropped from daemon gRPC registration in PR #1161 (ea8849a) and had been missing for 13 days. Restored in 443bad0.

    Remaining before closing this issue

    • Fix raw token leak in final no-tools inference pass: <|tool_call> tokens still stream as ChatChunk::Token in the last plain-text generation round. content deltas from oai_parser.update() may be dropping. Debug starting point: add logging in emit_oai_delta() (packages/nlp-engine/src/chat/mod.rs ~line 465) to inspect raw delta JSON strings.
    • Confirm plain-text streaming end-to-end in UI
  5. malibio commented on Jun 1, 2026

    @malibio
    CollaboratorAuthor

    Code Review — commits 3a4efd6, 443bad0, a6f4a16

    These commits were pushed directly to main during session verification of #1142. Review findings:


    443bad0 — Restore LocalAgentService registration ✅

    Correct. node_service.clone() before ImportServiceImpl::new(node_service) is right. Both server blocks (headless + tray) updated consistently.


    3a4efd6 — ChatParseStateOaicompat streaming parser

    🟡 args default of "{}" wrong for streaming partial deltas

    packages/nlp-engine/src/chat/mod.rs line 487

    let args = function
        .and_then(|f| f.get("arguments"))
        .and_then(|a| a.as_str())
        .unwrap_or("{}");  // ← wrong default

    Early streaming deltas carry name but absent/empty arguments; they arrive in subsequent deltas. Defaulting to "{}" emits a premature ToolCallArgs with empty args. Works for Gemma 4 (full args in one delta) but will break Mistral streaming. Fix: only emit ToolCallArgs if arguments is present and non-empty.

    🟡 token_to_piece(special=true) is a behavioral change for Mistral

    packages/nlp-engine/src/chat/mod.rs line 380

    Mistral's [TOOL_CALLS] special token now decodes as literal text and goes to the OAI parser directly instead of being intercepted. Functionally correct in theory (OAI parser handles it), but Mistral was not tested this session. Should be verified before closing #1142.

    🔴 Known unfixed: raw special tokens leak in plain-text pass

    Gemma 4 special tokens (<|tool_call>, <|"|>, <tool_call|>) stream as ChatChunk::Token during the final no-tools inference pass. The OAI parser (COMMON_CHAT_FORMAT_PEG_GEMMA4) appears to buffer content rather than emit content deltas incrementally for plain text, so raw pieces pass through unfiltered. Not yet diagnosed or fixed.


    Overall: The LocalAgent registration restore is clean. The parser approach is architecturally correct but has two issues to address (args default, raw token leak) and one regression risk (Mistral) before this can be considered complete.

  6. malibio commented on Jun 1, 2026

    @malibio
    CollaboratorAuthor

    Final Verification Results — Gemma 4 E4B (M2 Pro 16GB)

    Date: 2026-06-01
    Model: Gemma 4 E4B Q4_K_M (gemma-4-e4b-q4km, 5.3GB)
    Commits: 3a4efd6, 443bad0, d918293, 8b5c842

    Acceptance Criteria

    Criterion Result
    Gemma 4 E4B downloads and loads ✅
    No ffi error -1 on first token ✅
    Tokens stream correctly ✅ Clean plain-text output, no special token leaks
    Tool-call parsing works ✅ tool_calls=1 per inference round, correct name + args
    Plain-text streaming (no raw token leaks) ✅ Fixed via additional_stops + strip_gemma_special_tokens
    Ministral regression ⏭️ Skipped per user preference at session start

    Performance Numbers (M2 Pro 16GB)

    Metric Observed Experiment Baseline Notes
    Model load 461ms ~670ms Hot file cache
    Context creation 114ms —
    TTFT ~7.8s ~265ms 5362 prompt tokens (agent system prompt + 13 tools)
    Completion tok/s ~1.5 ~20.1 Dominated by 5k prompt KV fill; experiment used minimal prompts

    The TTFT and tok/s diverge from the experiment baseline because the daemon runs the full ReAct agent with 13 registered tools (~7500 char system prompt, 5362 tokens). The experiment repo tested bare inference with a minimal prompt. This is expected — not a regression.

    Fixes applied during this verification

    1. LocalAgentService missing from gRPC server (ea8849a regression, 13 days) — restored
    2. Tool-call parsing broken for Gemma 4 — replaced custom StreamingToolCallParser with ChatParseStateOaicompat (llama.cpp native, COMMON_CHAT_FORMAT_PEG_GEMMA4)
    3. args default "{}" wrong for streaming partial deltas — changed to Option<&str>
    4. Raw special token leak in plain-text pass — strip_gemma_special_tokens() + additional_stops stop sequence check

    Filed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions