server.go 31 KB

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