mirror of
https://github.com/ollama/ollama.git
synced 2026-04-17 15:53:27 +02:00
* bench: add prompt calibration, context size flag, and NumCtx reporting Add --num-ctx flag to set context size, and report NumCtx in model info header. Calibrate tokens-per-word ratio during warmup using actual tokenization metrics from the model, replacing the fixed 1.3 heuristic. This produces more accurate prompt token counts for --prompt-tokens. Also add fetchContextLength() to query running model context via /api/ps. * integration: improve vision test robustness and add thinking tests Add skipIfNoVisionOverride() to skip vision tests when OLLAMA_TEST_MODEL is set to a non-vision model. Add Think:false to context exhaustion test to prevent thinking models from using all context before the test can measure it. Add third test image (ollama homepage) and replace OCR test with ImageDescription test using it. Relax match strings for broader model compatibility. Add TestThinkingEnabled and TestThinkingSuppressed to verify thinking output and channel tag handling. * gemma4: add Gemma 4 GGML model support Add full Gemma 4 model family support (E2B, E4B, 26B MoE, 31B Dense) for the GGML backend including text, vision, converter, parser, and renderer. Text model features: - Sliding window + full attention with per-layer patterns - KV sharing across layers with donor map - Per-layer embeddings (PLE) with learned projections - MoE routing with RMSNorm + learned scale - Proportional RoPE with freq_factors for global attention - Final logit softcapping Vision model features: - SigLIP vision encoder with 2D RoPE - ClippableLinear with input/output clamping via packed v.clamp_data - Adaptive average pooling with nMerge kernel - Multi-modal projection with unweighted RMSNorm Converter: - Safetensors to GGUF with vision tensor renaming - Fused MoE gate_up_proj splitting - Vision patch embedding reshape (HF to Conv2D layout) - Packed clamp data tensor for ClippableLinear bounds - Proportional RoPE freq_factors generation Also includes: - BackendGet() on ml.Tensor for reading weight tensor data - Q6_K CUDA get_rows kernel support - MoE-aware ffn_down quantization layer counting - Gemma4 parser with tool calling and thinking support - Gemma4 renderer with structured tool format - Architecture-based auto-detection of renderer/parser/stop tokens - Integration test gemma4 model list additions * gemma4: add audio support with USM conformer encoder Add audio encoding for Gemma 4 using the USM conformer architecture: - Converter: audio tensor mapping, SSCP/conformer/embedder name replacements, softplus repacker for per_dim_scale, F32 enforcement for conv weights - GGML backend: Conv1DDW and PadExt tensor ops - Audio encoder: SSCP Conv2D, 12 conformer blocks (FFW + block-local attention with relative position embeddings + LightConv1d + FFW), output projection, audio-to-text embedding projector - Audio preprocessing: WAV decode, mel spectrogram, FFT (pure Go) - Model wiring: WAV detection, audio token handling, unified PostTokenize Correctly transcribes "why is the sky blue" from test audio. * integration: add gemma4 audio tests including OpenAI API coverage Test audio transcription and response via the Ollama native API, plus two new tests exercising the OpenAI-compatible endpoints: - /v1/audio/transcriptions (multipart form upload) - /v1/chat/completions with input_audio content type All tests use capability checks and skip models without audio support. * gemma4: add OpenAI audio API support and capability detection - Add CapabilityAudio and detect from audio.block_count in GGUF - Add /v1/audio/transcriptions endpoint with TranscriptionMiddleware - Add input_audio content type support in /v1/chat/completions - Add TranscriptionRequest/Response types in openai package * gemma4: add audio input support for run command - /audio toggle in interactive mode for voice chat - Platform-specific microphone recording (AVFoundation on macOS, PulseAudio/ALSA on Linux, WASAPI on Windows) - Space to start/stop recording, automatic chunking for long audio * gemma4: add transcribe command (ollama transcribe MODEL) - Interactive mode with readline prompt and slash commands - Non-interactive mode for piped audio or record-until-Ctrl+C - Chunked streaming transcription for long recordings - Word-wrapped output matching run command style * gemma4: add parser, renderer, and integration test plumbing * gemma4: fix renderer to emit BOS token * gemma4: add OpenAI audio transcription API and input_audio support * gemma4: update converter for new weight drop naming * gemma4: add per_expert_scale to MoE router and fix moe_intermediate_size config * gemma4: rewrite renderer to match HF Jinja2 template exactly Fix 8 bugs found by building 55 reference tests verified against the HF Jinja2 chat template (VERIFY_JINJA2=1 shells out to Python): - Tool responses use separate <|turn>tool turns (not inline tags) - Tool calls emitted before content in assistant messages - Thinking content stripped from assistant history (strip_thinking) - User, tool, and system content trimmed (template does | trim) - Empty system message still emits system turn (check role, not content) - Nested object properties rendered recursively with required field - Array items specification rendered for array-type properties - OBJECT/ARRAY type-specific rendering comma logic matches template Also adds Required field to api.ToolProperty for nested object schemas, replaces old gemma4_test.go with comprehensive gemma4_reference_test.go, and commits the Jinja2 template as testdata for verification. * gemma4: fix MoE fused gate_up split and multiline tool-call arg parsing - Text MoE: split `ffn_gate_up_exps` into contiguous `[gate|up]` halves instead of stride-2 slices. - Parser: escape control characters in `<|"|>...<|"|>` string literals when converting tool-call args to JSON. - Fixes warnings like `invalid character '\n' in string literal` for multiline tool arguments. - Add Gemma4 parser regressions for multiline tool-call args and `gemma4ArgsToJSON`. * cmd: simplify audio input to dropped file attachments * gemma4: use full SWA memory for better cache reuse * gemma4: initialize clamps after backend load * convert: align gemma4 audio tensor renames with llama.cpp * Remove redundant comments in gemma4 vision model * Format Gemma4 MoE block field alignment * use 4096 kvcache.NewSWAMemCache * convert: support new Gemma4 audio_tower tensor naming (#15221) Co-authored-by: jmorganca <jmorganca@gmail.com> * fix integration test defaults for audio * review comments and lint fixes * remove unused audio/video files --------- Co-authored-by: jmorganca <jmorganca@gmail.com>
295 lines
11 KiB
Go
295 lines
11 KiB
Go
//go:build integration
|
||
|
||
package integration
|
||
|
||
import (
|
||
"context"
|
||
"log/slog"
|
||
"sync"
|
||
"testing"
|
||
"time"
|
||
|
||
"github.com/ollama/ollama/api"
|
||
)
|
||
|
||
func TestLongInputContext(t *testing.T) {
|
||
// Setting NUM_PARALLEL to 1 ensures the allocated context is exactly what
|
||
// we asked for and there is nothing extra that we could spill over into
|
||
t.Setenv("OLLAMA_NUM_PARALLEL", "1")
|
||
|
||
// Longer needed for small footprint GPUs
|
||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||
defer cancel()
|
||
// Set up the test data
|
||
req := api.ChatRequest{
|
||
Model: smol,
|
||
Messages: []api.Message{
|
||
{
|
||
Role: "user",
|
||
Content: "Oh, don’t speak to me of Austria. Perhaps I don’t understand things, but Austria never has wished, and does not wish, for war. She is betraying us! Russia alone must save Europe. Our gracious sovereign recognizes his high vocation and will be true to it. That is the one thing I have faith in! Our good and wonderful sovereign has to perform the noblest role on earth, and he is so virtuous and noble that God will not forsake him. He will fulfill his vocation and crush the hydra of revolution, which has become more terrible than ever in the person of this murderer and villain! We alone must avenge the blood of the just one.... Whom, I ask you, can we rely on?... England with her commercial spirit will not and cannot understand the Emperor Alexander’s loftiness of soul. She has refused to evacuate Malta. She wanted to find, and still seeks, some secret motive in our actions. What answer did Novosíltsev get? None. The English have not understood and cannot understand the self-abnegation of our Emperor who wants nothing for himself, but only desires the good of mankind. And what have they promised? Nothing! And what little they have promised they will not perform! Prussia has always declared that Buonaparte is invincible, and that all Europe is powerless before him.... And I don’t believe a word that Hardenburg says, or Haugwitz either. This famous Prussian neutrality is just a trap. I have faith only in God and the lofty destiny of our adored monarch. He will save Europe! What country is this referring to?",
|
||
},
|
||
},
|
||
Stream: &stream,
|
||
Options: map[string]any{
|
||
"temperature": 0,
|
||
"seed": 123,
|
||
"num_ctx": 128,
|
||
},
|
||
}
|
||
client, _, cleanup := InitServerConnection(ctx, t)
|
||
defer cleanup()
|
||
pullOrSkip(ctx, t, client, req.Model)
|
||
DoChat(ctx, t, client, req, []string{"russia", "german", "france", "england", "austria", "prussia", "europe", "individuals", "coalition", "conflict"}, 120*time.Second, 10*time.Second)
|
||
}
|
||
|
||
func TestContextExhaustion(t *testing.T) {
|
||
// Setting NUM_PARALLEL to 1 ensures the allocated context is exactly what
|
||
// we asked for and there is nothing extra that we could spill over into
|
||
t.Setenv("OLLAMA_NUM_PARALLEL", "1")
|
||
|
||
// Longer needed for small footprint GPUs
|
||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||
defer cancel()
|
||
// Set up the test data
|
||
thinkOff := api.ThinkValue{Value: false}
|
||
req := api.ChatRequest{
|
||
Model: smol,
|
||
Messages: []api.Message{
|
||
{
|
||
Role: "user",
|
||
Content: "Write me a story in english with a lot of emojis",
|
||
},
|
||
},
|
||
Think: &thinkOff,
|
||
Stream: &stream,
|
||
Options: map[string]any{
|
||
"temperature": 0,
|
||
"seed": 123,
|
||
"num_ctx": 128,
|
||
},
|
||
}
|
||
client, _, cleanup := InitServerConnection(ctx, t)
|
||
defer cleanup()
|
||
pullOrSkip(ctx, t, client, req.Model)
|
||
DoChat(ctx, t, client, req, []string{"once", "upon", "lived", "sunny", "cloudy", "clear", "water", "time", "travel", "world"}, 120*time.Second, 10*time.Second)
|
||
}
|
||
|
||
// Send multiple generate requests with prior context and ensure the response is coherant and expected
|
||
func TestParallelGenerateWithHistory(t *testing.T) {
|
||
if testModel != "" {
|
||
t.Skip("uses hardcoded model, not applicable with model override")
|
||
}
|
||
modelName := "gpt-oss:20b"
|
||
req, resp := GenerateRequests()
|
||
numParallel := 2
|
||
iterLimit := 2
|
||
|
||
softTimeout, hardTimeout := getTimeouts(t)
|
||
ctx, cancel := context.WithTimeout(context.Background(), hardTimeout)
|
||
defer cancel()
|
||
client, _, cleanup := InitServerConnection(ctx, t)
|
||
defer cleanup()
|
||
initialTimeout := 120 * time.Second
|
||
streamTimeout := 20 * time.Second
|
||
|
||
// Get the server running (if applicable) warm the model up with a single initial request
|
||
slog.Info("loading", "model", modelName)
|
||
err := client.Generate(ctx,
|
||
&api.GenerateRequest{Model: modelName, KeepAlive: &api.Duration{Duration: 10 * time.Second}},
|
||
func(response api.GenerateResponse) error { return nil },
|
||
)
|
||
if err != nil {
|
||
t.Fatalf("failed to load model %s: %s", modelName, err)
|
||
}
|
||
gpuPercent := getGPUPercent(ctx, t, client, modelName)
|
||
if gpuPercent < 80 {
|
||
slog.Warn("Low GPU percentage - increasing timeouts", "percent", gpuPercent)
|
||
initialTimeout = 240 * time.Second
|
||
streamTimeout = 30 * time.Second
|
||
}
|
||
|
||
var wg sync.WaitGroup
|
||
wg.Add(numParallel)
|
||
for i := range numParallel {
|
||
go func(i int) {
|
||
defer wg.Done()
|
||
k := i % len(req)
|
||
req[k].Model = modelName
|
||
for j := 0; j < iterLimit; j++ {
|
||
if time.Now().Sub(started) > softTimeout {
|
||
slog.Info("exceeded soft timeout, winding down test")
|
||
return
|
||
}
|
||
slog.Info("Starting", "thread", i, "iter", j)
|
||
// On slower GPUs it can take a while to process the concurrent requests
|
||
// so we allow a much longer initial timeout
|
||
c := DoGenerate(ctx, t, client, req[k], resp[k], initialTimeout, streamTimeout)
|
||
req[k].Context = c
|
||
req[k].Prompt = "tell me more!"
|
||
}
|
||
}(i)
|
||
}
|
||
wg.Wait()
|
||
}
|
||
|
||
// Send generate requests with prior context and ensure the response is coherant and expected
|
||
func TestGenerateWithHistory(t *testing.T) {
|
||
if testModel != "" {
|
||
// The Generate API's Context field (token array continuation) is not
|
||
// supported by all runners (e.g. MLX). Chat history works; this is
|
||
// the only generate-specific continuation path.
|
||
t.Skip("generate context continuation not supported by all runners")
|
||
}
|
||
req := api.GenerateRequest{
|
||
Model: smol,
|
||
Prompt: rainbowPrompt,
|
||
Stream: &stream,
|
||
KeepAlive: &api.Duration{Duration: 10 * time.Second},
|
||
Options: map[string]any{
|
||
"num_ctx": 16384,
|
||
},
|
||
}
|
||
|
||
softTimeout, hardTimeout := getTimeouts(t)
|
||
ctx, cancel := context.WithTimeout(context.Background(), hardTimeout)
|
||
defer cancel()
|
||
client, _, cleanup := InitServerConnection(ctx, t)
|
||
defer cleanup()
|
||
|
||
// Get the server running (if applicable) warm the model up with a single initial request
|
||
slog.Info("loading", "model", req.Model)
|
||
err := client.Generate(ctx,
|
||
&api.GenerateRequest{Model: req.Model, KeepAlive: &api.Duration{Duration: 10 * time.Second}, Options: req.Options},
|
||
func(response api.GenerateResponse) error { return nil },
|
||
)
|
||
if err != nil {
|
||
t.Fatalf("failed to load model %s: %s", req.Model, err)
|
||
}
|
||
|
||
req.Context = DoGenerate(ctx, t, client, req, rainbowExpected, 30*time.Second, 20*time.Second)
|
||
|
||
for i := 0; i < len(rainbowFollowups); i++ {
|
||
req.Prompt = rainbowFollowups[i]
|
||
if time.Now().Sub(started) > softTimeout {
|
||
slog.Info("exceeded soft timeout, winding down test")
|
||
return
|
||
}
|
||
req.Context = DoGenerate(ctx, t, client, req, rainbowExpected, 30*time.Second, 20*time.Second)
|
||
}
|
||
}
|
||
|
||
// Send multiple chat requests with prior context and ensure the response is coherant and expected
|
||
func TestParallelChatWithHistory(t *testing.T) {
|
||
if testModel != "" {
|
||
t.Skip("uses hardcoded model, not applicable with model override")
|
||
}
|
||
modelName := "gpt-oss:20b"
|
||
req, resp := ChatRequests()
|
||
numParallel := 2
|
||
iterLimit := 2
|
||
|
||
softTimeout, hardTimeout := getTimeouts(t)
|
||
ctx, cancel := context.WithTimeout(context.Background(), hardTimeout)
|
||
defer cancel()
|
||
client, _, cleanup := InitServerConnection(ctx, t)
|
||
defer cleanup()
|
||
initialTimeout := 120 * time.Second
|
||
streamTimeout := 20 * time.Second
|
||
|
||
// Get the server running (if applicable) warm the model up with a single initial empty request
|
||
slog.Info("loading", "model", modelName)
|
||
err := client.Generate(ctx,
|
||
&api.GenerateRequest{Model: modelName, KeepAlive: &api.Duration{Duration: 10 * time.Second}},
|
||
func(response api.GenerateResponse) error { return nil },
|
||
)
|
||
if err != nil {
|
||
t.Fatalf("failed to load model %s: %s", modelName, err)
|
||
}
|
||
gpuPercent := getGPUPercent(ctx, t, client, modelName)
|
||
if gpuPercent < 80 {
|
||
slog.Warn("Low GPU percentage - increasing timeouts", "percent", gpuPercent)
|
||
initialTimeout = 240 * time.Second
|
||
streamTimeout = 30 * time.Second
|
||
}
|
||
|
||
var wg sync.WaitGroup
|
||
wg.Add(numParallel)
|
||
for i := range numParallel {
|
||
go func(i int) {
|
||
defer wg.Done()
|
||
k := i % len(req)
|
||
req[k].Model = modelName
|
||
for j := 0; j < iterLimit; j++ {
|
||
if time.Now().Sub(started) > softTimeout {
|
||
slog.Info("exceeded soft timeout, winding down test")
|
||
return
|
||
}
|
||
slog.Info("Starting", "thread", i, "iter", j)
|
||
// On slower GPUs it can take a while to process the concurrent requests
|
||
// so we allow a much longer initial timeout
|
||
assistant := DoChat(ctx, t, client, req[k], resp[k], initialTimeout, streamTimeout)
|
||
if assistant == nil {
|
||
t.Fatalf("didn't get an assistant response for context")
|
||
}
|
||
req[k].Messages = append(req[k].Messages,
|
||
*assistant,
|
||
api.Message{Role: "user", Content: "tell me more!"},
|
||
)
|
||
}
|
||
}(i)
|
||
}
|
||
wg.Wait()
|
||
}
|
||
|
||
// Send generate requests with prior context and ensure the response is coherant and expected
|
||
func TestChatWithHistory(t *testing.T) {
|
||
req := api.ChatRequest{
|
||
Model: smol,
|
||
Stream: &stream,
|
||
KeepAlive: &api.Duration{Duration: 10 * time.Second},
|
||
Options: map[string]any{
|
||
"num_ctx": 16384,
|
||
},
|
||
Messages: []api.Message{
|
||
{
|
||
Role: "user",
|
||
Content: rainbowPrompt,
|
||
},
|
||
},
|
||
}
|
||
|
||
softTimeout, hardTimeout := getTimeouts(t)
|
||
ctx, cancel := context.WithTimeout(context.Background(), hardTimeout)
|
||
defer cancel()
|
||
client, _, cleanup := InitServerConnection(ctx, t)
|
||
defer cleanup()
|
||
|
||
// Get the server running (if applicable) warm the model up with a single initial request
|
||
slog.Info("loading", "model", req.Model)
|
||
err := client.Generate(ctx,
|
||
&api.GenerateRequest{Model: req.Model, KeepAlive: &api.Duration{Duration: 10 * time.Second}, Options: req.Options},
|
||
func(response api.GenerateResponse) error { return nil },
|
||
)
|
||
if err != nil {
|
||
t.Fatalf("failed to load model %s: %s", req.Model, err)
|
||
}
|
||
|
||
assistant := DoChat(ctx, t, client, req, rainbowExpected, 30*time.Second, 20*time.Second)
|
||
|
||
for i := 0; i < len(rainbowFollowups); i++ {
|
||
if time.Now().Sub(started) > softTimeout {
|
||
slog.Info("exceeded soft timeout, winding down test")
|
||
return
|
||
}
|
||
req.Messages = append(req.Messages,
|
||
*assistant,
|
||
api.Message{Role: "user", Content: rainbowFollowups[i]},
|
||
)
|
||
|
||
assistant = DoChat(ctx, t, client, req, rainbowExpected, 30*time.Second, 20*time.Second)
|
||
if assistant == nil {
|
||
t.Fatalf("didn't get an assistant response for context")
|
||
}
|
||
}
|
||
}
|