server.go 31 KB

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