server.go 28 KB

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