sched.go 28 KB

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