server.go 32 KB

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