server.go 29 KB

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