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. 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 gpu.IsNUMA() {
  224. numaMode := "distribute"
  225. if runtime.GOOS == "linux" {
  226. if _, err := exec.LookPath("numactl"); err == nil {
  227. numaMode = "numactl"
  228. }
  229. }
  230. params = append(params, "--numa", numaMode)
  231. }
  232. params = append(params, "--parallel", strconv.Itoa(numParallel))
  233. if estimate.TensorSplit != "" {
  234. params = append(params, "--tensor-split", estimate.TensorSplit)
  235. }
  236. for i := range len(servers) {
  237. dir := availableServers[servers[i]]
  238. if dir == "" {
  239. // Shouldn't happen
  240. finalErr = fmt.Errorf("[%d] server %s not listed in available servers %v", i, servers[i], availableServers)
  241. slog.Error("server list inconsistent", "error", finalErr)
  242. continue
  243. }
  244. if strings.HasPrefix(servers[i], "cpu") {
  245. gpus = gpu.GetCPUInfo()
  246. }
  247. // Find an availableServers port, retry on each iteration in case the failure was a port conflict race
  248. port := 0
  249. if a, err := net.ResolveTCPAddr("tcp", "localhost:0"); err == nil {
  250. var l *net.TCPListener
  251. if l, err = net.ListenTCP("tcp", a); err == nil {
  252. port = l.Addr().(*net.TCPAddr).Port
  253. l.Close()
  254. }
  255. }
  256. if port == 0 {
  257. slog.Debug("ResolveTCPAddr failed ", "error", err)
  258. port = rand.Intn(65535-49152) + 49152 // get a random port in the ephemeral range
  259. }
  260. finalParams := append(params, "--port", strconv.Itoa(port))
  261. pathEnv := "LD_LIBRARY_PATH"
  262. if runtime.GOOS == "windows" {
  263. pathEnv = "PATH"
  264. }
  265. // prepend the server directory to LD_LIBRARY_PATH/PATH and the parent dir for common dependencies
  266. libraryPaths := []string{dir, filepath.Dir(dir)}
  267. if libraryPath, ok := os.LookupEnv(pathEnv); ok {
  268. // Append our runner directory to the path
  269. // This will favor system libraries over our bundled library dependencies
  270. libraryPaths = append(libraryPaths, filepath.SplitList(libraryPath)...)
  271. }
  272. // Note: we always put the dependency path first
  273. // since this was the exact version we verified for AMD GPUs
  274. // and we favor what the user had in their path
  275. if gpus[0].DependencyPath != "" {
  276. // TODO refine for multi-gpu support
  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. sem: semaphore.NewWeighted(int64(numParallel)),
  300. totalLayers: ggml.KV().BlockCount() + 1,
  301. gpus: gpus,
  302. done: make(chan error, 1),
  303. }
  304. s.cmd.Env = os.Environ()
  305. s.cmd.Stdout = os.Stdout
  306. s.cmd.Stderr = s.status
  307. s.cmd.SysProcAttr = LlamaServerSysProcAttr
  308. envWorkarounds := [][2]string{}
  309. for _, gpu := range gpus {
  310. envWorkarounds = append(envWorkarounds, gpu.EnvWorkarounds...)
  311. }
  312. visibleDevicesEnv, visibleDevicesEnvVal := gpus.GetVisibleDevicesEnv()
  313. pathEnvVal := strings.Join(libraryPaths, string(filepath.ListSeparator))
  314. // Update or add the path and visible devices variable with our adjusted version
  315. pathNeeded := true
  316. devicesNeeded := visibleDevicesEnv != ""
  317. for i := range s.cmd.Env {
  318. cmp := strings.SplitN(s.cmd.Env[i], "=", 2)
  319. if strings.EqualFold(cmp[0], pathEnv) {
  320. s.cmd.Env[i] = pathEnv + "=" + pathEnvVal
  321. pathNeeded = false
  322. } else if devicesNeeded && strings.EqualFold(cmp[0], visibleDevicesEnv) {
  323. s.cmd.Env[i] = visibleDevicesEnv + "=" + visibleDevicesEnvVal
  324. devicesNeeded = false
  325. } else if len(envWorkarounds) != 0 {
  326. for _, kv := range envWorkarounds {
  327. if strings.EqualFold(cmp[0], kv[0]) {
  328. s.cmd.Env[i] = kv[0] + "=" + kv[1]
  329. }
  330. }
  331. }
  332. }
  333. if pathNeeded {
  334. s.cmd.Env = append(s.cmd.Env, pathEnv+"="+pathEnvVal)
  335. }
  336. if devicesNeeded {
  337. s.cmd.Env = append(s.cmd.Env, visibleDevicesEnv+"="+visibleDevicesEnvVal)
  338. }
  339. slog.Info("starting llama server", "cmd", s.cmd.String())
  340. if envconfig.Debug() {
  341. filteredEnv := []string{}
  342. for _, ev := range s.cmd.Env {
  343. if strings.HasPrefix(ev, "CUDA_") ||
  344. strings.HasPrefix(ev, "ROCR_") ||
  345. strings.HasPrefix(ev, "ROCM_") ||
  346. strings.HasPrefix(ev, "HIP_") ||
  347. strings.HasPrefix(ev, "GPU_") ||
  348. strings.HasPrefix(ev, "HSA_") ||
  349. strings.HasPrefix(ev, "GGML_") ||
  350. strings.HasPrefix(ev, "PATH=") ||
  351. strings.HasPrefix(ev, "LD_LIBRARY_PATH=") {
  352. filteredEnv = append(filteredEnv, ev)
  353. }
  354. }
  355. // Log at debug as the environment is inherited and might contain sensitive information
  356. slog.Debug("subprocess", "environment", filteredEnv)
  357. }
  358. if err = s.cmd.Start(); err != nil {
  359. // Detect permission denied and augment them essage about noexec
  360. if errors.Is(err, os.ErrPermission) {
  361. 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)
  362. continue
  363. }
  364. msg := ""
  365. if s.status != nil && s.status.LastErrMsg != "" {
  366. msg = s.status.LastErrMsg
  367. }
  368. err = fmt.Errorf("error starting the external llama server: %v %s", err, msg)
  369. finalErr = err
  370. continue
  371. }
  372. // reap subprocess when it exits
  373. go func() {
  374. err := s.cmd.Wait()
  375. // Favor a more detailed message over the process exit status
  376. if err != nil && s.status != nil && s.status.LastErrMsg != "" {
  377. slog.Debug("llama runner terminated", "error", err)
  378. if strings.Contains(s.status.LastErrMsg, "unknown model") {
  379. s.status.LastErrMsg = "this model is not supported by your version of Ollama. You may need to upgrade"
  380. }
  381. s.done <- errors.New(s.status.LastErrMsg)
  382. } else {
  383. s.done <- err
  384. }
  385. }()
  386. return s, nil
  387. }
  388. slog.Error("unable to load any llama server", "error", finalErr)
  389. return nil, finalErr
  390. }
  391. func projectorMemoryRequirements(filename string) uint64 {
  392. file, err := os.Open(filename)
  393. if err != nil {
  394. return 0
  395. }
  396. defer file.Close()
  397. ggml, _, err := DecodeGGML(file, 0)
  398. if err != nil {
  399. return 0
  400. }
  401. var mem uint64
  402. for _, layer := range ggml.Tensors().Layers() {
  403. mem += layer.size()
  404. }
  405. return mem
  406. }
  407. type ServerStatus int
  408. const ( // iota is reset to 0
  409. ServerStatusReady ServerStatus = iota
  410. ServerStatusNoSlotsAvailable
  411. ServerStatusLoadingModel
  412. ServerStatusNotResponding
  413. ServerStatusError
  414. )
  415. func (s ServerStatus) ToString() string {
  416. switch s {
  417. case ServerStatusReady:
  418. return "llm server ready"
  419. case ServerStatusNoSlotsAvailable:
  420. return "llm busy - no slots available"
  421. case ServerStatusLoadingModel:
  422. return "llm server loading model"
  423. case ServerStatusNotResponding:
  424. return "llm server not responding"
  425. default:
  426. return "llm server error"
  427. }
  428. }
  429. type ServerStatusResp struct {
  430. Status string `json:"status"`
  431. SlotsIdle int `json:"slots_idle"`
  432. SlotsProcessing int `json:"slots_processing"`
  433. Error string `json:"error"`
  434. Progress float32 `json:"progress"`
  435. }
  436. func (s *llmServer) getServerStatus(ctx context.Context) (ServerStatus, error) {
  437. // Fail fast if its exited
  438. if s.cmd.ProcessState != nil {
  439. msg := ""
  440. if s.status != nil && s.status.LastErrMsg != "" {
  441. msg = s.status.LastErrMsg
  442. }
  443. if s.cmd.ProcessState.ExitCode() == -1 {
  444. // Most likely a signal killed it, log some more details to try to help troubleshoot
  445. slog.Warn("llama runner process no longer running", "sys", s.cmd.ProcessState.Sys(), "string", s.cmd.ProcessState.String())
  446. }
  447. return ServerStatusError, fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
  448. }
  449. req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/health", s.port), nil)
  450. if err != nil {
  451. return ServerStatusError, fmt.Errorf("error creating GET request: %v", err)
  452. }
  453. req.Header.Set("Content-Type", "application/json")
  454. resp, err := http.DefaultClient.Do(req)
  455. if err != nil {
  456. if errors.Is(err, context.DeadlineExceeded) {
  457. return ServerStatusNotResponding, errors.New("server not responding")
  458. }
  459. return ServerStatusError, fmt.Errorf("health resp: %w", err)
  460. }
  461. defer resp.Body.Close()
  462. body, err := io.ReadAll(resp.Body)
  463. if err != nil {
  464. return ServerStatusError, fmt.Errorf("read health request: %w", err)
  465. }
  466. var status ServerStatusResp
  467. if err := json.Unmarshal(body, &status); err != nil {
  468. return ServerStatusError, fmt.Errorf("health unmarshal encode response: %w", err)
  469. }
  470. switch status.Status {
  471. case "ok":
  472. return ServerStatusReady, nil
  473. case "no slot available":
  474. return ServerStatusNoSlotsAvailable, nil
  475. case "loading model":
  476. s.loadProgress = status.Progress
  477. return ServerStatusLoadingModel, nil
  478. default:
  479. return ServerStatusError, fmt.Errorf("server error: %+v", status)
  480. }
  481. }
  482. // getServerStatusRetry will retry if ServerStatusNoSlotsAvailable is received
  483. func (s *llmServer) getServerStatusRetry(ctx context.Context) (ServerStatus, error) {
  484. var retries int
  485. for {
  486. status, err := s.getServerStatus(ctx)
  487. if err != nil {
  488. return status, err
  489. }
  490. if status == ServerStatusNoSlotsAvailable {
  491. if retries >= 10 {
  492. return status, fmt.Errorf("no slots available after %d retries", retries)
  493. }
  494. time.Sleep(5 * time.Millisecond)
  495. retries++
  496. continue
  497. }
  498. return status, nil
  499. }
  500. }
  501. func (s *llmServer) Ping(ctx context.Context) error {
  502. _, err := s.getServerStatus(ctx)
  503. if err != nil {
  504. slog.Debug("server unhealthy", "error", err)
  505. return err
  506. }
  507. return nil
  508. }
  509. func (s *llmServer) WaitUntilRunning(ctx context.Context) error {
  510. start := time.Now()
  511. stallDuration := 5 * time.Minute // If no progress happens
  512. finalLoadDuration := 5 * time.Minute // After we hit 100%, give the runner more time to come online
  513. stallTimer := time.Now().Add(stallDuration) // give up if we stall
  514. slog.Info("waiting for llama runner to start responding")
  515. var lastStatus ServerStatus = -1
  516. fullyLoaded := false
  517. for {
  518. select {
  519. case <-ctx.Done():
  520. slog.Warn("client connection closed before server finished loading, aborting load")
  521. return fmt.Errorf("timed out waiting for llama runner to start: %w", ctx.Err())
  522. case err := <-s.done:
  523. return fmt.Errorf("llama runner process has terminated: %w", err)
  524. default:
  525. }
  526. if time.Now().After(stallTimer) {
  527. // timeout
  528. msg := ""
  529. if s.status != nil && s.status.LastErrMsg != "" {
  530. msg = s.status.LastErrMsg
  531. }
  532. return fmt.Errorf("timed out waiting for llama runner to start - progress %0.2f - %s", s.loadProgress, msg)
  533. }
  534. if s.cmd.ProcessState != nil {
  535. msg := ""
  536. if s.status != nil && s.status.LastErrMsg != "" {
  537. msg = s.status.LastErrMsg
  538. }
  539. return fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
  540. }
  541. ctx, cancel := context.WithTimeout(ctx, 200*time.Millisecond)
  542. defer cancel()
  543. priorProgress := s.loadProgress
  544. status, _ := s.getServerStatus(ctx)
  545. if lastStatus != status && status != ServerStatusReady {
  546. // Only log on status changes
  547. slog.Info("waiting for server to become available", "status", status.ToString())
  548. }
  549. switch status {
  550. case ServerStatusReady:
  551. s.loadDuration = time.Since(start)
  552. slog.Info(fmt.Sprintf("llama runner started in %0.2f seconds", s.loadDuration.Seconds()))
  553. return nil
  554. default:
  555. lastStatus = status
  556. // Reset the timer as long as we're making forward progress on the load
  557. if priorProgress != s.loadProgress {
  558. slog.Debug(fmt.Sprintf("model load progress %0.2f", s.loadProgress))
  559. stallTimer = time.Now().Add(stallDuration)
  560. } else if !fullyLoaded && int(s.loadProgress*100.0) >= 100 {
  561. slog.Debug("model load completed, waiting for server to become available", "status", status.ToString())
  562. stallTimer = time.Now().Add(finalLoadDuration)
  563. fullyLoaded = true
  564. }
  565. time.Sleep(time.Millisecond * 250)
  566. continue
  567. }
  568. }
  569. }
  570. const jsonGrammar = `
  571. root ::= object
  572. value ::= object | array | string | number | ("true" | "false" | "null") ws
  573. object ::=
  574. "{" ws (
  575. string ":" ws value
  576. ("," ws string ":" ws value)*
  577. )? "}" ws
  578. array ::=
  579. "[" ws (
  580. value
  581. ("," ws value)*
  582. )? "]" ws
  583. string ::=
  584. "\"" (
  585. [^"\\\x7F\x00-\x1F] |
  586. "\\" (["\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) # escapes
  587. )* "\"" ws
  588. number ::= ("-"? ([0-9] | [1-9] [0-9]*)) ("." [0-9]+)? ([eE] [-+]? [0-9]+)? ws
  589. # Optional space: by convention, applied in this grammar after literal chars when allowed
  590. ws ::= ([ \t\n] ws)?
  591. `
  592. const maxBufferSize = 512 * format.KiloByte
  593. type ImageData struct {
  594. Data []byte `json:"data"`
  595. ID int `json:"id"`
  596. }
  597. type completion struct {
  598. Content string `json:"content"`
  599. Model string `json:"model"`
  600. Prompt string `json:"prompt"`
  601. Stop bool `json:"stop"`
  602. StoppedLimit bool `json:"stopped_limit"`
  603. Timings struct {
  604. PredictedN int `json:"predicted_n"`
  605. PredictedMS float64 `json:"predicted_ms"`
  606. PromptN int `json:"prompt_n"`
  607. PromptMS float64 `json:"prompt_ms"`
  608. }
  609. }
  610. type CompletionRequest struct {
  611. Prompt string
  612. Format string
  613. Images []ImageData
  614. Options *api.Options
  615. }
  616. type CompletionResponse struct {
  617. Content string
  618. DoneReason string
  619. Done bool
  620. PromptEvalCount int
  621. PromptEvalDuration time.Duration
  622. EvalCount int
  623. EvalDuration time.Duration
  624. }
  625. func (s *llmServer) Completion(ctx context.Context, req CompletionRequest, fn func(CompletionResponse)) error {
  626. if err := s.sem.Acquire(ctx, 1); err != nil {
  627. slog.Error("Failed to acquire semaphore", "error", err)
  628. return err
  629. }
  630. defer s.sem.Release(1)
  631. // put an upper limit on num_predict to avoid the model running on forever
  632. if req.Options.NumPredict < 0 || req.Options.NumPredict > 10*s.options.NumCtx {
  633. req.Options.NumPredict = 10 * s.options.NumCtx
  634. }
  635. request := map[string]any{
  636. "prompt": req.Prompt,
  637. "stream": true,
  638. "n_predict": req.Options.NumPredict,
  639. "n_keep": req.Options.NumKeep,
  640. "main_gpu": req.Options.MainGPU,
  641. "temperature": req.Options.Temperature,
  642. "top_k": req.Options.TopK,
  643. "top_p": req.Options.TopP,
  644. "min_p": req.Options.MinP,
  645. "tfs_z": req.Options.TFSZ,
  646. "typical_p": req.Options.TypicalP,
  647. "repeat_last_n": req.Options.RepeatLastN,
  648. "repeat_penalty": req.Options.RepeatPenalty,
  649. "presence_penalty": req.Options.PresencePenalty,
  650. "frequency_penalty": req.Options.FrequencyPenalty,
  651. "mirostat": req.Options.Mirostat,
  652. "mirostat_tau": req.Options.MirostatTau,
  653. "mirostat_eta": req.Options.MirostatEta,
  654. "penalize_nl": req.Options.PenalizeNewline,
  655. "seed": req.Options.Seed,
  656. "stop": req.Options.Stop,
  657. "image_data": req.Images,
  658. "cache_prompt": true,
  659. }
  660. // Make sure the server is ready
  661. status, err := s.getServerStatusRetry(ctx)
  662. if err != nil {
  663. return err
  664. } else if status != ServerStatusReady {
  665. return fmt.Errorf("unexpected server status: %s", status.ToString())
  666. }
  667. if req.Format == "json" {
  668. request["grammar"] = jsonGrammar
  669. if !strings.Contains(strings.ToLower(req.Prompt), "json") {
  670. 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.")
  671. }
  672. }
  673. // Handling JSON marshaling with special characters unescaped.
  674. buffer := &bytes.Buffer{}
  675. enc := json.NewEncoder(buffer)
  676. enc.SetEscapeHTML(false)
  677. if err := enc.Encode(request); err != nil {
  678. return fmt.Errorf("failed to marshal data: %v", err)
  679. }
  680. endpoint := fmt.Sprintf("http://127.0.0.1:%d/completion", s.port)
  681. serverReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, buffer)
  682. if err != nil {
  683. return fmt.Errorf("error creating POST request: %v", err)
  684. }
  685. serverReq.Header.Set("Content-Type", "application/json")
  686. res, err := http.DefaultClient.Do(serverReq)
  687. if err != nil {
  688. return fmt.Errorf("POST predict: %v", err)
  689. }
  690. defer res.Body.Close()
  691. if res.StatusCode >= 400 {
  692. bodyBytes, err := io.ReadAll(res.Body)
  693. if err != nil {
  694. return fmt.Errorf("failed reading llm error response: %w", err)
  695. }
  696. log.Printf("llm predict error: %s", bodyBytes)
  697. return fmt.Errorf("%s", bodyBytes)
  698. }
  699. scanner := bufio.NewScanner(res.Body)
  700. buf := make([]byte, 0, maxBufferSize)
  701. scanner.Buffer(buf, maxBufferSize)
  702. // keep track of the last token generated, this is used to abort if the model starts looping
  703. var lastToken string
  704. var tokenRepeat int
  705. for scanner.Scan() {
  706. select {
  707. case <-ctx.Done():
  708. // This handles the request cancellation
  709. return ctx.Err()
  710. default:
  711. line := scanner.Bytes()
  712. if len(line) == 0 {
  713. continue
  714. }
  715. evt, ok := bytes.CutPrefix(line, []byte("data: "))
  716. if !ok {
  717. return fmt.Errorf("error parsing llm response stream: %s", line)
  718. }
  719. var c completion
  720. if err := json.Unmarshal(evt, &c); err != nil {
  721. return fmt.Errorf("error unmarshalling llm prediction response: %v", err)
  722. }
  723. switch {
  724. case strings.TrimSpace(c.Content) == lastToken:
  725. tokenRepeat++
  726. default:
  727. lastToken = strings.TrimSpace(c.Content)
  728. tokenRepeat = 0
  729. }
  730. // 30 picked as an arbitrary max token repeat limit, modify as needed
  731. if tokenRepeat > 30 {
  732. slog.Debug("prediction aborted, token repeat limit reached")
  733. return ctx.Err()
  734. }
  735. if c.Content != "" {
  736. fn(CompletionResponse{
  737. Content: c.Content,
  738. })
  739. }
  740. if c.Stop {
  741. doneReason := "stop"
  742. if c.StoppedLimit {
  743. doneReason = "length"
  744. }
  745. fn(CompletionResponse{
  746. Done: true,
  747. DoneReason: doneReason,
  748. PromptEvalCount: c.Timings.PromptN,
  749. PromptEvalDuration: parseDurationMs(c.Timings.PromptMS),
  750. EvalCount: c.Timings.PredictedN,
  751. EvalDuration: parseDurationMs(c.Timings.PredictedMS),
  752. })
  753. return nil
  754. }
  755. }
  756. }
  757. if err := scanner.Err(); err != nil {
  758. if strings.Contains(err.Error(), "unexpected EOF") {
  759. s.Close()
  760. msg := ""
  761. if s.status != nil && s.status.LastErrMsg != "" {
  762. msg = s.status.LastErrMsg
  763. }
  764. return fmt.Errorf("an unknown error was encountered while running the model %s", msg)
  765. }
  766. return fmt.Errorf("error reading llm response: %v", err)
  767. }
  768. return nil
  769. }
  770. type EmbedRequest struct {
  771. Content []string `json:"content"`
  772. }
  773. type EmbedResponse struct {
  774. Embedding [][]float32 `json:"embedding"`
  775. PromptEvalCount int `json:"prompt_n"`
  776. }
  777. func (s *llmServer) Embed(ctx context.Context, input []string) (*EmbedResponse, 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(EmbedRequest{Content: input})
  791. if err != nil {
  792. return nil, fmt.Errorf("error marshaling embed data: %w", err)
  793. }
  794. req, 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. req.Header.Set("Content-Type", "application/json")
  799. resp, err := http.DefaultClient.Do(req)
  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 EmbedResponse
  813. if err := json.Unmarshal(body, &e); err != nil {
  814. return nil, fmt.Errorf("unmarshal tokenize response: %w", err)
  815. }
  816. return &e, 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. }