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