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>
260 lines
7.0 KiB
Go
260 lines
7.0 KiB
Go
//go:build integration
|
|
|
|
package integration
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"mime/multipart"
|
|
"net/http"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/ollama/ollama/api"
|
|
)
|
|
|
|
var defaultAudioModels = []string{
|
|
"gemma4:e2b",
|
|
"gemma4:e4b",
|
|
}
|
|
|
|
// decodeTestAudio returns the test audio clip ("Why is the sky blue?", 16kHz mono WAV).
|
|
func decodeTestAudio(t *testing.T) api.ImageData {
|
|
t.Helper()
|
|
data, err := base64.StdEncoding.DecodeString(audioEncodingPrompt)
|
|
if err != nil {
|
|
t.Fatalf("failed to decode test audio: %v", err)
|
|
}
|
|
return data
|
|
}
|
|
|
|
// setupAudioModel pulls the model, preloads it, and skips if it doesn't support audio.
|
|
func setupAudioModel(ctx context.Context, t *testing.T, client *api.Client, model string) {
|
|
t.Helper()
|
|
requireCapability(ctx, t, client, model, "audio")
|
|
pullOrSkip(ctx, t, client, model)
|
|
err := client.Generate(ctx, &api.GenerateRequest{Model: model}, func(response api.GenerateResponse) error { return nil })
|
|
if err != nil {
|
|
t.Fatalf("failed to load model %s: %s", model, err)
|
|
}
|
|
}
|
|
|
|
// TestAudioTranscription tests that the model can transcribe audio to text.
|
|
func TestAudioTranscription(t *testing.T) {
|
|
for _, model := range testModels(defaultAudioModels) {
|
|
t.Run(model, func(t *testing.T) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
|
defer cancel()
|
|
client, _, cleanup := InitServerConnection(ctx, t)
|
|
defer cleanup()
|
|
|
|
setupAudioModel(ctx, t, client, model)
|
|
audio := decodeTestAudio(t)
|
|
noThink := &api.ThinkValue{Value: false}
|
|
|
|
req := api.ChatRequest{
|
|
Model: model,
|
|
Think: noThink,
|
|
Messages: []api.Message{
|
|
{
|
|
Role: "system",
|
|
Content: "Transcribe the audio exactly as spoken. Output only the transcription.",
|
|
},
|
|
{
|
|
Role: "user",
|
|
Content: "Transcribe this audio.",
|
|
Images: []api.ImageData{audio},
|
|
},
|
|
},
|
|
Stream: &stream,
|
|
Options: map[string]any{
|
|
"temperature": 0,
|
|
"seed": 123,
|
|
"num_predict": 50,
|
|
},
|
|
}
|
|
|
|
// The audio says "Why is the sky blue?" — expect key words in transcription.
|
|
DoChat(ctx, t, client, req, []string{"sky", "blue"}, 60*time.Second, 10*time.Second)
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestAudioResponse tests that the model can respond to a spoken question.
|
|
func TestAudioResponse(t *testing.T) {
|
|
for _, model := range testModels(defaultAudioModels) {
|
|
t.Run(model, func(t *testing.T) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
|
defer cancel()
|
|
client, _, cleanup := InitServerConnection(ctx, t)
|
|
defer cleanup()
|
|
|
|
setupAudioModel(ctx, t, client, model)
|
|
audio := decodeTestAudio(t)
|
|
noThink := &api.ThinkValue{Value: false}
|
|
|
|
req := api.ChatRequest{
|
|
Model: model,
|
|
Think: noThink,
|
|
Messages: []api.Message{
|
|
{
|
|
Role: "user",
|
|
Content: "",
|
|
Images: []api.ImageData{audio},
|
|
},
|
|
},
|
|
Stream: &stream,
|
|
Options: map[string]any{
|
|
"temperature": 0,
|
|
"seed": 123,
|
|
"num_predict": 200,
|
|
},
|
|
}
|
|
|
|
// The audio asks "Why is the sky blue?" — expect an answer about light/scattering.
|
|
DoChat(ctx, t, client, req, []string{
|
|
"scatter", "light", "blue", "atmosphere", "wavelength", "rayleigh",
|
|
}, 60*time.Second, 10*time.Second)
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestOpenAIAudioTranscription tests the /v1/audio/transcriptions endpoint.
|
|
func TestOpenAIAudioTranscription(t *testing.T) {
|
|
for _, model := range testModels(defaultAudioModels) {
|
|
t.Run(model, func(t *testing.T) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
|
defer cancel()
|
|
client, endpoint, cleanup := InitServerConnection(ctx, t)
|
|
defer cleanup()
|
|
|
|
setupAudioModel(ctx, t, client, model)
|
|
audioBytes := decodeTestAudio(t)
|
|
|
|
// Build multipart form request.
|
|
var body bytes.Buffer
|
|
writer := multipart.NewWriter(&body)
|
|
writer.WriteField("model", model)
|
|
part, err := writer.CreateFormFile("file", "prompt.wav")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
part.Write(audioBytes)
|
|
writer.Close()
|
|
|
|
url := fmt.Sprintf("http://%s/v1/audio/transcriptions", endpoint)
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, &body)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
req.Header.Set("Content-Type", writer.FormDataContentType())
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
t.Fatalf("request failed: %v", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
respBody, _ := io.ReadAll(resp.Body)
|
|
t.Fatalf("expected 200, got %d: %s", resp.StatusCode, string(respBody))
|
|
}
|
|
|
|
respBody, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
text := strings.ToLower(string(respBody))
|
|
if !strings.Contains(text, "sky") && !strings.Contains(text, "blue") {
|
|
t.Errorf("transcription response missing expected words, got: %s", string(respBody))
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestOpenAIChatWithAudio tests /v1/chat/completions with input_audio content.
|
|
func TestOpenAIChatWithAudio(t *testing.T) {
|
|
for _, model := range testModels(defaultAudioModels) {
|
|
t.Run(model, func(t *testing.T) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
|
defer cancel()
|
|
client, endpoint, cleanup := InitServerConnection(ctx, t)
|
|
defer cleanup()
|
|
|
|
setupAudioModel(ctx, t, client, model)
|
|
audioB64 := audioEncodingPrompt
|
|
|
|
reqBody := fmt.Sprintf(`{
|
|
"model": %q,
|
|
"messages": [{
|
|
"role": "user",
|
|
"content": [
|
|
{"type": "input_audio", "input_audio": {"data": %q, "format": "wav"}}
|
|
]
|
|
}],
|
|
"temperature": 0,
|
|
"seed": 123,
|
|
"max_tokens": 200,
|
|
"think": false
|
|
}`, model, strings.TrimSpace(audioB64))
|
|
|
|
url := fmt.Sprintf("http://%s/v1/chat/completions", endpoint)
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader(reqBody))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
t.Fatalf("request failed: %v", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
respBody, _ := io.ReadAll(resp.Body)
|
|
t.Fatalf("expected 200, got %d: %s", resp.StatusCode, string(respBody))
|
|
}
|
|
|
|
respBytes, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
t.Fatalf("failed to read response: %v", err)
|
|
}
|
|
|
|
var result struct {
|
|
Choices []struct {
|
|
Message struct {
|
|
Content string `json:"content"`
|
|
Reasoning string `json:"reasoning"`
|
|
} `json:"message"`
|
|
} `json:"choices"`
|
|
}
|
|
if err := json.Unmarshal(respBytes, &result); err != nil {
|
|
t.Fatalf("failed to decode response: %v", err)
|
|
}
|
|
|
|
if len(result.Choices) == 0 {
|
|
t.Fatal("no choices in response")
|
|
}
|
|
|
|
text := strings.ToLower(result.Choices[0].Message.Content + " " + result.Choices[0].Message.Reasoning)
|
|
found := false
|
|
for _, word := range []string{"sky", "blue", "scatter", "light", "atmosphere"} {
|
|
if strings.Contains(text, word) {
|
|
found = true
|
|
break
|
|
}
|
|
}
|
|
if !found {
|
|
t.Errorf("response missing expected words about sky/blue/light, got: %s", result.Choices[0].Message.Content)
|
|
}
|
|
})
|
|
}
|
|
}
|