server.go 30 KB

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