server.go 29 KB

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