server.go 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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/format"
  25. "github.com/ollama/ollama/gpu"
  26. "github.com/ollama/ollama/envconfig"
  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 iterration 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 := 60 * time.Second
  450. stallTimer := time.Now().Add(stallDuration) // give up if we stall for
  451. slog.Info("waiting for llama runner to start responding")
  452. var lastStatus ServerStatus = -1
  453. for {
  454. select {
  455. case <-ctx.Done():
  456. slog.Warn("client connection closed before server finished loading, aborting load")
  457. return fmt.Errorf("timed out waiting for llama runner to start: %w", ctx.Err())
  458. case err := <-s.done:
  459. msg := ""
  460. if s.status != nil && s.status.LastErrMsg != "" {
  461. msg = s.status.LastErrMsg
  462. }
  463. return fmt.Errorf("llama runner process has terminated: %v %s", err, msg)
  464. default:
  465. }
  466. if time.Now().After(stallTimer) {
  467. // timeout
  468. msg := ""
  469. if s.status != nil && s.status.LastErrMsg != "" {
  470. msg = s.status.LastErrMsg
  471. }
  472. return fmt.Errorf("timed out waiting for llama runner to start - progress %0.2f - %s", s.loadProgress, msg)
  473. }
  474. if s.cmd.ProcessState != nil {
  475. msg := ""
  476. if s.status != nil && s.status.LastErrMsg != "" {
  477. msg = s.status.LastErrMsg
  478. }
  479. return fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
  480. }
  481. ctx, cancel := context.WithTimeout(ctx, 200*time.Millisecond)
  482. defer cancel()
  483. priorProgress := s.loadProgress
  484. status, _ := s.getServerStatus(ctx)
  485. if lastStatus != status && status != ServerStatusReady {
  486. // Only log on status changes
  487. slog.Info("waiting for server to become available", "status", status.ToString())
  488. }
  489. switch status {
  490. case ServerStatusReady:
  491. s.loadDuration = time.Since(start)
  492. slog.Info(fmt.Sprintf("llama runner started in %0.2f seconds", s.loadDuration.Seconds()))
  493. return nil
  494. default:
  495. lastStatus = status
  496. // Reset the timer as long as we're making forward progress on the load
  497. if priorProgress != s.loadProgress {
  498. slog.Debug(fmt.Sprintf("model load progress %0.2f", s.loadProgress))
  499. stallTimer = time.Now().Add(stallDuration)
  500. }
  501. time.Sleep(time.Millisecond * 250)
  502. continue
  503. }
  504. }
  505. }
  506. const jsonGrammar = `
  507. root ::= object
  508. value ::= object | array | string | number | ("true" | "false" | "null") ws
  509. object ::=
  510. "{" ws (
  511. string ":" ws value
  512. ("," ws string ":" ws value)*
  513. )? "}" ws
  514. array ::=
  515. "[" ws (
  516. value
  517. ("," ws value)*
  518. )? "]" ws
  519. string ::=
  520. "\"" (
  521. [^"\\] |
  522. "\\" (["\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) # escapes
  523. )* "\"" ws
  524. number ::= ("-"? ([0-9] | [1-9] [0-9]*)) ("." [0-9]+)? ([eE] [-+]? [0-9]+)? ws
  525. # Optional space: by convention, applied in this grammar after literal chars when allowed
  526. ws ::= ([ \t\n] ws)?
  527. `
  528. const maxBufferSize = 512 * format.KiloByte
  529. type ImageData struct {
  530. Data []byte `json:"data"`
  531. ID int `json:"id"`
  532. }
  533. type completion struct {
  534. Content string `json:"content"`
  535. Model string `json:"model"`
  536. Prompt string `json:"prompt"`
  537. Stop bool `json:"stop"`
  538. StoppedLimit bool `json:"stopped_limit"`
  539. Timings struct {
  540. PredictedN int `json:"predicted_n"`
  541. PredictedMS float64 `json:"predicted_ms"`
  542. PromptN int `json:"prompt_n"`
  543. PromptMS float64 `json:"prompt_ms"`
  544. }
  545. }
  546. type CompletionRequest struct {
  547. Prompt string
  548. Format string
  549. Images []ImageData
  550. Options api.Options
  551. }
  552. type CompletionResponse struct {
  553. Content string
  554. DoneReason string
  555. Done bool
  556. PromptEvalCount int
  557. PromptEvalDuration time.Duration
  558. EvalCount int
  559. EvalDuration time.Duration
  560. }
  561. func (s *llmServer) Completion(ctx context.Context, req CompletionRequest, fn func(CompletionResponse)) error {
  562. if err := s.sem.Acquire(ctx, 1); err != nil {
  563. slog.Error("Failed to acquire semaphore", "error", err)
  564. return err
  565. }
  566. defer s.sem.Release(1)
  567. // only allow maximum 10 "context shifts" to avoid infinite generation
  568. if req.Options.NumPredict < 0 || req.Options.NumPredict > 10*s.options.NumCtx {
  569. req.Options.NumPredict = 10 * s.options.NumCtx
  570. slog.Debug("setting token limit to 10x num_ctx", "num_ctx", s.options.NumCtx, "num_predict", req.Options.NumPredict)
  571. }
  572. request := map[string]any{
  573. "prompt": req.Prompt,
  574. "stream": true,
  575. "n_predict": req.Options.NumPredict,
  576. "n_keep": req.Options.NumKeep,
  577. "main_gpu": req.Options.MainGPU,
  578. "temperature": req.Options.Temperature,
  579. "top_k": req.Options.TopK,
  580. "top_p": req.Options.TopP,
  581. "tfs_z": req.Options.TFSZ,
  582. "typical_p": req.Options.TypicalP,
  583. "repeat_last_n": req.Options.RepeatLastN,
  584. "repeat_penalty": req.Options.RepeatPenalty,
  585. "presence_penalty": req.Options.PresencePenalty,
  586. "frequency_penalty": req.Options.FrequencyPenalty,
  587. "mirostat": req.Options.Mirostat,
  588. "mirostat_tau": req.Options.MirostatTau,
  589. "mirostat_eta": req.Options.MirostatEta,
  590. "penalize_nl": req.Options.PenalizeNewline,
  591. "seed": req.Options.Seed,
  592. "stop": req.Options.Stop,
  593. "image_data": req.Images,
  594. "cache_prompt": true,
  595. }
  596. // Make sure the server is ready
  597. status, err := s.getServerStatusRetry(ctx)
  598. if err != nil {
  599. return err
  600. } else if status != ServerStatusReady {
  601. return fmt.Errorf("unexpected server status: %s", status.ToString())
  602. }
  603. if req.Format == "json" {
  604. request["grammar"] = jsonGrammar
  605. if !strings.Contains(strings.ToLower(req.Prompt), "json") {
  606. 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.")
  607. }
  608. }
  609. // Handling JSON marshaling with special characters unescaped.
  610. buffer := &bytes.Buffer{}
  611. enc := json.NewEncoder(buffer)
  612. enc.SetEscapeHTML(false)
  613. if err := enc.Encode(request); err != nil {
  614. return fmt.Errorf("failed to marshal data: %v", err)
  615. }
  616. endpoint := fmt.Sprintf("http://127.0.0.1:%d/completion", s.port)
  617. serverReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, buffer)
  618. if err != nil {
  619. return fmt.Errorf("error creating POST request: %v", err)
  620. }
  621. serverReq.Header.Set("Content-Type", "application/json")
  622. res, err := http.DefaultClient.Do(serverReq)
  623. if err != nil {
  624. return fmt.Errorf("POST predict: %v", err)
  625. }
  626. defer res.Body.Close()
  627. if res.StatusCode >= 400 {
  628. bodyBytes, err := io.ReadAll(res.Body)
  629. if err != nil {
  630. return fmt.Errorf("failed reading llm error response: %w", err)
  631. }
  632. log.Printf("llm predict error: %s", bodyBytes)
  633. return fmt.Errorf("%s", bodyBytes)
  634. }
  635. scanner := bufio.NewScanner(res.Body)
  636. buf := make([]byte, 0, maxBufferSize)
  637. scanner.Buffer(buf, maxBufferSize)
  638. // keep track of the last token generated, this is used to abort if the model starts looping
  639. var lastToken string
  640. var tokenRepeat int
  641. for scanner.Scan() {
  642. select {
  643. case <-ctx.Done():
  644. // This handles the request cancellation
  645. return ctx.Err()
  646. default:
  647. line := scanner.Bytes()
  648. if len(line) == 0 {
  649. continue
  650. }
  651. evt, ok := bytes.CutPrefix(line, []byte("data: "))
  652. if !ok {
  653. return fmt.Errorf("error parsing llm response stream: %s", line)
  654. }
  655. var c completion
  656. if err := json.Unmarshal(evt, &c); err != nil {
  657. return fmt.Errorf("error unmarshaling llm prediction response: %v", err)
  658. }
  659. switch {
  660. case strings.TrimSpace(c.Content) == lastToken:
  661. tokenRepeat++
  662. default:
  663. lastToken = strings.TrimSpace(c.Content)
  664. tokenRepeat = 0
  665. }
  666. // 30 picked as an arbitrary max token repeat limit, modify as needed
  667. if tokenRepeat > 30 {
  668. slog.Debug("prediction aborted, token repeat limit reached")
  669. return ctx.Err()
  670. }
  671. if c.Content != "" {
  672. fn(CompletionResponse{
  673. Content: c.Content,
  674. })
  675. }
  676. if c.Stop {
  677. doneReason := "stop"
  678. if c.StoppedLimit {
  679. doneReason = "length"
  680. }
  681. fn(CompletionResponse{
  682. Done: true,
  683. DoneReason: doneReason,
  684. PromptEvalCount: c.Timings.PromptN,
  685. PromptEvalDuration: parseDurationMs(c.Timings.PromptMS),
  686. EvalCount: c.Timings.PredictedN,
  687. EvalDuration: parseDurationMs(c.Timings.PredictedMS),
  688. })
  689. return nil
  690. }
  691. }
  692. }
  693. if err := scanner.Err(); err != nil {
  694. if strings.Contains(err.Error(), "unexpected EOF") {
  695. s.Close()
  696. msg := ""
  697. if s.status != nil && s.status.LastErrMsg != "" {
  698. msg = s.status.LastErrMsg
  699. }
  700. return fmt.Errorf("an unknown error was encountered while running the model %s", msg)
  701. }
  702. return fmt.Errorf("error reading llm response: %v", err)
  703. }
  704. return nil
  705. }
  706. type EmbeddingRequest struct {
  707. Content string `json:"content"`
  708. }
  709. type EmbeddingResponse struct {
  710. Embedding []float64 `json:"embedding"`
  711. }
  712. func (s *llmServer) Embedding(ctx context.Context, prompt string) ([]float64, error) {
  713. if err := s.sem.Acquire(ctx, 1); err != nil {
  714. slog.Error("Failed to acquire semaphore", "error", err)
  715. return nil, err
  716. }
  717. defer s.sem.Release(1)
  718. // Make sure the server is ready
  719. status, err := s.getServerStatusRetry(ctx)
  720. if err != nil {
  721. return nil, err
  722. } else if status != ServerStatusReady {
  723. return nil, fmt.Errorf("unexpected server status: %s", status.ToString())
  724. }
  725. data, err := json.Marshal(TokenizeRequest{Content: prompt})
  726. if err != nil {
  727. return nil, fmt.Errorf("error marshaling embed data: %w", err)
  728. }
  729. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/embedding", s.port), bytes.NewBuffer(data))
  730. if err != nil {
  731. return nil, fmt.Errorf("error creating embed request: %w", err)
  732. }
  733. req.Header.Set("Content-Type", "application/json")
  734. resp, err := http.DefaultClient.Do(req)
  735. if err != nil {
  736. return nil, fmt.Errorf("do embedding request: %w", err)
  737. }
  738. defer resp.Body.Close()
  739. body, err := io.ReadAll(resp.Body)
  740. if err != nil {
  741. return nil, fmt.Errorf("error reading embed response: %w", err)
  742. }
  743. if resp.StatusCode >= 400 {
  744. log.Printf("llm encode error: %s", body)
  745. return nil, fmt.Errorf("%s", body)
  746. }
  747. var embedding EmbeddingResponse
  748. if err := json.Unmarshal(body, &embedding); err != nil {
  749. return nil, fmt.Errorf("unmarshal tokenize response: %w", err)
  750. }
  751. return embedding.Embedding, nil
  752. }
  753. type TokenizeRequest struct {
  754. Content string `json:"content"`
  755. }
  756. type TokenizeResponse struct {
  757. Tokens []int `json:"tokens"`
  758. }
  759. func (s *llmServer) Tokenize(ctx context.Context, content string) ([]int, error) {
  760. // Make sure the server is ready
  761. status, err := s.getServerStatus(ctx)
  762. if err != nil {
  763. return nil, err
  764. } else if status != ServerStatusReady && status != ServerStatusNoSlotsAvailable {
  765. return nil, fmt.Errorf("unexpected server status: %s", status.ToString())
  766. }
  767. data, err := json.Marshal(TokenizeRequest{Content: content})
  768. if err != nil {
  769. return nil, fmt.Errorf("marshaling encode data: %w", err)
  770. }
  771. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/tokenize", s.port), bytes.NewBuffer(data))
  772. if err != nil {
  773. return nil, fmt.Errorf("encode request: %w", err)
  774. }
  775. req.Header.Set("Content-Type", "application/json")
  776. resp, err := http.DefaultClient.Do(req)
  777. if err != nil {
  778. return nil, fmt.Errorf("do encode request: %w", err)
  779. }
  780. defer resp.Body.Close()
  781. body, err := io.ReadAll(resp.Body)
  782. if err != nil {
  783. return nil, fmt.Errorf("read encode request: %w", err)
  784. }
  785. if resp.StatusCode >= 400 {
  786. log.Printf("llm encode error: %s", body)
  787. return nil, fmt.Errorf("%s", body)
  788. }
  789. var encoded TokenizeResponse
  790. if err := json.Unmarshal(body, &encoded); err != nil {
  791. return nil, fmt.Errorf("unmarshal encode response: %w", err)
  792. }
  793. return encoded.Tokens, nil
  794. }
  795. type DetokenizeRequest struct {
  796. Tokens []int `json:"tokens"`
  797. }
  798. type DetokenizeResponse struct {
  799. Content string `json:"content"`
  800. }
  801. func (s *llmServer) Detokenize(ctx context.Context, tokens []int) (string, error) {
  802. // Make sure the server is ready
  803. status, err := s.getServerStatus(ctx)
  804. if err != nil {
  805. return "", err
  806. } else if status != ServerStatusReady && status != ServerStatusNoSlotsAvailable {
  807. return "", fmt.Errorf("unexpected server status: %s", status.ToString())
  808. }
  809. data, err := json.Marshal(DetokenizeRequest{Tokens: tokens})
  810. if err != nil {
  811. return "", fmt.Errorf("marshaling decode data: %w", err)
  812. }
  813. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/detokenize", s.port), bytes.NewBuffer(data))
  814. if err != nil {
  815. return "", fmt.Errorf("decode request: %w", err)
  816. }
  817. req.Header.Set("Content-Type", "application/json")
  818. resp, err := http.DefaultClient.Do(req)
  819. if err != nil {
  820. return "", fmt.Errorf("do decode request: %w", err)
  821. }
  822. defer resp.Body.Close()
  823. body, err := io.ReadAll(resp.Body)
  824. if err != nil {
  825. return "", fmt.Errorf("read decode request: %w", err)
  826. }
  827. if resp.StatusCode >= 400 {
  828. log.Printf("llm decode error: %s", body)
  829. return "", fmt.Errorf("%s", body)
  830. }
  831. var decoded DetokenizeResponse
  832. if err := json.Unmarshal(body, &decoded); err != nil {
  833. return "", fmt.Errorf("unmarshal encode response: %w", err)
  834. }
  835. return decoded.Content, nil
  836. }
  837. func (s *llmServer) Close() error {
  838. if s.cmd != nil {
  839. slog.Debug("stopping llama server")
  840. if err := s.cmd.Process.Kill(); err != nil {
  841. return err
  842. }
  843. // if ProcessState is already populated, Wait already completed, no need to wait again
  844. if s.cmd.ProcessState == nil {
  845. slog.Debug("waiting for llama server to exit")
  846. <-s.done
  847. }
  848. slog.Debug("llama server stopped")
  849. }
  850. return nil
  851. }
  852. func (s *llmServer) EstimatedVRAM() uint64 {
  853. return s.estimatedVRAM
  854. }
  855. func (s *llmServer) EstimatedTotal() uint64 {
  856. return s.estimatedTotal
  857. }
  858. func parseDurationMs(ms float64) time.Duration {
  859. dur, err := time.ParseDuration(fmt.Sprintf("%fms", ms))
  860. if err != nil {
  861. panic(err)
  862. }
  863. return dur
  864. }