server.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  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. }
  734. type EmbedResponse struct {
  735. Embedding [][]float64 `json:"embedding"`
  736. }
  737. func (s *llmServer) Embed(ctx context.Context, input []string) ([][]float64, error) {
  738. if err := s.sem.Acquire(ctx, 1); err != nil {
  739. slog.Error("Failed to acquire semaphore", "error", err)
  740. return nil, err
  741. }
  742. defer s.sem.Release(1)
  743. // Make sure the server is ready
  744. status, err := s.getServerStatusRetry(ctx)
  745. if err != nil {
  746. return nil, err
  747. } else if status != ServerStatusReady {
  748. return nil, fmt.Errorf("unexpected server status: %s", status.ToString())
  749. }
  750. data, err := json.Marshal(EmbedRequest{Content: input})
  751. if err != nil {
  752. return nil, fmt.Errorf("error marshaling embed data: %w", err)
  753. }
  754. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/embedding", s.port), bytes.NewBuffer(data))
  755. if err != nil {
  756. return nil, fmt.Errorf("error creating embed request: %w", err)
  757. }
  758. req.Header.Set("Content-Type", "application/json")
  759. resp, err := http.DefaultClient.Do(req)
  760. if err != nil {
  761. return nil, fmt.Errorf("do embedding request: %w", err)
  762. }
  763. defer resp.Body.Close()
  764. body, err := io.ReadAll(resp.Body)
  765. if err != nil {
  766. return nil, fmt.Errorf("error reading embed response: %w", err)
  767. }
  768. if resp.StatusCode >= 400 {
  769. log.Printf("llm encode error: %s", body)
  770. return nil, fmt.Errorf("%s", body)
  771. }
  772. var embedding EmbedResponse
  773. if err := json.Unmarshal(body, &embedding); err != nil {
  774. return nil, fmt.Errorf("unmarshal tokenize response: %w", err)
  775. }
  776. return embedding.Embedding, nil
  777. }
  778. type EmbeddingRequest struct {
  779. Content string `json:"content"`
  780. }
  781. type EmbeddingResponse struct {
  782. Embedding []float64 `json:"embedding"`
  783. }
  784. func (s *llmServer) Embedding(ctx context.Context, prompt string) ([]float64, error) {
  785. if err := s.sem.Acquire(ctx, 1); err != nil {
  786. slog.Error("Failed to acquire semaphore", "error", err)
  787. return nil, err
  788. }
  789. defer s.sem.Release(1)
  790. // Make sure the server is ready
  791. status, err := s.getServerStatusRetry(ctx)
  792. if err != nil {
  793. return nil, err
  794. } else if status != ServerStatusReady {
  795. return nil, fmt.Errorf("unexpected server status: %s", status.ToString())
  796. }
  797. data, err := json.Marshal(TokenizeRequest{Content: prompt})
  798. if err != nil {
  799. return nil, fmt.Errorf("error marshaling embed data: %w", err)
  800. }
  801. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/embedding", s.port), bytes.NewBuffer(data))
  802. if err != nil {
  803. return nil, fmt.Errorf("error creating embed request: %w", err)
  804. }
  805. req.Header.Set("Content-Type", "application/json")
  806. resp, err := http.DefaultClient.Do(req)
  807. if err != nil {
  808. return nil, fmt.Errorf("do embedding request: %w", err)
  809. }
  810. defer resp.Body.Close()
  811. body, err := io.ReadAll(resp.Body)
  812. if err != nil {
  813. return nil, fmt.Errorf("error reading embed response: %w", err)
  814. }
  815. if resp.StatusCode >= 400 {
  816. log.Printf("llm encode error: %s", body)
  817. return nil, fmt.Errorf("%s", body)
  818. }
  819. var embedding EmbeddingResponse
  820. if err := json.Unmarshal(body, &embedding); err != nil {
  821. return nil, fmt.Errorf("unmarshal tokenize response: %w", err)
  822. }
  823. return embedding.Embedding, nil
  824. }
  825. type TokenizeRequest struct {
  826. Content string `json:"content"`
  827. }
  828. type TokenizeResponse struct {
  829. Tokens []int `json:"tokens"`
  830. }
  831. func (s *llmServer) Tokenize(ctx context.Context, content string) ([]int, error) {
  832. // Make sure the server is ready
  833. status, err := s.getServerStatus(ctx)
  834. if err != nil {
  835. return nil, err
  836. } else if status != ServerStatusReady && status != ServerStatusNoSlotsAvailable {
  837. return nil, fmt.Errorf("unexpected server status: %s", status.ToString())
  838. }
  839. data, err := json.Marshal(TokenizeRequest{Content: content})
  840. if err != nil {
  841. return nil, fmt.Errorf("marshaling encode data: %w", err)
  842. }
  843. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/tokenize", s.port), bytes.NewBuffer(data))
  844. if err != nil {
  845. return nil, fmt.Errorf("encode request: %w", err)
  846. }
  847. req.Header.Set("Content-Type", "application/json")
  848. resp, err := http.DefaultClient.Do(req)
  849. if err != nil {
  850. return nil, fmt.Errorf("do encode request: %w", err)
  851. }
  852. defer resp.Body.Close()
  853. body, err := io.ReadAll(resp.Body)
  854. if err != nil {
  855. return nil, fmt.Errorf("read encode request: %w", err)
  856. }
  857. if resp.StatusCode >= 400 {
  858. log.Printf("llm encode error: %s", body)
  859. return nil, fmt.Errorf("%s", body)
  860. }
  861. var encoded TokenizeResponse
  862. if err := json.Unmarshal(body, &encoded); err != nil {
  863. return nil, fmt.Errorf("unmarshal encode response: %w", err)
  864. }
  865. return encoded.Tokens, nil
  866. }
  867. type DetokenizeRequest struct {
  868. Tokens []int `json:"tokens"`
  869. }
  870. type DetokenizeResponse struct {
  871. Content string `json:"content"`
  872. }
  873. func (s *llmServer) Detokenize(ctx context.Context, tokens []int) (string, error) {
  874. // Make sure the server is ready
  875. status, err := s.getServerStatus(ctx)
  876. if err != nil {
  877. return "", err
  878. } else if status != ServerStatusReady && status != ServerStatusNoSlotsAvailable {
  879. return "", fmt.Errorf("unexpected server status: %s", status.ToString())
  880. }
  881. data, err := json.Marshal(DetokenizeRequest{Tokens: tokens})
  882. if err != nil {
  883. return "", fmt.Errorf("marshaling decode data: %w", err)
  884. }
  885. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/detokenize", s.port), bytes.NewBuffer(data))
  886. if err != nil {
  887. return "", fmt.Errorf("decode request: %w", err)
  888. }
  889. req.Header.Set("Content-Type", "application/json")
  890. resp, err := http.DefaultClient.Do(req)
  891. if err != nil {
  892. return "", fmt.Errorf("do decode request: %w", err)
  893. }
  894. defer resp.Body.Close()
  895. body, err := io.ReadAll(resp.Body)
  896. if err != nil {
  897. return "", fmt.Errorf("read decode request: %w", err)
  898. }
  899. if resp.StatusCode >= 400 {
  900. log.Printf("llm decode error: %s", body)
  901. return "", fmt.Errorf("%s", body)
  902. }
  903. var decoded DetokenizeResponse
  904. if err := json.Unmarshal(body, &decoded); err != nil {
  905. return "", fmt.Errorf("unmarshal encode response: %w", err)
  906. }
  907. return decoded.Content, nil
  908. }
  909. func (s *llmServer) Close() error {
  910. if s.cmd != nil {
  911. slog.Debug("stopping llama server")
  912. if err := s.cmd.Process.Kill(); err != nil {
  913. return err
  914. }
  915. // if ProcessState is already populated, Wait already completed, no need to wait again
  916. if s.cmd.ProcessState == nil {
  917. slog.Debug("waiting for llama server to exit")
  918. <-s.done
  919. }
  920. slog.Debug("llama server stopped")
  921. }
  922. return nil
  923. }
  924. func (s *llmServer) EstimatedVRAM() uint64 {
  925. return s.estimate.VRAMSize
  926. }
  927. func (s *llmServer) EstimatedTotal() uint64 {
  928. return s.estimate.TotalSize
  929. }
  930. func (s *llmServer) EstimatedVRAMByGPU(gpuID string) uint64 {
  931. for i, gpu := range s.gpus {
  932. if gpu.ID == gpuID {
  933. return s.estimate.GPUSizes[i]
  934. }
  935. }
  936. return 0
  937. }
  938. func parseDurationMs(ms float64) time.Duration {
  939. dur, err := time.ParseDuration(fmt.Sprintf("%fms", ms))
  940. if err != nil {
  941. panic(err)
  942. }
  943. return dur
  944. }