mindz-js 0.0.0-stage → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +24 -0
- package/README.md +169 -2
- package/js/cli.js +50 -0
- package/js/index.js +155 -0
- package/package.json +16 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bayram Kotan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
The bundled fonts in src/neurz/assets/fonts (Inter, JetBrains Mono) are
|
|
24
|
+
distributed under the SIL Open Font License 1.1; see the OFL files there.
|
package/README.md
CHANGED
|
@@ -1,3 +1,170 @@
|
|
|
1
|
-
#
|
|
1
|
+
# mindz
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Learn AI by watching it think: machine learning, neural networks, tokenization, attention and language models, one operation at a time.**
|
|
4
|
+
|
|
5
|
+
mindz is an educational desktop app. Every lesson runs a real algorithm with real arithmetic,
|
|
6
|
+
records every step and lets you play, pause, step and scrub through it like a video. Every
|
|
7
|
+
number on screen is a number the algorithm actually computed; every point, line, neuron,
|
|
8
|
+
token and matrix can be clicked for an explanation in plain language, in detail or as a formula.
|
|
9
|
+
|
|
10
|
+
It belongs with [qubitz](https://github.com/bayramkotan/qubitz) (quantum computing) and
|
|
11
|
+
[neurz](https://github.com/bayramkotan/neurz) (RNN, LSTM, GRU and CNN up close).
|
|
12
|
+
|
|
13
|
+
## What you can watch
|
|
14
|
+
|
|
15
|
+
Seventeen lessons in six chapters. Each runs a real algorithm and records every step.
|
|
16
|
+
|
|
17
|
+
| Chapter | Lesson | What is animated |
|
|
18
|
+
|---|---|---|
|
|
19
|
+
| **Machine learning** | **Linear regression** | the line, the errors and their squares, the loss, the gradient on the loss surface, every gradient-descent step; a learning rate that is too large diverges |
|
|
20
|
+
| | **Logistic regression** | one neuron: its line and the weight vector w, every point placed on the sigmoid by its z, cross-entropy, the line settling into the gap |
|
|
21
|
+
| | **Overfitting** | polynomials of degree 1 to 12 against training and validation data, the U-shaped validation error, ridge regularisation λ |
|
|
22
|
+
| | **k nearest neighbours** | distances from a new point, the k nearest inside a circle, the vote, the whole decision map, leave-one-out accuracy |
|
|
23
|
+
| | **Decision tree** | the Gini scan over every threshold, split after split, the regions and the tree drawn as it grows |
|
|
24
|
+
| | **K-means** | random centres, assignment and update rounds, the regions of the centres, J falling until nothing changes |
|
|
25
|
+
| **Deep learning** | **Neural network** | one sample forward and backward, then hundreds of epochs bending the boundary; the straight line of every hidden neuron |
|
|
26
|
+
| | **Convolution** | a 3×3 filter sliding over a picture, the feature map filling cell by cell, ReLU and 2×2 max pooling |
|
|
27
|
+
| **Language (NLP)** | **Tokenization (BPE)** | characters, pair counts, merge after merge, the vocabulary and the token ids |
|
|
28
|
+
| | **Word vectors** | context windows, co-occurrence counts, PPMI, SVD down to a word map, nearest words by cosine |
|
|
29
|
+
| **Transformer · LLM** | **Self-attention** | readable embeddings with positions, Q, K, V, scores, softmax and the weighted sum row by row, causal mask |
|
|
30
|
+
| | **Transformer block** | three heads side by side, concat and W_O, residual, layer norm, feed-forward, residual, layer norm |
|
|
31
|
+
| | **Attention learns** | a head that starts random and learns W_Q and W_K by gradient descent; the query–key table grows its diagonal |
|
|
32
|
+
| | **Next word** | logits, temperature, softmax, top-k, top-p, the dice on the cumulative bar, or greedy argmax |
|
|
33
|
+
| | **Beam search** | the search tree expanding and pruning, beam against greedy with their log probabilities |
|
|
34
|
+
| **Reinforcement learning** | **Q-learning** | an agent on a grid: ε-greedy moves, the update rule with its numbers, values spreading back from the goal, the policy |
|
|
35
|
+
| **Generative models** | **Diffusion** | noise added step by step, then removed from fresh noise with DDIM and the ideal denoiser, for 2-D points or tiny pictures |
|
|
36
|
+
|
|
37
|
+

|
|
38
|
+
|
|
39
|
+
- **Playback:** play / pause, step forward and back, jump to start or end, loop, speed 0.25×–8×, a timeline grouped by step that you can click or drag.
|
|
40
|
+
- **Click to learn:** every element opens a short bubble; the right panel explains it at three levels (Simple · Detailed · Math) with links to related concepts; hovering shows the exact numbers.
|
|
41
|
+
- **Lessons:** a guided lesson per topic, each step jumping to the moment it talks about, with a question at the end.
|
|
42
|
+
- **Change everything:** learning rates, steps, noise, k, datasets, depth, hidden neurons, filters and pictures, your own text and sentences, temperature, top-k, top-p, beam width, exploration ε, seeds. The run is recomputed at once.
|
|
43
|
+
- **Ten languages:** Türkçe, English, Azərbaycanca, Deutsch, Français, Español, Русский, العربية, فارسی, 中文 (right-to-left for Arabic and Persian). Interface and step narration are translated everywhere; the long concept texts are in Turkish and English, other languages show translated titles and the English text.
|
|
44
|
+
- **9 themes**, your own interface and number fonts and text sizes.
|
|
45
|
+
|
|
46
|
+

|
|
47
|
+
|
|
48
|
+

|
|
49
|
+
|
|
50
|
+

|
|
51
|
+
|
|
52
|
+

|
|
53
|
+
|
|
54
|
+

|
|
55
|
+
|
|
56
|
+

|
|
57
|
+
|
|
58
|
+
## Download (portable, nothing to install)
|
|
59
|
+
|
|
60
|
+
Every release on the [Releases page](https://github.com/bayramkotan/mindz/releases) carries ready-to-run builds:
|
|
61
|
+
|
|
62
|
+
| System | File | How to start |
|
|
63
|
+
|---|---|---|
|
|
64
|
+
| Windows 10/11 | `mindz-<version>-windows-x64.exe` | double-click (SmartScreen: *More info → Run anyway*) |
|
|
65
|
+
| Linux x86-64 | `mindz-<version>-linux-x86_64.AppImage` | `chmod +x mindz-*.AppImage && ./mindz-*.AppImage` |
|
|
66
|
+
| macOS (Apple silicon) | `mindz-<version>-macos-arm64.zip` | unzip, then right-click `mindz.app` → *Open* (the app is not notarised) |
|
|
67
|
+
|
|
68
|
+
## Install
|
|
69
|
+
|
|
70
|
+
The desktop app (Python, PyPI):
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
pip install mindz
|
|
74
|
+
mindz # or: mz
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Python 3.10+ with PySide6 and NumPy; runs on Windows, Linux and macOS.
|
|
78
|
+
|
|
79
|
+
Gradient descent and the BPE tokenizer also run in the terminal or in your own code, without the window:
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
npm install -g mindz-js # JavaScript (npm); the command is still mindz
|
|
83
|
+
mindz run linreg --lr 0.18
|
|
84
|
+
|
|
85
|
+
cargo install mindz # Rust (crates.io)
|
|
86
|
+
mindz run tokens --text "low lower lowest newer newest" --merges 5
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
```js
|
|
90
|
+
import { linreg, bpe } from "mindz-js";
|
|
91
|
+
const r = linreg({ lr: 0.08, steps: 40 }); // r.steps: [{ k, loss, w, b, dw, db }]
|
|
92
|
+
const t = bpe("low lower lowest", 4); // t.merges, t.vocab, t.tokens, t.ids
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
```rust
|
|
96
|
+
let r = mindz::linreg(0.08, 40, 0.8, 3); // r.steps, r.diverged
|
|
97
|
+
let t = mindz::bpe("low lower lowest", 4, "en"); // t.merges, t.vocab, t.tokens, t.ids
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
The packages are `mindz` on PyPI and crates.io and `mindz-js` on npm (npm refuses `mindz` as too similar to other names); every one installs a `mindz` command. The data come from the same small random generator,
|
|
101
|
+
so the JavaScript and Rust results match the Python app number for number (the test suites
|
|
102
|
+
check this against `tests/golden.json`). `mindz gui` in the npm and Rust versions opens the
|
|
103
|
+
Python desktop app if it is installed.
|
|
104
|
+
|
|
105
|
+
## Command line
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
mz topics # the seventeen lessons
|
|
109
|
+
mz run linreg --lr 0.3 # every step with its numbers (this one diverges)
|
|
110
|
+
mz run kmeans --k 4 --seed 9
|
|
111
|
+
mz run mlp --dataset spiral --hidden 8 --lr 3
|
|
112
|
+
mz run tokens --text "evler evlerde kitaplar kitaplarda" --lang tr
|
|
113
|
+
mz run attention --sentence "the small dog brought the big ball" --causal true
|
|
114
|
+
mz run sampling --temperature 1.5 --top-k 5 --top-p 0.9
|
|
115
|
+
mz run sampling --method greedy
|
|
116
|
+
mz run beam --start teacher --width 3
|
|
117
|
+
mz run tree --depth 4 --dataset xor
|
|
118
|
+
mz run qlearn --epsilon 0.2
|
|
119
|
+
mz run diffusion --shape images
|
|
120
|
+
mz concepts # every concept key
|
|
121
|
+
mz explain temperature --level math # simple | detail | math
|
|
122
|
+
mz update # upgrade with this Python's pip
|
|
123
|
+
mz -v
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
`--lang tr` or `--lang en` may stand anywhere on the line; without it the system language is used.
|
|
127
|
+
|
|
128
|
+
## Keyboard
|
|
129
|
+
|
|
130
|
+
| Key | Action |
|
|
131
|
+
|---|---|
|
|
132
|
+
| Space | play / pause |
|
|
133
|
+
| ← / → | step back / forward |
|
|
134
|
+
| Home / End | start / end |
|
|
135
|
+
| + / − | faster / slower |
|
|
136
|
+
| L | loop |
|
|
137
|
+
| 1 … 9 | the first nine topics |
|
|
138
|
+
| F1 / F2 / F3 | Simple / Detailed / Math explanations |
|
|
139
|
+
| Ctrl+B / Ctrl+E | left / right panel |
|
|
140
|
+
| Ctrl+L | lesson |
|
|
141
|
+
| Ctrl+, | settings |
|
|
142
|
+
|
|
143
|
+
## How it works
|
|
144
|
+
|
|
145
|
+
`src/mindz/core/topics.py` runs each algorithm once and records every operation as a frame
|
|
146
|
+
(phase, values, the formula with its own numbers, the concept it explains). The window only
|
|
147
|
+
moves through these frames, so pausing, stepping back and scrubbing never recompute anything.
|
|
148
|
+
The attention lesson uses a hand-made embedding whose six dimensions have a meaning (noun,
|
|
149
|
+
living, verb, pronoun, adjective, function word) plus two for position, and hand-written
|
|
150
|
+
W_Q, W_K, W_V, so the attention pattern can be explained; real Transformers learn all of these.
|
|
151
|
+
The next-word and beam-search lessons use a bigram model counted from a small built-in text.
|
|
152
|
+
The diffusion lesson uses the exact ("ideal") denoiser of its training set instead of a trained
|
|
153
|
+
network, so it shows the mechanics of the reverse process honestly, including that a perfect
|
|
154
|
+
denoiser can only give the training examples back.
|
|
155
|
+
|
|
156
|
+
## Development
|
|
157
|
+
|
|
158
|
+
```bash
|
|
159
|
+
git clone https://github.com/bayramkotan/mindz && cd mindz
|
|
160
|
+
pip install -e .[dev]
|
|
161
|
+
pytest -q # Python
|
|
162
|
+
npm test # JavaScript
|
|
163
|
+
cargo test # Rust
|
|
164
|
+
python tools/make_golden.py # after changing the shared runs
|
|
165
|
+
python packaging/build.py # portable build for this system
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
## License
|
|
169
|
+
|
|
170
|
+
MIT © 2026 Bayram Kotan. Bundled fonts: Inter and JetBrains Mono (SIL Open Font License).
|
package/js/cli.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// mindz command line (npm): print every step of a run; `mindz gui` opens the desktop app.
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import { DEFAULT_TEXT, PORTED, TOPICS, bpe, linreg, version } from "./index.js";
|
|
5
|
+
|
|
6
|
+
const args = process.argv.slice(2);
|
|
7
|
+
const VERSION_FLAGS = ["-v", "-V", "--version", "--Version", "-version", "--v", "--V"];
|
|
8
|
+
const opt = (name, def) => {
|
|
9
|
+
const i = args.indexOf("--" + name);
|
|
10
|
+
return i >= 0 && i + 1 < args.length ? args[i + 1] : def;
|
|
11
|
+
};
|
|
12
|
+
const help = () =>
|
|
13
|
+
console.log(`mindz ${version}
|
|
14
|
+
|
|
15
|
+
mindz topics list the topics
|
|
16
|
+
mindz run linreg [--lr 0.08] [--steps 40] [--noise 0.8] [--seed 3]
|
|
17
|
+
mindz run tokens [--text "..."] [--merges 10] [--lang tr|en]
|
|
18
|
+
mindz gui open the desktop app (needs: pip install mindz)
|
|
19
|
+
mindz -v | -V | --version`);
|
|
20
|
+
|
|
21
|
+
if (args.some((a) => VERSION_FLAGS.includes(a))) {
|
|
22
|
+
console.log(`mindz ${version}`);
|
|
23
|
+
} else if (args[0] === "topics") {
|
|
24
|
+
for (const t of TOPICS) console.log(`${t.padEnd(10)} ${PORTED.includes(t) ? "terminal + desktop" : "desktop app"}`);
|
|
25
|
+
} else if (args[0] === "run" && args[1] === "linreg") {
|
|
26
|
+
const r = linreg({ lr: Number(opt("lr", 0.08)), steps: Number(opt("steps", 40)), noise: Number(opt("noise", 0.8)),
|
|
27
|
+
seed: Number(opt("seed", 3)) });
|
|
28
|
+
console.log(` k loss w b ∂L/∂w ∂L/∂b`);
|
|
29
|
+
for (const s of r.steps)
|
|
30
|
+
console.log(`${String(s.k).padStart(3)} ${s.loss.toFixed(4).padStart(10)} ${s.w.toFixed(4).padStart(8)} ${s.b.toFixed(4).padStart(8)} ${s.dw.toFixed(4).padStart(8)} ${s.db.toFixed(4).padStart(8)}`);
|
|
31
|
+
if (r.diverged) console.log("diverged: the learning rate is too large");
|
|
32
|
+
} else if (args[0] === "run" && args[1] === "tokens") {
|
|
33
|
+
const lang = opt("lang", "en");
|
|
34
|
+
const r = bpe(opt("text", DEFAULT_TEXT[lang] || DEFAULT_TEXT.en), Number(opt("merges", 10)), lang);
|
|
35
|
+
r.merges.forEach(([a, b, c], i) => console.log(`${String(i + 1).padStart(3)} ${a} + ${b} → ${a + b} (${c}×)`));
|
|
36
|
+
console.log(`vocabulary (${r.vocab.length}): ${r.vocab.join(" ")}`);
|
|
37
|
+
console.log(`tokens (${r.tokens.length}): ${r.tokens.join(" | ")}`);
|
|
38
|
+
console.log(`ids: [${r.ids.join(", ")}]`);
|
|
39
|
+
} else if (args[0] === "run" && TOPICS.includes(args[1])) {
|
|
40
|
+
console.log(`"${args[1]}" runs in the desktop app: pip install mindz && mindz`);
|
|
41
|
+
} else if (args[0] === "gui") {
|
|
42
|
+
for (const py of ["python3", "python", "py"]) {
|
|
43
|
+
const r = spawnSync(py, ["-m", "mindz", "gui"], { stdio: "inherit" });
|
|
44
|
+
if (!r.error) process.exit(r.status ?? 0);
|
|
45
|
+
}
|
|
46
|
+
console.error("mindz desktop app not found: pip install mindz");
|
|
47
|
+
process.exit(1);
|
|
48
|
+
} else {
|
|
49
|
+
help();
|
|
50
|
+
}
|
package/js/index.js
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// mindz for JavaScript: the same gradient-descent and BPE runs as the Python desktop app,
|
|
2
|
+
// recorded step by step. The data come from the same tiny random generator (mulberry32),
|
|
3
|
+
// so every number matches the Python package.
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { dirname, join } from "node:path";
|
|
7
|
+
|
|
8
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
const pkg = JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8"));
|
|
10
|
+
export const version = pkg.version;
|
|
11
|
+
|
|
12
|
+
export const TOPICS = ["linreg", "kmeans", "mlp", "tokens", "attention", "sampling"];
|
|
13
|
+
export const PORTED = ["linreg", "tokens"];
|
|
14
|
+
|
|
15
|
+
// ------------------------------------------------------------------ random numbers
|
|
16
|
+
export class Rng {
|
|
17
|
+
constructor(seed) {
|
|
18
|
+
this.state = seed >>> 0;
|
|
19
|
+
}
|
|
20
|
+
nextU32() {
|
|
21
|
+
this.state = (this.state + 0x6d2b79f5) >>> 0;
|
|
22
|
+
let t = this.state;
|
|
23
|
+
t = Math.imul(t ^ (t >>> 15), t | 1) >>> 0;
|
|
24
|
+
t = (t ^ ((t + (Math.imul(t ^ (t >>> 7), t | 61) >>> 0)) >>> 0)) >>> 0;
|
|
25
|
+
return (t ^ (t >>> 14)) >>> 0;
|
|
26
|
+
}
|
|
27
|
+
uniform(lo = 0, hi = 1) {
|
|
28
|
+
return lo + (hi - lo) * (this.nextU32() / 4294967296.0);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// ------------------------------------------------------------------ linear regression
|
|
33
|
+
export const TRUE_W = 0.8;
|
|
34
|
+
export const TRUE_B = 1.0;
|
|
35
|
+
export const START_W = -0.6;
|
|
36
|
+
export const START_B = 3.6;
|
|
37
|
+
|
|
38
|
+
export function linregData(seed = 3, noise = 0.8, n = 18) {
|
|
39
|
+
const r = new Rng(seed);
|
|
40
|
+
const pts = [];
|
|
41
|
+
for (let i = 0; i < n; i++) {
|
|
42
|
+
const x = r.uniform(-2.0, 4.0);
|
|
43
|
+
const y = TRUE_W * x + TRUE_B + r.uniform(-noise, noise);
|
|
44
|
+
pts.push([x, y]);
|
|
45
|
+
}
|
|
46
|
+
pts.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
|
|
47
|
+
return { x: pts.map((p) => p[0]), y: pts.map((p) => p[1]) };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function gdStep(x, y, w, b, lr) {
|
|
51
|
+
const n = x.length;
|
|
52
|
+
let loss = 0, dw = 0, db = 0;
|
|
53
|
+
for (let i = 0; i < n; i++) {
|
|
54
|
+
const e = w * x[i] + b - y[i];
|
|
55
|
+
loss += e * e;
|
|
56
|
+
dw += e * x[i];
|
|
57
|
+
db += e;
|
|
58
|
+
}
|
|
59
|
+
loss /= n;
|
|
60
|
+
dw = (2 * dw) / n;
|
|
61
|
+
db = (2 * db) / n;
|
|
62
|
+
return { loss, dw, db, w: w - lr * dw, b: b - lr * db };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function linreg({ lr = 0.08, steps = 40, noise = 0.8, seed = 3 } = {}) {
|
|
66
|
+
const { x, y } = linregData(seed, noise);
|
|
67
|
+
let w = START_W, b = START_B;
|
|
68
|
+
const out = [];
|
|
69
|
+
let diverged = false;
|
|
70
|
+
for (let k = 1; k <= steps; k++) {
|
|
71
|
+
const s = gdStep(x, y, w, b, lr);
|
|
72
|
+
w = s.w;
|
|
73
|
+
b = s.b;
|
|
74
|
+
out.push({ k, loss: s.loss, dw: s.dw, db: s.db, w, b });
|
|
75
|
+
if (!(Math.abs(w) < 1e3 && Math.abs(b) < 1e3 && Number.isFinite(s.loss) && s.loss < 1e6)) {
|
|
76
|
+
diverged = true;
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return { x, y, steps: out, diverged };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// ------------------------------------------------------------------ BPE tokenizer
|
|
84
|
+
export const WORD_MARK = "▁";
|
|
85
|
+
export const DEFAULT_TEXT = {
|
|
86
|
+
tr: "evler evlerde evde ev kitaplar kitaplarda kitap okullar okullarda okul",
|
|
87
|
+
en: "low lower lowest new newer newest wide wider widest slow slower slowest",
|
|
88
|
+
};
|
|
89
|
+
const PUNCT = /[.,;:!?"'()[\]{}…“”‘’]/g;
|
|
90
|
+
|
|
91
|
+
export function lower(text, lang = "en") {
|
|
92
|
+
if (lang === "tr") text = text.replaceAll("İ", "i").replaceAll("I", "ı");
|
|
93
|
+
return text.toLowerCase().replaceAll("i̇", "i");
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function splitWords(text, lang = "en") {
|
|
97
|
+
return lower(text, lang).replace(PUNCT, " ").split(/\s+/).filter(Boolean);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function pairCounts(split, order, count) {
|
|
101
|
+
const out = new Map();
|
|
102
|
+
for (const w of order) {
|
|
103
|
+
const t = split.get(w);
|
|
104
|
+
for (let i = 0; i + 1 < t.length; i++) {
|
|
105
|
+
const key = t[i] + "\u0000" + t[i + 1];
|
|
106
|
+
out.set(key, (out.get(key) || 0) + count.get(w));
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return [...out.entries()].map(([k, c]) => [k.split("\u0000"), c]);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function bpe(text, merges = 10, lang = "en") {
|
|
113
|
+
const words = splitWords(text, lang);
|
|
114
|
+
const order = [];
|
|
115
|
+
const count = new Map();
|
|
116
|
+
for (const w of words) {
|
|
117
|
+
if (!count.has(w)) {
|
|
118
|
+
order.push(w);
|
|
119
|
+
count.set(w, 0);
|
|
120
|
+
}
|
|
121
|
+
count.set(w, count.get(w) + 1);
|
|
122
|
+
}
|
|
123
|
+
const split = new Map(order.map((w) => [w, [WORD_MARK, ...Array.from(w)]]));
|
|
124
|
+
const vocab = [];
|
|
125
|
+
for (const w of order) for (const t of split.get(w)) if (!vocab.includes(t)) vocab.push(t);
|
|
126
|
+
const history = [];
|
|
127
|
+
for (let m = 0; m < merges; m++) {
|
|
128
|
+
const pc = pairCounts(split, order, count);
|
|
129
|
+
if (!pc.length) break;
|
|
130
|
+
let [best, bc] = pc[0];
|
|
131
|
+
for (const [pair, c] of pc) if (c > bc) [best, bc] = [pair, c];
|
|
132
|
+
if (bc < 2) break;
|
|
133
|
+
const neu = best[0] + best[1];
|
|
134
|
+
for (const w of order) {
|
|
135
|
+
const toks = split.get(w);
|
|
136
|
+
const out = [];
|
|
137
|
+
for (let i = 0; i < toks.length; ) {
|
|
138
|
+
if (i + 1 < toks.length && toks[i] === best[0] && toks[i + 1] === best[1]) {
|
|
139
|
+
out.push(neu);
|
|
140
|
+
i += 2;
|
|
141
|
+
} else {
|
|
142
|
+
out.push(toks[i]);
|
|
143
|
+
i += 1;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
split.set(w, out);
|
|
147
|
+
}
|
|
148
|
+
if (!vocab.includes(neu)) vocab.push(neu);
|
|
149
|
+
history.push([best[0], best[1], bc]);
|
|
150
|
+
}
|
|
151
|
+
const ids = new Map(vocab.map((t, i) => [t, i]));
|
|
152
|
+
const seq = words.flatMap((w) => split.get(w));
|
|
153
|
+
return { words: order, merges: history, split: order.map((w) => split.get(w)), vocab, tokens: seq,
|
|
154
|
+
ids: seq.map((t) => ids.get(t)) };
|
|
155
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mindz-js",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.2",
|
|
4
|
+
"description": "Learn AI by watching it think: gradient descent and BPE tokenization recorded step by step with real numbers, the same runs as the mindz desktop app.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "js/index.js",
|
|
7
|
+
"exports": "./js/index.js",
|
|
8
|
+
"bin": { "mindz": "js/cli.js" },
|
|
9
|
+
"files": ["js/index.js", "js/cli.js", "README.md", "LICENSE"],
|
|
10
|
+
"scripts": { "test": "node --test js/test.js" },
|
|
11
|
+
"engines": { "node": ">=18" },
|
|
12
|
+
"keywords": ["machine learning", "gradient descent", "tokenization", "bpe", "education", "artificial intelligence"],
|
|
13
|
+
"author": "Bayram Kotan",
|
|
14
|
+
"license": "MIT",
|
|
15
|
+
"homepage": "https://github.com/bayramkotan/mindz",
|
|
16
|
+
"repository": { "type": "git", "url": "git+https://github.com/bayramkotan/mindz.git" },
|
|
17
|
+
"bugs": { "url": "https://github.com/bayramkotan/mindz/issues" }
|
|
18
|
+
}
|