sched.go 29 KB

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