mirror of
https://github.com/ollama/ollama.git
synced 2026-06-02 21:34:51 -04:00
* broad lint fixes to sidestep CI scope glitch * runner: Remove CGO engines, use llama-server exclusively for GGML models Remove the vendored GGML and llama.cpp backend, CGO runner, Go model implementations, and sample. llama-server (built from upstream llama.cpp via FetchContent) is now the sole inference engine for GGUF-based models. (Safetensor based models continue to run on the new MLX engine.) This allows us to more rapidly pick up new capabilities and fixes from llama.cpp as they come out. On windows this now requires recent AMD driver versions to support ROCm v7 as llama.cpp currently does not support building against v6. * llama/compat: load Ollama-format GGUFs in llama-server Squashed from upstream/jmorganca/llama-compat on 2026-04-29. Source tip:0c33775d37. Original source commits: -25223160dllama/compat: add in-memory shim so llama-server can load Ollama-format GGUFs -7449b539allm,server: route Ollama-format gemma3 blobs through llama/compat -436f2e2b1llama/compat: make patch-apply idempotent -8c2c9d4c8llama/compat: extend gemma3 handler to cover 1B and 270M blobs -021389f7bllama/compat: shrink clip.cpp injection from 18 lines to 1 -61b367ec2llama/compat: shrink patch to pure call-site hooks (34 -> 20 lines) -36049361cllama/compat: simplify shim (gemma3-tested) -8fa664865llama/compat: add qwen35moe text handler -db0c74530llama/compat: add qwen35moe vision (clip) support -2a388da77llama/compat: split shared infra into a util TU -9a69a17dcllama/compat: document non-public API dependencies -d0f38a915llama/compat: add gpt-oss and lfm2 handlers -086071822llama/compat: add mistral3 text handler (vision TODO) -63bde9ff7llama/compat: add mistral3 vision (clip) support -3a57b89d5llama/compat: apply LLaMA RoPE permute to mistral3 vision Q/K -99cb87439llama/compat: add qwen35, gemma4, deepseek-ocr handlers -2c7850dballama/compat: add nemotron_h_moe handler (latent FFN + MTP skip) -9e3b54225llama/compat: add llama4 text + clip handlers -034fee349llama/compat: add gemma4 clip handler (gemma4v projector) -9945c5a93server: remove dhiltgen/* compat redirect table -5d4539101llama/compat: rewrite gemma4 tokenizer model to BPE -7e0765327llama/compat: add glm-ocr text handler + text-loader load-op hook -f1bd1a25allama/compat: add glm-ocr clip handler (glm4v projector) -4b5cf3420llama/compat: collapse text-loader hook back to one new patch line -eb4ecf4fcllama/compat: extend gemma4 clip handler to gemma4a (audio) -a23a5e76fllama/compat: fix gemma4a per-block norm tensor mapping -cd2dcaff4llama/compat: add embeddinggemma handler -1ce8a6b26llama/compat: add qwen3-vl + qwen2.5-vl handlers -fd98ffa1ellama/compat: add gemma3n + glm4moelite handlers -cc7bdf0bcllama/compat: handle null buft in maybe_load_tensor -0c33775d3llama/compat: disable mmap when load_op transforms text-side tensors * refine implementation * ci: fix windows MLX build * ci: fix windows llama-server build * ci: fix windows rocm build * ci: windows mlx tuning Shorten long-tail on build, and get OllamaSetup.exe back under 2g limit * ci: fix windows dependencies * win: fix dependency gathering * disable openmp * win: arm64 cross-compile build also DRY out CI steps * scheduler improvements * ci: improvements from #15982 * win: favor ninja for faster developer builds * win: fix build * win: fix arm64 cross-compile * win: avoid spaces in compiler path * misc discovery fixes, and bos handling * lint fixes * win: fix arm cross-compile build/CI bugs * llama.cpp update * win: handle multiple CRT dirs * vulkan: add windows iGPU detection * fix creation bugs for patched models, other refactoring work * tune batch size for better performance * ci and lint fixes * fix repeat_last_n bug * build: revamp build for better developer UX * amd, sampler, qwen3next fixes * version bump * fix mlx build * revamp GPU discovery Scanning the output of llama-server is turning out to be too error prone across llama.cpp updates, so this switches to a thin dynamic library load against the bundled GGML libraries so more details can be gathered from the API. * version bump * missing file * ci: fix cache miss on rocm build * refine vulkan dep handling * fix ps reporting bug on full GPU load * improve cmake wiring for customized local builds * version bump * docker build arg cleanup * improve windows exit error logs * fix community gemma4 support and ci flakes * fix mlx unit test * tighten up ps logic to avoid double counting fit log lines * version bump * fix ps view for full gpu layer offload * add MTP wiring for llama-server and create with GGUFs * pick best template by capabilities * version bump * ci: harden apt repos * remove unused cpu core discovery * adjust batch default logic to reduce OOMs * support larger tool calls * fix audio support, template show * qwen35 mtp patch support * flesh out dtypes * rocm deps * version bump * lint fix * block broken gfx1150 on windows * fix qwen3.5 moe mtp tensors in patch * mmproj oom fallback and vulkan on by default * qwen MTP compat fix * version bump * ci: fix WoA cross-compile * ci: workaround ui tool in cross-compile * version bump * win: enable OpenMP for CPU builds * build: improve developer UX * ci: windows path workaround for CPU build * win: fix WoA dependencies * win: fix large offset reads for mmproj patched loads * version bump * fix vulkan dup detection * add OLLAMA_IGPU_ENABLE and largely disable iGPUs by default * opt-in MTP, win large offset, integraton fixes * fix unit test scheduler interaction hang * fix multi-gpu filtering * version bump * review comments * fix thinking level * fix linux rocm ordering and granite 3.3 template * version bump * ci fix - non-shallow MLX checkout * bypass linux sysfs unit test on windows --------- Co-authored-by: jmorganca <jmorganca@gmail.com>
327 lines
9.1 KiB
Go
327 lines
9.1 KiB
Go
package server
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"maps"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
|
|
fsggml "github.com/ollama/ollama/fs/ggml"
|
|
"github.com/ollama/ollama/llm"
|
|
"github.com/ollama/ollama/manifest"
|
|
)
|
|
|
|
// findLlamaQuantize locates the llama-quantize binary (installed alongside llama-server).
|
|
func findLlamaQuantize() (string, error) {
|
|
return llm.FindLlamaCppBinary("llama-quantize")
|
|
}
|
|
|
|
// progressRegex matches llama-quantize output lines like "[ 42/ 200]"
|
|
var progressRegex = regexp.MustCompile(`\[\s*(\d+)/\s*(\d+)\]`)
|
|
|
|
const llamaCppCompatEnv = "OLLAMA_LLAMA_CPP_COMPAT"
|
|
|
|
var runLlamaQuantize = runLlamaQuantizeCommand
|
|
|
|
// quantize re-quantizes a GGUF model by shelling out to llama-quantize.
|
|
// Embedded compatibility tensors are restored afterward because llama.cpp's
|
|
// text model loader intentionally does not claim those tensors.
|
|
func quantize(in, out *os.File, orig *fsggml.GGML, newFileType fsggml.FileType, progressFn func(n uint64)) error {
|
|
typeName := newFileType.String()
|
|
if typeName == "" {
|
|
return fmt.Errorf("unsupported quantization type: %v", newFileType)
|
|
}
|
|
if err := runLlamaQuantize(in, out, orig, newFileType, typeName, progressFn); err != nil {
|
|
return err
|
|
}
|
|
if hasEmbeddedCompatibilityTensors(orig) {
|
|
if err := restoreEmbeddedCompatibilityTensors(in, out, orig, newFileType); err != nil {
|
|
return fmt.Errorf("failed to restore embedded compatibility tensors: %w", err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func copyGGUFWithLlamaQuantize(in, out *os.File, orig *fsggml.GGML, progressFn func(n uint64)) error {
|
|
return runLlamaQuantize(in, out, orig, orig.KV().FileType(), "COPY", progressFn)
|
|
}
|
|
|
|
func needsDefaultLlavaProjectorType(ggml *fsggml.GGML) bool {
|
|
kv := ggml.KV()
|
|
if kv.Architecture() != "clip" || !kv.Bool("has_vision_encoder") {
|
|
return false
|
|
}
|
|
if _, ok := kv["clip.projector_type"]; ok {
|
|
return false
|
|
}
|
|
if _, ok := kv["clip.vision.projector_type"]; ok {
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func addDefaultLlavaProjectorType(layer *layerGGML) (*layerGGML, error) {
|
|
blob, err := manifest.BlobsPath(layer.Digest)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
fp, err := os.Open(blob)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer fp.Close()
|
|
|
|
temp, err := os.CreateTemp(filepath.Dir(blob), "projector-metadata")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer os.Remove(temp.Name())
|
|
defer temp.Close()
|
|
|
|
kv := maps.Clone(layer.GGML.KV())
|
|
kv["clip.projector_type"] = "mlp"
|
|
|
|
tensors := make([]*fsggml.Tensor, 0, len(layer.GGML.Tensors().Items()))
|
|
for _, tensor := range layer.GGML.Tensors().Items() {
|
|
tensors = append(tensors, tensorFromFile(fp, layer.GGML.Tensors().Offset+tensor.Offset, tensor))
|
|
}
|
|
|
|
if err := fsggml.WriteGGUF(temp, kv, tensors); err != nil {
|
|
return nil, err
|
|
}
|
|
if _, err := temp.Seek(0, io.SeekStart); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
newLayer, err := manifest.NewLayer(temp, layer.MediaType)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if _, err := temp.Seek(0, io.SeekStart); err != nil {
|
|
return nil, err
|
|
}
|
|
f, err := fsggml.Decode(temp, 1024)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &layerGGML{Layer: newLayer, GGML: f}, nil
|
|
}
|
|
|
|
func runLlamaQuantizeCommand(in, out *os.File, orig *fsggml.GGML, newFileType fsggml.FileType, typeName string, progressFn func(n uint64)) error {
|
|
quantizeExe, err := findLlamaQuantize()
|
|
if err != nil {
|
|
return fmt.Errorf("llama-quantize unavailable: %w", err)
|
|
}
|
|
|
|
slog.Info("quantizing model", "type", typeName, "input", in.Name(), "output", out.Name())
|
|
|
|
args := llamaQuantizeArgs(orig.KV().Architecture(), newFileType, in.Name(), out.Name(), typeName)
|
|
cmd := exec.Command(quantizeExe, args...)
|
|
cmd.Env = llamaQuantizeEnv(os.Environ(), hasEmbeddedCompatibilityTensors(orig))
|
|
|
|
// Parse progress from stdout
|
|
stdout, err := cmd.StdoutPipe()
|
|
if err != nil {
|
|
return fmt.Errorf("failed to create stdout pipe: %w", err)
|
|
}
|
|
cmd.Stderr = os.Stderr
|
|
|
|
if err := cmd.Start(); err != nil {
|
|
return fmt.Errorf("failed to start llama-quantize: %w", err)
|
|
}
|
|
|
|
// Track total tensor size for progress reporting
|
|
totalSize := uint64(0)
|
|
for _, t := range orig.Tensors().Items() {
|
|
totalSize += t.Size()
|
|
}
|
|
|
|
var lastReported uint64
|
|
scanner := bufio.NewScanner(stdout)
|
|
for scanner.Scan() {
|
|
line := scanner.Text()
|
|
if matches := progressRegex.FindStringSubmatch(line); len(matches) == 3 {
|
|
current, _ := strconv.ParseUint(matches[1], 10, 64)
|
|
total, _ := strconv.ParseUint(matches[2], 10, 64)
|
|
if total > 0 && progressFn != nil {
|
|
// progressFn expects incremental byte deltas
|
|
done := totalSize * current / total
|
|
if done > lastReported {
|
|
progressFn(done - lastReported)
|
|
lastReported = done
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if err := cmd.Wait(); err != nil {
|
|
return fmt.Errorf("llama-quantize failed: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func disableLlamaCppCompat(env []string) []string {
|
|
out := make([]string, 0, len(env)+1)
|
|
prefix := llamaCppCompatEnv + "="
|
|
for _, entry := range env {
|
|
if !strings.HasPrefix(entry, prefix) {
|
|
out = append(out, entry)
|
|
}
|
|
}
|
|
return append(out, llamaCppCompatEnv+"=0")
|
|
}
|
|
|
|
func llamaQuantizeEnv(env []string, enableCompat bool) []string {
|
|
if !enableCompat {
|
|
return disableLlamaCppCompat(env)
|
|
}
|
|
|
|
out := make([]string, 0, len(env))
|
|
prefix := llamaCppCompatEnv + "="
|
|
for _, entry := range env {
|
|
if !strings.HasPrefix(entry, prefix) {
|
|
out = append(out, entry)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
type tensorSection struct {
|
|
*io.SectionReader
|
|
}
|
|
|
|
func (r tensorSection) WriteTo(w io.Writer) (int64, error) {
|
|
return io.Copy(w, r.SectionReader)
|
|
}
|
|
|
|
func restoreEmbeddedCompatibilityTensors(in, out *os.File, orig *fsggml.GGML, newFileType fsggml.FileType) error {
|
|
if _, err := out.Seek(0, io.SeekStart); err != nil {
|
|
return err
|
|
}
|
|
|
|
rewritten, err := fsggml.Decode(out, -1)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
kv := maps.Clone(orig.KV())
|
|
kv["general.file_type"] = newFileType
|
|
|
|
present := map[string]struct{}{}
|
|
tensors := make([]*fsggml.Tensor, 0, len(rewritten.Tensors().Items()))
|
|
for _, tensor := range rewritten.Tensors().Items() {
|
|
if isEmbeddedCompatibilityTensor(tensor.Name) {
|
|
continue
|
|
}
|
|
present[tensor.Name] = struct{}{}
|
|
tensors = append(tensors, tensorFromFile(out, rewritten.Tensors().Offset+tensor.Offset, tensor))
|
|
}
|
|
|
|
var restored int
|
|
for _, tensor := range orig.Tensors().Items() {
|
|
if !isEmbeddedCompatibilityTensor(tensor.Name) {
|
|
continue
|
|
}
|
|
if _, ok := present[tensor.Name]; ok {
|
|
continue
|
|
}
|
|
tensors = append(tensors, tensorFromFile(in, orig.Tensors().Offset+tensor.Offset, tensor))
|
|
restored++
|
|
}
|
|
if restored == 0 {
|
|
return nil
|
|
}
|
|
|
|
temp, err := os.CreateTemp(filepath.Dir(out.Name()), "compat-tensors")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer os.Remove(temp.Name())
|
|
defer temp.Close()
|
|
|
|
if err := fsggml.WriteGGUF(temp, kv, tensors); err != nil {
|
|
return err
|
|
}
|
|
if _, err := temp.Seek(0, io.SeekStart); err != nil {
|
|
return err
|
|
}
|
|
if err := out.Truncate(0); err != nil {
|
|
return err
|
|
}
|
|
if _, err := out.Seek(0, io.SeekStart); err != nil {
|
|
return err
|
|
}
|
|
if _, err := io.Copy(out, temp); err != nil {
|
|
return err
|
|
}
|
|
|
|
slog.Info("restored embedded compatibility tensors after llama-quantize", "count", restored)
|
|
return nil
|
|
}
|
|
|
|
func tensorFromFile(file *os.File, offset uint64, tensor *fsggml.Tensor) *fsggml.Tensor {
|
|
return &fsggml.Tensor{
|
|
Name: tensor.Name,
|
|
Kind: tensor.Kind,
|
|
Shape: append([]uint64(nil), tensor.Shape...),
|
|
WriterTo: tensorSection{
|
|
SectionReader: io.NewSectionReader(file, int64(offset), int64(tensor.Size())),
|
|
},
|
|
}
|
|
}
|
|
|
|
func llamaQuantizeArgs(arch string, newFileType fsggml.FileType, input, output, typeName string) []string {
|
|
args := []string{"--allow-requantize"}
|
|
if typeName == "COPY" {
|
|
return append(args, input, output, typeName)
|
|
}
|
|
// gemma3n's per_layer_token_embd is read on every layer for every token
|
|
// (not just once at input like token_embd), so it's far more quality-sensitive
|
|
// than a normal token embedding. Keep it at F16 on K-quants via an anchored
|
|
// regex so we don't also bump token_embd (which --token-embedding-type would).
|
|
if arch == "gemma3n" {
|
|
switch newFileType {
|
|
case fsggml.FileTypeQ4_K_S, fsggml.FileTypeQ4_K_M:
|
|
args = append(args, "--tensor-type", `^per_layer_token_embd\.weight$=f16`)
|
|
}
|
|
}
|
|
// deepseek2 MLA tensors are small, critical matrices in DeepSeek-V2-style
|
|
// multi-head latent attention. Keep the same higher-precision policy used
|
|
// by published library/glm-4.7-flash K-quant models.
|
|
if arch == "deepseek2" {
|
|
switch newFileType {
|
|
case fsggml.FileTypeQ4_K_S, fsggml.FileTypeQ4_K_M:
|
|
args = append(args,
|
|
"--tensor-type", `attn_k_b\.weight$=q8_0`,
|
|
"--tensor-type", `attn_q_a\.weight$=q8_0`,
|
|
"--tensor-type", `attn_q_b\.weight$=q8_0`,
|
|
"--tensor-type", `attn_v_b\.weight$=q8_0`,
|
|
"--tensor-type", `attn_kv_a_mqa\.weight$=q8_0`,
|
|
)
|
|
}
|
|
}
|
|
// GLM-OCR is a small multimodal OCR model; keeping the input/output
|
|
// embeddings high precision avoids degenerate text output on K-quants.
|
|
// Legacy Ollama GGUFs use "glmocr"; split text GGUFs use llama.cpp's
|
|
// native "glm4" architecture.
|
|
if arch == "glmocr" || arch == "glm4" {
|
|
switch newFileType {
|
|
case fsggml.FileTypeQ4_K_S, fsggml.FileTypeQ4_K_M:
|
|
args = append(args,
|
|
"--tensor-type", `^token_embd\.weight$=f16`,
|
|
"--tensor-type", `^output\.weight$=f16`,
|
|
)
|
|
}
|
|
}
|
|
return append(args, input, output, typeName)
|
|
}
|