Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-bridge/patches/3ffeda8991d78e5b # omega-bridge Omega-first language interoperability: checked conversion backends and native language bindings Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/omega-bridge#23 (code only) closed derived `3ffeda8991d78e5b` #23 Imported from GitHub aien-dev/omega-bridge#23 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `fa8581e80afbfbfa4bb2a6622b2f2ca07c365720` · Head `9eb8efd8680159eb26664562766ed9f53448886d` github-advanced-security[bot] commented on `pytorch/omega_torch/__init__.py` line 100 on 2026-10-26 23:16 UTC ## CodeQL / Overly permissive file permissions Overly permissive mask in chmod sets file to world readable. Show more details github-advanced-security[bot] reviewed (COMMENTED) on 2026-10-26 23:16 UTC ### Fetch it A git bundle of the pull request's head, 37974 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/omega-bridge/patches/3ffeda8991d78e5b.bundle -o 3ffeda8991d78e5b.bundle git fetch 3ffeda8991d78e5b.bundle refs/pull/23/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/omega-bridge 23 9eb8efd8680159eb26664562766ed9f53448886d ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"omega-bridge","number":23,"url":"https://github.com/aien-dev/omega-bridge/pull/23","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:39:57Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/AGENTS.md b/AGENTS.md index 229ea76..6bacb03 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,6 +13,7 @@ Shared rules: read https://www.aienos.com/agents/RULES.md first. This file adds - `tools/`: shell entry points (`bootstrap.sh`, `build.sh`, `test.sh`, `bridge`, `native`, `build-gpu-adapter.sh`, `run-device-window.sh`). - `tests/`: Python test harness (infrastructure only), fixtures, refusal cases, native callers in six languages, GPU adapter protocol tests. - `conformance/`: separate-process Omega versus Modular MAX harness. `evidence/`: raw logs and result manifests. +- `pytorch/`: `torch.compile` backend `"omega"` (docs/OMEGA-TORCH.md). Kernels are `.om` (`pytorch/kernels/`); `pytorch/omega_torch/` is interim Python glue that registers the backend, walks the FX graph and calls units through the native ABI. It must never compute a tensor value; an unsupported op raises, and eager fallback only happens for ops the caller names, counted. - No compiler binary is stored here. Python/C input conversion is not implemented. Text constants, floats, heap operations and other target languages are refused by the C/Python converters. ## Installation diff --git a/README.md b/README.md index 5240540..44bb4b4 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,8 @@ quiet-build python3 tests/attachments.py See [supported features and limits](docs/CAPABILITIES.md), [caller ABI and ownership](docs/ABI.md), [design and study decisions](docs/DESIGN.md), and [provenance](docs/PROVENANCE.md). Text constants, floats, heap operations and other target languages are explicitly unsupported by the C/Python converters. GPU interoperability is a separate, opt-in adapter boundary (it converts no host program): see [GPU adapter](docs/GPU-ADAPTER.md) and the [support matrix](docs/GPU-SUPPORT-MATRIX.md). Python/C input conversion is not implemented. The Python test harness is infrastructure; all conversion logic and both runtime emitters are in [src/toc.om](src/toc.om). +PyTorch: `torch.compile(model, backend="omega")` runs a small set of float32 core-ATen ops (mm, addmm, 2-D transpose, add, relu, softmax) on CPU through Omega-generated AArch64 kernels called via the native call ABI, and refuses everything else. The Python under `pytorch/omega_torch/` is interim glue that computes no tensor value. Exercised on CPU against PyTorch eager only; see [docs/OMEGA-TORCH.md](docs/OMEGA-TORCH.md). + DeepInfer (deepseek-ai/DeepInfer) is a proposed translation and attachment target; its inventory, measured import coverage and extension plan are in [DeepInfer as a bridge target](docs/DEEPINFER.md). Call compiled Omega in place from six languages (the native call adapter, a separate claim from conversion: it runs Omega's own machine code, it does not turn Omega into another language): diff --git a/docs/NATIVE-ABI.md b/docs/NATIVE-ABI.md index a5508ae..8391609 100644 --- a/docs/NATIVE-ABI.md +++ b/docs/NATIVE-ABI.md @@ -259,8 +259,11 @@ Names must be C identifiers, a parameter name may not end in `_len` (the binding `o__len`), and each unit name appears once; anything else is refused before any C is written. Supported signatures: up to 6 parameters, each `ulong`, `long`, or `edit`/`view` of `ulong`, `uchar`, -`f32` or `ushort` with a fixed length; result `ulong`, `long` or `void`. An `f32` array is packed -binary32 (4-byte elements, 4-byte alignment) and a `ushort` array is packed 16-bit words (2-byte +`f32` or `ushort` with a fixed length; result `ulong`, `long` or `void`. A length is a decimal number or +the name of an integer constant declared on its own line before the signature as exactly +`const NAME ulong DIGITS` (OMEGESE 9.12); any other spelling of a constant used as a length is refused, +so a shape-specialised unit can be written as one fixed kernel text after a header of constants. +An `f32` array is packed binary32 (4-byte elements, 4-byte alignment) and a `ushort` array is packed 16-bit words (2-byte elements, 2-byte alignment), for example binary16 bits that the Omega code converts itself. C and C++ declarations stay `void *` / `const void *`; the generated library checks the element size, alignment, length and overlap. Python ctypes uses `c_float` and `c_uint16`. Rust and Zig declarations type these @@ -386,7 +389,7 @@ one-word type change in the generator must make that build or run fail for the s | | | |---|---| | scalar argument | `uint64_t`, the canonical bits of its type; a `long` is its two's-complement bits (-3 is 18446744073709551613) | -| array argument | `void *` (`const void *` for `view`) then `uint64_t` element count, which must equal the declared length | +| array argument | `void *` (`const void *` for `view`) then `uint64_t` element count, which must equal the declared length; elements are 8 bytes (`ulong`), 1 byte (`uchar`), 4 bytes (`f32`, IEEE-754 binary32) or 2 bytes (`ushort`), and the address must be aligned to the element size | | result | written only on status 0; a `void` function writes 0 | | status 0 | success | | status 1..14 | the Omega trap code (1 overflow, 2 divide by zero, 3 bounds, 4 loop bound, 5 conversion, 6 resource, 7 shift, or a `trap N` code) | @@ -466,6 +469,31 @@ by 70 (calc:a6a8bb76), 4,000,000 bytes is 0.954 of 4 MiB (calc:ffff21b2). Negati Separate claims, not made here: source translation (ABI v0) and GPU execution are qualified on their own. These historical qualification results cover AArch64 Linux, not the x86 target. +`f32` arrays and constant lengths (2026-10-26, for `pytorch/`): exercised by +`pytorch/tests/test_omega_torch.py` (class `Binding`: a `const L ulong 6` f32 unit binds with element +size 4 and the right writable flags; a `const L uint 6` length and an `f64` array are refused with exit +110 and no output) and by every PyTorch op test, which calls f32 units through this binding. Those tests +use the omega-mv main compiler (`2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f`, +omega-mv `369dbc96`), because floats are newer than the pin above. `tests/native/run.sh` with the pinned +compiler still prints `NATIVE-CALL PASS` with this generator. + +After merging main `7af4d11` (2026-11-04), the f32 kinds are #26's and this change adds only the +named lengths (the unit start is kept in `st 9`). The generator now takes its output word as argument 1, +so the PyTorch glue and the `Binding` tests call it with `c`; before that fix every unit was refused +with exit 110, which the two refusal tests could not tell from a real refusal. Rerun: 22 tests OK +(`evidence/omega-torch-m1/tests-merge-main-7af4d11.log`); with `pparam` reverted to `tknum` (named +lengths unread) `test_const_f32_bound` fails and `Ops.test_mm` errors with the refusal (exit 110) +(`evidence/omega-torch-m1/mutant-const-length-tknum.log`). + +Which compilers reach a named length (issue #20, 2026-11-04, `evidence/issue-20-const-length/red-green.log`): +the AArch64 OM-1 pin `734f0a39` refuses `const` itself (`omc: line 8: error 9`), so through +`tools/native` an AArch64 OM-1 unit with a named length stays refused until that pin moves past omega-mv +#806. The x86 pin `be8c5130`, omega-mv main `b4f45121` and `2c824805` accept it and emit code +byte-identical to the literal form. With `--target x86linux`, main `7af4d11` refuses the unit with exit +110 and this generator binds it; the bindings differ from the literal unit's only in the echoed +signature comment, and a C caller under QEMU 10.0.14 gets the same result and the same wrong-length +status 32 (EMULATED; physical x86 NOT_RUN). An undeclared name is refused by the compiler (error 16). + Zig and Go: run with Zig 0.13.0 and Go 1.27.3 (official aarch64 archives, checksums from ziglang.org/download/index.json and go.dev/dl, unpacked in the user's ~/.local/opt). Both callers pass their checks (12 each in this change). The library is linked with `-soname libomega_native.so`: without that name, Zig records the diff --git a/docs/OMEGA-TORCH.md b/docs/OMEGA-TORCH.md new file mode 100644 index 0000000..e1d54c8 --- /dev/null +++ b/docs/OMEGA-TORCH.md @@ -0,0 +1,70 @@ +# Omega under PyTorch: `torch.compile(model, backend="omega")` (milestone 1) + +Status: IMPLEMENTED and EXERCISED on CPU only (AArch64, DGX Spark host), oracle = PyTorch eager, +Omega-native codegen, Python glue. Not qualified, not merged, not a claim that Omega runs PyTorch in +general: it runs the core-ATen ops listed below, float32, static shapes, inference only. + +## What runs where + +| Layer | Implementation | Status | +|---|---|---| +| Kernels (`pytorch/kernels/*.om`) | seeded Omega, compiled by omega-mv `seed/out/omc` in function mode to AArch64 words | first-party | +| Binding (`src/native.om`) | Omega program that writes the C trampoline of native call ABI v1 (`docs/NATIVE-ABI.md`) | first-party; the C it writes is compiled by the host `cc` | +| Backend glue (`pytorch/omega_torch/__init__.py`) | Python: registers the backend, walks the FX graph, allocates outputs, calls units through `ctypes` | interim migration step | + +The glue computes no tensor value. Every value in an output was written by Omega machine code; +the glue only reads shapes, picks a kernel, supplies the shape constants as a `const NAME ulong N` +header in front of the fixed kernel text, and passes buffer addresses. + +## Ops + +Covered (core ATen after `core_aten_decompositions()`): `aten.mm`, `aten.addmm` (1-D bias, beta = alpha += 1), `aten.permute` (2-D, dims `[1, 0]`), `aten.add.Tensor` (equal shapes, alpha 1), `aten.relu`, +`aten._softmax` (2-D, last dim, `half_to_float` false). `addmm(b, x, permute(W, [1, 0]))` whose +permute has no other user is lowered to the `linear` kernel, which reads `W` in place. + +Refused at compile time, with every refused node listed and nothing run: any other op, broadcasting, +non-float32 dtypes, non-CPU devices, symbolic shapes (`dynamic=False` is required), empty tensors, +tensors above the Omega array limit of 16,777,216 elements (OMEGESE 9.4), softmax rows above the 4 MiB +local-array limit, non-contiguous inputs (at run time), autograd (run under `torch.no_grad()`), and a +visible CUDA device. Eager fallback exists only for ops named in `OMEGA_TORCH_FALLBACK` (or +`omega_torch.set_fallback`), and every such call is counted in `STATS["eager_fallback_calls"]`. + +Numerics: each dot product and softmax sum is accumulated in f64 and rounded once to f32. `exp` is +written in Omega (`expd` in `softmax.om`): range reduction by ln 2, degree-13 Taylor polynomial +(truncation below 5.9e-18 relative), exponent bits for 2^k. + +## Use + +```sh +export CUDA_VISIBLE_DEVICES= # TorchDynamo touches CUDA while tracing; milestone 1 is CPU only +export OMEGA_OMC=/path/to/omega-mv/seed/out/omc # sha256 2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f +python3 -m unittest -v pytorch/tests/test_omega_torch.py +``` + +```python +import sys; sys.path.insert(0, "pytorch") +import omega_torch # registers backend "omega" +with torch.no_grad(): + y = torch.compile(model, backend="omega", fullgraph=True, dynamic=False)(x) +``` + +Built units are cached under `build/torch/`. + +## Host dependencies + +| Dependency | Version used | What it does here | Omega successor | +|---|---|---|---| +| PyTorch | 2.14.0+cu130 | TorchDynamo capture, AOTAutograd core-ATen decomposition, tensor allocation, the eager oracle | the oracle stays; capture moves behind a PrivateUse1 `omega` device whose dispatch is an Omega unit | +| CPython | 3.12.3 | runs the glue and `ctypes` | the glue's graph walk and dispatch move into an Omega unit called through the same C ABI | +| `cc` (GCC) | system | compiles the C trampoline `src/native.om` writes | an Omega-emitted ELF shared object (the trampoline is a fixed instruction sequence) | + +## Successor + +The Python glue is interim. The successor is a PrivateUse1 out-of-tree device `omega` +(`torch.utils.rename_privateuse1_backend("omega")`) whose operator registrations are a fixed C ABI +table generated by the bridge, with lowering, shape specialisation and dispatch done by an Omega unit. +That keeps the PyTorch-required registration as the only foreign code and lets eager ops and +`torch.compile` graphs share one Omega dispatcher. Later targets (GB10 SASS, SPIR-V, StableHLO, +Tenstorrent, NKI) plug in at the kernel layer, unchanged above it. GPU runs are NOT_RUN: they need an +authorized window. diff --git a/evidence/issue-20-const-length/all.sh b/evidence/issue-20-const-length/all.sh new file mode 100644 index 0000000..093eaa1 --- /dev/null +++ b/evidence/issue-20-const-length/all.sh @@ -0,0 +1,11 @@ +cd /tmp/sweep/Dra103Bridge/i20 +echo "# omega-bridge#20: integer const as an array length. $(date -u +%FT%TZ)" +echo "# compilers (sha256 prefix = file name): omc-734f bridge OM-1 pin; omc-b4f4 omega-mv main; omc-be8c bridge x86 pin; omc-2c82 omega_torch kernels" +echo "## 1. direct compile (stdin -> code); cnst.om vs lit.om" +sh c.sh +echo "## 2. tools/native: ob = main 7af4d11 (red), w23 = feat/omega-torch-m1 (green)" +sh g.sh +echo "## 3. generated bindings, cnst vs lit (w23, x86linux): only the signature comment differs" +for f in omega_native.c omega_native.h omega_native.py omega_native.rs omega_native.zig omega_native.go; do cmp -s out-w23-cnst/$f out-w23-lit/$f && echo "$f identical" || { echo "$f:"; diff out-w23-cnst/$f out-w23-lit/$f; }; done +echo "## 4. C caller under QEMU 10.0.14 (EMULATED; physical x86 NOT_RUN)" +sh q.sh diff --git a/evidence/issue-20-const-length/c.sh b/evidence/issue-20-const-length/c.sh new file mode 100644 index 0000000..5d58caa --- /dev/null +++ b/evidence/issue-20-const-length/c.sh @@ -0,0 +1 @@ +for c in b4f4 734f 2c82 be8c 13ce 3988; do for u in cnst lit unk; do /tmp/sweep/L7/omc-$c < $u.om > $u-$c.bin 2>$u-$c.err; echo "omc-$c $u rc=$? $(sha256sum < $u-$c.bin|cut -c1-16) $(cat $u-$c.err)"; done; done diff --git a/evidence/issue-20-const-length/call.c b/evidence/issue-20-const-length/call.c new file mode 100644 index 0000000..f47ba18 --- /dev/null +++ b/evidence/issue-20-const-length/call.c @@ -0,0 +1,6 @@ +#include +#include +#include "omega_native.h" +int main(void){uint64_t b[4]={1,2,3,4},r=0;uint32_t s=omega_f(&r,b,4,10); +int ok=s==0&&r==14&&b[0]==11&&b[3]==14;uint64_t r2=0;uint32_t s2=omega_f(&r2,b,3,10); +ok=ok&&s2!=0;printf("%s status=%u result=%lu buf0=%lu wronglen_status=%u\n",ok?"PASS":"FAIL",s,(unsigned long)r,(unsigned long)b[0],s2);return !ok;} diff --git a/evidence/issue-20-const-length/cnst.om b/evidence/issue-20-const-length/cnst.om new file mode 100644 index 0000000..dc47dc4 --- /dev/null +++ b/evidence/issue-20-const-length/cnst.om @@ -0,0 +1,7 @@ +const N ulong 4 +fn f buf edit ulong N k ulong to ulong +for i ulong N +put buf i add get buf i k +end +ret get buf 3 +end diff --git a/evidence/issue-20-const-length/g.sh b/evidence/issue-20-const-length/g.sh new file mode 100644 index 0000000..8ddf386 --- /dev/null +++ b/evidence/issue-20-const-length/g.sh @@ -0,0 +1,6 @@ +export OMEGA_NATIVE_OMC=/tmp/sweep/L7/omc-734f OMEGA_NATIVE_X86_OMC=/tmp/sweep/L7/omc-be8c CC=x86_64-linux-gnu-gcc +for w in ob w23; do for u in cnst lit unk; do + rm -rf out-$w-$u; /tmp/sweep/Dra103Bridge/$w/tools/native --target x86linux out-$w-$u $u.om > $w-$u.log 2>&1; echo "$w x86 $u rc=$? $(tail -1 $w-$u.log)" +done + rm -rf a-$w; OMEGA_NATIVE_X86_OMC= CC=cc /tmp/sweep/Dra103Bridge/$w/tools/native a-$w cnst.om > a-$w.log 2>&1; echo "$w aarch64 cnst rc=$? $(tail -1 a-$w.log)" +done diff --git a/evidence/issue-20-const-length/lit.om b/evidence/issue-20-const-length/lit.om new file mode 100644 index 0000000..f1e2d0c --- /dev/null +++ b/evidence/issue-20-const-length/lit.om @@ -0,0 +1,6 @@ +fn f buf edit ulong 4 k ulong to ulong +for i ulong 4 +put buf i add get buf i k +end +ret get buf 3 +end diff --git a/evidence/issue-20-const-length/q.sh b/evidence/issue-20-const-length/q.sh new file mode 100644 index 0000000..c4513c4 --- /dev/null +++ b/evidence/issue-20-const-length/q.sh @@ -0,0 +1,2 @@ +Q=~/work/bridge-x86/build/qemu-oracle/build/qemu-x86_64 +for d in out-w23-cnst out-w23-lit; do x86_64-linux-gnu-gcc -I$d call.c -L$d -lomega_native -Wl,-rpath,'$ORIGIN' -o $d/call && $Q -L /usr/x86_64-linux-gnu $d/call; echo "$d rc=$?"; done diff --git a/evidence/issue-20-const-length/red-green.log b/evidence/issue-20-const-length/red-green.log new file mode 100644 index 0000000..3d5c755 --- /dev/null +++ b/evidence/issue-20-const-length/red-green.log @@ -0,0 +1,62 @@ +# omega-bridge#20: integer const as an array length. 2026-11-04T22:36:57Z +# compilers (sha256 prefix = file name): omc-734f bridge OM-1 pin; omc-b4f4 omega-mv main; omc-be8c bridge x86 pin; omc-2c82 omega_torch kernels +## 1. direct compile (stdin -> code); cnst.om vs lit.om +omc-b4f4 cnst rc=0 de45ba98406be279 +omc-b4f4 lit rc=0 de45ba98406be279 +omc-b4f4 unk rc=16 e3b0c44298fc1c14 omc: line 2: error 16 +omc-734f cnst rc=9 e3b0c44298fc1c14 omc: line 8: error 9 +omc-734f lit rc=0 de45ba98406be279 +omc-734f unk rc=16 e3b0c44298fc1c14 omc: line 2: error 16 +omc-2c82 cnst rc=0 de45ba98406be279 +omc-2c82 lit rc=0 de45ba98406be279 +omc-2c82 unk rc=16 e3b0c44298fc1c14 omc: line 2: error 16 +omc-be8c cnst rc=0 de45ba98406be279 +omc-be8c lit rc=0 de45ba98406be279 +omc-be8c unk rc=16 e3b0c44298fc1c14 omc: line 2: error 16 +omc-13ce cnst rc=0 de45ba98406be279 +omc-13ce lit rc=0 de45ba98406be279 +omc-13ce unk rc=16 e3b0c44298fc1c14 omc: line 2: error 16 +omc-3988 cnst rc=0 de45ba98406be279 +omc-3988 lit rc=0 de45ba98406be279 +omc-3988 unk rc=16 e3b0c44298fc1c14 omc: line 2: error 16 +## 2. tools/native: ob = main 7af4d11 (red), w23 = feat/omega-torch-m1 (green) +ob x86 cnst rc=110 tools/native: refused cnst.om: outside the native call subset, or a name the binding cannot carry (docs/NATIVE-ABI.md); nothing installed +ob x86 lit rc=0 tools/native: 1 unit(s) -> /out-ob-lit/libomega_native.so + omega_native.{c,h,py,rs,zig,go} (+ work/) +ob x86 unk rc=16 omc: line 3: error 16 +ob aarch64 cnst rc=9 omc: line 8: error 9 +w23 x86 cnst rc=0 tools/native: 1 unit(s) -> /out-w23-cnst/libomega_native.so + omega_native.{c,h,py,rs,zig,go} (+ work/) +w23 x86 lit rc=0 tools/native: 1 unit(s) -> /out-w23-lit/libomega_native.so + omega_native.{c,h,py,rs,zig,go} (+ work/) +w23 x86 unk rc=16 omc: line 3: error 16 +w23 aarch64 cnst rc=9 omc: line 8: error 9 +## 3. generated bindings, cnst vs lit (w23, x86linux): only the signature comment differs +omega_native.c identical +omega_native.h: +18c18 +< /* fn f buf edit ulong N k ulong to ulong */ +--- +> /* fn f buf edit ulong 4 k ulong to ulong */ +omega_native.py: +27c27 +< # fn f buf edit ulong N k ulong to ulong +--- +> # fn f buf edit ulong 4 k ulong to ulong +omega_native.rs: +19c19 +< // fn f buf edit ulong N k ulong to ulong +--- +> // fn f buf edit ulong 4 k ulong to ulong +omega_native.zig: +11c11 +< // fn f buf edit ulong N k ulong to ulong +--- +> // fn f buf edit ulong 4 k ulong to ulong +omega_native.go: +28c28 +< // fn f buf edit ulong N k ulong to ulong +--- +> // fn f buf edit ulong 4 k ulong to ulong +## 4. C caller under QEMU 10.0.14 (EMULATED; physical x86 NOT_RUN) +PASS status=0 result=14 buf0=11 wronglen_status=32 +out-w23-cnst rc=0 +PASS status=0 result=14 buf0=11 wronglen_status=32 +out-w23-lit rc=0 diff --git a/evidence/issue-20-const-length/unk.om b/evidence/issue-20-const-length/unk.om new file mode 100644 index 0000000..7437cc9 --- /dev/null +++ b/evidence/issue-20-const-length/unk.om @@ -0,0 +1,4 @@ +const N ulong 4 +fn f buf edit ulong M k ulong to ulong +ret k +end diff --git a/evidence/omega-torch-m1/mutant-const-length-tknum.log b/evidence/omega-torch-m1/mutant-const-length-tknum.log new file mode 100644 index 0000000..cdc623b --- /dev/null +++ b/evidence/omega-torch-m1/mutant-const-length-tknum.log @@ -0,0 +1,71 @@ +F..E +====================================================================== +ERROR: test_mm (pytorch.tests.test_omega_torch.Ops.test_mm) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/pytorch/tests/test_omega_torch.py", line 66, in test_mm + self.check(torch.mm, torch.randn(5, 7), torch.randn(7, 3), kernels=["mm"]) + File "/pytorch/tests/test_omega_torch.py", line 59, in check + got, want = run_both(fn, *args) + ^^^^^^^^^^^^^^^^^^^ + File "/pytorch/tests/test_omega_torch.py", line 32, in run_both + got = compiled(fn)(*args) + ^^^^^^^^^^^^^^^^^^^ + File "~/.venv/lib/python3.12/site-packages/torch/_dynamo/eval_frame.py", line 1278, in compile_wrapper + raise e.remove_dynamo_frames() from None # see TORCHDYNAMO_VERBOSE=1 + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "~/.venv/lib/python3.12/site-packages/torch/_dynamo/output_graph.py", line 3260, in _call_user_compiler + raise BackendCompilerFailed( + File "~/.venv/lib/python3.12/site-packages/torch/_dynamo/output_graph.py", line 3232, in _call_user_compiler + compiled_fn = compiler_fn(gm, example_inputs) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "~/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/after_dynamo.py", line 163, in __call__ + compiled_gm = compiler_fn(gm, example_inputs) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "~/.venv/lib/python3.12/site-packages/torch/__init__.py", line 3002, in __call__ + return self.compiler_fn(model_, inputs_, **self.kwargs) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/pytorch/tests/../omega_torch/__init__.py", line 332, in omega + return aot_module_simplified(gm, example_inputs, fw_compiler=fw, + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "~/.venv/lib/python3.12/site-packages/torch/_functorch/aot_autograd.py", line 1250, in aot_module_simplified + compiled_fn, _ = aot_stage2_compile( + ^^^^^^^^^^^^^^^^^^^ + File "~/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_compile.py", line 365, in aot_stage2_compile + return aot_stage2_inference( + ^^^^^^^^^^^^^^^^^^^^^ + File "~/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_compile.py", line 489, in aot_stage2_inference + compiled_fw = _aot_stage2b_inference_compile( + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "~/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_compile.py", line 416, in _aot_stage2b_inference_compile + return _aot_stage2b_compile_forward_or_inference( + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "~/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_compile.py", line 2843, in _aot_stage2b_compile_forward_or_inference + compiled_fw_func = compiler(fw_module, adjusted_flat_args) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/pytorch/tests/../omega_torch/__init__.py", line 330, in fw + return _lower(g, inputs) + ^^^^^^^^^^^^^^^^^ + File "/pytorch/tests/../omega_torch/__init__.py", line 288, in _lower + compiled.append((kind, n, kernel, load_unit(kernel, consts, len(ins) + 1), ins, + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/pytorch/tests/../omega_torch/__init__.py", line 134, in load_unit + raise OmegaRefused("src/native.om refused unit %s (exit %d)" % (kernel, rc)) +torch._dynamo.exc.BackendCompilerFailed: backend='omega' raised: +OmegaRefused: src/native.om refused unit mm (exit 110) + +Set TORCHDYNAMO_VERBOSE=1 for the internal stack trace (please do this especially if you're reporting a bug to PyTorch). For even more developer context, set TORCH_LOGS="+dynamo" + + +====================================================================== +FAIL: test_const_f32_bound (pytorch.tests.test_omega_torch.Binding.test_const_f32_bound) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/pytorch/tests/test_omega_torch.py", line 232, in test_const_f32_bound + self.assertEqual(rc, 0) +AssertionError: 110 != 0 + +---------------------------------------------------------------------- +Ran 4 tests in 0.141s + +FAILED (failures=1, errors=1) diff --git a/evidence/omega-torch-m1/tests-fresh-fix.log b/evidence/omega-torch-m1/tests-fresh-fix.log new file mode 100644 index 0000000..f7080e9 --- /dev/null +++ b/evidence/omega-torch-m1/tests-fresh-fix.log @@ -0,0 +1,27 @@ +test_const_f32_bound (pytorch.tests.test_omega_torch.Binding.test_const_f32_bound) ... ok +test_const_not_ulong_refused (pytorch.tests.test_omega_torch.Binding.test_const_not_ulong_refused) ... ok +test_f64_array_refused (pytorch.tests.test_omega_torch.Binding.test_f64_array_refused) ... ok +test_array_limit_refused (pytorch.tests.test_omega_torch.FailClosed.test_array_limit_refused) ... ok +test_broadcast_add_refused (pytorch.tests.test_omega_torch.FailClosed.test_broadcast_add_refused) ... ok +test_explicit_fallback_is_counted (pytorch.tests.test_omega_torch.FailClosed.test_explicit_fallback_is_counted) ... ok +test_unsupported_op_raises_and_runs_nothing (pytorch.tests.test_omega_torch.FailClosed.test_unsupported_op_raises_and_runs_nothing) ... ok +test_wrong_length_status_32 (pytorch.tests.test_omega_torch.FailClosed.test_wrong_length_status_32) ... ok +test_mlp_parity_and_all_omega (pytorch.tests.test_omega_torch.Model.test_mlp_parity_and_all_omega) ... ok +test_mutant_linear_caught (pytorch.tests.test_omega_torch.NegativeControl.test_mutant_linear_caught) ... ok +test_mutant_relu_caught (pytorch.tests.test_omega_torch.NegativeControl.test_mutant_relu_caught) ... ok +test_mutant_softmax_caught (pytorch.tests.test_omega_torch.NegativeControl.test_mutant_softmax_caught) ... ok +test_add (pytorch.tests.test_omega_torch.Ops.test_add) ... ok +test_addmm (pytorch.tests.test_omega_torch.Ops.test_addmm) ... ok +test_linear (pytorch.tests.test_omega_torch.Ops.test_linear) ... ok +test_mm (pytorch.tests.test_omega_torch.Ops.test_mm) ... ok +test_mm_exact_integers (pytorch.tests.test_omega_torch.Ops.test_mm_exact_integers) ... ok +test_permute (pytorch.tests.test_omega_torch.Ops.test_permute) ... ok +test_relu (pytorch.tests.test_omega_torch.Ops.test_relu) ... ok +test_softmax (pytorch.tests.test_omega_torch.Ops.test_softmax) ... ok +test_softmax_two_ulp_of_float64 (pytorch.tests.test_omega_torch.Ops.test_softmax_two_ulp_of_float64) ... ok +test_softmax_wolfram (pytorch.tests.test_omega_torch.Ops.test_softmax_wolfram) ... ok + +---------------------------------------------------------------------- +Ran 22 tests in 2.235s + +OK diff --git a/evidence/omega-torch-m1/tests-m1.log b/evidence/omega-torch-m1/tests-m1.log new file mode 100644 index 0000000..a0c6b2a --- /dev/null +++ b/evidence/omega-torch-m1/tests-m1.log @@ -0,0 +1,27 @@ +test_const_f32_bound (pytorch.tests.test_omega_torch.Binding.test_const_f32_bound) ... ok +test_const_not_ulong_refused (pytorch.tests.test_omega_torch.Binding.test_const_not_ulong_refused) ... ok +test_f64_array_refused (pytorch.tests.test_omega_torch.Binding.test_f64_array_refused) ... ok +test_array_limit_refused (pytorch.tests.test_omega_torch.FailClosed.test_array_limit_refused) ... ok +test_broadcast_add_refused (pytorch.tests.test_omega_torch.FailClosed.test_broadcast_add_refused) ... ok +test_explicit_fallback_is_counted (pytorch.tests.test_omega_torch.FailClosed.test_explicit_fallback_is_counted) ... ok +test_unsupported_op_raises_and_runs_nothing (pytorch.tests.test_omega_torch.FailClosed.test_unsupported_op_raises_and_runs_nothing) ... ok +test_wrong_length_status_32 (pytorch.tests.test_omega_torch.FailClosed.test_wrong_length_status_32) ... ok +test_mlp_parity_and_all_omega (pytorch.tests.test_omega_torch.Model.test_mlp_parity_and_all_omega) ... ok +test_mutant_linear_caught (pytorch.tests.test_omega_torch.NegativeControl.test_mutant_linear_caught) ... ok +test_mutant_relu_caught (pytorch.tests.test_omega_torch.NegativeControl.test_mutant_relu_caught) ... ok +test_mutant_softmax_caught (pytorch.tests.test_omega_torch.NegativeControl.test_mutant_softmax_caught) ... ok +test_add (pytorch.tests.test_omega_torch.Ops.test_add) ... ok +test_addmm (pytorch.tests.test_omega_torch.Ops.test_addmm) ... ok +test_linear (pytorch.tests.test_omega_torch.Ops.test_linear) ... ok +test_mm (pytorch.tests.test_omega_torch.Ops.test_mm) ... ok +test_mm_exact_integers (pytorch.tests.test_omega_torch.Ops.test_mm_exact_integers) ... ok +test_permute (pytorch.tests.test_omega_torch.Ops.test_permute) ... ok +test_relu (pytorch.tests.test_omega_torch.Ops.test_relu) ... ok +test_softmax (pytorch.tests.test_omega_torch.Ops.test_softmax) ... ok +test_softmax_two_ulp_of_float64 (pytorch.tests.test_omega_torch.Ops.test_softmax_two_ulp_of_float64) ... ok +test_softmax_wolfram (pytorch.tests.test_omega_torch.Ops.test_softmax_wolfram) ... ok + +---------------------------------------------------------------------- +Ran 22 tests in 7.530s + +OK diff --git a/evidence/omega-torch-m1/tests-merge-main-7af4d11.log b/evidence/omega-torch-m1/tests-merge-main-7af4d11.log new file mode 100644 index 0000000..9aecd83 --- /dev/null +++ b/evidence/omega-torch-m1/tests-merge-main-7af4d11.log @@ -0,0 +1,27 @@ +test_const_f32_bound (pytorch.tests.test_omega_torch.Binding.test_const_f32_bound) ... ok +test_const_not_ulong_refused (pytorch.tests.test_omega_torch.Binding.test_const_not_ulong_refused) ... ok +test_f64_array_refused (pytorch.tests.test_omega_torch.Binding.test_f64_array_refused) ... ok +test_array_limit_refused (pytorch.tests.test_omega_torch.FailClosed.test_array_limit_refused) ... ok +test_broadcast_add_refused (pytorch.tests.test_omega_torch.FailClosed.test_broadcast_add_refused) ... ok +test_explicit_fallback_is_counted (pytorch.tests.test_omega_torch.FailClosed.test_explicit_fallback_is_counted) ... ok +test_unsupported_op_raises_and_runs_nothing (pytorch.tests.test_omega_torch.FailClosed.test_unsupported_op_raises_and_runs_nothing) ... ok +test_wrong_length_status_32 (pytorch.tests.test_omega_torch.FailClosed.test_wrong_length_status_32) ... ok +test_mlp_parity_and_all_omega (pytorch.tests.test_omega_torch.Model.test_mlp_parity_and_all_omega) ... ok +test_mutant_linear_caught (pytorch.tests.test_omega_torch.NegativeControl.test_mutant_linear_caught) ... ok +test_mutant_relu_caught (pytorch.tests.test_omega_torch.NegativeControl.test_mutant_relu_caught) ... ok +test_mutant_softmax_caught (pytorch.tests.test_omega_torch.NegativeControl.test_mutant_softmax_caught) ... ok +test_add (pytorch.tests.test_omega_torch.Ops.test_add) ... ok +test_addmm (pytorch.tests.test_omega_torch.Ops.test_addmm) ... ok +test_linear (pytorch.tests.test_omega_torch.Ops.test_linear) ... ok +test_mm (pytorch.tests.test_omega_torch.Ops.test_mm) ... ok +test_mm_exact_integers (pytorch.tests.test_omega_torch.Ops.test_mm_exact_integers) ... ok +test_permute (pytorch.tests.test_omega_torch.Ops.test_permute) ... ok +test_relu (pytorch.tests.test_omega_torch.Ops.test_relu) ... ok +test_softmax (pytorch.tests.test_omega_torch.Ops.test_softmax) ... ok +test_softmax_two_ulp_of_float64 (pytorch.tests.test_omega_torch.Ops.test_softmax_two_ulp_of_float64) ... ok +test_softmax_wolfram (pytorch.tests.test_omega_torch.Ops.test_softmax_wolfram) ... ok + +---------------------------------------------------------------------- +Ran 22 tests in 2.345s + +OK diff --git a/evidence/omega-torch-m1/timings-low.json b/evidence/omega-torch-m1/timings-low.json new file mode 100644 index 0000000..23f9bda --- /dev/null +++ b/evidence/omega-torch-m1/timings-low.json @@ -0,0 +1,157 @@ +{ + "loadavg_before": "7.16 11.23 12.83 11/3421 207411", + "affinity": [ + 8 + ], + "torch_threads": 1, + "OMP_NUM_THREADS": "1", + "torch": "2.14.0+cu130", + "python": "3.12.3", + "batch": 64, + "rounds": 30, + "parity_max_abs": 4.470348358154297e-08, + "stats": { + "graphs": 0, + "omega_calls": 180, + "eager_fallback_calls": 0, + "units_built": 0, + "per_op": { + "linear": 60, + "relu": 30, + "eadd": 30, + "mm": 30, + "softmax": 30 + } + }, + "eager_ns": [ + 242898, + 261634, + 141969, + 211538, + 140449, + 210577, + 141985, + 303826, + 149105, + 251442, + 143073, + 248370, + 139554, + 187617, + 139217, + 212418, + 145746, + 230498, + 141009, + 220946, + 141905, + 336387, + 146081, + 265522, + 144402, + 219650, + 145058, + 210849, + 138498, + 227442 + ], + "omega_ns": [ + 13324158, + 13129196, + 13137147, + 13092219, + 13114028, + 13078380, + 13103803, + 13180268, + 13144780, + 13078155, + 13089676, + 13069083, + 13089179, + 13061627, + 13083516, + 13067083, + 13101259, + 13070108, + 13110092, + 13081099, + 13114139, + 13415791, + 13181164, + 13088699, + 13140188, + 13084971, + 13091147, + 13061275, + 13101995, + 13077691 + ], + "eager_loadavg": [ + "7.16 11.23 12.83 12/3411 207923", + "7.16 11.23 12.83 10/3411 207983", + "7.16 11.23 12.83 13/3411 207983", + "7.16 11.23 12.83 10/3410 208041", + "7.16 11.23 12.83 7/3411 208042", + "7.16 11.23 12.83 6/3410 208088", + "7.16 11.23 12.83 9/3409 208088", + "7.16 11.23 12.83 11/3409 208139", + "7.16 11.23 12.83 9/3408 208139", + "7.16 11.23 12.83 9/3408 208186", + "7.16 11.23 12.83 8/3408 208186", + "7.16 11.23 12.83 8/3410 208236", + "7.16 11.23 12.83 9/3410 208236", + "7.16 11.23 12.83 8/3410 208288", + "7.16 11.23 12.83 6/3410 208288", + "7.16 11.23 12.83 10/3409 208341", + "7.16 11.23 12.83 8/3410 208342", + "7.16 11.23 12.83 10/3410 208419", + "7.16 11.23 12.83 11/3408 208421", + "7.16 11.23 12.83 9/3409 208501", + "7.16 11.23 12.83 10/3409 208502", + "7.16 11.23 12.83 12/3409 208561", + "7.16 11.23 12.83 9/3410 208563", + "7.16 11.23 12.83 13/3419 208623", + "7.16 11.23 12.83 11/3420 208624", + "7.16 11.23 12.83 8/3422 208675", + "7.16 11.23 12.83 6/3424 208677", + "7.16 11.23 12.83 5/3423 208723", + "7.16 11.23 12.83 9/3424 208724", + "7.16 11.23 12.83 9/3429 208779" + ], + "omega_loadavg": [ + "7.16 11.23 12.83 11/3411 207924", + "7.16 11.23 12.83 13/3411 207951", + "7.16 11.23 12.83 13/3408 207983", + "7.16 11.23 12.83 6/3410 208016", + "7.16 11.23 12.83 8/3411 208042", + "7.16 11.23 12.83 7/3411 208065", + "7.16 11.23 12.83 6/3409 208088", + "7.16 11.23 12.83 10/3409 208115", + "7.16 11.23 12.83 10/3408 208139", + "7.16 11.23 12.83 8/3410 208163", + "7.16 11.23 12.83 8/3409 208187", + "7.16 11.23 12.83 8/3410 208211", + "7.16 11.23 12.83 9/3408 208236", + "7.16 11.23 12.83 8/3408 208261", + "7.16 11.23 12.83 5/3410 208288", + "7.16 11.23 12.83 6/3411 208315", + "7.16 11.23 12.83 9/3410 208342", + "7.16 11.23 12.83 9/3413 208377", + "7.16 11.23 12.83 11/3409 208422", + "7.16 11.23 12.83 14/3412 208465", + "7.16 11.23 12.83 9/3408 208502", + "7.16 11.23 12.83 12/3412 208533", + "7.16 11.23 12.83 9/3411 208564", + "7.16 11.23 12.83 11/3415 208595", + "7.16 11.23 12.83 12/3420 208624", + "7.16 11.23 12.83 9/3424 208652", + "7.16 11.23 12.83 6/3424 208677", + "7.16 11.23 12.83 9/3422 208700", + "7.16 11.23 12.83 9/3424 208724", + "7.16 11.23 12.83 12/3427 208752" + ], + "loadavg_after": "7.16 11.23 12.83 9/3430 208780", + "max_load1": 7.16, + "label": "load1 <= 8 for every sample" +} \ No newline at end of file diff --git a/evidence/omega-torch-m1/timings-m1.json b/evidence/omega-torch-m1/timings-m1.json new file mode 100644 index 0000000..d3ed262 --- /dev/null +++ b/evidence/omega-torch-m1/timings-m1.json @@ -0,0 +1,157 @@ +{ + "loadavg_before": "38.45 27.66 21.98 26/3765 2747533", + "affinity": [ + 17 + ], + "torch_threads": 1, + "OMP_NUM_THREADS": "1", + "torch": "2.14.0+cu130", + "python": "3.12.3", + "batch": 64, + "rounds": 30, + "parity_max_abs": 4.470348358154297e-08, + "stats": { + "graphs": 0, + "omega_calls": 180, + "eager_fallback_calls": 0, + "units_built": 0, + "per_op": { + "linear": 60, + "relu": 30, + "eadd": 30, + "mm": 30, + "softmax": 30 + } + }, + "eager_ns": [ + 339394, + 247137, + 155489, + 212194, + 156224, + 207409, + 140865, + 244753, + 140337, + 512994, + 171985, + 513587, + 153281, + 380610, + 147872, + 257170, + 139616, + 371682, + 152960, + 383233, + 140464, + 254034, + 142001, + 366738, + 145185, + 345890, + 137553, + 346865, + 142097, + 232513 + ], + "omega_ns": [ + 13900007, + 13228100, + 13201779, + 13119795, + 13295508, + 13169539, + 13223683, + 13165652, + 13304932, + 13236019, + 13228500, + 14662299, + 13255731, + 13094946, + 13155171, + 13081955, + 13180196, + 13186452, + 13217476, + 13557253, + 13274884, + 13123875, + 13773510, + 13231571, + 13221108, + 13165427, + 13193635, + 13096387, + 13192836, + 13133155 + ], + "eager_loadavg": [ + "38.45 27.66 21.98 31/3766 2747734", + "38.45 27.66 21.98 24/3770 2747744", + "38.45 27.66 21.98 27/3770 2747744", + "38.45 27.66 21.98 24/3775 2747751", + "38.45 27.66 21.98 27/3775 2747751", + "38.45 27.66 21.98 29/3775 2747751", + "38.45 27.66 21.98 28/3775 2747751", + "38.45 27.66 21.98 28/3774 2747762", + "38.45 27.66 21.98 30/3773 2747762", + "38.45 27.66 21.98 30/3774 2747783", + "38.45 27.66 21.98 30/3774 2747783", + "38.45 27.66 21.98 31/3776 2747785", + "38.45 27.66 21.98 30/3776 2747785", + "38.45 27.66 21.98 27/3776 2747786", + "38.45 27.66 21.98 26/3776 2747786", + "38.45 27.66 21.98 30/3776 2747787", + "38.45 27.66 21.98 29/3776 2747787", + "38.45 27.66 21.98 27/3776 2747788", + "38.45 27.66 21.98 27/3776 2747788", + "38.45 27.66 21.98 27/3781 2747805", + "38.45 27.66 21.98 27/3781 2747805", + "38.45 27.66 21.98 26/3804 2747835", + "38.45 27.66 21.98 26/3804 2747835", + "38.45 27.66 21.98 26/3804 2747840", + "38.45 27.66 21.98 30/3804 2747841", + "38.45 27.66 21.98 56/3826 2747877", + "38.45 27.66 21.98 46/3808 2747877", + "38.45 27.66 21.98 46/3797 2747878", + "38.45 27.66 21.98 47/3797 2747878", + "38.45 27.66 21.98 21/3776 2747890" + ], + "omega_loadavg": [ + "38.45 27.66 21.98 29/3766 2747734", + "38.45 27.66 21.98 27/3765 2747738", + "38.45 27.66 21.98 27/3770 2747744", + "38.45 27.66 21.98 25/3775 2747750", + "38.45 27.66 21.98 29/3775 2747751", + "38.45 27.66 21.98 26/3775 2747751", + "38.45 27.66 21.98 30/3775 2747751", + "38.45 27.66 21.98 28/3774 2747754", + "38.45 27.66 21.98 29/3773 2747762", + "38.45 27.66 21.98 29/3777 2747776", + "38.45 27.66 21.98 30/3774 2747783", + "38.45 27.66 21.98 28/3775 2747784", + "38.45 27.66 21.98 29/3776 2747785", + "38.45 27.66 21.98 26/3776 2747786", + "38.45 27.66 21.98 27/3776 2747786", + "38.45 27.66 21.98 30/3776 2747786", + "38.45 27.66 21.98 28/3776 2747787", + "38.45 27.66 21.98 26/3776 2747788", + "38.45 27.66 21.98 27/3776 2747788", + "38.45 27.66 21.98 32/3777 2747791", + "38.45 27.66 21.98 26/3781 2747805", + "38.45 27.66 21.98 29/3801 2747832", + "38.45 27.66 21.98 27/3804 2747835", + "38.45 27.66 21.98 30/3802 2747835", + "38.45 27.66 21.98 28/3804 2747841", + "38.45 27.66 21.98 45/3825 2747869", + "38.45 27.66 21.98 47/3807 2747877", + "38.45 27.66 21.98 38/3799 2747878", + "38.45 27.66 21.98 49/3797 2747878", + "38.45 27.66 21.98 22/3774 2747884" + ], + "loadavg_after": "38.45 27.66 21.98 21/3776 2747890", + "max_load1": 38.45, + "label": "taken under load (load1 > 8)" +} \ No newline at end of file diff --git a/pytorch/bench.py b/pytorch/bench.py new file mode 100644 index 0000000..8242a4d --- /dev/null +++ b/pytorch/bench.py @@ -0,0 +1,86 @@ +"""Paired, interleaved wall-clock timing of one MLP forward pass: eager PyTorch versus backend="omega". + +Run (both arms in the same process, on the same pinned core, one thread each): + CUDA_VISIBLE_DEVICES= OMP_NUM_THREADS=1 OMEGA_OMC= \ + taskset -c 17 python3 pytorch/bench.py --rounds 30 --out timings.json +Writes raw per-call nanoseconds for both arms, /proc/loadavg before every sample and before and after +the run, and labels the run "taken under load" when any sample saw load1 above 8. It computes no +statistics: summarise the raw numbers separately (the receipt names the tool used). +""" + +import argparse +import json +import os +import platform +import sys +import time + +import torch +import torch.nn as nn + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import omega_torch as ot # noqa: E402 + + +class MLP(nn.Module): + def __init__(self, d=256, h=64): + super().__init__() + self.l1 = nn.Linear(d, d) + self.l2 = nn.Linear(d, h) + self.p = nn.Parameter(torch.randn(h, h) / 8.0) + + def forward(self, x): + y = torch.relu(self.l1(x)) + x + return torch.softmax(torch.matmul(self.l2(y), self.p), dim=-1) + + +def loadavg(): + with open("/proc/loadavg") as f: + return f.read().strip() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--rounds", type=int, default=30) + ap.add_argument("--batch", type=int, default=64) + ap.add_argument("--out", required=True) + a = ap.parse_args() + threads = len(os.sched_getaffinity(0)) + torch.set_num_threads(threads) + rec = {"loadavg_before": loadavg(), "affinity": sorted(os.sched_getaffinity(0)), "torch_threads": threads, + "OMP_NUM_THREADS": os.environ.get("OMP_NUM_THREADS"), "torch": torch.__version__, + "python": platform.python_version(), "batch": a.batch, "rounds": a.rounds} + torch.manual_seed(0) + m = MLP().eval() + x = torch.randn(a.batch, 256) + with torch.no_grad(): + c = torch.compile(m, backend="omega", fullgraph=True, dynamic=False) + got, want = c(x), m(x) # compile and warm both arms + torch.testing.assert_close(got, want) + rec["parity_max_abs"] = (got - want).abs().max().item() + ot.reset_stats() + eager, omega, eager_load, omega_load = [], [], [], [] + for r in range(a.rounds): # interleaved, order alternating per round + arms = [(eager, eager_load, m), (omega, omega_load, c)] + if r % 2: + arms.reverse() + for sink, loads, f in arms: + loads.append(loadavg()) # /proc/loadavg read before each sample, outside the timed span + t0 = time.perf_counter_ns() + f(x) + sink.append(time.perf_counter_ns() - t0) + rec["stats"] = {k: v for k, v in ot.STATS.items()} + rec["eager_ns"], rec["omega_ns"] = eager, omega + rec["eager_loadavg"], rec["omega_loadavg"] = eager_load, omega_load + rec["loadavg_after"] = loadavg() + load1 = [float(s.split()[0]) for s in eager_load + omega_load] + rec["max_load1"] = max(load1) + rec["label"] = "taken under load (load1 > 8)" if max(load1) > 8 else "load1 <= 8 for every sample" + with open(a.out, "w") as f: + json.dump(rec, f, indent=1) + print(json.dumps({k: rec[k] for k in ("loadavg_before", "loadavg_after", "max_load1", "label", "affinity", + "torch_threads", "parity_max_abs", "stats")})) + + +if __name__ == "__main__": + main() diff --git a/pytorch/kernels/addmm.om b/pytorch/kernels/addmm.om new file mode 100644 index 0000000..6edbe73 --- /dev/null +++ b/pytorch/kernels/addmm.om @@ -0,0 +1,21 @@ +note addmm: o[M,N] = c[N] + a[M,K] @ b[K,N] (aten.addmm, beta 1, alpha 1, bias over rows), row-major +note f32. Each sum starts at the bias, is summed in f64 and rounded once to f32. +note The caller supplies const lines M K N MK KN MN before this text. +fn amdot c view f32 N a view f32 MK b view f32 KN i ulong j ulong to f64 +s = f64 get c j +ia = mul i K +rb = j +for k ulong K +s = add s mul f64 get a ia f64 get b rb +ia = add ia 1 +rb = add rb N +end +ret s +end +fn addmm c view f32 N a view f32 MK b view f32 KN o edit f32 MN to void +for i ulong M +for j ulong N +put o add mul i N j f32 amdot c a b i j +end +end +end diff --git a/pytorch/kernels/eadd.om b/pytorch/kernels/eadd.om new file mode 100644 index 0000000..f68c5c7 --- /dev/null +++ b/pytorch/kernels/eadd.om @@ -0,0 +1,7 @@ +note eadd: o = a + b element by element (aten.add.Tensor, alpha 1, equal shapes), one f32 rounding. +note The caller supplies the const line L (the element count) before this text. +fn eadd a view f32 L b view f32 L o edit f32 L to void +for i ulong L +put o i add get a i get b i +end +end diff --git a/pytorch/kernels/linear.om b/pytorch/kernels/linear.om new file mode 100644 index 0000000..f7d5231 --- /dev/null +++ b/pytorch/kernels/linear.om @@ -0,0 +1,21 @@ +note linear: o[M,N] = c[N] + a[M,K] @ w[N,K]^T, the addmm of a torch.nn.Linear whose weight transpose +note (aten.permute [1,0]) feeds only this addmm; w is read in place, nothing is copied. Each sum starts +note at the bias, is summed in f64 and rounded once to f32. Consts M K N MK NK MN come first. +fn lindot c view f32 N a view f32 MK w view f32 NK i ulong j ulong to f64 +s = f64 get c j +ia = mul i K +iw = mul j K +for k ulong K +s = add s mul f64 get a ia f64 get w iw +ia = add ia 1 +iw = add iw 1 +end +ret s +end +fn linear c view f32 N a view f32 MK w view f32 NK o edit f32 MN to void +for i ulong M +for j ulong N +put o add mul i N j f32 lindot c a w i j +end +end +end diff --git a/pytorch/kernels/mm.om b/pytorch/kernels/mm.om new file mode 100644 index 0000000..2ba02b4 --- /dev/null +++ b/pytorch/kernels/mm.om @@ -0,0 +1,20 @@ +note mm: o[M,N] = a[M,K] @ b[K,N] (aten.mm), row-major f32. Each dot product is summed in f64 and +note rounded once to f32. The caller supplies const lines M K N MK KN MN before this text. +fn mmdot a view f32 MK b view f32 KN i ulong j ulong to f64 +s = 0.0f64 +ia = mul i K +rb = j +for k ulong K +s = add s mul f64 get a ia f64 get b rb +ia = add ia 1 +rb = add rb N +end +ret s +end +fn mm a view f32 MK b view f32 KN o edit f32 MN to void +for i ulong M +for j ulong N +put o add mul i N j f32 mmdot a b i j +end +end +end diff --git a/pytorch/kernels/relu.om b/pytorch/kernels/relu.om new file mode 100644 index 0000000..ec84ff8 --- /dev/null +++ b/pytorch/kernels/relu.om @@ -0,0 +1,12 @@ +note relu: o = x where x is not below 0.0, else 0.0 (aten.relu); NaN is kept, as aten.relu keeps it. +note The caller supplies the const line L (the element count) before this text. +fn relu x view f32 L o edit f32 L to void +for i ulong L +v = get x i +if lt v 0.0f32 +put o i 0.0f32 +else +put o i v +end +end +end diff --git a/pytorch/kernels/softmax.om b/pytorch/kernels/softmax.om new file mode 100644 index 0000000..5ec7d05 --- /dev/null +++ b/pytorch/kernels/softmax.om @@ -0,0 +1,72 @@ +note softmax: o[R,C] = exp(x - rowmax) / rowsum over the last dimension (aten._softmax, dim -1, +note half_to_float false), row-major f32. Exponentials and sums are f64, each output rounded once to +note f32. A row holding NaN gives NaN. The caller supplies const lines R C RC before this text. +note expd: e^x in f64. x = k ln2 + r with k the nearest integer to x/ln2 and |r| <= ln2/2; e^r by the +note degree-13 Taylor polynomial in Horner form (s = 1 + r s / n, n = 13 .. 1), whose truncation is +note below 5.9e-18 relative (Wolfram: (Log[2]/2)^14/14! Exp[Log[2]/2] = 5.85e-18); then times 2^k +note built from its exponent bits. Below -746 the result is 0 (e^x < 2^-1075, Wolfram: Log[2^-1074] = +note -744.44); above 709.79 it is infinity (Log[$MaxMachineNumber] = 709.7827). +fn expd x f64 to f64 +if ne x x +ret x +end +if lt x -746.0f64 +ret 0.0f64 +end +if gt x 709.79f64 +ret div 1.0f64 0.0f64 +end +kf = mul x 1.442695040888963387f64 +ki = long kf +fr = sub kf f64 ki +if gt fr 0.5f64 +ki = add ki 1 +end +if lt fr -0.5f64 +ki = sub ki 1 +end +r = sub x mul f64 ki 0.6931471805599453094f64 +s = 1.0f64 +for j ulong 13 +n = f64 sub 13 j +s = add 1.0f64 div mul r s n +end +sc = 1.0f64 +if lt ki -1000 +sc = bitcast f64 shl ulong 423 52 +ki = add ki 600 +end +if gt ki 1000 +sc = bitcast f64 shl ulong 1623 52 +ki = sub ki 600 +end +e = bitcast f64 shl ulong add ki 1023 52 +ret mul mul s e sc +end +note smrow: softmax of row i into o, through the f64 scratch row t. +fn smrow x view f32 RC o edit f32 RC t edit f64 C i ulong to void +b = mul i C +m = get x b +for j ulong C +v = get x add b j +if gt v m +m = v +end +end +mf = f64 m +s = 0.0f64 +for j ulong C +e = expd sub f64 get x add b j mf +put t j e +s = add s e +end +for j ulong C +put o add b j f32 div get t j s +end +end +fn softmax x view f32 RC o edit f32 RC to void +t = new f64 C 0.0f64 +for i ulong R +smrow x o t i +end +end diff --git a/pytorch/kernels/tr.om b/pytorch/kernels/tr.om new file mode 100644 index 0000000..d59d27b --- /dev/null +++ b/pytorch/kernels/tr.om @@ -0,0 +1,9 @@ +note tr: o[C,R] = x[R,C] transposed (aten.permute with dims [1,0]) into a new row-major array. +note The caller supplies const lines R C RC before this text. +fn tr x view f32 RC o edit f32 RC to void +for i ulong R +for j ulong C +put o add mul j R i get x add mul i C j +end +end +end diff --git a/pytorch/omega_torch/__init__.py b/pytorch/omega_torch/__init__.py new file mode 100644 index 0000000..17027b5 --- /dev/null +++ b/pytorch/omega_torch/__init__.py @@ -0,0 +1,333 @@ +"""torch.compile(model, backend="omega"): core-ATen graphs run on Omega-generated AArch64 kernels. + +Interim Python glue (migration step, not the destination). This module only registers the backend, +walks the FX graph, allocates output tensors and calls compiled Omega units through the omega-bridge +native call ABI v1 (docs/NATIVE-ABI.md). It never computes a tensor value: every value an output holds +was written by machine code the seeded Omega compiler produced from pytorch/kernels/*.om. + +Successor (named in docs/OMEGA-TORCH.md): the graph walk, shape specialisation and op dispatch move to +an Omega unit behind the same bridge C ABI, driven from a PrivateUse1 "omega" device, so the Python +side shrinks to the device registration PyTorch itself requires. + +Fail closed: an op outside SUPPORTED raises OmegaRefused at compile time, listing every refused node. +An eager fallback happens only for ops the caller names in OMEGA_TORCH_FALLBACK (or set_fallback()), +and every such call is counted in STATS["eager_fallback_calls"]. +""" + +import ctypes +import hashlib +import os +import subprocess +import tempfile +import threading + +import torch +from torch._dynamo import register_backend +from torch._functorch.aot_autograd import aot_module_simplified +from torch._decomp import core_aten_decompositions + +aten = torch.ops.aten + +# omega-mv main 369dbc96daa1684db2d7c2c7085bbf16b3fd77ee, seed/out/omc as committed (not rebuilt). +OMC_SHA256 = "2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f" + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +KERNEL_DIR = os.environ.get("OMEGA_TORCH_KERNELS", os.path.join(ROOT, "pytorch", "kernels")) +CACHE = os.environ.get("OMEGA_TORCH_CACHE", os.path.join(ROOT, "build", "torch")) + +STATS = {"graphs": 0, "omega_calls": 0, "eager_fallback_calls": 0, "units_built": 0, "per_op": {}} +_FALLBACK = set(filter(None, os.environ.get("OMEGA_TORCH_FALLBACK", "").split(","))) +_LOCK = threading.Lock() +_LIBS = {} +_NATIVE = None + +STATUS = {1: "overflow", 2: "divide by zero", 3: "bounds", 4: "loop bound", 5: "conversion", + 6: "resource", 7: "shift", 32: "foreign argument refused", 33: "reentry", + 34: "runtime entry not provided", 35: "no stack"} + + +class OmegaRefused(RuntimeError): + """The graph holds work the Omega backend does not implement. Nothing ran.""" + + +class OmegaCallError(RuntimeError): + """A compiled Omega unit returned a nonzero status (trap or refused argument).""" + + +def set_fallback(ops): + """Name the ops (e.g. "aten.tanh.default") that may run in eager PyTorch. Each call is counted.""" + _FALLBACK.clear() + _FALLBACK.update(ops) + + +def reset_stats(): + STATS.update(graphs=0, omega_calls=0, eager_fallback_calls=0, per_op={}) + + +def _sha(path): + with open(path, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def _omc(): + path = os.environ.get("OMEGA_OMC") + if not path: + raise OmegaRefused("set OMEGA_OMC to omega-mv seed/out/omc (sha256 %s)" % OMC_SHA256) + got = _sha(path) + if got != OMC_SHA256: + raise OmegaRefused("omc sha256 %s is not the pinned %s" % (got, OMC_SHA256)) + return path + + +def _compile_om(src, out): + with open(out, "wb") as o, tempfile.TemporaryFile() as err: + rc = subprocess.run([_omc()], input=src, stdout=o, stderr=err).returncode + err.seek(0) + msg = err.read().decode(errors="replace").strip() + if rc != 0 or msg: + os.unlink(out) + raise OmegaRefused("omc refused the unit (rc=%d): %s" % (rc, msg)) + + +def _native(): + global _NATIVE + if _NATIVE is None: + os.makedirs(CACHE, exist_ok=True) + path = os.path.join(CACHE, "native-%s" % OMC_SHA256[:12]) + with open(os.path.join(ROOT, "src", "native.om"), "rb") as f: + _compile_om(f.read(), path) + os.chmod(path, 0o700) + _NATIVE = path + return _NATIVE + + +def unit_source(kernel, consts): + """The unit text: one "const NAME ulong V" line per shape constant, then the kernel file.""" + head = "".join("const %s ulong %d\n" % (k, v) for k, v in consts) + with open(os.path.join(KERNEL_DIR, kernel + ".om"), "rb") as f: + return head.encode() + f.read() + + +def load_unit(kernel, consts, nargs): + """Compile kernel specialised to consts, bind it with src/native.om, build and load the library. + Returns the ctypes function omega_(uint64_t *result, (ptr, len) * nargs).""" + src = unit_source(kernel, consts) + with open(os.path.join(ROOT, "src", "native.om"), "rb") as f: + key = hashlib.sha256(src + OMC_SHA256.encode() + f.read()).hexdigest()[:24] + with _LOCK: + if key in _LIBS: + return _LIBS[key] + d = os.path.join(CACHE, key) + os.makedirs(d, exist_ok=True) + so = os.path.join(d, "lib%s.so" % kernel) + if not os.path.exists(so): + binp = os.path.join(d, kernel + ".bin") + _compile_om(src, binp) + with open(binp, "rb") as f: + code = f.read() + frame = src + b"\0" + b"%08d" % len(code) + code + cfile = os.path.join(d, "binding.c") + with open(cfile, "wb") as o: + rc = subprocess.run([_native(), "c"], input=frame, stdout=o, stderr=subprocess.DEVNULL).returncode + if rc != 0: + raise OmegaRefused("src/native.om refused unit %s (exit %d)" % (kernel, rc)) + tmp = so + ".tmp" + subprocess.run(["cc", "-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror", "-fPIC", "-shared", + "-o", tmp, cfile], check=True) + os.replace(tmp, so) + STATS["units_built"] += 1 + fn = getattr(ctypes.CDLL(so), "omega_" + kernel) + fn.argtypes = [ctypes.POINTER(ctypes.c_uint64)] + [ctypes.c_void_p, ctypes.c_uint64] * nargs + fn.restype = ctypes.c_uint32 + _LIBS[key] = fn + return fn + + +def call_unit(fn, name, tensors): + """Call a bound unit on f32 CPU tensors (borrowed for the call). Raises on any nonzero status.""" + args = [] + for t in tensors: + args += [t.data_ptr(), t.numel()] + res = ctypes.c_uint64(0) + st = fn(ctypes.byref(res), *args) + if st != 0: + raise OmegaCallError("omega_%s returned status %d (%s)" % (name, st, STATUS.get(st, "trap"))) + STATS["omega_calls"] += 1 + STATS["per_op"][name] = STATS["per_op"].get(name, 0) + 1 + + +# ---- graph lowering ----------------------------------------------------------------------------- + +SUPPORTED = ("aten.mm.default", "aten.addmm.default", "aten.permute.default", "aten.add.Tensor", + "aten.relu.default", "aten._softmax.default") + +# Language limits at the pinned omc (OMEGESE 9.4): an array holds 1 .. 16777216 elements, and a +# function's local arrays total at most 4 MiB (softmax keeps one f64 row: 8 bytes per column). +OM_MAX_ARRAY = 16777216 +OM_MAX_LOCAL_BYTES = 4 << 20 + + +def _meta(n): + v = n.meta.get("val") if hasattr(n, "meta") else None + return v + + +def _static_shape(v): + out = [] + for s in v.shape: + if not isinstance(s, int): + return None + out.append(s) + return out + + +def _check_tensor(v, why): + if not isinstance(v, torch.Tensor): + return why + ": not a tensor" + if v.dtype != torch.float32: + return why + ": dtype %s (only float32)" % v.dtype + if v.device.type != "cpu": + return why + ": device %s (only cpu)" % v.device + if _static_shape(v) is None: + return why + ": symbolic shape %s (compile with dynamic=False)" % (tuple(v.shape),) + if any(s == 0 for s in v.shape): + return why + ": empty tensor" + if v.numel() > OM_MAX_ARRAY: + return why + ": %d elements, above the Omega array limit %d (OMEGESE 9.4)" % (v.numel(), OM_MAX_ARRAY) + return None + + +def _plan_node(n, users): + """Return (kernel, consts, input nodes) for n, or a refusal string.""" + t = str(n.target) + ins = [a for a in n.args if isinstance(a, torch.fx.Node)] + for a in ins + [n]: + bad = _check_tensor(_meta(a), "%s %s" % (t, a.name)) + if bad: + return bad + sh = lambda a: _static_shape(_meta(a)) + if n.kwargs: + return "%s: keyword arguments %s not supported" % (t, dict(n.kwargs)) + if t == "aten.mm.default": + a, b = n.args + (M, K), (K2, N) = sh(a), sh(b) + return ("mm", [("M", M), ("K", K), ("N", N), ("MK", M * K), ("KN", K * N), ("MN", M * N)], [a, b]) + if t == "aten.addmm.default": + if len(n.args) != 3: + return "aten.addmm: beta/alpha other than 1 not supported" + c, a, b = n.args + if len(sh(a)) != 2 or len(sh(b)) != 2: + return "aten.addmm: operands must be 2-D" + (M, K), (K2, N) = sh(a), sh(b) + if sh(c) != [N]: + return "aten.addmm: bias shape %s (only a 1-D bias of length N=%d)" % (sh(c), N) + cs = [("M", M), ("K", K), ("N", N), ("MK", M * K)] + p = b + if p.op == "call_function" and str(p.target) == "aten.permute.default" and list(p.args[1]) == [1, 0] \ + and len(users[p]) == 1: + # nn.Linear: read the [N,K] weight in place instead of materialising its transpose. + return ("linear", cs + [("NK", N * K), ("MN", M * N)], [c, a, p.args[0]]) + return ("addmm", cs + [("KN", K * N), ("MN", M * N)], [c, a, b]) + if t == "aten.permute.default": + x, dims = n.args + if len(sh(x)) != 2 or list(dims) != [1, 0]: + return "aten.permute: only 2-D [1, 0] (got dims %s on shape %s)" % (list(dims), sh(x)) + R, C = sh(x) + return ("tr", [("R", R), ("C", C), ("RC", R * C)], [x]) + if t == "aten.add.Tensor": + if len(n.args) != 2 or len(ins) != 2: + return "aten.add.Tensor: only tensor + tensor with alpha 1" + a, b = n.args + if sh(a) != sh(b): + return "aten.add.Tensor: broadcasting %s + %s not supported" % (sh(a), sh(b)) + return ("eadd", [("L", _meta(a).numel())], [a, b]) + if t == "aten.relu.default": + (x,) = n.args + return ("relu", [("L", _meta(x).numel())], [x]) + if t == "aten._softmax.default": + x, dim, half = n.args + r = len(sh(x)) + if half or (dim % r) != r - 1 or r != 2: + return "aten._softmax: only 2-D over the last dim, half_to_float False" + R, C = sh(x) + if 8 * C > OM_MAX_LOCAL_BYTES: + return "aten._softmax: row of %d columns exceeds the 4 MiB local-array limit" % C + return ("softmax", [("R", R), ("C", C), ("RC", R * C)], [x]) + return "%s: no Omega kernel" % t + + +def _lower(gm, example_inputs): + g = gm.graph + users = {n: list(n.users) for n in g.nodes} + steps, refused, fused = [], [], set() + for n in g.nodes: + if n.op in ("placeholder", "output"): + continue + if n.op != "call_function": + refused.append("%s (%s): only call_function nodes" % (n.name, n.op)) + continue + t = str(n.target) + p = _plan_node(n, users) if t in SUPPORTED else "%s: no Omega kernel" % t + if isinstance(p, tuple): + if p[0] == "linear": + fused.add(n.args[2]) + steps.append(("omega", n, p)) + elif t in _FALLBACK: + steps.append(("eager", n, None)) + else: + refused.append("%s: %s" % (n.name, p)) + steps = [s for s in steps if s[1] not in fused or len(users[s[1]]) != 1] + if refused: + raise OmegaRefused("Omega backend refuses this graph (nothing ran; no eager fallback):\n " + + "\n ".join(refused)) + compiled = [] + for kind, n, p in steps: + if kind == "omega": + kernel, consts, ins = p + compiled.append((kind, n, kernel, load_unit(kernel, consts, len(ins) + 1), ins, + _static_shape(_meta(n)))) + else: + compiled.append((kind, n, None, None, None, None)) + placeholders = [n for n in g.nodes if n.op == "placeholder"] + (out_node,) = [n for n in g.nodes if n.op == "output"] + live_steps = [s for s in compiled if s[1] not in fused] + STATS["graphs"] += 1 + + def run(*args): + env = {} + for ph, a in zip(placeholders, args): + if isinstance(a, torch.Tensor) and not a.is_contiguous(): + raise OmegaRefused("input %s is not contiguous; Omega kernels read row-major storage" % ph.name) + env[ph] = a + for kind, n, kernel, fn, ins, shape in live_steps: + if kind == "omega": + xs = [env[a] for a in ins] + o = torch.empty(shape, dtype=torch.float32) + call_unit(fn, kernel, xs + [o]) + env[n] = o + else: + STATS["eager_fallback_calls"] += 1 + a = torch.fx.node.map_arg(n.args, lambda x: env[x]) + k = torch.fx.node.map_arg(n.kwargs, lambda x: env[x]) + env[n] = n.target(*a, **k) + return tuple(torch.fx.node.map_arg(out_node.args[0], lambda x: env[x])) + + run._omega_steps = [(s[0], s[2] or str(s[1].target)) for s in live_steps] + return run + + +@register_backend +def omega(gm, example_inputs): + """torch.compile backend "omega": inference only, float32 CPU, static shapes.""" + if torch.is_grad_enabled() and any(getattr(x, "requires_grad", False) for x in example_inputs): + raise OmegaRefused("autograd is not supported by the Omega backend (milestone 1); " + "run the compiled model under torch.no_grad()") + if torch.cuda.is_available(): + raise OmegaRefused("a CUDA device is visible; milestone 1 is CPU-only (set CUDA_VISIBLE_DEVICES=)") + + def fw(g, inputs): + return _lower(g, inputs) + + return aot_module_simplified(gm, example_inputs, fw_compiler=fw, + decompositions=core_aten_decompositions()) diff --git a/pytorch/tests/test_omega_torch.py b/pytorch/tests/test_omega_torch.py new file mode 100644 index 0000000..dfaa5cd --- /dev/null +++ b/pytorch/tests/test_omega_torch.py @@ -0,0 +1,247 @@ +"""Milestone 1 checks for torch.compile(backend="omega"). CPU only; the oracle is eager PyTorch. + +Run: CUDA_VISIBLE_DEVICES= OMEGA_OMC= python3 -m unittest -v pytorch/tests/test_omega_torch.py +Tolerance: torch.testing.assert_close float32 defaults (rtol 1.3e-6, atol 1e-5) against eager float32. +""" + +import os +import re +import shutil +import subprocess +import sys +import tempfile +import unittest + +import torch +import torch.nn as nn + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) +import omega_torch as ot # noqa: E402 + +torch.manual_seed(0) + + +def compiled(fn): + torch._dynamo.reset() + return torch.compile(fn, backend="omega", fullgraph=True, dynamic=False) + + +def run_both(fn, *args): + ot.reset_stats() + with torch.no_grad(): + got = compiled(fn)(*args) + want = fn(*args) + return got, want + + +def two_ulp(got, ref64): + """|got - ref| <= 2^-22 |ref| elementwise: two float32 ulps from a float64 eager reference.""" + return bool(((got.double() - ref64).abs() <= ref64.abs() * 2.0 ** -22).all()) + + +class MLP(nn.Module): + def __init__(self, i=16, h=32, o=8): + super().__init__() + self.l1 = nn.Linear(i, h) + self.l2 = nn.Linear(h, o) + self.p = nn.Parameter(torch.randn(o, o)) + + def forward(self, x, y): + h = torch.relu(self.l1(x)) + y + z = torch.matmul(self.l2(h), self.p) + return torch.softmax(z, dim=-1) + + +class Ops(unittest.TestCase): + """One op at a time, each through an Omega kernel, against eager float32.""" + + def check(self, fn, *args, kernels): + got, want = run_both(fn, *args) + torch.testing.assert_close(got, want) + self.assertEqual(ot.STATS["eager_fallback_calls"], 0) + for k in kernels: + self.assertGreaterEqual(ot.STATS["per_op"].get(k, 0), 1, (k, ot.STATS)) + + def test_mm(self): + self.check(torch.mm, torch.randn(5, 7), torch.randn(7, 3), kernels=["mm"]) + + def test_addmm(self): + self.check(torch.addmm, torch.randn(3), torch.randn(5, 7), torch.randn(7, 3), kernels=["addmm"]) + + def test_linear(self): + lin = nn.Linear(7, 3) + self.check(lin, torch.randn(5, 7), kernels=["linear"]) + self.assertNotIn("tr", ot.STATS["per_op"]) + + def test_permute(self): + self.check(lambda x, y: x.t() + y, torch.randn(4, 6), torch.randn(6, 4), kernels=["tr", "eadd"]) + + def test_add(self): + self.check(torch.add, torch.randn(3, 5), torch.randn(3, 5), kernels=["eadd"]) + + def test_relu(self): + x = torch.randn(4, 9) + x[0, 0] = float("nan") + x[0, 1] = float("-inf") + x[0, 2] = float("inf") + got, want = run_both(torch.relu, x) + torch.testing.assert_close(got, want, equal_nan=True) + self.assertEqual(ot.STATS["per_op"], {"relu": 1}) + + def test_softmax(self): + x = torch.randn(6, 11) * 40.0 + x[1, 3] = float("-inf") + self.check(lambda t: torch.softmax(t, dim=-1), x, kernels=["softmax"]) + + def test_softmax_two_ulp_of_float64(self): + # Stricter than the float32 default: within 2^-22 relative (2 float32 ulps) of eager float64. + # The default (atol 1e-5) cannot see an exp truncated at degree 4 (measured 4.9e-5 relative). + x = torch.randn(6, 11) * 4.0 + got, _ = run_both(lambda t: torch.softmax(t, dim=-1), x) + self.assertTrue(two_ulp(got, torch.softmax(x.double(), dim=-1))) + + def test_softmax_wolfram(self): + # WolframLanguageEvaluator: Exp[k]/(Exp[1]+Exp[2]+Exp[3]), k = 1, 2, 3, to 20 digits -> + # 0.090030573170380457998, 0.24472847105479765247, 0.66524095577482188953. + # Omega must give the float32 nearest to each exact value (one rounding of an f64 result). + exact = torch.tensor([[0.090030573170380457998, 0.24472847105479765247, + 0.66524095577482188953]], dtype=torch.float64).to(torch.float32) + got, _ = run_both(lambda t: torch.softmax(t, dim=-1), torch.tensor([[1.0, 2.0, 3.0]])) + self.assertTrue(torch.equal(got, exact), (got, exact)) + + def test_mm_exact_integers(self): + # Small integers: every product and sum is exact in f32, so Omega and eager must agree bitwise. + a = torch.randint(-9, 10, (6, 5)).float() + b = torch.randint(-9, 10, (5, 4)).float() + got, want = run_both(torch.mm, a, b) + self.assertTrue(torch.equal(got, want)) + + +class Model(unittest.TestCase): + def test_mlp_parity_and_all_omega(self): + m = MLP().eval() + x, y = torch.randn(4, 16), torch.randn(4, 32) + got, want = run_both(m, x, y) + torch.testing.assert_close(got, want) + s = ot.STATS + self.assertEqual(s["eager_fallback_calls"], 0) + self.assertEqual(s["per_op"], {"linear": 2, "relu": 1, "eadd": 1, "mm": 1, "softmax": 1}) + # Independent float64 eager reference: Omega's error is no larger than eager float32's plus 1e-7. + with torch.no_grad(): + ref = m.double()(x.double(), y.double()) + err_o = (got.double() - ref).abs().max().item() + err_e = (want.double() - ref).abs().max().item() + self.assertLessEqual(err_o, err_e + 1e-7, (err_o, err_e)) + + +class FailClosed(unittest.TestCase): + def test_unsupported_op_raises_and_runs_nothing(self): + ot.set_fallback(()) + ot.reset_stats() + with torch.no_grad(), self.assertRaises(Exception) as cm: + compiled(lambda x: torch.tanh(x) + x)(torch.randn(3, 3)) + self.assertIn("OmegaRefused", repr(cm.exception) + str(cm.exception)) + self.assertIn("aten.tanh.default", str(cm.exception)) + self.assertEqual(ot.STATS["omega_calls"], 0) + self.assertEqual(ot.STATS["eager_fallback_calls"], 0) + + def test_broadcast_add_refused(self): + with torch.no_grad(), self.assertRaises(Exception) as cm: + compiled(lambda a, b: a + b)(torch.randn(3, 4), torch.randn(4)) + self.assertIn("broadcasting", str(cm.exception)) + + def test_explicit_fallback_is_counted(self): + ot.set_fallback({"aten.tanh.default"}) + try: + got, want = run_both(lambda x: torch.tanh(x) + x, torch.randn(3, 3)) + finally: + ot.set_fallback(()) + torch.testing.assert_close(got, want) + self.assertEqual(ot.STATS["eager_fallback_calls"], 1) + self.assertEqual(ot.STATS["per_op"], {"eadd": 1}) + + def test_array_limit_refused(self): + with torch.no_grad(), self.assertRaises(Exception) as cm: + compiled(torch.relu)(torch.zeros(4097, 4096)) + self.assertIn("above the Omega array limit 16777216", str(cm.exception)) + + def test_wrong_length_status_32(self): + fn = ot.load_unit("relu", [("L", 4)], 2) + with self.assertRaises(ot.OmegaCallError) as cm: + ot.call_unit(fn, "relu", [torch.zeros(5), torch.zeros(4)]) + self.assertIn("status 32", str(cm.exception)) + + +class NegativeControl(unittest.TestCase): + """Deliberately wrong kernels must make the parity checks fail.""" + + def mutate(self, name, old, new): + d = tempfile.mkdtemp(prefix="omega-torch-mut-") + for f in os.listdir(ot.KERNEL_DIR): + shutil.copy(os.path.join(ot.KERNEL_DIR, f), d) + p = os.path.join(d, name + ".om") + with open(p) as f: + src = f.read() + self.assertIn(old, src) + with open(p, "w") as f: + f.write(src.replace(old, new, 1)) + return d + + def with_kernels(self, d, fn, *args): + saved = ot.KERNEL_DIR + ot.KERNEL_DIR = d + try: + return run_both(fn, *args) + finally: + ot.KERNEL_DIR = saved + + def test_mutant_linear_caught(self): + d = self.mutate("linear", "s = add s mul", "s = sub s mul") + got, want = self.with_kernels(d, MLP().eval(), torch.randn(4, 16), torch.randn(4, 32)) + with self.assertRaises(AssertionError): + torch.testing.assert_close(got, want) + + def test_mutant_relu_caught(self): + d = self.mutate("relu", "if lt v 0.0f32", "if gt v 0.0f32") + got, want = self.with_kernels(d, torch.relu, torch.randn(4, 9)) + with self.assertRaises(AssertionError): + torch.testing.assert_close(got, want) + + def test_mutant_softmax_caught(self): + # exp truncated at degree 4 instead of 13: 4.9e-5 relative error, which the float32 default + # tolerance (atol 1e-5) misses on probabilities this small; the two-ulp float64 check catches it. + d = self.mutate("softmax", "for j ulong 13\nn = f64 sub 13 j", "for j ulong 4\nn = f64 sub 4 j") + x = torch.randn(6, 11) * 4.0 + got, _ = self.with_kernels(d, lambda t: torch.softmax(t, dim=-1), x) + self.assertFalse(two_ulp(got, torch.softmax(x.double(), dim=-1))) + + +class Binding(unittest.TestCase): + """src/native.om: f32 arrays and const-named lengths are bound; anything else is refused.""" + + def gen(self, src): + with tempfile.NamedTemporaryFile() as t: + ot._compile_om(src.encode(), t.name) + code = t.read() + frame = src.encode() + b"\0" + b"%08d" % len(code) + code + p = subprocess.run([ot._native(), "c"], input=frame, capture_output=True) + return p.returncode, p.stdout.decode() + + def test_const_f32_bound(self): + rc, c = self.gen("const L ulong 6\nfn k a view f32 L o edit f32 L to void\nput o 0 get a 0\nend\n") + self.assertEqual(rc, 0) + self.assertRegex(c, r"ombr_span_add\(sp, &ns, o_a, o_a_len, 6u, 4u, 0\)") + self.assertRegex(c, r"ombr_span_add\(sp, &ns, o_o, o_o_len, 6u, 4u, 1\)") + + def test_const_not_ulong_refused(self): + # The compiler accepts a uint constant as a length; the binding reads only "const NAME ulong N". + rc, c = self.gen("const L uint 6\nfn k a view f32 L to void\nret\nend\n") + self.assertEqual((rc, c), (110, "")) + + def test_f64_array_refused(self): + rc, c = self.gen("fn k a view f64 4 to void\nret\nend\n") + self.assertEqual((rc, c), (110, "")) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/native.om b/src/native.om index bd87358..461077a 100644 --- a/src/native.om +++ b/src/native.om @@ -10,7 +10,8 @@ note code (word 0 branches to it); earlier functions are private helpers with an note function's parameters are ulong or long scalars, or edit/view arrays of ulong, uchar, f32 or note ushort; its result is ulong, long or void. An f32 array is 4-byte aligned binary32 and a ushort note array is 2-byte aligned. Rust and Zig declarations type those two as byte pointers; the C library -note enforces element size and alignment. Python ctypes uses c_float and c_uint16. +note enforces element size and alignment. Python ctypes uses c_float and c_uint16. An array length is +note a decimal number or the name of an earlier "const NAME ulong DIGITS" line of the unit. note trap 10 (exit 110) and no output. global inb uchar 16777216 global outb uchar 16777216 @@ -38,7 +39,7 @@ text fxe "static const ombr_rt ombr_rt_table" text xqd "\\n.quad " text xby "\\n.byte " text xfasm "/* SysV AMD64 adapter to the pinned private Omega frame ABI on the caller's stack. ombr_enter saves\n * the callee-saved registers there, keeps that stack pointer in R12, points R14 at the runtime table\n * and sets the owned-stack floor R15 to 0, so, as in the AArch64 binding, the pure scalar code runs on\n * the caller's stack with no bound check. A normal return stores RAX through out and returns 0. A\n * runtime entry restores the stack pointer from R12 and returns a status; out is not written.\n * CET shadow-stack enforcement is not supported by the nonlocal trap return. */\n__asm__(\".text\\n.balign 16\\n.local ombr_enter\\n.hidden ombr_enter\\n.type ombr_enter,@function\\nombr_enter:\\n\"\n \"endbr64\\npush %rbx\\npush %rbp\\npush %r12\\npush %r13\\npush %r14\\npush %r15\\npush %rcx\\n\"\n \"mov %rsp,%r12\\nmov %rdx,%r14\\nxor %r15d,%r15d\\nmov %rdi,%r10\\n\"\n \"mov %rsp,%rbp\\nsub $256,%rsp\\n\"\n \"mov 0(%rsi),%rax\\nmov %rax,-8(%rbp)\\nmov 8(%rsi),%rax\\nmov %rax,-16(%rbp)\\n\"\n \"mov 16(%rsi),%rax\\nmov %rax,-24(%rbp)\\nmov 24(%rsi),%rax\\nmov %rax,-32(%rbp)\\n\"\n \"mov 32(%rsi),%rax\\nmov %rax,-40(%rbp)\\nmov 40(%rsi),%rax\\nmov %rax,-48(%rbp)\\n\"\n \"call *%r10\\nmov %r12,%rsp\\nmov (%rsp),%rcx\\nmov %rax,(%rcx)\\nxor %eax,%eax\\n\"\n \"ombr_leave:\\nadd $8,%rsp\\npop %r15\\npop %r14\\npop %r13\\npop %r12\\npop %rbp\\npop %rbx\\nret\\n\"\n \".size ombr_enter,.-ombr_enter\\n.local ombr_trap\\n.hidden ombr_trap\\n.type ombr_trap,@function\\nombr_trap:\\n\"\n \"endbr64\\nmov %r12,%rsp\\nlea -1(%rsi),%eax\\ncmp $13,%eax\\nmov $34,%eax\\ncmovbe %esi,%eax\\njmp ombr_leave\\n\"\n \".size ombr_trap,.-ombr_trap\\n.local ombr_no_entry\\n.hidden ombr_no_entry\\n.type ombr_no_entry,@function\\nombr_no_entry:\\n\"\n \"endbr64\\nmov %r12,%rsp\\nmov $34,%eax\\njmp ombr_leave\\n.size ombr_no_entry,.-ombr_no_entry\\n\");\n" -text kw "toeditviewulonglongucharvoidmainf32ushort" +text kw "toeditviewulonglongucharvoidmainf32ushortconst" text fr "__asm__(\".section .text.omega_bridge,\\\"ax\\\",@progbits\\n.balign 4\\n.local ombr_code_~\\n.hidden ombr_code_~\\nombr_code_~:\\n.byte ~\\n.previous\\n\");\nextern const unsigned char ombr_entry_~[] __attribute__((visibility(\"hidden\")));\n__attribute__((visibility(\"default\"))) uint32_t omega_~(uint64_t *result~, uint64_t o_~, void *o_~, const void *o_~_len~)\n{\n ombr_span sp[7];\n unsigned ns = 0;\n uint64_t a[6] = {0};\n if (ombr_span_add(sp, &ns, result, 1u, 1u, 8u, 1))\n return OMEGA_BAD_ARG;\n~ if (ombr_span_add(sp, &ns, o_~, o_~_len, ~u, ~))\n return OMEGA_BAD_ARG;\n a[~] = (uint64_t)(uintptr_t)o_~;\n~ a[~] = o_~ if (ombr_overlap(sp, ns))\n return OMEGA_BAD_ARG;\n return ombr_run(ombr_entry_~, a, result, ~);\n}\n~\\n.local ombr_entry_~\\n.hidden ombr_entry_~\\nombr_entry_~:\\nhint #34\\nb ombr_code_" text pre "/* Generated by omega-bridge src/native.om: native call ABI v1 (docs/NATIVE-ABI.md).\n * The Omega machine code below is embedded byte for byte as the seeded compiler wrote it.\n * This file only adapts the C calling convention to it. Regenerate it; do not edit it. */\n#include \n#include \n#include \n#include \n#define OMEGA_OK 0u\n#define OMEGA_BAD_ARG 32u\n#define OMEGA_REENTRY 33u\n#define OMEGA_BAD_RT 34u\n#define OMEGA_NO_STACK 35u\n#define OMBR_STACK (8u << 20)\n#define OMBR_GUARD (8u << 20)\n/* entry[2] is the trap entry (OSC-1 section 7). */\ntypedef struct ombr_rt { const void *entry[32]; } ombr_rt;\ntypedef struct ombr_span { uintptr_t lo, hi; int w; } ombr_span;\nstatic _Thread_local volatile sig_atomic_t ombr_active;\nstatic _Thread_local unsigned char *ombr_stk;\nstatic pthread_key_t ombr_key;\nstatic int ombr_keyok;\nstatic pthread_once_t ombr_once = PTHREAD_ONCE_INIT;\nuint32_t ombr_enter(const void *code, const uint64_t *args, const ombr_rt *rt, uint64_t *out, void *top)\n __attribute__((visibility(\"hidden\")));\nextern const unsigned char ombr_trap[] __attribute__((visibility(\"hidden\")));\nextern const unsigned char ombr_no_entry[] __attribute__((visibility(\"hidden\")));\n/* ombr_enter saves the callee-saved registers on the caller's stack, keeps that stack pointer in x19 and\n * runs the code on the binding's own stack. A normal return stores x0 through out and\n * returns 0. A runtime entry restores the stack pointer from x19 and returns a status; out is not\n * written. The seeded compiler never writes x19..x28. Runtime entries are reached by blr/br, so they\n * start with bti jc. */\n__asm__(\".text\\n.balign 4\\n.local ombr_enter\\n.hidden ombr_enter\\n.type ombr_enter,%function\\nombr_enter:\\n\"\n \"hint #34\\nstp x29,x30,[sp,#-176]!\\nmov x29,sp\\nstp x19,x20,[sp,#16]\\nstp x21,x22,[sp,#32]\\n\"\n \"stp x23,x24,[sp,#48]\\nstp x25,x26,[sp,#64]\\nstp x27,x28,[sp,#80]\\nstp d8,d9,[sp,#96]\\n\"\n \"stp d10,d11,[sp,#112]\\nstp d12,d13,[sp,#128]\\nstp d14,d15,[sp,#144]\\nstr x3,[sp,#160]\\n\"\n \"mov x19,sp\\nmov x16,x0\\nmov x17,x1\\nmov x7,x2\\nmov sp,x4\\n\"\n \"ldp x0,x1,[x17]\\nldp x2,x3,[x17,#16]\\nldp x4,x5,[x17,#32]\\nblr x16\\n\"\n \"mov sp,x19\\nldr x9,[sp,#160]\\nstr x0,[x9]\\nmov w0,#0\\n\"\n \"ombr_leave:\\nldp d14,d15,[sp,#144]\\nldp d12,d13,[sp,#128]\\nldp d10,d11,[sp,#112]\\n\"\n \"ldp d8,d9,[sp,#96]\\nldp x27,x28,[sp,#80]\\nldp x25,x26,[sp,#64]\\nldp x23,x24,[sp,#48]\\n\"\n \"ldp x21,x22,[sp,#32]\\nldp x19,x20,[sp,#16]\\nldp x29,x30,[sp],#176\\nret\\n.size ombr_enter,.-ombr_enter\\n\"\n \".local ombr_trap\\n.hidden ombr_trap\\n.type ombr_trap,%function\\nombr_trap:\\nhint #38\\n\"\n \"mov sp,x19\\nsub x2,x1,#1\\nmov w3,#34\\ncmp x2,#13\\ncsel w0,w1,w3,ls\\nb ombr_leave\\n\"\n \".size ombr_trap,.-ombr_trap\\n\"\n \".local ombr_no_entry\\n.hidden ombr_no_entry\\n.type ombr_no_entry,%function\\nombr_no_entry:\\nhint #38\\n\"\n \"mov sp,x19\\nmov w0,#34\\nb ombr_leave\\n.size ombr_no_entry,.-ombr_no_entry\\n\");\nstatic void ombr_free(void *p)\n{\n munmap(p, OMBR_STACK + OMBR_GUARD);\n}\nstatic void ombr_init(void)\n{\n ombr_keyok = pthread_key_create(&ombr_key, ombr_free) == 0;\n}\n/* The thread's Omega stack: OMBR_STACK usable bytes above an OMBR_GUARD no-access region. A function-mode\n * unit has no call cycles and at most 4 MiB of local arrays per function (OMEGESE, local arrays), so a frame that\n * would pass the bottom starts inside the guard and faults there; nothing below the guard is touched. */\nstatic unsigned char *ombr_stack(void)\n{\n if (ombr_stk)\n return ombr_stk;\n pthread_once(&ombr_once, ombr_init);\n if (!ombr_keyok)\n return 0;\n unsigned char *p = mmap(0, OMBR_STACK + OMBR_GUARD, PROT_READ | PROT_WRITE,\n MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);\n if (p == MAP_FAILED)\n return 0;\n if (mprotect(p, OMBR_GUARD, PROT_NONE) != 0 || pthread_setspecific(ombr_key, p) != 0) {\n munmap(p, OMBR_STACK + OMBR_GUARD);\n return 0;\n }\n ombr_stk = p + OMBR_GUARD + OMBR_STACK;\n return ombr_stk;\n}\nstatic int ombr_span_add(ombr_span *sp, unsigned *ns, const void *p, uint64_t n, uint64_t want, uint64_t es, int w)\n{\n uintptr_t lo = (uintptr_t)p;\n if (!p || n != want || lo % es != 0u || n > (UINTPTR_MAX - lo) / es)\n return 1;\n sp[*ns].lo = lo;\n sp[*ns].hi = lo + n * es;\n sp[*ns].w = w;\n (*ns)++;\n return 0;\n}\nstatic int ombr_overlap(const ombr_span *sp, unsigned ns)\n{\n for (unsigned i = 0; i < ns; i++)\n for (unsigned j = i + 1; j < ns; j++)\n if ((sp[i].w || sp[j].w) && sp[i].lo < sp[j].hi && sp[j].lo < sp[i].hi)\n return 1;\n return 0;\n}\n/* One read-only runtime table for every call and thread: the code only reads it (a write would fault). */\nstatic const ombr_rt ombr_rt_table = {{ ombr_no_entry, ombr_no_entry, ombr_trap, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry }};\nstatic uint32_t ombr_run(const void *code, const uint64_t *args, uint64_t *result, int has_value)\n{\n if (ombr_active)\n return OMEGA_REENTRY;\n ombr_active = 1;\n unsigned char *top = ombr_stack();\n if (!top) {\n ombr_active = 0;\n return OMEGA_NO_STACK;\n }\n uint64_t v = 0;\n uint32_t s = ombr_enter(code, args, &ombr_rt_table, &v, top);\n ombr_active = 0;\n if (s == OMEGA_OK)\n *result = has_value ? v : 0u;\n return s;\n}\n" note mo: the output names; tb: the binding texts, fragments separated by ~ (byte 126): 0-11 h, @@ -719,6 +720,113 @@ end end ret 1 end +note isat: 1 when input bytes i .. i+n-1 lie before q and equal kw bytes o .. o+n-1, else 0. +fn isat i ulong o ulong n ulong q ulong to ulong +if gt add i n q +ret 0 +end +for j ulong n +if ne get inb add i j get kw add o j +ret 0 +end +end +ret 1 +end +note spat: 1 when byte a lies before q and is a space, else 0. +fn spat a ulong q ulong to ulong +if ge a q +ret 0 +end +if ne get inb a 32 +ret 0 +end +ret 1 +end +note cline: the value on the line at i when it is exactly "const NAME ulong DIGITS" and NAME is the +note bytes s .. e-1; 0 when it is another line. A matching line whose value is not 1 .. 8 digits, or +note is 0, is refused. +fn cline i ulong q ulong s ulong e ulong to ulong +if eq isat i 41 5 q 0 +ret 0 +end +a = add i 5 +if eq spat a q 0 +ret 0 +end +a = add a 1 +n = sub e s +if gt add a n q +ret 0 +end +if eq samenm a add a n s e 0 +ret 0 +end +a = add a n +if eq spat a q 0 +ret 0 +end +a = add a 1 +if eq isat a 10 5 q 0 +ret 0 +end +a = add a 5 +if eq spat a q 0 +ret 0 +end +a = add a 1 +v = ulong 0 +d = ulong 0 +while and lt a q ne get inb a 10 +c = get inb a +if or lt c 48 gt c 57 +trap 10 +end +if ge d 8 +trap 10 +end +v = add mul v 10 ulong sub c 48 +d = add d 1 +a = add a 1 +end +if or eq d 0 eq v 0 +trap 10 +end +ret v +end +note cval: the value of the integer constant named by bytes s .. e-1, defined on a line of the unit +note before its signature line (st 9 is the unit start, st 6 the signature line); refused when absent. +fn cval s ulong e ulong to ulong +p = get st 9 +q = get st 6 +ls = p +i = p +while lt i q +if eq i ls +v = cline i q s e +if gt v 0 +ret v +end +end +if eq get inb i 10 +ls = add i 1 +end +i = add i 1 +end +trap 10 +end +note tklen: an array length token: decimal digits, or the name of an integer constant (cval). +fn tklen k ulong to ulong +s = get tks k +e = get tke k +if eq s e +trap 10 +end +c = get inb s +if and ge c 48 le c 57 +ret tknum k +end +ret cval s e +end note uname: refuse a unit name (token 1) that is not a C identifier or repeats an earlier unit name. fn uname to void s = get tks 1 @@ -757,7 +865,7 @@ put st 2 add np 1 if le ki 2 ret add k 2 end -ln = tknum add k 3 +ln = tklen add k 3 if or eq ln 0 gt ln 16777216 trap 10 end @@ -2644,6 +2752,7 @@ if eq prof p q 1 ret unit2 p q end fl = sigln p q +put st 9 p parse fl q cl = codelen q c0 = add q 9 ```