sched.go 21 KB

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