Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions .github/workflows/validate_wrapper.yml
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,7 @@ jobs:
llamadart_tts_api_test
llamadart_tts_eval_test
llamadart_mtmd_compat_test
llamadart_image_token_limit_test
llamadart_barrier_test
llamadart_vulkan_device_info_test
llamadart_exit_teardown_test
Expand Down Expand Up @@ -465,13 +466,14 @@ jobs:
llamadart_exit_teardown_test
llamadart_vulkan_device_info_test
llamadart_tts_api_test
llamadart_image_token_limit_test
- name: Run the barrier and Vulkan probe tests
shell: pwsh
run: |
$wrapperDir = (Resolve-Path build/wx64).Path
$upstreamDir = (Resolve-Path build/wx64/bin).Path
$env:PATH = "$wrapperDir;$upstreamDir;$env:PATH"
ctest --test-dir build/wx64 -R "barrier|vocabulary|vulkan_device_info|tts_api" --timeout 120 --output-on-failure
ctest --test-dir build/wx64 -R "barrier|vocabulary|vulkan_device_info|tts_api|image_token_limit" --timeout 120 --output-on-failure
- name: Validate wrapper exports
shell: pwsh
run: |
Expand Down Expand Up @@ -525,7 +527,9 @@ jobs:
-DGGML_CCACHE=OFF
-DLLAMADART_BUILD_TESTS=ON
- name: Build the exit teardown test
run: cmake --build ${{ matrix.build_dir }} --target llamadart_exit_teardown_test
run: >-
cmake --build ${{ matrix.build_dir }} --target
llamadart_exit_teardown_test llamadart_image_token_limit_test
- name: Validate wrapper exports and the static destructor binding
run: >-
python3 tools/validate_exports.py --format nm --tool nm
Expand All @@ -536,7 +540,7 @@ jobs:
# the Metal library, which takes most of a minute.
- name: Run the exit teardown scenarios
run: >-
ctest --test-dir ${{ matrix.build_dir }} -R exit_teardown
ctest --test-dir ${{ matrix.build_dir }} -R "exit_teardown|image_token_limit"
--timeout 300 --output-on-failure
# A model that nothing tracks aborts at exit when Metal residency sets
# are live. Whether a runner has them is outside this repository's
Expand Down
10 changes: 9 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ llamadart_attach_android_cpu_backend_score(ggml-cpu)

add_library(llamadart_lib SHARED
"src/llama_dart_wrapper.cpp"
"src/llama_dart_image_token_limit.cpp"
"src/llama_dart_vulkan_device_info.cpp")
# The Vulkan device facts need only the Vulkan types: the loader is opened at
# run time, so libllamadart links no Vulkan library and loads without one.
Expand Down Expand Up @@ -269,6 +270,13 @@ if (LLAMADART_BUILD_TESTS)
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
add_test(NAME llamadart_tts_eval_test COMMAND llamadart_tts_eval_test)

add_executable(llamadart_image_token_limit_test tests/image_token_limit_test.cpp)
target_compile_features(llamadart_image_token_limit_test PRIVATE cxx_std_17)
target_include_directories(llamadart_image_token_limit_test PRIVATE
src third_party/llama.cpp/include third_party/llama.cpp/tools/mtmd)
target_link_libraries(llamadart_image_token_limit_test PRIVATE llamadart_lib ggml-base)
add_test(NAME llamadart_image_token_limit_test COMMAND llamadart_image_token_limit_test)

add_executable(llamadart_mtmd_compat_test tests/mtmd_compat_test.cpp)
target_compile_features(llamadart_mtmd_compat_test PRIVATE cxx_std_17)
target_include_directories(llamadart_mtmd_compat_test PRIVATE src)
Expand Down Expand Up @@ -398,7 +406,7 @@ if (LLAMADART_BUILD_TESTS)
# Contract assertions must execute against optimized Release libraries too.
foreach(test_target llamadart_speculative_api_test llamadart_tts_api_test
llamadart_tts_eval_test llamadart_exit_teardown_test llamadart_mtmd_compat_test
llamadart_vulkan_device_info_test llamadart_barrier_test)
llamadart_vulkan_device_info_test llamadart_barrier_test llamadart_image_token_limit_test)
if (MSVC)
target_compile_options(${test_target} PRIVATE /UNDEBUG)
else()
Expand Down
61 changes: 61 additions & 0 deletions docs/image_token_limit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Opt-in image-token limit

