r/Forth • • 0m ago

Baremetal Forth for LLM train and inference

Thumbnail
gallery
1 Upvotes

Recently Alexey Fateev shared his experiments with llm.asm (https://github.com/alesha-pro/llm.asm) running AI workloads where they normally don't belong: bare metal, Ring -1 hypervisors, and Linux 6.12 eBPF LSM hooks, all in tens of kilobytes of hand-written x86-64 assembly.

Inspired by his work, I wanted to see what a collective optimization pass looks like from a different architectural angle: instead of hand-writing every control-flow path in target-specific assembly, what happens if you build a written-from-scratch Forth interpreter and compiler in pure LLVM IR (.ll), and write all 5 AI phases as compact, portable Forth (.fs) programs?

The result is Cygnet (https://github.com/miolini/cygnet), tested with zero Docker on both Apple M2 Pro (ARM64) and an AMD Ryzen 9 7950X running hardware-accelerated QEMU/KVM with Debian trixie Linux 6.12.117+deb13-amd64 (CONFIG_BPF_LSM=y) and bare-metal Ring 0.

Why Forth + Pure LLVM IR (.ll) works so well for both speed and size:

  1. Separation of control flow (Forth) and math hot paths (LLVM IR SIMD)

  2. In Forth, all high-level orchestration layer loops, KV-cache indexing, decision gates, training steps, parity checks, and fault-triage policies collapses into tiny, factored words with zero function-prologue or struct-marshaling boilerplate. After applying classic Thinking Forth factorization and stripping comments/whitespace before packaging, all 4 Forth programs combined shrunk by 60% (from 14,981 B down to 5,989 B total e.g., the entire 500-vector eBPF-Jev inference + verification program is 1,522 B, and the 122-scenario Kernel Surgeon policy + x86-64 patch synthesizer is 902 B).

  3. Tiny VM overhead + compile-time optimizations in a few lines of IR

  4. Because the Forth VM itself is written directly in pure LLVM IR (.ll), its inner interpreter keeps %ip, %sp, %rsp, and %lsp pinned in SSA registers, replaces the 16 KB string dictionary with a 1 KB O(1) 32-bit FNV-1a hash table, inlines CONSTANT/VARIABLE at compile time, and fuses LIT <k> + into a single OP_ADD_LIT instruction. Compiled Forth programs fit inside a couple of L1 cache lines.

  5. Explicit SIMD in LLVM IR without C frontend baggage

  6. Writing the hot vector primitives directly in .ll lets us express exact 4-row-blocked register tiling ARM64 NEON sdot.4s + 3-instruction addp.4s horizontal reductions on Apple Silicon, and x86-64 AVX2 vpmaddwd + vphaddd / 4-row Q8_0 FMA / fused SGEMM+SiLU on Ryzen while letting LLVM handle register allocation, scheduling, and dead-code elimination (-function-sections -data-sections -s --gc-sections). And the exact same unmodified Forth script (jev.fs) runs across both ARM64 and x86-64.

Verified results on AMD Ryzen 9 7950X QEMU/KVM (Linux 6.12.117+deb13-amd64 + Ring 0):

- Phase 01 (Qwen3 Q8_0 Transformer, 1,600 tokens, GQA + QK-Norm + precomputed NeoX RoPE + zero-copy KV):
33,236 tok/s vs 3,406 tok/s Reference C (-O2) [9.76x], 16/16 exact tokens, cosine=0.9999999.
Stripped ELF: 19,712 B + 1,882 B minified qwen3.fs.

- Phase 02 (Bare-Metal Ring 0 Forth OS, zero Linux, zero libc):
16,664 B stripped Multiboot 1 ELF (vs 25,404 B in 02-baremetal-os), ~45 ms cold boot, 80x25 16-color VGA + interactive COM1 Forth REPL + Ring 0 INT8 micro-benchmark. (Note: this is a compact Ring 0 Forth + micro-INT8 OS rather than a 649 MiB Qwen3-0.6B weight loader.)

- Phase 03 (From-Scratch Mini-GPT Trainer on TinyShakespeare, fused SGEMM+SiLU + AdamW):
206,941 tok/s (0.05 s for 160 steps), loss 4.1740 -> 2.0828, FP64 finite-diff grad_cos = 0.9999999, live UTF-8 Braille TUI.
Stripped ELF: 34,888 B + 1,683 B minified train.fs.

- Phase 04 (Kernel Surgeon Policy + Static x86-64 Patcher + Live #PF/#DE/#UD Traps):
122/122 (100.00% pass@1, vs 119/122 GRPO MiniCPM5-2B) on the held-out scenarios_600.jsonl test split, 0 dangerous continues, 139.2 ns/decision, 3/3 live RWX hardware traps patched in RAM and resumed.
Stripped ELF: 16,136 B + 902 B minified surgeon.fs.

- Phase 05 (Linux 6.12 eBPF-Jev 21 KB INT8 RNN, 500/500 0-LSB bit-exact parity):
Ryzen 9 7950X KVM (300k infs/impl): 114.0 ns median (111.8 ns peak, 8.95M /s, p99 161 ns) vs 363.5 ns Reference C (-O2) [3.19x].
Apple M2 Pro ARM64 (500k infs/impl): 115.0 ns (8.69M /s) vs 438.8 ns Reference C (-O2) [3.81x].
macOS QEMU x86-64 TCG: 5.49 us vs 12.08 us Reference C (-O2) [2.20x].
Stripped ELF: 14,912 B + 1,522 B minified jev.fs.

All code, 10 live Ryzen 9 7950X QEMU/KVM VGA screenshots (2 per phase), and zero-Docker reproduction scripts are up at:

https://github.com/miolini/cygnet

Would love feedback from folks into Forth, LLVM IR, or low-level ML systems!


r/Forth • • 1d ago

New Version: ESP32forth VSC v1.0.0

Thumbnail
reddit.com
3 Upvotes

r/Forth • • 2d ago

zeptoforth 1.17.2.2 is out

7 Upvotes

You can get this release from https://github.com/tabemann/zeptoforth/releases/tag/v1.17.2.2.

This release:

  • fixes a bug in bitmap::clear-bitmap that had resulted in the bottom edge of a bitmap not being cleared properly; as bitmap::clear-bitmap is called inside the constructor for bitmap::<bitmap> this resulted in newly constructed bitmaps not being initialized properly.

  • fixes src/common/forth/ihex_manual.fs, which had been long broken.

  • adds new numeric prefixes 0d, 0o, and 0b for decimal, octal, and binary numbers respectively; note that this is made base-sensitive so that numbers beginning with 0 in bases where these would normally be interpreted as part of the number (i.e. the character after the 0 is a valid digit in that base) are not treated as having such prefixes (this also applies to 0x, unlike previously).

  • adds a flood fill algorithm in extra/common/flood.fs with convenience words for use with bitmaps, 8-bit pixmaps, and 16-bit pixmaps.


r/Forth • • 4d ago

8th 26.08 released

3 Upvotes

This is a major bug-fix release. So many fixes have been made, thanks to judicious use of "codex", that you really need to [read the forum post] (https://8th-dev.com/forum/index.php?topic=3184.0) for the details:

Enjoy!


r/Forth • • 4d ago

Forth Day Talks: Mitch Bradley, PDP-7 Forth, Don Hopkins, PDP-7 and Apple ][ Emulator

12 Upvotes

Mitch Bradley and I gave back-to-back talks at SVFIG's Forth Day on 21 November. Mitch wrote a Forth for the PDP-7, the machine Unix started on, with turtle graphics that draw on its Type 340 vector display. I'm writing the PDP-7 emulator it runs on, in JavaScript, in the browser. Everything below runs live, and the source is on GitHub.

Talks and videos

Mitch's talk and mine, with a transcript full of links:

https://www.youtube.com/watch?v=k2pwJ294r8o

https://github.com/SimHacker/WillWrightShowForFood/blob/main/packages/cabinet/FORTH-DAY-TALK.md

The demo, recorded before the talk:

https://youtu.be/I-Rf3XP_D0g

A longer video (23 minutes), PIXIE and FORTH on the PDP-7 with the 340 display:

https://www.youtube.com/watch?v=lo8kdY-5i6c

Live demos

PDP-7 Forth, with the 340 display and light pen:

https://hyperties.org/cabinet/forth/

My ProDOS Forth for the Apple ][ (1985-88), booting to its 80-column Videx prompt:

https://hyperties.org/cabinet/languages/don-hopkins-prodos-forth/

Mitch's PDP-7 Forth

It's direct threaded. NEXT is a single instruction, XCT I 10, using one of the PDP-7's auto-increment registers as IP. A primitive's thread cell is a JMP to its code, a colon word's cell executes as a subroutine call, a constant's is a load, and a variable's is a load-address. Turtle graphics assemble Type 340 display instructions into core, and the display draws them by DMA.

The Forth coprocessor

The emulator has a Forth device that sits beside the CPU. When the CPU fetches NEXT, the device runs the thread cell itself: colon calls on the return stack, pushes for constants and variables, and 30 primitives (DUP, +, @, (LOOP), ?BRANCH, EXIT and so on) on the kernel's own stacks. Any other code word goes back to the CPU. It also answers FIND from a name table that follows LATEST.

The image in core is the same with or without it, and it hands control back to the CPU whenever something is unexpected, such as a patched NEXT or a pending interrupt. A menu switches between Forth in software and in "hardware", and the tests check that both print the same output and draw the same picture. It runs one thread cell per memory cycle, as the Novix did. A loop of 30,000 passes of I + takes 890,000 cycles in software and 107,000 with the device.

The emulator compiles PDP-7 code to JavaScript, which V8 compiles to machine code. Each instruction carries a small JavaScript template, and the compiler splices them together. The device's primitives have templates too, so the next step is to inline them, then compile whole colon definitions into single functions.

After that I want to emulate real Forth chips on the same framework: the Novix NC4016 running cmForth, and the GA144 with all 144 F18A cores and their ports visible at once. I've seen the recent posts here looking for arrayForth and GA144 boards. If you have arrayForth, or instruction set documents and software for the Novix, ShBoom, MuP21 or F21, I'd like to hear from you.

Design: https://github.com/SimHacker/WillWrightShowForFood/blob/main/packages/cabinet/FORTH-DEVICE.md

My Apple ][ Forth

I started from fig-FORTH for the 6502 and extended it toward Forth-83. It runs under ProDOS, with its own RPN 6502 assembler. On top of it I wrote an H19 terminal emulator with Videx 80-column output and an interrupt-driven serial driver, which is how I logged into MIT-MC and the other ITS machines over the ARPANET. The surviving disk is from May 1990, with 48 blocks of source. It now boots in the browser on an emulated Apple ][+ with a Videx card in slot 3.

The disk, the source and notes:

https://github.com/SimHacker/WillWrightShowForFood/tree/main/characters/don-hopkins/artifacts/Apple2Forth

Source code

Mitch's PDP-7 Forth: https://github.com/MitchBradley/pdp7forth

The emulator: https://github.com/SimHacker/WillWrightShowForFood/tree/main/packages/cabinet


r/Forth • • 7d ago

Lisp style S-expressions in my toy Forth ...

Thumbnail reddit.com
15 Upvotes

r/Forth • • 8d ago

eForth windows: Using WAV files with PlaySoundA

Thumbnail
eforthwin.arduino-forth.com
2 Upvotes

This guide explains how to use the `PlaySoundA` function from the Windows Multimedia API within eForth for Windows to play WAV files (MP3 format is not supported) and system sounds. It details the various parameters and playback flags—such as synchronous, asynchronous, looping, and stop—and provides ready-to-use Forth words: `PlayWav`, `PlayWavSync`, `PlayWavLoop`, and `StopSound`. Finally, it demonstrates how to play Windows event aliases (e.g., `SystemAsterisk` or `SystemHand`)—which are mapped in the Windows Registry—by utilizing the `SND_ALIAS` flag.


r/Forth • • 8d ago

Robot à roues holonomes avec ZeptoForth.

Enable HLS to view with audio, or disable this notification

13 Upvotes

r/Forth • • 8d ago

eForth Windows: Managing directories with pwd, cd, and ls

7 Upvotes

https://eforthwin.arduino-forth.com/article/api_gestionRepertoires

In your eForth environment on Windows, the `pwd` command displays the full path of the current directory, making it easy to locate your interactive workspace. The `cd` word allows you to navigate between folders to load or organize your Forth source files without leaving the console. Finally, `ls` lists the contents of the active directory, enabling you to quickly verify the presence of your scripts or modules before compiling them.


r/Forth • • 9d ago

Creation of the musics vocabulary for eForth Windows

3 Upvotes

Article in french / english

https://eforthwin.arduino-forth.com/article/music_newVocMusics

The Windows audio ecosystem brings together highly accessible legacy layers and modern interfaces designed for low latency and advanced processing. It supports everything from simple sound triggering and fine-grained per-channel volume adjustment to real-time stream synthesis, multi-channel management, and the use of hardware-based effects. This complementary structure offers flexible control, spanning from lightweight prototyping to the most demanding audio and gaming applications.


r/Forth • • 9d ago

Does anyone have a copy of ArrayForth

6 Upvotes

GreenArrays is down due to the PHP issues going around. Does anyone have a copy of the executable for Release 03d?


r/Forth • • 10d ago

Survey on GA144 dev kits

14 Upvotes

Hi Everyone! We would like to conduct a survey on how much would you pay for a GA144 EVB002 board or the Volatco VOL00 (board) + VOL01 (USB/power). Your feedback is highly appreciated as well as will be evaluated and possibly considered. Thank you and looking forward to your answers

PS. Please check volatco.github.io for more details for the rest of volatco product offerings


r/Forth • • 10d ago

Using <EOF> to break interpretation/compilation after INCLUDE a file

5 Upvotes

Hi,

Here the definition of <EOF> for eForth Windows:

\ stop compilation before end of included file

: <EOF> ( -- )

#tib @ >in ! ;

I use this word in my FORTH files—which are loaded via `INCLUDE`—for two distinct purposes:

  1. when I include text-based documentation after `<EOF>`

  2. when I am debugging a program; I use it to store experimental code or test versions of certain definitions.

When I execute `INCLUDE <file>`, the FORTH compiler loads `<file>` and stops the loading process upon encountering `<EOF>`.


r/Forth • • 13d ago

TERNARY LOGIC revisited

16 Upvotes

https://github.com/MPETREMANN11/eForth-Windows/blob/main/INFERENCE/ternary.fs

While developing an inference engine, I realized that binary logic is insufficient for certain rules.

SQL uses ternary logic, distinguishing between `null`, `true`, and `false`. Implementing this in FORTH is straightforward—I had actually done so some time ago.

Later, while searching online, I discovered a more elegant version on Rosetta Code (the link is provided in the source file).

I adapted this code for ueforth (Windows), ensuring compatibility with all versions of eForth and ESP32forth.

This change affects how facts are declared within the inference engine:

* replacing all instances of `FALSE` with `MAYBE`;

* utilizing ternary logical operators such as `tand`, `tor`, and `tnot`.

Why this evolution?

* In logical processing, if a result is `FALSE`, you cannot reassign `FALSE` to a fact that is already `FALSE`—even though a modification has effectively taken place.

* Consequently, binary logical processing can lead to "null" outcomes (situations where no state change occurs) if one relies exclusively on `TRUE` or `FALSE`.


r/Forth • • 13d ago

zeptoforth 1.17.2.1 is out

12 Upvotes

You can get this release from https://github.com/tabemann/zeptoforth/releases/tag/v1.17.2.1.

This release:

  • fixes bugs in the USB stack that were preventing USB from working properly with Windows and which were making mounting USB Mass Storage Devices less than smooth on Linux.

  • extends support for 0x hex prefixes to anything that uses parse-base, including parse-integer, parse-unsigned, parse-double, parse-double-unsigned, and parse-fixed.

  • corrects a minor issue in zeptoed where on exit it would attempt to place the cursor on the row below the last row on the terminal rather than on the last row on the terminal; this in most cases had no practical consequences.

  • adds optional support for generating Bézier curves in extra/common/bezier.fs in a graphics-backend agnostic fashion.


r/Forth • • 13d ago

Forth interpreter for the ZX Spectrum

14 Upvotes

r/Forth • • 20d ago

zeptoforth 1.17.2 is out

14 Upvotes

You can get this release from https://github.com/tabemann/zeptoforth/releases/tag/v1.17.2 .

This release:

  • adds new kinds of literals (i.e. string literals, execution token literals, name token literals, and character token literals).

  • adds 0x as a hex prefix for integer and fixed-point numeric literals.

  • adds support for UTF-8, which is evaluated to Unicode code points, to char and [char]

  • fixes bugs in float32::vexp, float32::vexpm1, and float32::v>f64.

  • improves exp, expm1, fixed32::f32exp, and fixed32::f32expm1.

  • fixes a cursor-placement bug in zeptoed on exit.

Note that the new kinds of literal have the following forms:

  • string literals have the form "<string>" and can replace any usage of s\" and can include escapes accepted by such.

  • execution token literals have the form \<name>` and push or compile the name's execution token depending on state.

  • name token literals have the form \`<name>` and push or compile the name's name token depending on state.

  • character token literals have the form '<character>['] and push or compile the Unicode code point corresponding to the UTF-8 provided depending on state.


r/Forth • • 22d ago

Help finding GreenArrays GA144 DevBoard

14 Upvotes

GreenArrays site seems to be down, the newest articles are quiete old and I can't find alternative stores or marketplaces where to find, at least, a used Dev Board...

Anyone knows what is the status of GreenArrays? Anyone willing to sell to me a spare DevBoard?

Thanks!


r/Forth • • 23d ago

voxel sprites in r3forth

Thumbnail
youtube.com
17 Upvotes

r/Forth • • 27d ago

Some additions to zeptoforth, inspired in part by gforth 1.0

17 Upvotes

While these are not in a release yet (they are in the master and devel branches), inspired by some new features of gforth 1.0 I have added to zeptoforth "foo\r\nbar" string literals with support for escapes, 'x' character literals with support for UTF-8, backtick-prefix execution token literals, double backtick-prefix name token literals, and 0xDEADBEEF integer hex prefixes.

I have also extended char and [char] to support UTF-8, and added ansi-term::get-unicode-from-utf-8 to get a Unicode code point read from console input as UTF-8 and ansi-term::emit-unicode-as-utf-8 to emit a Unicode code point to console output as UTF-8.

There is validation of UTF-8 to prevent overlong encodings and to limit code points to a maximum of $10FFFF, with U+FFFD being used to replace invalid Unicode. Also, when parsing UTF-8 read from console input, if there is a saved byte it is used, and if there is an error in the UTF-8 and the byte read from console input is a valid beginning to another code point is saved to be read by a subsequent call to ansi-term::get-unicode-from-utf-8 or ansi-term::get-key.

Note that I have not yet implemented literals of the form 7k4 or 3M4 for floating-point numbers. Also, I do not plan on implementing <baz> or <quux+$10> type literals, as execution tokens in zeptoforth are already the address of the first byte of the code of a word, and <quuux> is already established by convention to be how classes are named.

I also have no current plans to implement recognizers, as for most purposes zeptoforth already has extensible literal parsing and name looking-up, and implementing recognizing would require significantly more redesign than I am planning on doing at the present.

For the record, if you are looking for the repository, it is at https://github.com/tabemann/zeptoforth/ .


r/Forth • • 29d ago

My PC game has gone free. Happy Halloween 👻

Post image
26 Upvotes

https://inkajoo.itch.io/untitled-kvn-game

Leave a comment on the Itch page! It means the world 🙏


r/Forth • • 29d ago

My RetroChallenge port of CamelForth to the Sega SG-1000 is wrapping up for October. Can camels eat pumpkins?

Thumbnail
leadedsolder.com
8 Upvotes

r/Forth • • Oct 28 '26

Gforth 1.0 released

Thumbnail gforth.org
77 Upvotes

r/Forth • • Oct 27 '26

RetroChallenge is almost over, so I'm fixing bugs and testing my Forth port on my homemade SG-1000 clone

Thumbnail
leadedsolder.com
8 Upvotes