server.go 30 KB

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