Files
LocalAI/core/config/gguf_header_cache.go
T
mudler-agentandEttore Di Giacinto c7ce0c602c fix: stop listing the models directory on request paths and cache GGUF header reads (#12683)
* fix(http): stop listing the models directory on embeddings and bearer requests

Every embeddings request read the whole models directory before the body
was parsed, even when the body named its model. On a network-backed
models directory this cost seconds per request.

Embeddings now binds the body first and looks up a default model only
when the body has none, like chat. The pre-bind default lookup and the
gpt-4o constant default are gone from that route.

The first-available default lookup skips the directory when the filter
cannot accept an unconfigured file. Every usecase filter rejects files
without a config, so the scan never added results for them. Match-all,
nil and name filters keep the scan.

The bearer token check is now an exact test: a configured name, or one
stat of that name in the models directory. The value is a literal, not a
regular expression, and a name that is not a local relative path never
matches a file.

Assisted-by: Claude Code:claude-haiku-5-5

* perf(config): cache GGUF header reads for model defaults

Model defaults re-parsed the GGUF header on every SetDefaults call, which
runs per request and at startup reload. Put a bounded LRU in front of the
parser, keyed by absolute path and validated by size and modification
time. The cached value is a snapshot of the fields the defaults use, not
the parser output.

A changed size or mtime is a miss. Missing files and parse errors are not
cached, so the existing fallback is unchanged. LOCALAI_DISABLE_GUESSING,
the empty-path guard, the alias early return, the panic recovery and the
context-size default are all kept in front of the cache.

Assisted-by: Claude:claude-haiku-5-5

* test(http): cover listing-free default lookup on every usecase route

Assisted-by: Claude Code:claude-haiku-5-5

* feat(config): persist the GGUF header cache per instance

The header cache kept parsed GGUF results only in memory, so every restart
parsed each model file again before its defaults were known. Write the cache
to a per-instance file in the data path and load it at startup. A restarted
frontend with a fixed instance ID starts warm.

The file is versioned and records the estimator inputs (gguf-parser version,
candidate contexts, auto context size, offload count). A mismatch on any of
them makes the file ignored. Each entry keeps path, size and mtime, so a
changed model file is a miss on load. Writes run on one background saver,
debounced, through a temp file and rename. The entry bound applies to the
file as well. Without a data path the cache stays in memory only.

Documented as a per-instance exception in the model configuration docs.

Assisted-by: Claude:claude-haiku-5-5

* docs(embeddings): document model selection and the no-model error

Assisted-by: Claude Code:claude-haiku-5-5

* refactor(config): split the header cache into a generic cache

The GGUF header cache mixed two things: the mechanics (bounded LRU keyed
by path and identity, per-instance file, debounced atomic save, tolerant
load) and the GGUF fields. Move the mechanics into headerCache[S], driven
by a headerCacheSpec[S] that names the file prefix, schema, fingerprint,
parser and the snapshot encode/decode pair. The GGUF cache becomes one
instance of it.

File names, the identity check, LRU size, debounce, atomic write and the
corruption handling are unchanged. The on-disk JSON keeps the "estimator"
key so existing files still load.

Assisted-by: Claude Code:claude-haiku-5-5

* feat(config): share one GGUF header cache file between frontends

Every frontend used to write its own header cache file, named after its
instance ID, so a header read by one frontend was never reused by another.
The cache now uses one file, header-cache.json, in the data path, for all
frontends and for standalone mode. The instance ID no longer changes the
file name.

Frontends share the file in three ways. A save first merges the file's
entries in, so one frontend's write does not drop another's entries. A
miss reloads the file when its modification time has changed, and a hit
never reads it. Writes go to a temp file that is renamed into place, so a
reader never sees a partial file.

Two frontends saving at the same moment can still drop each other's last
entries. That costs one re-parse, never a wrong value, because every
entry is checked against its model file before use.

The shared file is valid only when every frontend mounts the same data
volume. The distributed-mode and model-configuration docs state this mode
and its volume limit.

Assisted-by: Claude:claude-haiku-5-5

* feat(config): give an instance ID its own header cache file

Assisted-by: Claude Code:claude-haiku-5-5

* style(config): gofmt the distributed config struct

Assisted-by: Claude Code:claude-haiku-5-5

---------

Co-authored-by: Ettore Di Giacinto <mudler@localai.io>
2026-10-14 01:06:14 +02:00

160 lines
5.7 KiB
Go

// SPDX-License-Identifier: MIT
package config
import (
gguf "github.com/gpustack/gguf-parser-go"
)
// ggufHeaderCacheSize bounds the in-memory header cache. Each entry is a few
// hundred bytes, so this covers a large model directory while keeping the
// memory footprint trivial. Entries past the bound are evicted least recently
// used and simply re-parsed on their next use.
const ggufHeaderCacheSize = 256
// ggufParser matches gguf.ParseGGUFFile and is the seam tests use to count
// header reads.
type ggufParser func(string, ...gguf.GGUFReadOption) (*gguf.GGUFFile, error)
// ggufHeader is the set of values model defaults read from a parsed GGUF. It
// is the only thing kept between requests: the parser output (tensors, the
// full metadata map) is not. Every field is a property of the file bytes, so a
// snapshot stays valid for as long as the file identity does not change.
type ggufHeader struct {
Name string // general.name, falling back as the parser does
Architecture string // general.architecture
MaxContextLength int // architecture's trained maximum, 0 when absent
BOSTokenID int64 // tokenizer, for diagnostic logging
EOSTokenID int64 // tokenizer, for diagnostic logging
ChatTemplate string // tokenizer.chat_template
HasChatTemplate bool
MTPLayers uint32 // <arch>.nextn_predict_layers, when an embedded MTP head exists
HasMTP bool
// TrainedContext is the estimator's default context size (0 when the
// estimator yields nothing usable).
TrainedContext int
// trainedPanic is the value the estimator panicked with, if it did. The
// defaults path has never recovered from that panic locally; it is replayed
// at the same point so the outcome for such a file does not change.
trainedPanic any
// footprints holds the per-device VRAM footprint at each context that the
// auto-context logic may ask about. It is filled only when TrainedContext
// is positive, the same condition under which that logic runs.
footprints map[int]uint64
// maxCtxFootprint is the VRAM estimate at MaxContextLength used by the
// context_size=-1 warning.
maxCtxFootprint uint64
}
// footprintAt returns the precomputed footprint at ctx. A context that was not
// precomputed reports 0, the same "cannot confirm" answer as an estimate gap.
func (h ggufHeader) footprintAt(ctx int) uint64 {
return h.footprints[ctx]
}
// readGGUFHeader converts a parsed file into a snapshot. It is the only place
// the parser output is consumed on the defaults path.
func readGGUFHeader(f *gguf.GGUFFile) ggufHeader {
var h ggufHeader
arch := f.Architecture()
h.Name = f.Metadata().Name
h.Architecture = arch.Architecture
h.MaxContextLength = int(arch.MaximumContextLength)
tok := f.Tokenizer()
h.BOSTokenID = tok.BOSTokenID
h.EOSTokenID = tok.EOSTokenID
if t, ok := f.Header.MetadataKV.Get("tokenizer.chat_template"); ok {
h.ChatTemplate = t.ValueString()
h.HasChatTemplate = true
}
h.MTPLayers, h.HasMTP = HasEmbeddedMTPHead(f)
h.TrainedContext, h.trainedPanic = safeTrainedContext(f)
if h.TrainedContext > 0 {
chosen := h.TrainedContext
if chosen > DefaultAutoContextSize {
chosen = DefaultAutoContextSize
}
h.footprints = map[int]uint64{chosen: estimateContextVRAM(f, chosen)}
for _, cand := range contextFitCandidates {
h.footprints[cand] = estimateContextVRAM(f, cand)
}
}
if h.MaxContextLength > 0 {
h.maxCtxFootprint = estimateNonUMAAt(f, h.MaxContextLength)
}
return h
}
// safeTrainedContext returns the estimator's default context size and, when the
// estimator panics, the panic value instead of letting it escape.
func safeTrainedContext(f *gguf.GGUFFile) (n int, panicked any) {
defer func() {
if r := recover(); r != nil {
n, panicked = 0, r
}
}()
return int(f.EstimateLLaMACppRun().ContextSize), nil
}
// estimateNonUMAAt returns the discrete-GPU footprint at ctx for the -1 warning.
// It returns 0 on any estimator failure, which suppresses the warning as before.
func estimateNonUMAAt(f *gguf.GGUFFile, ctx int) (used uint64) {
defer func() {
if r := recover(); r != nil {
used = 0
}
}()
sum := f.EstimateLLaMACppRun(gguf.WithLLaMACppContextSize(int32(ctx))).Summarize(true, 0, 0)
if len(sum.Items) == 0 {
return 0
}
for _, v := range sum.Items[0].VRAMs {
used += uint64(v.NonUMA)
}
return used
}
// ggufIdentity is what a cached header is validated against.
type ggufIdentity = headerIdentity
// ggufHeaderCache is the GGUF instance of the generic header cache.
type ggufHeaderCache = headerCache[ggufHeader]
// persistedGGUFCache is the GGUF cache file as read back from disk.
type persistedGGUFCache = headerFile
func newGGUFHeaderCache(max int) *ggufHeaderCache {
return newHeaderCache(ggufHeaderSpec, max)
}
// ggufHeaders is the process-wide header cache used by llamaCppDefaults.
var ggufHeaders = newGGUFHeaderCache(ggufHeaderCacheSize)
// parseGGUFHeader parses modelFile with parse and reduces the result to a
// snapshot. Only the scalar metadata and array lengths are read, see
// llamaCppDefaultsWithParser for why.
func parseGGUFHeader(modelFile string, parse ggufParser) (ggufHeader, error) {
f, err := parse(modelFile, gguf.UseMMap(), gguf.SkipLargeMetadata())
if err != nil {
return ggufHeader{}, err
}
return readGGUFHeader(f), nil
}
// loadGGUFHeader returns the header snapshot for modelFile, parsing it only when
// no cached snapshot matches the file's current identity. A file that cannot be
// stat'ed or parsed is never cached, so the caller sees the same error path as
// before the cache existed.
func loadGGUFHeader(modelFile string, parse ggufParser) (ggufHeader, error) {
return ggufHeaders.loadVia(modelFile, func(p string) (ggufHeader, error) {
return parseGGUFHeader(p, parse)
})
}