Repository navigation
Expand file tree
/
Copy pathqueueing-talk.jl
More file actions
2754 lines (2336 loc) · 103 KB
/
Copy pathqueueing-talk.jl
File metadata and controls
2754 lines (2336 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
### A Pluto.jl notebook ###
# v1.0.3
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
#! format: off
return quote
local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)
el
end
#! format: on
end
# ╔═╡ eac0e680-c24f-5b56-ab9b-e71d55df97ce
using PlutoUI, Plots, Random, Statistics
# ╔═╡ 0fa45428-cdd4-5710-8796-cfb1772bb14c
begin
default(size=(760, 380), linewidth=2.5, framestyle=:box, grid=:y, gridalpha=0.25,
titlefontsize=12, guidefontsize=11, tickfontsize=10, legendfontsize=10,
left_margin=4Plots.mm, bottom_margin=4Plots.mm)
const BLUE = "#2563eb"
const RED = "#dc2626"
const GRAY = "#94a3b8"
const GREEN = "#16a34a"
const ORANGE = "#ea580c"
const PURPLE = "#7c3aed"
end;
# ╔═╡ 7b7ac9c1-9958-514b-912e-501b8e24fecc
html"""<style>
pluto-output table td, pluto-output table th { font-family: inherit !important; }
</style>"""
# ╔═╡ 5ff52dbd-37c6-5bba-b62d-08ef81a1685b
md"""
# How many GPUs should I rent?
### A crash course in queueing theory
"""
# ╔═╡ 8d109aa3-cc57-5445-bc50-75bb08128299
md"""
## Imagine you're a tech bro 🦺
- You dropped out, bought the vest, and built **Scribbl**: snap a photo of your messy handwritten notes and AI hands back clean, typed notes.
- Every photo needs a **GPU** to read the handwriting. That takes about **15 seconds**, so one GPU can do **240 notes an hour**.
- Launch day. It goes viral. **220 notes an hour** come in.
- 220 < 240. One GPU is enough. Ship it. 🚀
"""
# ╔═╡ db2f45d3-454a-595d-8ef3-e8560e71d0d0
md"""
*→ Let's see how launch day goes.*
"""
# ╔═╡ 207fb2e0-99c7-5c80-bbdd-f51059c99709
md"""
## Launch day 📈
GPUs rented: $(@bind c_hook Slider(1:4, default=1, show_value=true)) $(html"  ") $(@bind replay_hook CounterButton("🎲 replay the day"))
Minutes since launch: $(@bind t_hook Slider(0:180, default=0, show_value=true))
"""
# ╔═╡ 372907b3-cb05-5e5b-abce-ebe3aa646e8f
md"""
- Each 🧍 = a note waiting. Red line = the minute you're looking at.
- The GPU is only **92% busy** (220 of 240 per hour), yet the line hits 20–30 notes.
"""
# ╔═╡ c5a7981c-dfcc-59f8-b47c-374770d190cc
md"""
*→ A GPU that keeps up on average still built a 30-note line. Why? And how many GPUs do we actually need? First, let's state the problem precisely.*
"""
# ╔═╡ efb6a82b-ca62-521e-8b9f-98658f804bd4
md"""
## The problem, formally
| symbol | meaning | launch day |
|:--|:--|:--|
| ``\lambda`` | **arrival rate**: notes per hour coming in | 220 |
| ``\mu`` | **service rate**: notes per hour **one** GPU can finish | 240 |
| ``c`` | number of GPUs, all pulling from **one shared line** | ? |
| ``W_q`` | average time a note **waits in line** before a GPU picks it up | ? |
**Goal:** the smallest ``c`` with ``W_q \le`` some target (say 10 seconds). Every GPU costs money; every second of waiting costs users.
This is the **M/M/c queue**: arrivals are **M**emoryless, processing times are **M**emoryless, ``c`` servers.
We will find out what "memoryless" means and why anyone would assume it.
"""
# ╔═╡ 35deae72-67fe-5620-8f00-adc13ab88917
md"""
*→ First question: if the GPU keeps up on average, where does the line even come from?*
"""
# ╔═╡ e8a2724f-a775-515b-8e4a-dc0f9cc5e541
md"""
## Why is there a line at all?
On average the GPU keeps up. Turn the two sources of randomness on and off, and watch the line.
Arrivals: $(@bind arr_mode Select(["evenly spaced", "random"], default="evenly spaced")) $(html"  ")
Processing time: $(@bind svc_mode Select(["always 15 s", "random, 15 s on average"], default="always 15 s"))
How busy the GPU is (``\lambda/\mu``): $(@bind u_why Slider(0.5:0.01:0.99, default=0.92, show_value=true))
"""
# ╔═╡ 9c953c3f-07b8-54be-9f26-82e0b2e57ac3
md"""
- **Evenly spaced, always 15 s:** each note finishes before the next arrives. Nobody waits, even at 92% busy.
- **Random:** notes sometimes bunch up or run long. Idle time can't be saved for later, so a line forms.
- **Lines come from randomness, not from being over capacity.**
"""
# ╔═╡ 7987f2ba-3779-5ffc-befa-7f7c96f6fdb8
md"""
*→ So what does "random arrivals" mean, precisely?*
"""
# ╔═╡ 76783a62-4940-5ac5-aa1c-7edd0e8e4025
md"""
## Where "random" comes from: the Poisson distribution
Many users, each with a tiny, independent chance of uploading at any moment → the number of uploads per minute is **Poisson**:
```math
P(k) = \frac{e^{-\lambda}\lambda^{k}}{k!}
```
``P(k)`` = chance of exactly ``k`` uploads in a minute; ``\lambda`` = average per minute.
**Why:** split a minute into ``m`` slots, each with chance ``\lambda/m``. Finer slots → the count matches Poisson. Try it:
Arrivals per minute ``\lambda``: $(@bind λ_pois Slider(0.5:0.5:4, default=3, show_value=true)) $(html"  ")
Slots per minute ``m``: $(@bind n_slots Slider([4, 6, 10, 20, 60, 600, 3600], default=4, show_value=true)) $(html"  ")
$(@bind reroll_pois CounterButton("🎲"))
"""
# ╔═╡ a0a2b245-ea8a-572a-918d-804dd3c680c2
md"""
- **Top:** one minute in ``m`` slots (blue = an upload). **Bottom:** bars = slot model, dots = Poisson.
- Few slots: they disagree (4 slots can't give 5 uploads). More slots: bars land on the dots.
"""
# ╔═╡ 4aaedcea-bf5b-59c0-b5a2-78b478733e62
md"""
*→ Poisson tells us how many notes arrive per minute. Next: how long we wait *between* arrivals, and the property that makes the whole problem solvable.*
"""
# ╔═╡ fd8c6de1-f58d-5933-9b23-21126f2aa09f
md"""
## Exponential gaps and memorylessness
**Gap ``T`` between arrivals is exponential:** no arrival for ``t`` minutes = zero Poisson arrivals, so ``P(T > t) = e^{-\lambda t}``. Average gap ``1/\lambda``.
**Memoryless:** already waited ``s`` minutes? The chance of waiting ``t`` more is the same as from scratch. A gap longer than ``s+t`` is automatically longer than ``s``, so:
```math
P(T > s+t \mid T > s) = \frac{P(T > s+t)}{P(T > s)} = \frac{e^{-\lambda(s+t)}}{e^{-\lambda s}} = e^{-\lambda t} = P(T > t)
```
We assume **processing times** are exponential too (15 s average). A GPU has worked ``s`` seconds on a note: how much longer?
Compare with **Erlang-4**, a more realistic job: 4 random steps in a row, same 15 s average.
Processing time is: $(@bind dist_mem Select(["exponential", "realistic (Erlang-4)"], default="exponential")) $(html"  ")
Already worked ``s`` = $(@bind s_mem Slider(0:1:45, default=0, show_value=true)) seconds
"""
# ╔═╡ c2cee7d4-8ce4-5c9c-85f7-9cbda25fb840
let m = 15.0, s = s_mem
if dist_mem == "exponential"
r = 1 / m
f = t -> r * exp(-r * t)
S = t -> exp(-r * t)
else
k, r = 4, 4 / m
f = t -> r^k * t^(k - 1) * exp(-r * t) / factorial(k - 1)
S = t -> exp(-r * t) * sum((r * t)^j / factorial(j) for j in 0:k-1)
end
g = u -> f(s + u) / S(s)
left = sum(S(s + u) for u in 0:0.05:400) * 0.05 / S(s)
plot(f, 0, 60, color=GRAY, linewidth=5, label="total time for a brand-new note",
xlabel="seconds", ylabel="probability density", ylims=(0, max(0.11, 1.1maximum(g, 0:0.5:60))),
title="expected time left after $(s) s of work: $(round(left, digits=1)) s", size=(760, 330))
plot!(g, 0, 60, color=RED, linestyle=:dash, linewidth=3, label="time left, given it already ran $(s) s")
end
# ╔═╡ c5266f89-4ad2-5bd0-a572-9e32d55b7eb4
md"""
- Exponential: the red curve never moves. Erlang-4: the longer it ran, the sooner it's done.
- Payoff: to predict the future we only need **``n`` = total notes in the system** (waiting + being processed).
"""
# ╔═╡ 01aa8d87-7f26-5287-abb5-62b06fdb1477
md"""
*→ Quick check before we use it.*
"""
# ╔═╡ 14ed8947-fb06-5a9e-9034-c51244e3abde
md"""
## ✋ Checkpoint 1: memorylessness
Uploads are Poisson, **3 per minute** (one every 20 s on average). Nobody has uploaded for **2 minutes**. Expected time until the next upload?
Vote **A, B, C or D**. $(html"  ") $(@bind cp1 CheckBox()) reveal the answer
"""
# ╔═╡ 2b542e50-0bd5-5191-99da-9e7c53ff3d71
if cp1
md"""
- **A: 20 seconds.** ``P(T > 2 + t \mid T > 2) = P(T > t)``: nothing is ever "overdue".
- C is a good *real-world* instinct: maybe it's night and ``\lambda`` dropped. But then it's not Poisson with constant ``\lambda``. More at the end.
"""
else
md""
end
# ╔═╡ 207f41ef-3e21-55c3-9d7f-9a4ce1cc9e0c
cp1 ? md"""
*→ One more tool before we solve anything: a law that holds no matter how random things are.*
""" : md""
# ╔═╡ f8cb1979-1ee2-5281-8cbb-93f8be3bbc20
md"""
## Little's law: ``L = \lambda W``
- ``L`` = average number of notes in the system, ``\lambda`` = arrival rate, ``W`` = average time a note spends there.
- Holds for **any** randomness. Proof: count one area two ways.
Show the first $(@bind T_little Slider(2:1:20, default=6, show_value=true)) minutes of launch day (1 GPU)
"""
# ╔═╡ 6f7763da-fbcb-5bae-be69-f1c03dd8612b
md"""
- **Bar length** = one note's time in the system (minutes). All bars together = total **note-minutes**.
- ``N(t)`` = notes in the system at time ``t``; ``T`` = window length (minutes).
- A vertical slice at time ``t`` crosses ``N(t)`` bars, so **total bar length = area under ``N(t)``**:
```math
\underbrace{L \cdot T}_{\text{area, counted by time}} \;=\; \underbrace{(\lambda T)\cdot W}_{\text{area, counted by note}}
\quad\Longrightarrow\quad L = \lambda W
```
Also: ``\rho = \dfrac{\lambda}{c\mu}`` (**utilization**) = fraction of time each GPU works. If ``\rho \ge 1``, the line grows forever.
"""
# ╔═╡ 722b0fb3-0b47-5903-b8f4-f02935812fb1
md"""
*→ We now have both tools: memorylessness lets us track just ``n`` (the total number of notes in the system), and Little's law turns counts into times. Let's solve the one-GPU case.*
"""
# ╔═╡ 1ce703b6-c1a8-53fd-b1cb-da12be56e94e
md"""
## M/M/1: a random walk on one number
``n`` = total notes in the system (waiting + being processed). Arrivals push ``n`` up at rate ``\lambda``; the GPU pulls it down at rate ``\mu``.
Show the arrows as: $(@bind view_mm1 Select(["rates", "probabilities of the next move"]))
"""
# ╔═╡ 1d811f54-83bf-5e83-97ee-1a8c54e5f905
if view_mm1 == "rates"
md"Each arrow is a **rate**: how often that move happens per minute. The balance argument uses rates."
else
md"""
- **Traditional Markov chain:** each arrow = chance it's the **next** move = its rate ÷ total rate out.
- From ``n \ge 1``: up ``\frac{\lambda}{\lambda+\mu}``, down ``\frac{\mu}{\lambda+\mu}`` (launch day: 0.48 / 0.52). From 0: up, probability 1.
"""
end
# ╔═╡ 959a3a7b-7987-5cb0-bfbd-ea95560b8a53
md"""
``p_n`` = fraction of time there are exactly ``n`` notes in the system (so ``p_0`` = fraction of time it's empty). ``\rho = \lambda/\mu``.
**Where ``p_n`` comes from.** In the long run the walk crosses each gap as often rightward as leftward:
```math
\underbrace{\lambda\,p_n}_{\text{rightward}} = \underbrace{\mu\,p_{n+1}}_{\text{leftward}}
\;\Rightarrow\; p_{n+1} = \rho\,p_n
\;\Rightarrow\; p_n = p_0\,\rho^{\,n},
\qquad \textstyle\sum_n p_n = 1 \;\Rightarrow\; p_0 = 1-\rho
```
How busy the GPU is, ``\rho``: $(@bind ρ_mm1 Slider(0.1:0.05:0.95, default=0.5, show_value=true))
"""
# ╔═╡ 412a6b56-ecfc-5334-bab4-c01ccdaca9ba
md"""
- Bars: ``p_n`` from the formula. Dots: a simulation. They match.
- As ``\rho`` grows the bars flatten: the GPU is rarely empty, and long lines become normal.
"""
# ╔═╡ 9f5305f5-d1c8-50d4-b22e-792175a42862
md"""
*→ Long lines become normal as ``\rho \to 1``. How fast does the **wait** grow?*
"""
# ╔═╡ b184ca0b-a580-5259-a958-02aa80b1a75a
md"""
## The hockey stick
- ``L`` = average notes in the system, ``W`` = average time in the system, ``W_q`` = average **wait in line**, ``1/\mu`` = processing time (15 s).
- ``\frac{\rho}{1-\rho}`` is the **average** of ``p_n`` from the last slide.
```math
\begin{aligned}
L &= \sum_n n\,p_n = \frac{\rho}{1-\rho} && \text{(the average of } p_n\text{)}\\
W &= \frac{L}{\lambda} = \frac{1}{\mu-\lambda} && \text{(Little)}\\
W_q &= W - \frac{1}{\mu} = \frac{1}{\mu}\cdot\frac{\rho}{1-\rho} && \text{(minus your own processing)}
\end{aligned}
```
How busy the GPU is, ``\rho``: $(@bind ρ_hockey Slider(0.05:0.01:0.99, default=0.5, show_value=true))
"""
# ╔═╡ 17710779-ef2e-5d73-9304-4ac69133b882
let ρ = ρ_hockey
f = x -> x / (1 - x)
plot(f, 0, 0.975, color=BLUE, label=false, xlims=(0, 1), ylims=(0, 40),
xlabel="utilization ρ", ylabel="wait ÷ processing time",
title="at $(round(Int, 100ρ))% busy a note waits $(round(f(ρ), digits=1))× its own processing time (= $(round(15f(ρ), digits=0)) s)",
size=(760, 330), xticks=0:0.1:1)
scatter!([220 / 240], [f(220 / 240)], color=ORANGE, markersize=6, label="launch day (92%)")
scatter!([ρ], [min(f(ρ), 40)], color=RED, markersize=9, label=false)
end
# ╔═╡ 510c27d9-3092-5be1-b6c0-68053deb5f04
md"""
*→ How sensitive is the wait to a little more traffic?*
"""
# ╔═╡ f9339ea6-21eb-5ff3-808a-e0694db85c71
md"""
## ✋ Checkpoint 2: the hockey stick
Traffic grows by the same **5 percentage points** in two situations. Which one makes the average wait grow more?
Vote **A, B, C or D**. $(html"  ") $(@bind cp2 CheckBox()) reveal the answer
"""
# ╔═╡ 082ebccc-f5dc-53d3-bf84-2864116bd91d
if cp2
md"""
- **B.** 50% → 55%: wait goes 1× → 1.2×. 90% → 95%: 9× → 19×.
- The slope ``\dfrac{1}{(1-\rho)^2}`` is 4 at 50% busy, 100 at 90%. **The last 10% of utilization is the expensive 10%.**
"""
else
md""
end
# ╔═╡ f036ed59-e7b4-5edb-956c-e56844c43a3b
cp2 ? md"""
*→ On launch day we were on the steep part with one GPU. What happens with ``c`` GPUs?*
""" : md""
# ╔═╡ e5f6b838-1efc-584a-a614-bbf48ecc030e
md"""
## More GPUs: the M/M/c queue
With ``c`` GPUs the walk goes down at rate ``\min(n, c)\,\mu``, because only busy GPUs finish notes.
GPUs ``c``: $(@bind c_mmc Slider(1:6, default=2, show_value=true)) $(html"  ") Notes per hour ``\lambda``: $(@bind λ_mmc Slider(20:10:1400, default=220, show_value=true))
Show the arrows as: $(@bind view_mmc Select(["rates", "probabilities of the next move"]))
"""
# ╔═╡ a5f3be65-4476-5ce4-8a4a-9144586ae5ba
if view_mmc == "rates"
md""
else
md"""
Each arrow = chance it's the **next** move. With ``k`` GPUs busy: up ``\frac{\lambda}{\lambda + k\mu}``, down ``\frac{k\mu}{\lambda + k\mu}``.
"""
end
# ╔═╡ 43ec7b13-56f8-5325-832c-0bcd4b62adbc
md"""
**Where Erlang C comes from.** Same balance argument.
- ``a = \lambda/\mu`` = GPUs' worth of work arriving; ``\rho = a/c`` = fraction of time each GPU works.
- ``p_c`` = chance of exactly ``c`` notes; ``C(c,a)`` = chance a new note waits (all busy); ``L_q`` = average line.
```math
\lambda\,p_n = \min(n{+}1,\,c)\,\mu\,p_{n+1}
\;\Rightarrow\;
p_n = \begin{cases} p_0\,\dfrac{a^n}{n!} & n \le c \\[6pt] p_c\,\rho^{\,n-c} & n \ge c \;\;\text{(geometric again)}\end{cases}
```
```math
C(c,a) = P(\text{all } c \text{ busy}) = \sum_{n \ge c} p_n = \frac{p_c}{1-\rho},
\qquad
L_q = C(c,a)\,\frac{\rho}{1-\rho}
\;\xrightarrow{\;\text{Little}\;}\;
W_q = \frac{C(c,a)}{c\mu - \lambda}
```
- ``L_q`` = (chance all GPUs are busy) × (average line, given all busy).
- Once all are busy, the line is geometric again, like ``p_n`` in M/M/1, so its average is ``\frac{\rho}{1-\rho}``.
"""
# ╔═╡ 06fc262f-d17e-5d7a-81b3-98bd09dbb805
md"""
- One curve per number of GPUs (gray = fewer). Red dot = current setting.
- Each extra GPU adds another hockey stick, further right.
"""
# ╔═╡ 51f975d4-8967-5a70-b2b9-df1e89daf109
md"""
*→ Each extra GPU pushes the hockey stick further right. What does that mean for really big pools?*
"""
# ╔═╡ 0c47dc36-4e4e-5083-b859-270736b0643d
md"""
## Big pools can run hot
Every GPU **equally busy** (same ``\rho``); grow the pool from 1 to 30 GPUs. What happens to the wait?
- **Left:** average wait ÷ processing time.
- **Right:** at a random moment, % of GPUs busy, for 5 vs 50 GPUs (red = all busy, a new note waits).
How busy each GPU is: $(@bind u_pool Slider(0.5:0.01:0.98, default=0.8, show_value=true))
"""
# ╔═╡ 4a2c84e8-10fe-5754-bb57-a003258f518f
md"""
**Takeaway:** same utilization, bigger shared pool, far less waiting.
- A big pool can run its GPUs **hotter** (busier, cheaper per note) for the same wait.
- Twice the traffic does *not* need twice the GPUs: spare GPUs absorb random bursts, and bursts grow slower than traffic (1000 notes/hour: 6 GPUs; 2000: only 10).
**Why (right):** both pools are equally busy *on average*, but it fluctuates.
- Small pool: one extra note = 20% of capacity, so it often hits 100%.
- Big pool: bunched near its average, rarely hits 100%.
- On average ``a = \lambda/\mu`` GPUs are busy; fluctuations are about ``\sqrt a``, small *relative to the pool* when ``a`` is big.
- So spare capacity grows like ``\sqrt a``, not ``a``: **square-root staffing**, ``c \approx a + \beta\sqrt a`` (``\beta`` = safety factor, 1–3).
"""
# ╔═╡ 7c46256a-c93d-592d-a11b-e3eb3e7c9d65
md"""
*→ Quick check: does pooling help even when nothing else changes?*
"""
# ╔═╡ 55741125-9f43-578d-8ed8-fce176fb6b45
md"""
## ✋ Checkpoint 3: merging two pools
Two offices, each with **5 GPUs at 80% busy** and its own line. They merge into **one pool of 10 GPUs**: same traffic, still 80% busy. The average wait:
Vote **A, B, C or D**. $(html"  ") $(@bind cp3 CheckBox()) reveal the answer
"""
# ╔═╡ 67bfef08-1706-5c8b-b321-805738a100e7
cp3 ? md"""
*→ We now have everything we need to answer the investor.*
""" : md""
# ╔═╡ 4a725500-a83a-5b14-9f31-7f83b1b48d75
md"""
## Answering the investor 💸
Notes per hour: $(@bind λ_inv Slider(50:50:5000, default=1000, show_value=true)) $(html"  ")
Seconds per note on one GPU: $(@bind sec_inv Slider(5:1:60, default=15, show_value=true))
Target average wait (seconds): $(@bind target_inv Slider(1:1:120, default=10, show_value=true)) $(html"  ")
GPU price (dollars per hour): $(@bind price_inv Slider(0.5:0.25:5, default=2.0, show_value=true))
Budget (dollars per month): $(@bind budget_inv Slider(1000:500:60000, default=10000, show_value=true))
"""
# ╔═╡ f71e769f-ddc2-59ec-9381-910faeba7820
md"""
*→ Problem solved... until the product changes.*
"""
# ╔═╡ d63f94b6-074a-5745-8110-6f29bff71a9b
md"""
*→ Why is it so hard? Look at what we would have to keep track of.*
"""
# ╔═╡ 349f4eab-d29a-5097-8d52-25dfa63f8185
md"""
## Why it's hard: a random walk in ``k`` dimensions
- One GPU: the state was one number, ``n``.
- ``k`` branches: the state is **every branch's line length**: ``(n_1)``, ``(n_1, n_2)``, ``(n_1, n_2, n_3)``.
- The dot is the state; the line is its path.
- **The link to Scribbl v2:** for one GPU we got the wait from ``p_n``, the long-run chance of each state. Here we'd need the chance of every combination ``(n_1, n_2, n_3)``, the ``p_n`` of this walk, and that's what has no formula.
Branches ``k``: $(@bind k_walk Slider(1:3, default=1, show_value=true)) $(html"  ")
How busy each branch is: $(@bind ρ_walk Slider(0.5:0.05:0.9, default=0.8, show_value=true)) $(html"  ")
$(@bind reroll_walk CounterButton("🎲 new walk"))
Events so far (drag to watch it move): $(@bind step_walk Slider(0:5:600, default=150, show_value=true))
"""
# ╔═╡ d2a08a62-6acd-5a0f-99cb-0a615375053e
md"""
- New note: the dot moves **diagonally** (every line +1). Finished note: back along **one** axis.
- So the lines tend to rise and fall **together**. Remember that for later.
- **1 branch:** a walk on a line = M/M/1, solved: ``p_n = (1-\rho)\rho^n``.
- **2 branches:** a walk on a grid, solved in 1984 (Flatto & Hahn) with math that only works in 2-D.
- **3 branches:** a walk in 3-D, **no exact formula known**, but easy to simulate.
"""
# ╔═╡ 0022c931-6091-5e3c-ab6a-2ee6f0c6a9f6
md"""
*→ First question: what does the GPU stage pass on to the next stage?*
"""
# ╔═╡ 52591f69-e8ff-5873-9dbf-3c0a4775d84b
md"""
## ✋ Checkpoint 4: what leaves the GPU stage?
Notes arrive at **100 per hour** to a GPU stage that can handle up to **125 per hour**, so it keeps up (80% busy). In the long run, how many notes per hour **leave** it?
Vote **A, B, C or D**. $(html"  ") $(@bind cp4 CheckBox()) reveal the answer
"""
# ╔═╡ ffad597d-1e28-5a31-8413-1ac8f3505f0d
if cp4
md"""
GPUs: $(@bind c_burke Slider(1:4, default=1, show_value=true)) $(html"  ")
How busy: $(@bind u_burke Slider(0.1:0.05:0.95, default=0.8, show_value=true)) $(html"  ")
Processing time: $(@bind svc_burke Select(["random (exponential)", "always the same"]))
"""
else
md""
end
# ╔═╡ c739df48-4093-59c9-93a3-4e80d0a14232
if cp4
md"""
- **A: 100.** It keeps up, so what goes in comes out. (125/hour only while busy, 80% of the time: 0.8 × 125 = 100.)
- **Surprise, Burke's theorem:** the gaps between departures are **exponential** too, like the arrivals (histogram).
- *Why:* each step up is matched by a step down, so the walk looks the same played **backwards**, and backwards, departures are arrivals.
- **So stages in a row are each their own M/M/c, and the times just add.** ("Always the same" breaks it: it needs memorylessness.)
"""
else
md""
end
# ╔═╡ 38882797-5fb6-5a13-8bb7-e12a8f64c8ec
cp4 ? md"""
*→ Stages **in a row** are fine. The fork is where things get hard.*
""" : md""
# ╔═╡ 404316e0-2955-53b4-bf65-cc10de17cb1b
md"""
## ✋ Checkpoint 5: waiting for the slowest
A note needs **all three** branches done. Each takes an exponential time, mean **1 minute**, independently. Average time until **all three** are done?
Vote **A, B, C or D**. $(html"  ") $(@bind cp5 CheckBox()) reveal the answer
"""
# ╔═╡ 56edf76d-5e33-5be9-aad7-80a6c86e8ca4
if cp5
md"""Branches ``k``: $(@bind k_max Slider(1:10, default=3, show_value=true))"""
else
md""
end
# ╔═╡ a06b4438-0ec9-51b3-9c60-33cf000b718f
if cp5
md"""
- **B: between 1 and 3.** More than 1 (you wait for the slowest); less than 3 (they run at the same time).
- Exactly **1.83 min**: a race that memorylessness restarts after each finisher:
```math
E[\max] = \underbrace{\tfrac13}_{\text{first of 3 done}} + \underbrace{\tfrac12}_{\text{first of other 2}} + \underbrace{1}_{\text{last one}} = H_3 \approx 1.83
```
- In general ``H_k = 1 + \tfrac12 + \dots + \tfrac1k \approx \ln k + 0.58``: grows, but slowly.
- *Refresher:* the first of ``k`` exponentials (rate 1) finishes at rate ``k``: ``P(\min > t) = e^{-kt}``.
"""
else
md""
end
# ╔═╡ bd7baa0d-0fb3-54d8-9084-3b1ef4571fc0
cp5 ? md"""
*→ That assumed the three branches are independent. Are they?*
""" : md""
# ╔═╡ 4cbe2db9-bb0b-5df7-a3de-e582626ad39e
md"""
## ✋ Checkpoint 6: the branches are not independent
- All branches see the **same** arrivals: a burst jams every branch at once.
- Each dot = one note: its time in branch 1 (x) vs branch 2 (y).
How busy each branch is: $(@bind u_corr Slider(0.05:0.05:0.95, default=0.8, show_value=true))
"""
# ╔═╡ 4cc8885f-b4fe-59e9-b57e-aef0625942a0
md"""
Branch times are **positively correlated**. If we compute the average slowest time **pretending they're independent** (the ``H_k`` trick), we get:
Vote **A, B, C or D**. $(html"  ") $(@bind cp6 CheckBox()) reveal the answer
"""
# ╔═╡ b2b064e4-e88c-54e3-9856-857262bd6703
if cp6
md"""
- **C: too high.** Compare the extremes:
- Perfectly correlated: all finish together, so slowest = one branch, ``\frac{1}{\mu-\lambda}``.
- Independent: ``\frac{H_k}{\mu-\lambda}``.
- Positive correlation is in between, so **independence overestimates**. That gives us **two bounds for free**.
"""
else
md""
end
# ╔═╡ 2b0d4c11-0330-52f6-9b5e-370b9562bca5
cp6 ? md"""
*→ So "one branch alone" is too low and "independent branches" is too high. How good are those bounds, and can we do better?*
""" : md""
# ╔═╡ fdcd479d-108e-50d9-8adc-7964c4bd7f65
md"""
## So how do we model it?
Let's test the two bounds against a simulation of the real thing, plus a published approximation.
- ``k`` branches, one worker each, 1 time unit per note on average, same Poisson stream.
- ``\rho`` = how busy each branch is. ``H_k = 1 + \tfrac12 + \dots + \tfrac1k`` (Checkpoint 5).
- ``\frac{1}{\mu-\lambda}`` = average time in one branch (in M/M/1 it's exponential with rate ``\mu-\lambda``).
Branches ``k``: $(@bind k_models Slider(2:8, default=3, show_value=true))
Show: $(@bind shown_models MultiCheckBox(["ignore the join", "assume independent branches", "Nelson–Tantawi approximation", "simulation"]))
"""
# ╔═╡ c94149c5-35f3-5ff9-a2ab-2519948a984c
md"""
**How the simulation works (red dots):**
- 200,000 random notes (Poisson arrivals, exponential processing), each sent into all ``k`` branches.
- Each branch: one line, one worker, first come first served. A note is done when its **slowest** branch finishes.
- Average over all notes (skip the first 10% while lines fill up). No formula, just play it forward and measure.
| approach | formula | verdict |
|:--|:--|:--|
| ignore the join (perfect correlation) | ``\frac{1}{\mu-\lambda}`` | too optimistic: a **lower bound** |
| assume independent branches (Checkpoint 6) | ``\frac{H_k}{\mu-\lambda}`` | too pessimistic: an **upper bound** |
| Nelson–Tantawi | ``\Big[\tfrac{H_k}{H_2}+\tfrac{4}{11}\big(1-\tfrac{H_k}{H_2}\big)\rho\Big]\tfrac{12-\rho}{8}\cdot\tfrac{1}{\mu-\lambda}`` | exact-ish for ``k=2``, a fit to simulations beyond |
| simulate | no formula | always works, but gives no insight |
- The simulation always lands **between the two bounds**: two one-line formulas trap the answer.
- The gap widens with busier or more branches. Then use Nelson–Tantawi, or simulate.
"""
# ╔═╡ 5f48c35f-feb6-5be0-986c-3d340ea09f82
md"""
*→ Now let's put the GPU stage and the fork back together.*
"""
# ╔═╡ edb2c1d7-b83a-5e44-bd4a-4fc211e82762
md"""
## Putting it together: Scribbl v2, end to end
- By Burke (Checkpoint 4): total time = GPU stage + three branches. Just add them.
- GPU stage: M/M/c. Branches: our bounds. The question: **where does the time go?**
Notes per hour: $(@bind λ_e2e Slider(60:10:900, default=300, show_value=true)) $(html"  ")
GPUs: $(@bind c_e2e Slider(1:8, default=2, show_value=true)) $(html"  ")
GPU seconds per note: $(@bind gpu_e2e Slider(5:1:40, default=15, show_value=true))
Seconds per note in each branch. Summarize: $(@bind s1_e2e Slider(1:0.5:15, default=7, show_value=true)) $(html"  ")
Flashcards: $(@bind s2_e2e Slider(1:0.5:15, default=9, show_value=true)) $(html"  ")
Translate: $(@bind s3_e2e Slider(1:0.5:15, default=10, show_value=true))
"""
# ╔═╡ 51975da8-4e7a-5227-bdb1-4d711d3dff87
e2e = let λ = λ_e2e / 60, μg = 60 / gpu_e2e, c = c_e2e, μb = 60 ./ [s1_e2e, s2_e2e, s3_e2e]
utils = vcat(λ / (c * μg), λ ./ μb)
(; λ, μg, c, μb, utils, stable=maximum(utils) < 1)
end;
# ╔═╡ e6226ef6-3034-554c-b599-d1ee0e6e39f9
let names = ["GPU stage", "summarize", "flashcards", "translate"], u = e2e.utils, worst = argmax(e2e.utils)
cells = join(["<td style='padding:4px 14px;border:1px solid #cbd5e1;$(i == worst ? "background:#fee2e2;font-weight:700" : "")'>$(names[i])<br>$(round(Int, 100u[i]))% busy</td>" for i in 1:4])
warn = !e2e.stable ? "<p style='font-size:1.2em'>⚠️ <b>$(names[worst])</b> is over 100% busy: its line grows forever.</p>" :
maximum(u) > 0.9 ? "<p style='color:#64748b'>Above 90% busy the simulation needs a very long run to settle, so it wobbles from run to run.</p>" : ""
HTML("<table style='border-collapse:collapse'><tr>$cells</tr></table>$warn")
end
# ╔═╡ 3d03290b-56f5-5e27-96b2-d2c748024d2c
md"""
- Each bar: average time from upload to ready, in the order a note lives it: wait for a GPU, get read, then the three jobs (until all are done).
- Top two bars: our two bounds. Bottom bar: simulation. Red cell in the table: the **bottleneck** (busiest stage).
**A usable formula for the whole pipeline** (the "independent branches" bar, about 4% high at the defaults):
```math
\text{total} \;\approx\; \underbrace{W_q(\lambda, \mu_{\text{GPU}}, c) + \frac{1}{\mu_{\text{GPU}}}}_{\text{GPU stage: Erlang C, exact}} \;+\; \underbrace{E\big[\max(R_1, R_2, R_3)\big]}_{\text{3 jobs, as if independent}}, \qquad R_i \sim \text{Exp}(\mu_i - \lambda)
```
- ``R_i`` = time a note spends in job ``i`` (waiting + processing). It's exponential with rate ``\mu_i - \lambda`` (the job's spare capacity), so its average is ``\frac{1}{\mu_i - \lambda}``.
**How we got it:**
- Burke: the stages just add (Checkpoint 4).
- GPU stage: M/M/c, exact.
- Each job: an M/M/1, whose time is exponential with rate ``\mu_i - \lambda``.
- Pretend the jobs are independent: slightly too high (Checkpoint 6).
**What do we tell the investors about v2?**
- At 300 notes/hour, **2 GPUs are enough**: going to 4 only cuts the total from 1.6 to 1.5 min.
- Spend on **translation**, the bottleneck: 30% faster (10 s → 7 s) cuts the total to 1.1 min.
- "How many GPUs?" is the wrong question now. Ask: **which stage is the bottleneck?**
"""
# ╔═╡ 5446014a-af40-568b-979f-ee8722788d09
md"""
*→ This model still simplifies a lot.*
"""
# ╔═╡ 626ccda4-6993-57e2-a51a-3c51c052bf70
md"""
## What I left out (and what I'd try next)
- **Workers of different speeds.** Adding a slow laptop to a fast GPU can make the average *worse*. Fix: use it only when the line is long.
- **Bursty arrivals.** More uploads at 9 am than 3 am: ``\lambda`` changes during the day.
- **Non-exponential processing.** Pollaczek–Khinchine: ``W_q = \dfrac{1 + C_s^2}{2}\cdot W_q^{\text{M/M/1}}`` (``C_s`` = spread of processing time). Fixed times (``C_s = 0``) halve the wait.
- **Failures:** workers disconnect, notes time out and get retried.
"""
# ╔═╡ d075f692-473a-5d6c-ade6-0a8ed720b287
md"""
## Takeaways
1. Lines come from **randomness**, not from being over capacity.
2. The wait grows like ``\dfrac{\rho}{1-\rho}``: the last 10% of utilization is the expensive 10%.
3. A bigger shared pool can run hotter for the same wait.
4. Stages **in a row** add up (Burke). Parallel branches don't: you wait for the slowest, and they're correlated. So: bounds, approximations, simulation.
**Not just GPUs.** Anything with arrivals and servers works the same way:
- How many call-center agents, ER doctors, checkout lanes, or web servers? (M/M/c, Erlang C)
- One shared line beats separate lines: banks, airports, cloud pools.
- "Wait for all parts": a web page calling several services, a hospital waiting on multiple test results (fork-join).
**Question for you:** we assumed uploads are Poisson. When is that a bad assumption, and how would you check?
"""
# ╔═╡ 5daf03b1-b5e5-54b8-a080-4a3d4f0d4d89
md"""
# Thank you! Questions?
"""
# ╔═╡ 6f8f3b6c-2af9-5b0e-be3a-d56d0ef2888e
md"""
# Appendix: the code behind the slides
Everything is computed live. These are the only pieces.
"""
# ╔═╡ 6134dde2-fbaf-581e-9621-109c380552e9
"Arrival times of a Poisson process with rate λ on [0, T]: add up exponential gaps."
function poisson_arrivals(rng, λ, T)
ts = Float64[]
t = randexp(rng) / λ
while t ≤ T
push!(ts, t)
t += randexp(rng) / λ
end
ts
end
# ╔═╡ fa722cc8-1703-5387-9524-9db7e75e3d92
"""
One shared line, `c` identical servers, first come first served.
`arrival` must be sorted. Each note goes to whichever server frees up first.
"""
function simulate_queue(arrival, service, c)
n = length(arrival)
free_at = zeros(c)
start, depart = similar(arrival), similar(arrival)
server = zeros(Int, n)
for i in 1:n
k = argmin(free_at)
start[i] = max(arrival[i], free_at[k])
depart[i] = start[i] + service[i]
free_at[k] = depart[i]
server[i] = k
end
(; arrival, start, depart, server, wait=start .- arrival, sojourn=depart .- arrival)
end
# ╔═╡ c8d8c9c2-2d49-55a3-a4ed-54f75f0b2776
sim_hook = let rng = Xoshiro(16 + replay_hook)
λ, μ = 220 / 60, 240 / 60 # notes per minute
arr = poisson_arrivals(rng, λ, 180.0)
simulate_queue(arr, randexp(rng, length(arr)) ./ μ, c_hook)
end;
# ╔═╡ 8683bc88-0859-597a-94c4-fe1f40fe4f19
let s = sim_hook, t = t_hook
idx = eachindex(s.arrival)
waiting = count(i -> s.arrival[i] ≤ t < s.start[i], idx)
busy = [any(i -> s.server[i] == k && s.start[i] ≤ t < s.depart[i], idx) for k in 1:c_hook]
nxt = findfirst(>(t), s.arrival)
wait_now = nxt === nothing ? 0.0 : s.wait[nxt]
arrived = count(≤(t), s.arrival)
angry = count(i -> s.arrival[i] ≤ t && min(s.start[i], t) - s.arrival[i] > 3, idx)
people = waiting ≤ 50 ? "🧍"^waiting : "🧍"^50 * " <b>+$(waiting - 50)</b>"
gpus = join(["<div style='display:inline-block;width:92px;margin:4px;padding:8px;border-radius:10px;text-align:center;background:$(b ? "#dbeafe" : "#f1f5f9");border:2px solid $(b ? BLUE : GRAY)'>GPU $k<br>$(b ? "📝 busy" : "💤 idle")</div>" for (k, b) in enumerate(busy)])
stat(label, value) = "<div style='display:inline-block;margin-right:28px'><div style='font-size:0.85em;color:#64748b'>$label</div><div style='font-size:1.5em;font-weight:600'>$value</div></div>"
HTML("""
<div style='font-family:system-ui,sans-serif'>
<div>$gpus</div>
<div style='margin:8px 0 12px 0;min-height:32px;font-size:1.3em;line-height:1.1;word-break:break-all'>Line: $(waiting == 0 ? "<span style='color:#64748b;font-size:0.8em'>nobody waiting</span>" : people)</div>
$(stat("in line right now", waiting))
$(stat("upload now and you wait", "$(round(wait_now, digits=1)) min"))
$(stat("😡 users who waited over 3 min", "$angry of $arrived"))
</div>""")
end
# ╔═╡ 9a20755d-9d74-5861-97ff-647a5e27164f
let T = T_little
rng = Xoshiro(16)
arr = poisson_arrivals(rng, 220 / 60, 40.0)
s = simulate_queue(arr, randexp(rng, length(arr)) ./ 4.0, 1)
idx = findall(<(T), s.arrival)
n = length(idx)
ends = min.(s.depart[idx], T)
A = sum(ends .- s.arrival[idx])
top = plot(xlims=(0, T), ylims=(0, n + 1), yflip=true, legend=false, ylabel="note #",
title="one bar per note: total length $(round(A, digits=1)) note-minutes")
for (j, i) in enumerate(idx)
plot!(top, [s.arrival[i], ends[j]], [j, j], color=BLUE, linewidth=4)
end
tg = range(0, T, length=1000)
Ns = [count(j -> s.arrival[idx[j]] ≤ t < ends[j], 1:n) for t in tg]
bot = plot(tg, Ns, seriestype=:steppost, fillrange=0, fillalpha=0.3, fillcolor=ORANGE,
color=ORANGE, xlims=(0, T), legend=false, xlabel="minutes", ylabel="N(t)",
title="N(t): area $(round(A, digits=1)) note-minutes, L = area/T = $(round(A / T, digits=2)) notes")
plot(top, bot, layout=grid(2, 1, heights=[0.6, 0.4]), size=(760, 500))
end
# ╔═╡ f45695df-828e-5807-b66e-ebd808e1ebf4
if cp4
let c = c_burke, λ = u_burke * c_burke, n = 60_000
arr = cumsum(randexp(Xoshiro(41), n) ./ λ)
svc = svc_burke == "always the same" ? ones(n) : randexp(Xoshiro(42), n)
s = simulate_queue(arr, svc, c)
gaps = diff(sort(s.depart))[n÷10:end]
cv = std(gaps) / mean(gaps)
gmax = 4 / λ
histogram(gaps, normalize=:pdf, bins=range(0, gmax, length=40), color=BLUE, alpha=0.55,
linewidth=0, label="gaps between notes leaving the GPU stage", xlims=(0, gmax),
xlabel="gap", ylabel="density", size=(760, 280),
title="spread of the gaps (std ÷ mean) = $(round(cv, digits=2)) (exponential = 1)")
plot!(t -> λ * exp(-λ * t), 0, gmax, color=RED, label="exponential, same rate λ as the arrivals")
end
else
md""
end
# ╔═╡ 30c76f1e-19f3-5a74-a3a2-77aa8e610e8f
"Number of notes waiting in line, as a step function `(times, counts)`."
function line_length(s)
w = s.wait .> 0
ts = vcat(0.0, s.arrival[w], s.start[w])
d = vcat(0, fill(1, count(w)), fill(-1, count(w)))
p = sortperm(ts)
ts[p], cumsum(d[p])
end
# ╔═╡ 3e4688b1-fc01-53ad-8fef-596e9220cf57
let (ts, q) = line_length(sim_hook)
plot(ts, q, seriestype=:steppost, color=BLUE, label=false, xlims=(0, 180),
ylims=(0, max(5, maximum(q) + 1)), xlabel="minutes since launch",
ylabel="people in line", size=(760, 250))
vline!([t_hook], color=RED, label=false, linewidth=2)
end
# ╔═╡ f8382513-b2c9-5fe3-b98f-6c6432df8871
let μ = 4.0, λ = u_why * μ, T = 180.0
arr = arr_mode == "random" ? poisson_arrivals(Xoshiro(3), λ, T) : collect(1/λ:1/λ:T)
svc = svc_mode == "always 15 s" ? fill(1 / μ, length(arr)) : randexp(Xoshiro(4), length(arr)) ./ μ
s = simulate_queue(arr, svc, 1)
ts, q = line_length(s)
plot(ts, q, seriestype=:steppost, color=BLUE, label=false, xlims=(0, T),
ylims=(0, max(5, maximum(q) + 1)), xlabel="minutes", ylabel="people in line",
title="one GPU, $(round(Int, 100u_why))% busy: average wait $(round(Int, 60mean(s.wait))) s, longest line $(maximum(q))",
size=(760, 300))
end
# ╔═╡ 7829298d-2335-5600-afaa-92be8adf787d
"Fraction of time with exactly n = 0..nmax notes in the system."
function time_in_state(s, nmax)
ts = vcat(s.arrival, s.depart)
d = vcat(fill(1, length(s.arrival)), fill(-1, length(s.depart)))
p = sortperm(ts)
frac = zeros(nmax + 1)
N, tprev = 0, 0.0
for j in p
N ≤ nmax && (frac[N+1] += ts[j] - tprev)
N += d[j]
tprev = ts[j]
end
frac ./ tprev
end
# ╔═╡ a72c7db8-5ce7-5691-a960-dd4ef3aa54e9
let ρ = ρ_mm1, N = 15
arr = cumsum(randexp(Xoshiro(21), 200_000) ./ ρ)
s = simulate_queue(arr, randexp(Xoshiro(22), length(arr)), 1)
frac = time_in_state(s, N)
ns = 0:N
bar(ns, (1 - ρ) .* ρ .^ ns, color=BLUE, alpha=0.55, linewidth=0, label="theory (1−ρ)ρⁿ",
xlabel="notes in the system, n", ylabel="fraction of time", xticks=ns, ylims=(0, 0.92),
title="average notes in system: theory ρ/(1−ρ) = $(round(ρ/(1-ρ), digits=2)), simulation $(round(sum(s.sojourn)/s.depart[end], digits=2))",
size=(760, 320))
scatter!(ns, frac, color=RED, markersize=6, label="simulation (200,000 notes)")
end
# ╔═╡ 9ad53e52-4d84-52c8-9b96-13023b517eb5
"Binomial(n, p) probabilities for k = 0..K, by the ratio P(k+1)/P(k) (no huge factorials)."
function binom_pmf(n, p, K)
p == 1 && return [k == n ? 1.0 : 0.0 for k in 0:K]
out = zeros(K + 1)
P = (1 - p)^n
for k in 0:K
out[k+1] = k ≤ n ? P : 0.0
P *= (n - k) / (k + 1) * p / (1 - p)
end
out
end
# ╔═╡ d10587e6-fd4f-5242-aca3-f94f95f4467d
"Poisson(λ) probabilities for k = 0..K."
function pois_pmf(λ, K)
out = zeros(K + 1)
P = exp(-λ)
for k in 0:K
out[k+1] = P
P *= λ / (k + 1)
end
out
end
# ╔═╡ f61decbf-3652-53df-a760-35b65783f278
let n = n_slots, λ = λ_pois, p = λ / n
hits = rand(Xoshiro(11 + reroll_pois), n) .< p
strip = plot(xlims=(0, 1), ylims=(0, 1), yticks=false, xticks=false, legend=false,
grid=false, title="one simulated minute: $(count(hits)) arrivals")
if n ≤ 60
for i in 1:n
plot!(strip, Shape([(i-1)/n, i/n, i/n, (i-1)/n] .+ [0.1, -0.1, -0.1, 0.1] ./ n, [0.15, 0.15, 0.85, 0.85]),
fillcolor=hits[i] ? BLUE : :white, linecolor=GRAY, linewidth=1)
end
else
vline!(strip, (findall(hits) .- 0.5) ./ n, color=BLUE, linewidth=2)
end
ks = 0:10
bp, pp = binom_pmf(n, p, 10), pois_pmf(λ, 10)
pm = bar(ks, bp, color=BLUE, alpha=0.55, linewidth=0, ylims=(0, 1.15max(maximum(bp), maximum(pp))),
label="slot model: $n slots, chance $(round(p, digits=4)) each",
xlabel="arrivals in one minute (k)", ylabel="probability", xticks=ks)
scatter!(pm, ks, pp, color=RED, markersize=7, label="Poisson formula")
plot(strip, pm, layout=grid(2, 1, heights=[0.22, 0.78]), size=(760, 430))
end
# ╔═╡ 57d1bf91-2cc8-523f-942a-42df50029224
"""
Erlang B by its recursion, which avoids computing aⁿ and n! separately (they overflow
for big pools). `a = λ/μ` is the offered load.
"""
function erlang_b(c::Int, a::Real)
b = 1.0
for n in 1:c
b = a * b / (n + a * b)
end
b
end
# ╔═╡ 97ecf5b5-d7f3-5fb6-9c76-7fb0de2d3789
"Erlang C: probability that a new arrival finds all c servers busy and has to wait."
function erlang_c(c::Int, a::Real)
b = erlang_b(c, a)
b / (1 - (a / c) * (1 - b))
end
# ╔═╡ 21aa852f-26f5-5571-90ed-21ba01018d94
"Average wait in line for M/M/c (same time unit as 1/μ). Inf when over capacity."
mmc_wait(λ, μ, c) = λ < c * μ ? erlang_c(c, λ / μ) / (c * μ - λ) : Inf
# ╔═╡ f7e589e5-fba9-5bd4-aa58-5204b3865806
let μ = 240.0, λ = λ_mmc, c = c_mmc
p = plot(xlabel="notes per hour λ", ylabel="average wait in line (seconds)", ylims=(0, 120),
xlims=(0, 1450), size=(760, 300), legend=:topright)
for k in 1:c