drix10 commited on
Commit
79aec3d
·
verified ·
1 Parent(s): 040ffc6

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +278 -0
README.md CHANGED
@@ -1,3 +1,281 @@
1
  ---
2
  license: mit
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: mit
3
+ pretty_name: Key Stroke LLM
4
+ size_categories:
5
+ - 10K<n<100K
6
  ---
7
+
8
+ # Keystroke-LLM
9
+
10
+ <p align="center">
11
+ <strong>A tiny language model that turns your keyboard into its own prediction display.</strong><br />
12
+ Type a character. The model guesses what comes next. The Kreo Hive 75 lights the answer.
13
+ </p>
14
+
15
+ <p align="center">
16
+ <img alt="Python 3.9+" src="https://img.shields.io/badge/Python-3.9%2B-3776AB?style=for-the-badge&logo=python&logoColor=white" />
17
+ <img alt="NumPy" src="https://img.shields.io/badge/NumPy-Only%20ML%20Runtime-013243?style=for-the-badge&logo=numpy&logoColor=white" />
18
+ <img alt="USB HID" src="https://img.shields.io/badge/USB%20HID-EVision%20CMD%200x12-FF6B6B?style=for-the-badge" />
19
+ <img alt="Hardware" src="https://img.shields.io/badge/Hardware-Kreo%20Hive%2075-6C5CE7?style=for-the-badge" />
20
+ <img alt="License" src="https://img.shields.io/badge/License-MIT-green?style=for-the-badge" />
21
+ </p>
22
+
23
+ ## See It First
24
+
25
+ <div align="center">
26
+ <video controls="controls" width="100%" style="max-width: 720px; border-radius: 8px;">
27
+ <source src="https://github.com/user-attachments/assets/4eb3b5ba-52da-42e5-badb-cacd0d38c6ec" type="video/mp4" />
28
+ Your browser cannot play the video. <a href="https://github.com/user-attachments/assets/4eb3b5ba-52da-42e5-badb-cacd0d38c6ec">Open the demo video</a>.
29
+ </video>
30
+ <p><a href="https://github.com/user-attachments/assets/4eb3b5ba-52da-42e5-badb-cacd0d38c6ec">Open the demo video if the player does not load</a></p>
31
+ </div>
32
+
33
+ <p align="center">
34
+ <a href="https://www.linkedin.com/posts/drix10_llm-ondeviceai-mechanicalkeyboards-activity-7503825549148975105-CW31">
35
+ <img alt="LinkedIn engineering discussion" src="https://img.shields.io/badge/LinkedIn-Engineering%20Discussion-0A66C2?style=for-the-badge&logo=linkedin&logoColor=white" />
36
+ </a>
37
+ </p>
38
+
39
+ ## The Idea
40
+
41
+ Most language models show their predictions on a screen. Keystroke-LLM puts the prediction under your fingers.
42
+
43
+ It watches a rolling window of typed characters, predicts the next character with a small Transformer written from scratch in NumPy, translates likely characters into physical key names, and sends RGB frames directly to the keyboard. Unpredicted keys stay white. The strongest candidate glows red; the next candidates fade through lighter reds.
44
+
45
+ This is not a text-completion service and it does not replace what you type. It is a visible, physical experiment in how a character-level language model turns context into action.
46
+
47
+ ## Follow One Keystroke
48
+
49
+ Suppose the current context is `th`:
50
+
51
+ ```text
52
+ 1. The input reader receives the next key event.
53
+ 2. CharTokenizer turns t and h into token IDs.
54
+ 3. TinyTransformer adds token and position embeddings.
55
+ 4. Causal attention looks at the context without seeing the future.
56
+ 5. Softmax produces one probability for every vocabulary token.
57
+ 6. The runtime keeps valid, mappable candidates and groups them by physical key.
58
+ 7. KeyboardController fills the 128-slot RGB buffer white and paints the top keys red.
59
+ 8. The HID transport sends the frame to the Kreo Hive 75.
60
+ ```
61
+
62
+ The important boundary is between the model and the hardware: the model predicts characters, while `key_mapper.py` decides which physical switch represents each character. `A` and `a` therefore share one key, as do `!` and `1`.
63
+
64
+ ## Architecture
65
+
66
+ ```mermaid
67
+ flowchart LR
68
+ Input["Keyboard event"] --> Reader["LowLatencyInputReader\nnormalize + debounce"]
69
+ Reader --> Queue["Bounded queue\nmax 128"]
70
+ Queue --> Context["Rolling context\nup to 48 chars"]
71
+ Context --> Tokenizer["CharTokenizer"]
72
+ Tokenizer --> Model["TinyTransformer\nNumPy causal attention"]
73
+ Model --> Candidates["Valid character\nprobabilities"]
74
+ Candidates --> Mapper["CHAR_TO_KEY\ncharacter -> switch"]
75
+ Mapper --> Buffer["128-slot RGB buffer\nwhite background + red ranks"]
76
+ Buffer --> HID["EVision HID\n64-byte reports + checksum"]
77
+ HID --> LEDs["Kreo Hive 75 LEDs"]
78
+ ```
79
+
80
+ There is one attention block, not a large multi-layer model. That is deliberate: every weight, tensor, mask, and update can be read in `model.py`.
81
+
82
+ ## What Is Inside the Model?
83
+
84
+ `TinyTransformer` is a character-level causal Transformer:
85
+
86
+ - `W_emb` stores a learned vector for each token.
87
+ - `W_pos` stores a learned vector for each position in the context.
88
+ - `W_q`, `W_k`, and `W_v` build the attention queries, keys, and values.
89
+ - The causal mask prevents position `i` from attending to positions after `i`.
90
+ - `W_o` projects the attention result back into the hidden space.
91
+ - `W1` and `W2` form a ReLU feed-forward block.
92
+ - Residual connections preserve the input signal through both blocks.
93
+ - `W_out` and `b_out` produce vocabulary logits.
94
+ - A numerically stable softmax turns the final row into probabilities.
95
+
96
+ New models use these constructor defaults:
97
+
98
+ | Setting | Default |
99
+ |---|---:|
100
+ | Vocabulary | 98 tokens |
101
+ | Hidden size | 64 |
102
+ | Context length | 48 characters |
103
+ | Feed-forward size | 128 |
104
+
105
+ The checked-in `checkpoints/model_final.npz` was trained with hidden size `128`, feed-forward size `256`, vocabulary size `98`, and context length `48`. The checkpoint loader reconstructs the saved shapes, so the runtime can use that model even though newly created models default to hidden size `64`.
106
+
107
+ Training supports two update styles:
108
+
109
+ - `backprop`: analytical gradients through the complete forward pass, with Adam updates and gradient clipping.
110
+ - `heuristic`: a smaller educational update that adjusts the output head and token embeddings.
111
+
112
+ The model also exposes `generate()` with temperature and nucleus (`top_p`) sampling, although the live lighting path uses the next-character probability distribution directly.
113
+
114
+ ## Why NumPy?
115
+
116
+ The point is transparency. There is no PyTorch graph hidden behind an API and no remote inference service. The project shows the whole loop:
117
+
118
+ ```text
119
+ text -> token IDs -> matrix operations -> probabilities -> physical LEDs
120
+ ```
121
+
122
+ That makes it useful as a learning project, a hardware experiment, and a compact place to study attention, backpropagation, checkpointing, and device control together.
123
+
124
+ For the full mathematical derivation and implementation walkthrough, read [GUIDE.md](GUIDE.md).
125
+
126
+ ## The Keyboard Layer
127
+
128
+ The Kreo Hive 75 profile describes 82 mapped physical keys across six logical rows and fifteen logical columns. The controller allocates 128 RGB memory slots because the hardware address space is larger than the visible key count.
129
+
130
+ `profiles/hive75.json` owns the details that must not be guessed from the keycap layout:
131
+
132
+ - USB IDs: `320f:5055`, `258a:010c`, `258a:002a`, and `258a:001f`
133
+ - EVision mode and RGB order
134
+ - Report ID `4`
135
+ - The verified key-to-slot mapping
136
+ - The 128-slot RGB buffer size
137
+
138
+ For the EVision interface, `hardware_controller.py` sends the 384-byte RGB buffer as 64-byte reports with up to 56 RGB payload bytes per report. Each report receives a 16-bit checksum and an acknowledgment is drained after the write. The EVision keepalive path refreshes the current frame every 100 milliseconds.
139
+
140
+ The controller also supports the Linux `hidraw` feature-report path and keeps reconnection ownership in the keepalive thread, so a failed write does not try to reconnect recursively while holding the frame lock.
141
+
142
+ ## The Runtime Has Guardrails
143
+
144
+ The live application is intentionally more than a loop around `model.forward()`:
145
+
146
+ - `pynput` captures global keyboard events while a platform console reader runs in its own worker.
147
+ - Carriage return becomes newline, terminal DEL becomes backspace, and unprintable controls are ignored.
148
+ - A 15 ms debounce window reduces duplicate events.
149
+ - A bounded queue prevents input capture from blocking forever during bursts.
150
+ - Backspace removes one character; Enter clears the context.
151
+ - The context is clamped to the model's maximum sequence length.
152
+ - Empty, NaN, or very low-confidence predictions return the board to white.
153
+ - Four recent WASD events or five identical repeated keys activate a temporary gaming pause.
154
+ - After the idle timeout, red prediction highlights are cleared.
155
+ - A lockfile prevents multiple processes from fighting over the same keyboard.
156
+ - Closing the application restores the keyboard's default lighting mode.
157
+
158
+ Because the reader uses a global keyboard hook, it can observe keystrokes in other windows, including sensitive fields. Use it only in an environment where that behavior is appropriate.
159
+
160
+ ## Colors Are the Interface
161
+
162
+ | Rank | Color | Meaning |
163
+ |---|---|---|
164
+ | Background | `#FFFFFF` | No prediction highlight |
165
+ | 1 | `#FF0000` | Highest-ranked physical key |
166
+ | 2 | `#FF3333` | Second-ranked key |
167
+ | 3 | `#FF5555` | Third-ranked key |
168
+ | 4 | `#FF7777` | Fourth-ranked key |
169
+ | 5 | `#FF9999` | Fifth-ranked key |
170
+
171
+ The runtime ranks physical keys, not only raw characters. If several predicted characters map to the same switch, their probabilities are combined before the key is assigned a color.
172
+
173
+ ## Try It Without Hardware
174
+
175
+ Install the pinned dependencies:
176
+
177
+ ```powershell
178
+ python -m pip install -r requirements.txt
179
+ ```
180
+
181
+ Then run the automated mock demo:
182
+
183
+ ```powershell
184
+ python predict_and_light.py --mock --demo --show-probs
185
+ ```
186
+
187
+ The demo feeds sample text into the same queue used by live input and prints the mock LED state. To type into the mock runtime yourself:
188
+
189
+ ```powershell
190
+ python predict_and_light.py --mock --show-probs
191
+ ```
192
+
193
+ ## Run the Physical Demo
194
+
195
+ Connect the Kreo Hive 75 and start the live predictor:
196
+
197
+ ```powershell
198
+ python predict_and_light.py --show-probs
199
+ ```
200
+
201
+ Useful options:
202
+
203
+ ```powershell
204
+ # Print the causal attention heatmap
205
+ python predict_and_light.py --show-probs --show-attn
206
+
207
+ # Show three ranked keys at half brightness
208
+ python predict_and_light.py --top-k 3 --brightness 0.5
209
+
210
+ # Start with an initial context
211
+ python predict_and_light.py --seed "The quick "
212
+
213
+ # Disable the automatic WASD pause
214
+ python predict_and_light.py --no-auto-pause-wasd
215
+ ```
216
+
217
+ The default checkpoint is `checkpoints/model_final.npz`. Use `--checkpoint PATH` to load another compatible checkpoint. `--profile NAME` selects a JSON profile from `profiles/`.
218
+
219
+ ## Train It Again
220
+
221
+ `train.py` builds overlapping character windows from a text file. An input window contains `seq_len` characters; the target window is the same text shifted one character forward. Backpropagation trains every position in the window at once.
222
+
223
+ ```powershell
224
+ # Analytical backpropagation, Adam, and a reproducible seed
225
+ python train.py --data data/sample_training_text.txt --epochs 15 --lr 0.003 --mode backprop --seed 42
226
+
227
+ # Resume weights and Adam state from a compatible checkpoint
228
+ python train.py --resume checkpoints/model_final.npz --epochs 5
229
+
230
+ # More overlapping windows and a larger validation holdout
231
+ python train.py --stride 1 --val-split 0.15
232
+
233
+ # Educational heuristic update
234
+ python train.py --mode heuristic
235
+ ```
236
+
237
+ Defaults are 15 epochs, learning rate `0.003`, context length `48`, hidden size `64`, stride `3`, backpropagation mode, and a `10%` validation split. Training writes `checkpoints/loss_log.csv`, periodic epoch checkpoints, and `checkpoints/model_final.npz`.
238
+
239
+ ## Test the Hardware Layer
240
+
241
+ The hardware utility can run against the mock controller:
242
+
243
+ ```powershell
244
+ python hardware_controller.py --mock
245
+ python hardware_controller.py --mock --key w ff0000 space 00ff00
246
+ python hardware_controller.py --mock --color 202020 --brightness 0.5
247
+ ```
248
+
249
+ Run the test suite from the repository root:
250
+
251
+ ```powershell
252
+ python tests/test_suite.py
253
+ ```
254
+
255
+ The tests cover model forward passes and checkpoint round trips, tokenizer and key mapping, RGB buffers, input normalization and debouncing, dataset creation, attention rendering, and predictive app lifecycle behavior.
256
+
257
+ ## Repository Map
258
+
259
+ | Path | Role |
260
+ |---|---|
261
+ | `model.py` | NumPy Transformer, generation, training steps, and checkpoints |
262
+ | `train.py` | Sliding-window dataset, training loop, validation, and loss logging |
263
+ | `key_mapper.py` | Vocabulary, tokenizer, and character-to-key translation |
264
+ | `predict_and_light.py` | Input capture, context state, prediction ranking, and lighting orchestration |
265
+ | `hardware_controller.py` | HID connection, RGB buffers, checksums, keepalive, reconnect, and mock output |
266
+ | `profiles/hive75.json` | Kreo Hive 75 USB identity, protocol, and LED slots |
267
+ | `data/sample_training_text.txt` | Example training corpus |
268
+ | `checkpoints/` | Saved model weights and training logs |
269
+ | `tests/test_suite.py` | Portable `unittest` coverage |
270
+ | `DemoVideo.mp4` | Recorded hardware demonstration |
271
+ | `GUIDE.md` | Full architecture and implementation walkthrough |
272
+
273
+ ## Limitations Worth Knowing
274
+
275
+ This is a small character model trained on a local corpus. It can learn useful local patterns, but it does not have the world knowledge, vocabulary, or reliability of a large language model. Predictions can be strange, especially with little context or a small training set.
276
+
277
+ The project currently targets the Kreo Hive 75 profile. Other keyboards need their own verified profile rather than a guessed row or column layout. HID permissions, global keyboard-hook permissions, and driver behavior also vary across operating systems.
278
+
279
+ ## License
280
+
281
+ MIT License. Built for transparent hardware experimentation and learning.