server.go 32 KB

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