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