-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecoding-serving-explainer.html
More file actions
1624 lines (1484 loc) · 81.3 KB
/
decoding-serving-explainer.html
File metadata and controls
1624 lines (1484 loc) · 81.3 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text Generation, Decoding & Serving — Visual Guide</title>
<meta name="description" content="Temperature, top-k, top-p sampling with live sliders. Beam search visualization, KV cache mechanics, quantization (FP16/INT8/INT4), and scalable LLM serving.">
<meta name="keywords" content="Softmax Academy, text generation, decoding, temperature, top-k, top-p, beam search, KV cache, quantization, LLM serving, model inference">
<meta name="author" content="Pedram Rezaei, Claude">
<link rel="canonical" href="https://cloudtoid.github.io/llm-book/decoding-serving-explainer.html">
<meta property="og:title" content="Text Generation, Decoding & Serving — Visual Guide">
<meta property="og:description" content="Temperature, top-k, top-p sampling with live sliders. Beam search visualization, KV cache mechanics, quantization (FP16/INT8/INT4), and scalable LLM serving.">
<meta property="og:image" content="https://cloudtoid.github.io/llm-book/og-image.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:type" content="article">
<meta property="og:url" content="https://cloudtoid.github.io/llm-book/decoding-serving-explainer.html">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Text Generation, Decoding & Serving — Visual Guide">
<meta name="twitter:description" content="Temperature, top-k, top-p sampling with live sliders. Beam search visualization, KV cache mechanics, quantization (FP16/INT8/INT4), and scalable LLM serving.">
<meta name="twitter:image" content="https://cloudtoid.github.io/llm-book/og-image.png">
<link rel="icon" type="image/png" sizes="32x32" href="favicon.png">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="theme-color" content="#0f1117">
<meta name="robots" content="index, follow">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"></script>
<style>
:root {
--bg: #0f1117; --surface: #1a1d27; --surface2: #252836;
--accent: #6c63ff; --accent2: #ff6b6b; --accent3: #4ecdc4;
--accent4: #ffe66d; --accent5: #a882ff; --accent6: #ff9f43;
--text: #e8e8e8; --text-dim: #8b8fa3; --border: #2e3244;
}
* { margin:0; padding:0; box-sizing:border-box; }
body { font-family:'Segoe UI',system-ui,-apple-system,sans-serif; background:var(--bg); color:var(--text); line-height:1.7; overflow-x:hidden; }
.container { max-width:1100px; margin:0 auto; padding:0 24px; }
header { text-align:center; padding:60px 0 40px; border-bottom:1px solid var(--border); }
header h1 { font-size:2.4rem; font-weight:700; background:linear-gradient(135deg,var(--accent5),var(--accent3)); -webkit-background-clip:text; -webkit-text-fill-color:transparent; margin-bottom:12px; }
header p { color:var(--text-dim); font-size:1.05rem; max-width:700px; margin:0 auto; }
section { padding:50px 0; }
section h2 { font-size:1.8rem; margin-bottom:8px; }
.sub { color:var(--text-dim); margin-bottom:28px; font-size:1rem; }
.card { background:var(--surface); border:1px solid var(--border); border-radius:16px; padding:28px; margin-bottom:24px; }
.divider { border:none; border-top:1px solid var(--border); margin:10px 0 40px; }
.concept-grid { display:grid; grid-template-columns:1fr 1fr; gap:20px; }
.concept-card { background:var(--surface2); border:1px solid var(--border); border-radius:14px; padding:22px; }
.concept-card h4 { margin-bottom:8px; font-size:1rem; }
.concept-card p { font-size:0.85rem; color:var(--text-dim); }
.flow { display:flex; align-items:center; justify-content:center; gap:0; margin:24px 0; flex-wrap:wrap; }
.flow-node { padding:14px 20px; border-radius:12px; font-size:0.88rem; font-weight:600; text-align:center; min-width:100px; }
.flow-node.input { background:rgba(255,107,107,0.15); color:var(--accent2); border:1px solid rgba(255,107,107,0.3); }
.flow-node.process { background:rgba(108,99,255,0.15); color:var(--accent); border:1px solid rgba(108,99,255,0.3); }
.flow-node.output { background:rgba(78,205,196,0.15); color:var(--accent3); border:1px solid rgba(78,205,196,0.3); }
.flow-node.warn { background:rgba(255,230,109,0.12); color:var(--accent4); border:1px solid rgba(255,230,109,0.3); }
.flow-node.purple { background:rgba(168,130,255,0.15); color:var(--accent5); border:1px solid rgba(168,130,255,0.3); }
.flow-node.orange { background:rgba(255,159,67,0.15); color:var(--accent6); border:1px solid rgba(255,159,67,0.3); }
.flow-arrow { font-size:1.4rem; color:var(--text-dim); padding:0 10px; }
.mono { font-family:'Cascadia Code','Fira Code',monospace; }
code { background:var(--surface2); padding:2px 8px; border-radius:6px; font-size:0.85rem; font-family:'Cascadia Code','Fira Code',monospace; }
.formula { background:var(--surface2); padding:16px 20px; border-radius:10px; font-family:'Cascadia Code','Fira Code',monospace; font-size:0.92rem; color:var(--accent3); margin:12px 0; text-align:center; overflow-x:auto; }
.badge { display:inline-block; padding:2px 10px; border-radius:20px; font-size:0.78rem; font-weight:600; }
.badge.good { background:rgba(78,205,196,0.2); color:var(--accent3); }
.badge.info { background:rgba(108,99,255,0.2); color:var(--accent); }
.badge.warn { background:rgba(255,230,109,0.2); color:var(--accent4); }
canvas { border-radius:12px; display:block; }
.cmp-table { width:100%; border-collapse:collapse; margin-top:16px; }
.cmp-table th,.cmp-table td { padding:8px 12px; text-align:left; border-bottom:1px solid var(--border); font-size:0.82rem; }
.cmp-table th { color:var(--text-dim); font-size:0.78rem; text-transform:uppercase; letter-spacing:0.05em; }
.cmp-table td:first-child { color:var(--accent3); font-weight:600; }
.cmp-table tr:hover td { background:rgba(108,99,255,0.04); }
.slider-row { display:flex; align-items:center; gap:12px; margin:8px 0; }
.slider-row label { font-size:0.82rem; color:var(--text-dim); min-width:110px; }
input[type="range"] { flex:1; accent-color:var(--accent); }
@media (max-width:700px) {
.concept-grid { grid-template-columns:1fr; }
.flow { flex-direction:column; }
.flow-arrow { transform:rotate(90deg); }
header h1 { font-size:1.8rem; }
}
/* === Chapter Navigation === */
.ch-nav { position: sticky; top: 0; z-index: 1000; background: var(--bg); border-bottom: 1px solid var(--border); }
.ch-nav-bar { max-width: 1100px; margin: 0 auto; padding: 8px 24px; display: flex; align-items: center; gap: 12px; }
.ch-nav-home { text-decoration: none; font-weight: 700; font-size: 0.85rem; color: var(--accent); white-space: nowrap; }
.ch-nav-home:hover { color: var(--accent3); }
.ch-nav-sep { color: var(--border); font-size: 0.9rem; }
.ch-nav-prevnext { display: flex; gap: 6px; }
.ch-nav-prevnext a {
text-decoration: none; font-size: 0.78rem; padding: 4px 10px;
border-radius: 6px; border: 1px solid var(--border); color: var(--text-dim);
transition: all 0.15s;
}
.ch-nav-prevnext a:hover { border-color: var(--accent); color: var(--text); }
.ch-nav-prevnext a.disabled { opacity: 0.3; pointer-events: none; }
.ch-nav-toggle {
background: none; border: 1px solid var(--border);
color: var(--text-dim); padding: 4px 12px; border-radius: 6px;
font-size: 0.78rem; cursor: pointer; transition: all 0.15s;
font-family: inherit;
}
.ch-nav-toggle:hover { border-color: var(--accent); color: var(--text); }
.ch-nav-toc {
display: none; max-width: 1100px; margin: 0 auto; padding: 0 24px 12px;
}
.ch-nav-toc.open { display: block; }
.ch-nav-toc ol {
list-style: none; display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 4px 16px; padding: 0; margin: 0;
}
.ch-nav-toc li a {
display: block; padding: 6px 10px; border-radius: 6px; font-size: 0.8rem;
color: var(--text-dim); text-decoration: none; transition: all 0.15s;
}
.ch-nav-toc li a:hover { background: var(--surface2); color: var(--text); }
.ch-nav-toc li a.current { background: var(--surface2); color: var(--accent); font-weight: 600; }
.ch-nav-toc li .ch-num { color: var(--accent3); font-weight: 600; margin-right: 6px; }
@media (max-width: 600px) {
.ch-nav-toc ol { grid-template-columns: 1fr; }
}
/* === Left sidebar TOC === */
.page-layout { display: flex; max-width: 1200px; margin: 0 auto; }
.left-toc { position: sticky; top: 52px; align-self: flex-start; width: 230px; min-width: 230px; height: calc(100vh - 52px); overflow-y: auto; padding: 1.2rem 0.75rem; border-right: 1px solid var(--border); font-size: 0.78rem; scrollbar-width: thin; scrollbar-color: var(--border) transparent; }
.left-toc::-webkit-scrollbar { width: 4px; }
.left-toc::-webkit-scrollbar-thumb { background: var(--border); border-radius: 2px; }
.left-toc h3 { color: var(--text-dim); font-size: 0.65rem; text-transform: uppercase; letter-spacing: 0.08em; margin-bottom: 0.6rem; padding-left: 0.4rem; }
.left-toc a { display: flex; align-items: center; gap: 0.45rem; padding: 0.28rem 0.5rem; border-radius: 6px; color: var(--text-dim); text-decoration: none; transition: all 0.15s ease; line-height: 1.35; }
.left-toc a:hover { color: var(--text); background: var(--surface); }
.left-toc a.active { color: var(--accent); background: var(--surface); font-weight: 600; }
.left-toc .toc-num { flex-shrink: 0; width: 20px; height: 20px; border-radius: 5px; display: flex; align-items: center; justify-content: center; font-size: 0.65rem; font-weight: 700; background: rgba(108,99,255,0.1); color: var(--accent); }
.left-toc a.active .toc-num { background: var(--accent); color: var(--bg); }
.page-main { flex: 1; min-width: 0; }
@media (max-width: 900px) { .left-toc { display: none; } .page-layout { display: block; } }
h2[id] { scroll-margin-top: 60px; }
/* === Light mode === */
[data-theme="light"] {
--bg: #f8f9fc; --surface: #ffffff; --surface2: #eef0f4;
--accent: #4f46e5; --accent2: #dc2626; --accent3: #0d9488;
--accent4: #ca8a04; --accent5: #7c3aed; --accent6: #ea580c;
--text: #1e293b; --text-dim: #64748b; --border: #d1d5db;
}
[data-theme="light"] body { background: var(--bg); color: var(--text); }
[data-theme="light"] .card,
[data-theme="light"] .visual-container,
[data-theme="light"] .demo-card,
[data-theme="light"] .info-box { background: var(--surface); border-color: var(--border); box-shadow: 0 1px 3px rgba(0,0,0,0.08); }
[data-theme="light"] pre,
[data-theme="light"] code { background: #f1f5f9; color: #334155; }
[data-theme="light"] .section-divider { border-color: var(--border); }
[data-theme="light"] input[type="text"],
[data-theme="light"] input[type="number"],
[data-theme="light"] textarea,
[data-theme="light"] select { background: var(--surface); border-color: var(--border); color: var(--text); }
[data-theme="light"] input[type="range"] { background: #cbd5e1; }
[data-theme="light"] input[type="range"]::-webkit-slider-thumb { background: var(--accent); border-color: var(--surface); }
[data-theme="light"] .ch-nav { background: var(--bg); border-bottom-color: var(--border); }
[data-theme="light"] .left-toc { border-right-color: var(--border); }
[data-theme="light"] .left-toc .toc-num { background: rgba(79,70,229,0.1); color: var(--accent); }
[data-theme="light"] .left-toc a.active .toc-num { background: var(--accent); color: #fff; }
[data-theme="light"] table, [data-theme="light"] th, [data-theme="light"] td { border-color: var(--border); }
[data-theme="light"] th { background: rgba(79,70,229,0.08); color: var(--accent); }
[data-theme="light"] tbody tr:nth-child(even) td { background: #f8f9fc; }
[data-theme="light"] tr:hover td { background: rgba(79,70,229,0.04); }
[data-theme="light"] .chapter-card { background: var(--surface); border-color: var(--border); }
[data-theme="light"] .chapter-card:hover { border-color: var(--accent); background: var(--surface2); }
.theme-toggle { margin-left: auto; background: none; border: 1px solid var(--border); color: var(--text-dim); padding: 4px 10px; border-radius: 6px; font-size: 0.82rem; cursor: pointer; transition: all 0.15s; font-family: inherit; display: flex; align-items: center; gap: 4px; }
.theme-toggle:hover { border-color: var(--accent); color: var(--text); }
</style>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Article",
"headline": "Text Generation, Decoding & Serving — Visual Guide",
"description": "Temperature, top-k, top-p sampling with live sliders. Beam search visualization, KV cache mechanics, quantization (FP16/INT8/INT4), and scalable LLM serving.",
"url": "https://cloudtoid.github.io/llm-book/decoding-serving-explainer.html",
"author": [
{ "@type": "Person", "name": "Pedram Rezaei", "url": "https://www.linkedin.com/in/pedramrezaei/" },
{ "@type": "Person", "name": "Claude" }
],
"isPartOf": {
"@type": "Book",
"name": "Softmax Academy",
"url": "https://cloudtoid.github.io/llm-book/"
},
"position": 15
}
</script>
<link rel="prev" href="custom-embeddings-explainer.html">
<link rel="next" href="gpu-inference-explainer.html">
<script>
(function() {
var saved = localStorage.getItem('theme');
if (saved) document.documentElement.setAttribute('data-theme', saved);
})();
</script>
</head>
<body>
<nav class="ch-nav" aria-label="Chapter navigation">
<div class="ch-nav-bar">
<a href="index.html" class="ch-nav-home"><img src="logo-small.png" alt="" style="width:22px;height:22px;vertical-align:middle;margin-right:6px;">Softmax Academy</a>
<span class="ch-nav-sep">|</span>
<span style="font-size:0.82rem;color:var(--text);font-weight:600;">Decoding & Serving</span>
<span class="ch-nav-sep">|</span>
<div class="ch-nav-prevnext">
<a href="custom-embeddings-explainer.html">← Prev</a>
<a href="gpu-inference-explainer.html">Next →</a>
</div>
<button class="theme-toggle" aria-label="Toggle theme"></button>
<button class="ch-nav-toggle" onclick="document.querySelector('.ch-nav-toc').classList.toggle('open')">All Chapters ▾</button>
</div>
<div class="ch-nav-toc">
<ol>
<li><a href="tokenizer-explainer.html"><span class="ch-num">1.</span>Tokens & Tokenization</a></li>
<li><a href="embeddings-explainer.html"><span class="ch-num">2.</span>Embeddings</a></li>
<li><a href="transformers-explainer.html"><span class="ch-num">3.</span>Transformers & Attention</a></li>
<li><a href="model-families-explainer.html"><span class="ch-num">4.</span>Model Families & Objectives</a></li>
<li><a href="pretraining-explainer.html"><span class="ch-num">5.</span>Pretraining & Scaling</a></li>
<li><a href="finetuning-explainer.html"><span class="ch-num">6.</span>Post-Training & Alignment</a></li>
<li><a href="math-foundations-explainer.html"><span class="ch-num">7.</span>Math Foundations</a></li>
<li><a href="classification-explainer.html"><span class="ch-num">8.</span>Classification</a></li>
<li><a href="topic-modeling-explainer.html"><span class="ch-num">9.</span>Topic Modeling</a></li>
<li><a href="prompting-explainer.html"><span class="ch-num">10.</span>Prompting & Tool Use</a></li>
<li><a href="multimodal-explainer.html"><span class="ch-num">11.</span>Multimodal LLMs</a></li>
<li><a href="retrieval-explainer.html"><span class="ch-num">12.</span>Retrieval Foundations</a></li>
<li><a href="rag-production-explainer.html"><span class="ch-num">13.</span>Production RAG</a></li>
<li><a href="custom-embeddings-explainer.html"><span class="ch-num">14.</span>Custom Embeddings</a></li>
<li><a href="decoding-serving-explainer.html" class="current"><span class="ch-num">15.</span>Decoding & Serving</a></li>
<li><a href="gpu-inference-explainer.html"><span class="ch-num">16.</span>GPU Inference</a></li>
<li><a href="nanochat-explainer.html"><span class="ch-num">17.</span>Practical: nanochat</a></li>
<li><a href="advanced-topics-explainer.html"><span class="ch-num">18.</span>Advanced Topics</a></li>
</ol>
</div>
</nav>
<header class="container">
<h1>Text Generation, Decoding & Serving</h1>
<p>From raw logits to production APIs — how LLMs generate text, how decoding strategies shape output, and how serving infrastructure makes it all fast and reliable.</p>
</header>
<div class="page-layout">
<nav class="left-toc" aria-label="Section navigation">
<h3>On This Page</h3>
<a href="#s1" class="active"><span class="toc-num">1</span>Temperature, Top-k, and Top-p Sam…</a>
<a href="#s2"><span class="toc-num">2</span>Greedy vs Beam Search vs Sampling</a>
<a href="#s3"><span class="toc-num">3</span>Streaming Generation</a>
<a href="#s4"><span class="toc-num">4</span>Batching & Concurrency</a>
<a href="#s5"><span class="toc-num">5</span>The KV Cache</a>
<a href="#s6"><span class="toc-num">6</span>Quantization: FP16, INT8, INT4</a>
<a href="#s7"><span class="toc-num">7</span>Throughput vs Latency Tradeoff</a>
<a href="#s8"><span class="toc-num">8</span>Long-Context Serving Challenges</a>
<a href="#s9"><span class="toc-num">9</span>Safety & Moderation Pipeline</a>
<a href="#s10"><span class="toc-num">10</span>Scalable LLM Service Architecture</a>
</nav>
<div class="page-main">
<div class="container" role="main">
<!-- ===== 1. TEMPERATURE, TOP-K, TOP-P ===== -->
<section id="s1">
<h2>Temperature, Top-k, and Top-p Sampling</h2>
<p class="sub">Three knobs that control how "creative" or "focused" the model's output is. They all modify the probability distribution before sampling the next token.</p>
<div class="card">
<div style="display:grid;grid-template-columns:1fr 1fr;gap:24px;">
<div>
<h4 style="color:var(--accent);margin-bottom:12px;">Interactive: Adjust the parameters</h4>
<p style="font-size:0.82rem;color:var(--text-dim);margin-bottom:12px;">Watch how the token probability distribution changes as you move the sliders.</p>
<div class="slider-row">
<label>Temperature:</label>
<input type="range" id="temp-slider" min="5" max="300" value="100" oninput="updateSampling()">
<span id="temp-val" class="mono" style="min-width:50px;color:var(--accent3);">1.00</span>
</div>
<div class="slider-row">
<label>Top-k:</label>
<input type="range" id="topk-slider" min="1" max="20" value="20" oninput="updateSampling()">
<span id="topk-val" class="mono" style="min-width:50px;color:var(--accent2);">20 (off)</span>
</div>
<div class="slider-row">
<label>Top-p (nucleus):</label>
<input type="range" id="topp-slider" min="10" max="100" value="100" oninput="updateSampling()">
<span id="topp-val" class="mono" style="min-width:50px;color:var(--accent4);">1.00 (off)</span>
</div>
<div id="sampling-info" style="margin-top:16px;padding:12px;background:var(--surface2);border-radius:10px;font-size:0.82rem;color:var(--text-dim);min-height:60px;"></div>
</div>
<div>
<div style="position:relative;height:350px;background:var(--surface2);border-radius:12px;"><canvas id="sampling-canvas"></canvas></div>
</div>
</div>
<div style="margin-top:20px;display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;">
<div style="padding:14px;background:var(--surface2);border-radius:10px;border-left:3px solid var(--accent3);">
<h4 style="color:var(--accent3);font-size:0.9rem;margin-bottom:6px;">Temperature</h4>
<div class="formula" style="font-size:0.78rem;text-align:left;margin:4px 0;">p_i = exp(z_i / T) / sum(exp(z_j / T))</div>
<p style="font-size:0.78rem;color:var(--text-dim);">T < 1: sharpens (more confident, less diverse). T > 1: flattens (more random, more creative). T -> 0: becomes greedy (always picks highest).</p>
</div>
<div style="padding:14px;background:var(--surface2);border-radius:10px;border-left:3px solid var(--accent2);">
<h4 style="color:var(--accent2);font-size:0.9rem;margin-bottom:6px;">Top-k</h4>
<p style="font-size:0.78rem;color:var(--text-dim);">Keep only the k most probable tokens, zero out the rest, then renormalize. Simple cutoff. k=1 is greedy decoding. k=40 is a common default.</p>
</div>
<div style="padding:14px;background:var(--surface2);border-radius:10px;border-left:3px solid var(--accent4);">
<h4 style="color:var(--accent4);font-size:0.9rem;margin-bottom:6px;">Top-p (Nucleus)</h4>
<p style="font-size:0.78rem;color:var(--text-dim);">Keep the smallest set of tokens whose cumulative probability exceeds p. Adapts to the shape of the distribution — includes more tokens when the model is uncertain, fewer when confident.</p>
</div>
</div>
</div>
</section>
<hr class="divider">
<!-- ===== 2. GREEDY VS BEAM VS SAMPLING ===== -->
<section id="s2">
<h2>Greedy vs Beam Search vs Sampling</h2>
<p class="sub">Three fundamentally different approaches to choosing which tokens to generate. Each makes a different tradeoff between quality and diversity.</p>
<div class="card">
<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;">
<div class="concept-card" style="border-color:rgba(78,205,196,0.3);">
<h4 style="color:var(--accent3);">Greedy Decoding</h4>
<p>Always pick the highest-probability token. Fast, deterministic, but can get stuck in repetitive or suboptimal sequences.</p>
<div style="margin-top:12px;text-align:center;">
<canvas id="greedy-tree" width="200" height="180" style="background:var(--bg);max-width:100%;"></canvas>
</div>
<p style="font-size:0.78rem;color:var(--text-dim);margin-top:8px;">Best for: factual answers, code generation, deterministic outputs.</p>
<p style="margin-top:4px;"><span class="badge good">Speed: fastest</span></p>
</div>
<div class="concept-card" style="border-color:rgba(108,99,255,0.3);">
<h4 style="color:var(--accent);">Beam Search</h4>
<p>Maintain k "beams" (partial sequences) simultaneously. At each step, expand all beams and keep the top-k total scores. Finds higher-probability sequences.</p>
<div style="margin-top:12px;text-align:center;">
<canvas id="beam-tree" width="200" height="180" style="background:var(--bg);max-width:100%;"></canvas>
</div>
<p style="font-size:0.78rem;color:var(--text-dim);margin-top:8px;">Best for: translation, summarization, when you need the "best" output.</p>
<p style="margin-top:4px;"><span class="badge info">Speed: k times slower</span></p>
</div>
<div class="concept-card" style="border-color:rgba(255,107,107,0.3);">
<h4 style="color:var(--accent2);">Sampling</h4>
<p>Randomly sample from the probability distribution (optionally modified by temperature, top-k, top-p). Produces diverse, natural-sounding text.</p>
<div style="margin-top:12px;text-align:center;">
<canvas id="sample-tree" width="200" height="180" style="background:var(--bg);max-width:100%;"></canvas>
</div>
<p style="font-size:0.78rem;color:var(--text-dim);margin-top:8px;">Best for: creative writing, chat, brainstorming, when diversity matters.</p>
<p style="margin-top:4px;"><span class="badge warn">Speed: fast, non-deterministic</span></p>
</div>
</div>
<table class="cmp-table" style="margin-top:20px;">
<thead><tr><th>Strategy</th><th>Deterministic?</th><th>Diverse?</th><th>Finds global best?</th><th>Typical use</th></tr></thead>
<tbody>
<tr><td>Greedy</td><td>Yes</td><td>No</td><td>No (locally optimal)</td><td>Classification, extraction</td></tr>
<tr><td>Beam (k=4)</td><td>Yes</td><td>Somewhat</td><td>Approximately</td><td>Translation, summarization</td></tr>
<tr><td>Sampling (T=0.7)</td><td>No</td><td>Yes</td><td>No (stochastic)</td><td>Chat, creative writing</td></tr>
</tbody>
</table>
</div>
</section>
<hr class="divider">
<!-- ===== 3. STREAMING GENERATION ===== -->
<section id="s3">
<h2>Streaming Generation</h2>
<p class="sub">Why waiting for the full response is bad UX — and how streaming fixes it by sending tokens as they're generated.</p>
<div class="card">
<h4 style="color:var(--accent3);margin-bottom:16px;">Visual timeline: Streaming vs Non-Streaming</h4>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
<div class="concept-card" style="border-color:rgba(255,107,107,0.3);">
<h4 style="color:var(--accent2);">Without streaming</h4>
<div style="margin:12px 0;">
<canvas id="nostream-canvas" width="350" height="120" style="background:var(--bg);max-width:100%;"></canvas>
</div>
<p style="font-size:0.82rem;color:var(--text-dim);">User waits for the entire response to be generated. Long silence, then everything appears at once. Feels slow even if total time is the same.</p>
</div>
<div class="concept-card" style="border-color:rgba(78,205,196,0.3);">
<h4 style="color:var(--accent3);">With streaming (SSE / WebSocket)</h4>
<div style="margin:12px 0;">
<canvas id="stream-canvas" width="350" height="120" style="background:var(--bg);max-width:100%;"></canvas>
</div>
<p style="font-size:0.82rem;color:var(--text-dim);">Tokens arrive as they're generated. User sees the response building in real time. Feels fast and interactive. Users can cancel early if the direction is wrong.</p>
</div>
</div>
<div style="margin-top:20px;">
<h4 style="color:var(--accent4);margin-bottom:8px;">Live streaming demo</h4>
<p style="font-size:0.82rem;color:var(--text-dim);margin-bottom:8px;">Click "Stream" to see tokens appear one by one, simulating real streaming generation.</p>
<div style="display:flex;gap:12px;align-items:center;margin-bottom:12px;">
<button id="stream-btn" onclick="startStreamDemo()" style="padding:8px 20px;background:var(--accent);color:#fff;border:none;border-radius:8px;cursor:pointer;font-size:0.85rem;font-weight:600;">Stream</button>
<button onclick="resetStreamDemo()" style="padding:8px 20px;background:var(--surface2);color:var(--text-dim);border:1px solid var(--border);border-radius:8px;cursor:pointer;font-size:0.85rem;">Reset</button>
<span id="stream-metrics" class="mono" style="font-size:0.82rem;color:var(--text-dim);"></span>
</div>
<div id="stream-output" style="padding:16px;background:var(--surface2);border-radius:10px;min-height:60px;font-size:0.95rem;line-height:1.8;"></div>
</div>
<div style="margin-top:20px;padding:14px;background:var(--surface2);border-radius:10px;">
<strong style="color:var(--accent4);font-size:0.85rem;">Systems implications of streaming:</strong>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:8px;font-size:0.82rem;">
<div style="padding:8px 10px;background:var(--bg);border-radius:8px;color:var(--text-dim);">
<strong style="color:var(--accent3);">Error handling changes</strong> — Errors mid-stream mean partial output is already visible. Need graceful degradation.
</div>
<div style="padding:8px 10px;background:var(--bg);border-radius:8px;color:var(--text-dim);">
<strong style="color:var(--accent2);">Cancellation</strong> — User can stop generation early, saving compute. Requires proper connection lifecycle management.
</div>
</div>
</div>
</div>
</section>
<hr class="divider">
<!-- ===== 4. BATCHING & CONCURRENCY ===== -->
<section id="s4">
<h2>Batching & Concurrency</h2>
<p class="sub">How serving systems pack multiple requests onto the GPU simultaneously to maximize throughput — and the tradeoffs involved.</p>
<div class="card">
<h4 style="color:var(--accent6);margin-bottom:16px;">Visual: Requests packing into GPU compute</h4>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:24px;">
<div>
<h4 style="color:var(--accent2);margin-bottom:8px;">Without batching</h4>
<canvas id="nobatch-canvas" width="350" height="200" style="background:var(--surface2);max-width:100%;"></canvas>
<p style="font-size:0.78rem;color:var(--text-dim);margin-top:6px;">One request at a time. GPU is mostly idle between requests. Low utilization, high per-request latency for queued requests.</p>
</div>
<div>
<h4 style="color:var(--accent3);margin-bottom:8px;">With continuous batching</h4>
<canvas id="batch-canvas" width="350" height="200" style="background:var(--surface2);max-width:100%;"></canvas>
<p style="font-size:0.78rem;color:var(--text-dim);margin-top:6px;">Multiple requests processed simultaneously. New requests join the batch as old ones finish. GPU stays busy. Higher throughput.</p>
</div>
</div>
<div style="margin-top:20px;padding:14px;background:var(--surface2);border-radius:10px;">
<h4 style="color:var(--accent4);margin-bottom:8px;">Key serving concepts</h4>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;font-size:0.82rem;">
<div style="padding:10px;background:var(--bg);border-radius:8px;border-left:3px solid var(--accent);">
<strong style="color:var(--accent);">Static batching</strong>
<span style="color:var(--text-dim);display:block;">Wait until batch is full, process all at once. Simple but wastes time waiting and short sequences pad to max length.</span>
</div>
<div style="padding:10px;background:var(--bg);border-radius:8px;border-left:3px solid var(--accent3);">
<strong style="color:var(--accent3);">Continuous batching</strong>
<span style="color:var(--text-dim);display:block;">Requests join and leave the batch dynamically. A finishing request immediately frees its slot for a new one. Much better GPU utilization.</span>
</div>
<div style="padding:10px;background:var(--bg);border-radius:8px;border-left:3px solid var(--accent6);">
<strong style="color:var(--accent6);">Iteration-level scheduling</strong>
<span style="color:var(--text-dim);display:block;">At each decoding step, decide which requests to process. Can preempt low-priority requests or pause long generations.</span>
</div>
<div style="padding:10px;background:var(--bg);border-radius:8px;border-left:3px solid var(--accent4);">
<strong style="color:var(--accent4);">The tradeoff</strong>
<span style="color:var(--text-dim);display:block;">Larger batches = higher throughput but higher per-request latency. The optimal batch size depends on the SLA.</span>
</div>
</div>
</div>
</div>
</section>
<hr class="divider">
<!-- ===== 5. KV CACHE ===== -->
<section id="s5">
<h2>The KV Cache</h2>
<p class="sub">The single most important optimization for autoregressive generation. Without it, every new token would recompute attention over the entire sequence from scratch.</p>
<div class="card">
<h4 style="color:var(--accent);margin-bottom:16px;">Cached vs recomputed: what happens at each step</h4>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
<div class="concept-card" style="border-color:rgba(255,107,107,0.3);">
<h4 style="color:var(--accent2);">Without KV cache (naive)</h4>
<div style="font-family:monospace;font-size:0.78rem;margin:12px 0;color:var(--text-dim);">
<div style="padding:4px 0;">Step 1: process [The] -> compute K,V for "The"</div>
<div style="padding:4px 0;color:var(--accent2);">Step 2: process [The, cat] -> recompute K,V for "The" AND "cat"</div>
<div style="padding:4px 0;color:var(--accent2);">Step 3: process [The, cat, sat] -> recompute ALL three</div>
<div style="padding:4px 0;color:var(--accent2);">Step 4: process [The, cat, sat, on] -> recompute ALL four</div>
</div>
<p style="font-size:0.82rem;color:var(--accent2);">Cost per step grows linearly. Total cost is O(n^2).</p>
</div>
<div class="concept-card" style="border-color:rgba(78,205,196,0.3);">
<h4 style="color:var(--accent3);">With KV cache</h4>
<div style="font-family:monospace;font-size:0.78rem;margin:12px 0;color:var(--text-dim);">
<div style="padding:4px 0;">Step 1: process [The] -> store K,V for "The"</div>
<div style="padding:4px 0;color:var(--accent3);">Step 2: process [cat] only -> reuse stored K,V, add new K,V</div>
<div style="padding:4px 0;color:var(--accent3);">Step 3: process [sat] only -> reuse all stored K,V, add new</div>
<div style="padding:4px 0;color:var(--accent3);">Step 4: process [on] only -> reuse all stored K,V, add new</div>
</div>
<p style="font-size:0.82rem;color:var(--accent3);">Each step only computes the new token's K,V projection (not all previous tokens'). Attention is still O(n) per step, but avoiding redundant K,V recomputation is a massive speedup.</p>
</div>
</div>
<div style="margin-top:20px;">
<h4 style="color:var(--accent4);margin-bottom:8px;">Visual: KV cache growth</h4>
<canvas id="kv-canvas" width="700" height="250" style="background:var(--surface2);max-width:100%;"></canvas>
<p style="font-size:0.75rem;color:var(--text-dim);margin-top:4px;">Each column is a decoding step. Green blocks are cached (reused). Orange blocks are newly computed. Without caching, every block would be orange.</p>
</div>
<div style="margin-top:20px;padding:14px;background:var(--surface2);border-radius:10px;">
<h4 style="color:var(--accent4);margin-bottom:8px;">KV cache memory budget</h4>
<table class="cmp-table" style="margin-top:0;">
<thead><tr><th>Model</th><th>Layers</th><th>Heads</th><th>d_head</th><th>KV cache per token</th><th>128K ctx</th></tr></thead>
<tbody>
<tr><td>LLaMA 3 8B</td><td>32</td><td>8 (GQA)</td><td>128</td><td>~128 KB</td><td>~16 GB</td></tr>
<tr><td>LLaMA 3 70B</td><td>80</td><td>8 (GQA)</td><td>128</td><td>~320 KB</td><td>~40 GB</td></tr>
<tr style="opacity:0.6;font-style:italic;"><td>GPT-4 class (estimated)</td><td>~120?</td><td>~16?</td><td>128?</td><td>~1 MB?</td><td>~120 GB?</td></tr>
</tbody>
</table>
<p style="font-size:0.78rem;color:var(--text-dim);margin-top:8px;">The KV cache can consume more GPU memory than the model weights themselves for long sequences. This is why techniques like GQA (Grouped Query Attention), paged attention (vLLM), and KV cache compression exist.</p>
</div>
</div>
</section>
<hr class="divider">
<!-- ===== 6. QUANTIZATION ===== -->
<section id="s6">
<h2>Quantization: FP16, INT8, INT4</h2>
<p class="sub">Reducing the numerical precision of weights to save memory and speed up inference — the key technique for running large models on consumer hardware.</p>
<div class="card">
<h4 style="color:var(--accent5);margin-bottom:16px;">Precision comparison</h4>
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;">
<div class="concept-card" style="border-color:rgba(108,99,255,0.3);">
<h4 style="color:var(--accent);">FP32</h4>
<div style="margin:8px 0;">
<canvas id="fp32-bits" width="160" height="40" style="background:var(--bg);max-width:100%;"></canvas>
</div>
<p style="font-size:0.78rem;color:var(--text-dim);">32 bits per value. Full precision. Baseline quality.</p>
<div style="font-family:monospace;font-size:0.72rem;color:var(--accent4);margin-top:4px;">70B model: ~280 GB</div>
</div>
<div class="concept-card" style="border-color:rgba(78,205,196,0.3);">
<h4 style="color:var(--accent3);">FP16 / BF16</h4>
<div style="margin:8px 0;">
<canvas id="fp16-bits" width="160" height="40" style="background:var(--bg);max-width:100%;"></canvas>
</div>
<p style="font-size:0.78rem;color:var(--text-dim);">16 bits per value. Negligible quality loss. Standard for training and inference.</p>
<div style="font-family:monospace;font-size:0.72rem;color:var(--accent4);margin-top:4px;">70B model: ~140 GB</div>
</div>
<div class="concept-card" style="border-color:rgba(255,159,67,0.3);">
<h4 style="color:var(--accent6);">INT8</h4>
<div style="margin:8px 0;">
<canvas id="int8-bits" width="160" height="40" style="background:var(--bg);max-width:100%;"></canvas>
</div>
<p style="font-size:0.78rem;color:var(--text-dim);">8 bits per value. Small quality loss on most tasks. Great for inference.</p>
<div style="font-family:monospace;font-size:0.72rem;color:var(--accent4);margin-top:4px;">70B model: ~70 GB</div>
</div>
<div class="concept-card" style="border-color:rgba(255,107,107,0.3);">
<h4 style="color:var(--accent2);">INT4</h4>
<div style="margin:8px 0;">
<canvas id="int4-bits" width="160" height="40" style="background:var(--bg);max-width:100%;"></canvas>
</div>
<p style="font-size:0.78rem;color:var(--text-dim);">4 bits per value. Noticeable quality loss on hard tasks. Enables consumer GPUs.</p>
<div style="font-family:monospace;font-size:0.72rem;color:var(--accent4);margin-top:4px;">70B model: ~35 GB</div>
</div>
</div>
<div style="margin-top:20px;">
<h4 style="color:var(--accent4);margin-bottom:8px;">Precision vs Model Size vs Quality</h4>
<div style="position:relative;height:250px;background:var(--surface2);border-radius:12px;"><canvas id="quant-chart"></canvas></div>
</div>
<div style="margin-top:20px;padding:14px;background:var(--surface2);border-radius:10px;">
<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;font-size:0.82rem;">
<div style="padding:10px;background:var(--bg);border-radius:8px;border-left:3px solid var(--accent3);">
<strong style="color:var(--accent3);">Post-training quantization (PTQ)</strong>
<span style="color:var(--text-dim);display:block;">Quantize after training. Simple, no retraining needed. May degrade quality on sensitive tasks. GPTQ, AWQ are popular methods.</span>
</div>
<div style="padding:10px;background:var(--bg);border-radius:8px;border-left:3px solid var(--accent);">
<strong style="color:var(--accent);">Quantization-aware training (QAT)</strong>
<span style="color:var(--text-dim);display:block;">Simulate quantization during the forward pass so the model learns to be robust to reduced precision. Better quality but requires full training compute.</span>
</div>
<div style="padding:10px;background:var(--bg);border-radius:8px;border-left:3px solid var(--accent5);">
<strong style="color:var(--accent5);">QLoRA (different from QAT)</strong>
<span style="color:var(--text-dim);display:block;">Quantizes the frozen base model to 4-bit (NF4) but trains LoRA adapters in full precision (FP16). The base weights are never updated through quantization — it's a memory-saving technique for fine-tuning, not QAT.</span>
</div>
</div>
</div>
</div>
</section>
<hr class="divider">
<!-- ===== 7. THROUGHPUT VS LATENCY ===== -->
<section id="s7">
<h2>Throughput vs Latency Tradeoff</h2>
<p class="sub">The fundamental tension in serving: serving many users efficiently (throughput) vs serving each user quickly (latency). Optimizing one often hurts the other.</p>
<div class="card">
<div style="display:grid;grid-template-columns:1fr 1fr;gap:24px;">
<div>
<h4 style="color:var(--accent);margin-bottom:12px;">Interactive: Batch size vs Metrics</h4>
<p style="font-size:0.82rem;color:var(--text-dim);margin-bottom:12px;">Drag the batch size slider to see how throughput and latency respond.</p>
<div class="slider-row">
<label>Batch size:</label>
<input type="range" id="batch-slider" min="1" max="64" value="8" oninput="updateThroughputLatency()">
<span id="batch-val" class="mono" style="min-width:40px;color:var(--accent3);">8</span>
</div>
<div id="tl-metrics" style="margin-top:16px;display:grid;grid-template-columns:1fr 1fr;gap:12px;">
<div style="padding:14px;background:var(--surface2);border-radius:10px;text-align:center;">
<div style="font-size:0.78rem;color:var(--text-dim);">Throughput</div>
<div id="tl-throughput" style="font-size:1.4rem;font-weight:700;color:var(--accent3);font-family:monospace;">120 tok/s</div>
</div>
<div style="padding:14px;background:var(--surface2);border-radius:10px;text-align:center;">
<div style="font-size:0.78rem;color:var(--text-dim);">P50 Latency</div>
<div id="tl-latency" style="font-size:1.4rem;font-weight:700;color:var(--accent2);font-family:monospace;">45 ms/tok</div>
</div>
</div>
</div>
<div>
<canvas id="tl-canvas" width="400" height="280" style="background:var(--surface2);max-width:100%;"></canvas>
</div>
</div>
<div style="margin-top:20px;padding:14px;background:var(--surface2);border-radius:10px;">
<h4 style="color:var(--accent4);margin-bottom:8px;">Which to optimize?</h4>
<table class="cmp-table" style="margin-top:0;">
<thead><tr><th>Workload</th><th>Priority</th><th>Why</th></tr></thead>
<tbody>
<tr><td>Interactive chat</td><td style="color:var(--accent2);">Latency (TTFT + TPS)</td><td style="color:var(--text-dim);">Users notice delay. First-token latency and streaming speed matter most.</td></tr>
<tr><td>Batch processing</td><td style="color:var(--accent3);">Throughput</td><td style="color:var(--text-dim);">Processing 10M documents — total time matters, individual speed doesn't.</td></tr>
<tr><td>Code completion</td><td style="color:var(--accent2);">Latency (P99)</td><td style="color:var(--text-dim);">Must feel instant. High P99 latency kills the feature — users turn it off.</td></tr>
<tr><td>Copilot agents</td><td style="color:var(--accent4);">Both</td><td style="color:var(--text-dim);">Need fast responses AND efficient multi-turn. Balance with tiered routing.</td></tr>
</tbody>
</table>
</div>
</div>
</section>
<hr class="divider">
<!-- ===== 8. LONG-CONTEXT CHALLENGES ===== -->
<section id="s8">
<h2>Long-Context Serving Challenges</h2>
<p class="sub">Models now support 128K-1M token contexts, but using all of it on every request is expensive and sometimes counterproductive.</p>
<div class="card">
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
<div>
<h4 style="color:var(--accent2);margin-bottom:12px;">Challenges</h4>
<div style="font-size:0.85rem;">
<div style="margin:8px 0;padding:10px;background:var(--surface2);border-radius:8px;border-left:3px solid var(--accent2);">
<strong style="color:var(--accent2);">Memory: KV cache explosion</strong>
<span style="color:var(--text-dim);display:block;">At 128K tokens, the KV cache alone can be 4-30 GB per request. Limits concurrency.</span>
</div>
<div style="margin:8px 0;padding:10px;background:var(--surface2);border-radius:8px;border-left:3px solid var(--accent6);">
<strong style="color:var(--accent6);">Compute: O(n^2) attention</strong>
<span style="color:var(--text-dim);display:block;">Standard attention scales quadratically with sequence length. 128K tokens = 16 billion attention interactions per layer.</span>
</div>
<div style="margin:8px 0;padding:10px;background:var(--surface2);border-radius:8px;border-left:3px solid var(--accent4);">
<strong style="color:var(--accent4);">Quality: context dilution</strong>
<span style="color:var(--text-dim);display:block;">Models struggle with "lost in the middle" — information in the middle of very long contexts is less likely to be used than information at the start or end.</span>
</div>
<div style="margin:8px 0;padding:10px;background:var(--surface2);border-radius:8px;border-left:3px solid var(--accent5);">
<strong style="color:var(--accent5);">Cost: $$$ per request</strong>
<span style="color:var(--text-dim);display:block;">A 100K-token prompt is 50x more expensive than a 2K-token prompt. Retrieval can often provide the same information at 1/50th the cost.</span>
</div>
</div>
</div>
<div>
<h4 style="color:var(--accent3);margin-bottom:12px;">Solutions</h4>
<div style="font-size:0.85rem;">
<div style="margin:8px 0;padding:10px;background:var(--surface2);border-radius:8px;border-left:3px solid var(--accent3);">
<strong style="color:var(--accent3);">Retrieval instead of cramming</strong>
<span style="color:var(--text-dim);display:block;">Use RAG to find the relevant 2K tokens from 100K documents instead of sending everything.</span>
</div>
<div style="margin:8px 0;padding:10px;background:var(--surface2);border-radius:8px;border-left:3px solid var(--accent);">
<strong style="color:var(--accent);">Sparse attention patterns</strong>
<span style="color:var(--text-dim);display:block;">Only attend to nearby tokens + selected distant tokens. Reduces O(n^2) to O(n*sqrt(n)) or O(n*log(n)).</span>
</div>
<div style="margin:8px 0;padding:10px;background:var(--surface2);border-radius:8px;border-left:3px solid var(--accent6);">
<strong style="color:var(--accent6);">KV cache compression</strong>
<span style="color:var(--text-dim);display:block;">Evict old or low-attention KV pairs. Quantize cached values. Multi-query / grouped-query attention (GQA).</span>
</div>
<div style="margin:8px 0;padding:10px;background:var(--surface2);border-radius:8px;border-left:3px solid var(--accent4);">
<strong style="color:var(--accent4);">Context design</strong>
<span style="color:var(--text-dim);display:block;">Place critical info at the start and end. Summarize long sections. Use structured formats that models handle well.</span>
</div>
</div>
</div>
</div>
</div>
</section>
<hr class="divider">
<!-- ===== 9. SAFETY & MODERATION PIPELINE ===== -->
<section id="s9">
<h2>Safety & Moderation Pipeline</h2>
<p class="sub">Safety is not a single classifier — it's a pipeline of controls applied before, during, and after generation.</p>
<div class="card">
<h4 style="color:var(--accent4);margin-bottom:16px;">The full safety pipeline</h4>
<div class="flow">
<div class="flow-node input">User input<br><span style="font-size:0.72rem;">prompt + context</span></div>
<div class="flow-arrow">-></div>
<div class="flow-node warn">Input filter<br><span style="font-size:0.72rem;">block harmful prompts</span></div>
<div class="flow-arrow">-></div>
<div class="flow-node process">Tool gating<br><span style="font-size:0.72rem;">permission checks</span></div>
<div class="flow-arrow">-></div>
<div class="flow-node purple">Model<br><span style="font-size:0.72rem;">RLHF-aligned</span></div>
<div class="flow-arrow">-></div>
<div class="flow-node orange">Output filter<br><span style="font-size:0.72rem;">content moderation</span></div>
<div class="flow-arrow">-></div>
<div class="flow-node output">Response<br><span style="font-size:0.72rem;">or refusal</span></div>
</div>
<div style="margin-top:20px;display:grid;grid-template-columns:repeat(3,1fr);gap:12px;">
<div class="concept-card" style="border-color:rgba(255,230,109,0.3);">
<h4 style="color:var(--accent4);">Pre-generation</h4>
<p>Input classifiers detect jailbreak attempts, PII, or policy-violating prompts. System prompts enforce behavior boundaries. Tool permissions limit what the model can do.</p>
</div>
<div class="concept-card" style="border-color:rgba(168,130,255,0.3);">
<h4 style="color:var(--accent5);">During generation</h4>
<p>Constrained decoding can prevent certain token sequences. Watermarking embeds invisible signals. RLHF alignment means the model itself has learned to refuse unsafe requests.</p>
</div>
<div class="concept-card" style="border-color:rgba(255,159,67,0.3);">
<h4 style="color:var(--accent6);">Post-generation</h4>
<p>Output classifiers check for harmful content. PII redaction removes leaked data. Citation verification checks factual claims. Human review for high-stakes decisions.</p>
</div>
</div>
<div style="margin-top:16px;padding:12px;background:var(--surface2);border-radius:10px;font-size:0.82rem;color:var(--text-dim);">
<strong style="color:var(--accent4);">Key insight:</strong> No single mechanism catches everything. Layered defense ("defense in depth") is essential. The model's alignment (RLHF/RLAIF) is the foundation, but external guardrails add robustness.
</div>
</div>
</section>
<hr class="divider">
<!-- ===== 10. SCALABLE LLM SERVICE ARCHITECTURE ===== -->
<section id="s10">
<h2>Scalable LLM Service Architecture</h2>
<p class="sub">What it takes to turn "I have a model" into "I have a production service that handles 10,000 requests per second."</p>
<div class="card">
<h4 style="color:var(--accent3);margin-bottom:16px;">Full system diagram</h4>
<div style="display:flex;flex-direction:column;align-items:center;gap:0;">
<!-- Client tier -->
<div style="display:flex;gap:12px;margin-bottom:0;">
<div class="flow-node input" style="padding:10px 16px;">Web client</div>
<div class="flow-node input" style="padding:10px 16px;">Mobile app</div>
<div class="flow-node input" style="padding:10px 16px;">API consumer</div>
</div>
<div style="color:var(--text-dim);font-size:1rem;padding:6px 0;">|</div>
<!-- Gateway -->
<div class="flow-node warn" style="padding:12px 40px;">API Gateway / Load Balancer<br><span style="font-size:0.72rem;">Auth, rate limiting, routing</span></div>
<div style="color:var(--text-dim);font-size:1rem;padding:6px 0;">|</div>
<!-- Orchestration -->
<div class="flow-node process" style="padding:12px 40px;">Orchestration Layer<br><span style="font-size:0.72rem;">Prompt assembly, tool dispatch, retrieval</span></div>
<div style="display:flex;gap:30px;margin:8px 0;">
<div style="text-align:center;">
<div style="color:var(--text-dim);font-size:0.8rem;padding:4px;">|</div>
<div class="flow-node output" style="padding:8px 14px;font-size:0.78rem;">Vector DB<br><span style="font-size:0.68rem;">RAG retrieval</span></div>
</div>
<div style="text-align:center;">
<div style="color:var(--text-dim);font-size:0.8rem;padding:4px;">|</div>
<div class="flow-node orange" style="padding:8px 14px;font-size:0.78rem;">Tool APIs<br><span style="font-size:0.68rem;">search, compute</span></div>
</div>
<div style="text-align:center;">
<div style="color:var(--text-dim);font-size:0.8rem;padding:4px;">|</div>
<div class="flow-node purple" style="padding:8px 14px;font-size:0.78rem;">Cache<br><span style="font-size:0.68rem;">prompt + response</span></div>
</div>
</div>
<div style="color:var(--text-dim);font-size:1rem;padding:6px 0;">|</div>
<!-- Model serving -->
<div style="padding:16px 24px;border:2px solid var(--border);border-radius:16px;position:relative;">
<div style="position:absolute;top:-12px;left:16px;background:var(--surface);padding:0 8px;font-size:0.75rem;color:var(--text-dim);">Model Serving Cluster (autoscaled)</div>
<div style="display:flex;gap:12px;">
<div class="flow-node output" style="padding:10px 14px;font-size:0.78rem;">GPU Node 1<br><span style="font-size:0.68rem;">Model shard</span></div>
<div class="flow-node output" style="padding:10px 14px;font-size:0.78rem;">GPU Node 2<br><span style="font-size:0.68rem;">Model shard</span></div>
<div class="flow-node output" style="padding:10px 14px;font-size:0.78rem;">GPU Node N<br><span style="font-size:0.68rem;">Model shard</span></div>
</div>
</div>
<div style="color:var(--text-dim);font-size:1rem;padding:6px 0;">|</div>
<!-- Observability -->
<div style="display:flex;gap:12px;">
<div class="flow-node warn" style="padding:8px 14px;font-size:0.78rem;">Logging<br><span style="font-size:0.68rem;">traces, metrics</span></div>
<div class="flow-node warn" style="padding:8px 14px;font-size:0.78rem;">Evaluation<br><span style="font-size:0.68rem;">quality monitoring</span></div>
<div class="flow-node warn" style="padding:8px 14px;font-size:0.78rem;">Guardrails<br><span style="font-size:0.68rem;">safety, PII</span></div>
</div>
</div>
<div style="margin-top:24px;padding:14px;background:var(--surface2);border-radius:10px;">
<h4 style="color:var(--accent4);margin-bottom:8px;">Production components most teams underestimate</h4>
<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;font-size:0.82rem;">
<div style="padding:10px;background:var(--bg);border-radius:8px;border-left:3px solid var(--accent2);">
<strong style="color:var(--accent2);">Evaluation pipeline</strong>
<span style="color:var(--text-dim);display:block;">Continuous monitoring of output quality. Regression detection. A/B testing between model versions.</span>
</div>
<div style="padding:10px;background:var(--bg);border-radius:8px;border-left:3px solid var(--accent6);">
<strong style="color:var(--accent6);">Tiered model routing</strong>
<span style="color:var(--text-dim);display:block;">Route simple queries to cheaper/faster models. Reserve expensive models for hard tasks. Saves 60-80% compute.</span>
</div>
<div style="padding:10px;background:var(--bg);border-radius:8px;border-left:3px solid var(--accent5);">
<strong style="color:var(--accent5);">Rollback strategy</strong>
<span style="color:var(--text-dim);display:block;">When a new model version degrades quality, you need instant rollback. Model versioning + prompt versioning = complex matrix.</span>
</div>
</div>
</div>
</div>
</section>
</div>
</div><!-- page-main -->
</div><!-- page-layout -->
<footer style="text-align:center;padding:40px 0;color:var(--text-dim);font-size:0.8rem;border-top:1px solid var(--border);margin-top:40px;">
</footer>
<script>
// Auto-apply retina scaling to all raw canvases
(function() {
var dpr = window.devicePixelRatio || 1;
if (dpr <= 1) return;
var SKIP = {'softmax-canvas':1,'pr-curve':1,'residual-canvas':1,'sampling-canvas':1,'ce-canvas':1,'kl-canvas':1,'quant-chart':1,'cost-canvas':1,'forgetting-canvas':1,'act-canvas':1};
document.querySelectorAll('canvas').forEach(function(c) {
if (!c.id || SKIP[c.id] || c.dataset.retina) return;
c.dataset.retina = '1';
var w = c.width, h = c.height;
c.dataset.cssW = w;
c.dataset.cssH = h;
c.style.width = w + 'px';
c.style.height = h + 'px';
c.width = Math.round(w * dpr);
c.height = Math.round(h * dpr);
var origGetContext = c.getContext.bind(c);
var patched = false;
c.getContext = function(type, attrs) {
var ctx = origGetContext(type, attrs);
if (type === '2d' && !patched) {
patched = true;
ctx.scale(dpr, dpr);
}
return ctx;
};
});
})();
// ===== TEMPERATURE / TOP-K / TOP-P INTERACTIVE =====
const baseLogits = [3.5, 2.8, 2.1, 1.5, 1.2, 0.9, 0.7, 0.5, 0.3, 0.2, 0.15, 0.1, 0.08, 0.05, 0.03, 0.02, 0.01, 0.005, 0.003, 0.001];
const tokenNames = ['the','cat','a','sat','is','on','it','was','in','and','my','to','an','of','at','by','or','as','so','if'];
function softmax(arr) {
const max = Math.max(...arr);
const exps = arr.map(x => Math.exp(x - max));
const sum = exps.reduce((a,b) => a+b, 0);
return exps.map(e => e/sum);
}
// Chart.js dark theme defaults
Chart.defaults.color = '#8b8fa3';
Chart.defaults.borderColor = '#2e3244';
let samplingChart = null;
function updateSampling() {
const temp = document.getElementById('temp-slider').value / 100;
const topk = parseInt(document.getElementById('topk-slider').value);
const topp = document.getElementById('topp-slider').value / 100;
document.getElementById('temp-val').textContent = temp.toFixed(2);
document.getElementById('topk-val').textContent = topk >= 20 ? '20 (off)' : topk;
document.getElementById('topp-val').textContent = topp >= 1 ? '1.00 (off)' : topp.toFixed(2);
// Apply temperature
let logits = baseLogits.map(l => l / temp);
let probs = softmax(logits);
// Sort descending
let indexed = probs.map((p, i) => ({p, i, name: tokenNames[i]}));
indexed.sort((a, b) => b.p - a.p);
// Apply top-k
let kept = indexed.map((x, i) => ({...x, kept: true}));
if (topk < 20) {
kept.forEach((x, i) => { if (i >= topk) x.kept = false; });
}
// Apply top-p
if (topp < 1) {
let cumP = 0;
kept.forEach(x => {
if (!x.kept) return;
cumP += x.p;
if (cumP > topp && cumP - x.p > 0) {
if (cumP - x.p >= topp) x.kept = false;
}
});
}
// Renormalize kept
const keptSum = kept.filter(x => x.kept).reduce((s, x) => s + x.p, 0);
kept.forEach(x => { x.finalP = x.kept ? x.p / keptSum : 0; });
// Info text
const keptCount = kept.filter(x => x.kept).length;
const topToken = kept[0];
let info = `<strong style="color:var(--accent3);">${keptCount}</strong> tokens in the sampling pool. `;
info += `Top token "<strong style="color:var(--accent);">${topToken.name}</strong>" has ${(topToken.finalP*100).toFixed(1)}% probability.`;
if (temp < 0.3) info += ' <span style="color:var(--accent2);">Very focused — almost greedy.</span>';
else if (temp > 1.5) info += ' <span style="color:var(--accent4);">Very spread out — high randomness.</span>';
document.getElementById('sampling-info').innerHTML = info;
// Build Chart.js data
const labels = kept.map(x => x.name);
const values = kept.map(x => x.finalP * 100);
const bgColors = kept.map(x => x.kept ? 'rgba(108,99,255,0.7)' : 'rgba(255,107,107,0.15)');
const borderColors = kept.map(x => x.kept ? '#6c63ff' : 'rgba(255,107,107,0.4)');
if (!samplingChart) {
const ctx = document.getElementById('sampling-canvas').getContext('2d');
samplingChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Probability (%)',
data: values,
backgroundColor: bgColors,
borderColor: borderColors,
borderWidth: 1,
borderRadius: 3,
borderSkipped: 'bottom'
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
animation: { duration: 200 },
plugins: {
legend: { display: false },
tooltip: {
callbacks: {
label: function(ctx) {
return ctx.parsed.y.toFixed(1) + '%';
}
}
}
},
scales: {
x: {
grid: { display: false },
ticks: { font: { size: 10 } }
},
y: {
beginAtZero: true,
grid: { color: '#2e3244' },
ticks: {
font: { size: 10, family: 'monospace' },
callback: function(val) { return val.toFixed(0) + '%'; }
}
}
}
}
});
} else {
samplingChart.data.labels = labels;
samplingChart.data.datasets[0].data = values;
samplingChart.data.datasets[0].backgroundColor = bgColors;
samplingChart.data.datasets[0].borderColor = borderColors;
samplingChart.update();
}
}
updateSampling();
// ===== DECODING STRATEGY TREES =====
function drawTree(canvasId, type) {
const canvas = document.getElementById(canvasId);
const ctx = canvas.getContext('2d');
const w = canvas.width, h = canvas.height;
ctx.clearRect(0,0,w,h);
const colors = {
greedy: '#4ecdc4',
beam: '#6c63ff',
sample: '#ff6b6b'
};
// Root
ctx.fillStyle = '#ffe66d';
ctx.beginPath(); ctx.arc(w/2, 20, 8, 0, Math.PI*2); ctx.fill();
ctx.fillStyle = '#8b8fa3';
ctx.font = '9px sans-serif';
ctx.textAlign = 'center';
ctx.fillText('"The"', w/2, 12);
if (type === 'greedy') {
// Single path