server.go 32 KB

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