The next wrapper rebuild adds `llama_dart_mtmd_supports_image_token_limit`.
It reads GGUF projector metadata without weights or GPU initialization and
returns 1 only for `gemma4v`/`gemma4uv` and limits 70 through 1120. Both the
legacy `clip.projector_type` and mixed-modality `clip.vision.projector_type`
keys follow upstream precedence. Missing, unknown and wrongly typed keys
return unsupported; read/argument errors return -1 through the exception
barrier. The call is guarded against exit teardown.

After a successful probe, callers explicitly set
`mtmd_context_params.image_max_tokens` before the existing guarded projector
initialization. Omitted options retain upstream metadata defaults. The option
reduces vision-patch detail and may change answers; it does not automatically
track a context microbatch or bound prompt/marker tokens. Existing decode
size checks remain necessary. Gemma 3 and other projector families are
unsupported rather than silently ignoring the request.

The 70-token lower bound preserves the default minimum-pixel threshold;
the 1120-token upper bound prevents expanding the model's default budget.
Primary implementation: upstream v0.6.0 clip.cpp Gemma 4 projector setup and
clip-model.h `set_limit_image_tokens`/`set_warmup_n_tokens`.

`llamadart_image_token_limit_test` reads real metadata fixtures and covers
supported ranges, unsupported types, mixed metadata, type mismatch and
exception-barrier recovery. Real Gemma 4 image encoding remains a separate
qualification gate before publication or downstream pin adoption.

Local verification (2026-10-09, macOS arm64, upstream v0.6.0): all 46 native
CTest cases pass and the export validator finds all 86 required exports.
A real cached Gemma 4 E2B Q4_K_S model with its F16 projector and a 1600x1600
RGB image produces 1089 image tokens by default and 484 with an explicit
512-token limit. The same maintained test optionally takes a model and
projector path and checks preprocessing. A fourth argument selects a limit and additionally
encodes the capped image:

```sh
build/v060-2/llamadart_image_token_limit_test /path/to/model.gguf /path/to/mmproj.gguf
build/v060-2/llamadart_image_token_limit_test /path/to/model.gguf /path/to/mmproj.gguf 70
```

A full default-image CPU encode was stopped at the bounded limit while still
computing. The smaller capped encoding smoke is recorded separately; neither
preprocessing nor encoding alone establishes answer quality.

The upstream resize budget is not a strict ceiling on arbitrary input. A
source-path control using the exact vendored `mtmd-image.cpp` resize helper
produced 81 patches for a tiny square at 70 and 715 for a 48x48000 image at 512.
Minimum-size and patch alignment can overshoot the target. Consumers that
promise a ceiling must reject oversized image chunks before encoding. The
prepared Dart consumer does so, on both causal and noncausal projectors, and
rejects runtimes lacking chunk inspection. Default inputs are unchanged.

Real noncausal Gemma 4 (`gemma4v`) projectors remain unqualified: no matching
cached projector is available. Gemma 3 remains explicitly unsupported. No
runtime release, device run or downstream pin change was performed.

The bounded real CPU encode with an explicit limit of 70 passed: default
preprocessing 1089 patches, capped 64 patches, encoded output shape
[1536,64,1]. This is real Gemma 4 E2B vision-encoding evidence. It does not
qualify noncausal Gemma 4v, GPU inference, full text decode or answer quality.
39 changes: 39 additions & 0 deletions src/llama_dart_image_token_limit.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#include "llama_dart_image_token_limit_internal.h"
#include "clip-impl.h"
#include "gguf.h"

#include <cstring>
#include <memory>
#include <stdexcept>

int32_t llama_dart_image_token_limit_supported(const char *mmproj_fname,
int32_t max_tokens) {
const gguf_init_params params{true, nullptr};
std::unique_ptr<gguf_context, decltype(&gguf_free)> metadata(
gguf_init_from_file(mmproj_fname, params), gguf_free);
if (!metadata) {
throw std::runtime_error("could not read projector GGUF metadata");
}
auto key = gguf_find_key(metadata.get(), "clip.projector_type");
if (key >= 0 && gguf_get_kv_type(metadata.get(), key) != GGUF_TYPE_STRING) {
return 0;
}
if (key < 0 || std::strlen(gguf_get_val_str(metadata.get(), key)) == 0) {
key = gguf_find_key(metadata.get(), "clip.vision.projector_type");
}
if (key < 0 || gguf_get_kv_type(metadata.get(), key) != GGUF_TYPE_STRING) {
return 0;
}
const char *type = gguf_get_val_str(metadata.get(), key);
if (clip_projector_type_from_string(type) == PROJECTOR_TYPE_UNKNOWN) {
return 0;
}
// v0.6.0 applies custom_image_max_tokens for these dynamic projectors
// through set_limit_image_tokens(70, 1120). Never raise their metadata
// budget or set a maximum below the default minimum-pixel threshold.
return (std::strcmp(type, "gemma4v") == 0 ||
std::strcmp(type, "gemma4uv") == 0) &&
max_tokens >= 70 && max_tokens <= 1120
? 1
: 0;
}
6 changes: 6 additions & 0 deletions src/llama_dart_image_token_limit_internal.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#pragma once
#include <cstdint>

