server.go 31 KB

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