server.go 31 KB

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