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