mirror of
https://github.com/mudler/LocalAI.git
synced 2026-06-19 14:19:16 -04:00
* feat(backend): add depth-anything (Depth Anything 3) C++/ggml backend + gallery Mirrors the locate-anything-cpp backend to register a new depth-anything backend that wraps the Depth Anything 3 ggml port (depth-anything.cpp) via purego (cgo-less, no Python at inference). - backend/go/depth-anything-cpp/: gRPC backend (Load + Predict + GenerateImage), purego binding to the da_capi_* C ABI, CMake/Makefile/run/package/test scripts building depth-anything.cpp's DA_SHARED static .so per CPU variant. - backend/index.yaml: depth-anything backend meta + all hardware-variant capability entries (cpu/cuda12/cuda13/intel-sycl-f32+f16/vulkan/nvidia-l4t). - gallery/index.yaml: 8 Depth Anything 3 GGUF models (base q4_k/q8_0/f16/f32, small, large, giant, mono-large). - .github/backend-matrix.yml: one build entry per hardware variant. Assisted-by: Claude:claude-opus-4-8 Signed-off-by: Ettore Di Giacinto <mudler@localai.io> * feat(depth): typed Depth RPC + REST endpoint exposing full DA3 data Assisted-by: Claude:claude-opus-4-8 Signed-off-by: Ettore Di Giacinto <mudler@localai.io> * fix(depth): pin depth-anything.cpp to e0b6814 (ABI 3 dense C-API) The Depth RPC handler calls da_capi_depth_dense / da_capi_points (C-API ABI 3); pin the native build to the commit that exports them. Assisted-by: Claude:claude-opus-4-8 Signed-off-by: Ettore Di Giacinto <mudler@localai.io> * fix(depth): pin depth-anything.cpp to v0.1.0 release (b515c31) Repoint the native version from the now-orphaned e0b6814 to the b515c31 release commit, kept alive by the upstream v0.1.0 tag. C-API is unchanged (da_capi_abi_version == 3). Assisted-by: Claude:claude-opus-4-8 Signed-off-by: Ettore Di Giacinto <mudler@localai.io> * fix(depth): wire depth-anything-cpp into build, CI bump, and importer The backend dir, gallery index, and CI build-matrix were present but the backend was never wired into the integration points that adding-backends.md requires: - root Makefile: add to .NOTPARALLEL, the test-extra chain, a BACKEND_* definition, the docker-build target eval, and docker-build-backends (mirrors parakeet-cpp; the backend's own Makefile already documented that its `test` target is driven by test-extra). - bump_deps.yaml: register the DEPTHANYTHING_VERSION pin so the daily auto-bump bot tracks mudler/depth-anything.cpp master (it cannot see an unregistered Makefile pin). - import form: add a preference-only KnownBackend entry so depth-anything is selectable at /import-model (mirrors sam3-cpp; no reliable GGUF auto-detect signal, so pref-only per the doc's default). changed-backends.js needs no entry: the generic golang suffix branch already resolves backend/go/depth-anything-cpp/. Assisted-by: Claude:claude-opus-4-8 Signed-off-by: Ettore Di Giacinto <mudler@localai.io> * feat(depth): auto-detect importer for depth-anything GGUFs Replace the preference-only entry with a real auto-detect importer (mirrors parakeet-cpp / locate-anything): - DepthAnythingImporter matches a .gguf whose name carries a depth-anything token (depth-anything-<size>-<quant>.gguf), so /import-model recognises mudler/depth-anything.cpp-gguf repos and direct GGUF URLs without an explicit backend preference. preferences.backend= "depth-anything" still forces it. - Registered before LlamaCPPImporter so its GGUF bundles aren't claimed by the generic .gguf importer; the narrow name match means it cannot claim arbitrary llama GGUFs or the upstream safetensors PyTorch repos. - Multi-quant repos pick the smallest quant by default (q4_k -> ... -> f32, depth stays >0.998 corr even at q4_k); quantizations preference overrides. - Drops the now-redundant knownPrefOnlyBackends entry (importer-backed backends are not listed there, matching parakeet-cpp). - Table-driven Ginkgo test covers detection, negative cases (llama GGUF, upstream safetensors), default/override/fallback quant pick, and direct URL import. 10/10 specs pass. Assisted-by: Claude:claude-opus-4-8 Signed-off-by: Ettore Di Giacinto <mudler@localai.io> * fix(depth): check conn.Close error in grpc Depth client (errcheck) The new Depth() client method used a bare `defer conn.Close()`. golangci-lint runs with new-from-merge-base, so although the 39 sibling methods use the same bare form (grandfathered), the newly added line trips errcheck. Drop the result explicitly to satisfy the linter. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 * fix(depth): bump depth-anything.cpp to v0.1.1 (embeddable CMake) v0.1.0 (b515c31) used ${CMAKE_SOURCE_DIR} for its include dirs, which points at the parent project when built via add_subdirectory() as this backend does, so the container build failed with missing stb_image.h / da_gguf_keys.h. v0.1.1 (2d42897) switches to project-relative paths. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 * fix(depth): resolve gosec findings in the backend wrapper The code-scanning gate flagged three new failure-level alerts in godepthanythingcpp.go (gosec runs with -no-fail; GitHub gates on new alerts): - G301: export dirs were created with 0o755. Tighten to 0o750 (no world access needed for backend-written export output). - G304: writeDepthPNG creates req.GetDst(). That path is chosen by the LocalAI core as the intended output destination (same pattern every image backend uses), not attacker input, so annotate with #nosec G304 and document why. The remaining G103 "audit unsafe" notes on the unsafe.Slice C-buffer copies are warning-level (the same purego interop whisper/parakeet use) and do not gate the check, per the supertonic exclusion precedent in secscan.yaml. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 * fix(depth): bump depth-anything.cpp to v0.1.2 (CUDA cross-build arch) v0.1.1 forced CMAKE_CUDA_ARCHITECTURES=native, which breaks the GPU-less l4t/cublas CI builds (nvcc "Unsupported gpu architecture 'compute_'" on CMake 3.22). v0.1.2 (442eea4) drops the override and lets ggml pick its default cross-build arch list. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 --------- Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Co-authored-by: Ettore Di Giacinto <mudler@localai.io>
229 lines
7.1 KiB
Go
229 lines
7.1 KiB
Go
package trace
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"slices"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/emirpasic/gods/v2/queues/circularbuffer"
|
|
"github.com/mudler/LocalAI/core/schema"
|
|
"github.com/mudler/xlog"
|
|
)
|
|
|
|
type BackendTraceType string
|
|
|
|
const (
|
|
BackendTraceLLM BackendTraceType = "llm"
|
|
BackendTraceEmbedding BackendTraceType = "embedding"
|
|
BackendTraceTranscription BackendTraceType = "transcription"
|
|
BackendTraceImageGeneration BackendTraceType = "image_generation"
|
|
BackendTraceVideoGeneration BackendTraceType = "video_generation"
|
|
BackendTraceTTS BackendTraceType = "tts"
|
|
BackendTraceSoundGeneration BackendTraceType = "sound_generation"
|
|
BackendTraceRerank BackendTraceType = "rerank"
|
|
BackendTraceTokenize BackendTraceType = "tokenize"
|
|
BackendTraceDetection BackendTraceType = "detection"
|
|
BackendTraceDepth BackendTraceType = "depth"
|
|
BackendTraceFaceVerify BackendTraceType = "face_verify"
|
|
BackendTraceFaceAnalyze BackendTraceType = "face_analyze"
|
|
BackendTraceVoiceVerify BackendTraceType = "voice_verify"
|
|
BackendTraceVoiceAnalyze BackendTraceType = "voice_analyze"
|
|
BackendTraceVoiceEmbed BackendTraceType = "voice_embed"
|
|
BackendTraceAudioTransform BackendTraceType = "audio_transform"
|
|
BackendTraceModelLoad BackendTraceType = "model_load"
|
|
BackendTraceScore BackendTraceType = "score"
|
|
BackendTraceVectorStore BackendTraceType = "vector_store"
|
|
)
|
|
|
|
type BackendTrace struct {
|
|
Timestamp time.Time `json:"timestamp"`
|
|
Duration time.Duration `json:"duration"`
|
|
Type BackendTraceType `json:"type"`
|
|
ModelName string `json:"model_name"`
|
|
Backend string `json:"backend"`
|
|
Summary string `json:"summary"`
|
|
// Body is the full request payload sent to the backend, when one
|
|
// applies (currently: cloud-proxy passthrough forwards). Summary
|
|
// is a short preview for the trace list; Body is the full
|
|
// payload shown when the row is expanded. Capped by the recorder
|
|
// to keep the in-memory ring buffer bounded.
|
|
Body string `json:"body,omitempty"`
|
|
Error string `json:"error,omitempty"`
|
|
Data map[string]any `json:"data"`
|
|
}
|
|
|
|
// MaxTraceBodyBytes caps the per-trace stored request body. Roomy
|
|
// enough to keep typical chat histories intact while preventing a
|
|
// runaway buffer when a caller streams MB-scale payloads.
|
|
const MaxTraceBodyBytes = 1 << 20
|
|
|
|
var backendTraceBuffer *circularbuffer.Queue[*BackendTrace]
|
|
var backendMu sync.Mutex
|
|
var backendLogChan = make(chan *BackendTrace, 100)
|
|
var backendInitOnce sync.Once
|
|
|
|
// backendMaxBodyBytes caps each captured string value in a BackendTrace.Data
|
|
// field to keep the /api/backend-traces JSON small enough for the admin UI to
|
|
// load on every 5s auto-refresh. Mirrors the API-trace body cap added in
|
|
// commit 61bf34ea: without it a chatty LLM workload (full message history per
|
|
// trace) or any TTS run (~1.3 MiB of audio_wav_base64 per trace) blows the
|
|
// payload past tens of MiB and locks the Traces page in a loading state.
|
|
//
|
|
// 0 disables the cap. Set on the first InitBackendTracingIfEnabled call only,
|
|
// matching the sync.Once-guarded maxItems semantics.
|
|
var backendMaxBodyBytes int
|
|
|
|
func InitBackendTracingIfEnabled(maxItems, maxBodyBytes int) {
|
|
backendInitOnce.Do(func() {
|
|
if maxItems <= 0 {
|
|
maxItems = 100
|
|
}
|
|
backendMu.Lock()
|
|
backendTraceBuffer = circularbuffer.New[*BackendTrace](maxItems)
|
|
backendMaxBodyBytes = maxBodyBytes
|
|
backendMu.Unlock()
|
|
|
|
go func() {
|
|
for t := range backendLogChan {
|
|
backendMu.Lock()
|
|
if backendTraceBuffer != nil {
|
|
backendTraceBuffer.Enqueue(t)
|
|
}
|
|
backendMu.Unlock()
|
|
}
|
|
}()
|
|
})
|
|
}
|
|
|
|
func RecordBackendTrace(t BackendTrace) {
|
|
if t.Data != nil && backendMaxBodyBytes > 0 {
|
|
t.Data = capDataStrings(t.Data, backendMaxBodyBytes)
|
|
}
|
|
select {
|
|
case backendLogChan <- &t:
|
|
default:
|
|
xlog.Warn("Backend trace channel full, dropping trace")
|
|
}
|
|
}
|
|
|
|
// capDataStrings walks a trace Data map and replaces any string value (at any
|
|
// depth) that exceeds maxBytes with a fixed-size marker that names the
|
|
// original byte count. The replacement is intentionally short and not valid
|
|
// base64/JSON: the goal is to flag "this was dropped" cheaply, not to keep a
|
|
// partial value that the UI might try to render. Non-string scalars and
|
|
// non-map containers pass through untouched so structural fields like
|
|
// total_deltas or audio_sample_rate remain useful.
|
|
func capDataStrings(data map[string]any, maxBytes int) map[string]any {
|
|
out := make(map[string]any, len(data))
|
|
for k, v := range data {
|
|
out[k] = capValue(v, maxBytes)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func capValue(v any, maxBytes int) any {
|
|
switch val := v.(type) {
|
|
case string:
|
|
if len(val) > maxBytes {
|
|
return fmt.Sprintf("<truncated: %d bytes>", len(val))
|
|
}
|
|
return val
|
|
case map[string]any:
|
|
return capDataStrings(val, maxBytes)
|
|
default:
|
|
return v
|
|
}
|
|
}
|
|
|
|
func GetBackendTraces() []BackendTrace {
|
|
backendMu.Lock()
|
|
if backendTraceBuffer == nil {
|
|
backendMu.Unlock()
|
|
return []BackendTrace{}
|
|
}
|
|
ptrs := backendTraceBuffer.Values()
|
|
backendMu.Unlock()
|
|
|
|
traces := make([]BackendTrace, len(ptrs))
|
|
for i, p := range ptrs {
|
|
traces[i] = *p
|
|
}
|
|
|
|
slices.SortFunc(traces, func(a, b BackendTrace) int {
|
|
return b.Timestamp.Compare(a.Timestamp)
|
|
})
|
|
|
|
return traces
|
|
}
|
|
|
|
func ClearBackendTraces() {
|
|
backendMu.Lock()
|
|
if backendTraceBuffer != nil {
|
|
backendTraceBuffer.Clear()
|
|
}
|
|
backendMu.Unlock()
|
|
}
|
|
|
|
func GenerateLLMSummary(messages schema.Messages, prompt string) string {
|
|
if len(messages) > 0 {
|
|
last := messages[len(messages)-1]
|
|
text := ""
|
|
switch content := last.Content.(type) {
|
|
case string:
|
|
text = content
|
|
default:
|
|
b, err := json.Marshal(content)
|
|
if err == nil {
|
|
text = string(b)
|
|
}
|
|
}
|
|
if text != "" {
|
|
return TruncateString(text, 200)
|
|
}
|
|
}
|
|
if prompt != "" {
|
|
return TruncateString(prompt, 200)
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func TruncateString(s string, maxLen int) string {
|
|
if len(s) <= maxLen {
|
|
return s
|
|
}
|
|
return s[:maxLen] + "..."
|
|
}
|
|
|
|
// TruncateToBytes caps a string at exactly maxBytes, preserving the leading
|
|
// content and appending a marker so the UI knows the value was clipped.
|
|
// Unlike TruncateString it guarantees output <= maxBytes, which matters for
|
|
// fields that feed back into the trace pipeline: capDataStrings in
|
|
// RecordBackendTrace re-checks size and would otherwise replace a producer's
|
|
// head-preserving truncation with the bare marker, losing the prefix.
|
|
//
|
|
// maxBytes <= 0 disables the cap, matching backendMaxBodyBytes semantics.
|
|
func TruncateToBytes(s string, maxBytes int) string {
|
|
if maxBytes <= 0 || len(s) <= maxBytes {
|
|
return s
|
|
}
|
|
suffix := fmt.Sprintf("...[truncated, %d bytes]", len(s))
|
|
if len(suffix) >= maxBytes {
|
|
// Pathologically small caps can't fit the marker; fall back to a
|
|
// hard cut so the contract (output <= maxBytes) still holds.
|
|
return s[:maxBytes]
|
|
}
|
|
return s[:maxBytes-len(suffix)] + suffix
|
|
}
|
|
|
|
// TruncateBytes is the []byte counterpart of TruncateString — it copies
|
|
// at most maxLen bytes, avoiding a full string([]byte) allocation when
|
|
// the input is a large request body.
|
|
func TruncateBytes(b []byte, maxLen int) string {
|
|
if len(b) <= maxLen {
|
|
return string(b)
|
|
}
|
|
return string(b[:maxLen]) + "..."
|
|
}
|