An AI keyboard that types new Shakespeare from an M5Stack CoreS3
Bard Lite is an AI keyboard. A small model on an M5Stack CoreS3 writes a new Shakespeare scene and types it into your computer as a USB keyboard. Open any text editor, tap Write a scene, and the lines appear as the model
Bard Lite is an AI keyboard. A small model on an M5Stack CoreS3 writes a new Shakespeare scene and types it into your computer as a USB keyboard. Open any text editor, tap Write a scene, and the lines appear as the model writes them. The model runs on the chip, with no network and nothing installed on the computer: it just sees a keyboard.
It got a short mention in my first post. This post covers the rest: turning the Complete Works into training data, knowing when to stop training on a small text, and making the CoreS3 a keyboard.
The code and model are here:
- esp32-bard-lite on GitHub
- jmclean/esp32-bard-lite on Hugging Face
| A scene | Another, with typing on |
|---|---|
![]() |
![]() |
Here's one of its scenes:
KING HENRY:
Cassian, let me hear us, and think it not.
What man doth do, to whose dangerous tears
Dispatch ourselves, with my dukedom with me?
You must be, my lord, for this night, I am glad.
KING JOHN:
Lord Baster Francular Hish,
Which I can do aslease me for the field.
HOTSPUR:
That I may find me, I'll say to him.
It sounds like Shakespeare and keeps to his layout. It rarely makes sense for long, and about one word in 30 is invented ("aslease"). Kings from different plays share a scene.
The model
The same kind of model as the rest of this series: a transformer in the per-layer embedding layout from slvDev/esp32-ai, with 4-bit weights, run by its inference code (llm.h).
It has 2.9 million parameters, but most of them are lookup tables. 1.6 million are per-layer embeddings and 0.2 million the token embedding, read straight from flash as each token needs them. The 1.1 million in the transformer core (6 layers, width 96, 4 attention heads) do the work. The model file is 1.5 MB.
It writes about 7.5 tokens a second. A scene averages about 180 tokens, so it takes about 24 seconds to write and type.
Where the time goes
I timed each part of writing a token on the CoreS3, over 4 or 5 scenes, with typing off:
| Per token | Time |
|---|---|
| Running the model | 95 ms |
| Redrawing the scene on screen | 37 ms |
| Picking the token | 4 ms |
| Total | about 136 ms |
The model is about 70% of the time. The screen is most of the rest, because after every token the whole scene so far is word-wrapped and redrawn.
The inference code has two ways to make the model faster, which Bard Lite doesn't use. One copies the 4-bit weights into PSRAM as 8-bit values when the model loads, so they don't have to be unpacked for every token. The other splits each matrix multiply across the ESP32-S3's two cores. I tried both:
| Model time per token | |
|---|---|
| As shipped: 4-bit weights, one core | 95 ms |
| 8-bit weights in PSRAM, one core | 89 to 93 ms |
| 8-bit weights in PSRAM, both cores | 73 to 80 ms |
Unpacking the weights costs very little. Two cores saved about 20%, not half, probably because both cores still read the weights from the same external memory. With both, a token takes about 115 ms instead of 136, about 8.7 tokens a second instead of 7.3.
In my diffusion model, layers whose weights didn't fit the ESP32-S3's 32 KB cache were the bottleneck. That doesn't happen here. A convolution uses each weight at every pixel, so weights that don't fit get fetched again and again. Writing one token uses each weight once, so there's nothing for the cache to save.
Turning the Complete Works into speeches
The training text is Project Gutenberg's Complete Works of William Shakespeare (ebook 100), public domain. The model should only learn to write speeches, so training/convert_complete_works.py keeps those and drops everything else: title pages, contents, cast lists, act and scene headings, stage directions, the sonnets and poems, and Project Gutenberg's licence text.
The Gutenberg text has two layouts. In some plays a speech is a speaker's name in capitals ending in a full stop, on its own line:
BARNARDO.
Who's there?
In most, the name starts the first line and the rest of the speech is indented:
DUNCAN. Great happiness!
The converter matches both:
NAME = re.compile(r"^[A-Z][A-Z0-9 ,'&-]*[A-Z]\.$") # "BARNARDO.", "FIRST CITIZEN."
INLINE = re.compile(r"^ {2}([A-Z][A-Z0-9 ,'&-]*[A-Z])\. +(.*)$") # " DUNCAN. Great happiness!"
STAGE = re.compile(r"^(Re-?enter|Enter|Exeunt|Exit)\b\.?")
GAP = re.compile(r" {3,}") # a gap before a direction
DIRECTION = re.compile(r"\[_.*?_\]|\[.*?\]") # "[_Exit._]", "[_Aside._]"
Stage directions turn up in several forms too: their own lines ("Exeunt."), "Enter ..." lines, text pushed off to the right after a wide gap, and brackets, some of which run on over a line break ("I think th'art mad. [Rises and walks"). Each of those is taken out.
Curly quotes, dashes and accented letters become plain ASCII, because the CoreS3 can only type plain characters.
The result is 29,711 speeches by 928 speakers, 4.4 MB, all in one layout: a name and a colon on one line, the lines spoken, a blank line.
The tokeniser and the end token
The model has its own tokeniser, learnt from the plays: byte-level BPE with 2,048 tokens. BPE (byte-pair encoding) starts from single bytes and keeps merging the commonest pairs into new tokens until it has enough, so common words and endings ("thou", "hath", "doth", "'d") become single tokens. A token here is about 2.7 characters.
training/prepare_shakespeare.py cuts the speeches into pieces of a few whole speeches, up to about 600 characters, and ends each piece with the end-of-text token:
def pieces(text):
speeches = [s.strip("\n") for s in text.split("\n\n") if s.strip()]
out, cur = [], ""
for s in speeches:
if cur and len(cur) + len(s) > PIECE:
out.append(cur)
cur = ""
cur = cur + s + "\n\n" if cur else s + "\n\n"
if cur:
out.append(cur)
return out
So in training, what always comes straight after the end token is the start of a speech: a speaker's name and a colon. The device uses that. It starts the model at the end token, and the first thing the model writes is a name. And because every piece ends with the end token, the model learns to end a scene on its own. In 50 scenes I generated with the same model and sampling code as the device, 47 ended themselves before the 256-token limit, after 3 or 4 speeches.
That's 1.5 million tokens to train on. The last 5% of the text (The Winter's Tale and part of The Two Noble Kinsmen) is held out: the model never trains on it, so its loss there shows how well it does on Shakespeare it hasn't seen.
Knowing when to stop
1.5 million tokens is a small text for a model this size. Train too long and it starts memorising lines rather than learning how they go. Loss on the training text keeps falling, but held-out loss (on the plays it never sees) starts rising.
So before the real run, a 5,000-step test run tracked both:
| Step | Training loss | Held-out loss |
|---|---|---|
| 250 | 4.32 | 4.51 |
| 500 | 3.89 | 4.23 |
| 1,000 | 3.37 | 4.04 |
| 1,500 | 3.10 | 4.01 |
| 2,000 | 2.96 | 4.04 |
| 3,000 | 2.83 | 4.13 |
| 5,000 | 2.43 | 4.35 |
Held-out loss is best at about 1,500 steps. After that the gap between the two keeps growing: the model is getting better at the plays it has seen and worse at the ones it hasn't. So training stops at 1,600 steps, about 4 passes over the text.
The first version was trained on tiny Shakespeare, a well-known 1.1 MB extract of the plays, a quarter as much text. Its test run started memorising much sooner:
| Step | Training loss | Held-out loss |
|---|---|---|
| 300 | 4.03 | 4.36 |
| 600 | 3.59 | 4.09 |
| 1,000 | 2.63 | 4.27 |
| 2,000 | 1.95 | 5.03 |
Best at about 600 steps, and by 2,000 its held-out loss was worse than at step 300. The two versions have different tokenisers, so their loss numbers can't be compared with each other, only the shape of each curve. Four times the text gave over twice the useful training.
The last 300 of the 1,600 steps are quantisation-aware: the weights are rounded to 4 bits in each training step, the way the device has them, so the model learns to work with the rounding. The full settings, in training/train.sh:
ESP32AI_DATA=data/bard2 ESP32AI_ALIGN_EOT=0 ESP32AI_QAT_STEPS=300 PYTHONPATH=src \
$PY research/tinystories/train.py --arm ple --vocab 2048 --d-model 96 --n-layers 6 \
--ple-dim 128 --target-core 1100000 --batch-size 16 --seq-len 256 --steps 1600 \
--lr 1e-3 --warmup 100 --eval-every 100 --tag bard2
Training takes about 4 minutes on an M3 MacBook. The final held-out loss is 3.99.
How good is it?
Against the first, tiny Shakespeare version, 12 scenes each, both checked against the complete works:
| Tiny Shakespeare | Complete works | |
|---|---|---|
| Words that aren't in Shakespeare | 10% | 3.6% |
| Runs of 8 words copied from the plays | 0 of 1,635 | 0 of 1,516 |
I checked the complete-works model again on 50 new scenes: 3.7% of words in the speeches aren't in Shakespeare, and none of 4,742 runs of 8 words appears in the plays.
Many of the invented words are near misses on real ones: "bewounded", "avoidder", "brokeing". Names get blended ("Lord Baster Francular Hish"), and speakers are invented as well as borrowed.
What still goes wrong:
- It doesn't make sense. Lines sound right, but the meaning wanders within a sentence or two.
- Characters mix plays. Kings from different histories meet, and Miranda (The Tempest) talks to Aaron (Titus Andronicus).
Picking each token
The model doesn't output a token. It outputs a score for each of its 2,048 tokens, and the device picks one at random, weighted by those scores. Two settings shape the pick:
- Top 40: only the 40 highest-scoring tokens can be picked. The other 2,008 are dropped, so a very unlikely token is never chosen.
- Temperature 0.8: the scores are divided by 0.8 before they're turned into probabilities. Dividing by less than 1 pushes the scores further apart, so the likelier tokens get a bigger share of the picks than they otherwise would.
static const float TEMPERATURE = 0.8f;
static const int TOP_K = 40;
...
float mx = -1e30f, p[TOP_K], sum = 0;
for (int i = 0; i < n; i++) mx = fmaxf(mx, s.logits[top[i]]);
for (int i = 0; i < n; i++) { p[i] = expf((s.logits[top[i]] - mx) / TEMPERATURE); sum += p[i]; }
float r = (esp_random() / 4294967296.0f) * sum;
for (int i = 0; i < n; i++) { r -= p[i]; if (r <= 0) return top[i]; }
p[i] is each of the 40 tokens' weight. The last two lines pick a random point between 0 and the total weight, then walk along the tokens until they reach it, so each token's chance is its share of the total. The random number comes from the ESP32's hardware random number generator, so every scene is different.
Making the CoreS3 a keyboard
The ESP32-S3 has native USB, so it can act as a USB device such as a keyboard. With TinyUSB, the CoreS3's USB port shows up as a keyboard and a serial port at the same time. That needs a change to the board's default USB mode in platformio.ini:
; USB as a keyboard and a serial port at once (TinyUSB), instead of the board's default
; built-in USB serial, which can only be a serial port.
build_unflags = -Os -DARDUINO_USB_MODE=1
build_flags = -O3 -DARDUINO_USB_MODE=0 -DARDUINO_USB_CDC_ON_BOOT=1
A USB keyboard is a HID (human interface device), which every computer accepts without a driver, so nothing needs installing.
Each token is typed as soon as it's written, a character at a time, with a Return for each new line:
static void typeOut(const uint8_t *b, int len) {
for (int i = 0; i < len; i++) {
if (b[i] == '\n') keyboard.write(KEY_RETURN);
else if (b[i] >= 32 && b[i] < 127) keyboard.write(b[i]);
}
}
A keyboard sends which keys are pressed, not characters, and the computer decides what each key means from its keyboard layout. The library maps each character to the keys a US keyboard would use, so on a computer set to another layout some punctuation comes out differently.
Some things to know:
- Typing starts off, so a scene only appears on the CoreS3's screen until you tap Typing: off to turn it on. When typing is on, there's a 3-second countdown to click into an editor.
- On a Mac, the Keyboard Setup Assistant opens the first time the CoreS3 is plugged in; close it. TextEdit turns ' into curly quotes; a plain-text editor keeps them as typed.
- Flashing needs download mode. The USB port is now a keyboard, not the usual serial port, so the upload tool can't put the board into its bootloader itself. Hold the reset button for about 3 seconds until the green LED lights, then flash.
Run it
Needs PlatformIO. Put the CoreS3 in download mode, then from firmware/:
pio run -t upload_model
pio run -t upload
Tap reset once to start it. The model goes into flash at 0xC00000, in the model partition, after the other apps' models.
Over serial at 115200, write writes a scene, shot sends the screen to tools/screenshot.py, and tap X Y touches the screen there.
Train it yourself
- Clone my fork of esp32-ai at the commit this model was trained with, and set up its environment. The fork adds the options this needs: another data folder, starting each training window at a piece, and quantisation-aware training.
git clone https://github.com/justinmclean/esp32-ai.git ~/esp32-ai
git -C ~/esp32-ai checkout 4074dae
- Download the Complete Works (5.9 MB, from the GITenberg copy on GitHub) and convert the plays:
training/get_data.sh
- Build the training data and tokeniser, then train and export into
firmware/model(about 4 minutes on an M3 MacBook):
export ESP32AI=~/esp32-ai
$ESP32AI/.venv/bin/python training/prepare_shakespeare.py data/complete.txt $ESP32AI/data/bard2
training/train.sh
A new tokeniser means new token ids, so reflash both the model and the app afterwards (train.sh rewrites firmware/src/vocab.h).
What I'd tell someone starting out
- Clean the data for what the device can output. It can only type ASCII, so the model only learns ASCII.
- End every training piece with the end token. Then the device can start a scene from it, and the model learns to finish one too.
- Hold some text out and watch both losses. On a small text, the point where held-out loss turns up is when to stop. Here that was about 1,500 steps; on a quarter of the text it was about 600.
- More text buys more training before memorising. Four times the text gave over twice the useful steps and a third as many invented words.
- Check for copying. None of the model's 8-word runs appear in the plays.
- A USB keyboard needs no software on the computer. Every computer accepts one without a driver.
Links
- esp32-bard-lite: code, firmware, training scripts and the model
- jmclean/esp32-bard-lite: the model, model card and full-precision weights
- slvDev/esp32-ai and my fork: the model layout, trainer and inference code
- Project Gutenberg's Complete Works of William Shakespeare: the training text
- Training a tiny model for the M5Stack CoreS3: the first post in this series
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.
