server.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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.Debug("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() {
  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 len(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. // prepend the server directory to LD_LIBRARY_PATH/PATH and the parent dir for common dependencies
  268. libraryPaths := []string{dir, filepath.Dir(dir)}
  269. if libraryPath, ok := os.LookupEnv(pathEnv); ok {
  270. // Append our runner directory to the path
  271. // This will favor system libraries over our bundled library dependencies
  272. libraryPaths = append(libraryPaths, filepath.SplitList(libraryPath)...)
  273. }
  274. // Note: we always put the dependency path first
  275. // since this was the exact version we verified for AMD GPUs
  276. // and we favor what the user had in their path
  277. if gpus[0].DependencyPath != "" {
  278. // TODO refine for multi-gpu support
  279. libraryPaths = append([]string{gpus[0].DependencyPath}, libraryPaths...)
  280. }
  281. server := filepath.Join(dir, "ollama_llama_server")
  282. if runtime.GOOS == "windows" {
  283. server += ".exe"
  284. }
  285. // Detect tmp cleaners wiping out the file
  286. _, err := os.Stat(server)
  287. if errors.Is(err, os.ErrNotExist) {
  288. slog.Warn("llama server disappeared, reinitializing payloads", "path", server, "error", err)
  289. err = Init()
  290. if err != nil {
  291. slog.Warn("failed to reinitialize payloads", "error", err)
  292. return nil, err
  293. }
  294. }
  295. s := &llmServer{
  296. port: port,
  297. cmd: exec.Command(server, finalParams...),
  298. status: NewStatusWriter(os.Stderr),
  299. options: opts,
  300. estimate: estimate,
  301. numParallel: numParallel,
  302. sem: semaphore.NewWeighted(int64(numParallel)),
  303. totalLayers: ggml.KV().BlockCount() + 1,
  304. gpus: gpus,
  305. done: make(chan error, 1),
  306. }
  307. s.cmd.Env = os.Environ()
  308. s.cmd.Stdout = os.Stdout
  309. s.cmd.Stderr = s.status
  310. s.cmd.SysProcAttr = LlamaServerSysProcAttr
  311. envWorkarounds := [][2]string{}
  312. for _, gpu := range gpus {
  313. envWorkarounds = append(envWorkarounds, gpu.EnvWorkarounds...)
  314. }
  315. visibleDevicesEnv, visibleDevicesEnvVal := gpus.GetVisibleDevicesEnv()
  316. pathEnvVal := strings.Join(libraryPaths, string(filepath.ListSeparator))
  317. // Update or add the path and visible devices variable with our adjusted version
  318. pathNeeded := true
  319. devicesNeeded := visibleDevicesEnv != ""
  320. for i := range s.cmd.Env {
  321. cmp := strings.SplitN(s.cmd.Env[i], "=", 2)
  322. if strings.EqualFold(cmp[0], pathEnv) {
  323. s.cmd.Env[i] = pathEnv + "=" + pathEnvVal
  324. pathNeeded = false
  325. } else if devicesNeeded && strings.EqualFold(cmp[0], visibleDevicesEnv) {
  326. s.cmd.Env[i] = visibleDevicesEnv + "=" + visibleDevicesEnvVal
  327. devicesNeeded = false
  328. } else if len(envWorkarounds) != 0 {
  329. for _, kv := range envWorkarounds {
  330. if strings.EqualFold(cmp[0], kv[0]) {
  331. s.cmd.Env[i] = kv[0] + "=" + kv[1]
  332. }
  333. }
  334. }
  335. }
  336. if pathNeeded {
  337. s.cmd.Env = append(s.cmd.Env, pathEnv+"="+pathEnvVal)
  338. }
  339. if devicesNeeded {
  340. s.cmd.Env = append(s.cmd.Env, visibleDevicesEnv+"="+visibleDevicesEnvVal)
  341. }
  342. slog.Info("starting llama server", "cmd", s.cmd.String())
  343. if envconfig.Debug() {
  344. filteredEnv := []string{}
  345. for _, ev := range s.cmd.Env {
  346. if strings.HasPrefix(ev, "CUDA_") ||
  347. strings.HasPrefix(ev, "ROCR_") ||
  348. strings.HasPrefix(ev, "ROCM_") ||
  349. strings.HasPrefix(ev, "HIP_") ||
  350. strings.HasPrefix(ev, "GPU_") ||
  351. strings.HasPrefix(ev, "HSA_") ||
  352. strings.HasPrefix(ev, "GGML_") ||
  353. strings.HasPrefix(ev, "PATH=") ||
  354. strings.HasPrefix(ev, "LD_LIBRARY_PATH=") {
  355. filteredEnv = append(filteredEnv, ev)
  356. }
  357. }
  358. // Log at debug as the environment is inherited and might contain sensitive information
  359. slog.Debug("subprocess", "environment", filteredEnv)
  360. }
  361. if err = s.cmd.Start(); err != nil {
  362. // Detect permission denied and augment them essage about noexec
  363. if errors.Is(err, os.ErrPermission) {
  364. 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)
  365. continue
  366. }
  367. msg := ""
  368. if s.status != nil && s.status.LastErrMsg != "" {
  369. msg = s.status.LastErrMsg
  370. }
  371. err = fmt.Errorf("error starting the external llama server: %v %s", err, msg)
  372. finalErr = err
  373. continue
  374. }
  375. // reap subprocess when it exits
  376. go func() {
  377. err := s.cmd.Wait()
  378. // Favor a more detailed message over the process exit status
  379. if err != nil && s.status != nil && s.status.LastErrMsg != "" {
  380. slog.Debug("llama runner terminated", "error", err)
  381. if strings.Contains(s.status.LastErrMsg, "unknown model") {
  382. s.status.LastErrMsg = "this model is not supported by your version of Ollama. You may need to upgrade"
  383. }
  384. s.done <- errors.New(s.status.LastErrMsg)
  385. } else {
  386. s.done <- err
  387. }
  388. }()
  389. return s, nil
  390. }
  391. slog.Error("unable to load any llama server", "error", finalErr)
  392. return nil, finalErr
  393. }
  394. func projectorMemoryRequirements(filename string) uint64 {
  395. file, err := os.Open(filename)
  396. if err != nil {
  397. return 0
  398. }
  399. defer file.Close()
  400. ggml, _, err := DecodeGGML(file, 0)
  401. if err != nil {
  402. return 0
  403. }
  404. var mem uint64
  405. for _, layer := range ggml.Tensors().Layers() {
  406. mem += layer.size()
  407. }
  408. return mem
  409. }
  410. type ServerStatus int
  411. const ( // iota is reset to 0
  412. ServerStatusReady ServerStatus = iota
  413. ServerStatusNoSlotsAvailable
  414. ServerStatusLoadingModel
  415. ServerStatusNotResponding
  416. ServerStatusError
  417. )
  418. func (s ServerStatus) ToString() string {
  419. switch s {
  420. case ServerStatusReady:
  421. return "llm server ready"
  422. case ServerStatusNoSlotsAvailable:
  423. return "llm busy - no slots available"
  424. case ServerStatusLoadingModel:
  425. return "llm server loading model"
  426. case ServerStatusNotResponding:
  427. return "llm server not responding"
  428. default:
  429. return "llm server error"
  430. }
  431. }
  432. type ServerStatusResp struct {
  433. Status string `json:"status"`
  434. SlotsIdle int `json:"slots_idle"`
  435. SlotsProcessing int `json:"slots_processing"`
  436. Error string `json:"error"`
  437. Progress float32 `json:"progress"`
  438. }
  439. func (s *llmServer) getServerStatus(ctx context.Context) (ServerStatus, error) {
  440. // Fail fast if its exited
  441. if s.cmd.ProcessState != nil {
  442. msg := ""
  443. if s.status != nil && s.status.LastErrMsg != "" {
  444. msg = s.status.LastErrMsg
  445. }
  446. if s.cmd.ProcessState.ExitCode() == -1 {
  447. // Most likely a signal killed it, log some more details to try to help troubleshoot
  448. slog.Warn("llama runner process no longer running", "sys", s.cmd.ProcessState.Sys(), "string", s.cmd.ProcessState.String())
  449. }
  450. return ServerStatusError, fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
  451. }
  452. req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/health", s.port), nil)
  453. if err != nil {
  454. return ServerStatusError, fmt.Errorf("error creating GET request: %v", err)
  455. }
  456. req.Header.Set("Content-Type", "application/json")
  457. resp, err := http.DefaultClient.Do(req)
  458. if err != nil {
  459. if errors.Is(err, context.DeadlineExceeded) {
  460. return ServerStatusNotResponding, errors.New("server not responding")
  461. }
  462. return ServerStatusError, fmt.Errorf("health resp: %w", err)
  463. }
  464. defer resp.Body.Close()
  465. body, err := io.ReadAll(resp.Body)
  466. if err != nil {
  467. return ServerStatusError, fmt.Errorf("read health request: %w", err)
  468. }
  469. var status ServerStatusResp
  470. if err := json.Unmarshal(body, &status); err != nil {
  471. return ServerStatusError, fmt.Errorf("health unmarshal encode response: %w", err)
  472. }
  473. switch status.Status {
  474. case "ok":
  475. return ServerStatusReady, nil
  476. case "no slot available":
  477. return ServerStatusNoSlotsAvailable, nil
  478. case "loading model":
  479. s.loadProgress = status.Progress
  480. return ServerStatusLoadingModel, nil
  481. default:
  482. return ServerStatusError, fmt.Errorf("server error: %+v", status)
  483. }
  484. }
  485. // getServerStatusRetry will retry if ServerStatusNoSlotsAvailable is received
  486. func (s *llmServer) getServerStatusRetry(ctx context.Context) (ServerStatus, error) {
  487. var retries int
  488. for {
  489. status, err := s.getServerStatus(ctx)
  490. if err != nil {
  491. return status, err
  492. }
  493. if status == ServerStatusNoSlotsAvailable {
  494. if retries >= 10 {
  495. return status, fmt.Errorf("no slots available after %d retries", retries)
  496. }
  497. time.Sleep(5 * time.Millisecond)
  498. retries++
  499. continue
  500. }
  501. return status, nil
  502. }
  503. }
  504. func (s *llmServer) Ping(ctx context.Context) error {
  505. _, err := s.getServerStatus(ctx)
  506. if err != nil {
  507. slog.Debug("server unhealthy", "error", err)
  508. return err
  509. }
  510. return nil
  511. }
  512. func (s *llmServer) WaitUntilRunning(ctx context.Context) error {
  513. start := time.Now()
  514. stallDuration := 5 * time.Minute // If no progress happens
  515. finalLoadDuration := 5 * time.Minute // After we hit 100%, give the runner more time to come online
  516. stallTimer := time.Now().Add(stallDuration) // give up if we stall
  517. slog.Info("waiting for llama runner to start responding")
  518. var lastStatus ServerStatus = -1
  519. fullyLoaded := false
  520. for {
  521. select {
  522. case <-ctx.Done():
  523. slog.Warn("client connection closed before server finished loading, aborting load")
  524. return fmt.Errorf("timed out waiting for llama runner to start: %w", ctx.Err())
  525. case err := <-s.done:
  526. return fmt.Errorf("llama runner process has terminated: %w", err)
  527. default:
  528. }
  529. if time.Now().After(stallTimer) {
  530. // timeout
  531. msg := ""
  532. if s.status != nil && s.status.LastErrMsg != "" {
  533. msg = s.status.LastErrMsg
  534. }
  535. return fmt.Errorf("timed out waiting for llama runner to start - progress %0.2f - %s", s.loadProgress, msg)
  536. }
  537. if s.cmd.ProcessState != nil {
  538. msg := ""
  539. if s.status != nil && s.status.LastErrMsg != "" {
  540. msg = s.status.LastErrMsg
  541. }
  542. return fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
  543. }
  544. ctx, cancel := context.WithTimeout(ctx, 200*time.Millisecond)
  545. defer cancel()
  546. priorProgress := s.loadProgress
  547. status, _ := s.getServerStatus(ctx)
  548. if lastStatus != status && status != ServerStatusReady {
  549. // Only log on status changes
  550. slog.Info("waiting for server to become available", "status", status.ToString())
  551. }
  552. switch status {
  553. case ServerStatusReady:
  554. s.loadDuration = time.Since(start)
  555. slog.Info(fmt.Sprintf("llama runner started in %0.2f seconds", s.loadDuration.Seconds()))
  556. return nil
  557. default:
  558. lastStatus = status
  559. // Reset the timer as long as we're making forward progress on the load
  560. if priorProgress != s.loadProgress {
  561. slog.Debug(fmt.Sprintf("model load progress %0.2f", s.loadProgress))
  562. stallTimer = time.Now().Add(stallDuration)
  563. } else if !fullyLoaded && int(s.loadProgress*100.0) >= 100 {
  564. slog.Debug("model load completed, waiting for server to become available", "status", status.ToString())
  565. stallTimer = time.Now().Add(finalLoadDuration)
  566. fullyLoaded = true
  567. }
  568. time.Sleep(time.Millisecond * 250)
  569. continue
  570. }
  571. }
  572. }
  573. const jsonGrammar = `
  574. root ::= object
  575. value ::= object | array | string | number | ("true" | "false" | "null") ws
  576. object ::=
  577. "{" ws (
  578. string ":" ws value
  579. ("," ws string ":" ws value)*
  580. )? "}" ws
  581. array ::=
  582. "[" ws (
  583. value
  584. ("," ws value)*
  585. )? "]" ws
  586. string ::=
  587. "\"" (
  588. [^"\\\x7F\x00-\x1F] |
  589. "\\" (["\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) # escapes
  590. )* "\"" ws
  591. number ::= ("-"? ([0-9] | [1-9] [0-9]*)) ("." [0-9]+)? ([eE] [-+]? [0-9]+)? ws
  592. # Optional space: by convention, applied in this grammar after literal chars when allowed
  593. ws ::= ([ \t\n] ws)?
  594. `
  595. const maxBufferSize = 512 * format.KiloByte
  596. type ImageData struct {
  597. Data []byte `json:"data"`
  598. ID int `json:"id"`
  599. }
  600. type completion struct {
  601. Content string `json:"content"`
  602. Model string `json:"model"`
  603. Prompt string `json:"prompt"`
  604. Stop bool `json:"stop"`
  605. StoppedLimit bool `json:"stopped_limit"`
  606. Timings struct {
  607. PredictedN int `json:"predicted_n"`
  608. PredictedMS float64 `json:"predicted_ms"`
  609. PromptN int `json:"prompt_n"`
  610. PromptMS float64 `json:"prompt_ms"`
  611. }
  612. }
  613. type CompletionRequest struct {
  614. Prompt string
  615. Format string
  616. Images []ImageData
  617. Options *api.Options
  618. }
  619. type CompletionResponse struct {
  620. Content string
  621. DoneReason string
  622. Done bool
  623. PromptEvalCount int
  624. PromptEvalDuration time.Duration
  625. EvalCount int
  626. EvalDuration time.Duration
  627. }
  628. func (s *llmServer) Completion(ctx context.Context, req CompletionRequest, fn func(CompletionResponse)) error {
  629. if err := s.sem.Acquire(ctx, 1); err != nil {
  630. slog.Error("Failed to acquire semaphore", "error", err)
  631. return err
  632. }
  633. defer s.sem.Release(1)
  634. // put an upper limit on num_predict to avoid the model running on forever
  635. if req.Options.NumPredict < 0 || req.Options.NumPredict > 10*s.options.NumCtx {
  636. req.Options.NumPredict = 10 * s.options.NumCtx
  637. }
  638. request := map[string]any{
  639. "prompt": req.Prompt,
  640. "stream": true,
  641. "n_predict": req.Options.NumPredict,
  642. "n_keep": req.Options.NumKeep,
  643. "main_gpu": req.Options.MainGPU,
  644. "temperature": req.Options.Temperature,
  645. "top_k": req.Options.TopK,
  646. "top_p": req.Options.TopP,
  647. "min_p": req.Options.MinP,
  648. "tfs_z": req.Options.TFSZ,
  649. "typical_p": req.Options.TypicalP,
  650. "repeat_last_n": req.Options.RepeatLastN,
  651. "repeat_penalty": req.Options.RepeatPenalty,
  652. "presence_penalty": req.Options.PresencePenalty,
  653. "frequency_penalty": req.Options.FrequencyPenalty,
  654. "mirostat": req.Options.Mirostat,
  655. "mirostat_tau": req.Options.MirostatTau,
  656. "mirostat_eta": req.Options.MirostatEta,
  657. "penalize_nl": req.Options.PenalizeNewline,
  658. "seed": req.Options.Seed,
  659. "stop": req.Options.Stop,
  660. "image_data": req.Images,
  661. "cache_prompt": true,
  662. }
  663. // Make sure the server is ready
  664. status, err := s.getServerStatusRetry(ctx)
  665. if err != nil {
  666. return err
  667. } else if status != ServerStatusReady {
  668. return fmt.Errorf("unexpected server status: %s", status.ToString())
  669. }
  670. if req.Format == "json" {
  671. request["grammar"] = jsonGrammar
  672. if !strings.Contains(strings.ToLower(req.Prompt), "json") {
  673. 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.")
  674. }
  675. }
  676. // Handling JSON marshaling with special characters unescaped.
  677. buffer := &bytes.Buffer{}
  678. enc := json.NewEncoder(buffer)
  679. enc.SetEscapeHTML(false)
  680. if err := enc.Encode(request); err != nil {
  681. return fmt.Errorf("failed to marshal data: %v", err)
  682. }
  683. endpoint := fmt.Sprintf("http://127.0.0.1:%d/completion", s.port)
  684. serverReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, buffer)
  685. if err != nil {
  686. return fmt.Errorf("error creating POST request: %v", err)
  687. }
  688. serverReq.Header.Set("Content-Type", "application/json")
  689. res, err := http.DefaultClient.Do(serverReq)
  690. if err != nil {
  691. return fmt.Errorf("POST predict: %v", err)
  692. }
  693. defer res.Body.Close()
  694. if res.StatusCode >= 400 {
  695. bodyBytes, err := io.ReadAll(res.Body)
  696. if err != nil {
  697. return fmt.Errorf("failed reading llm error response: %w", err)
  698. }
  699. log.Printf("llm predict error: %s", bodyBytes)
  700. return fmt.Errorf("%s", bodyBytes)
  701. }
  702. scanner := bufio.NewScanner(res.Body)
  703. buf := make([]byte, 0, maxBufferSize)
  704. scanner.Buffer(buf, maxBufferSize)
  705. // keep track of the last token generated, this is used to abort if the model starts looping
  706. var lastToken string
  707. var tokenRepeat int
  708. for scanner.Scan() {
  709. select {
  710. case <-ctx.Done():
  711. // This handles the request cancellation
  712. return ctx.Err()
  713. default:
  714. line := scanner.Bytes()
  715. if len(line) == 0 {
  716. continue
  717. }
  718. evt, ok := bytes.CutPrefix(line, []byte("data: "))
  719. if !ok {
  720. return fmt.Errorf("error parsing llm response stream: %s", line)
  721. }
  722. var c completion
  723. if err := json.Unmarshal(evt, &c); err != nil {
  724. return fmt.Errorf("error unmarshalling llm prediction response: %v", err)
  725. }
  726. switch {
  727. case strings.TrimSpace(c.Content) == lastToken:
  728. tokenRepeat++
  729. default:
  730. lastToken = strings.TrimSpace(c.Content)
  731. tokenRepeat = 0
  732. }
  733. // 30 picked as an arbitrary max token repeat limit, modify as needed
  734. if tokenRepeat > 30 {
  735. slog.Debug("prediction aborted, token repeat limit reached")
  736. return ctx.Err()
  737. }
  738. if c.Content != "" {
  739. fn(CompletionResponse{
  740. Content: c.Content,
  741. })
  742. }
  743. if c.Stop {
  744. doneReason := "stop"
  745. if c.StoppedLimit {
  746. doneReason = "length"
  747. }
  748. fn(CompletionResponse{
  749. Done: true,
  750. DoneReason: doneReason,
  751. PromptEvalCount: c.Timings.PromptN,
  752. PromptEvalDuration: parseDurationMs(c.Timings.PromptMS),
  753. EvalCount: c.Timings.PredictedN,
  754. EvalDuration: parseDurationMs(c.Timings.PredictedMS),
  755. })
  756. return nil
  757. }
  758. }
  759. }
  760. if err := scanner.Err(); err != nil {
  761. if strings.Contains(err.Error(), "unexpected EOF") {
  762. s.Close()
  763. msg := ""
  764. if s.status != nil && s.status.LastErrMsg != "" {
  765. msg = s.status.LastErrMsg
  766. }
  767. return fmt.Errorf("an unknown error was encountered while running the model %s", msg)
  768. }
  769. return fmt.Errorf("error reading llm response: %v", err)
  770. }
  771. return nil
  772. }
  773. type EmbeddingRequest struct {
  774. Content string `json:"content"`
  775. }
  776. type EmbeddingResponse struct {
  777. Embedding []float32 `json:"embedding"`
  778. }
  779. func (s *llmServer) Embedding(ctx context.Context, input string) ([]float32, error) {
  780. if err := s.sem.Acquire(ctx, 1); err != nil {
  781. slog.Error("Failed to acquire semaphore", "error", err)
  782. return nil, err
  783. }
  784. defer s.sem.Release(1)
  785. // Make sure the server is ready
  786. status, err := s.getServerStatusRetry(ctx)
  787. if err != nil {
  788. return nil, err
  789. } else if status != ServerStatusReady {
  790. return nil, fmt.Errorf("unexpected server status: %s", status.ToString())
  791. }
  792. data, err := json.Marshal(EmbeddingRequest{Content: input})
  793. if err != nil {
  794. return nil, fmt.Errorf("error marshaling embed data: %w", err)
  795. }
  796. r, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/embedding", s.port), bytes.NewBuffer(data))
  797. if err != nil {
  798. return nil, fmt.Errorf("error creating embed request: %w", err)
  799. }
  800. r.Header.Set("Content-Type", "application/json")
  801. resp, err := http.DefaultClient.Do(r)
  802. if err != nil {
  803. return nil, fmt.Errorf("do embedding request: %w", err)
  804. }
  805. defer resp.Body.Close()
  806. body, err := io.ReadAll(resp.Body)
  807. if err != nil {
  808. return nil, fmt.Errorf("error reading embed response: %w", err)
  809. }
  810. if resp.StatusCode >= 400 {
  811. log.Printf("llm encode error: %s", body)
  812. return nil, fmt.Errorf("%s", body)
  813. }
  814. var e EmbeddingResponse
  815. if err := json.Unmarshal(body, &e); err != nil {
  816. return nil, fmt.Errorf("unmarshal tokenize response: %w", err)
  817. }
  818. return e.Embedding, nil
  819. }
  820. type TokenizeRequest struct {
  821. Content string `json:"content"`
  822. }
  823. type TokenizeResponse struct {
  824. Tokens []int `json:"tokens"`
  825. }
  826. func (s *llmServer) Tokenize(ctx context.Context, content string) ([]int, error) {
  827. // Make sure the server is ready
  828. status, err := s.getServerStatus(ctx)
  829. if err != nil {
  830. return nil, err
  831. } else if status != ServerStatusReady && status != ServerStatusNoSlotsAvailable {
  832. return nil, fmt.Errorf("unexpected server status: %s", status.ToString())
  833. }
  834. data, err := json.Marshal(TokenizeRequest{Content: content})
  835. if err != nil {
  836. return nil, fmt.Errorf("marshaling encode data: %w", err)
  837. }
  838. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/tokenize", s.port), bytes.NewBuffer(data))
  839. if err != nil {
  840. return nil, fmt.Errorf("encode request: %w", err)
  841. }
  842. req.Header.Set("Content-Type", "application/json")
  843. resp, err := http.DefaultClient.Do(req)
  844. if err != nil {
  845. return nil, fmt.Errorf("do encode request: %w", err)
  846. }
  847. defer resp.Body.Close()
  848. body, err := io.ReadAll(resp.Body)
  849. if err != nil {
  850. return nil, fmt.Errorf("read encode request: %w", err)
  851. }
  852. if resp.StatusCode >= 400 {
  853. log.Printf("llm encode error: %s", body)
  854. return nil, fmt.Errorf("%s", body)
  855. }
  856. var encoded TokenizeResponse
  857. if err := json.Unmarshal(body, &encoded); err != nil {
  858. return nil, fmt.Errorf("unmarshal encode response: %w", err)
  859. }
  860. return encoded.Tokens, nil
  861. }
  862. type DetokenizeRequest struct {
  863. Tokens []int `json:"tokens"`
  864. }
  865. type DetokenizeResponse struct {
  866. Content string `json:"content"`
  867. }
  868. func (s *llmServer) Detokenize(ctx context.Context, tokens []int) (string, error) {
  869. // Make sure the server is ready
  870. status, err := s.getServerStatus(ctx)
  871. if err != nil {
  872. return "", err
  873. } else if status != ServerStatusReady && status != ServerStatusNoSlotsAvailable {
  874. return "", fmt.Errorf("unexpected server status: %s", status.ToString())
  875. }
  876. data, err := json.Marshal(DetokenizeRequest{Tokens: tokens})
  877. if err != nil {
  878. return "", fmt.Errorf("marshaling decode data: %w", err)
  879. }
  880. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/detokenize", s.port), bytes.NewBuffer(data))
  881. if err != nil {
  882. return "", fmt.Errorf("decode request: %w", err)
  883. }
  884. req.Header.Set("Content-Type", "application/json")
  885. resp, err := http.DefaultClient.Do(req)
  886. if err != nil {
  887. return "", fmt.Errorf("do decode request: %w", err)
  888. }
  889. defer resp.Body.Close()
  890. body, err := io.ReadAll(resp.Body)
  891. if err != nil {
  892. return "", fmt.Errorf("read decode request: %w", err)
  893. }
  894. if resp.StatusCode >= 400 {
  895. log.Printf("llm decode error: %s", body)
  896. return "", fmt.Errorf("%s", body)
  897. }
  898. var decoded DetokenizeResponse
  899. if err := json.Unmarshal(body, &decoded); err != nil {
  900. return "", fmt.Errorf("unmarshal encode response: %w", err)
  901. }
  902. return decoded.Content, nil
  903. }
  904. func (s *llmServer) Close() error {
  905. if s.cmd != nil {
  906. slog.Debug("stopping llama server")
  907. if err := s.cmd.Process.Kill(); err != nil {
  908. return err
  909. }
  910. // if ProcessState is already populated, Wait already completed, no need to wait again
  911. if s.cmd.ProcessState == nil {
  912. slog.Debug("waiting for llama server to exit")
  913. <-s.done
  914. }
  915. slog.Debug("llama server stopped")
  916. }
  917. return nil
  918. }
  919. func (s *llmServer) EstimatedVRAM() uint64 {
  920. return s.estimate.VRAMSize
  921. }
  922. func (s *llmServer) EstimatedTotal() uint64 {
  923. return s.estimate.TotalSize
  924. }
  925. func (s *llmServer) EstimatedVRAMByGPU(gpuID string) uint64 {
  926. for i, gpu := range s.gpus {
  927. if gpu.ID == gpuID {
  928. return s.estimate.GPUSizes[i]
  929. }
  930. }
  931. return 0
  932. }
  933. func parseDurationMs(ms float64) time.Duration {
  934. dur, err := time.ParseDuration(fmt.Sprintf("%fms", ms))
  935. if err != nil {
  936. panic(err)
  937. }
  938. return dur
  939. }