server.go 32 KB

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