sched.go 29 KB

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