server.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  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/build"
  26. "github.com/ollama/ollama/discover"
  27. "github.com/ollama/ollama/envconfig"
  28. "github.com/ollama/ollama/format"
  29. "github.com/ollama/ollama/llama"
  30. "github.com/ollama/ollama/runners"
  31. )
  32. type LlamaServer interface {
  33. Ping(ctx context.Context) error
  34. WaitUntilRunning(ctx context.Context) error
  35. Completion(ctx context.Context, req CompletionRequest, fn func(CompletionResponse)) error
  36. Embedding(ctx context.Context, input string) ([]float32, error)
  37. Tokenize(ctx context.Context, content string) ([]int, error)
  38. Detokenize(ctx context.Context, tokens []int) (string, error)
  39. Close() error
  40. EstimatedVRAM() uint64 // Total VRAM across all GPUs
  41. EstimatedTotal() uint64
  42. EstimatedVRAMByGPU(gpuID string) uint64
  43. }
  44. // llmServer is an instance of the llama.cpp server
  45. type llmServer struct {
  46. port int
  47. cmd *exec.Cmd
  48. done chan error // Channel to signal when the process exits
  49. status *StatusWriter
  50. options api.Options
  51. numParallel int
  52. modelPath string
  53. modelLock sync.Mutex // Temporary until we switch fully to Go server
  54. model *llama.Model // If non-nil, the runner is a new Go server
  55. estimate MemoryEstimate
  56. totalLayers uint64
  57. // gpuCount int
  58. gpus discover.GpuInfoList // Recorded just before the model loaded, free space will be incorrect
  59. loadDuration time.Duration // Record how long it took the model to load
  60. loadProgress float32
  61. sem *semaphore.Weighted
  62. }
  63. // LoadModel will load a model from disk. The model must be in the GGML format.
  64. //
  65. // It collects array values for arrays with a size less than or equal to
  66. // maxArraySize. If maxArraySize is 0, the default value of 1024 is used. If
  67. // the maxArraySize is negative, all arrays are collected.
  68. func LoadModel(model string, maxArraySize int) (*GGML, error) {
  69. if _, err := os.Stat(model); err != nil {
  70. return nil, err
  71. }
  72. f, err := os.Open(model)
  73. if err != nil {
  74. return nil, err
  75. }
  76. defer f.Close()
  77. ggml, _, err := DecodeGGML(f, maxArraySize)
  78. return ggml, err
  79. }
  80. // NewLlamaServer will run a server for the given GPUs
  81. // The gpu list must be a single family.
  82. func NewLlamaServer(gpus discover.GpuInfoList, model string, ggml *GGML, adapters, projectors []string, opts api.Options, numParallel int) (LlamaServer, error) {
  83. var err error
  84. var cpuRunner string
  85. var estimate MemoryEstimate
  86. var systemTotalMemory uint64
  87. var systemFreeMemory uint64
  88. var systemSwapFreeMemory uint64
  89. systemInfo := discover.GetSystemInfo()
  90. systemTotalMemory = systemInfo.System.TotalMemory
  91. systemFreeMemory = systemInfo.System.FreeMemory
  92. systemSwapFreeMemory = systemInfo.System.FreeSwap
  93. slog.Info("system memory", "total", format.HumanBytes2(systemTotalMemory), "free", format.HumanBytes2(systemFreeMemory), "free_swap", format.HumanBytes2(systemSwapFreeMemory))
  94. // If the user wants zero GPU layers, reset the gpu list to be CPU/system ram info
  95. if opts.NumGPU == 0 {
  96. gpus = discover.GetCPUInfo()
  97. }
  98. if len(gpus) == 1 && gpus[0].Library == "cpu" {
  99. cpuRunner = runners.ServerForCpu()
  100. estimate = EstimateGPULayers(gpus, ggml, projectors, opts)
  101. } else {
  102. estimate = EstimateGPULayers(gpus, ggml, projectors, opts)
  103. switch {
  104. case gpus[0].Library == "metal" && estimate.VRAMSize > systemTotalMemory:
  105. // disable partial offloading when model is greater than total system memory as this
  106. // can lead to locking up the system
  107. opts.NumGPU = 0
  108. case gpus[0].Library != "metal" && estimate.Layers == 0:
  109. // Don't bother loading into the GPU if no layers can fit
  110. cpuRunner = runners.ServerForCpu()
  111. gpus = discover.GetCPUInfo()
  112. case opts.NumGPU < 0 && estimate.Layers > 0 && gpus[0].Library != "cpu":
  113. opts.NumGPU = estimate.Layers
  114. }
  115. }
  116. // On linux and windows, over-allocating CPU memory will almost always result in an error
  117. // Darwin has fully dynamic swap so has no direct concept of free swap space
  118. if runtime.GOOS != "darwin" {
  119. systemMemoryRequired := estimate.TotalSize - estimate.VRAMSize
  120. available := systemFreeMemory + systemSwapFreeMemory
  121. if systemMemoryRequired > available {
  122. 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))
  123. return nil, fmt.Errorf("model requires more system memory (%s) than is available (%s)", format.HumanBytes2(systemMemoryRequired), format.HumanBytes2(available))
  124. }
  125. }
  126. estimate.log()
  127. // Loop through potential servers
  128. finalErr := errors.New("no suitable llama servers found")
  129. rDir, err := runners.Refresh(build.EmbedFS)
  130. if err != nil {
  131. return nil, err
  132. }
  133. availableServers := runners.GetAvailableServers(rDir)
  134. if len(availableServers) == 0 {
  135. return nil, finalErr
  136. }
  137. var servers []string
  138. if cpuRunner != "" {
  139. servers = []string{cpuRunner}
  140. } else {
  141. servers = runners.ServersForGpu(gpus[0]) // All GPUs in the list are matching Library and Variant
  142. }
  143. demandLib := envconfig.LLMLibrary()
  144. if demandLib != "" {
  145. serverPath := availableServers[demandLib]
  146. if serverPath == "" {
  147. slog.Info(fmt.Sprintf("Invalid OLLAMA_LLM_LIBRARY %s - not found", demandLib))
  148. } else {
  149. slog.Info("user override", "OLLAMA_LLM_LIBRARY", demandLib, "path", serverPath)
  150. servers = []string{demandLib}
  151. if strings.HasPrefix(demandLib, "cpu") {
  152. // Omit the GPU flag to silence the warning
  153. opts.NumGPU = -1
  154. }
  155. }
  156. }
  157. if len(servers) == 0 {
  158. return nil, fmt.Errorf("no servers found for %v", gpus)
  159. }
  160. params := []string{
  161. "--model", model,
  162. "--ctx-size", strconv.Itoa(opts.NumCtx),
  163. "--batch-size", strconv.Itoa(opts.NumBatch),
  164. }
  165. if opts.NumGPU >= 0 {
  166. params = append(params, "--n-gpu-layers", strconv.Itoa(opts.NumGPU))
  167. }
  168. if envconfig.Debug() {
  169. params = append(params, "--verbose")
  170. }
  171. if opts.MainGPU > 0 {
  172. params = append(params, "--main-gpu", strconv.Itoa(opts.MainGPU))
  173. }
  174. if len(adapters) > 0 {
  175. for _, adapter := range adapters {
  176. params = append(params, "--lora", adapter)
  177. }
  178. }
  179. if len(projectors) > 0 {
  180. // TODO: applying multiple projectors is not supported by the llama.cpp server yet
  181. params = append(params, "--mmproj", projectors[0])
  182. }
  183. defaultThreads := systemInfo.GetOptimalThreadCount()
  184. if opts.NumThread > 0 {
  185. params = append(params, "--threads", strconv.Itoa(opts.NumThread))
  186. } else if defaultThreads > 0 {
  187. params = append(params, "--threads", strconv.Itoa(defaultThreads))
  188. }
  189. flashAttnEnabled := envconfig.FlashAttention()
  190. for _, g := range gpus {
  191. // only cuda (compute capability 7+) and metal support flash attention
  192. if g.Library != "metal" && (g.Library != "cuda" || g.DriverMajor < 7) {
  193. flashAttnEnabled = false
  194. }
  195. // mmap has issues with partial offloading on metal
  196. if g.Library == "metal" &&
  197. uint64(opts.NumGPU) > 0 &&
  198. uint64(opts.NumGPU) < ggml.KV().BlockCount()+1 {
  199. opts.UseMMap = new(bool)
  200. *opts.UseMMap = false
  201. }
  202. }
  203. if flashAttnEnabled {
  204. params = append(params, "--flash-attn")
  205. }
  206. // Windows CUDA should not use mmap for best performance
  207. // Linux with a model larger than free space, mmap leads to thrashing
  208. // For CPU loads we want the memory to be allocated, not FS cache
  209. if (runtime.GOOS == "windows" && gpus[0].Library == "cuda" && opts.UseMMap == nil) ||
  210. (runtime.GOOS == "linux" && systemFreeMemory < estimate.TotalSize && opts.UseMMap == nil) ||
  211. (gpus[0].Library == "cpu" && opts.UseMMap == nil) ||
  212. (opts.UseMMap != nil && !*opts.UseMMap) {
  213. params = append(params, "--no-mmap")
  214. }
  215. if opts.UseMLock {
  216. params = append(params, "--mlock")
  217. }
  218. // TODO - NUMA support currently doesn't work properly
  219. params = append(params, "--parallel", strconv.Itoa(numParallel))
  220. if estimate.TensorSplit != "" {
  221. params = append(params, "--tensor-split", estimate.TensorSplit)
  222. }
  223. if envconfig.MultiUserCache() {
  224. params = append(params, "--multiuser-cache")
  225. }
  226. for i := range servers {
  227. dir := availableServers[servers[i]]
  228. if dir == "" {
  229. // Shouldn't happen
  230. finalErr = fmt.Errorf("[%d] server %s not listed in available servers %v", i, servers[i], availableServers)
  231. slog.Error("server list inconsistent", "error", finalErr)
  232. continue
  233. }
  234. if strings.HasPrefix(servers[i], "cpu") {
  235. gpus = discover.GetCPUInfo()
  236. }
  237. // Find an availableServers port, retry on each iteration in case the failure was a port conflict race
  238. port := 0
  239. if a, err := net.ResolveTCPAddr("tcp", "localhost:0"); err == nil {
  240. var l *net.TCPListener
  241. if l, err = net.ListenTCP("tcp", a); err == nil {
  242. port = l.Addr().(*net.TCPAddr).Port
  243. l.Close()
  244. }
  245. }
  246. if port == 0 {
  247. slog.Debug("ResolveTCPAddr failed ", "error", err)
  248. port = rand.Intn(65535-49152) + 49152 // get a random port in the ephemeral range
  249. }
  250. finalParams := append(params, "--port", strconv.Itoa(port))
  251. pathEnv := "LD_LIBRARY_PATH"
  252. if runtime.GOOS == "windows" {
  253. pathEnv = "PATH"
  254. }
  255. // Start with the server directory for the LD_LIBRARY_PATH/PATH
  256. libraryPaths := []string{dir}
  257. if libraryPath, ok := os.LookupEnv(pathEnv); ok {
  258. // favor our bundled library dependencies over system libraries
  259. libraryPaths = append(libraryPaths, filepath.SplitList(libraryPath)...)
  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. // assume gpus from the same library have the same dependency path
  265. libraryPaths = append(gpus[0].DependencyPath, libraryPaths...)
  266. }
  267. server := filepath.Join(dir, "ollama_llama_server")
  268. if runtime.GOOS == "windows" {
  269. server += ".exe"
  270. }
  271. // Detect tmp cleaners wiping out the file
  272. _, err := os.Stat(server)
  273. if errors.Is(err, os.ErrNotExist) {
  274. slog.Warn("llama server disappeared, reinitializing payloads", "path", server, "error", err)
  275. _, err = runners.Refresh(build.EmbedFS)
  276. if err != nil {
  277. slog.Warn("failed to reinitialize payloads", "error", err)
  278. return nil, err
  279. }
  280. }
  281. // TODO - once fully switched to the Go runner, load the model here for tokenize/detokenize cgo access
  282. s := &llmServer{
  283. port: port,
  284. cmd: exec.Command(server, finalParams...),
  285. status: NewStatusWriter(os.Stderr),
  286. options: opts,
  287. modelPath: model,
  288. estimate: estimate,
  289. numParallel: numParallel,
  290. sem: semaphore.NewWeighted(int64(numParallel)),
  291. totalLayers: ggml.KV().BlockCount() + 1,
  292. gpus: gpus,
  293. done: make(chan error, 1),
  294. }
  295. s.cmd.Env = os.Environ()
  296. s.cmd.Stdout = os.Stdout
  297. s.cmd.Stderr = s.status
  298. s.cmd.SysProcAttr = LlamaServerSysProcAttr
  299. envWorkarounds := [][2]string{}
  300. for _, gpu := range gpus {
  301. envWorkarounds = append(envWorkarounds, gpu.EnvWorkarounds...)
  302. }
  303. visibleDevicesEnv, visibleDevicesEnvVal := gpus.GetVisibleDevicesEnv()
  304. pathEnvVal := strings.Join(libraryPaths, string(filepath.ListSeparator))
  305. // Update or add the path and visible devices variable with our adjusted version
  306. pathNeeded := true
  307. devicesNeeded := visibleDevicesEnv != ""
  308. for i := range s.cmd.Env {
  309. cmp := strings.SplitN(s.cmd.Env[i], "=", 2)
  310. if strings.EqualFold(cmp[0], pathEnv) {
  311. s.cmd.Env[i] = pathEnv + "=" + pathEnvVal
  312. pathNeeded = false
  313. } else if devicesNeeded && strings.EqualFold(cmp[0], visibleDevicesEnv) {
  314. s.cmd.Env[i] = visibleDevicesEnv + "=" + visibleDevicesEnvVal
  315. devicesNeeded = false
  316. } else if len(envWorkarounds) != 0 {
  317. for _, kv := range envWorkarounds {
  318. if strings.EqualFold(cmp[0], kv[0]) {
  319. s.cmd.Env[i] = kv[0] + "=" + kv[1]
  320. }
  321. }
  322. }
  323. }
  324. if pathNeeded {
  325. s.cmd.Env = append(s.cmd.Env, pathEnv+"="+pathEnvVal)
  326. }
  327. if devicesNeeded {
  328. s.cmd.Env = append(s.cmd.Env, visibleDevicesEnv+"="+visibleDevicesEnvVal)
  329. }
  330. slog.Info("starting llama server", "cmd", s.cmd.String())
  331. if envconfig.Debug() {
  332. filteredEnv := []string{}
  333. for _, ev := range s.cmd.Env {
  334. if strings.HasPrefix(ev, "CUDA_") ||
  335. strings.HasPrefix(ev, "ROCR_") ||
  336. strings.HasPrefix(ev, "ROCM_") ||
  337. strings.HasPrefix(ev, "HIP_") ||
  338. strings.HasPrefix(ev, "GPU_") ||
  339. strings.HasPrefix(ev, "HSA_") ||
  340. strings.HasPrefix(ev, "GGML_") ||
  341. strings.HasPrefix(ev, "PATH=") ||
  342. strings.HasPrefix(ev, "LD_LIBRARY_PATH=") {
  343. filteredEnv = append(filteredEnv, ev)
  344. }
  345. }
  346. // Log at debug as the environment is inherited and might contain sensitive information
  347. slog.Debug("subprocess", "environment", filteredEnv)
  348. }
  349. if err = s.cmd.Start(); err != nil {
  350. // Detect permission denied and augment the message about noexec
  351. if errors.Is(err, os.ErrPermission) {
  352. 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)
  353. continue
  354. }
  355. msg := ""
  356. if s.status != nil && s.status.LastErrMsg != "" {
  357. msg = s.status.LastErrMsg
  358. }
  359. err = fmt.Errorf("error starting the external llama server: %v %s", err, msg)
  360. finalErr = err
  361. continue
  362. }
  363. // reap subprocess when it exits
  364. go func() {
  365. err := s.cmd.Wait()
  366. // Favor a more detailed message over the process exit status
  367. if err != nil && s.status != nil && s.status.LastErrMsg != "" {
  368. slog.Debug("llama runner terminated", "error", err)
  369. if strings.Contains(s.status.LastErrMsg, "unknown model") {
  370. s.status.LastErrMsg = "this model is not supported by your version of Ollama. You may need to upgrade"
  371. }
  372. s.done <- errors.New(s.status.LastErrMsg)
  373. } else {
  374. s.done <- err
  375. }
  376. }()
  377. return s, nil
  378. }
  379. slog.Error("unable to load any llama server", "error", finalErr)
  380. return nil, finalErr
  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. const jsonGrammar = `
  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 string
  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. if err := s.sem.Acquire(ctx, 1); err != nil {
  602. if errors.Is(err, context.Canceled) {
  603. slog.Info("aborting completion request due to client closing the connection")
  604. } else {
  605. slog.Error("Failed to acquire semaphore", "error", err)
  606. }
  607. return err
  608. }
  609. defer s.sem.Release(1)
  610. // put an upper limit on num_predict to avoid the model running on forever
  611. if req.Options.NumPredict < 0 || req.Options.NumPredict > 10*s.options.NumCtx {
  612. req.Options.NumPredict = 10 * s.options.NumCtx
  613. }
  614. request := map[string]any{
  615. "prompt": req.Prompt,
  616. "stream": true,
  617. "n_predict": req.Options.NumPredict,
  618. "n_keep": req.Options.NumKeep,
  619. "main_gpu": req.Options.MainGPU,
  620. "temperature": req.Options.Temperature,
  621. "top_k": req.Options.TopK,
  622. "top_p": req.Options.TopP,
  623. "min_p": req.Options.MinP,
  624. "tfs_z": req.Options.TFSZ,
  625. "typical_p": req.Options.TypicalP,
  626. "repeat_last_n": req.Options.RepeatLastN,
  627. "repeat_penalty": req.Options.RepeatPenalty,
  628. "presence_penalty": req.Options.PresencePenalty,
  629. "frequency_penalty": req.Options.FrequencyPenalty,
  630. "mirostat": req.Options.Mirostat,
  631. "mirostat_tau": req.Options.MirostatTau,
  632. "mirostat_eta": req.Options.MirostatEta,
  633. "penalize_nl": req.Options.PenalizeNewline,
  634. "seed": req.Options.Seed,
  635. "stop": req.Options.Stop,
  636. "image_data": req.Images,
  637. "cache_prompt": true,
  638. }
  639. // Make sure the server is ready
  640. status, err := s.getServerStatusRetry(ctx)
  641. if err != nil {
  642. return err
  643. } else if status != ServerStatusReady {
  644. return fmt.Errorf("unexpected server status: %s", status.ToString())
  645. }
  646. if req.Format == "json" {
  647. request["grammar"] = jsonGrammar
  648. if !strings.Contains(strings.ToLower(req.Prompt), "json") {
  649. 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.")
  650. }
  651. }
  652. // Handling JSON marshaling with special characters unescaped.
  653. buffer := &bytes.Buffer{}
  654. enc := json.NewEncoder(buffer)
  655. enc.SetEscapeHTML(false)
  656. if err := enc.Encode(request); err != nil {
  657. return fmt.Errorf("failed to marshal data: %v", err)
  658. }
  659. endpoint := fmt.Sprintf("http://127.0.0.1:%d/completion", s.port)
  660. serverReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, buffer)
  661. if err != nil {
  662. return fmt.Errorf("error creating POST request: %v", err)
  663. }
  664. serverReq.Header.Set("Content-Type", "application/json")
  665. res, err := http.DefaultClient.Do(serverReq)
  666. if err != nil {
  667. return fmt.Errorf("POST predict: %v", err)
  668. }
  669. defer res.Body.Close()
  670. if res.StatusCode >= 400 {
  671. bodyBytes, err := io.ReadAll(res.Body)
  672. if err != nil {
  673. return fmt.Errorf("failed reading llm error response: %w", err)
  674. }
  675. log.Printf("llm predict error: %s", bodyBytes)
  676. return fmt.Errorf("%s", bodyBytes)
  677. }
  678. scanner := bufio.NewScanner(res.Body)
  679. buf := make([]byte, 0, maxBufferSize)
  680. scanner.Buffer(buf, maxBufferSize)
  681. // keep track of the last token generated, this is used to abort if the model starts looping
  682. var lastToken string
  683. var tokenRepeat int
  684. for scanner.Scan() {
  685. select {
  686. case <-ctx.Done():
  687. // This handles the request cancellation
  688. return ctx.Err()
  689. default:
  690. line := scanner.Bytes()
  691. if len(line) == 0 {
  692. continue
  693. }
  694. // slog.Debug("got line", "line", string(line))
  695. evt, ok := bytes.CutPrefix(line, []byte("data: "))
  696. if !ok {
  697. evt = line
  698. }
  699. var c completion
  700. if err := json.Unmarshal(evt, &c); err != nil {
  701. return fmt.Errorf("error unmarshalling llm prediction response: %v", err)
  702. }
  703. switch {
  704. case strings.TrimSpace(c.Content) == lastToken:
  705. tokenRepeat++
  706. default:
  707. lastToken = strings.TrimSpace(c.Content)
  708. tokenRepeat = 0
  709. }
  710. // 30 picked as an arbitrary max token repeat limit, modify as needed
  711. if tokenRepeat > 30 {
  712. slog.Debug("prediction aborted, token repeat limit reached")
  713. return ctx.Err()
  714. }
  715. if c.Content != "" {
  716. fn(CompletionResponse{
  717. Content: c.Content,
  718. })
  719. }
  720. if c.Stop {
  721. doneReason := "stop"
  722. if c.StoppedLimit {
  723. doneReason = "length"
  724. }
  725. fn(CompletionResponse{
  726. Done: true,
  727. DoneReason: doneReason,
  728. PromptEvalCount: c.Timings.PromptN,
  729. PromptEvalDuration: parseDurationMs(c.Timings.PromptMS),
  730. EvalCount: c.Timings.PredictedN,
  731. EvalDuration: parseDurationMs(c.Timings.PredictedMS),
  732. })
  733. return nil
  734. }
  735. }
  736. }
  737. if err := scanner.Err(); err != nil {
  738. if strings.Contains(err.Error(), "unexpected EOF") || strings.Contains(err.Error(), "forcibly closed") {
  739. s.Close()
  740. var msg string
  741. if s.status != nil && s.status.LastErrMsg != "" {
  742. msg = s.status.LastErrMsg
  743. } else {
  744. msg = err.Error()
  745. }
  746. return fmt.Errorf("an error was encountered while running the model: %s", msg)
  747. }
  748. return fmt.Errorf("error reading llm response: %v", err)
  749. }
  750. return nil
  751. }
  752. type EmbeddingRequest struct {
  753. Content string `json:"content"`
  754. }
  755. type EmbeddingResponse struct {
  756. Embedding []float32 `json:"embedding"`
  757. }
  758. func (s *llmServer) Embedding(ctx context.Context, input string) ([]float32, error) {
  759. if err := s.sem.Acquire(ctx, 1); err != nil {
  760. if errors.Is(err, context.Canceled) {
  761. slog.Info("aborting embedding request due to client closing the connection")
  762. } else {
  763. slog.Error("Failed to acquire semaphore", "error", err)
  764. }
  765. return nil, err
  766. }
  767. defer s.sem.Release(1)
  768. // Make sure the server is ready
  769. status, err := s.getServerStatusRetry(ctx)
  770. if err != nil {
  771. return nil, err
  772. } else if status != ServerStatusReady {
  773. return nil, fmt.Errorf("unexpected server status: %s", status.ToString())
  774. }
  775. data, err := json.Marshal(EmbeddingRequest{Content: input})
  776. if err != nil {
  777. return nil, fmt.Errorf("error marshaling embed data: %w", err)
  778. }
  779. r, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/embedding", s.port), bytes.NewBuffer(data))
  780. if err != nil {
  781. return nil, fmt.Errorf("error creating embed request: %w", err)
  782. }
  783. r.Header.Set("Content-Type", "application/json")
  784. resp, err := http.DefaultClient.Do(r)
  785. if err != nil {
  786. return nil, fmt.Errorf("do embedding request: %w", err)
  787. }
  788. defer resp.Body.Close()
  789. body, err := io.ReadAll(resp.Body)
  790. if err != nil {
  791. return nil, fmt.Errorf("error reading embed response: %w", err)
  792. }
  793. if resp.StatusCode >= 400 {
  794. log.Printf("llm embedding error: %s", body)
  795. return nil, fmt.Errorf("%s", body)
  796. }
  797. var e EmbeddingResponse
  798. if err := json.Unmarshal(body, &e); err != nil {
  799. return nil, fmt.Errorf("unmarshal tokenize response: %w", err)
  800. }
  801. return e.Embedding, nil
  802. }
  803. type TokenizeRequest struct {
  804. Content string `json:"content"`
  805. }
  806. type TokenizeResponse struct {
  807. Tokens []int `json:"tokens"`
  808. }
  809. func (s *llmServer) Tokenize(ctx context.Context, content string) ([]int, error) {
  810. s.modelLock.Lock()
  811. defer s.modelLock.Unlock()
  812. if s.model != nil {
  813. return s.model.Tokenize(content, false, true)
  814. }
  815. // Make sure the server is ready
  816. status, err := s.getServerStatus(ctx)
  817. if err != nil {
  818. return nil, err
  819. } else if status != ServerStatusReady && status != ServerStatusNoSlotsAvailable {
  820. return nil, fmt.Errorf("unexpected server status: %s", status.ToString())
  821. }
  822. data, err := json.Marshal(TokenizeRequest{Content: content})
  823. if err != nil {
  824. return nil, fmt.Errorf("marshaling encode data: %w", err)
  825. }
  826. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/tokenize", s.port), bytes.NewBuffer(data))
  827. if err != nil {
  828. return nil, fmt.Errorf("encode request: %w", err)
  829. }
  830. req.Header.Set("Content-Type", "application/json")
  831. resp, err := http.DefaultClient.Do(req)
  832. if err != nil {
  833. return nil, fmt.Errorf("do encode request: %w", err)
  834. }
  835. defer resp.Body.Close()
  836. if resp.StatusCode == http.StatusNotFound {
  837. if s.model == nil {
  838. slog.Debug("new runner detected, loading model for cgo tokenization")
  839. m, err := llama.LoadModelFromFile(s.modelPath, llama.ModelParams{VocabOnly: true})
  840. if err != nil {
  841. return nil, err
  842. }
  843. s.model = m
  844. }
  845. return s.model.Tokenize(content, false, true)
  846. }
  847. body, err := io.ReadAll(resp.Body)
  848. if err != nil {
  849. return nil, fmt.Errorf("read encode request: %w", err)
  850. }
  851. if resp.StatusCode >= 400 {
  852. log.Printf("llm encode error: %s", body)
  853. return nil, fmt.Errorf("%s", body)
  854. }
  855. var encoded TokenizeResponse
  856. if err := json.Unmarshal(body, &encoded); err != nil {
  857. return nil, fmt.Errorf("unmarshal encode response: %w", err)
  858. }
  859. return encoded.Tokens, nil
  860. }
  861. type DetokenizeRequest struct {
  862. Tokens []int `json:"tokens"`
  863. }
  864. type DetokenizeResponse struct {
  865. Content string `json:"content"`
  866. }
  867. func (s *llmServer) Detokenize(ctx context.Context, tokens []int) (string, error) {
  868. s.modelLock.Lock()
  869. defer s.modelLock.Unlock()
  870. if s.model != nil {
  871. var resp string
  872. for _, token := range tokens {
  873. resp += s.model.TokenToPiece(token)
  874. }
  875. return resp, nil
  876. }
  877. // Make sure the server is ready
  878. status, err := s.getServerStatus(ctx)
  879. if err != nil {
  880. return "", err
  881. } else if status != ServerStatusReady && status != ServerStatusNoSlotsAvailable {
  882. return "", fmt.Errorf("unexpected server status: %s", status.ToString())
  883. }
  884. data, err := json.Marshal(DetokenizeRequest{Tokens: tokens})
  885. if err != nil {
  886. return "", fmt.Errorf("marshaling decode data: %w", err)
  887. }
  888. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/detokenize", s.port), bytes.NewBuffer(data))
  889. if err != nil {
  890. return "", fmt.Errorf("decode request: %w", err)
  891. }
  892. req.Header.Set("Content-Type", "application/json")
  893. resp, err := http.DefaultClient.Do(req)
  894. if err != nil {
  895. return "", fmt.Errorf("do decode request: %w", err)
  896. }
  897. defer resp.Body.Close()
  898. if resp.StatusCode == http.StatusNotFound {
  899. if s.model == nil {
  900. slog.Debug("new runner detected, loading model for cgo tokenization")
  901. m, err := llama.LoadModelFromFile(s.modelPath, llama.ModelParams{VocabOnly: true})
  902. if err != nil {
  903. return "", err
  904. }
  905. s.model = m
  906. }
  907. var resp string
  908. for _, token := range tokens {
  909. resp += s.model.TokenToPiece(token)
  910. }
  911. return resp, nil
  912. }
  913. body, err := io.ReadAll(resp.Body)
  914. if err != nil {
  915. return "", fmt.Errorf("read decode request: %w", err)
  916. }
  917. if resp.StatusCode >= 400 {
  918. log.Printf("llm decode error: %s", body)
  919. return "", fmt.Errorf("%s", body)
  920. }
  921. var decoded DetokenizeResponse
  922. if err := json.Unmarshal(body, &decoded); err != nil {
  923. return "", fmt.Errorf("unmarshal encode response: %w", err)
  924. }
  925. return decoded.Content, nil
  926. }
  927. func (s *llmServer) Close() error {
  928. s.modelLock.Lock()
  929. if s.model != nil {
  930. llama.FreeModel(s.model)
  931. s.model = nil
  932. }
  933. s.modelLock.Unlock()
  934. if s.cmd != nil {
  935. slog.Debug("stopping llama server")
  936. if err := s.cmd.Process.Kill(); err != nil {
  937. return err
  938. }
  939. // if ProcessState is already populated, Wait already completed, no need to wait again
  940. if s.cmd.ProcessState == nil {
  941. slog.Debug("waiting for llama server to exit")
  942. <-s.done
  943. }
  944. slog.Debug("llama server stopped")
  945. }
  946. return nil
  947. }
  948. func (s *llmServer) EstimatedVRAM() uint64 {
  949. return s.estimate.VRAMSize
  950. }
  951. func (s *llmServer) EstimatedTotal() uint64 {
  952. return s.estimate.TotalSize
  953. }
  954. func (s *llmServer) EstimatedVRAMByGPU(gpuID string) uint64 {
  955. for i, gpu := range s.gpus {
  956. if gpu.ID == gpuID {
  957. if i < len(s.estimate.GPUSizes) {
  958. return s.estimate.GPUSizes[i]
  959. }
  960. }
  961. }
  962. return 0
  963. }
  964. func parseDurationMs(ms float64) time.Duration {
  965. dur, err := time.ParseDuration(fmt.Sprintf("%fms", ms))
  966. if err != nil {
  967. panic(err)
  968. }
  969. return dur
  970. }