server.go 31 KB

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