server.go 31 KB

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