server.go 30 KB

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