server.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  1. package llm
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "log"
  11. "log/slog"
  12. "math/rand"
  13. "net"
  14. "net/http"
  15. "os"
  16. "os/exec"
  17. "path/filepath"
  18. "runtime"
  19. "strconv"
  20. "strings"
  21. "sync"
  22. "time"
  23. "golang.org/x/sync/semaphore"
  24. "github.com/ollama/ollama/api"
  25. "github.com/ollama/ollama/build"
  26. "github.com/ollama/ollama/discover"
  27. "github.com/ollama/ollama/envconfig"
  28. "github.com/ollama/ollama/format"
  29. "github.com/ollama/ollama/llama"
  30. "github.com/ollama/ollama/runners"
  31. )
  32. type LlamaServer interface {
  33. Ping(ctx context.Context) error
  34. WaitUntilRunning(ctx context.Context) error
  35. Completion(ctx context.Context, req CompletionRequest, fn func(CompletionResponse)) error
  36. Embedding(ctx context.Context, input string) ([]float32, error)
  37. Tokenize(ctx context.Context, content string) ([]int, error)
  38. Detokenize(ctx context.Context, tokens []int) (string, error)
  39. Close() error
  40. EstimatedVRAM() uint64 // Total VRAM across all GPUs
  41. EstimatedTotal() uint64
  42. EstimatedVRAMByGPU(gpuID string) uint64
  43. }
  44. // llmServer is an instance of the llama.cpp server
  45. type llmServer struct {
  46. port int
  47. cmd *exec.Cmd
  48. done chan error // Channel to signal when the process exits
  49. status *StatusWriter
  50. options api.Options
  51. numParallel int
  52. modelPath string
  53. modelLock sync.Mutex // Temporary until we switch fully to Go server
  54. model *llama.Model // If non-nil, the runner is a new Go server
  55. estimate MemoryEstimate
  56. totalLayers uint64
  57. // gpuCount int
  58. gpus discover.GpuInfoList // Recorded just before the model loaded, free space will be incorrect
  59. loadDuration time.Duration // Record how long it took the model to load
  60. loadProgress float32
  61. sem *semaphore.Weighted
  62. }
  63. // LoadModel will load a model from disk. The model must be in the GGML format.
  64. //
  65. // It collects array values for arrays with a size less than or equal to
  66. // maxArraySize. If maxArraySize is 0, the default value of 1024 is used. If
  67. // the maxArraySize is negative, all arrays are collected.
  68. func LoadModel(model string, maxArraySize int) (*GGML, error) {
  69. if _, err := os.Stat(model); err != nil {
  70. return nil, err
  71. }
  72. f, err := os.Open(model)
  73. if err != nil {
  74. return nil, err
  75. }
  76. defer f.Close()
  77. ggml, _, err := DecodeGGML(f, maxArraySize)
  78. return ggml, err
  79. }
  80. // NewLlamaServer will run a server for the given GPUs
  81. // The gpu list must be a single family.
  82. func NewLlamaServer(gpus discover.GpuInfoList, model string, ggml *GGML, adapters, projectors []string, opts api.Options, numParallel int) (LlamaServer, error) {
  83. var err error
  84. var cpuRunner string
  85. var estimate MemoryEstimate
  86. var systemTotalMemory uint64
  87. var systemFreeMemory uint64
  88. var systemSwapFreeMemory uint64
  89. systemInfo := discover.GetSystemInfo()
  90. systemTotalMemory = systemInfo.System.TotalMemory
  91. systemFreeMemory = systemInfo.System.FreeMemory
  92. systemSwapFreeMemory = systemInfo.System.FreeSwap
  93. slog.Info("system memory", "total", format.HumanBytes2(systemTotalMemory), "free", format.HumanBytes2(systemFreeMemory), "free_swap", format.HumanBytes2(systemSwapFreeMemory))
  94. // If the user wants zero GPU layers, reset the gpu list to be CPU/system ram info
  95. if opts.NumGPU == 0 {
  96. gpus = discover.GetCPUInfo()
  97. }
  98. if len(gpus) == 1 && gpus[0].Library == "cpu" {
  99. cpuRunner = runners.ServerForCpu()
  100. estimate = EstimateGPULayers(gpus, ggml, projectors, opts)
  101. } else {
  102. estimate = EstimateGPULayers(gpus, ggml, projectors, opts)
  103. switch {
  104. case gpus[0].Library == "metal" && estimate.VRAMSize > systemTotalMemory:
  105. // disable partial offloading when model is greater than total system memory as this
  106. // can lead to locking up the system
  107. opts.NumGPU = 0
  108. case gpus[0].Library != "metal" && estimate.Layers == 0:
  109. // Don't bother loading into the GPU if no layers can fit
  110. cpuRunner = runners.ServerForCpu()
  111. gpus = discover.GetCPUInfo()
  112. case opts.NumGPU < 0 && estimate.Layers > 0 && gpus[0].Library != "cpu":
  113. opts.NumGPU = estimate.Layers
  114. }
  115. }
  116. // On linux and windows, over-allocating CPU memory will almost always result in an error
  117. // Darwin has fully dynamic swap so has no direct concept of free swap space
  118. if runtime.GOOS != "darwin" {
  119. systemMemoryRequired := estimate.TotalSize - estimate.VRAMSize
  120. available := systemFreeMemory + systemSwapFreeMemory
  121. if systemMemoryRequired > available {
  122. slog.Warn("model request too large for system", "requested", format.HumanBytes2(systemMemoryRequired), "available", available, "total", format.HumanBytes2(systemTotalMemory), "free", format.HumanBytes2(systemFreeMemory), "swap", format.HumanBytes2(systemSwapFreeMemory))
  123. return nil, fmt.Errorf("model requires more system memory (%s) than is available (%s)", format.HumanBytes2(systemMemoryRequired), format.HumanBytes2(available))
  124. }
  125. }
  126. estimate.log()
  127. // Loop through potential servers
  128. finalErr := errors.New("no suitable llama servers found")
  129. rDir, err := runners.Refresh(build.EmbedFS)
  130. if err != nil {
  131. return nil, err
  132. }
  133. availableServers := runners.GetAvailableServers(rDir)
  134. if len(availableServers) == 0 {
  135. return nil, finalErr
  136. }
  137. var servers []string
  138. if cpuRunner != "" {
  139. servers = []string{cpuRunner}
  140. } else {
  141. servers = runners.ServersForGpu(gpus[0]) // All GPUs in the list are matching Library and Variant
  142. }
  143. demandLib := envconfig.LLMLibrary()
  144. if demandLib != "" {
  145. serverPath := availableServers[demandLib]
  146. if serverPath == "" {
  147. slog.Info(fmt.Sprintf("Invalid OLLAMA_LLM_LIBRARY %s - not found", demandLib))
  148. } else {
  149. slog.Info("user override", "OLLAMA_LLM_LIBRARY", demandLib, "path", serverPath)
  150. servers = []string{demandLib}
  151. if strings.HasPrefix(demandLib, "cpu") {
  152. // Omit the GPU flag to silence the warning
  153. opts.NumGPU = -1
  154. }
  155. }
  156. }
  157. if len(servers) == 0 {
  158. return nil, fmt.Errorf("no servers found for %v", gpus)
  159. }
  160. params := []string{
  161. "--model", model,
  162. "--ctx-size", strconv.Itoa(opts.NumCtx),
  163. "--batch-size", strconv.Itoa(opts.NumBatch),
  164. }
  165. if opts.NumGPU >= 0 {
  166. params = append(params, "--n-gpu-layers", strconv.Itoa(opts.NumGPU))
  167. }
  168. if envconfig.Debug() {
  169. params = append(params, "--verbose")
  170. }
  171. if opts.MainGPU > 0 {
  172. params = append(params, "--main-gpu", strconv.Itoa(opts.MainGPU))
  173. }
  174. if len(adapters) > 0 {
  175. for _, adapter := range adapters {
  176. params = append(params, "--lora", adapter)
  177. }
  178. }
  179. if len(projectors) > 0 {
  180. // TODO: applying multiple projectors is not supported by the llama.cpp server yet
  181. params = append(params, "--mmproj", projectors[0])
  182. }
  183. defaultThreads := systemInfo.GetOptimalThreadCount()
  184. if opts.NumThread > 0 {
  185. params = append(params, "--threads", strconv.Itoa(opts.NumThread))
  186. } else if defaultThreads > 0 {
  187. params = append(params, "--threads", strconv.Itoa(defaultThreads))
  188. }
  189. fa := envconfig.FlashAttention()
  190. if fa && !gpus.FlashAttentionSupported() {
  191. slog.Warn("flash attention enabled but not supported by gpu")
  192. fa = false
  193. }
  194. if fa && !ggml.SupportsFlashAttention() {
  195. slog.Warn("flash attention enabled but not supported by model")
  196. fa = false
  197. }
  198. kvct := envconfig.KvCacheType()
  199. if fa {
  200. slog.Info("enabling flash attention")
  201. params = append(params, "--flash-attn")
  202. // Flash Attention also supports kv cache quantization
  203. // Enable if the requested and kv cache type is supported by the model
  204. if kvct != "" && ggml.SupportsKVCacheType(kvct) {
  205. params = append(params, "--kv-cache-type", kvct)
  206. } else {
  207. slog.Warn("kv cache type not supported by model", "type", kvct)
  208. }
  209. } else if kvct != "" && kvct != "f16" {
  210. slog.Warn("quantized kv cache requested but flash attention disabled", "type", kvct)
  211. }
  212. // mmap has issues with partial offloading on metal
  213. for _, g := range gpus {
  214. if g.Library == "metal" &&
  215. uint64(opts.NumGPU) > 0 &&
  216. uint64(opts.NumGPU) < ggml.KV().BlockCount()+1 {
  217. opts.UseMMap = new(bool)
  218. *opts.UseMMap = false
  219. }
  220. }
  221. // Windows CUDA should not use mmap for best performance
  222. // Linux with a model larger than free space, mmap leads to thrashing
  223. // For CPU loads we want the memory to be allocated, not FS cache
  224. if (runtime.GOOS == "windows" && gpus[0].Library == "cuda" && opts.UseMMap == nil) ||
  225. (runtime.GOOS == "linux" && systemFreeMemory < estimate.TotalSize && opts.UseMMap == nil) ||
  226. (gpus[0].Library == "cpu" && opts.UseMMap == nil) ||
  227. (opts.UseMMap != nil && !*opts.UseMMap) {
  228. params = append(params, "--no-mmap")
  229. }
  230. if opts.UseMLock {
  231. params = append(params, "--mlock")
  232. }
  233. // TODO - NUMA support currently doesn't work properly
  234. params = append(params, "--parallel", strconv.Itoa(numParallel))
  235. if estimate.TensorSplit != "" {
  236. params = append(params, "--tensor-split", estimate.TensorSplit)
  237. }
  238. if envconfig.MultiUserCache() {
  239. params = append(params, "--multiuser-cache")
  240. }
  241. for i := range servers {
  242. dir := availableServers[servers[i]]
  243. if dir == "" {
  244. // Shouldn't happen
  245. finalErr = fmt.Errorf("[%d] server %s not listed in available servers %v", i, servers[i], availableServers)
  246. slog.Error("server list inconsistent", "error", finalErr)
  247. continue
  248. }
  249. if strings.HasPrefix(servers[i], "cpu") {
  250. gpus = discover.GetCPUInfo()
  251. }
  252. // Find an availableServers port, retry on each iteration in case the failure was a port conflict race
  253. port := 0
  254. if a, err := net.ResolveTCPAddr("tcp", "localhost:0"); err == nil {
  255. var l *net.TCPListener
  256. if l, err = net.ListenTCP("tcp", a); err == nil {
  257. port = l.Addr().(*net.TCPAddr).Port
  258. l.Close()
  259. }
  260. }
  261. if port == 0 {
  262. slog.Debug("ResolveTCPAddr failed ", "error", err)
  263. port = rand.Intn(65535-49152) + 49152 // get a random port in the ephemeral range
  264. }
  265. finalParams := append(params, "--port", strconv.Itoa(port))
  266. pathEnv := "LD_LIBRARY_PATH"
  267. if runtime.GOOS == "windows" {
  268. pathEnv = "PATH"
  269. }
  270. // Start with the server directory for the LD_LIBRARY_PATH/PATH
  271. libraryPaths := []string{dir}
  272. if libraryPath, ok := os.LookupEnv(pathEnv); ok {
  273. // favor our bundled library dependencies over system libraries
  274. libraryPaths = append(libraryPaths, filepath.SplitList(libraryPath)...)
  275. }
  276. // Note: we always put the dependency path first
  277. // since this was the exact version we compiled/linked against
  278. if gpus[0].DependencyPath != nil {
  279. // assume gpus from the same library have the same dependency path
  280. libraryPaths = append(gpus[0].DependencyPath, libraryPaths...)
  281. }
  282. server := filepath.Join(dir, "ollama_llama_server")
  283. if runtime.GOOS == "windows" {
  284. server += ".exe"
  285. }
  286. // Detect tmp cleaners wiping out the file
  287. _, err := os.Stat(server)
  288. if errors.Is(err, os.ErrNotExist) {
  289. slog.Warn("llama server disappeared, reinitializing payloads", "path", server, "error", err)
  290. _, err = runners.Refresh(build.EmbedFS)
  291. if err != nil {
  292. slog.Warn("failed to reinitialize payloads", "error", err)
  293. return nil, err
  294. }
  295. }
  296. // TODO - once fully switched to the Go runner, load the model here for tokenize/detokenize cgo access
  297. s := &llmServer{
  298. port: port,
  299. cmd: exec.Command(server, finalParams...),
  300. status: NewStatusWriter(os.Stderr),
  301. options: opts,
  302. modelPath: model,
  303. estimate: estimate,
  304. numParallel: numParallel,
  305. sem: semaphore.NewWeighted(int64(numParallel)),
  306. totalLayers: ggml.KV().BlockCount() + 1,
  307. gpus: gpus,
  308. done: make(chan error, 1),
  309. }
  310. s.cmd.Env = os.Environ()
  311. s.cmd.Stdout = os.Stdout
  312. s.cmd.Stderr = s.status
  313. s.cmd.SysProcAttr = LlamaServerSysProcAttr
  314. envWorkarounds := [][2]string{}
  315. for _, gpu := range gpus {
  316. envWorkarounds = append(envWorkarounds, gpu.EnvWorkarounds...)
  317. }
  318. visibleDevicesEnv, visibleDevicesEnvVal := gpus.GetVisibleDevicesEnv()
  319. pathEnvVal := strings.Join(libraryPaths, string(filepath.ListSeparator))
  320. // Update or add the path and visible devices variable with our adjusted version
  321. pathNeeded := true
  322. devicesNeeded := visibleDevicesEnv != ""
  323. for i := range s.cmd.Env {
  324. cmp := strings.SplitN(s.cmd.Env[i], "=", 2)
  325. if strings.EqualFold(cmp[0], pathEnv) {
  326. s.cmd.Env[i] = pathEnv + "=" + pathEnvVal
  327. pathNeeded = false
  328. } else if devicesNeeded && strings.EqualFold(cmp[0], visibleDevicesEnv) {
  329. s.cmd.Env[i] = visibleDevicesEnv + "=" + visibleDevicesEnvVal
  330. devicesNeeded = false
  331. } else if len(envWorkarounds) != 0 {
  332. for _, kv := range envWorkarounds {
  333. if strings.EqualFold(cmp[0], kv[0]) {
  334. s.cmd.Env[i] = kv[0] + "=" + kv[1]
  335. }
  336. }
  337. }
  338. }
  339. if pathNeeded {
  340. s.cmd.Env = append(s.cmd.Env, pathEnv+"="+pathEnvVal)
  341. }
  342. if devicesNeeded {
  343. s.cmd.Env = append(s.cmd.Env, visibleDevicesEnv+"="+visibleDevicesEnvVal)
  344. }
  345. slog.Info("starting llama server", "cmd", s.cmd.String())
  346. if envconfig.Debug() {
  347. filteredEnv := []string{}
  348. for _, ev := range s.cmd.Env {
  349. if strings.HasPrefix(ev, "CUDA_") ||
  350. strings.HasPrefix(ev, "ROCR_") ||
  351. strings.HasPrefix(ev, "ROCM_") ||
  352. strings.HasPrefix(ev, "HIP_") ||
  353. strings.HasPrefix(ev, "GPU_") ||
  354. strings.HasPrefix(ev, "HSA_") ||
  355. strings.HasPrefix(ev, "GGML_") ||
  356. strings.HasPrefix(ev, "PATH=") ||
  357. strings.HasPrefix(ev, "LD_LIBRARY_PATH=") {
  358. filteredEnv = append(filteredEnv, ev)
  359. }
  360. }
  361. // Log at debug as the environment is inherited and might contain sensitive information
  362. slog.Debug("subprocess", "environment", filteredEnv)
  363. }
  364. if err = s.cmd.Start(); err != nil {
  365. // Detect permission denied and augment the message about noexec
  366. if errors.Is(err, os.ErrPermission) {
  367. finalErr = fmt.Errorf("unable to start server %w. %s may have noexec set. Set OLLAMA_TMPDIR for server to a writable executable directory", err, dir)
  368. continue
  369. }
  370. msg := ""
  371. if s.status != nil && s.status.LastErrMsg != "" {
  372. msg = s.status.LastErrMsg
  373. }
  374. err = fmt.Errorf("error starting the external llama server: %v %s", err, msg)
  375. finalErr = err
  376. continue
  377. }
  378. // reap subprocess when it exits
  379. go func() {
  380. err := s.cmd.Wait()
  381. // Favor a more detailed message over the process exit status
  382. if err != nil && s.status != nil && s.status.LastErrMsg != "" {
  383. slog.Debug("llama runner terminated", "error", err)
  384. if strings.Contains(s.status.LastErrMsg, "unknown model") {
  385. s.status.LastErrMsg = "this model is not supported by your version of Ollama. You may need to upgrade"
  386. }
  387. s.done <- errors.New(s.status.LastErrMsg)
  388. } else {
  389. s.done <- err
  390. }
  391. }()
  392. return s, nil
  393. }
  394. slog.Error("unable to load any llama server", "error", finalErr)
  395. return nil, finalErr
  396. }
  397. type ServerStatus int
  398. const ( // iota is reset to 0
  399. ServerStatusReady ServerStatus = iota
  400. ServerStatusNoSlotsAvailable
  401. ServerStatusLoadingModel
  402. ServerStatusNotResponding
  403. ServerStatusError
  404. )
  405. func (s ServerStatus) ToString() string {
  406. switch s {
  407. case ServerStatusReady:
  408. return "llm server ready"
  409. case ServerStatusNoSlotsAvailable:
  410. return "llm busy - no slots available"
  411. case ServerStatusLoadingModel:
  412. return "llm server loading model"
  413. case ServerStatusNotResponding:
  414. return "llm server not responding"
  415. default:
  416. return "llm server error"
  417. }
  418. }
  419. type ServerStatusResp struct {
  420. Status string `json:"status"`
  421. SlotsIdle int `json:"slots_idle"`
  422. SlotsProcessing int `json:"slots_processing"`
  423. Error string `json:"error"`
  424. Progress float32 `json:"progress"`
  425. }
  426. func (s *llmServer) getServerStatus(ctx context.Context) (ServerStatus, error) {
  427. // Fail fast if its exited
  428. if s.cmd.ProcessState != nil {
  429. msg := ""
  430. if s.status != nil && s.status.LastErrMsg != "" {
  431. msg = s.status.LastErrMsg
  432. }
  433. if s.cmd.ProcessState.ExitCode() == -1 {
  434. // Most likely a signal killed it, log some more details to try to help troubleshoot
  435. slog.Warn("llama runner process no longer running", "sys", s.cmd.ProcessState.Sys(), "string", s.cmd.ProcessState.String())
  436. }
  437. return ServerStatusError, fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
  438. }
  439. req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/health", s.port), nil)
  440. if err != nil {
  441. return ServerStatusError, fmt.Errorf("error creating GET request: %v", err)
  442. }
  443. req.Header.Set("Content-Type", "application/json")
  444. resp, err := http.DefaultClient.Do(req)
  445. if err != nil {
  446. if errors.Is(err, context.DeadlineExceeded) {
  447. return ServerStatusNotResponding, errors.New("server not responding")
  448. }
  449. return ServerStatusError, fmt.Errorf("health resp: %w", err)
  450. }
  451. defer resp.Body.Close()
  452. body, err := io.ReadAll(resp.Body)
  453. if err != nil {
  454. return ServerStatusError, fmt.Errorf("read health request: %w", err)
  455. }
  456. var status ServerStatusResp
  457. if err := json.Unmarshal(body, &status); err != nil {
  458. return ServerStatusError, fmt.Errorf("health unmarshal encode response: %w", err)
  459. }
  460. switch status.Status {
  461. case "ok":
  462. return ServerStatusReady, nil
  463. case "no slot available":
  464. return ServerStatusNoSlotsAvailable, nil
  465. case "loading model":
  466. s.loadProgress = status.Progress
  467. return ServerStatusLoadingModel, nil
  468. default:
  469. return ServerStatusError, fmt.Errorf("server error: %+v", status)
  470. }
  471. }
  472. // getServerStatusRetry will retry if ServerStatusNoSlotsAvailable is received
  473. func (s *llmServer) getServerStatusRetry(ctx context.Context) (ServerStatus, error) {
  474. var retries int
  475. for {
  476. status, err := s.getServerStatus(ctx)
  477. if err != nil {
  478. return status, err
  479. }
  480. if status == ServerStatusNoSlotsAvailable {
  481. if retries >= 10 {
  482. return status, fmt.Errorf("no slots available after %d retries", retries)
  483. }
  484. time.Sleep(5 * time.Millisecond)
  485. retries++
  486. continue
  487. }
  488. return status, nil
  489. }
  490. }
  491. func (s *llmServer) Ping(ctx context.Context) error {
  492. _, err := s.getServerStatus(ctx)
  493. if err != nil {
  494. slog.Debug("server unhealthy", "error", err)
  495. return err
  496. }
  497. return nil
  498. }
  499. func (s *llmServer) WaitUntilRunning(ctx context.Context) error {
  500. start := time.Now()
  501. stallDuration := envconfig.LoadTimeout() // If no progress happens
  502. stallTimer := time.Now().Add(stallDuration) // give up if we stall
  503. slog.Info("waiting for llama runner to start responding")
  504. var lastStatus ServerStatus = -1
  505. fullyLoaded := false
  506. for {
  507. select {
  508. case <-ctx.Done():
  509. slog.Warn("client connection closed before server finished loading, aborting load")
  510. return fmt.Errorf("timed out waiting for llama runner to start: %w", ctx.Err())
  511. case err := <-s.done:
  512. return fmt.Errorf("llama runner process has terminated: %w", err)
  513. default:
  514. }
  515. if time.Now().After(stallTimer) {
  516. // timeout
  517. msg := ""
  518. if s.status != nil && s.status.LastErrMsg != "" {
  519. msg = s.status.LastErrMsg
  520. }
  521. return fmt.Errorf("timed out waiting for llama runner to start - progress %0.2f - %s", s.loadProgress, msg)
  522. }
  523. if s.cmd.ProcessState != nil {
  524. msg := ""
  525. if s.status != nil && s.status.LastErrMsg != "" {
  526. msg = s.status.LastErrMsg
  527. }
  528. return fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
  529. }
  530. ctx, cancel := context.WithTimeout(ctx, 200*time.Millisecond)
  531. defer cancel()
  532. priorProgress := s.loadProgress
  533. status, _ := s.getServerStatus(ctx)
  534. if lastStatus != status && status != ServerStatusReady {
  535. // Only log on status changes
  536. slog.Info("waiting for server to become available", "status", status.ToString())
  537. }
  538. switch status {
  539. case ServerStatusReady:
  540. s.loadDuration = time.Since(start)
  541. slog.Info(fmt.Sprintf("llama runner started in %0.2f seconds", s.loadDuration.Seconds()))
  542. return nil
  543. default:
  544. lastStatus = status
  545. // Reset the timer as long as we're making forward progress on the load
  546. if priorProgress != s.loadProgress {
  547. slog.Debug(fmt.Sprintf("model load progress %0.2f", s.loadProgress))
  548. stallTimer = time.Now().Add(stallDuration)
  549. } else if !fullyLoaded && int(s.loadProgress*100.0) >= 100 {
  550. slog.Debug("model load completed, waiting for server to become available", "status", status.ToString())
  551. stallTimer = time.Now().Add(stallDuration)
  552. fullyLoaded = true
  553. }
  554. time.Sleep(time.Millisecond * 250)
  555. continue
  556. }
  557. }
  558. }
  559. const jsonGrammar = `
  560. root ::= object
  561. value ::= object | array | string | number | ("true" | "false" | "null") ws
  562. object ::=
  563. "{" ws (
  564. string ":" ws value
  565. ("," ws string ":" ws value)*
  566. )? "}" ws
  567. array ::=
  568. "[" ws (
  569. value
  570. ("," ws value)*
  571. )? "]" ws
  572. string ::=
  573. "\"" (
  574. [^"\\\x7F\x00-\x1F] |
  575. "\\" (["\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) # escapes
  576. )* "\"" ws
  577. number ::= ("-"? ([0-9] | [1-9] [0-9]*)) ("." [0-9]+)? ([eE] [-+]? [0-9]+)? ws
  578. # Optional space: by convention, applied in this grammar after literal chars when allowed
  579. ws ::= ([ \t\n] ws)?
  580. `
  581. const maxBufferSize = 512 * format.KiloByte
  582. type ImageData struct {
  583. Data []byte `json:"data"`
  584. ID int `json:"id"`
  585. AspectRatioID int `json:"aspect_ratio_id"`
  586. }
  587. type completion struct {
  588. Content string `json:"content"`
  589. Model string `json:"model"`
  590. Prompt string `json:"prompt"`
  591. Stop bool `json:"stop"`
  592. StoppedLimit bool `json:"stopped_limit"`
  593. Timings struct {
  594. PredictedN int `json:"predicted_n"`
  595. PredictedMS float64 `json:"predicted_ms"`
  596. PromptN int `json:"prompt_n"`
  597. PromptMS float64 `json:"prompt_ms"`
  598. }
  599. }
  600. type CompletionRequest struct {
  601. Prompt string
  602. Format string
  603. Images []ImageData
  604. Options *api.Options
  605. }
  606. type CompletionResponse struct {
  607. Content string
  608. DoneReason string
  609. Done bool
  610. PromptEvalCount int
  611. PromptEvalDuration time.Duration
  612. EvalCount int
  613. EvalDuration time.Duration
  614. }
  615. func (s *llmServer) Completion(ctx context.Context, req CompletionRequest, fn func(CompletionResponse)) error {
  616. if err := s.sem.Acquire(ctx, 1); err != nil {
  617. if errors.Is(err, context.Canceled) {
  618. slog.Info("aborting completion request due to client closing the connection")
  619. } else {
  620. slog.Error("Failed to acquire semaphore", "error", err)
  621. }
  622. return err
  623. }
  624. defer s.sem.Release(1)
  625. // put an upper limit on num_predict to avoid the model running on forever
  626. if req.Options.NumPredict < 0 || req.Options.NumPredict > 10*s.options.NumCtx {
  627. req.Options.NumPredict = 10 * s.options.NumCtx
  628. }
  629. request := map[string]any{
  630. "prompt": req.Prompt,
  631. "stream": true,
  632. "n_predict": req.Options.NumPredict,
  633. "n_keep": req.Options.NumKeep,
  634. "main_gpu": req.Options.MainGPU,
  635. "temperature": req.Options.Temperature,
  636. "top_k": req.Options.TopK,
  637. "top_p": req.Options.TopP,
  638. "min_p": req.Options.MinP,
  639. "tfs_z": req.Options.TFSZ,
  640. "typical_p": req.Options.TypicalP,
  641. "repeat_last_n": req.Options.RepeatLastN,
  642. "repeat_penalty": req.Options.RepeatPenalty,
  643. "presence_penalty": req.Options.PresencePenalty,
  644. "frequency_penalty": req.Options.FrequencyPenalty,
  645. "mirostat": req.Options.Mirostat,
  646. "mirostat_tau": req.Options.MirostatTau,
  647. "mirostat_eta": req.Options.MirostatEta,
  648. "penalize_nl": req.Options.PenalizeNewline,
  649. "seed": req.Options.Seed,
  650. "stop": req.Options.Stop,
  651. "image_data": req.Images,
  652. "cache_prompt": true,
  653. }
  654. // Make sure the server is ready
  655. status, err := s.getServerStatusRetry(ctx)
  656. if err != nil {
  657. return err
  658. } else if status != ServerStatusReady {
  659. return fmt.Errorf("unexpected server status: %s", status.ToString())
  660. }
  661. if req.Format == "json" {
  662. request["grammar"] = jsonGrammar
  663. if !strings.Contains(strings.ToLower(req.Prompt), "json") {
  664. slog.Warn("Prompt does not specify that the LLM should response in JSON, but JSON format is expected. For best results specify that JSON is expected in the system prompt.")
  665. }
  666. }
  667. // Handling JSON marshaling with special characters unescaped.
  668. buffer := &bytes.Buffer{}
  669. enc := json.NewEncoder(buffer)
  670. enc.SetEscapeHTML(false)
  671. if err := enc.Encode(request); err != nil {
  672. return fmt.Errorf("failed to marshal data: %v", err)
  673. }
  674. endpoint := fmt.Sprintf("http://127.0.0.1:%d/completion", s.port)
  675. serverReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, buffer)
  676. if err != nil {
  677. return fmt.Errorf("error creating POST request: %v", err)
  678. }
  679. serverReq.Header.Set("Content-Type", "application/json")
  680. res, err := http.DefaultClient.Do(serverReq)
  681. if err != nil {
  682. return fmt.Errorf("POST predict: %v", err)
  683. }
  684. defer res.Body.Close()
  685. if res.StatusCode >= 400 {
  686. bodyBytes, err := io.ReadAll(res.Body)
  687. if err != nil {
  688. return fmt.Errorf("failed reading llm error response: %w", err)
  689. }
  690. log.Printf("llm predict error: %s", bodyBytes)
  691. return fmt.Errorf("%s", bodyBytes)
  692. }
  693. scanner := bufio.NewScanner(res.Body)
  694. buf := make([]byte, 0, maxBufferSize)
  695. scanner.Buffer(buf, maxBufferSize)
  696. // keep track of the last token generated, this is used to abort if the model starts looping
  697. var lastToken string
  698. var tokenRepeat int
  699. for scanner.Scan() {
  700. select {
  701. case <-ctx.Done():
  702. // This handles the request cancellation
  703. return ctx.Err()
  704. default:
  705. line := scanner.Bytes()
  706. if len(line) == 0 {
  707. continue
  708. }
  709. // slog.Debug("got line", "line", string(line))
  710. evt, ok := bytes.CutPrefix(line, []byte("data: "))
  711. if !ok {
  712. evt = line
  713. }
  714. var c completion
  715. if err := json.Unmarshal(evt, &c); err != nil {
  716. return fmt.Errorf("error unmarshalling llm prediction response: %v", err)
  717. }
  718. switch {
  719. case strings.TrimSpace(c.Content) == lastToken:
  720. tokenRepeat++
  721. default:
  722. lastToken = strings.TrimSpace(c.Content)
  723. tokenRepeat = 0
  724. }
  725. // 30 picked as an arbitrary max token repeat limit, modify as needed
  726. if tokenRepeat > 30 {
  727. slog.Debug("prediction aborted, token repeat limit reached")
  728. return ctx.Err()
  729. }
  730. if c.Content != "" {
  731. fn(CompletionResponse{
  732. Content: c.Content,
  733. })
  734. }
  735. if c.Stop {
  736. doneReason := "stop"
  737. if c.StoppedLimit {
  738. doneReason = "length"
  739. }
  740. fn(CompletionResponse{
  741. Done: true,
  742. DoneReason: doneReason,
  743. PromptEvalCount: c.Timings.PromptN,
  744. PromptEvalDuration: parseDurationMs(c.Timings.PromptMS),
  745. EvalCount: c.Timings.PredictedN,
  746. EvalDuration: parseDurationMs(c.Timings.PredictedMS),
  747. })
  748. return nil
  749. }
  750. }
  751. }
  752. if err := scanner.Err(); err != nil {
  753. if strings.Contains(err.Error(), "unexpected EOF") || strings.Contains(err.Error(), "forcibly closed") {
  754. s.Close()
  755. var msg string
  756. if s.status != nil && s.status.LastErrMsg != "" {
  757. msg = s.status.LastErrMsg
  758. } else {
  759. msg = err.Error()
  760. }
  761. return fmt.Errorf("an error was encountered while running the model: %s", msg)
  762. }
  763. return fmt.Errorf("error reading llm response: %v", err)
  764. }
  765. return nil
  766. }
  767. type EmbeddingRequest struct {
  768. Content string `json:"content"`
  769. }
  770. type EmbeddingResponse struct {
  771. Embedding []float32 `json:"embedding"`
  772. }
  773. func (s *llmServer) Embedding(ctx context.Context, input string) ([]float32, error) {
  774. if err := s.sem.Acquire(ctx, 1); err != nil {
  775. if errors.Is(err, context.Canceled) {
  776. slog.Info("aborting embedding request due to client closing the connection")
  777. } else {
  778. slog.Error("Failed to acquire semaphore", "error", err)
  779. }
  780. return nil, err
  781. }
  782. defer s.sem.Release(1)
  783. // Make sure the server is ready
  784. status, err := s.getServerStatusRetry(ctx)
  785. if err != nil {
  786. return nil, err
  787. } else if status != ServerStatusReady {
  788. return nil, fmt.Errorf("unexpected server status: %s", status.ToString())
  789. }
  790. data, err := json.Marshal(EmbeddingRequest{Content: input})
  791. if err != nil {
  792. return nil, fmt.Errorf("error marshaling embed data: %w", err)
  793. }
  794. r, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/embedding", s.port), bytes.NewBuffer(data))
  795. if err != nil {
  796. return nil, fmt.Errorf("error creating embed request: %w", err)
  797. }
  798. r.Header.Set("Content-Type", "application/json")
  799. resp, err := http.DefaultClient.Do(r)
  800. if err != nil {
  801. return nil, fmt.Errorf("do embedding request: %w", err)
  802. }
  803. defer resp.Body.Close()
  804. body, err := io.ReadAll(resp.Body)
  805. if err != nil {
  806. return nil, fmt.Errorf("error reading embed response: %w", err)
  807. }
  808. if resp.StatusCode >= 400 {
  809. log.Printf("llm embedding error: %s", body)
  810. return nil, fmt.Errorf("%s", body)
  811. }
  812. var e EmbeddingResponse
  813. if err := json.Unmarshal(body, &e); err != nil {
  814. return nil, fmt.Errorf("unmarshal tokenize response: %w", err)
  815. }
  816. return e.Embedding, nil
  817. }
  818. type TokenizeRequest struct {
  819. Content string `json:"content"`
  820. }
  821. type TokenizeResponse struct {
  822. Tokens []int `json:"tokens"`
  823. }
  824. func (s *llmServer) Tokenize(ctx context.Context, content string) ([]int, error) {
  825. s.modelLock.Lock()
  826. defer s.modelLock.Unlock()
  827. if s.model != nil {
  828. return s.model.Tokenize(content, false, true)
  829. }
  830. // Make sure the server is ready
  831. status, err := s.getServerStatus(ctx)
  832. if err != nil {
  833. return nil, err
  834. } else if status != ServerStatusReady && status != ServerStatusNoSlotsAvailable {
  835. return nil, fmt.Errorf("unexpected server status: %s", status.ToString())
  836. }
  837. data, err := json.Marshal(TokenizeRequest{Content: content})
  838. if err != nil {
  839. return nil, fmt.Errorf("marshaling encode data: %w", err)
  840. }
  841. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/tokenize", s.port), bytes.NewBuffer(data))
  842. if err != nil {
  843. return nil, fmt.Errorf("encode request: %w", err)
  844. }
  845. req.Header.Set("Content-Type", "application/json")
  846. resp, err := http.DefaultClient.Do(req)
  847. if err != nil {
  848. return nil, fmt.Errorf("do encode request: %w", err)
  849. }
  850. defer resp.Body.Close()
  851. if resp.StatusCode == http.StatusNotFound {
  852. if s.model == nil {
  853. slog.Debug("new runner detected, loading model for cgo tokenization")
  854. m, err := llama.LoadModelFromFile(s.modelPath, llama.ModelParams{VocabOnly: true})
  855. if err != nil {
  856. return nil, err
  857. }
  858. s.model = m
  859. }
  860. return s.model.Tokenize(content, false, true)
  861. }
  862. body, err := io.ReadAll(resp.Body)
  863. if err != nil {
  864. return nil, fmt.Errorf("read encode request: %w", err)
  865. }
  866. if resp.StatusCode >= 400 {
  867. log.Printf("llm encode error: %s", body)
  868. return nil, fmt.Errorf("%s", body)
  869. }
  870. var encoded TokenizeResponse
  871. if err := json.Unmarshal(body, &encoded); err != nil {
  872. return nil, fmt.Errorf("unmarshal encode response: %w", err)
  873. }
  874. return encoded.Tokens, nil
  875. }
  876. type DetokenizeRequest struct {
  877. Tokens []int `json:"tokens"`
  878. }
  879. type DetokenizeResponse struct {
  880. Content string `json:"content"`
  881. }
  882. func (s *llmServer) Detokenize(ctx context.Context, tokens []int) (string, error) {
  883. s.modelLock.Lock()
  884. defer s.modelLock.Unlock()
  885. if s.model != nil {
  886. var resp string
  887. for _, token := range tokens {
  888. resp += s.model.TokenToPiece(token)
  889. }
  890. return resp, nil
  891. }
  892. // Make sure the server is ready
  893. status, err := s.getServerStatus(ctx)
  894. if err != nil {
  895. return "", err
  896. } else if status != ServerStatusReady && status != ServerStatusNoSlotsAvailable {
  897. return "", fmt.Errorf("unexpected server status: %s", status.ToString())
  898. }
  899. data, err := json.Marshal(DetokenizeRequest{Tokens: tokens})
  900. if err != nil {
  901. return "", fmt.Errorf("marshaling decode data: %w", err)
  902. }
  903. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/detokenize", s.port), bytes.NewBuffer(data))
  904. if err != nil {
  905. return "", fmt.Errorf("decode request: %w", err)
  906. }
  907. req.Header.Set("Content-Type", "application/json")
  908. resp, err := http.DefaultClient.Do(req)
  909. if err != nil {
  910. return "", fmt.Errorf("do decode request: %w", err)
  911. }
  912. defer resp.Body.Close()
  913. if resp.StatusCode == http.StatusNotFound {
  914. if s.model == nil {
  915. slog.Debug("new runner detected, loading model for cgo tokenization")
  916. m, err := llama.LoadModelFromFile(s.modelPath, llama.ModelParams{VocabOnly: true})
  917. if err != nil {
  918. return "", err
  919. }
  920. s.model = m
  921. }
  922. var resp string
  923. for _, token := range tokens {
  924. resp += s.model.TokenToPiece(token)
  925. }
  926. return resp, nil
  927. }
  928. body, err := io.ReadAll(resp.Body)
  929. if err != nil {
  930. return "", fmt.Errorf("read decode request: %w", err)
  931. }
  932. if resp.StatusCode >= 400 {
  933. log.Printf("llm decode error: %s", body)
  934. return "", fmt.Errorf("%s", body)
  935. }
  936. var decoded DetokenizeResponse
  937. if err := json.Unmarshal(body, &decoded); err != nil {
  938. return "", fmt.Errorf("unmarshal encode response: %w", err)
  939. }
  940. return decoded.Content, nil
  941. }
  942. func (s *llmServer) Close() error {
  943. s.modelLock.Lock()
  944. if s.model != nil {
  945. llama.FreeModel(s.model)
  946. s.model = nil
  947. }
  948. s.modelLock.Unlock()
  949. if s.cmd != nil {
  950. slog.Debug("stopping llama server")
  951. if err := s.cmd.Process.Kill(); err != nil {
  952. return err
  953. }
  954. // if ProcessState is already populated, Wait already completed, no need to wait again
  955. if s.cmd.ProcessState == nil {
  956. slog.Debug("waiting for llama server to exit")
  957. <-s.done
  958. }
  959. slog.Debug("llama server stopped")
  960. }
  961. return nil
  962. }
  963. func (s *llmServer) EstimatedVRAM() uint64 {
  964. return s.estimate.VRAMSize
  965. }
  966. func (s *llmServer) EstimatedTotal() uint64 {
  967. return s.estimate.TotalSize
  968. }
  969. func (s *llmServer) EstimatedVRAMByGPU(gpuID string) uint64 {
  970. for i, gpu := range s.gpus {
  971. if gpu.ID == gpuID {
  972. if i < len(s.estimate.GPUSizes) {
  973. return s.estimate.GPUSizes[i]
  974. }
  975. }
  976. }
  977. return 0
  978. }
  979. func parseDurationMs(ms float64) time.Duration {
  980. dur, err := time.ParseDuration(fmt.Sprintf("%fms", ms))
  981. if err != nil {
  982. panic(err)
  983. }
  984. return dur
  985. }