server.go 29 KB

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