// Reads upstream projector metadata; the public wrapper guards the call and
// translates exceptions into llama_dart_last_error.
int32_t llama_dart_image_token_limit_supported(const char *path, int32_t max_tokens);
12 changes: 12 additions & 0 deletions src/llama_dart_wrapper.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include "llama_dart_wrapper.h"
#include "llama_dart_image_token_limit_internal.h"
#include "llama_dart_barrier_internal.h"
#include "llama_dart_mtp_internal.h"
#include "llama_dart_mtmd_compat.h"
Expand Down Expand Up @@ -1163,6 +1164,17 @@ llama_dart_init_from_model(struct llama_model *model,
});
}

LLAMADART_API int32_t llama_dart_mtmd_supports_image_token_limit(
const char *mmproj_fname, int32_t max_tokens) {
return llama_dart_barrier<int32_t>(-1, [mmproj_fname, max_tokens] {
if (mmproj_fname == nullptr || max_tokens <= 0) {
throw std::invalid_argument("image token limit needs a projector and a positive limit");
}
llama_dart_exit_creating_call call;
return llama_dart_image_token_limit_supported(mmproj_fname, max_tokens);
});
}

LLAMADART_API struct mtmd_context *llama_dart_mtmd_init_from_file(
const char *mmproj_fname, const struct llama_model *text_model,
const struct mtmd_context_params *ctx_params) {
Expand Down
13 changes: 13 additions & 0 deletions src/llama_dart_wrapper.h
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,19 @@ LLAMADART_API struct llama_context * llama_dart_init_from_model(
struct llama_model * model,
struct llama_context_params params);

// Capability probe for an explicit mtmd_context_params.image_max_tokens.
// Reads projector metadata only; does not load weights or initialize a GPU.
// Returns 1 for a Gemma 4 vision projector (gemma4v/gemma4uv) and a limit
// in [70, 1120], 0 for an unsupported projector/limit, -1 for a read error
// or invalid arguments (llama_dart_last_error describes the error).
// It is an upstream resize budget: minimum-size/patch alignment can exceed
// it, especially for extreme aspect ratios. Callers enforcing a ceiling must
// inspect image-chunk token counts before encoding. It does not limit prompt
// or marker tokens. Defaults
// are unchanged unless the caller explicitly sets image_max_tokens.
LLAMADART_API int32_t llama_dart_mtmd_supports_image_token_limit(
const char * mmproj_fname, int32_t max_tokens);

// mtmd_init_from_file that tracks the context in the MODEL_USER stage. Free it
// with llama_dart_exit_free. Blocks after teardown.
LLAMADART_API struct mtmd_context * llama_dart_mtmd_init_from_file(
Expand Down
109 changes: 109 additions & 0 deletions tests/image_token_limit_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
#include "llama_dart_wrapper.h"
#include "gguf.h"

#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <initializer_list>
#include <vector>
#include "mtmd.h"

#ifdef NDEBUG
#error "Wrapper contract tests require active assertions"
#endif

static void real_image_limit(const char *model_path, const char *projector_path,
int limit, bool encode) {
assert(llama_dart_mtmd_supports_image_token_limit(projector_path, limit) == 1);
llama_model_params model_params = llama_model_default_params();
model_params.n_gpu_layers = 0;
model_params.vocab_only = true;
llama_model *model = llama_dart_model_load_from_file(model_path, model_params);
assert(model != nullptr);
std::vector<unsigned char> pixels(1600 * 1600 * 3, 127);
mtmd_bitmap *bitmap = mtmd_bitmap_init(1600, 1600, pixels.data());
const mtmd_bitmap *bitmaps[] = {bitmap};
size_t counts[2] = {};
for (int run = 0; run < 2; ++run) {
auto params = mtmd_context_params_default();
params.use_gpu = false;
params.warmup = false;
params.n_threads = 4;
if (run == 1) params.image_max_tokens = limit;
mtmd_context *projector = llama_dart_mtmd_init_from_file(projector_path, model, &params);
assert(projector != nullptr);
auto *chunks = mtmd_input_chunks_init();
const char *marker = mtmd_get_marker(projector);
const mtmd_input_text text{marker, std::strlen(marker), true, true};
assert(llama_dart_mtmd_tokenize(projector, chunks, &text, bitmaps, 1) == 0);
for (size_t i = 0; i < mtmd_input_chunks_size(chunks); ++i) {
const auto *chunk = mtmd_input_chunks_get(chunks, i);
if (mtmd_input_chunk_get_type(chunk) == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
counts[run] += mtmd_input_chunk_get_n_tokens(chunk);
if (encode && run == 1) {
assert(llama_dart_mtmd_encode_chunk(projector, chunk) == 0);
}
}
}
mtmd_input_chunks_free(chunks);
llama_dart_exit_free(projector);
}
std::printf("real image tokens: default=%zu capped=%zu\n", counts[0], counts[1]);
assert(counts[0] > static_cast<size_t>(limit) && counts[1] > 0 &&
counts[1] <= static_cast<size_t>(limit));
mtmd_bitmap_free(bitmap);
llama_dart_exit_free(model);
}

int main(int argc, char **argv) {
if (argc == 3 || argc == 4) {
const int limit = argc == 4 ? std::atoi(argv[3]) : 512;
real_image_limit(argv[1], argv[2], limit, argc == 4);
return 0;
}
const char *path = "image_token_limit_metadata.gguf";
const auto check = [path](const char *key, const char *type, int limit, int expected) {
gguf_context *metadata = gguf_init_empty();
if (type != nullptr) gguf_set_val_str(metadata, key, type);
assert(gguf_write_to_file(metadata, path, true));
gguf_free(metadata);
assert(llama_dart_mtmd_supports_image_token_limit(path, limit) == expected);
};
for (const char *type : {"gemma4v", "gemma4uv"}) {
for (int limit : {70, 256, 512, 1120}) {
check("clip.projector_type", type, limit, 1);
check("clip.vision.projector_type", type, limit, 1);
}
check("clip.projector_type", type, 69, 0);
check("clip.projector_type", type, 1121, 0);
}
for (const char *type : {"gemma3", "mlp", "gemma4a", "unknown"}) {
check("clip.projector_type", type, 512, 0);
}
check("clip.projector_type", nullptr, 512, 0);
gguf_context *mixed = gguf_init_empty();
gguf_set_val_str(mixed, "clip.projector_type", "gemma3");
gguf_set_val_str(mixed, "clip.vision.projector_type", "gemma4v");
assert(gguf_write_to_file(mixed, path, true));
assert(llama_dart_mtmd_supports_image_token_limit(path, 512) == 0);
gguf_set_val_str(mixed, "clip.projector_type", "");
assert(gguf_write_to_file(mixed, path, true));
assert(llama_dart_mtmd_supports_image_token_limit(path, 512) == 1);
gguf_free(mixed);
gguf_context *metadata = gguf_init_empty();
gguf_set_val_u32(metadata, "clip.projector_type", 7);
assert(gguf_write_to_file(metadata, path, true));
gguf_free(metadata);
assert(llama_dart_mtmd_supports_image_token_limit(path, 512) == 0);
assert(llama_dart_mtmd_supports_image_token_limit(path, 0) == -1);
assert(std::strstr(llama_dart_last_error(), "positive limit") != nullptr);
assert(llama_dart_mtmd_supports_image_token_limit(nullptr, 512) == -1);
std::remove(path);
assert(llama_dart_mtmd_supports_image_token_limit(path, 512) == -1);
assert(std::strstr(llama_dart_last_error(), "GGUF metadata") != nullptr);
// A later successful probe clears the caught-error slot.
check("clip.projector_type", "gemma4v", 512, 1);
assert(llama_dart_last_error() == nullptr || llama_dart_last_error()[0] == 0);
std::remove(path);
}
1 change: 1 addition & 0 deletions tools/validate_exports.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"llama_dart_model_load_from_file",
"llama_dart_init_from_model",
"llama_dart_mtmd_init_from_file",
"llama_dart_mtmd_supports_image_token_limit",
"llama_dart_decode",
"llama_dart_encode",
"llama_dart_synchronize",
Expand Down
Loading