server.go 29 KB

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