sched.go 27 KB

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