server.go 33 KB

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