server.go 31 KB

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