-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathself-attention.html
More file actions
629 lines (521 loc) · 33.2 KB
/
self-attention.html
File metadata and controls
629 lines (521 loc) · 33.2 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
<!DOCTYPE html>
<html lang="uk">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Transformer Attention: Full Math & 3D</title>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.160.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"
}
}
</script>
<script>
MathJax = { tex: { inlineMath: [['$', '$'], ['\\(', '\\)']] } };
</script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<style>
:root {
--bg: #f8fafc; --panel: #ffffff; --text: #1e293b; --border: #cbd5e1;
--accent: #4f46e5;
--ctx-bio: #16a34a;
--ctx-music: #2563eb;
--ctx-admin: #db2777;
}
body { margin: 0; font-family: 'Segoe UI', system-ui, sans-serif; background: var(--bg); color: var(--text); overflow: hidden; display: flex; height: 100vh; }
/* Ліва панель (Ширша для формул) */
#sidebar {
width: 50%; min-width: 480px; overflow-y: auto; padding: 25px;
background: var(--panel); border-right: 1px solid var(--border);
box-shadow: 2px 0 5px rgba(0,0,0,0.05);
display: flex; flex-direction: column; gap: 25px;
}
#canvas-container {
flex-grow: 1; position: relative; background: #0f172a; overflow: hidden;
}
h1 { margin: 0; font-size: 1.6rem; color: var(--accent); }
h2 { font-size: 1.2rem; border-bottom: 2px solid var(--accent); padding-bottom: 5px; margin-top: 15px; color: #334155; }
h3 { font-size: 1rem; margin-bottom: 5px; color: #475569; font-weight: 600; margin-top: 15px;}
p { font-size: 0.95rem; line-height: 1.6; color: #475569; margin-bottom: 10px; }
.step-box { background: #f1f5f9; border: 1px solid var(--border); border-radius: 8px; padding: 20px; }
.controls { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 10px; }
button {
padding: 8px 14px; border: 1px solid var(--border); border-radius: 6px;
cursor: pointer; background: white; font-size: 0.9rem; transition: all 0.2s;
}
button:hover { background: #e2e8f0; }
button.active { background: var(--accent); color: white; border-color: var(--accent); }
/* Таблиці */
.matrix-wrapper { overflow-x: auto; margin: 10px 0; border: 1px solid #e2e8f0; border-radius: 4px;}
table { border-collapse: collapse; font-family: monospace; font-size: 0.8rem; width: 100%; background: white; }
td, th { border: 1px solid #cbd5e1; padding: 4px 8px; text-align: center; }
th { background: #e2e8f0; font-weight: bold; }
.highlight-cell { background-color: #fef08a; font-weight: bold; border: 2px solid #f59e0b; }
/* Пояснення */
.math-expl {
font-size: 0.9rem; background: #fffbeb; padding: 12px;
border-left: 4px solid #f59e0b; margin: 10px 0; border-radius: 0 4px 4px 0;
}
/* 3D Legend */
#scene-legend {
position: absolute; top: 15px; right: 15px;
background: rgba(15, 23, 42, 0.85); color: white;
padding: 15px; border-radius: 8px; font-size: 0.85rem;
pointer-events: none; backdrop-filter: blur(4px);
}
.label {
position: absolute; color: white; font-family: sans-serif; font-size: 11px; font-weight: bold;
background: rgba(0,0,0,0.7); padding: 3px 6px; border-radius: 4px;
pointer-events: none; user-select: none; transition: opacity 0.2s;
}
</style>
</head>
<body>
<div id="sidebar">
<div>
<h1>Алгебраїчні методи ШІ: Self-Attention</h1>
<details style="margin-top: 20px; background: #fff; border: 1px solid #cbd5e1; border-radius: 8px; overflow: hidden;">
<summary style="padding: 15px; cursor: pointer; background: #e2e8f0; font-weight: bold; color: #334155; list-style: none; display: flex; align-items: center; justify-content: space-between;">
<span>📚 Теоретичний довідник</span>
<span style="font-size: 1.2em;">▼</span>
</summary>
<div style="padding: 20px; font-size: 0.9rem; color: #334155;">
<h3 style="margin-top:0;">1. Структура мереж з Увагою</h3>
<p>Механізм Self-Attention вперше став популярним не в Трансформерах, а в RNN (LSTM) для машинного перекладу, щоб вирішити проблему "забування" початку речення. Але Трансформер (2017) відмовився від рекурентності (послідовної обробки) на користь паралельної уваги.</p>
<ul>
<li><b>Attention (Увага):</b> Механізм пошуку зв'язків між усіма словами речення одночасно.</li>
<li><b>Feed-Forward Network (FFN):</b> Звичайна нейромережа, яка обробляє кожне слово окремо після блоку уваги.</li>
<li><b>Residual Connection ($x + f(x)$):</b> Дозволяє градієнтам "протікати" крізь глибоку мережу без згасання.</li>
</ul>
<hr style="border: 0; border-top: 1px solid #e2e8f0; margin: 15px 0;">
<h3>2. Математичний апарат</h3>
<h4>Скалярний добуток (Dot Product)</h4>
<p>У формулі $Q \cdot K^T$ ми виконуємо множення матриць. Якщо розглядати два вектори $a$ і $b$:</p>
<ul>
<li><b>Алгебраїчно:</b> $\sum a_i b_i$ (сума добутків координат).</li>
<li><b>Геометрично:</b> $|a||b| \cos(\theta)$. Якщо вектори нормовані ($|a|=|b|=1$), добуток дорівнює косинусу кута (Cosine Similarity). 1 = співпадають, 0 = ортогональні, -1 = протилежні.</li>
<li><b>Статистично:</b> Це схоже на <i>коваріацію</i>. Він показує, наскільки дві змінні (розмірності слів) змінюються разом.</li>
</ul>
<h4>Softmax</h4>
$$ \text{softmax}(z_i) = \frac{e^{z_i}}{\sum_{j} e^{z_j}} $$
<p>Експонента "розтягує" різницю: трохи більші значення стають значно більшими ("winner takes all"), а знаменник гарантує, що сума всіх ймовірностей дорівнює 1.</p>
<h4>Чому в Attention ділимо саме на $\sqrt{d_k}$?</h4>
$$ \text{Score} = \frac{Q \cdot K^T}{\sqrt{d_k}} $$
<p>Припустімо, що компоненти векторів $Q$ і $K$ — це незалежні випадкові величини з дисперсією 1.</p>
<ul>
<li>Скалярний добуток — це сума $d_k$ попарних добутків.</li>
<li>Дисперсія суми незалежних величин дорівнює сумі їх дисперсій. Тобто дисперсія результату буде дорівнювати $d_k$.</li>
<li>Якщо $d_k = 100$, то значення скалярного добутку будуть "розлітатися" дуже далеко (від -30 до 30).</li>
<li>Softmax для великих чисел дає 1 або 0 (зникають градієнти).</li>
<li>Щоб повернути дисперсію до 1, треба поділити на <i>корінь</i> з дисперсії <b>(стандартне відхилення)</b>, тобто на $\sqrt{d_k}$.</li>
</ul>
<h4>Layer Normalization (LayerNorm)</h4>
$$ \text{LN}(x) = \frac{x - \mu}{\sigma} \cdot \gamma + \beta $$
<p>Тут є два типи параметрів:</p>
<ul>
<li><b>Статистичні (обчислюються "на льоту" для кожного слова):</b>
<ul>
<li>$\mu$ (мю) — середнє арифметичне елементів вектора. Центрує вектор навколо нуля.</li>
<li>$\sigma$ (сігма) — стандартне відхилення. Масштабує вектор так, щоб дисперсія стала дорівнювати 1.</li>
</ul>
</li>
<li><b>Навчені (Learnable parameters, частина "пам'яті" мережі):</b>
<ul>
<li>$\gamma$ (гамма) — параметр масштабу. Дозволяє мережі "розтягнути" вектор, якщо це потрібно.</li>
<li>$\beta$ (бета) — параметр зсуву. Дозволяє змістити центр розподілу.</li>
</ul>
</li>
</ul>
<p><i>Призначення $\gamma$ і $\beta$:</i> Нормалізація ($\mu, \sigma$) може знищити корисну інформацію. Параметри $\gamma$ і $\beta$ дають мережі можливість скасувати нормалізацію для певних ознак, якщо це допомагає мінімізувати помилку.</p>
<h4>Верхні індекси $W^Q, W^K$</h4>
<p>Це не степінь! У тензорній алгебрі це просто мітка. $W^Q$ означає "Матриця ваг для Query". Можна писати $W_{query}$.</p>
<hr style="border: 0; border-top: 1px solid #e2e8f0; margin: 15px 0;">
<h3>3. Чи ортогональний простір ознак?</h3>
<p>У нашому прикладі осі (Біологія, Музика, Бюрократія) перпендикулярні. У реальних LLM:</p>
<ul>
<li><b>Майже ортогональність:</b> У просторі з 12,000 вимірів можна розмістити тисячі майже перпендикулярних векторів.</li>
<li><b>Суперпозиція:</b> Одне слово може бути лінійною комбінацією багатьох тем. "Орган" не лежить на осі, він має проєкції на кілька осей.</li>
<li><b>Неідеальна ортогональність:</b> Реальні вектори слів утворюють щільні хмари, і теми часто перетинаються (наприклад, "медицина" і "біологія" корелюють).</li>
</ul>
<hr style="border: 0; border-top: 1px solid #e2e8f0; margin: 15px 0;">
<h3>4. Як навчаються матриці $W$?</h3>
<p>Спочатку $W^Q, W^K, W^V$ ініціалізуються випадковими числами (гаусівський шум). Увага працює хаотично.</p>
<p>Під час навчання (Backpropagation) оновлюються матриці $W^Q, W^K, W^V$:</p>
$$ W_{new} = W_{old} - \eta \cdot \nabla Loss $$
<ul>
<li>$\nabla Loss$ (градієнт) — вектор, що вказує напрямок найшвидшого зростання помилки. Ми рухаємось у протилежний бік (мінус).</li>
<li>$\eta$ (ета) — <b>Learning Rate</b> (швидкість навчання).
<br>Це "розмір кроку". Якщо $\eta$ завеликий — ми перестрибнемо мінімум. Якщо замалий — будемо вчитися вічність.
</li>
</ul>
<p>Мережа сама "розуміє", що для граматики треба одна матриця уваги, а для розв'язання омонімії — інша (Multi-Head Attention).</p>
<hr style="border: 0; border-top: 1px solid #e2e8f0; margin: 15px 0;">
<h3>5. Обчислювальна складність </h3>
<p>Головний недолік Self-Attention — це "квадратична складність" відносно довжини вхідного тексту ($N$).</p>
<ul>
<li><b>Матриця Уваги:</b> Щоб кожне слово "подивилося" на кожне інше, ми обчислюємо матрицю $Attn$ розміром $N \times N$.</li>
<li><b>Операції:</b> Множення $Q$ ($N \times d$) на $K^T$ ($d \times N$) вимагає $O(N^2 \cdot d)$ операцій.</li>
<li><b>Пам'ять:</b> Зберігання матриці $N \times N$ теж вимагає квадратичної пам'яті.</li>
</ul>
<p><b>На практиці:</b> Якщо ви збільшите довжину контексту в 2 рази (наприклад, з 4 тис. до 8 тис. токенів), час обробки та споживання пам'яті зростуть у <b>4 рази</b>. Саме тому старі моделі мали ліміт контексту, і саме тому розробка ефективних методів (наприклад, <i>FlashAttention</i>) є критично важливою для роботи з цілими книгами.</p>
</div>
</details>
<p>Симуляція процесу контекстуалізації слова <b>"орган"</b> через механізм уваги та залишкові зв'язки (Residual Connections).</p>
</div>
<div class="controls">
<button id="btn1" onclick="setScenario(1)" class="active">Контекст 1: Біологія</button>
<button id="btn2" onclick="setScenario(2)">Контекст 2: Музика</button>
<button id="btn3" onclick="setScenario(3)">Контекст 3: Бюрократія</button>
</div>
<p id="current-sentence" style="font-weight: bold; font-style: italic; color: var(--accent); text-align: center; font-size: 1.1rem; margin: 0;">...</p>
<div class="step-box">
<h2>1. Вхідні Ембеддінги ($X$)</h2>
<p>Кожне слово представлене вектором. У реальних LLM (GPT-4, BERT) розмірність вектора ($d_{model}$) становить від 768 до 12288. Для візуалізації ми використовуємо 3 виміри:</p>
<ul>
<li><b>$x_1$:</b> Біологічність</li>
<li><b>$x_2$:</b> Музичність</li>
<li><b>$x_3$:</b> Бюрократія/Управління</li>
</ul>
<div id="matrix-X" class="matrix-wrapper"></div>
</div>
<div class="step-box">
<h2>2. Проєкції: Query, Key, Value</h2>
<div class="math-expl">
Ми створюємо три версії кожного слова, множачи $X$ на навчені матриці ваг ($W^Q, W^K, W^V$):
$$ Q = X \cdot W^Q, \quad K = X \cdot W^K, \quad V = X \cdot W^V $$
<ul>
<li><b>Query (Q) - Запит:</b> "Що я шукаю?" (наприклад, іменник шукає прикметник).</li>
<li><b>Key (K) - Ключ:</b> "Як мене знайти/ідентифікувати?" (моя категорія).</li>
<li><b>Value (V) - Значення:</b> "Який зміст я передам, якщо на мене звернуть увагу?"</li>
</ul>
</div>
<p><i>Для спрощення у цій демонстрації матриці ваг $W$ є діагональними (майже одиничними), тому Q, K, V схожі на X.</i></p>
<h3>Матриця Query (Q)</h3>
<div id="matrix-Q" class="matrix-wrapper"></div>
<h3>Матриця Key (K)</h3>
<div id="matrix-K" class="matrix-wrapper"></div>
</div>
<div class="step-box">
<h2>3. Розрахунок Уваги (Attention)</h2>
<p>Ядро трансформера — це формула <b>Scaled Dot-Product Attention</b>:</p>
$$ \text{Attention}(Q, K) = \text{softmax}\left(\frac{Q \cdot K^T}{\sqrt{d_k}}\right) $$
<div class="math-expl">
<b>Пояснення складових:</b><br>
1. <b>$Q \cdot K^T$ (Скалярний добуток):</b> Це міра кореляції. Геометрично це $ |a||b|\cos(\theta) $. Чим більше вектори схожі (вказують в один бік), тим більше число. Ми перевіряємо схожість Запиту слова А з Ключем слова Б.<br>
2. <b>$\sqrt{d_k}$ (Масштабування):</b> При великих розмірностях скалярні добутки стають величезними, що "ламає" градієнти. Ділення на корінь з розмірності (тут $\sqrt{3} \approx 1.73$) стабілізує навчання.<br>
3. <b>Softmax:</b> Перетворює "сирі" числа (логіти) на ймовірності. Сума значень у рядку стає 1 (100% уваги розподіляється між словами).
</div>
<h3>Матриця Ваг Уваги (після Softmax):</h3>
<p>Рядок показує, як слово зліва розподіляє свою увагу. Зверніть увагу на рядок <b>"орган"</b>.</p>
<div id="matrix-Attn" class="matrix-wrapper"></div>
</div>
<div class="step-box">
<h2>4. Контекстуалізація (Residual)</h2>
<div class="math-expl">
У сучасних трансформерах ми додаємо знайдений контекст до початкового слова (Residual Connection), а потім нормалізуємо:
$$ Z_{\text{raw}} = X + (\text{Attention} \cdot V) $$
$$ Z = \text{LayerNorm}(Z_{\text{raw}}) $$
</div>
<p>
<b>Фізичний зміст:</b> Вектор $(\text{Attention} \cdot V)$ — це "вітер змін", що дме від контексту.
Слова, які впевнені у собі (контекст), додають до себе вектори, схожі на них самих (тому вони майже не рухаються).
Слово "орган" отримує вектор від сусідів, що зміщує його у потрібний кластер.
</p>
<h3>Фінальні вектори (Z):</h3>
<div id="matrix-Z" class="matrix-wrapper"></div>
</div>
</div>
<div id="canvas-container">
<div id="scene-legend">
<div style="margin-bottom:5px; font-weight:bold; border-bottom:1px solid #555; padding-bottom:5px;">Простір змістів $\mathbb{R}^3$</div>
<div style="display:flex; align-items:center; gap:8px; margin-bottom:4px;">
<span style="display:inline-block; width:12px; height:12px; background:#16a34a; border-radius:2px;"></span>
<span>Вісь X: Біологія</span>
</div>
<div style="display:flex; align-items:center; gap:8px; margin-bottom:4px;">
<span style="display:inline-block; width:12px; height:12px; background:#2563eb; border-radius:2px;"></span>
<span>Вісь Y: Музика</span>
</div>
<div style="display:flex; align-items:center; gap:8px;">
<span style="display:inline-block; width:12px; height:12px; background:#db2777; border-radius:2px;"></span>
<span>Вісь Z: Бюрократія</span>
</div>
</div>
<div id="labels-container"></div>
</div>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// --- ДАНІ ---
// Виправлені ваги для більшої логічності
// Format: [Bio(X), Music(Y), Admin(Z)]
const vocab = {
"непарний": [0.9, 0.05, 0.05], // Чиста біологія
"орган": [0.35, 0.35, 0.35], // Невизначеність (центр)
"ендокринної": [0.95, 0.0, 0.05], // Bio
"системи": [0.6, 0.1, 0.6], // Bio + Admin (системи бувають і там і там)
"великий": [0.2, 0.2, 0.2], // Neutral generic
"звучав": [0.05, 0.95, 0.0], // Music
"урочисто": [0.0, 0.8, 0.5], // Music + Admin (церемонії)
"державний": [0.0, 0.0, 0.95], // Admin
"управління": [0.05, 0.1, 0.9], // Admin
"освітою": [0.1, 0.05, 0.85] // Admin
};
const scenarios = {
1: ["непарний", "орган", "ендокринної", "системи"],
2: ["великий", "орган", "звучав", "урочисто"],
3: ["державний", "орган", "управління", "освітою"]
};
// Матриці ваг (Identity for simplicity in demo, but conceptually present)
const WQ = [[1,0,0], [0,1,0], [0,0,1]];
const WK = [[1,0,0], [0,1,0], [0,0,1]];
const WV = [[1,0,0], [0,1,0], [0,0,1]];
let currentScenarioId = 1;
let scene, camera, renderer, controls;
let spheres = [];
let labels = [];
// --- MATH UTILS ---
function matMul(A, B) {
let rowsA = A.length, colsA = A[0].length, colsB = B[0].length;
let C = Array(rowsA).fill(0).map(() => Array(colsB).fill(0));
for (let i = 0; i < rowsA; i++) {
for (let j = 0; j < colsB; j++) {
for (let k = 0; k < colsA; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
return C;
}
function addMat(A, B) {
return A.map((row, i) => row.map((val, j) => val + B[i][j]));
}
function transpose(A) { return A[0].map((_, c) => A.map(r => r[c])); }
function softmax(matrix) {
return matrix.map(row => {
let max = Math.max(...row);
let exps = row.map(x => Math.exp(x - max));
let sum = exps.reduce((a, b) => a + b, 0);
return exps.map(x => x / sum);
});
}
function normalizeRows(matrix) {
return matrix.map(row => {
let mag = Math.sqrt(row.reduce((sum, val) => sum + val*val, 0));
return (mag === 0) ? row : row.map(x => x / mag);
});
}
function formatMatrix(matrix, rowLabels, colLabels, highlightIdx = -1) {
let html = '<table><thead><tr><th></th>';
if (colLabels) colLabels.forEach(l => html += `<th>${l}</th>`);
else matrix[0].forEach((_, i) => html += `<th>${i}</th>`);
html += '</tr></thead><tbody>';
matrix.forEach((row, i) => {
const style = (i === highlightIdx) ? 'class="highlight-cell"' : '';
html += `<tr><th ${style}>${rowLabels ? rowLabels[i] : i}</th>`;
row.forEach(val => {
let bg = `rgba(79, 70, 229, ${Math.min(Math.abs(val), 1) * 0.3})`;
html += `<td style="background:${bg}">${val.toFixed(2)}</td>`;
});
html += '</tr>';
});
html += '</tbody></table>';
return html;
}
// --- LOGIC ---
function runSimulation() {
const words = scenarios[currentScenarioId];
const X = words.map(w => vocab[w]);
// 1. Projections
const Q = matMul(X, WQ);
const K = matMul(X, WK);
const V = matMul(X, WV);
// 2. Attention Scores
const KT = transpose(K);
let scores = matMul(Q, KT);
// Scaling and Softmax
const sharpFactor = 0.6; // Tuning parameter for demo visuals
scores = scores.map(row => row.map(val => val / sharpFactor));
const attn = softmax(scores);
// 3. Context Vector (Delta)
const Delta = matMul(attn, V);
// 4. Residual + Norm
const Z_raw = addMat(X, Delta);
const Z = normalizeRows(Z_raw);
// --- UI UPDATES ---
document.getElementById('current-sentence').innerText = `"${words.join(' ')}"`;
const cols = ["Bio(X)", "Mus(Y)", "Adm(Z)"];
// Render all matrices
document.getElementById('matrix-X').innerHTML = formatMatrix(X, words, cols);
document.getElementById('matrix-Q').innerHTML = formatMatrix(Q, words, cols);
document.getElementById('matrix-K').innerHTML = formatMatrix(K, words, cols);
document.getElementById('matrix-Attn').innerHTML = formatMatrix(attn, words, words, 1); // Highlight Organ row
document.getElementById('matrix-Z').innerHTML = formatMatrix(Z, words, cols, 1);
// Update 3D
update3DScene(words, X, Z);
// Refresh MathJax
if(window.MathJax) MathJax.typeset();
}
// --- 3D SCENE ---
function init3D() {
const container = document.getElementById('canvas-container');
scene = new THREE.Scene();
scene.background = new THREE.Color(0x0f172a);
camera = new THREE.PerspectiveCamera(45, container.clientWidth / container.clientHeight, 0.1, 100);
camera.position.set(3, 2.5, 4);
camera.lookAt(0.5, 0.5, 0.5);
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(container.clientWidth, container.clientHeight);
container.appendChild(renderer.domElement);
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.target.set(0.5, 0.5, 0.5);
// Lights
scene.add(new THREE.AmbientLight(0xffffff, 0.7));
const dl = new THREE.DirectionalLight(0xffffff, 1);
dl.position.set(5, 10, 7);
scene.add(dl);
// Custom Axes
const axesMaterial = new THREE.LineBasicMaterial({ vertexColors: true, linewidth: 3 });
const axesPoints = [
new THREE.Vector3(0,0,0), new THREE.Vector3(3,0,0), // X
new THREE.Vector3(0,0,0), new THREE.Vector3(0,3,0), // Y
new THREE.Vector3(0,0,0), new THREE.Vector3(0,0,3) // Z
];
const axesGeometry = new THREE.BufferGeometry().setFromPoints(axesPoints);
// Colors: Green(Bio), Blue(Music), Pink(Admin)
const colors = [
0.086, 0.639, 0.290, 0.086, 0.639, 0.290, // Bio
0.145, 0.388, 0.921, 0.145, 0.388, 0.921, // Music
0.858, 0.152, 0.466, 0.858, 0.152, 0.466 // Admin
];
axesGeometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
const axesLines = new THREE.LineSegments(axesGeometry, axesMaterial);
scene.add(axesLines);
window.addEventListener('resize', onWindowResize);
animate();
}
function update3DScene(words, startVecs, endVecs) {
spheres.forEach(obj => scene.remove(obj));
spheres = [];
const labelCont = document.getElementById('labels-container');
labelCont.innerHTML = '';
labels = [];
words.forEach((w, i) => {
const geo = new THREE.SphereGeometry(0.06, 32, 32);
// Calculate color based on FINAL position
const v = endVecs[i];
const colBio = new THREE.Color(0x16a34a);
const colMusic = new THREE.Color(0x2563eb);
const colAdmin = new THREE.Color(0xdb2777);
let color = new THREE.Color(0x000000);
color.add(colBio.multiplyScalar(v[0]));
color.add(colMusic.multiplyScalar(v[1]));
color.add(colAdmin.multiplyScalar(v[2]));
const isOrgan = w.includes("орган");
const mat = new THREE.MeshStandardMaterial({
color: isOrgan ? 0xffffff : color,
roughness: 0.4, metalness: 0.1
});
const mesh = new THREE.Mesh(geo, mat);
// Scale positions for visualization space
const s = startVecs[i];
const e = endVecs[i];
mesh.position.set(s[0]*1.8, s[1]*1.8, s[2]*1.8);
mesh.userData = {
start: mesh.position.clone(),
end: new THREE.Vector3(e[0]*1.8, e[1]*1.8, e[2]*1.8),
finalColor: color,
isDynamic: isOrgan
};
scene.add(mesh);
spheres.push(mesh);
// Label
const el = document.createElement('div');
el.className = 'label';
el.textContent = w;
if (isOrgan) el.style.border = "1px solid rgba(255,255,255,0.5)";
labelCont.appendChild(el);
labels.push(el);
});
animationTime = 0;
}
let animationTime = 0;
function animate() {
requestAnimationFrame(animate);
controls.update();
// Animation Loop
if (animationTime < 1) {
animationTime += 0.01; // Slower animation
spheres.forEach(s => {
s.position.lerpVectors(s.userData.start, s.userData.end, animationTime);
if(s.userData.isDynamic) {
s.material.color.lerp(s.userData.finalColor, 0.02);
}
});
}
updateLabels();
renderer.render(scene, camera);
}
function updateLabels() {
const container = document.getElementById('canvas-container');
const width = container.clientWidth;
const height = container.clientHeight;
let points = [];
spheres.forEach((mesh, i) => {
const v = mesh.position.clone();
v.project(camera);
if (v.z > 1) {
labels[i].style.opacity = 0;
return;
} else {
labels[i].style.opacity = 1;
}
const x = (v.x * .5 + .5) * width;
const y = -(v.y * .5 - .5) * height;
points.push({ id: i, x: x, y: y, el: labels[i] });
});
// Repulsion Logic
for(let iter=0; iter<8; iter++) {
for(let i=0; i<points.length; i++) {
for(let j=i+1; j<points.length; j++) {
let dx = points[i].x - points[j].x;
let dy = points[i].y - points[j].y;
let distSq = dx*dx + dy*dy;
let minDist = 35;
if (distSq < minDist*minDist) {
let dist = Math.sqrt(distSq);
let overlap = minDist - dist;
let angle = Math.atan2(dy, dx);
let moveX = Math.cos(angle) * overlap * 0.5;
let moveY = Math.sin(angle) * overlap * 0.5;
points[i].x += moveX; points[i].y += moveY;
points[j].x -= moveX; points[j].y -= moveY;
}
}
}
}
points.forEach(p => {
p.el.style.transform = `translate(${p.x}px, ${p.y}px)`;
});
}
function onWindowResize() {
const c = document.getElementById('canvas-container');
camera.aspect = c.clientWidth / c.clientHeight;
camera.updateProjectionMatrix();
renderer.setSize(c.clientWidth, c.clientHeight);
}
window.setScenario = function(id) {
currentScenarioId = id;
document.querySelectorAll('.controls button').forEach((b, i) => {
b.className = (i+1 === id) ? 'active' : '';
});
runSimulation();
}
init3D();
runSimulation();
</script>
</body>
</html>