server.go 32 KB

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