server.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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. // 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(exe, 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: f.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. strings.HasPrefix(ev, "DYLD_LIBRARY_PATH=") {
  340. filteredEnv = append(filteredEnv, ev)
  341. }
  342. }
  343. // Log at debug as the environment is inherited and might contain sensitive information
  344. slog.Debug("subprocess", "environment", filteredEnv)
  345. }
  346. if err = s.cmd.Start(); err != nil {
  347. var msg string
  348. if s.status != nil && s.status.LastErrMsg != "" {
  349. msg = s.status.LastErrMsg
  350. }
  351. err := fmt.Errorf("error starting runner: %v %s", err, msg)
  352. if len(compatible) == 0 {
  353. return nil, err
  354. }
  355. slog.Warn("unable to start runner with compatible gpu", "error", err, "compatible", compatible)
  356. compatible = compatible[1:]
  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.Error("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. }
  376. type ServerStatus int
  377. const ( // iota is reset to 0
  378. ServerStatusReady ServerStatus = iota
  379. ServerStatusNoSlotsAvailable
  380. ServerStatusLoadingModel
  381. ServerStatusNotResponding
  382. ServerStatusError
  383. )
  384. func (s ServerStatus) ToString() string {
  385. switch s {
  386. case ServerStatusReady:
  387. return "llm server ready"
  388. case ServerStatusNoSlotsAvailable:
  389. return "llm busy - no slots available"
  390. case ServerStatusLoadingModel:
  391. return "llm server loading model"
  392. case ServerStatusNotResponding:
  393. return "llm server not responding"
  394. default:
  395. return "llm server error"
  396. }
  397. }
  398. type ServerStatusResp struct {
  399. Status string `json:"status"`
  400. SlotsIdle int `json:"slots_idle"`
  401. SlotsProcessing int `json:"slots_processing"`
  402. Error string `json:"error"`
  403. Progress float32 `json:"progress"`
  404. }
  405. func (s *llmServer) getServerStatus(ctx context.Context) (ServerStatus, error) {
  406. // Fail fast if its exited
  407. if s.cmd.ProcessState != nil {
  408. msg := ""
  409. if s.status != nil && s.status.LastErrMsg != "" {
  410. msg = s.status.LastErrMsg
  411. }
  412. if s.cmd.ProcessState.ExitCode() == -1 {
  413. // Most likely a signal killed it, log some more details to try to help troubleshoot
  414. slog.Warn("llama runner process no longer running", "sys", s.cmd.ProcessState.Sys(), "string", s.cmd.ProcessState.String())
  415. }
  416. return ServerStatusError, fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
  417. }
  418. req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/health", s.port), nil)
  419. if err != nil {
  420. return ServerStatusError, fmt.Errorf("error creating GET request: %v", err)
  421. }
  422. req.Header.Set("Content-Type", "application/json")
  423. resp, err := http.DefaultClient.Do(req)
  424. if err != nil {
  425. if errors.Is(err, context.DeadlineExceeded) {
  426. return ServerStatusNotResponding, errors.New("server not responding")
  427. }
  428. return ServerStatusError, fmt.Errorf("health resp: %w", err)
  429. }
  430. defer resp.Body.Close()
  431. body, err := io.ReadAll(resp.Body)
  432. if err != nil {
  433. return ServerStatusError, fmt.Errorf("read health request: %w", err)
  434. }
  435. var status ServerStatusResp
  436. if err := json.Unmarshal(body, &status); err != nil {
  437. return ServerStatusError, fmt.Errorf("health unmarshal encode response: %w", err)
  438. }
  439. switch status.Status {
  440. case "ok":
  441. return ServerStatusReady, nil
  442. case "no slot available":
  443. return ServerStatusNoSlotsAvailable, nil
  444. case "loading model":
  445. s.loadProgress = status.Progress
  446. return ServerStatusLoadingModel, nil
  447. default:
  448. return ServerStatusError, fmt.Errorf("server error: %+v", status)
  449. }
  450. }
  451. // getServerStatusRetry will retry if ServerStatusNoSlotsAvailable is received
  452. func (s *llmServer) getServerStatusRetry(ctx context.Context) (ServerStatus, error) {
  453. var retries int
  454. for {
  455. status, err := s.getServerStatus(ctx)
  456. if err != nil {
  457. return status, err
  458. }
  459. if status == ServerStatusNoSlotsAvailable {
  460. if retries >= 10 {
  461. return status, fmt.Errorf("no slots available after %d retries", retries)
  462. }
  463. time.Sleep(5 * time.Millisecond)
  464. retries++
  465. continue
  466. }
  467. return status, nil
  468. }
  469. }
  470. func (s *llmServer) Ping(ctx context.Context) error {
  471. _, err := s.getServerStatus(ctx)
  472. if err != nil {
  473. slog.Debug("server unhealthy", "error", err)
  474. return err
  475. }
  476. return nil
  477. }
  478. func (s *llmServer) WaitUntilRunning(ctx context.Context) error {
  479. start := time.Now()
  480. stallDuration := envconfig.LoadTimeout() // If no progress happens
  481. stallTimer := time.Now().Add(stallDuration) // give up if we stall
  482. slog.Info("waiting for llama runner to start responding")
  483. var lastStatus ServerStatus = -1
  484. fullyLoaded := false
  485. for {
  486. select {
  487. case <-ctx.Done():
  488. slog.Warn("client connection closed before server finished loading, aborting load")
  489. return fmt.Errorf("timed out waiting for llama runner to start: %w", ctx.Err())
  490. case err := <-s.done:
  491. return fmt.Errorf("llama runner process has terminated: %w", err)
  492. default:
  493. }
  494. if time.Now().After(stallTimer) {
  495. // timeout
  496. msg := ""
  497. if s.status != nil && s.status.LastErrMsg != "" {
  498. msg = s.status.LastErrMsg
  499. }
  500. return fmt.Errorf("timed out waiting for llama runner to start - progress %0.2f - %s", s.loadProgress, msg)
  501. }
  502. if s.cmd.ProcessState != nil {
  503. msg := ""
  504. if s.status != nil && s.status.LastErrMsg != "" {
  505. msg = s.status.LastErrMsg
  506. }
  507. return fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
  508. }
  509. ctx, cancel := context.WithTimeout(ctx, 200*time.Millisecond)
  510. defer cancel()
  511. priorProgress := s.loadProgress
  512. status, _ := s.getServerStatus(ctx)
  513. if lastStatus != status && status != ServerStatusReady {
  514. // Only log on status changes
  515. slog.Info("waiting for server to become available", "status", status.ToString())
  516. }
  517. switch status {
  518. case ServerStatusReady:
  519. s.loadDuration = time.Since(start)
  520. slog.Info(fmt.Sprintf("llama runner started in %0.2f seconds", s.loadDuration.Seconds()))
  521. return nil
  522. default:
  523. lastStatus = status
  524. // Reset the timer as long as we're making forward progress on the load
  525. if priorProgress != s.loadProgress {
  526. slog.Debug(fmt.Sprintf("model load progress %0.2f", s.loadProgress))
  527. stallTimer = time.Now().Add(stallDuration)
  528. } else if !fullyLoaded && int(s.loadProgress*100.0) >= 100 {
  529. slog.Debug("model load completed, waiting for server to become available", "status", status.ToString())
  530. stallTimer = time.Now().Add(stallDuration)
  531. fullyLoaded = true
  532. }
  533. time.Sleep(time.Millisecond * 250)
  534. continue
  535. }
  536. }
  537. }
  538. var grammarJSON = `
  539. root ::= object
  540. value ::= object | array | string | number | ("true" | "false" | "null") ws
  541. object ::=
  542. "{" ws (
  543. string ":" ws value
  544. ("," ws string ":" ws value)*
  545. )? "}" ws
  546. array ::=
  547. "[" ws (
  548. value
  549. ("," ws value)*
  550. )? "]" ws
  551. string ::=
  552. "\"" (
  553. [^"\\\x7F\x00-\x1F] |
  554. "\\" (["\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) # escapes
  555. )* "\"" ws
  556. number ::= ("-"? ([0-9] | [1-9] [0-9]*)) ("." [0-9]+)? ([eE] [-+]? [0-9]+)? ws
  557. # Optional space: by convention, applied in this grammar after literal chars when allowed
  558. ws ::= ([ \t\n] ws)?
  559. `
  560. const maxBufferSize = 512 * format.KiloByte
  561. type ImageData struct {
  562. Data []byte `json:"data"`
  563. ID int `json:"id"`
  564. AspectRatioID int `json:"aspect_ratio_id"`
  565. }
  566. type completion struct {
  567. Content string `json:"content"`
  568. Model string `json:"model"`
  569. Prompt string `json:"prompt"`
  570. Stop bool `json:"stop"`
  571. StoppedLimit bool `json:"stopped_limit"`
  572. Timings struct {
  573. PredictedN int `json:"predicted_n"`
  574. PredictedMS float64 `json:"predicted_ms"`
  575. PromptN int `json:"prompt_n"`
  576. PromptMS float64 `json:"prompt_ms"`
  577. }
  578. }
  579. type CompletionRequest struct {
  580. Prompt string
  581. Format json.RawMessage
  582. Images []ImageData
  583. Options *api.Options
  584. }
  585. type CompletionResponse struct {
  586. Content string
  587. DoneReason string
  588. Done bool
  589. PromptEvalCount int
  590. PromptEvalDuration time.Duration
  591. EvalCount int
  592. EvalDuration time.Duration
  593. }
  594. func (s *llmServer) Completion(ctx context.Context, req CompletionRequest, fn func(CompletionResponse)) error {
  595. request := map[string]any{
  596. "prompt": req.Prompt,
  597. "stream": true,
  598. "n_predict": req.Options.NumPredict,
  599. "n_keep": req.Options.NumKeep,
  600. "main_gpu": req.Options.MainGPU,
  601. "temperature": req.Options.Temperature,
  602. "top_k": req.Options.TopK,
  603. "top_p": req.Options.TopP,
  604. "min_p": req.Options.MinP,
  605. "typical_p": req.Options.TypicalP,
  606. "repeat_last_n": req.Options.RepeatLastN,
  607. "repeat_penalty": req.Options.RepeatPenalty,
  608. "presence_penalty": req.Options.PresencePenalty,
  609. "frequency_penalty": req.Options.FrequencyPenalty,
  610. "mirostat": req.Options.Mirostat,
  611. "mirostat_tau": req.Options.MirostatTau,
  612. "mirostat_eta": req.Options.MirostatEta,
  613. "seed": req.Options.Seed,
  614. "stop": req.Options.Stop,
  615. "image_data": req.Images,
  616. "cache_prompt": true,
  617. }
  618. if len(req.Format) > 0 {
  619. switch string(req.Format) {
  620. case `null`, `""`:
  621. // Field was set, but "missing" a value. We accept
  622. // these as "not set".
  623. break
  624. case `"json"`:
  625. request["grammar"] = grammarJSON
  626. default:
  627. if req.Format[0] != '{' {
  628. return fmt.Errorf("invalid format: %q; expected \"json\" or a valid JSON Schema object", req.Format)
  629. }
  630. // User provided a JSON schema
  631. g := llama.SchemaToGrammar(req.Format)
  632. if g == nil {
  633. return fmt.Errorf("invalid JSON schema in format")
  634. }
  635. request["grammar"] = string(g)
  636. }
  637. }
  638. if err := s.sem.Acquire(ctx, 1); err != nil {
  639. if errors.Is(err, context.Canceled) {
  640. slog.Info("aborting completion request due to client closing the connection")
  641. } else {
  642. slog.Error("Failed to acquire semaphore", "error", err)
  643. }
  644. return err
  645. }
  646. defer s.sem.Release(1)
  647. // put an upper limit on num_predict to avoid the model running on forever
  648. if req.Options.NumPredict < 0 || req.Options.NumPredict > 10*s.options.NumCtx {
  649. req.Options.NumPredict = 10 * s.options.NumCtx
  650. }
  651. // Make sure the server is ready
  652. status, err := s.getServerStatusRetry(ctx)
  653. if err != nil {
  654. return err
  655. } else if status != ServerStatusReady {
  656. return fmt.Errorf("unexpected server status: %s", status.ToString())
  657. }
  658. // Handling JSON marshaling with special characters unescaped.
  659. buffer := &bytes.Buffer{}
  660. enc := json.NewEncoder(buffer)
  661. enc.SetEscapeHTML(false)
  662. if err := enc.Encode(request); err != nil {
  663. return fmt.Errorf("failed to marshal data: %v", err)
  664. }
  665. endpoint := fmt.Sprintf("http://127.0.0.1:%d/completion", s.port)
  666. serverReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, buffer)
  667. if err != nil {
  668. return fmt.Errorf("error creating POST request: %v", err)
  669. }
  670. serverReq.Header.Set("Content-Type", "application/json")
  671. res, err := http.DefaultClient.Do(serverReq)
  672. if err != nil {
  673. return fmt.Errorf("POST predict: %v", err)
  674. }
  675. defer res.Body.Close()
  676. if res.StatusCode >= 400 {
  677. bodyBytes, err := io.ReadAll(res.Body)
  678. if err != nil {
  679. return fmt.Errorf("failed reading llm error response: %w", err)
  680. }
  681. log.Printf("llm predict error: %s", bodyBytes)
  682. return fmt.Errorf("%s", bodyBytes)
  683. }
  684. scanner := bufio.NewScanner(res.Body)
  685. buf := make([]byte, 0, maxBufferSize)
  686. scanner.Buffer(buf, maxBufferSize)
  687. // keep track of the last token generated, this is used to abort if the model starts looping
  688. var lastToken string
  689. var tokenRepeat int
  690. for scanner.Scan() {
  691. select {
  692. case <-ctx.Done():
  693. // This handles the request cancellation
  694. return ctx.Err()
  695. default:
  696. line := scanner.Bytes()
  697. if len(line) == 0 {
  698. continue
  699. }
  700. // slog.Debug("got line", "line", string(line))
  701. evt, ok := bytes.CutPrefix(line, []byte("data: "))
  702. if !ok {
  703. evt = line
  704. }
  705. var c completion
  706. if err := json.Unmarshal(evt, &c); err != nil {
  707. return fmt.Errorf("error unmarshalling llm prediction response: %v", err)
  708. }
  709. switch {
  710. case strings.TrimSpace(c.Content) == lastToken:
  711. tokenRepeat++
  712. default:
  713. lastToken = strings.TrimSpace(c.Content)
  714. tokenRepeat = 0
  715. }
  716. // 30 picked as an arbitrary max token repeat limit, modify as needed
  717. if tokenRepeat > 30 {
  718. slog.Debug("prediction aborted, token repeat limit reached")
  719. return ctx.Err()
  720. }
  721. if c.Content != "" {
  722. fn(CompletionResponse{
  723. Content: c.Content,
  724. })
  725. }
  726. if c.Stop {
  727. doneReason := "stop"
  728. if c.StoppedLimit {
  729. doneReason = "length"
  730. }
  731. fn(CompletionResponse{
  732. Done: true,
  733. DoneReason: doneReason,
  734. PromptEvalCount: c.Timings.PromptN,
  735. PromptEvalDuration: parseDurationMs(c.Timings.PromptMS),
  736. EvalCount: c.Timings.PredictedN,
  737. EvalDuration: parseDurationMs(c.Timings.PredictedMS),
  738. })
  739. return nil
  740. }
  741. }
  742. }
  743. if err := scanner.Err(); err != nil {
  744. if strings.Contains(err.Error(), "unexpected EOF") || strings.Contains(err.Error(), "forcibly closed") {
  745. s.Close()
  746. var msg string
  747. if s.status != nil && s.status.LastErrMsg != "" {
  748. msg = s.status.LastErrMsg
  749. } else {
  750. msg = err.Error()
  751. }
  752. return fmt.Errorf("an error was encountered while running the model: %s", msg)
  753. }
  754. return fmt.Errorf("error reading llm response: %v", err)
  755. }
  756. return nil
  757. }
  758. type EmbeddingRequest struct {
  759. Content string `json:"content"`
  760. }
  761. type EmbeddingResponse struct {
  762. Embedding []float32 `json:"embedding"`
  763. }
  764. func (s *llmServer) Embedding(ctx context.Context, input string) ([]float32, error) {
  765. if err := s.sem.Acquire(ctx, 1); err != nil {
  766. if errors.Is(err, context.Canceled) {
  767. slog.Info("aborting embedding request due to client closing the connection")
  768. } else {
  769. slog.Error("Failed to acquire semaphore", "error", err)
  770. }
  771. return nil, err
  772. }
  773. defer s.sem.Release(1)
  774. // Make sure the server is ready
  775. status, err := s.getServerStatusRetry(ctx)
  776. if err != nil {
  777. return nil, err
  778. } else if status != ServerStatusReady {
  779. return nil, fmt.Errorf("unexpected server status: %s", status.ToString())
  780. }
  781. data, err := json.Marshal(EmbeddingRequest{Content: input})
  782. if err != nil {
  783. return nil, fmt.Errorf("error marshaling embed data: %w", err)
  784. }
  785. r, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/embedding", s.port), bytes.NewBuffer(data))
  786. if err != nil {
  787. return nil, fmt.Errorf("error creating embed request: %w", err)
  788. }
  789. r.Header.Set("Content-Type", "application/json")
  790. resp, err := http.DefaultClient.Do(r)
  791. if err != nil {
  792. return nil, fmt.Errorf("do embedding request: %w", err)
  793. }
  794. defer resp.Body.Close()
  795. body, err := io.ReadAll(resp.Body)
  796. if err != nil {
  797. return nil, fmt.Errorf("error reading embed response: %w", err)
  798. }
  799. if resp.StatusCode >= 400 {
  800. log.Printf("llm embedding error: %s", body)
  801. return nil, fmt.Errorf("%s", body)
  802. }
  803. var e EmbeddingResponse
  804. if err := json.Unmarshal(body, &e); err != nil {
  805. return nil, fmt.Errorf("unmarshal tokenize response: %w", err)
  806. }
  807. return e.Embedding, nil
  808. }
  809. type TokenizeRequest struct {
  810. Content string `json:"content"`
  811. }
  812. type TokenizeResponse struct {
  813. Tokens []int `json:"tokens"`
  814. }
  815. func (s *llmServer) Tokenize(ctx context.Context, content string) ([]int, error) {
  816. s.modelLock.Lock()
  817. defer s.modelLock.Unlock()
  818. if s.model != nil {
  819. return s.model.Tokenize(content, false, true)
  820. }
  821. // Make sure the server is ready
  822. status, err := s.getServerStatus(ctx)
  823. if err != nil {
  824. return nil, err
  825. } else if status != ServerStatusReady && status != ServerStatusNoSlotsAvailable {
  826. return nil, fmt.Errorf("unexpected server status: %s", status.ToString())
  827. }
  828. data, err := json.Marshal(TokenizeRequest{Content: content})
  829. if err != nil {
  830. return nil, fmt.Errorf("marshaling encode data: %w", err)
  831. }
  832. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/tokenize", s.port), bytes.NewBuffer(data))
  833. if err != nil {
  834. return nil, fmt.Errorf("encode request: %w", err)
  835. }
  836. req.Header.Set("Content-Type", "application/json")
  837. resp, err := http.DefaultClient.Do(req)
  838. if err != nil {
  839. return nil, fmt.Errorf("do encode request: %w", err)
  840. }
  841. defer resp.Body.Close()
  842. if resp.StatusCode == http.StatusNotFound {
  843. if s.model == nil {
  844. slog.Debug("new runner detected, loading model for cgo tokenization")
  845. m, err := llama.LoadModelFromFile(s.modelPath, llama.ModelParams{VocabOnly: true})
  846. if err != nil {
  847. return nil, err
  848. }
  849. s.model = m
  850. }
  851. return s.model.Tokenize(content, false, true)
  852. }
  853. body, err := io.ReadAll(resp.Body)
  854. if err != nil {
  855. return nil, fmt.Errorf("read encode request: %w", err)
  856. }
  857. if resp.StatusCode >= 400 {
  858. log.Printf("llm encode error: %s", body)
  859. return nil, fmt.Errorf("%s", body)
  860. }
  861. var encoded TokenizeResponse
  862. if err := json.Unmarshal(body, &encoded); err != nil {
  863. return nil, fmt.Errorf("unmarshal encode response: %w", err)
  864. }
  865. return encoded.Tokens, nil
  866. }
  867. type DetokenizeRequest struct {
  868. Tokens []int `json:"tokens"`
  869. }
  870. type DetokenizeResponse struct {
  871. Content string `json:"content"`
  872. }
  873. func (s *llmServer) Detokenize(ctx context.Context, tokens []int) (string, error) {
  874. s.modelLock.Lock()
  875. defer s.modelLock.Unlock()
  876. if s.model != nil {
  877. var resp string
  878. for _, token := range tokens {
  879. resp += s.model.TokenToPiece(token)
  880. }
  881. return resp, nil
  882. }
  883. // Make sure the server is ready
  884. status, err := s.getServerStatus(ctx)
  885. if err != nil {
  886. return "", err
  887. } else if status != ServerStatusReady && status != ServerStatusNoSlotsAvailable {
  888. return "", fmt.Errorf("unexpected server status: %s", status.ToString())
  889. }
  890. data, err := json.Marshal(DetokenizeRequest{Tokens: tokens})
  891. if err != nil {
  892. return "", fmt.Errorf("marshaling decode data: %w", err)
  893. }
  894. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/detokenize", s.port), bytes.NewBuffer(data))
  895. if err != nil {
  896. return "", fmt.Errorf("decode request: %w", err)
  897. }
  898. req.Header.Set("Content-Type", "application/json")
  899. resp, err := http.DefaultClient.Do(req)
  900. if err != nil {
  901. return "", fmt.Errorf("do decode request: %w", err)
  902. }
  903. defer resp.Body.Close()
  904. if resp.StatusCode == http.StatusNotFound {
  905. if s.model == nil {
  906. slog.Debug("new runner detected, loading model for cgo tokenization")
  907. m, err := llama.LoadModelFromFile(s.modelPath, llama.ModelParams{VocabOnly: true})
  908. if err != nil {
  909. return "", err
  910. }
  911. s.model = m
  912. }
  913. var resp string
  914. for _, token := range tokens {
  915. resp += s.model.TokenToPiece(token)
  916. }
  917. return resp, nil
  918. }
  919. body, err := io.ReadAll(resp.Body)
  920. if err != nil {
  921. return "", fmt.Errorf("read decode request: %w", err)
  922. }
  923. if resp.StatusCode >= 400 {
  924. log.Printf("llm decode error: %s", body)
  925. return "", fmt.Errorf("%s", body)
  926. }
  927. var decoded DetokenizeResponse
  928. if err := json.Unmarshal(body, &decoded); err != nil {
  929. return "", fmt.Errorf("unmarshal encode response: %w", err)
  930. }
  931. return decoded.Content, nil
  932. }
  933. func (s *llmServer) Close() error {
  934. s.modelLock.Lock()
  935. if s.model != nil {
  936. llama.FreeModel(s.model)
  937. s.model = nil
  938. }
  939. s.modelLock.Unlock()
  940. if s.cmd != nil {
  941. slog.Debug("stopping llama server")
  942. if err := s.cmd.Process.Kill(); err != nil {
  943. return err
  944. }
  945. // if ProcessState is already populated, Wait already completed, no need to wait again
  946. if s.cmd.ProcessState == nil {
  947. slog.Debug("waiting for llama server to exit")
  948. <-s.done
  949. }
  950. slog.Debug("llama server stopped")
  951. }
  952. return nil
  953. }
  954. func (s *llmServer) EstimatedVRAM() uint64 {
  955. return s.estimate.VRAMSize
  956. }
  957. func (s *llmServer) EstimatedTotal() uint64 {
  958. return s.estimate.TotalSize
  959. }
  960. func (s *llmServer) EstimatedVRAMByGPU(gpuID string) uint64 {
  961. for i, gpu := range s.gpus {
  962. if gpu.ID == gpuID {
  963. if i < len(s.estimate.GPUSizes) {
  964. return s.estimate.GPUSizes[i]
  965. }
  966. }
  967. }
  968. return 0
  969. }
  970. func parseDurationMs(ms float64) time.Duration {
  971. dur, err := time.ParseDuration(fmt.Sprintf("%fms", ms))
  972. if err != nil {
  973. panic(err)
  974. }
  975. return dur
  976. }