server.go 30 KB

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