server.go 29 KB

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