server.go 31 KB

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