sched.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. package server
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log/slog"
  7. "reflect"
  8. "runtime"
  9. "sort"
  10. "strings"
  11. "sync"
  12. "time"
  13. "github.com/ollama/ollama/api"
  14. "github.com/ollama/ollama/envconfig"
  15. "github.com/ollama/ollama/format"
  16. "github.com/ollama/ollama/gpu"
  17. "github.com/ollama/ollama/llm"
  18. )
  19. type LlmRequest struct {
  20. ctx context.Context //nolint:containedctx
  21. model *Model
  22. opts api.Options
  23. sessionDuration time.Duration
  24. successCh chan *runnerRef
  25. errCh chan error
  26. }
  27. type Scheduler struct {
  28. pendingReqCh chan *LlmRequest
  29. finishedReqCh chan *LlmRequest
  30. expiredCh chan *runnerRef
  31. unloadedCh chan interface{}
  32. loaded map[string]*runnerRef
  33. loadedMu sync.Mutex
  34. loadFn func(req *LlmRequest, ggml *llm.GGML, gpus gpu.GpuInfoList)
  35. newServerFn func(gpus gpu.GpuInfoList, model string, ggml *llm.GGML, adapters []string, projectors []string, opts api.Options) (llm.LlamaServer, error)
  36. getGpuFn func() gpu.GpuInfoList
  37. getCpuFn func() gpu.GpuInfoList
  38. }
  39. var ErrMaxQueue = fmt.Errorf("server busy, please try again. maximum pending requests exceeded")
  40. func InitScheduler(ctx context.Context) *Scheduler {
  41. sched := &Scheduler{
  42. pendingReqCh: make(chan *LlmRequest, envconfig.MaxQueuedRequests),
  43. finishedReqCh: make(chan *LlmRequest, envconfig.MaxQueuedRequests),
  44. expiredCh: make(chan *runnerRef, envconfig.MaxQueuedRequests),
  45. unloadedCh: make(chan interface{}, envconfig.MaxQueuedRequests),
  46. loaded: make(map[string]*runnerRef),
  47. newServerFn: llm.NewLlamaServer,
  48. getGpuFn: gpu.GetGPUInfo,
  49. getCpuFn: gpu.GetCPUInfo,
  50. }
  51. sched.loadFn = sched.load
  52. return sched
  53. }
  54. // context must be canceled to decrement ref count and release the runner
  55. func (s *Scheduler) GetRunner(c context.Context, model *Model, opts api.Options, sessionDuration time.Duration) (chan *runnerRef, chan error) {
  56. // allocate a large enough kv cache for all parallel requests
  57. if opts.NumCtx < 4 {
  58. opts.NumCtx = 4
  59. }
  60. opts.NumCtx *= envconfig.NumParallel
  61. req := &LlmRequest{
  62. ctx: c,
  63. model: model,
  64. opts: opts,
  65. sessionDuration: sessionDuration,
  66. successCh: make(chan *runnerRef),
  67. errCh: make(chan error, 1),
  68. }
  69. select {
  70. case s.pendingReqCh <- req:
  71. default:
  72. req.errCh <- ErrMaxQueue
  73. }
  74. return req.successCh, req.errCh
  75. }
  76. // Returns immediately, spawns go routines for the scheduler which will shutdown when ctx is done
  77. func (s *Scheduler) Run(ctx context.Context) {
  78. slog.Debug("starting llm scheduler")
  79. go func() {
  80. s.processPending(ctx)
  81. }()
  82. go func() {
  83. s.processCompleted(ctx)
  84. }()
  85. }
  86. func (s *Scheduler) processPending(ctx context.Context) {
  87. for {
  88. select {
  89. case <-ctx.Done():
  90. slog.Debug("shutting down scheduler pending loop")
  91. return
  92. case pending := <-s.pendingReqCh:
  93. // Block other requests until we get this pending request running
  94. if pending.ctx.Err() != nil {
  95. slog.Debug("pending request cancelled or timed out, skipping scheduling")
  96. continue
  97. }
  98. for {
  99. var runnerToExpire *runnerRef
  100. s.loadedMu.Lock()
  101. runner := s.loaded[pending.model.ModelPath]
  102. loadedCount := len(s.loaded)
  103. s.loadedMu.Unlock()
  104. if runner != nil {
  105. if runner.needsReload(ctx, pending) {
  106. runnerToExpire = runner
  107. } else {
  108. // Runner is usable, return it
  109. pending.useLoadedRunner(runner, s.finishedReqCh)
  110. break
  111. }
  112. } else if envconfig.MaxRunners > 0 && loadedCount >= envconfig.MaxRunners {
  113. slog.Debug("max runners achieved, unloading one to make room", "runner_count", loadedCount)
  114. runnerToExpire = s.findRunnerToUnload()
  115. } else {
  116. // Either no models are loaded or below envconfig.MaxRunners
  117. // Get a refreshed GPU list
  118. var gpus gpu.GpuInfoList
  119. if pending.opts.NumGPU == 0 {
  120. gpus = s.getCpuFn()
  121. } else {
  122. gpus = s.getGpuFn()
  123. }
  124. // Load model for fitting
  125. ggml, err := llm.LoadModel(pending.model.ModelPath)
  126. if err != nil {
  127. pending.errCh <- err
  128. break
  129. }
  130. // Evaluate if the model will fit in the available system memory, or if we should unload a model first
  131. if len(gpus) == 1 && gpus[0].Library == "cpu" {
  132. if loadedCount == 0 {
  133. slog.Debug("cpu mode with first model, loading")
  134. s.loadFn(pending, ggml, gpus)
  135. break
  136. }
  137. runnerToExpire = s.maybeFindCPURunnerToUnload(pending, ggml, gpus)
  138. if runnerToExpire == nil {
  139. slog.Debug("cpu mode with available system memory or first model, loading")
  140. s.loadFn(pending, ggml, gpus)
  141. break
  142. }
  143. // else we need to expire a runner
  144. } else if loadedCount == 0 {
  145. // No models loaded. Load the model but prefer the best fit.
  146. slog.Debug("loading first model", "model", pending.model.ModelPath)
  147. g := pickBestFitGPUs(pending, ggml, gpus)
  148. if g != nil {
  149. gpus = g
  150. }
  151. s.loadFn(pending, ggml, gpus)
  152. break
  153. }
  154. if runnerToExpire == nil {
  155. // More than one loaded model, so we have to see if the new one fits
  156. // Update free memory from currently loaded models
  157. s.updateFreeSpace(gpus)
  158. gpus = pickBestFitGPUs(pending, ggml, gpus)
  159. if gpus != nil {
  160. slog.Debug("new model fits with existing models, loading")
  161. s.loadFn(pending, ggml, gpus)
  162. break
  163. }
  164. runnerToExpire = s.findRunnerToUnload()
  165. }
  166. }
  167. if runnerToExpire == nil {
  168. // Shouildn't happen
  169. slog.Error("runner to expire was nil!")
  170. continue
  171. }
  172. // Trigger an expiration to unload once it's done
  173. runnerToExpire.refMu.Lock()
  174. slog.Debug("resetting model to expire immediately to make room", "modelPath", runnerToExpire.modelPath, "refCount", runnerToExpire.refCount)
  175. if runnerToExpire.expireTimer != nil {
  176. runnerToExpire.expireTimer.Stop()
  177. runnerToExpire.expireTimer = nil
  178. }
  179. runnerToExpire.sessionDuration = 0
  180. if runnerToExpire.refCount <= 0 {
  181. s.expiredCh <- runnerToExpire
  182. }
  183. runnerToExpire.refMu.Unlock()
  184. // Wait for the unload to happen
  185. // Note: at this point we're queueing up all incoming requests, even if they were for
  186. // a different model that's loaded and not scheduled to be removed.
  187. slog.Debug("waiting for pending requests to complete and unload to occur", "modelPath", runnerToExpire.modelPath)
  188. select {
  189. case <-ctx.Done():
  190. slog.Debug("shutting down scheduler pending loop")
  191. return
  192. case <-s.unloadedCh:
  193. slog.Debug("unload completed", "modelPath", runnerToExpire.modelPath)
  194. continue
  195. }
  196. }
  197. case <-s.unloadedCh:
  198. // An unload request when there are no pending request can be ignored
  199. slog.Debug("ignoring unload event with no pending requests")
  200. }
  201. }
  202. }
  203. func (s *Scheduler) processCompleted(ctx context.Context) {
  204. // Process completed requests, expired timers, and unloading models
  205. for {
  206. select {
  207. case <-ctx.Done():
  208. slog.Debug("shutting down scheduler completed loop")
  209. return
  210. case finished := <-s.finishedReqCh:
  211. s.loadedMu.Lock()
  212. runner := s.loaded[finished.model.ModelPath]
  213. s.loadedMu.Unlock()
  214. if runner == nil {
  215. slog.Error("finished request signal received after model unloaded", "modelPath", finished.model.ModelPath)
  216. continue
  217. }
  218. runner.refMu.Lock()
  219. runner.refCount--
  220. if runner.refCount <= 0 {
  221. if runner.sessionDuration <= 0 {
  222. slog.Debug("runner with zero duration has gone idle, expiring to unload", "modelPath", runner.modelPath)
  223. if runner.expireTimer != nil {
  224. runner.expireTimer.Stop()
  225. runner.expireTimer = nil
  226. }
  227. s.expiredCh <- runner
  228. } else if runner.expireTimer == nil {
  229. slog.Debug("runner with non-zero duration has gone idle, adding timer", "modelPath", runner.modelPath, "duration", runner.sessionDuration)
  230. runner.expireTimer = time.AfterFunc(runner.sessionDuration, func() {
  231. slog.Debug("timer expired, expiring to unload", "modelPath", runner.modelPath)
  232. runner.refMu.Lock()
  233. defer runner.refMu.Unlock()
  234. if runner.expireTimer != nil {
  235. runner.expireTimer.Stop()
  236. runner.expireTimer = nil
  237. }
  238. s.expiredCh <- runner
  239. })
  240. runner.expiresAt = time.Now().Add(runner.sessionDuration)
  241. } else {
  242. slog.Debug("runner with non-zero duration has gone idle, resetting timer", "modelPath", runner.modelPath, "duration", runner.sessionDuration)
  243. runner.expireTimer.Reset(runner.sessionDuration)
  244. runner.expiresAt = time.Now().Add(runner.sessionDuration)
  245. }
  246. }
  247. slog.Debug("after processing request finished event", "modelPath", runner.modelPath, "refCount", runner.refCount)
  248. runner.refMu.Unlock()
  249. case runner := <-s.expiredCh:
  250. slog.Debug("runner expired event received", "modelPath", runner.modelPath)
  251. runner.refMu.Lock()
  252. if runner.refCount > 0 {
  253. // Shouldn't happen, but safeguard to ensure no leaked runners
  254. slog.Debug("expired event with positive ref count, retrying", "modelPath", runner.modelPath, "refCount", runner.refCount)
  255. go func(runner *runnerRef) {
  256. // We can't unload yet, but want to as soon as the current request completes
  257. // So queue up another expired event
  258. time.Sleep(10 * time.Millisecond)
  259. s.expiredCh <- runner
  260. }(runner)
  261. runner.refMu.Unlock()
  262. continue
  263. }
  264. s.loadedMu.Lock()
  265. slog.Debug("got lock to unload", "modelPath", runner.modelPath)
  266. finished := runner.waitForVRAMRecovery()
  267. runner.unload()
  268. delete(s.loaded, runner.modelPath)
  269. s.loadedMu.Unlock()
  270. slog.Debug("runner released", "modelPath", runner.modelPath)
  271. runner.refMu.Unlock()
  272. <-finished
  273. slog.Debug("sending an unloaded event", "modelPath", runner.modelPath)
  274. s.unloadedCh <- struct{}{}
  275. }
  276. }
  277. }
  278. // Complete the pending request and send the runner back to the requester
  279. // Wires up a finished event after the request context is completed
  280. // Updates session duration, and resets expiration timer
  281. func (pending *LlmRequest) useLoadedRunner(runner *runnerRef, finished chan *LlmRequest) {
  282. runner.refMu.Lock()
  283. defer runner.refMu.Unlock()
  284. runner.refCount++
  285. if runner.expireTimer != nil {
  286. runner.expireTimer.Stop()
  287. runner.expireTimer = nil
  288. }
  289. runner.sessionDuration = pending.sessionDuration
  290. pending.successCh <- runner
  291. go func() {
  292. <-pending.ctx.Done()
  293. slog.Debug("context for request finished")
  294. finished <- pending
  295. }()
  296. }
  297. func (s *Scheduler) load(req *LlmRequest, ggml *llm.GGML, gpus gpu.GpuInfoList) {
  298. llama, err := s.newServerFn(gpus, req.model.ModelPath, ggml, req.model.AdapterPaths, req.model.ProjectorPaths, req.opts)
  299. if err != nil {
  300. // some older models are not compatible with newer versions of llama.cpp
  301. // show a generalized compatibility error until there is a better way to
  302. // check for model compatibility
  303. if errors.Is(llm.ErrUnsupportedFormat, err) || strings.Contains(err.Error(), "failed to load model") {
  304. err = fmt.Errorf("%v: this model may be incompatible with your version of Ollama. If you previously pulled this model, try updating it by running `ollama pull %s`", err, req.model.ShortName)
  305. }
  306. slog.Info("NewLlamaServer failed", "model", req.model.ModelPath, "error", err)
  307. req.errCh <- err
  308. return
  309. }
  310. runner := &runnerRef{
  311. model: req.model,
  312. modelPath: req.model.ModelPath,
  313. llama: llama,
  314. Options: &req.opts,
  315. sessionDuration: req.sessionDuration,
  316. gpus: gpus,
  317. estimatedVRAM: llama.EstimatedVRAM(),
  318. estimatedTotal: llama.EstimatedTotal(),
  319. loading: true,
  320. refCount: 1,
  321. }
  322. runner.refMu.Lock()
  323. s.loadedMu.Lock()
  324. s.loaded[req.model.ModelPath] = runner
  325. slog.Info("loaded runners", "count", len(s.loaded))
  326. s.loadedMu.Unlock()
  327. go func() {
  328. defer runner.refMu.Unlock()
  329. if err = llama.WaitUntilRunning(req.ctx); err != nil {
  330. slog.Error("error loading llama server", "error", err)
  331. runner.refCount--
  332. req.errCh <- err
  333. slog.Debug("triggering expiration for failed load", "model", runner.modelPath)
  334. s.expiredCh <- runner
  335. return
  336. }
  337. slog.Debug("finished setting up runner", "model", req.model.ModelPath)
  338. runner.loading = false
  339. go func() {
  340. <-req.ctx.Done()
  341. slog.Debug("context for request finished")
  342. s.finishedReqCh <- req
  343. }()
  344. req.successCh <- runner
  345. }()
  346. }
  347. func (s *Scheduler) updateFreeSpace(allGpus gpu.GpuInfoList) {
  348. type predKey struct {
  349. Library string
  350. ID string
  351. }
  352. predMap := map[predKey]uint64{} // Sum up the total predicted usage per GPU for all runners
  353. s.loadedMu.Lock()
  354. for _, r := range s.loaded {
  355. r.refMu.Lock()
  356. if r.llama != nil {
  357. for _, gpu := range allGpus {
  358. // if slices.Contains(gpuIDs, gpu.ID) {
  359. predMap[predKey{gpu.Library, gpu.ID}] += r.llama.EstimagedVRAMByGPU(gpu.ID)
  360. // }
  361. }
  362. } else {
  363. slog.Warn("unexpected nil runner reference, memory prediction may be incorrect")
  364. }
  365. r.refMu.Unlock()
  366. }
  367. s.loadedMu.Unlock()
  368. // Now that we've summed up all the GPU usage predictions across all the loaded runners, update the gpu list
  369. for i := range allGpus {
  370. if p, ok := predMap[predKey{allGpus[i].Library, allGpus[i].ID}]; ok {
  371. slog.Debug("gpu reported", "gpu", allGpus[i].ID, "library", allGpus[i].Library, "available", format.HumanBytes2(allGpus[i].FreeMemory))
  372. if p > allGpus[i].TotalMemory {
  373. // Shouldn't happen
  374. slog.Warn("predicted usage exceeds VRAM", "gpu", allGpus[i].ID, "totalMemory", allGpus[i].TotalMemory, "predicted", p)
  375. allGpus[i].FreeMemory = 0
  376. } else if (allGpus[i].TotalMemory - p) < allGpus[i].FreeMemory { // predicted free is smaller than reported free, use it
  377. // TODO maybe we should just always trust our numbers, since cuda's free memory reporting is laggy
  378. // and we might unload models we didn't actually need to. The risk is if some other GPU intensive app is loaded
  379. // after we start our first runner, then we'll never acount for that, so picking the smallest free value seems prudent.
  380. allGpus[i].FreeMemory = allGpus[i].TotalMemory - p
  381. }
  382. slog.Info("updated VRAM", "gpu", allGpus[i].ID, "library", allGpus[i].Library, "total", format.HumanBytes2(allGpus[i].TotalMemory), "available", format.HumanBytes2(allGpus[i].FreeMemory))
  383. }
  384. }
  385. }
  386. type runnerRef struct {
  387. refMu sync.Mutex
  388. // refCond sync.Cond // Signaled on transition from 1 -> 0 refCount
  389. refCount uint // prevent unloading if > 0
  390. // unloading bool // set to true when we are trying to unload the runner
  391. llama llm.LlamaServer
  392. loading bool // True only during initial load, then false forever
  393. gpus gpu.GpuInfoList // Recorded at time of provisioning
  394. estimatedVRAM uint64
  395. estimatedTotal uint64
  396. sessionDuration time.Duration
  397. expireTimer *time.Timer
  398. expiresAt time.Time
  399. model *Model
  400. modelPath string
  401. *api.Options
  402. }
  403. // The refMu must already be held when calling unload
  404. func (runner *runnerRef) unload() {
  405. if runner.expireTimer != nil {
  406. runner.expireTimer.Stop()
  407. runner.expireTimer = nil
  408. }
  409. if runner.llama != nil {
  410. runner.llama.Close()
  411. }
  412. runner.model = nil
  413. runner.llama = nil
  414. runner.Options = nil
  415. runner.gpus = nil
  416. }
  417. func (runner *runnerRef) needsReload(ctx context.Context, req *LlmRequest) bool {
  418. slog.Debug("evaluating already loaded", "model", req.model.ModelPath)
  419. runner.refMu.Lock()
  420. defer runner.refMu.Unlock()
  421. timeout := 10 * time.Second
  422. if runner.loading {
  423. timeout = 2 * time.Minute // Initial load can take a long time for big models on slow systems...
  424. }
  425. if runner.Options == nil {
  426. return true
  427. }
  428. // Don't reload runner if num_gpu=-1 was provided
  429. optsExisting := runner.Options.Runner
  430. optsNew := req.opts.Runner
  431. if optsNew.NumGPU < 0 {
  432. optsExisting.NumGPU = -1
  433. optsNew.NumGPU = -1
  434. }
  435. ctx, cancel := context.WithTimeout(ctx, timeout)
  436. defer cancel()
  437. if !reflect.DeepEqual(runner.model.AdapterPaths, req.model.AdapterPaths) || // have the adapters changed?
  438. !reflect.DeepEqual(runner.model.ProjectorPaths, req.model.ProjectorPaths) || // have the projectors changed?
  439. !reflect.DeepEqual(optsExisting, optsNew) || // have the runner options changed?
  440. runner.llama.Ping(ctx) != nil {
  441. return true
  442. }
  443. return false
  444. }
  445. // Free memory reporting on GPUs can lag for a while even after the runner
  446. // exits, so we have to keep checking until we see the available memory recover,
  447. // otherwise subsequent model loads will get far less layers loaded or worse
  448. // case, may completely fall back to CPU mode.
  449. // This routine must be called before the runner unloads so it can establish
  450. // a before and after GPU memory allocation. The returned channel
  451. // will be notified when we're done waiting, or have timed out and should
  452. // proceed anyway
  453. func (runner *runnerRef) waitForVRAMRecovery() chan interface{} {
  454. finished := make(chan interface{}, 1)
  455. // CPU or Metal don't need checking, so no waiting required
  456. // windows can page VRAM, only cuda currently can report accurate used vram usage
  457. if len(runner.gpus) == 0 ||
  458. (len(runner.gpus) == 1 && (runner.gpus[0].Library == "cpu" || runner.gpus[0].Library == "metal")) ||
  459. (runtime.GOOS == "windows" && runner.gpus[0].Library != "cuda") {
  460. finished <- struct{}{}
  461. return finished
  462. }
  463. start := time.Now()
  464. // Establish a baseline before we unload
  465. gpusBefore := gpu.GetGPUInfo()
  466. var totalMemoryBefore, freeMemoryBefore uint64
  467. for _, gpu := range gpusBefore {
  468. totalMemoryBefore += gpu.TotalMemory
  469. freeMemoryBefore += gpu.FreeMemory
  470. }
  471. go func() {
  472. expiresAt := start.Add(5 * time.Second) // typical convergence is 0.5-1.5s
  473. ticker := time.NewTicker(250 * time.Millisecond)
  474. defer ticker.Stop()
  475. for {
  476. <-ticker.C
  477. if time.Now().After(expiresAt) {
  478. slog.Warn("gpu VRAM usage didn't recover within timeout", "seconds", time.Since(start).Seconds())
  479. finished <- struct{}{}
  480. }
  481. // Query GPUs, look for free to go back up
  482. gpusNow := gpu.GetGPUInfo()
  483. var totalMemoryNow, freeMemoryNow uint64
  484. for _, gpu := range gpusNow {
  485. totalMemoryNow += gpu.TotalMemory
  486. freeMemoryNow += gpu.FreeMemory
  487. }
  488. // If we're within ~80% of the estimated memory usage recovered, bail out
  489. if float32(freeMemoryNow-freeMemoryBefore) > float32(runner.estimatedVRAM)*0.8 {
  490. slog.Debug(fmt.Sprintf("gpu VRAM free memory converged after %0.2f seconds", time.Since(start).Seconds()))
  491. finished <- struct{}{}
  492. return
  493. }
  494. }
  495. }()
  496. return finished
  497. }
  498. type ByDuration []*runnerRef
  499. func (a ByDuration) Len() int { return len(a) }
  500. func (a ByDuration) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  501. func (a ByDuration) Less(i, j int) bool {
  502. // uint64 to turn negative time (never unload) to largest
  503. return uint64(a[i].sessionDuration) < uint64(a[j].sessionDuration)
  504. }
  505. // TODO - future consideration to pick runners based on size
  506. // type BySize []*runnerRef
  507. // func (a BySize) Len() int { return len(a) }
  508. // func (a BySize) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  509. // func (a BySize) Less(i, j int) bool { return a[i].estimatedVRAM < a[j].estimatedVRAM }
  510. // pickBestFitGPUs will try to find the optimal placement of the model in the available GPUs where the model fully fits
  511. // If the model can not be fit fully within the available GPU(s) nil is returned
  512. func pickBestFitGPUs(req *LlmRequest, ggml *llm.GGML, gpus gpu.GpuInfoList) gpu.GpuInfoList {
  513. var estimatedVRAM uint64
  514. for _, gl := range gpus.ByLibrary() {
  515. var ok bool
  516. sgl := append(make(gpu.GpuInfoList, 0, len(gl)), gl...)
  517. // TODO - potentially sort by performance capability, existing models loaded, etc.
  518. // Note: at present, this will favor more VRAM over faster GPU speed in mixed setups
  519. sort.Sort(sort.Reverse(gpu.ByFreeMemory(sgl)))
  520. // First attempt to fit the model into a single GPU
  521. if !envconfig.SchedSpread {
  522. for _, g := range sgl {
  523. if ok, estimatedVRAM = llm.PredictServerFit([]gpu.GpuInfo{g}, ggml, req.model.AdapterPaths, req.model.ProjectorPaths, req.opts); ok {
  524. slog.Debug("new model will fit in available VRAM in single GPU, loading", "model", req.model.ModelPath, "gpu", g.ID, "available", g.FreeMemory, "required", format.HumanBytes2(estimatedVRAM))
  525. return []gpu.GpuInfo{g}
  526. }
  527. }
  528. }
  529. // TODO future refinements
  530. // - if multiple Libraries, see if any single GPU in any Library will fit
  531. // - try subsets of GPUs instead of just falling back to 1 or all in a family
  532. // Now try all the GPUs
  533. if ok, estimatedVRAM = llm.PredictServerFit(sgl, ggml, req.model.AdapterPaths, req.model.ProjectorPaths, req.opts); ok {
  534. slog.Debug("new model will fit in available VRAM, loading", "model", req.model.ModelPath, "library", sgl[0].Library, "required", format.HumanBytes2(estimatedVRAM))
  535. return sgl
  536. }
  537. }
  538. return nil
  539. }
  540. // findRunnerToUnload finds a runner to unload to make room for a new model
  541. func (s *Scheduler) findRunnerToUnload() *runnerRef {
  542. s.loadedMu.Lock()
  543. runnerList := make([]*runnerRef, 0, len(s.loaded))
  544. for _, r := range s.loaded {
  545. runnerList = append(runnerList, r)
  546. }
  547. s.loadedMu.Unlock()
  548. if len(runnerList) == 0 {
  549. slog.Debug("no loaded runner to unload")
  550. return nil
  551. }
  552. // In the future we can enhance the algorithm to be smarter about picking the optimal runner to unload
  553. // e.g., if we have multiple options, will one make room for the request?
  554. sort.Sort(ByDuration(runnerList))
  555. // First try to find a runner that's already idle
  556. for _, runner := range runnerList {
  557. runner.refMu.Lock()
  558. rc := runner.refCount
  559. runner.refMu.Unlock()
  560. if rc == 0 {
  561. slog.Debug("found an idle runner to unload")
  562. return runner
  563. }
  564. }
  565. // None appear idle, just wait for the one with the shortest duration
  566. slog.Debug("no idle runners, picking the shortest duration", "count", len(runnerList))
  567. return runnerList[0]
  568. }
  569. func (s *Scheduler) unloadAllRunners() {
  570. s.loadedMu.Lock()
  571. defer s.loadedMu.Unlock()
  572. for model, runner := range s.loaded {
  573. if runner.llama != nil {
  574. slog.Debug("shutting down runner", "model", model)
  575. runner.llama.Close()
  576. }
  577. }
  578. }
  579. // If other runners are loaded, make sure the pending request will fit in system memory
  580. // If not, pick a runner to unload, else return nil and the request can be loaded
  581. func (s *Scheduler) maybeFindCPURunnerToUnload(req *LlmRequest, ggml *llm.GGML, gpus gpu.GpuInfoList) *runnerRef {
  582. slog.Debug("evaluating if CPU model load will fit in available system memory")
  583. estimate := llm.EstimateGPULayers(gpus, ggml, req.model.ProjectorPaths, req.opts)
  584. if estimate.TotalSize <= gpus[0].FreeMemory {
  585. slog.Debug("cpu inference mode, model fits in available system memory", "model", format.HumanBytes2(estimate.TotalSize), "available", format.HumanBytes2(gpus[0].FreeMemory))
  586. return nil
  587. }
  588. // TODO - optimization: try to find CPU only runners first, or partial offloads with enough in system memory to make room
  589. return s.findRunnerToUnload()
  590. }