sched.go 21 KB

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