server.go 29 KB

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