server.go 31 KB

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