server.go 31 KB

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