server.go 32 KB

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