server.go 32 KB

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