-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathneural_thickets.py
More file actions
3095 lines (2730 loc) · 129 KB
/
Copy pathneural_thickets.py
File metadata and controls
3095 lines (2730 loc) · 129 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
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "altair==6.0.0",
# "anywidget>=0.10.0",
# "marimo>=0.23.2",
# "numpy>=2.4.4",
# "pandas==3.0.2",
# "plotly>=6.0.0",
# "torch>=2.11.0",
# ]
# ///
import marimo
__generated_with = "0.23.2"
app = marimo.App(width="medium", css_file="", auto_download=["html"])
@app.cell(hide_code=True)
def _():
import anywidget
import copy
import marimo as mo
import random
import math
from dataclasses import dataclass, replace
from types import SimpleNamespace
import pandas as pd
import altair as alt
import html as html_lib
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import torch
import traitlets
from simple_1D_signals_expts import datasets as signal_datasets_module
from simple_1D_signals_expts import models as signal_models_module
return (
SimpleNamespace,
anywidget,
copy,
go,
html_lib,
mo,
np,
signal_datasets_module,
signal_models_module,
torch,
traitlets,
)
@app.cell(hide_code=True)
def _(mo):
banner = """
<style>
.nt-paper-hero {
color: #1f2937;
margin: 0 0 24px;
overflow: hidden;
position: relative;
}
.nt-paper-hero__grid {
align-items: stretch;
display: grid;
gap: 22px;
grid-template-columns: minmax(0, 1.25fr) minmax(260px, 0.75fr);
padding: 30px 28px;
position: relative;
}
@media (max-width: 760px) {
.nt-paper-hero__grid {
grid-template-columns: 1fr;
padding: 24px 18px;
}
.nt-paper-hero h1 {
font-size: 1.9rem !important;
}
}
</style>
<div class="nt-paper-hero">
<div class="nt-paper-hero__grid">
<div>
<div style="display:inline-flex;align-items:center;gap:8px;padding:6px 10px;border:1px solid #bae6fd;background:rgba(240,249,255,0.78);border-radius:999px;color:#0369a1;font-size:0.76rem;font-weight:800;letter-spacing:0;text-transform:uppercase;">
Paper Explainer
</div>
<h1 style="margin:14px 0 10px;color:#111827;font-size:2.35rem;line-height:1.06;font-weight:850;letter-spacing:0;">
Neural Thickets
</h1>
<p style="margin:0;max-width:650px;color:#374151;font-size:1.05rem;line-height:1.52;">
What if pretraining does more than initialize a model? This notebook explores the
paper's claim that many task-specialized experts can live densely near pretrained
weights, making random local perturbations a plausible post-training strategy.
</p>
<div style="margin-top:18px;color:#475569;font-size:0.92rem;line-height:1.5;">
<div>
Submission for the
<a href="https://marimo.io/pages/events/notebook-competition" style="color:#2563eb;text-decoration:none;font-weight:750;">molab Notebook Competition</a>
</div>
<div>
Notebook by <b style="color:#111827;">Akash Sharma</b>
· <a href="https://x.com/mathcrush247" style="color:#2563eb;text-decoration:none;font-weight:750;">X</a>
· <a href="https://github.com/akashrma" style="color:#2563eb;text-decoration:none;font-weight:750;">GitHub</a>
</div>
</div>
</div>
<div style="display:flex;flex-direction:column;justify-content:space-between;gap:14px;border:1px solid rgba(148,163,184,0.35);background:rgba(255,255,255,0.62);border-radius:8px;padding:16px 16px 14px;box-shadow:0 12px 30px rgba(148,163,184,0.13);">
<div>
<div style="color:#64748b;font-size:0.72rem;font-weight:850;letter-spacing:0;text-transform:uppercase;margin-bottom:7px;">Original paper</div>
<div style="font-size:1rem;line-height:1.35;font-weight:800;color:#111827;">Diverse Task Experts Are Dense Around Pretrained Weights</div>
<div style="margin-top:7px;color:#475569;font-size:0.9rem;line-height:1.35;">Yulu Gan · Phillip Isola</div>
<a href="https://www.alphaxiv.org/abs/2603.12228" style="display:inline-block;margin-top:8px;color:#2563eb;font-size:0.9rem;font-weight:750;text-decoration:none;">alphaxiv:2603.12228</a>
</div>
<svg viewBox="0 0 320 148" role="img" aria-label="Abstract thicket of nearby task experts around pretrained weights" style="width:100%;height:auto;display:block;">
<defs>
<radialGradient id="nt-thicket-glow" cx="50%" cy="50%" r="55%">
<stop offset="0%" stop-color="#ffffff" stop-opacity="0.98"/>
<stop offset="38%" stop-color="#bfdbfe" stop-opacity="0.82"/>
<stop offset="68%" stop-color="#bbf7d0" stop-opacity="0.52"/>
<stop offset="100%" stop-color="#fed7aa" stop-opacity="0"/>
</radialGradient>
<radialGradient id="nt-point-blue" cx="38%" cy="35%" r="68%">
<stop offset="0%" stop-color="#ffffff" stop-opacity="0.95"/>
<stop offset="100%" stop-color="#60a5fa" stop-opacity="0.96"/>
</radialGradient>
<radialGradient id="nt-point-green" cx="38%" cy="35%" r="68%">
<stop offset="0%" stop-color="#ffffff" stop-opacity="0.95"/>
<stop offset="100%" stop-color="#4ade80" stop-opacity="0.96"/>
</radialGradient>
<radialGradient id="nt-point-peach" cx="38%" cy="35%" r="68%">
<stop offset="0%" stop-color="#ffffff" stop-opacity="0.95"/>
<stop offset="100%" stop-color="#fb923c" stop-opacity="0.92"/>
</radialGradient>
<radialGradient id="nt-point-pink" cx="38%" cy="35%" r="68%">
<stop offset="0%" stop-color="#ffffff" stop-opacity="0.95"/>
<stop offset="100%" stop-color="#f472b6" stop-opacity="0.92"/>
</radialGradient>
<filter id="nt-soft-blur" x="-30%" y="-30%" width="160%" height="160%">
<feGaussianBlur stdDeviation="0.5"/>
</filter>
<filter id="nt-star-shadow" x="-40%" y="-40%" width="180%" height="180%">
<feDropShadow dx="0" dy="7" stdDeviation="6" flood-color="#64748b" flood-opacity="0.25"/>
</filter>
</defs>
<rect x="0" y="0" width="320" height="148" rx="8" fill="#f8fafc"/>
<circle cx="160" cy="74" r="82" fill="url(#nt-thicket-glow)"/>
<g filter="url(#nt-soft-blur)">
<circle cx="108" cy="45" r="12" fill="#93c5fd" opacity="0.24"/>
<circle cx="219" cy="47" r="16" fill="#86efac" opacity="0.24"/>
<circle cx="105" cy="105" r="15" fill="#fdba74" opacity="0.22"/>
<circle cx="225" cy="103" r="13" fill="#f9a8d4" opacity="0.24"/>
</g>
<g stroke="#ffffff" stroke-width="1.4">
<circle cx="120" cy="59" r="4.8" fill="url(#nt-point-blue)"/>
<circle cx="139" cy="43" r="3.4" fill="url(#nt-point-green)" opacity="0.88"/>
<circle cx="184" cy="46" r="4.6" fill="url(#nt-point-peach)"/>
<circle cx="210" cy="64" r="3.7" fill="url(#nt-point-pink)" opacity="0.9"/>
<circle cx="132" cy="93" r="4.4" fill="url(#nt-point-peach)"/>
<circle cx="188" cy="99" r="4.2" fill="url(#nt-point-blue)" opacity="0.9"/>
<circle cx="219" cy="91" r="3.2" fill="url(#nt-point-green)" opacity="0.84"/>
<circle cx="100" cy="82" r="3.5" fill="url(#nt-point-pink)" opacity="0.82"/>
<circle cx="151" cy="109" r="3.1" fill="url(#nt-point-green)" opacity="0.78"/>
<circle cx="231" cy="44" r="2.8" fill="url(#nt-point-blue)" opacity="0.74"/>
<circle cx="91" cy="52" r="2.7" fill="url(#nt-point-green)" opacity="0.72"/>
<circle cx="244" cy="78" r="2.5" fill="url(#nt-point-peach)" opacity="0.7"/>
</g>
<path d="M160 63.5 L163 70.3 L170.4 71.1 L164.8 76.1 L166.4 83.4 L160 79.7 L153.6 83.4 L155.2 76.1 L149.6 71.1 L157 70.3 Z" fill="#111827" stroke="#ffffff" stroke-width="1.8" stroke-linejoin="round" filter="url(#nt-star-shadow)"/>
</svg>
</div>
</div>
</div>
"""
mo.Html(banner)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
**Reader's note.** This notebook is best viewed in **app view** with the **vertical** layout setting, and it is meant to be read after running all cells once. It is CPU-friendly, should run directly from the molab link and default experimental settings are recommended $-$ however, settings have been configurable so the reader can experiment independently.
If you want to tinker with it locally, especially with the imports for the 1D toy experiment, use the GitHub repo: [akashrma/neural-thickets-molab](https://github.com/akashrma/neural-thickets-molab).
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## **The Post-Training Bottleneck**
The modern LLM pipeline is firmly established: massive self-supervised pretraining followed by alignment-focused post-training. While pretraining endows a model with general representations and reasoning priors, post-training is required to surface specialized behaviors—like instruction following, code generation, or complex mathematical reasoning.
However, post-training is computationally brutal and notoriously brittle. Algorithms like RLHF, PPO, DPO, and GRPO require calculating gradients through massive networks, maintaining KL-divergence penalties, training auxiliary reward models, and navigating extreme hyperparameter sensitivity.
If explicit post-training is this expensive and difficult, is there a simpler alternative?
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## **Enter Neural Thickets**
In this notebook, we explore an alternative by diving into the core ideas of [Neural Thickets: Diverse Task Experts Are Dense Around Pretrained Weights](https://www.alphaxiv.org/abs/2603.12228) by Yulu Gan and Phillip Isola.
The authors observe an interesting after-effect of scaling and pretraining: in the parameter space of large language models, high-performing, task-specific "expert" solutions reside densely in the immediate neighborhood of the pretrained base weights. Even better, as models scale up, the density of these solutions increases.
This phenomenon unlocks an idea that sounds almost absurd at first: **_what if we just randomly perturb the pretrained weights and keep the ones that work?_** Because of this dense "thicket" of solutions, we can achieve state-of-the-art post-training alignment not through expensive gradient-based optimization, but through highly parallel random guessing.
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## **What does this all mean and how is it useful?**
The main goal of this notebook is to make the Neural Thickets idea feel concrete. The paper's proposal can sound strange on first contact: instead of carefully optimizing a model after pretraining, sample random nearby perturbations and keep the ones that work. Why should that ever be reasonable?
We will build up to that answer in three layers:
1. **Intuition for random guessing.** We start with a small grid game to show the difference between a sparse needle-in-a-haystack regime and a dense thicket regime.
2. **Interactive extensions of the paper's 1D toy experiment.** We use the original RandOpt toy-model code and extend the visualizations so you can inspect solution density, perturbation diversity, complementary experts, and top-k ensembling directly.
3. **A new exploratory direction: Controllable RandOpt.** This part is our notebook extension, not a result from the paper. We sketch how changing the sampling distribution could reduce the need for brute-force parallel perturbation evaluation when parallel compute is limited.
In short: the paper gives the thicket hypothesis and RandOpt; this notebook tries to make the geometry, trade-offs, and possible next questions easier to see.
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
# **A Game of Random Guessing**
As we've established, traditional post-training methods like PPO or SFT can be a delicate, computationally expensive dance. This paper proposes bypassing this complexity by leaning entirely on the geometry of the pretrained model's local weight landscape. **_Instead of carefully steering the model with gradients, what if we just roll the dice?_**
To intuitively grasp why this seemingly naïve approach might actually succeed, let's play a quick game.
Imagine the center of the grid ⭐ below represents your base pretrained model. Each click on the board is a random tweak (perturbation) to those weights, and a hidden diamond 💎 represents a "task expert" $-$ a specific configuration that performs much better on your downstream task.
- **1 Diamond**: If there is only one diamond hidden on the board, you are in the **needle-in-a-haystack regime**. Randomly clicking around is frustrating and highly unlikely to yield a good result.
- **Multiple Diamonds**: As you increase the number of diamonds, you enter the **thicket regime**. Here, useful task experts are so densely packed around the starting point that you are almost guaranteed to stumble upon one with just a few guesses.
<u>**Your goal is simple**</u>: adjust the number of diamonds to see the difference in density, and start clicking (or use Auto search) until you uncover an expert. Also note how scaling the grid makes the needle-in-a-haystack regime harder to win.
""")
return
@app.cell(hide_code=True)
def _(html_lib, mo):
game_html = r"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="nt-self-contained-game" class="nt-game">
<style>
body {
margin: 0;
}
#nt-self-contained-game {
--nt-cell-size: 24px;
color: #24292f;
font-family: var(--nt-parent-font-family, inherit);
}
#nt-self-contained-game * {
box-sizing: border-box;
}
#nt-self-contained-game .nt-game-layout {
align-items: flex-start;
display: flex;
flex-wrap: wrap;
gap: 16px;
width: 100%;
}
#nt-self-contained-game .nt-panel {
background: #f8fafc;
border: 1px solid #d0d7de;
border-radius: 8px;
box-shadow: 0 6px 18px rgba(15, 23, 42, 0.10);
padding: 12px 14px;
}
#nt-self-contained-game .nt-left {
flex: 1.2 1 430px;
min-width: min(100%, 430px);
}
#nt-self-contained-game .nt-right {
flex: 0.8 1 250px;
min-width: min(100%, 250px);
}
#nt-self-contained-game h2,
#nt-self-contained-game h3 {
margin: 0 0 8px;
}
#nt-self-contained-game h2 {
font-size: 1rem;
}
#nt-self-contained-game h3 {
font-size: 0.9rem;
}
#nt-self-contained-game p {
line-height: 1.5;
margin: 0 0 10px;
}
#nt-self-contained-game .nt-left > p,
#nt-self-contained-game .nt-right h3,
#nt-self-contained-game .nt-right p {
display: none;
}
#nt-self-contained-game .nt-controls {
align-items: end;
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-bottom: 12px;
}
#nt-self-contained-game .nt-control {
flex: 1 1 160px;
min-width: 160px;
}
#nt-self-contained-game label {
color: #57606a;
display: block;
font-size: 0.82rem;
font-weight: 600;
margin-bottom: 7px;
}
#nt-self-contained-game input[type="range"] {
accent-color: #0969da;
width: 100%;
}
#nt-self-contained-game .nt-value {
color: #24292f;
font-variant-numeric: tabular-nums;
font-weight: 600;
}
#nt-self-contained-game .nt-action-button {
background: #f6f8fa;
border-color: #ffffff #7b7b7b #7b7b7b #ffffff;
border-style: solid;
border-width: 2px;
color: #24292f;
cursor: pointer;
font-weight: 600;
min-height: 36px;
padding: 6px 14px;
}
#nt-self-contained-game .nt-action-button:active {
border-color: #7b7b7b #ffffff #ffffff #7b7b7b;
padding: 7px 13px 5px 15px;
}
#nt-self-contained-game .nt-action-button:disabled {
color: #6e7781;
cursor: default;
}
#nt-self-contained-game .nt-auto-active {
background: #fff8c5;
}
#nt-self-contained-game .nt-board-wrap {
overflow-x: visible;
padding-bottom: 4px;
}
#nt-self-contained-game .nt-mine-board {
background: #bdbdbd;
border-color: #7b7b7b #ffffff #ffffff #7b7b7b;
border-style: solid;
border-width: 3px;
display: inline-block;
padding: 6px;
}
#nt-self-contained-game .nt-mine-topbar {
align-items: center;
background: #bdbdbd;
border-color: #7b7b7b #ffffff #ffffff #7b7b7b;
border-style: solid;
border-width: 3px;
display: flex;
justify-content: space-between;
margin-bottom: 6px;
padding: 4px;
}
#nt-self-contained-game .nt-counter {
background: #111111;
border-color: #7b7b7b #ffffff #ffffff #7b7b7b;
border-style: solid;
border-width: 2px;
color: #f43f3f;
font-size: 0.92rem;
font-weight: 700;
font-variant-numeric: tabular-nums;
line-height: 1;
min-width: 46px;
padding: 4px 5px;
text-align: right;
}
#nt-self-contained-game .nt-face {
align-items: center;
background: #c6c6c6;
border-color: #ffffff #7b7b7b #7b7b7b #ffffff;
border-style: solid;
border-width: 2px;
cursor: pointer;
display: flex;
font-size: 0.9rem;
font-weight: 700;
height: 30px;
justify-content: center;
line-height: 1;
padding: 0;
width: 30px;
}
#nt-self-contained-game .nt-face:active {
border-color: #7b7b7b #ffffff #ffffff #7b7b7b;
}
#nt-self-contained-game .nt-grid {
display: grid;
gap: 0;
}
#nt-self-contained-game .nt-cell {
align-items: center;
background: #c6c6c6;
border-color: #ffffff #7b7b7b #7b7b7b #ffffff;
border-style: solid;
border-width: 1px;
color: #111111;
cursor: pointer;
display: flex;
font-size: clamp(0.35rem, calc(var(--nt-cell-size) * 0.52), 0.9rem);
font-weight: 700;
height: var(--nt-cell-size);
justify-content: center;
line-height: 1;
padding: 0;
user-select: none;
width: var(--nt-cell-size);
}
#nt-self-contained-game .nt-cell:hover {
background: #d3d3d3;
}
#nt-self-contained-game .nt-cell:disabled {
cursor: default;
}
#nt-self-contained-game .nt-cell.nt-revealed {
background: #bdbdbd;
border-color: #9a9a9a;
border-width: 1px;
color: #555555;
}
#nt-self-contained-game .nt-cell.nt-diamond {
color: #111111;
}
#nt-self-contained-game .nt-cell.nt-origin {
color: #111111;
cursor: default;
}
#nt-self-contained-game .nt-status {
align-items: center;
background: #ffffff;
border: 1px solid #d8dee4;
border-radius: 6px;
display: flex;
font-weight: 600;
gap: 8px;
margin: 8px 0 10px;
padding: 8px 10px;
}
#nt-self-contained-game .nt-info-grid {
display: grid;
gap: 8px;
grid-template-columns: repeat(2, minmax(0, 1fr));
margin: 8px 0 10px;
}
#nt-self-contained-game .nt-stat {
background: #ffffff;
border: 1px solid #d8dee4;
border-radius: 6px;
padding: 8px 10px;
}
#nt-self-contained-game .nt-stat-label {
color: #57606a;
display: block;
font-size: 0.74rem;
font-weight: 600;
line-height: 1.2;
margin-bottom: 4px;
text-transform: uppercase;
}
#nt-self-contained-game .nt-stat-value {
color: #24292f;
display: block;
font-size: 1.02rem;
font-weight: 600;
font-variant-numeric: tabular-nums;
line-height: 1.25;
}
@media (max-width: 900px) {
#nt-self-contained-game .nt-game-layout {
gap: 12px;
}
#nt-self-contained-game {
--nt-cell-size: 22px;
}
#nt-self-contained-game .nt-cell {
height: var(--nt-cell-size);
width: var(--nt-cell-size);
}
#nt-self-contained-game .nt-counter {
font-size: 0.95rem;
min-width: 44px;
}
#nt-self-contained-game .nt-info-grid {
grid-template-columns: 1fr;
}
}
</style>
<div class="nt-game-layout">
<section class="nt-panel nt-left">
<h2>Grid controls</h2>
<p>
Start with <strong>1 diamond</strong> for the needle-in-a-haystack
regime. Increase the number of diamonds to create a denser thicket.
</p>
<div class="nt-controls">
<div class="nt-control">
<label for="nt-grid-size">Grid size: <span class="nt-value" data-role="grid-value">9</span></label>
<input id="nt-grid-size" data-role="grid-size" type="range" min="9" max="81" step="2" value="9">
</div>
<div class="nt-control">
<label for="nt-diamond-count">Number of diamonds: <span class="nt-value" data-role="diamond-value">1</span></label>
<input id="nt-diamond-count" data-role="diamond-count" type="range" min="1" max="200" step="1" value="1">
</div>
<button class="nt-action-button" type="button" data-role="new-game">New game</button>
<button class="nt-action-button" type="button" data-role="auto-search">Auto search</button>
</div>
<h2>Grid game</h2>
<div class="nt-board-wrap">
<div class="nt-mine-board" data-role="board">
<div class="nt-mine-topbar">
<div class="nt-counter" data-role="mines-left">001</div>
<button class="nt-face" type="button" data-role="face">:)</button>
<div class="nt-counter" data-role="step-count">000</div>
</div>
<div class="nt-grid" data-role="grid"></div>
</div>
</div>
</section>
<section class="nt-panel nt-right">
<h2>Probabilistic details</h2>
<div class="nt-status">
<span data-role="status-icon">?</span>
<span data-role="status-text">Still searching.</span>
</div>
<div class="nt-info-grid" data-role="stats"></div>
<h3>Interpretation</h3>
<p>
With <strong>one diamond</strong>, useful solutions are sparse: this
is the <strong>needle-in-a-haystack</strong> regime.
</p>
<p>
As the number of diamonds increases, the local neighborhood becomes
denser with useful solutions: this is the <strong>thicket</strong> regime.
</p>
</section>
</div>
<script>
(() => {
const root = document.currentScript.closest("#nt-self-contained-game");
if (!root) {
return;
}
try {
const parentFontFamily = window.parent.getComputedStyle(
window.parent.document.body
).fontFamily;
if (parentFontFamily) {
root.style.setProperty("--nt-parent-font-family", parentFontFamily);
}
} catch {
root.style.setProperty("--nt-parent-font-family", "inherit");
}
const els = {
gridSize: root.querySelector("[data-role='grid-size']"),
gridValue: root.querySelector("[data-role='grid-value']"),
diamondCount: root.querySelector("[data-role='diamond-count']"),
diamondValue: root.querySelector("[data-role='diamond-value']"),
newGame: root.querySelector("[data-role='new-game']"),
autoSearch: root.querySelector("[data-role='auto-search']"),
face: root.querySelector("[data-role='face']"),
grid: root.querySelector("[data-role='grid']"),
minesLeft: root.querySelector("[data-role='mines-left']"),
stepCount: root.querySelector("[data-role='step-count']"),
statusIcon: root.querySelector("[data-role='status-icon']"),
statusText: root.querySelector("[data-role='status-text']"),
stats: root.querySelector("[data-role='stats']"),
};
let game = null;
let autoTimer = null;
function centerCell(size) {
return Math.floor(size / 2);
}
function cellKey(row, col) {
return `${row},${col}`;
}
function clampDiamondCount(size, count) {
return Math.max(1, Math.min(count, size * size - 1));
}
function formatCounter(value) {
return String(Math.max(0, value)).padStart(3, "0").slice(-3);
}
function formatPercent(value) {
return `${(value * 100).toFixed(4)}%`;
}
function setCompactCellSize(size) {
const cellSize = Math.max(4, Math.min(24, Math.floor(330 / size)));
root.style.setProperty("--nt-cell-size", `${cellSize}px`);
}
function combinationsRatio(total, diamonds, guesses) {
if (guesses <= 0) {
return 0;
}
if (guesses > total - diamonds) {
return 1;
}
let miss = 1;
for (let i = 0; i < guesses; i += 1) {
miss *= (total - diamonds - i) / (total - i);
}
return 1 - miss;
}
function isAutoRunning() {
return autoTimer !== null;
}
function updateAutoButton() {
els.autoSearch.textContent = isAutoRunning() ? "Stop auto" : "Auto search";
els.autoSearch.classList.toggle("nt-auto-active", isAutoRunning());
els.autoSearch.disabled = Boolean(game && game.won);
}
function stopAuto() {
if (autoTimer !== null) {
window.clearInterval(autoTimer);
autoTimer = null;
}
updateAutoButton();
}
function hiddenClickableCells() {
const center = centerCell(game.size);
const cells = [];
for (let row = 0; row < game.size; row += 1) {
for (let col = 0; col < game.size; col += 1) {
const key = cellKey(row, col);
if ((row !== center || col !== center) && !game.revealed.has(key)) {
cells.push([row, col]);
}
}
}
return cells;
}
function autoStep() {
if (!game || game.won) {
stopAuto();
return;
}
const cells = hiddenClickableCells();
if (cells.length === 0) {
stopAuto();
return;
}
const [row, col] = cells[Math.floor(Math.random() * cells.length)];
reveal(row, col);
}
function startAuto() {
if (!game || game.won || isAutoRunning()) {
return;
}
autoTimer = window.setInterval(autoStep, 90);
autoStep();
updateAutoButton();
}
function toggleAuto() {
if (isAutoRunning()) {
stopAuto();
} else {
startAuto();
}
}
function makeGame() {
stopAuto();
const size = Number(els.gridSize.value);
const requestedDiamonds = Number(els.diamondCount.value);
const diamonds = clampDiamondCount(size, requestedDiamonds);
const center = centerCell(size);
const candidates = [];
setCompactCellSize(size);
els.diamondCount.max = String(size * size - 1);
els.diamondCount.value = String(diamonds);
els.gridValue.textContent = String(size);
els.diamondValue.textContent = String(diamonds);
for (let row = 0; row < size; row += 1) {
for (let col = 0; col < size; col += 1) {
if (row !== center || col !== center) {
candidates.push(cellKey(row, col));
}
}
}
const diamondSet = new Set();
while (diamondSet.size < diamonds) {
const index = Math.floor(Math.random() * candidates.length);
diamondSet.add(candidates[index]);
}
game = {
size,
diamonds,
diamondSet,
revealed: new Set(),
steps: 0,
won: false,
};
render();
}
function reveal(row, col) {
if (!game || game.won) {
return;
}
const center = centerCell(game.size);
const key = cellKey(row, col);
if ((row === center && col === center) || game.revealed.has(key)) {
return;
}
game.revealed.add(key);
game.steps += 1;
game.won = game.diamondSet.has(key);
if (game.won) {
stopAuto();
}
render();
}
function renderGrid() {
const center = centerCell(game.size);
els.grid.innerHTML = "";
els.grid.style.gridTemplateColumns = `repeat(${game.size}, var(--nt-cell-size))`;
for (let row = 0; row < game.size; row += 1) {
for (let col = 0; col < game.size; col += 1) {
const button = document.createElement("button");
const key = cellKey(row, col);
button.className = "nt-cell";
button.type = "button";
button.setAttribute("aria-label", `Reveal row ${row + 1}, column ${col + 1}`);
const shouldReveal = game.won || game.revealed.has(key);
if (row === center && col === center) {
button.classList.add("nt-origin");
button.disabled = true;
button.textContent = "⭐";
button.title = "pretrained weights";
} else if (shouldReveal) {
button.classList.add("nt-revealed");
button.disabled = true;
if (game.diamondSet.has(key)) {
button.classList.add("nt-diamond");
button.textContent = "💎";
button.title = "task expert";
} else {
button.title = "empty cell";
}
} else {
button.title = "covered cell";
button.addEventListener("click", () => reveal(row, col));
}
els.grid.appendChild(button);
}
}
}
function renderStats() {
const total = game.size * game.size - 1;
const revealedDiamonds = [...game.revealed].filter((key) => game.diamondSet.has(key)).length;
const remainingHidden = total - game.revealed.size;
const remainingDiamonds = game.diamonds - revealedDiamonds;
const initialSuccess = game.diamonds / total;
const nextSuccess = remainingHidden === 0 || game.won
? 0
: remainingDiamonds / remainingHidden;
const cumulative = combinationsRatio(total, game.diamonds, Math.min(game.steps, total));
const expected = (total + 1) / (game.diamonds + 1);
const stats = [
["Guesses made", String(game.steps)],
["Clickable cells", String(total)],
["Diamonds in grid", String(game.diamonds)],
["Initial success", formatPercent(initialSuccess)],
["Next-click success", formatPercent(nextSuccess)],
["Won by now", formatPercent(cumulative)],
["Expected guesses", expected.toFixed(2)],
];
els.stats.innerHTML = stats.map(([label, value]) => `
<div class="nt-stat">
<span class="nt-stat-label">${label}</span>
<span class="nt-stat-value">${value}</span>
</div>
`).join("");
}
function render() {
if (!game) {
return;
}
const revealedDiamonds = [...game.revealed].filter((key) => game.diamondSet.has(key)).length;
els.minesLeft.textContent = formatCounter(
game.won ? 0 : game.diamonds - revealedDiamonds
);
els.stepCount.textContent = formatCounter(game.steps);
els.face.textContent = game.won ? "B)" : ":)";
els.statusIcon.textContent = game.won ? "💎" : "?";
els.statusText.textContent = game.won
? "You found a task expert."
: "Still searching.";
renderGrid();
renderStats();
updateAutoButton();
}
els.gridSize.addEventListener("input", makeGame);
els.diamondCount.addEventListener("input", makeGame);
els.newGame.addEventListener("click", makeGame);
els.autoSearch.addEventListener("click", toggleAuto);
els.face.addEventListener("click", makeGame);
makeGame();
})();
</script>
</div>
</body>
</html>
"""
mo.Html(
f"""
<iframe
title="Minesweeper grid game"
srcdoc="{html_lib.escape(game_html, quote=True)}"
style="border: 0; display: block; height: 520px; width: 100%;"
></iframe>
"""
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
# **From Grids to the Loss Landscape: The Scaling Law**
With one diamond, random guessing is painfully inefficient: useful solutions are sparse, like a needle in a haystack.
As you increase the number of diamonds, finding one becomes much easier. This represents the paper's density scaling claim: as models scale up and undergo massive pretraining, the nearby parameter space can contain many task-specialized solutions.
We do not know the exact solution locations, but the thicket hypothesis says many good solutions are nearby. Why does this matter? The answer comes down to **computational time**. Let's map our 2D grid game onto an actual 3D **Loss Landscape** (where lower elevation means fewer errors):
- **The Starting Point (Black Diamond):** The pretrained base model weights ($\theta$). It sits on a high plateau, meaning its performance on our specific downstream task isn't great yet.
- **The Pockets:** The deep holes surrounding the center. These are the "Diamonds" from our game—local minima that act as "experts" for our specific task.
- **A Random Guess:** Adding one random Gaussian perturbation to the pretrained weights ($\theta + \epsilon$), constrained by the search window.
In sparse _needle-in-a-haystack_ regimes, random guessing is usually impractical, so we rely on sequential optimization methods such as SGD or post-training algorithms. In dense thicket regimes, parallel random perturbations can become competitive because many nearby directions already contain useful experts.
Interact with the landscape below to see how optimization changes when we enter the thicket regime:
1. **Run SGD (Sequential):** Stochastic Gradient Descent calculates the slope and takes a step downward. Use the slider to watch it navigate. It successfully finds an expert, but it requires **$T$ sequential forward and backward passes** to get there.
2. **Run Random Perturbation Search (Parallel):** If we know the landscape around $\theta$ is a densely packed thicket, we don't need to walk step-by-step. We can sample 50 Gaussian perturbations inside the dashed search window and evaluate them simultaneously. This can hit a minimum in exactly **1 step** ($\mathcal{O}(1)$ time).
""")
return
@app.cell(hide_code=True)
def _(mo):
active_mode, set_active_mode = mo.state("start")
perturbation_run, set_perturbation_run = mo.state(0)
return active_mode, perturbation_run, set_active_mode, set_perturbation_run
@app.cell(hide_code=True)
def _(mo):
sgd_frame = mo.ui.slider(
start=0,
stop=32,
step=1,
value=0,
show_value=True,
label="SGD frame",
full_width=True,
)
return (sgd_frame,)
@app.cell(hide_code=True)
def _(mo, set_active_mode, set_perturbation_run):
def run_perturbation_click(_):
set_perturbation_run(lambda run: run + 1)
set_active_mode("perturbation")