server.go 30 KB

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