server.go 31 KB

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