server.go 30 KB

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