server.go 33 KB

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