server.go 26 KB

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