server.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  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() && 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 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. // 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 := 5 * time.Minute // If no progress happens
  513. finalLoadDuration := 5 * time.Minute // After we hit 100%, give the runner more time to come online
  514. stallTimer := time.Now().Add(stallDuration) // give up if we stall
  515. slog.Info("waiting for llama runner to start responding")
  516. var lastStatus ServerStatus = -1
  517. fullyLoaded := false
  518. for {
  519. select {
  520. case <-ctx.Done():
  521. slog.Warn("client connection closed before server finished loading, aborting load")
  522. return fmt.Errorf("timed out waiting for llama runner to start: %w", ctx.Err())
  523. case err := <-s.done:
  524. return fmt.Errorf("llama runner process has terminated: %w", err)
  525. default:
  526. }
  527. if time.Now().After(stallTimer) {
  528. // timeout
  529. msg := ""
  530. if s.status != nil && s.status.LastErrMsg != "" {
  531. msg = s.status.LastErrMsg
  532. }
  533. return fmt.Errorf("timed out waiting for llama runner to start - progress %0.2f - %s", s.loadProgress, msg)
  534. }
  535. if s.cmd.ProcessState != nil {
  536. msg := ""
  537. if s.status != nil && s.status.LastErrMsg != "" {
  538. msg = s.status.LastErrMsg
  539. }
  540. return fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
  541. }
  542. ctx, cancel := context.WithTimeout(ctx, 200*time.Millisecond)
  543. defer cancel()
  544. priorProgress := s.loadProgress
  545. status, _ := s.getServerStatus(ctx)
  546. if lastStatus != status && status != ServerStatusReady {
  547. // Only log on status changes
  548. slog.Info("waiting for server to become available", "status", status.ToString())
  549. }
  550. switch status {
  551. case ServerStatusReady:
  552. s.loadDuration = time.Since(start)
  553. slog.Info(fmt.Sprintf("llama runner started in %0.2f seconds", s.loadDuration.Seconds()))
  554. return nil
  555. default:
  556. lastStatus = status
  557. // Reset the timer as long as we're making forward progress on the load
  558. if priorProgress != s.loadProgress {
  559. slog.Debug(fmt.Sprintf("model load progress %0.2f", s.loadProgress))
  560. stallTimer = time.Now().Add(stallDuration)
  561. } else if !fullyLoaded && int(s.loadProgress*100.0) >= 100 {
  562. slog.Debug("model load completed, waiting for server to become available", "status", status.ToString())
  563. stallTimer = time.Now().Add(finalLoadDuration)
  564. fullyLoaded = true
  565. }
  566. time.Sleep(time.Millisecond * 250)
  567. continue
  568. }
  569. }
  570. }
  571. const jsonGrammar = `
  572. root ::= object
  573. value ::= object | array | string | number | ("true" | "false" | "null") ws
  574. object ::=
  575. "{" ws (
  576. string ":" ws value
  577. ("," ws string ":" ws value)*
  578. )? "}" ws
  579. array ::=
  580. "[" ws (
  581. value
  582. ("," ws value)*
  583. )? "]" ws
  584. string ::=
  585. "\"" (
  586. [^"\\\x7F\x00-\x1F] |
  587. "\\" (["\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) # escapes
  588. )* "\"" ws
  589. number ::= ("-"? ([0-9] | [1-9] [0-9]*)) ("." [0-9]+)? ([eE] [-+]? [0-9]+)? ws
  590. # Optional space: by convention, applied in this grammar after literal chars when allowed
  591. ws ::= ([ \t\n] ws)?
  592. `
  593. const maxBufferSize = 512 * format.KiloByte
  594. type ImageData struct {
  595. Data []byte `json:"data"`
  596. ID int `json:"id"`
  597. }
  598. type completion struct {
  599. Content string `json:"content"`
  600. Model string `json:"model"`
  601. Prompt string `json:"prompt"`
  602. Stop bool `json:"stop"`
  603. StoppedLimit bool `json:"stopped_limit"`
  604. Timings struct {
  605. PredictedN int `json:"predicted_n"`
  606. PredictedMS float64 `json:"predicted_ms"`
  607. PromptN int `json:"prompt_n"`
  608. PromptMS float64 `json:"prompt_ms"`
  609. }
  610. }
  611. type CompletionRequest struct {
  612. Prompt string
  613. Format string
  614. Images []ImageData
  615. Options *api.Options
  616. }
  617. type CompletionResponse struct {
  618. Content string
  619. DoneReason string
  620. Done bool
  621. PromptEvalCount int
  622. PromptEvalDuration time.Duration
  623. EvalCount int
  624. EvalDuration time.Duration
  625. }
  626. func (s *llmServer) Completion(ctx context.Context, req CompletionRequest, fn func(CompletionResponse)) error {
  627. if err := s.sem.Acquire(ctx, 1); err != nil {
  628. slog.Error("Failed to acquire semaphore", "error", err)
  629. return err
  630. }
  631. defer s.sem.Release(1)
  632. // put an upper limit on num_predict to avoid the model running on forever
  633. if req.Options.NumPredict < 0 || req.Options.NumPredict > 10*s.options.NumCtx {
  634. req.Options.NumPredict = 10 * s.options.NumCtx
  635. }
  636. request := map[string]any{
  637. "prompt": req.Prompt,
  638. "stream": true,
  639. "n_predict": req.Options.NumPredict,
  640. "n_keep": req.Options.NumKeep,
  641. "main_gpu": req.Options.MainGPU,
  642. "temperature": req.Options.Temperature,
  643. "top_k": req.Options.TopK,
  644. "top_p": req.Options.TopP,
  645. "min_p": req.Options.MinP,
  646. "tfs_z": req.Options.TFSZ,
  647. "typical_p": req.Options.TypicalP,
  648. "repeat_last_n": req.Options.RepeatLastN,
  649. "repeat_penalty": req.Options.RepeatPenalty,
  650. "presence_penalty": req.Options.PresencePenalty,
  651. "frequency_penalty": req.Options.FrequencyPenalty,
  652. "mirostat": req.Options.Mirostat,
  653. "mirostat_tau": req.Options.MirostatTau,
  654. "mirostat_eta": req.Options.MirostatEta,
  655. "penalize_nl": req.Options.PenalizeNewline,
  656. "seed": req.Options.Seed,
  657. "stop": req.Options.Stop,
  658. "image_data": req.Images,
  659. "cache_prompt": true,
  660. }
  661. // Make sure the server is ready
  662. status, err := s.getServerStatusRetry(ctx)
  663. if err != nil {
  664. return err
  665. } else if status != ServerStatusReady {
  666. return fmt.Errorf("unexpected server status: %s", status.ToString())
  667. }
  668. if req.Format == "json" {
  669. request["grammar"] = jsonGrammar
  670. if !strings.Contains(strings.ToLower(req.Prompt), "json") {
  671. 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.")
  672. }
  673. }
  674. // Handling JSON marshaling with special characters unescaped.
  675. buffer := &bytes.Buffer{}
  676. enc := json.NewEncoder(buffer)
  677. enc.SetEscapeHTML(false)
  678. if err := enc.Encode(request); err != nil {
  679. return fmt.Errorf("failed to marshal data: %v", err)
  680. }
  681. endpoint := fmt.Sprintf("http://127.0.0.1:%d/completion", s.port)
  682. serverReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, buffer)
  683. if err != nil {
  684. return fmt.Errorf("error creating POST request: %v", err)
  685. }
  686. serverReq.Header.Set("Content-Type", "application/json")
  687. res, err := http.DefaultClient.Do(serverReq)
  688. if err != nil {
  689. return fmt.Errorf("POST predict: %v", err)
  690. }
  691. defer res.Body.Close()
  692. if res.StatusCode >= 400 {
  693. bodyBytes, err := io.ReadAll(res.Body)
  694. if err != nil {
  695. return fmt.Errorf("failed reading llm error response: %w", err)
  696. }
  697. log.Printf("llm predict error: %s", bodyBytes)
  698. return fmt.Errorf("%s", bodyBytes)
  699. }
  700. scanner := bufio.NewScanner(res.Body)
  701. buf := make([]byte, 0, maxBufferSize)
  702. scanner.Buffer(buf, maxBufferSize)
  703. // keep track of the last token generated, this is used to abort if the model starts looping
  704. var lastToken string
  705. var tokenRepeat int
  706. for scanner.Scan() {
  707. select {
  708. case <-ctx.Done():
  709. // This handles the request cancellation
  710. return ctx.Err()
  711. default:
  712. line := scanner.Bytes()
  713. if len(line) == 0 {
  714. continue
  715. }
  716. evt, ok := bytes.CutPrefix(line, []byte("data: "))
  717. if !ok {
  718. return fmt.Errorf("error parsing llm response stream: %s", line)
  719. }
  720. var c completion
  721. if err := json.Unmarshal(evt, &c); err != nil {
  722. return fmt.Errorf("error unmarshalling llm prediction response: %v", err)
  723. }
  724. switch {
  725. case strings.TrimSpace(c.Content) == lastToken:
  726. tokenRepeat++
  727. default:
  728. lastToken = strings.TrimSpace(c.Content)
  729. tokenRepeat = 0
  730. }
  731. // 30 picked as an arbitrary max token repeat limit, modify as needed
  732. if tokenRepeat > 30 {
  733. slog.Debug("prediction aborted, token repeat limit reached")
  734. return ctx.Err()
  735. }
  736. if c.Content != "" {
  737. fn(CompletionResponse{
  738. Content: c.Content,
  739. })
  740. }
  741. if c.Stop {
  742. doneReason := "stop"
  743. if c.StoppedLimit {
  744. doneReason = "length"
  745. }
  746. fn(CompletionResponse{
  747. Done: true,
  748. DoneReason: doneReason,
  749. PromptEvalCount: c.Timings.PromptN,
  750. PromptEvalDuration: parseDurationMs(c.Timings.PromptMS),
  751. EvalCount: c.Timings.PredictedN,
  752. EvalDuration: parseDurationMs(c.Timings.PredictedMS),
  753. })
  754. return nil
  755. }
  756. }
  757. }
  758. if err := scanner.Err(); err != nil {
  759. if strings.Contains(err.Error(), "unexpected EOF") {
  760. s.Close()
  761. msg := ""
  762. if s.status != nil && s.status.LastErrMsg != "" {
  763. msg = s.status.LastErrMsg
  764. }
  765. return fmt.Errorf("an unknown error was encountered while running the model %s", msg)
  766. }
  767. return fmt.Errorf("error reading llm response: %v", err)
  768. }
  769. return nil
  770. }
  771. type EmbeddingRequest struct {
  772. Content string `json:"content"`
  773. }
  774. type EmbeddingResponse struct {
  775. Embedding []float32 `json:"embedding"`
  776. }
  777. func (s *llmServer) Embedding(ctx context.Context, input string) ([]float32, error) {
  778. if err := s.sem.Acquire(ctx, 1); err != nil {
  779. slog.Error("Failed to acquire semaphore", "error", err)
  780. return nil, err
  781. }
  782. defer s.sem.Release(1)
  783. // Make sure the server is ready
  784. status, err := s.getServerStatusRetry(ctx)
  785. if err != nil {
  786. return nil, err
  787. } else if status != ServerStatusReady {
  788. return nil, fmt.Errorf("unexpected server status: %s", status.ToString())
  789. }
  790. data, err := json.Marshal(EmbeddingRequest{Content: input})
  791. if err != nil {
  792. return nil, fmt.Errorf("error marshaling embed data: %w", err)
  793. }
  794. r, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/embedding", s.port), bytes.NewBuffer(data))
  795. if err != nil {
  796. return nil, fmt.Errorf("error creating embed request: %w", err)
  797. }
  798. r.Header.Set("Content-Type", "application/json")
  799. resp, err := http.DefaultClient.Do(r)
  800. if err != nil {
  801. return nil, fmt.Errorf("do embedding request: %w", err)
  802. }
  803. defer resp.Body.Close()
  804. body, err := io.ReadAll(resp.Body)
  805. if err != nil {
  806. return nil, fmt.Errorf("error reading embed response: %w", err)
  807. }
  808. if resp.StatusCode >= 400 {
  809. log.Printf("llm encode error: %s", body)
  810. return nil, fmt.Errorf("%s", body)
  811. }
  812. var e EmbeddingResponse
  813. if err := json.Unmarshal(body, &e); err != nil {
  814. return nil, fmt.Errorf("unmarshal tokenize response: %w", err)
  815. }
  816. return e.Embedding, nil
  817. }
  818. type TokenizeRequest struct {
  819. Content string `json:"content"`
  820. }
  821. type TokenizeResponse struct {
  822. Tokens []int `json:"tokens"`
  823. }
  824. func (s *llmServer) Tokenize(ctx context.Context, content string) ([]int, error) {
  825. // Make sure the server is ready
  826. status, err := s.getServerStatus(ctx)
  827. if err != nil {
  828. return nil, err
  829. } else if status != ServerStatusReady && status != ServerStatusNoSlotsAvailable {
  830. return nil, fmt.Errorf("unexpected server status: %s", status.ToString())
  831. }
  832. data, err := json.Marshal(TokenizeRequest{Content: content})
  833. if err != nil {
  834. return nil, fmt.Errorf("marshaling encode data: %w", err)
  835. }
  836. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/tokenize", s.port), bytes.NewBuffer(data))
  837. if err != nil {
  838. return nil, fmt.Errorf("encode request: %w", err)
  839. }
  840. req.Header.Set("Content-Type", "application/json")
  841. resp, err := http.DefaultClient.Do(req)
  842. if err != nil {
  843. return nil, fmt.Errorf("do encode request: %w", err)
  844. }
  845. defer resp.Body.Close()
  846. body, err := io.ReadAll(resp.Body)
  847. if err != nil {
  848. return nil, fmt.Errorf("read encode request: %w", err)
  849. }
  850. if resp.StatusCode >= 400 {
  851. log.Printf("llm encode error: %s", body)
  852. return nil, fmt.Errorf("%s", body)
  853. }
  854. var encoded TokenizeResponse
  855. if err := json.Unmarshal(body, &encoded); err != nil {
  856. return nil, fmt.Errorf("unmarshal encode response: %w", err)
  857. }
  858. return encoded.Tokens, nil
  859. }
  860. type DetokenizeRequest struct {
  861. Tokens []int `json:"tokens"`
  862. }
  863. type DetokenizeResponse struct {
  864. Content string `json:"content"`
  865. }
  866. func (s *llmServer) Detokenize(ctx context.Context, tokens []int) (string, error) {
  867. // Make sure the server is ready
  868. status, err := s.getServerStatus(ctx)
  869. if err != nil {
  870. return "", err
  871. } else if status != ServerStatusReady && status != ServerStatusNoSlotsAvailable {
  872. return "", fmt.Errorf("unexpected server status: %s", status.ToString())
  873. }
  874. data, err := json.Marshal(DetokenizeRequest{Tokens: tokens})
  875. if err != nil {
  876. return "", fmt.Errorf("marshaling decode data: %w", err)
  877. }
  878. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/detokenize", s.port), bytes.NewBuffer(data))
  879. if err != nil {
  880. return "", fmt.Errorf("decode request: %w", err)
  881. }
  882. req.Header.Set("Content-Type", "application/json")
  883. resp, err := http.DefaultClient.Do(req)
  884. if err != nil {
  885. return "", fmt.Errorf("do decode request: %w", err)
  886. }
  887. defer resp.Body.Close()
  888. body, err := io.ReadAll(resp.Body)
  889. if err != nil {
  890. return "", fmt.Errorf("read decode request: %w", err)
  891. }
  892. if resp.StatusCode >= 400 {
  893. log.Printf("llm decode error: %s", body)
  894. return "", fmt.Errorf("%s", body)
  895. }
  896. var decoded DetokenizeResponse
  897. if err := json.Unmarshal(body, &decoded); err != nil {
  898. return "", fmt.Errorf("unmarshal encode response: %w", err)
  899. }
  900. return decoded.Content, nil
  901. }
  902. func (s *llmServer) Close() error {
  903. if s.cmd != nil {
  904. slog.Debug("stopping llama server")
  905. if err := s.cmd.Process.Kill(); err != nil {
  906. return err
  907. }
  908. // if ProcessState is already populated, Wait already completed, no need to wait again
  909. if s.cmd.ProcessState == nil {
  910. slog.Debug("waiting for llama server to exit")
  911. <-s.done
  912. }
  913. slog.Debug("llama server stopped")
  914. }
  915. return nil
  916. }
  917. func (s *llmServer) EstimatedVRAM() uint64 {
  918. return s.estimate.VRAMSize
  919. }
  920. func (s *llmServer) EstimatedTotal() uint64 {
  921. return s.estimate.TotalSize
  922. }
  923. func (s *llmServer) EstimatedVRAMByGPU(gpuID string) uint64 {
  924. for i, gpu := range s.gpus {
  925. if gpu.ID == gpuID {
  926. return s.estimate.GPUSizes[i]
  927. }
  928. }
  929. return 0
  930. }
  931. func parseDurationMs(ms float64) time.Duration {
  932. dur, err := time.ParseDuration(fmt.Sprintf("%fms", ms))
  933. if err != nil {
  934. panic(err)
  935. }
  936. return dur
  937. }