server.go 28 KB

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