mirror of
https://github.com/mudler/LocalAI.git
synced 2026-10-28 17:18:49 -04:00
* feat(llama-cpp): add slot prompt-cache save and restore API Add POST /v1/slots/save and POST /v1/slots/restore. They write one llama.cpp slot's prompt cache (KV state) to a file and load it back, so a client can warm a long system prompt in a few hundred milliseconds instead of re-running prefill. Refs #12685. The new SlotCache gRPC call posts the same slot save and restore tasks the llama-server /slots endpoint uses. It is off unless the model sets the new slot_save_path option, so existing models are not affected. The /slots monitoring endpoint is not needed here: the backend has no HTTP server. The file name comes from the caller, so it is checked twice, in Go and again in the backend. It must be one path component: no empty name, "/", "\", "..", NUL, control characters or absolute path. The resolved path, with symbolic links followed, must be a direct child of slot_save_path. The routes are admin only because they write files on the backend host. Assisted-by: Claude:claude-sonnet-5-5 Signed-off-by: Ettore Di Giacinto <mudler@localai.io> * fix(llama-cpp): answer 501 when a backend lacks slot cache A backend that does not implement the SlotCache rpc returns gRPC UNIMPLEMENTED. The API passed that text through, so the client saw "unknown method SlotCache". Map the status to a typed error in core/backend and return 501 with a fixed message instead. Every other error path is unchanged. Make the SlotCache comments in backend.proto backend-neutral: slot is the backend's state slot, filename must stay inside the save directory, and an empty model_identity means the backend does not check it. Only comments change, no field or name. Add tests that the identity sent is the configured model, and for the error mapping. Assisted-by: Claude:claude-sonnet-5-5 Signed-off-by: Ettore Di Giacinto <mudler@localai.io> * fix(llama-cpp): issue slot cache IDs on the server The slot save and restore API let the client pick the file name. Restore could load any file in slot_save_path, and the symlink check ran before llama.cpp opened the file. The backend now issues the name. A save returns a random 128-bit ID (32 lowercase hex characters, read from /dev/urandom) and never overwrites an existing file. Files live in a 0700 directory per model, named from the SHA-256 of the model identity, with a manifest.json that records each save. The manifest is written atomically and a corrupt one stops both save and restore. A restore takes the ID, finds it in the manifest, refuses an entry of another model, builds the path from the entry and checks with lstat that it is a plain file of the recorded size. The directory mode is the main defence against another local user, since llama.cpp still opens the path itself. Each model keeps at most 32 saves and the oldest is deleted first. A file over 8 GiB is deleted after the save, because llama.cpp does not report the size before it writes. Responses carry no host path. The HTTP bodies change: save takes {model, slot}, restore takes {model, slot, id}, and an unknown ID returns 404. In the proto, SlotCacheRequest.filename and SlotCacheResponse.filename become id. SlotCache no longer calls checkModelIdentity, which reads a field this request does not have. Assisted-by: Claude:claude-sonnet-5-5 Signed-off-by: Ettore Di Giacinto <mudler@localai.io> * fix(llama-cpp): copy slot_cache files in prepare.sh grpc-server.cpp includes slot_cache.h, but prepare.sh copies the helper headers into llama.cpp/tools/grpc-server/ one by one and skipped it. The llama-cpp, turboquant and bonsai builds share this step, so they all failed with "slot_cache.h: No such file or directory". Copy slot_cache.h and slot_cache_test.cpp, which CMakeLists.txt builds when LLAMA_GRPC_BUILD_TESTS is on. Assisted-by: Claude:claude-sonnet-5-5 Signed-off-by: Ettore Di Giacinto <mudler@localai.io> * chore(deps): bump LocalAGI to pick up the scheduler start/stop fix LocalAGI's scheduler could hit a nil pointer in run when Start and Stop raced. That made the core/services/agentpool tests panic at random and turned tests-linux red. Move to mudler/LocalAGI@7aa0c8fea0, the merge of mudler/LocalAGI#519 ("make Start and Stop safe to call concurrently"). The new module version also adds a few indirect requirements to go.mod and go.sum. Assisted-by: Claude:claude-sonnet-5-5 Signed-off-by: Ettore Di Giacinto <mudler@localai.io> --------- Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Co-authored-by: Ettore Di Giacinto <mudler@localai.io> Co-authored-by: Ettore Di Giacinto <mudler@users.noreply.github.com>
120 lines
4.1 KiB
Go
120 lines
4.1 KiB
Go
package backend
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/mudler/LocalAI/core/config"
|
|
"github.com/mudler/LocalAI/core/schema"
|
|
"github.com/mudler/LocalAI/core/trace"
|
|
pb "github.com/mudler/LocalAI/pkg/grpc/proto"
|
|
"github.com/mudler/LocalAI/pkg/model"
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/status"
|
|
)
|
|
|
|
// ErrSlotCacheUnsupported is returned when the model's backend does not
|
|
// implement the SlotCache rpc (gRPC UNIMPLEMENTED).
|
|
var ErrSlotCacheUnsupported = errors.New("slot save and restore is not supported by this model's backend")
|
|
|
|
// slotCacheCaller is the part of a loaded backend that slot cache needs.
|
|
type slotCacheCaller interface {
|
|
SlotCache(ctx context.Context, in *pb.SlotCacheRequest, opts ...grpc.CallOption) (*pb.SlotCacheResponse, error)
|
|
}
|
|
|
|
// callSlotCache sends the request and maps an UNIMPLEMENTED status to
|
|
// ErrSlotCacheUnsupported. Every other error is returned unchanged.
|
|
func callSlotCache(ctx context.Context, c slotCacheCaller, req *pb.SlotCacheRequest) (*pb.SlotCacheResponse, error) {
|
|
resp, err := c.SlotCache(ctx, req)
|
|
if err != nil {
|
|
if st, ok := status.FromError(err); ok && st.Code() == codes.Unimplemented {
|
|
return nil, ErrSlotCacheUnsupported
|
|
}
|
|
return nil, err
|
|
}
|
|
return resp, nil
|
|
}
|
|
|
|
// newSlotCacheRequest always sends the configured model as ModelIdentity, so a
|
|
// backend that checks it can refuse a request meant for another model.
|
|
func newSlotCacheRequest(action pb.SlotCacheAction, slot int32, id string, modelConfig config.ModelConfig) *pb.SlotCacheRequest {
|
|
return &pb.SlotCacheRequest{
|
|
ModelIdentity: modelConfig.Model,
|
|
Action: action,
|
|
Slot: slot,
|
|
Id: id,
|
|
}
|
|
}
|
|
|
|
// ModelSlotCache saves or restores the prompt cache of one slot of a loaded
|
|
// model. On save id is empty and the backend issues one. On restore the caller
|
|
// must have validated id (see pkg/slotcache); the backend checks it again and
|
|
// accepts only an ID it issued for this model.
|
|
func ModelSlotCache(action pb.SlotCacheAction, slot int32, id string, loader *model.ModelLoader, modelConfig config.ModelConfig, appConfig *config.ApplicationConfig) (schema.SlotCacheResponse, error) {
|
|
name := "restore"
|
|
if action == pb.SlotCacheAction_SLOT_CACHE_ACTION_SAVE {
|
|
name = "save"
|
|
}
|
|
|
|
inferenceModel, err := loader.Load(ModelOptions(modelConfig, appConfig)...)
|
|
if err != nil {
|
|
recordModelLoadFailure(appConfig, modelConfig.Name, modelConfig.Backend, err, nil)
|
|
return schema.SlotCacheResponse{}, err
|
|
}
|
|
|
|
release, err := AcquireGlobalBackendSlot()
|
|
if err != nil {
|
|
return schema.SlotCacheResponse{}, err
|
|
}
|
|
defer release()
|
|
|
|
var startTime time.Time
|
|
var traceID string
|
|
if appConfig.EnableTracing {
|
|
trace.InitBackendTracingIfEnabled(appConfig.TracingMaxItems, appConfig.TracingMaxBodyBytes)
|
|
startTime = time.Now()
|
|
traceID = trace.BeginBackendTrace(trace.BackendTrace{Timestamp: startTime, Type: trace.BackendTraceTokenize, ModelName: modelConfig.Name, Backend: modelConfig.Backend, Summary: "slot cache " + name})
|
|
}
|
|
defer trace.CancelBackendTrace(traceID)
|
|
|
|
resp, err := callSlotCache(appConfig.Context, inferenceModel, newSlotCacheRequest(action, slot, id, modelConfig))
|
|
|
|
if appConfig.EnableTracing {
|
|
errStr := ""
|
|
if err != nil {
|
|
errStr = err.Error()
|
|
}
|
|
trace.RecordBackendTrace(trace.BackendTrace{
|
|
ID: traceID,
|
|
Timestamp: startTime,
|
|
Duration: time.Since(startTime),
|
|
Type: trace.BackendTraceTokenize,
|
|
ModelName: modelConfig.Name,
|
|
Backend: modelConfig.Backend,
|
|
Summary: fmt.Sprintf("slot cache %s", name),
|
|
Error: errStr,
|
|
Data: map[string]any{"action": name, "slot": slot, "id": id},
|
|
})
|
|
}
|
|
if err != nil {
|
|
return schema.SlotCacheResponse{}, err
|
|
}
|
|
if !resp.GetSuccess() {
|
|
return schema.SlotCacheResponse{}, fmt.Errorf("slot cache %s failed: %s", name, resp.GetMessage())
|
|
}
|
|
|
|
return schema.SlotCacheResponse{
|
|
Model: modelConfig.Name,
|
|
Action: name,
|
|
Slot: resp.GetSlot(),
|
|
ID: resp.GetId(),
|
|
Message: resp.GetMessage(),
|
|
NTokens: resp.GetNTokens(),
|
|
NBytes: resp.GetNBytes(),
|
|
DurationMS: resp.GetDurationMs(),
|
|
}, nil
|
|
}
|