mirror of
https://github.com/mudler/LocalAI.git
synced 2026-09-12 22:33:54 -04:00
* feat(router): make KNN a first-class classifier with a persisted, curated corpus
Add `classifier: knn` — similarity-weighted voting over labelled
example prompts. Unlike score/colbert it needs no classifier model:
label knowledge lives in a corpus seeded and curated through the
admin API, so routing decisions are deterministic, auditable, and
grounded in graded experience rather than a model's opinion.
Epistemic gate: corpus entries below knn.similarity_threshold cannot
vote; when none clears it the classifier activates no labels and the
router uses the fallback — a prompt unlike all labelled experience is
treated as undecidable, not guessed. Decisions record
nearest_similarity (also on fallback rows) so admins can see how far
the nearest labelled experience was; the Routing tab explains
out-of-corpus fallbacks and shows per-label corpus counts.
Persistence: one JSONL file per router under
<data path>/router-corpus (text, labels, vector, embedder
fingerprint). The file is the source of truth; the local-store index
is rebuilt from it at classifier build time and stays a pure
in-memory index. Entries recorded under a different embedding model
re-embed on load. Also corrects the docs' false claim that
local-store collections persist — the embedding cache never survived
restarts (and still doesn't); the corpus does.
Corpus input is API-only by design (entries may contain example user
content): POST /api/router/{name}/corpus seeds (labels validated
against declared policies, embedded server-side, indexed
immediately), GET .../corpus/stats inspects — label counts only,
entry texts are never returned by any surface — DELETE .../corpus
wipes. Admin-gated like the sibling router endpoints, and exposed as
MCP tools (seed_router_corpus / get_router_corpus_stats /
clear_router_corpus) in both the httpapi and inproc clients with
coverage-test route mappings.
Plumbing: VectorStore gains SearchK (top-K was hardcoded to 1);
local-store gets InsertBatch/Delete as optional fast paths;
RouterConfig gains a knn block (embedding_model, k,
similarity_threshold, vote_threshold, store_name) with meta-registry
fields; the classifier dropdown now offers knn and the
previously-missing colbert; embedding_cache is ignored (with a
warning) for knn — it IS an embedding-KNN lookup; the stale
/api/instructions intelligent-routing entry is rewritten (it
described a classifier that no longer exists); swagger regenerated.
Tests: KNN vote/gate specs with hand-computed vote shares, corpus
manager suite (restart reload without re-embedding, fingerprint
re-embed, dedupe, hostile store names), middleware specs (corpus
routing, gate fallback, config validation, cache-wrap refusal),
corpus endpoint specs pinning the texts-never-returned contract, MCP
catalog + route-mapping gates, and a Playwright spec for corpus
stats and the out-of-corpus decision detail.
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* feat(router): name consulted corpus neighbours in knn decisions
Every knn decision (decision log rows and the /api/router/decide
response) now carries neighbors: the K retrieved corpus entries by
descending similarity - including ones below the epistemic gate, which
is what makes fallback decisions diagnosable - each as {id, similarity,
labels}. The id is the entry's content hash (first 8 bytes of the
SHA-256 of its text, hex): stable across reseeds and re-embeds, and
text-free, so an external platform that seeded the corpus can recompute
text->id on its own copy and bucket decisions by corpus region (per-
region reliability accounting) without corpus text ever leaving the
server. A corrupt index payload surfaces as an id-less neighbour at a
real similarity instead of disappearing.
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* refactor(router): deduplicate knn plumbing and cut corpus hot-path waste
Post-review cleanup of the knn-first-class-router branch; no behaviour
changes on the API surface.
Reuse/altitude:
- RouterKNNConfig.ResolvedStoreName is now the single source of the
router-corpus-<name> default (was hand-derived in four files).
- corpus.ResolveKNNRouter + corpus.Seed carry the shared model
resolution and seed validation; the REST endpoints and the assistant
MCP client are thin transport adapters over them, with sentinel
errors mapped to HTTP statuses at the echo boundary.
- middleware.NewClassifierDeps assembles the classifier dependency set
once for all five entry points (OpenAI, Anthropic, realtime, decide,
corpus) instead of five hand-copied literals.
- router.AllClassifiers feeds both the status endpoint and the
unknown-classifier error, ending the classifier-list drift.
- Per-classifier requirements moved out of validateRouterPolicies into
their buildClassifier arms; the knn arm owns its embedding_cache
opt-out instead of a name-check in the shared wrap tail.
- adminOnly replaces four inline copies of the admin gate in the
middleware routes.
- localVectorStore.Search delegates to SearchK (identical traces).
Efficiency:
- Manager.Add embeds outside the manager mutex and appends to the
JSONL file (O(new) instead of O(corpus) rewrite); a torn tail from a
crash mid-append is tolerated on read and repaired on next write.
- Stats memoises per store keyed on the file's stat fingerprint and no
longer takes the manager mutex, so the 5s status poll stops parsing
vector-laden JSONL and stops blocking behind seeds.
- KNN Classify decodes each neighbour payload once (was twice) and
builds refs and votes in a single pass with one fallback return.
- Corpus file writes fsync before rename/close.
- The corpus manager is built eagerly in newApplication (sync.Once
dropped); test helper dead branch removed.
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* feat(router): bind knn corpus vectors to an embedder fingerprint and fail closed on mismatch
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* chore(mcp): align corpus tool prompts and the mutating-tool safety list
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* feat(proto,backend): report embedding shape from the llama-cpp backend
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* feat(embeddings): Go-side pooling — mean/last/decayed_mean with half-life
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* feat(embeddings): accept chat messages[] and per-request pooling on /v1/embeddings
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* chore(middleware): name the failing fields when post-merge validation 400s
An intermittent post-merge validation failure surfaced as an opaque 400
during integration (pooling scheme mismatch that no client had sent).
Log the model, the request's pooling override, and the merged config's
pooling fields at the failure point so the next occurrence identifies
whether the request or the stored config carried the bad value.
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* fix(embeddings): scheme override must not inherit the config's half-life
A model config defaulting to decayed_mean pooling carries
pooling_half_life_tokens; a request overriding the scheme to mean/last
without its own half-life inherited that value, and post-merge
validation rejected the pair the server itself had assembled. Zero the
inherited half-life when the overridden scheme is not decayed_mean; a
request that explicitly pairs a half-life with a non-decayed scheme
still 400s.
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* fix embedding pooling validation and router bounds
Declare backend embedding layouts and reject incompatible pooling modes. Reset local-store dimensions after a full clear, validate KNN thresholds, and add real backend and store integration coverage.
Assisted-by: Codex:gpt-5
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* ci: run local-store integration tests
Build and install the local-store backend in the Linux test job, then run the existing store integration suite so new specs are discovered automatically.
Assisted-by: Codex:gpt-5
Signed-off-by: Richard Palethorpe <io@richiejp.com>
---------
Signed-off-by: Richard Palethorpe <io@richiejp.com>
188 lines
6.1 KiB
Go
188 lines
6.1 KiB
Go
package backend
|
|
|
|
import (
|
|
"fmt"
|
|
"math"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/mudler/LocalAI/core/config"
|
|
"github.com/mudler/LocalAI/pkg/grpc/proto"
|
|
)
|
|
|
|
// Go-side embedding pooling schemes. The canonical strings live on the
|
|
// config package (config.Pooling* — mirroring the ScoreNormalization*
|
|
// pattern) so ModelConfig.Validate can reject unknown values without
|
|
// importing this package; these aliases are the API the backend layer
|
|
// (and the HTTP endpoints) program against.
|
|
const (
|
|
// PoolingBackend leaves pooling to the inference backend — the exact
|
|
// pre-existing behavior of the embeddings path (also selected by "").
|
|
PoolingBackend = config.PoolingBackend
|
|
// PoolingMean averages the per-token vectors.
|
|
PoolingMean = config.PoolingMean
|
|
// PoolingLast selects the last token's vector.
|
|
PoolingLast = config.PoolingLast
|
|
// PoolingDecayedMean is a mean weighted toward the most recent tokens:
|
|
// w_i = 2^(-(T-1-i)/H) for token i of T, with half-life H tokens.
|
|
PoolingDecayedMean = config.PoolingDecayedMean
|
|
|
|
// DefaultPoolingHalfLifeTokens is the half-life used by
|
|
// PoolingDecayedMean when the model config / request doesn't set one.
|
|
DefaultPoolingHalfLifeTokens = 256
|
|
)
|
|
|
|
// reshapeEmbeddings views the flat float payload of an EmbeddingResult as
|
|
// tokens rows of dim columns. The gRPC contract packs vectors row-major
|
|
// (vector 0 first), so row i aliases flat[i*dim : (i+1)*dim].
|
|
func reshapeEmbeddings(flat []float32, tokens, dim int) ([][]float32, error) {
|
|
if tokens <= 0 || dim <= 0 {
|
|
return nil, fmt.Errorf("invalid embedding shape: %d vectors x %d dims", tokens, dim)
|
|
}
|
|
if len(flat) != tokens*dim {
|
|
return nil, fmt.Errorf("embedding payload of %d floats does not match reported shape %d vectors x %d dims", len(flat), tokens, dim)
|
|
}
|
|
vecs := make([][]float32, tokens)
|
|
for i := range vecs {
|
|
vecs[i] = flat[i*dim : (i+1)*dim]
|
|
}
|
|
return vecs, nil
|
|
}
|
|
|
|
// poolMean averages the per-token vectors with float64 accumulators.
|
|
func poolMean(vecs [][]float32) []float32 {
|
|
dim := len(vecs[0])
|
|
acc := make([]float64, dim)
|
|
for _, v := range vecs {
|
|
for j, x := range v {
|
|
acc[j] += float64(x)
|
|
}
|
|
}
|
|
out := make([]float32, dim)
|
|
for j := range out {
|
|
out[j] = float32(acc[j] / float64(len(vecs)))
|
|
}
|
|
return out
|
|
}
|
|
|
|
// poolLast returns (a copy of) the last token's vector.
|
|
func poolLast(vecs [][]float32) []float32 {
|
|
last := vecs[len(vecs)-1]
|
|
out := make([]float32, len(last))
|
|
copy(out, last)
|
|
return out
|
|
}
|
|
|
|
// poolDecayedMean computes a weighted mean over the per-token vectors with
|
|
// exponentially decaying weights anchored at the last token: token i of T
|
|
// gets w_i = 2^(-(T-1-i)/halfLife), so the last token always weighs 1 and a
|
|
// token halfLife positions earlier weighs 0.5. Accumulation is in float64.
|
|
func poolDecayedMean(vecs [][]float32, halfLife float64) []float32 {
|
|
dim := len(vecs[0])
|
|
T := len(vecs)
|
|
acc := make([]float64, dim)
|
|
wsum := 0.0
|
|
for i, v := range vecs {
|
|
w := math.Exp2(-float64(T-1-i) / halfLife)
|
|
wsum += w
|
|
for j, x := range v {
|
|
acc[j] += w * float64(x)
|
|
}
|
|
}
|
|
out := make([]float32, dim)
|
|
for j := range out {
|
|
out[j] = float32(acc[j] / wsum)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// normalizeEmbedding is an exact port of llama.cpp's common_embd_normalize
|
|
// (backend/cpp/llama-cpp/llama.cpp/common/common.cpp), applied after Go-side
|
|
// pooling because per-token vectors arrive RAW from llama.cpp with
|
|
// pooling:none (the server only normalizes vectors it pooled itself).
|
|
// embdNorm: <0 none, 0 max-abs scaled to int16 range (/32760.0), 2 L2
|
|
// (llama.cpp default), anything else p-norm with p=embdNorm (1 = taxicab).
|
|
func normalizeEmbedding(v []float32, embdNorm int) []float32 {
|
|
sum := 0.0
|
|
switch {
|
|
case embdNorm < 0: // no normalisation
|
|
sum = 1.0
|
|
case embdNorm == 0: // max absolute
|
|
for _, x := range v {
|
|
if a := math.Abs(float64(x)); sum < a {
|
|
sum = a
|
|
}
|
|
}
|
|
sum /= 32760.0 // make an int16 range
|
|
case embdNorm == 2: // euclidean
|
|
for _, x := range v {
|
|
sum += float64(x) * float64(x)
|
|
}
|
|
sum = math.Sqrt(sum)
|
|
default: // p-norm (euclidean is p-norm p=2)
|
|
for _, x := range v {
|
|
sum += math.Pow(math.Abs(float64(x)), float64(embdNorm))
|
|
}
|
|
sum = math.Pow(sum, 1.0/float64(embdNorm))
|
|
}
|
|
|
|
// llama.cpp computes the reciprocal as a float32 and multiplies in
|
|
// float32; mirror that so both paths yield bit-identical vectors.
|
|
var norm float32
|
|
if sum > 0.0 {
|
|
norm = float32(1.0 / sum)
|
|
}
|
|
out := make([]float32, len(v))
|
|
for i, x := range v {
|
|
out[i] = x * norm
|
|
}
|
|
return out
|
|
}
|
|
|
|
// embdNormalizeFromOptions extracts the load-time embd_normalize backend
|
|
// option ("embd_normalize:<n>", alias "embedding_normalize:<n>") the same
|
|
// way the llama-cpp gRPC server parses it, so Go-side pooling normalizes
|
|
// with the exact norm the backend would have applied had it pooled
|
|
// server-side. Defaults to 2 (L2) like llama.cpp; unparsable values are
|
|
// ignored (llama.cpp swallows std::stoi failures).
|
|
func embdNormalizeFromOptions(options []string) int {
|
|
embdNorm := 2
|
|
for _, opt := range options {
|
|
name, val, found := strings.Cut(opt, ":")
|
|
if !found || (name != "embd_normalize" && name != "embedding_normalize") {
|
|
continue
|
|
}
|
|
if n, err := strconv.Atoi(strings.TrimSpace(val)); err == nil {
|
|
embdNorm = n
|
|
}
|
|
}
|
|
return embdNorm
|
|
}
|
|
|
|
// PoolEmbeddingResult reduces a per-token EmbeddingResult (the backend ran
|
|
// with pooling:none) to a single vector using scheme, then normalizes it
|
|
// with llama.cpp's common_embd_normalize semantics. halfLife only applies
|
|
// to PoolingDecayedMean; non-positive values fall back to
|
|
// DefaultPoolingHalfLifeTokens.
|
|
func PoolEmbeddingResult(res *proto.EmbeddingResult, scheme string, halfLife float64, embdNorm int) ([]float32, error) {
|
|
vecs, err := reshapeEmbeddings(res.GetEmbeddings(), int(res.GetTokens()), int(res.GetDim()))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var pooled []float32
|
|
switch scheme {
|
|
case PoolingMean:
|
|
pooled = poolMean(vecs)
|
|
case PoolingLast:
|
|
pooled = poolLast(vecs)
|
|
case PoolingDecayedMean:
|
|
if halfLife <= 0 {
|
|
halfLife = DefaultPoolingHalfLifeTokens
|
|
}
|
|
pooled = poolDecayedMean(vecs, halfLife)
|
|
default:
|
|
return nil, fmt.Errorf("unknown Go-side pooling scheme %q (expected %q, %q or %q)", scheme, PoolingMean, PoolingLast, PoolingDecayedMean)
|
|
}
|
|
return normalizeEmbedding(pooled, embdNorm), nil
|
|
}
|