omega-mv
Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.
Brought by drakestapleton
GitHub aien-dev/omega-mv#854 (code only)
Fetch it
curl -fsSL https://interplane.io/drakestapleton/omega-mv/patches/de1778b93f97f344.bundle -o de1778b93f97f344.bundle git fetch de1778b93f97f344.bundle refs/pull/854/head
Provenance
github-import 1
aien-dev/omega-mv
854
5c743f0e0b3cd2f777aa92c06ce4a177573cb58a
{"kind":"github-import","owner":"aien-dev","repo":"omega-mv","number":854,"url":"https://github.com/aien-dev/omega-mv/pull/854","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:38:52Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.crumb b/.crumb index fb8a4717b..5c06b691f 100644 --- a/.crumb +++ b/.crumb @@ -72,38 +72,38 @@ }, { "digest": "f765ad87fdddd9b47f690b07298c951a0f7e7675dc5de4ffe44e33a0c14b1986", - "last_commit": "d94a503f7", + "last_commit": "62d1d0d66", "name": "spec", "purpose": "Directory spec. Purpose not yet described by a human." }, { "digest": "aaf5acb82fd4c720cd60c85fd6087f636c72a98e2f3740c9295dcfa525dc64d7", - "last_commit": "bf54b19fa", + "last_commit": "089e5b053", "name": "src", "purpose": "Directory src. Purpose not yet described by a human." }, { "digest": "5395ff8ff9afceebe8e453788f80a3064b831513cc4cb92fd55869115e06b874", - "last_commit": "dcccc0211", + "last_commit": "62d1d0d66", "name": "tests", "purpose": "Directory tests. Purpose not yet described by a human." }, { "digest": "308db0e6cf45c0a48f01f5f5f228450f191389de68006915b9ecf9c65b9a2e29", - "last_commit": "a50c3bd41", + "last_commit": "62d1d0d66", "name": "tools", "purpose": "Directory tools. Purpose not yet described by a human." } ], "children_root": "sha256:07bf1706dcffbad66c0353871ff67a6749055da03cee8d8ebdf9a4c91e36bddc", - "compiled_at": "2026-10-30T16:29:04Z", + "compiled_at": "2026-10-30T17:13:30Z", "compiler": "crumb-compile/1", - "digest": "sha256:145642bc89d576e2614c2880b07804488e9369307a4d13f55cf04c7396f2e476", + "digest": "sha256:ba9dff29a5b878f02c3b09c648b4a358c409a9256ebf9f60909846fe4a54baca", "evidence_files": 12622, "evidence_root": "sha256:b1a08e2ce56e6feada0d8a31f06fbd7adee57adc1c1ad8dec220293ee5d439f9", - "files": 17850, - "generated_at_commit": "30a54e64589db9b65d24ba595ef0a610ad35d341", - "source_tree": "sha256:7c95a05d1eae5990bd3f40252a6694204823fb08a90298b49a01c933fac8509e" + "files": 17857, + "generated_at_commit": "3e778bd698374595dc543f7e9dad7f079d4f5a96", + "source_tree": "sha256:3efe1d1926648cc25637e015265d64006ae33bc622d97cc87b44a38ea4aadde7" }, "owner_lane": "", "provenance": { diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index d07ebcf59..da30f1a1f 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -5,6 +5,7 @@ Every model below did real work. A model is listed only for work it did. The orc | Model | What it did | |---|---| +| Grok 4.7 | Merged current main (`6d482de0e`) into #854. The only conflict was the generated root `.crumb` (compile stamps and source-tree digest). Regenerated crumbs with the crumb.lock tool (`d0f0b95d`). | | Grok 4.7 | Merged current main (`089e5b053`) into #936. Conflicts were generated crumbs (`.crumb`, `tests/.crumb`); regenerated them with the crumb.lock tool (`d0f0b95d`). | | Grok 4.7 | Restored the offline DAG evaluator's forbidden-symbol guard from #590 (`3bd56731`): generation store, authority, world, and calls that map or run code. | | Grok 4.7 | Imported the offline DAG evaluator `tools/dagsim` verbatim from closed PR #590 (`3bd56731`) and wired a host `test-dagsim` target. Analytical fixture checks only. No validated cost claim. | @@ -36,6 +37,7 @@ Every model below did real work. A model is listed only for work it did. The orc | Claude Opus 5.5 | Omega 1.0 roadmap: source-pinned readiness audit of the seeded compiler, IR, WebAssembly and bridge paths, milestone acceptance gates, tracking issues #790-#800, OM-2 contract files brought to main byte-identical, and stale status text corrected | | Claude Opus 5.5 | Function-mode constants in the seeded compiler (`fnstore`): consts accepted without `fn main`, globals/texts/host words still error 9, gate16 byte-identity fixtures and old-compiler/mutant negative controls | | Codex (GPT-6.1 Sol) | Repaired qty float-domain classification and checked ingress, diagnostic categories and query/output streaming; permanent adversarial regression fixtures for the #909/#911 audit | +| Claude Opus 5.5 | AWS Trainium/Inferentia backend `seed/nki`: `irnki.om` OSC IR v1 to `nki.isa` vecadd/elementwise emitter, native-Omega reference lanes, NKI CPU simulator interop-oracle gate (trn1/trn2/trn3) with negative controls and refusals, pinned oracle setup | This table starts with the numeric work on this branch. Earlier work in this repository is not yet attributed here; add rows only for work that can be traced to a model. diff --git a/seed/nki/.crumb b/seed/nki/.crumb new file mode 100644 index 000000000..ccd069463 --- /dev/null +++ b/seed/nki/.crumb @@ -0,0 +1,20 @@ +{ + "extensions": { + "generated": { + "children": [], + "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "compiled_at": "2026-10-30T02:52:13Z", + "compiler": "crumb-compile/1", + "digest": "sha256:77abf208f8226ddb9217067f78c12d708ae06cc5b906d5e7e27c78d32d5cbe73", + "evidence_files": 0, + "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "files": 7, + "generated_at_commit": "6c95edd2da9415f341ed1dc57f417251e8a16053", + "source_tree": "sha256:a7a092a9c257dd37b4b579860adacecdda4d8dd0fb05cb7efbc89c1d32622955" + } + }, + "layer": "seed", + "name": "nki", + "purpose": "Seeded Omega OSC IR v1 elementwise scalar to AWS NKI (nki.isa) kernel emitter with NKI CPU simulator interop-oracle verification", + "schema_version": "1.0.0" +} diff --git a/seed/nki/README.md b/seed/nki/README.md new file mode 100644 index 000000000..498f98ed8 --- /dev/null +++ b/seed/nki/README.md @@ -0,0 +1,162 @@ +# seed/nki: Omega to AWS Trainium / Inferentia (NKI) + +`irnki.om` is a handwritten, seeded-Omega emitter. It reads an OSC IR v1 unit +(`spec/one-layer-format.md`) and writes an NKI kernel module in Python at the `nki.isa` +(NISA) level. NISA is the lowest level AWS documents publicly. The first kernel is +vecadd: `out[i] = a[i] + b[i]`. + +Status, 2026-10-26: + +| Item | Status | +|---|---| +| Emitter `irnki.om` | IMPLEMENTED | +| Kernels on the NKI CPU simulator, targets trn1, trn2, trn3 | EXERCISED-on-oracle (interop oracle, not Omega-native) | +| Trainium or Inferentia hardware | NOT_RUN | + +## What it emits + +Each function becomes one `@nki.jit` kernel. The kernel loops over tiles of +128 partitions x 512 elements (`nl.affine_range`) and keeps three explicit SBUF tiles per +step, `ta`, `tb` and `tc`. It moves data with `nisa.dma_copy` (HBM to SBUF and back) and +computes one `nisa.tensor_tensor(dst=tc, data1=, data2=, op=nl.<op>)`. The module ends +with `KERNELS = {name: (kernel, dtype)}`. + +The emitter lifts only this shape: + +- two parameters and a result, all u32 (tag 4), and three vregs; +- one block of two instructions: `BIN sub dst=2 a b` (a and b are params 0 or 1), then `RET 2`. + +The supported subcodes are add, sub, mul, and, or and xor, mapped to `nl.add`, +`subtract`, `multiply`, `bitwise_and`, `bitwise_or` and `bitwise_xor`. These are refused: + +| Input | Exit and message | +|---|---| +| div, rem, shl, shr | 24 UNSUPPORTED_OP. Omega traps on these and NKI has no trap. | +| Any tag other than u32 | 25 UNSUPPORTED_TAG | +| Any other function shape | 29 NOT_ELEMENTWISE | +| Bad bytes | 20–28, as in irwasm | +| Bad arguments | 30 USAGE | + +Every refusal happens before the first stdout byte. + +`irnki f32` retypes the lanes to float32 and then allows only add, sub and mul. This +retyping is explicit and documented. It exists because IR v1 cannot carry floats: the +compiler refuses float words in `ir` mode with error 16, and the float tags in spec +section 10.3 are not produced yet. The f32 vecadd is therefore the u32 unit +`vecadd.unit.om` with float32 lanes. The gate computes the f32 reference from the same +unit with `uint` read as `f32`. + +Shape limits: the kernels take 2-D arrays whose rows are a multiple of 128 and whose +columns are a multiple of 512. Any other shape is refused by an assertion, and the gate +checks that (128, 500) is refused. Three f32 tiles take 6144 bytes per partition, which +is 1/32 of the 192 KiB trn1 SBUF partition (224 KiB on trn2, 256 KiB on trn3). Computed +with WolframLanguageEvaluator: `3*512*4 -> 6144`, `3*512*4/(192*1024) -> 0.03125`. + +## Run + +```sh +seed/nki/setup-oracle.sh /tmp/nki-oracle # pinned downloads, user files only +NKI_ORACLE_DIR=/tmp/nki-oracle nice -n 19 seed/nki/gate-irnki.sh +``` + +Exit codes: 0 PASS, 1 FAIL, 3 NOT_RUN (no oracle directory, the oracle does not start, +the oracle version differs from the pin, or the host is not AArch64). Artifacts go to +`build/seed/nki/`, and `gate.log` holds SOURCE, COMPILER, ORACLE and PLATFORM. + +The gate does the following: + +1. Builds `irnki` with the pinned `seed/out/omc` (sha256 `2c824805…029f`). +2. Lifts `vecadd.unit.om` (f32 and u32) and `ops.unit.om` (8 functions: every op, + swapped operands `sub b a`, and repeated operands `add a a`). Each module is emitted + twice and compared with `cmp`. +3. Computes the expected lanes with a native AArch64 Omega program for each function, + built from the same unit source plus a driver. No foreign code computes expected + values. +4. Runs every kernel in `nki.simulate` for trn1, trn2 and trn3 on 262144 lanes, shaped + (256, 1024), which is 4 tiles. The input set includes all pairs of edge values: 100 + for u32, and 196 for f32, covering ±0, ±inf, NaN, ±max, min-normal, subnormals and + 1+ulp. Results are compared bit for bit, except that two NaNs count as equal, because + NaN sign and payload are not part of the IEEE result. +5. Negative controls, each of which must FAIL: + - an emitted `nl.add` edited to `nl.subtract`; + - the IR BIN subcode byte changed from add to sub before lifting; + - one expected bit flipped; + - a kernel dropped from `KERNELS`. +6. Checks 14 refusals: exact exit code, the message on stderr and empty stdout. + +Measured 2026-10-26 on the DGX Spark: PASS, with 30 of 30 kernel/target runs equal and +every control rejected. The same result came from a directory freshly prepared by +`setup-oracle.sh`. + +## Oracle stack (interop oracle, not Omega-native; never generates kernels) + +The nki wheel is published for x86_64 only, so on AArch64 it runs as x86_64 CPython +under qemu-user. Every item is a host dependency of the oracle only. + +| Item | Version | Licence | sha256 | +|---|---|---|---| +| nki (from `pip.repos.neuron.amazonaws.com`) | 0.7.0+37713544100.gfede04bb, cp312 linux_x86_64 | Apache-2.0 | `03543bed…0c4e` | +| numpy | 2.2.6 | BSD-3-Clause | `fd83c012…6249` | +| ml_dtypes | 0.5.3 | Apache-2.0 | `1b255aca…9e55` | +| typing_extensions | 4.15.0 | PSF-2.0 | `f0fa19c6…e548` | +| CPython (python-build-standalone 20261026) | 3.12.16 x86_64 | PSF-2.0 | `6a79e922…9de` | +| qemu-user (Debian trixie) | 10.0.13+ds-0+deb13u1 arm64 | GPL-2.0 | `c73711af…158d` | +| libc6, libgcc-s1, libstdc++6, zlib1g (Ubuntu noble amd64) | see `setup-oracle.sh` | LGPL-2.1 / GPL-3 with runtime exception / zlib | see `setup-oracle.sh` | + +`setup-oracle.sh` holds the full pins. The host qemu 8.2.2 crashes (internal SIGSEGV) +when Python reads `/proc/self/maps`, which is why the Debian 10.0.13 static build is used. + +`oracle.py` is the only foreign code. It writes the deterministic inputs, runs the +emitted kernels and compares bits. It never writes a kernel or an expected value. +There is no Omega replacement yet: it needs an Omega reader for the NKI simulator, or +an Omega NISA interpreter. + +## How open the stack is (primary sources, read 2026-10-26) + +- The NKI programming interface (`nki.language`, `nki.isa`) and the CPU simulator ship in + the `nki` wheel under Apache-2.0. Wheels exist for x86_64 only. + https://awsdocs-neuron.readthedocs-hosted.com/en/latest/nki/get-started/about/index.html, + https://awsdocs-neuron.readthedocs-hosted.com/en/latest/nki/guides/nki_simulator.html +- The NKI compiler (MLIR based) is announced as open source but is a private beta. The + wheel's project URL `github.com/aws-neuron/private-nki-staging` is not public, and + `github.com/aws-neuron/nki` returns 404. The NKI IR and its MLIR dialect ship only as + compiled binaries and are not documented. + https://aws.amazon.com/about-aws/whats-new/2025/12/announcement-aws-neuron-2-27/, + https://awsdocs-neuron.readthedocs-hosted.com/en/latest/nki/deep-dives/nki-compiler.html +- The lowest documented level is therefore `nki.isa`, one call per engine instruction. + Below it, NEFF and the engine binary encodings are not public. +- `neuronx-cc` 2.28.7631.0 (wheel METADATA and LICENSE.txt, read without installing) is + under the "AWS Neuron Software License Agreement". That agreement grants use only "in + connection with AWS Services" and requires an AWS account in good standing. The gate + does not use it. +- nki-samples is MIT-0; nki-library and nkipy are Apache-2.0; aws-neuron-driver is + GPL-2.0. https://awsdocs-neuron.readthedocs-hosted.com/en/latest/about-neuron/oss/index.html +- Architecture figures (SBUF 24/28/32 MiB = 128 partitions of 192/224/256 KiB; PSUM + 2 MiB) come from + https://awsdocs-neuron.readthedocs-hosted.com/en/latest/nki/guides/architecture/trainium_inferentia2_arch.html, + `trainium2_arch.html` and `trainium3_arch.html`. + +## What is NOT established + +- No hardware run. The simulator is AWS's functional model; it is not the chip. Engine + choice, timing, subnormal flushing and NaN payloads on Trainium/Inferentia are not + measured. The simulator runs with its default `NKI_PRECISE_FP=1`. +- Kernels are not compiled by `neuronx-cc`, and no NEFF exists. +- Only single-op elementwise u32 units are covered, plus the f32 retyping. There are no + reductions, no matmul (TensorE/PSUM), no broadcasting and no ragged shapes. + +## Path to hardware (NOT_RUN) + +1. An AWS account and a Neuron instance: inf2.xlarge or trn1.2xlarge (NeuronCore-v2), + trn2 (v3) or trn3 (v4), with the Neuron DLAMI or the driver, runtime and `neuronx-cc` + from the Neuron setup guide. + https://awsdocs-neuron.readthedocs-hosted.com/en/latest/setup/index.html +2. Run the same emitted module with `@nki.jit` on NumPy arrays (it compiles through + `neuronx-cc` and runs on the NeuronDevice), and compare the lanes with the same + native Omega references used here. +3. Record the instance type, Neuron SDK versions and the NEFF sha256 in a receipt. Only + that receipt can move the status past EXERCISED-on-oracle. + +The next kernel is matmul: `nisa.nc_matmul` with a 128x128 stationary tile and a 128x512 +moving tile accumulating in PSUM, then `nisa.tensor_copy` PSUM to SBUF and `dma_copy` out, +checked on the same simulator against a native Omega reference. diff --git a/seed/nki/gate-irnki.sh b/seed/nki/gate-irnki.sh new file mode 100755 index 000000000..e9181b37b --- /dev/null +++ b/seed/nki/gate-irnki.sh @@ -0,0 +1,229 @@ +#!/bin/sh +# Host-only verification of seed/nki/irnki.om, the OSC IR v1 -> AWS NKI (nki.isa) emitter. +# The NKI CPU simulator (nki.simulate, nki 0.7.0, Apache-2.0) is an interop oracle, not +# Omega-native, and never generates kernels: irnki.om writes every kernel and a native +# Omega program computes every expected lane. Simulator results are not hardware +# qualification; the Trainium/Inferentia hardware receipt stays NOT_RUN. +# NKI_ORACLE_DIR names a directory prepared by seed/nki/setup-oracle.sh (x86_64 CPython + +# nki wheel run under qemu-user, because the nki wheel is published for x86_64 only). +# Optional: OMC, NKI_TARGETS (default "trn1 trn2 trn3"). +# Exit 0 PASS, 1 FAIL, 3 NOT_RUN. Every artifact stays under build/seed/nki. +set -eu +cd "$(dirname "$0")/../.." +B=build/seed/nki +mkdir -p "$B" +find "$B" -mindepth 1 -maxdepth 1 -exec rm -rf {} + +: > "$B/gate.log" +say() { printf '%s\n' "$*" | tee -a "$B/gate.log"; } +fail() { say "FAIL $*"; exit 1; } +notrun() { say "NOT_RUN $*"; exit 3; } +[ "$(uname -m)" = aarch64 ] || notrun 'requires AArch64 Linux (seed/out/omc emits AArch64)' +OMC=${OMC:-seed/out/omc} +pin=62775d2a391cfef7cde64e387655caa9809a267093112910ec76bfa568f3712b +[ -f "$OMC" ] || fail "compiler $OMC missing" +[ "$(sha256sum "$OMC" | cut -d ' ' -f 1)" = "$pin" ] || fail 'compiler pin differs' +D=${NKI_ORACLE_DIR:-} +[ -n "$D" ] || notrun 'NKI_ORACLE_DIR unset; prepare it with seed/nki/setup-oracle.sh DIR' +for f in qemu/usr/bin/qemu-x86_64 python/bin/python3.12 sysroot/usr/lib/x86_64-linux-gnu/libc.so.6 site/nki/__init__.py; do + [ -e "$D/$f" ] || notrun "oracle file $D/$f missing; rerun seed/nki/setup-oracle.sh" +done +D=$(cd "$D" && pwd) +TARGETS=${NKI_TARGETS:-trn1 trn2 trn3} +oracle() { + target=$1 + shift + env -i PATH=/usr/bin:/bin PYTHONPATH="$D/site" NEURON_LOGICAL_NC_CONFIG=1 \ + NEURON_PLATFORM_TARGET_OVERRIDE="$target" \ + nice -n 19 "$D/qemu/usr/bin/qemu-x86_64" -L "$D/sysroot" \ + "$D/python/bin/python3.12" -s -S seed/nki/oracle.py "$@" +} +version=$(oracle trn3 version 2> "$B/oracle-version.err") || + { cat "$B/oracle-version.err"; notrun 'NKI simulator does not start'; } +want='nki 0.7.0+37713544100.gfede04bb numpy 2.2.6 python 3.12.16' +[ "$version" = "$want" ] || notrun "oracle is '$version', pinned '$want'" +say "SOURCE $(git rev-parse HEAD)" +say "COMPILER $OMC sha256=$pin" +say "ORACLE interop oracle, not Omega-native: nki.simulate ($version) targets=$TARGETS" +say "ORACLE_HOST qemu-x86_64 $("$D/qemu/usr/bin/qemu-x86_64" --version | sed -n 1p) sha256=$(sha256sum "$D/qemu/usr/bin/qemu-x86_64" | cut -d ' ' -f 1)" +say "ORACLE_DRIVER oracle.py sha256=$(sha256sum seed/nki/oracle.py | cut -d ' ' -f 1)" +say "PLATFORM $(uname -srm)" +nice -n 19 "$OMC" < seed/nki/irnki.om > "$B/irnki" 2> "$B/compile.err" +[ ! -s "$B/compile.err" ] || fail 'emitter compile stderr' +chmod +x "$B/irnki" +# lift UNIT LANE OUT: IR v1 bytes of a unit, then the NKI module, emitted twice. +lift() { + { printf 'ir\n'; cat "seed/nki/$1.unit.om"; } | nice -n 19 "$OMC" > "$B/$1.ir" 2> "$B/$1.ir.err" + [ ! -s "$B/$1.ir.err" ] || fail "$1 IR stderr" + if [ "$2" = float32 ]; then mode=f32; else mode=; fi + # shellcheck disable=SC2086 # empty mode means no argument + "$B/irnki" $mode < "$B/$1.ir" > "$B/$3.py" 2> "$B/$3.err" || fail "irnki $1 $2 exit $?" + # shellcheck disable=SC2086 + "$B/irnki" $mode < "$B/$1.ir" > "$B/$3.again.py" + cmp -s "$B/$3.py" "$B/$3.again.py" || fail "$3 emission is not deterministic" + [ ! -s "$B/$3.err" ] || fail "$3 emitter stderr" + say "EMIT $3 from $1.unit.om lane=$2 deterministic sha256=$(sha256sum "$B/$3.py" | cut -d ' ' -f 1)" +} +# ref UNIT LANE OUT: one native AArch64 Omega program per function computes the expected +# lanes from the same unit source. float32 rereads the unit with uint as f32, the same +# retyping irnki applies to the lanes. +ref() { + mkdir -p "$B/$3.ref" + for name in $(sed -n 's/^fn \([A-Za-z0-9_]*\) .*/\1/p' "seed/nki/$1.unit.om"); do + p=$B/$3.ref/$name + if [ "$2" = float32 ]; then + sed '/^fn /s/ uint/ f32/g' "seed/nki/$1.unit.om" > "$p.om" + call="r = ulong bitcast uint $name bitcast f32 a bitcast f32 b" + else + cat "seed/nki/$1.unit.om" > "$p.om" + call="r = ulong $name a b" + fi + cat >> "$p.om" <<EOF +note gate driver: stdin is 262144 a lanes then 262144 b lanes (LE u32); stdout the results. +global inb uchar 2097152 +global outb uchar 1048576 +global tailb uchar 1 +fn rdall to void +n = ulong 0 +for t ulong 2097152 +if eq n len inb +break +end +k = read 0 inb n sub len inb n +if le k 0 +exit 91 +end +n = add n ulong k +end +if ne n len inb +exit 91 +end +k = read 0 tailb 0 1 +if ne k 0 +exit 92 +end +end +fn lane o ulong to uint +v = ulong 0 +for j ulong 4 +v = or v shl ulong get inb add o j mul j 8 +end +ret uint v +end +fn main to int +rdall +for i ulong 262144 +a = lane mul i 4 +b = lane add 1048576 mul i 4 +$call +for j ulong 4 +put outb add mul i 4 j uchar and shr r mul j 8 255 +end +end +p = ulong 0 +for t ulong 1048577 +if eq p len outb +break +end +k = write 1 outb p sub len outb p +if le k 0 +exit 93 +end +p = add p ulong k +end +ret 0 +end +EOF + nice -n 19 "$OMC" < "$p.om" > "$p.bin.exe" 2> "$p.err" || { cat "$p.err"; fail "native reference $name compile"; } + [ ! -s "$p.err" ] || { cat "$p.err"; fail "native reference $name compile stderr"; } + chmod +x "$p.bin.exe" + nice -n 19 "$p.bin.exe" < "$B/$2.in" > "$B/$3.ref/$name.bin" || fail "native reference $name exit $?" + done + names=$(sed -n 's/^fn \([A-Za-z0-9_]*\) .*/\1/p' "seed/nki/$1.unit.om" | tr '\n' ' ') + say "REFERENCE $3 native Omega lanes for: $names" +} +# check ID LANE EXPECTREF: run every kernel of ID.py on every target. +check() { + for t in $TARGETS; do + # shellcheck disable=SC2086 # names are [A-Za-z0-9_] words + oracle "$t" check "$B/$1.py" "$B/$2.in" "$B/$3" $names > "$B/$1.$t.log" 2>&1 || return 1 + tee -a "$B/gate.log" < "$B/$1.$t.log" + done +} +for lane in uint32 float32; do + oracle trn3 inputs "$lane" > "$B/$lane.in" 2> "$B/$lane.in.err" || { cat "$B/$lane.in.err"; fail "inputs $lane"; } + say "INPUT $lane 2x262144 lanes sha256=$(sha256sum "$B/$lane.in" | cut -d ' ' -f 1)" +done +lift vecadd float32 vecadd-f32 +lift vecadd uint32 vecadd-u32 +lift ops uint32 ops-u32 +grep -q '^ nisa.tensor_tensor(dst=tc, data1=ta, data2=tb, op=nl.add)$' "$B/vecadd-f32.py" || + fail 'vecadd kernel does not use nisa.tensor_tensor add' +ref vecadd float32 vecadd-f32 +ref vecadd uint32 vecadd-u32 +ref ops uint32 ops-u32 +names=vecadd +check vecadd-f32 float32 vecadd-f32.ref || { cat "$B"/vecadd-f32.*.log; fail 'vecadd float32 differs from native Omega'; } +check vecadd-u32 uint32 vecadd-u32.ref || { cat "$B"/vecadd-u32.*.log; fail 'vecadd uint32 differs from native Omega'; } +names=$(sed -n 's/^fn \([A-Za-z0-9_]*\) .*/\1/p' seed/nki/ops.unit.om | tr '\n' ' ') +check ops-u32 uint32 ops-u32.ref || { cat "$B"/ops-u32.*.log; fail 'ops uint32 differ from native Omega'; } +oracle trn3 limit "$B/vecadd-f32.py" vecadd > "$B/limit.log" 2>&1 || { cat "$B/limit.log"; fail 'kernel accepted a shape outside 128x512 tiles'; } +say "CONTROL limit $(sed -n 1p "$B/limit.log")" + +# Negative controls: each must make the oracle comparison FAIL. +names=vecadd +ALL=$TARGETS +TARGETS=trn3 +neg() { + if check "$1" "$2" "$3"; then fail "negative control $1 passed"; fi + say "CONTROL $1 rejected: $(grep -m 1 '^FAIL\|oracle:' "$B/$1.trn3.log")" +} +# (a) the emitted kernel text changed from add to subtract +sed 's/op=nl.add)/op=nl.subtract)/' "$B/vecadd-f32.py" > "$B/mut-text.py" +cmp -s "$B/vecadd-f32.py" "$B/mut-text.py" && fail 'text mutant unchanged' +neg mut-text float32 vecadd-f32.ref +# (b) the IR BIN subcode changed from add (1) to sub (2) before lifting +[ "$(od -An -j 38 -N 2 -t u1 "$B/vecadd.ir" | tr -s ' ')" = ' 3 1' ] || fail 'vecadd IR BIN is not at offset 38' +cp "$B/vecadd.ir" "$B/mut-ir.ir" +printf '\002' | dd of="$B/mut-ir.ir" bs=1 seek=39 conv=notrunc 2> /dev/null +"$B/irnki" f32 < "$B/mut-ir.ir" > "$B/mut-ir.py" +neg mut-ir float32 vecadd-f32.ref +# (c) one expected lane flipped by one bit +mkdir -p "$B/mut-ref" +cp "$B/vecadd-f32.ref/vecadd.bin" "$B/mut-ref/vecadd.bin" +b0=$(od -An -j 4000 -N 1 -t u1 "$B/mut-ref/vecadd.bin" | tr -d ' ') +printf "\\$(printf '%03o' $((b0 ^ 1)))" | dd of="$B/mut-ref/vecadd.bin" bs=1 seek=4000 conv=notrunc 2> /dev/null +cp "$B/vecadd-f32.py" "$B/mut-ref.py" +neg mut-ref float32 mut-ref +# (d) a kernel set that drops a function +sed '/^ "vecadd": /d' "$B/vecadd-f32.py" > "$B/mut-set.py" +neg mut-set float32 vecadd-f32.ref +# Refusals: exact exit code, the error text on stderr and nothing on stdout. +refuse() { + want=$1; label=$2; shift 2 + set +e + "$B/irnki" "$@" < "$B/r.ir" > "$B/r.out" 2> "$B/r.err" + got=$? + set -e + [ "$got" = "$want" ] || fail "refusal $label exit $got, expected $want" + [ ! -s "$B/r.out" ] || fail "refusal $label wrote stdout" + grep -q '^irnki: ' "$B/r.err" || fail "refusal $label without message" + say "REFUSE $label exit $got $(cat "$B/r.err")" +} +unit() { { printf 'ir\n'; printf '%s\n' "$@"; } | nice -n 19 "$OMC" > "$B/r.ir" || fail "unit $1 IR"; } +cp "$B/vecadd.ir" "$B/r.ir"; refuse 30 usage-extra-arg f32 x +cp "$B/ops.ir" "$B/r.ir"; refuse 24 f32-xor f32 +cp "$B/vecadd.ir" "$B/r.ir"; refuse 30 usage-bad-lane f64 +unit 'fn q a uint b uint to uint' 'ret div a b' 'end'; refuse 24 div +unit 'fn q a uint b uint to uint' 'ret shl a b' 'end'; refuse 24 shl +unit 'fn q a int b int to int' 'ret add a b' 'end'; refuse 25 int-tag +unit 'fn q a ulong b ulong to ulong' 'ret add a b' 'end'; refuse 25 ulong-tag +unit 'fn q a uint b uint to uint' 'ret add mul a b a' 'end'; refuse 29 two-ops +unit 'fn q a uint to uint' 'ret add a a' 'end'; refuse 29 one-param +printf 'OSC1IR\000\002\001\000' > "$B/r.ir"; refuse 21 version +printf 'OSC2IR\000\001\001\000' > "$B/r.ir"; refuse 20 magic +head -c 30 "$B/vecadd.ir" > "$B/r.ir"; refuse 22 truncated +{ cat "$B/vecadd.ir"; printf '\000'; } > "$B/r.ir"; refuse 27 trailing +printf 'OSC1IR\000\001\000\000' > "$B/r.ir"; refuse 26 no-functions +say "HARDWARE NOT_RUN: no Trainium/Inferentia instance; simulator results are not hardware qualification" +say "PASS irnki: kernels from Omega equal native Omega lanes on nki.simulate targets=$ALL; controls on trn3" +sha256sum seed/nki/irnki.om seed/nki/oracle.py seed/nki/*.unit.om "$B/irnki" "$B"/*.py "$B"/*.ir | tee -a "$B/gate.log" diff --git a/seed/nki/irnki.om b/seed/nki/irnki.om new file mode 100644 index 000000000..29ce70766 --- /dev/null +++ b/seed/nki/irnki.om @@ -0,0 +1,528 @@ +note SPDX-License-Identifier: Apache-2.0 +note irnki: OSC IR v1 elementwise scalar functions to AWS NKI kernels at the nki.isa level. +note Wire authority spec/one-layer-format.md. NKI ISA reference (read 2026-10-26): +note https://awsdocs-neuron.readthedocs-hosted.com/en/latest/nki/api/nki.isa.html +note A liftable function is exactly: two parameters and a result of tag 4 (u32), three vregs, +note one block of two instructions, BIN sub dst=2 a,b in {0,1}, then RET 2. +note Lane dtype: uint32 (default, same meaning as the IR) or float32 with argument f32, +note an explicit retyping because IR v1 has no float tag (spec section 10.3 is not produced yet). +note Output is buffered: every refusal happens before the first stdout byte. +global input uchar 2620252 +global output uchar 1048576 +note state slots: 0 input cursor, 1 input size, 2 output size, 3 lane (0 uint32, 1 float32), 4 nfuncs +global state ulong 8 +global names ulong 32 +global namelen ulong 32 +global subs ulong 32 +global lhs ulong 32 +global rhs ulong 32 +text emagic "irnki: MAGIC\n" +text ever "irnki: VERSION\n" +text etrunc "irnki: TRUNCATED\n" +text ecap "irnki: CAPACITY\n" +text eop "irnki: UNSUPPORTED_OP\n" +text etype "irnki: UNSUPPORTED_TAG\n" +text einval "irnki: INVALID\n" +text etrail "irnki: TRAILING\n" +text eio "irnki: IO\n" +text eshape "irnki: NOT_ELEMENTWISE\n" +text eusage "irnki: USAGE irnki [f32] < unit.ir > kernels.py\n" +text th0 "# Generated by seed/nki/irnki.om (seeded Omega) from an OSC IR v1 unit. Do not edit.\n# Level: nki.isa (NISA) instructions on explicit SBUF tiles of 128 partitions x 512.\n# Lane dtype: " +text th1 "\nimport nki\nimport nki.isa as nisa\nimport nki.language as nl\n\nTILE_P = 128\nTILE_F = 512\n" +text tf0 "\n\n@nki.jit\ndef om_" +text tf1 "(a, b):\n assert a.shape == b.shape\n rows, cols = a.shape\n assert rows % TILE_P == 0\n assert cols % TILE_F == 0\n out = nl.ndarray(a.shape, dtype=nl." +text tf2 ", buffer=nl.shared_hbm)\n for m in nl.affine_range(rows // TILE_P):\n for n in nl.affine_range(cols // TILE_F):\n" +text tal0 " t" +text tal1 " = nl.ndarray((TILE_P, TILE_F), dtype=nl." +text tal2 ", buffer=nl.sbuf)\n" +text td0 " nisa.dma_copy(dst=t" +text td1 ", src=" +text tslc "[m * TILE_P:(m + 1) * TILE_P, n * TILE_F:(n + 1) * TILE_F]" +text td2 ")\n" +text tt0 " nisa.tensor_tensor(dst=tc, data1=t" +text tt1 ", data2=t" +text tt2 ", op=nl." +text ts0 " nisa.dma_copy(dst=out" +text ts1 ", src=tc)\n return out\n" +text tk0 "\n\nKERNELS = {\n" +text tk1 " \"" +text tk2 "\": (om_" +text tk3 ", \"" +text tk4 "\"),\n" +text tk5 "}\n" +text tdf "float32" +text tdu "uint32" +text tadd "add" +text tsub "subtract" +text tmul "multiply" +text tand "bitwise_and" +text tor "bitwise_or" +text txor "bitwise_xor" +fn refuse code int to void +k = long 0 +if eq code 20 +k = write 2 emagic 0 len emagic +end +if eq code 21 +k = write 2 ever 0 len ever +end +if eq code 22 +k = write 2 etrunc 0 len etrunc +end +if eq code 23 +k = write 2 ecap 0 len ecap +end +if eq code 24 +k = write 2 eop 0 len eop +end +if eq code 25 +k = write 2 etype 0 len etype +end +if eq code 26 +k = write 2 einval 0 len einval +end +if eq code 27 +k = write 2 etrail 0 len etrail +end +if eq code 28 +k = write 2 eio 0 len eio +end +if eq code 29 +k = write 2 eshape 0 len eshape +end +if eq code 30 +k = write 2 eusage 0 len eusage +end +exit code +end +fn need ok bool to void +if not ok +refuse 26 +end +end +fn rd n ulong to ulong +p = get state 0 +if gt n sub get state 1 p +refuse 22 +end +v = ulong 0 +for j ulong n +v = or v shl ulong get input add p j mul j 8 +end +put state 0 add p n +ret v +end +fn shape ok bool to void +if not ok +refuse 29 +end +end +note Every register and the result must be u32 (tag 4). Tags 0..12 other than 4 are +note unsupported; tags above 12 do not exist in any OSC version. +fn lane t ulong to void +if ne t 4 +refuse 25 +end +end +fn namech c ulong to bool +if and ge c 48 le c 57 +ret true +end +if and ge c 65 le c 90 +ret true +end +if and ge c 97 le c 122 +ret true +end +ret eq c 95 +end +fn same a ulong b ulong to bool +if ne get namelen a get namelen b +ret false +end +for j ulong get namelen a +x = get input add get names a j +y = get input add get names b j +if ne x y +ret false +end +end +ret true +end +note BIN subcodes 1 add, 2 sub, 3 mul, 6 and, 7 or, 8 xor are liftable for uint32 lanes; +note float32 lanes take only add, sub, mul (float bitwise BIN is invalid, spec 10.3). +note div/rem trap on zero and shl/shr trap on wide counts in Omega; NKI has no trap, +note so 4, 5, 9 and 10 are refused rather than silently changed. +fn binsub s ulong to void +need and ge s 1 le s 10 +if or eq s 4 eq s 5 +refuse 24 +end +if or eq s 9 eq s 10 +refuse 24 +end +if and eq get state 3 1 gt s 3 +refuse 24 +end +end +fn loadfn f ulong to void +n = rd 1 +need and ne n 0 le n 63 +put namelen f n +put names f get state 0 +for j ulong n +need namech rd 1 +end +for j ulong f +need not same f j +end +shape eq rd 1 2 +lane rd 1 +shape eq rd 2 3 +for j ulong 3 +lane rd 1 +end +shape eq rd 2 1 +need eq rd 4 0 +shape eq rd 4 2 +shape eq rd 4 2 +if ne rd 1 3 +refuse 24 +end +s = rd 1 +binsub s +put subs f s +need eq rd 2 2 +x = rd 2 +need lt x 2 +put lhs f x +x = rd 2 +need lt x 2 +put rhs f x +if ne rd 1 15 +refuse 24 +end +need eq rd 2 2 +for c ulong 2 +n = rd 2 +need le n 255 +for j ulong n +need ne rd 1 0 +end +end +end +fn emit v ulong to void +p = get state 2 +if ge p len output +refuse 23 +end +put output p uchar v +put state 2 add p 1 +end +note Fragment table: one id per text above, emitted byte for byte. +fn frag k ulong to void +if eq k 0 +for j ulong len th0 +emit ulong get th0 j +end +end +if eq k 1 +for j ulong len th1 +emit ulong get th1 j +end +end +if eq k 2 +for j ulong len tf0 +emit ulong get tf0 j +end +end +if eq k 3 +for j ulong len tf1 +emit ulong get tf1 j +end +end +if eq k 4 +for j ulong len tf2 +emit ulong get tf2 j +end +end +if eq k 5 +for j ulong len tal0 +emit ulong get tal0 j +end +end +if eq k 6 +for j ulong len tal1 +emit ulong get tal1 j +end +end +if eq k 7 +for j ulong len tal2 +emit ulong get tal2 j +end +end +if eq k 8 +for j ulong len td0 +emit ulong get td0 j +end +end +if eq k 9 +for j ulong len td1 +emit ulong get td1 j +end +end +if eq k 10 +for j ulong len tslc +emit ulong get tslc j +end +end +if eq k 11 +for j ulong len td2 +emit ulong get td2 j +end +end +if eq k 12 +for j ulong len tt0 +emit ulong get tt0 j +end +end +if eq k 13 +for j ulong len tt1 +emit ulong get tt1 j +end +end +if eq k 14 +for j ulong len tt2 +emit ulong get tt2 j +end +end +if eq k 15 +for j ulong len ts0 +emit ulong get ts0 j +end +end +if eq k 16 +for j ulong len ts1 +emit ulong get ts1 j +end +end +if eq k 17 +for j ulong len tk0 +emit ulong get tk0 j +end +end +if eq k 18 +for j ulong len tk1 +emit ulong get tk1 j +end +end +if eq k 19 +for j ulong len tk2 +emit ulong get tk2 j +end +end +if eq k 20 +for j ulong len tk3 +emit ulong get tk3 j +end +end +if eq k 21 +for j ulong len tk4 +emit ulong get tk4 j +end +end +if eq k 22 +for j ulong len tk5 +emit ulong get tk5 j +end +end +end +fn dtype to void +if eq get state 3 1 +for j ulong len tdf +emit ulong get tdf j +end +else +for j ulong len tdu +emit ulong get tdu j +end +end +end +fn opname s ulong to void +if eq s 1 +for j ulong len tadd +emit ulong get tadd j +end +end +if eq s 2 +for j ulong len tsub +emit ulong get tsub j +end +end +if eq s 3 +for j ulong len tmul +emit ulong get tmul j +end +end +if eq s 6 +for j ulong len tand +emit ulong get tand j +end +end +if eq s 7 +for j ulong len tor +emit ulong get tor j +end +end +if eq s 8 +for j ulong len txor +emit ulong get txor j +end +end +end +fn fname f ulong to void +for j ulong get namelen f +emit ulong get input add get names f j +end +end +note Parameter register 0 is a, 1 is b; their SBUF tiles are ta and tb. +fn param r ulong to void +emit add 97 r +end +fn tile c ulong to void +frag 5 +emit c +frag 6 +dtype +frag 7 +end +fn load r ulong to void +frag 8 +param r +frag 9 +param r +frag 10 +frag 11 +end +fn kernel f ulong to void +frag 2 +fname f +frag 3 +dtype +frag 4 +tile 97 +tile 98 +tile 99 +load 0 +load 1 +frag 12 +param get lhs f +frag 13 +param get rhs f +frag 14 +opname get subs f +frag 11 +frag 15 +frag 10 +frag 16 +end +fn module to void +frag 0 +dtype +frag 1 +for f ulong get state 4 +kernel f +end +frag 17 +for f ulong get state 4 +frag 18 +fname f +frag 19 +fname f +frag 20 +dtype +frag 21 +end +frag 22 +end +fn args to void +c = argcnt +if eq c 1 +put state 3 0 +ret +end +if ne c 2 +refuse 30 +end +b = new uchar 4 0 +k = argread 1 b 0 4 +if ne k 3 +refuse 30 +end +if or ne get b 0 102 or ne get b 1 51 ne get b 2 50 +refuse 30 +end +put state 3 1 +end +fn main to int +args +n = ulong 0 +for attempt ulong 2620252 +if eq n len input +refuse 23 +end +k = read 0 input n sub len input n +if lt k 0 +refuse 28 +end +if eq k 0 +break +end +n = add n ulong k +end +if eq n len input +refuse 23 +end +put state 1 n +magic = new uchar 7 0 +put magic 0 79 +put magic 1 83 +put magic 2 67 +put magic 3 49 +put magic 4 73 +put magic 5 82 +for j ulong 7 +v = rd 1 +if ne v ulong get magic j +refuse 20 +end +end +if ne rd 1 1 +refuse 21 +end +nf = rd 2 +if gt nf 32 +refuse 23 +end +need ne nf 0 +put state 4 nf +for f ulong nf +loadfn f +end +if ne get state 0 n +refuse 27 +end +module +p = ulong 0 +for attempt ulong 1048576 +if eq p get state 2 +break +end +k = write 1 output p sub get state 2 p +if le k 0 +refuse 28 +end +p = add p ulong k +end +ret 0 +end diff --git a/seed/nki/ops.unit.om b/seed/nki/ops.unit.om new file mode 100644 index 000000000..bfae5008e --- /dev/null +++ b/seed/nki/ops.unit.om @@ -0,0 +1,25 @@ +note Every BIN subcode irnki lifts for uint32 lanes, plus swapped and repeated operands. +fn vaddu a uint b uint to uint +ret add a b +end +fn vsubu a uint b uint to uint +ret sub a b +end +fn vsubr a uint b uint to uint +ret sub b a +end +fn vmulu a uint b uint to uint +ret mul a b +end +fn vandu a uint b uint to uint +ret and a b +end +fn voru a uint b uint to uint +ret or a b +end +fn vxoru a uint b uint to uint +ret xor a b +end +fn vdbl a uint b uint to uint +ret add a a +end diff --git a/seed/nki/oracle.py b/seed/nki/oracle.py new file mode 100644 index 000000000..11b98f191 --- /dev/null +++ b/seed/nki/oracle.py @@ -0,0 +1,134 @@ +# SPDX-License-Identifier: Apache-2.0 +# interop oracle, not Omega-native; never generates kernels. +# +# Host dependency (oracle only): CPython 3.12 + nki 0.7.0 (Apache-2.0, AWS) + numpy 2.2.6. +# Omega replacement: none yet. The kernels come from seed/nki/irnki.om; the expected +# values come from a native Omega program built by gate-irnki.sh. This script only +# (1) writes deterministic input lanes and (2) runs the emitted kernels on the public +# NKI CPU simulator (nki.simulate) and compares the result bits with the Omega values. +# +# oracle.py version +# oracle.py inputs uint32|float32 > in.bin a lanes then b lanes, little-endian +# oracle.py check kernels.py in.bin refdir name... exit 0 all equal, 1 any differ +# oracle.py limit kernels.py name exit 0 if a (128, 500) call is refused +import importlib.util +import os +import sys + +ROWS, COLS = 256, 1024 +N = ROWS * COLS + + +def die(msg, code): + sys.stderr.write("oracle: " + msg + "\n") + sys.exit(code) + + +try: + import numpy as np + import nki +except Exception as ex: # the gate maps exit 3 to NOT_RUN + die("cannot import the simulator: %s: %s" % (type(ex).__name__, ex), 3) + + +def load(path): + spec = importlib.util.spec_from_file_location("omnki", path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod.KERNELS + + +def inputs(dtype): + rng = np.random.default_rng(20261026) + a = rng.integers(0, 2 ** 32, N, dtype=np.uint64).astype(np.uint32) + b = rng.integers(0, 2 ** 32, N, dtype=np.uint64).astype(np.uint32) + if dtype == "uint32": + edge = [0, 1, 2, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFF, 0x10000, 0xFFFFFFFE, 0xFFFFFFFF] + elif dtype == "float32": + # +0 -0 +inf -inf qNaN max -max min-normal smallest/largest subnormal 1 -1 1+ulp 2^24 + edge = [0x00000000, 0x80000000, 0x7F800000, 0xFF800000, 0x7FC00000, 0x7F7FFFFF, + 0xFF7FFFFF, 0x00800000, 0x00000001, 0x007FFFFF, 0x3F800000, 0xBF800000, + 0x3F800001, 0x4B800000] + # the rest: half raw bit patterns (all exponents), half normal values near 1 + k = N // 2 + a[k:] = rng.standard_normal(N - k).astype(np.float32).view(np.uint32) + b[k:] = rng.standard_normal(N - k).astype(np.float32).view(np.uint32) + else: + die("inputs: dtype must be uint32 or float32", 2) + e = np.array(edge, dtype=np.uint32) + m = len(edge) + a[: m * m] = np.repeat(e, m) + b[: m * m] = np.tile(e, m) + sys.stdout.buffer.write(a.astype("<u4").tobytes() + b.astype("<u4").tobytes()) + + +def check(path, inpath, refdir, names): + kernels = load(path) + if sorted(kernels) != sorted(names): + die("kernel set %s differs from expected %s" % (sorted(kernels), sorted(names)), 1) + raw = np.frombuffer(open(inpath, "rb").read(), dtype="<u4") + if raw.size != 2 * N: + die("input size %d lanes, expected %d" % (raw.size, 2 * N), 1) + target = os.environ.get("NEURON_PLATFORM_TARGET_OVERRIDE", "default") + bad = 0 + for name in names: + fn, dtype = kernels[name] + a = raw[:N].copy().reshape(ROWS, COLS) + b = raw[N:].copy().reshape(ROWS, COLS) + if dtype == "float32": + a, b = a.view(np.float32), b.view(np.float32) + elif dtype != "uint32": + die("%s: unknown lane dtype %s" % (name, dtype), 1) + got = np.asarray(nki.simulate(fn)(a, b)) + if got.shape != (ROWS, COLS) or got.dtype.itemsize != 4: + die("%s: result shape %s dtype %s" % (name, got.shape, got.dtype), 1) + g = got.reshape(N).view(np.uint32) + r = np.frombuffer(open(os.path.join(refdir, name + ".bin"), "rb").read(), dtype="<u4") + if r.size != N: + die("%s: reference size %d lanes" % (name, r.size), 1) + diff = g != r + nanpair = 0 + if dtype == "float32": + # NaN payload and sign are not part of the IEEE result; compare NaN as a class. + gn = (g & 0x7F800000 == 0x7F800000) & (g & 0x007FFFFF != 0) + rn = (r & 0x7F800000 == 0x7F800000) & (r & 0x007FFFFF != 0) + nanpair = int((diff & gn & rn).sum()) + diff = diff & ~(gn & rn) + n = int(diff.sum()) + state = "PASS" if n == 0 else "FAIL" + print("%s target=%s kernel=%s dtype=%s lanes=%d mismatches=%d nan_class_only=%d" + % (state, target, name, dtype, N, n, nanpair)) + if n: + i = int(np.flatnonzero(diff)[0]) + print(" first lane %d a=%08x b=%08x simulator=%08x omega=%08x" + % (i, raw[i], raw[N + i], g[i], r[i])) + bad += 1 + sys.exit(1 if bad else 0) + + +def limit(path, name): + fn, dtype = load(path)[name] + a = np.zeros((128, 500), dtype=np.dtype(dtype)) + try: + nki.simulate(fn)(a, a) + except Exception as ex: + print("REFUSED kernel=%s shape=(128, 500) %s" % (name, type(ex).__name__)) + sys.exit(0) + die("%s accepted shape (128, 500)" % name, 1) + + +def main(argv): + if len(argv) == 2 and argv[1] == "version": + print("nki %s numpy %s python %s" % (nki.__version__, np.__version__, sys.version.split()[0])) + elif len(argv) == 3 and argv[1] == "inputs": + inputs(argv[2]) + elif len(argv) >= 6 and argv[1] == "check": + check(argv[2], argv[3], argv[4], argv[5:]) + elif len(argv) == 4 and argv[1] == "limit": + limit(argv[2], argv[3]) + else: + die("usage: see header", 2) + + +if __name__ == "__main__": + main(sys.argv) diff --git a/seed/nki/setup-oracle.sh b/seed/nki/setup-oracle.sh new file mode 100755 index 000000000..9abe2b2c8 --- /dev/null +++ b/seed/nki/setup-oracle.sh @@ -0,0 +1,43 @@ +#!/bin/sh +# Prepare the NKI simulator oracle for seed/nki/gate-irnki.sh in DIR (user files only, no +# root, no account). Interop oracle, not Omega-native; nothing here generates kernels. +# The nki wheel is published for x86_64 only, so on AArch64 it runs as an x86_64 CPython +# under qemu-user with an x86_64 glibc sysroot. Every download is pinned by sha256. +# Host tools used: curl, sha256sum, tar, dpkg-deb, unzip. +# seed/nki/setup-oracle.sh DIR then: NKI_ORACLE_DIR=DIR seed/nki/gate-irnki.sh +set -eu +[ $# -eq 1 ] || { echo 'usage: setup-oracle.sh DIR' >&2; exit 2; } +D=$1 +mkdir -p "$D/dl" +D=$(cd "$D" && pwd) +U=http://archive.ubuntu.com/ubuntu/pool/main +PY=https://files.pythonhosted.org/packages +# sha256 file url (licences: README.md, "Oracle stack") +cat > "$D/dl/pins" <<EOF +6a79e922e50006b601f29e688407659da1c2b86ebcd4e9c7254cf234be8b89de cpython.tar.gz https://github.com/astral-sh/python-build-standalone/releases/download/20261026/cpython-3.12.16%2B20261026-x86_64-unknown-linux-gnu-install_only.tar.gz +c73711af02b97cd5e2667e735d9c06890c57165517110ca4e646c95a7083158d qemu-user.deb http://deb.debian.org/debian/pool/main/q/qemu/qemu-user_10.0.13+ds-0+deb13u1_arm64.deb +ff5557d99b51f761c4b7c92368b9cc45565eda17df9bf9eb4b134d09825008be libc6.deb $U/g/glibc/libc6_2.39-0ubuntu8.9_amd64.deb +aa7fadbe33b78bcf99885318040601c550c208929565b179891d9a3cc2aa68cd libgcc-s1.deb $U/g/gcc-14/libgcc-s1_14.2.0-4ubuntu2~24.04.1_amd64.deb +a51f8de7829211db961a31f02158058ad1a95f92ac6d0a5dff6350e2821c54c0 libstdcxx6.deb $U/g/gcc-14/libstdc++6_14.2.0-4ubuntu2~24.04.1_amd64.deb +376249c8de139568221dbb242318cc8cb8f02299e3a62b7432948e1754fbddf9 zlib1g.deb $U/z/zlib/zlib1g_1.3.dfsg-3.1ubuntu2.3_amd64.deb +fd83c01228a688733f1ded5201c678f0c53ecc1006ffbc404db9f7a899ac6249 numpy.whl $PY/8c/3d/1e1db36cfd41f895d266b103df00ca5b3cbe965184df824dec5c08c6b803/numpy-2.2.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl +1b255acada256d1fa8c35ed07b5f6d18bc21d1556f842fbc2d5718aea2cd9e55 ml_dtypes.whl $PY/d8/a9/b98b86426c24900b0c754aad006dce2863df7ce0bb2bcc2c02f9cc7e8489/ml_dtypes-0.5.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl +f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548 typing_extensions.whl $PY/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl +03543beda64b5a74e88a90320a01bdb4b1c5865f50a14b2f17e96d4c596f0c4e nki.whl https://pip.repos.neuron.amazonaws.com/nki/nki-0.7.0%2B37713544100.gfede04bb-cp312-cp312-linux_x86_64.whl +EOF +while read -r sum file url; do + f=$D/dl/$file + [ -f "$f" ] && [ "$(sha256sum "$f" | cut -d ' ' -f 1)" = "$sum" ] && continue + curl -fsSL -o "$f.part" "$url" + [ "$(sha256sum "$f.part" | cut -d ' ' -f 1)" = "$sum" ] || { echo "setup-oracle: $file sha256 differs from pin" >&2; exit 1; } + mv "$f.part" "$f" +done < "$D/dl/pins" +rm -rf "$D/python" "$D/qemu" "$D/sysroot" "$D/site" +tar -xzf "$D/dl/cpython.tar.gz" -C "$D" +dpkg-deb -x "$D/dl/qemu-user.deb" "$D/qemu" +mkdir -p "$D/sysroot" "$D/site" +for p in libc6 libgcc-s1 libstdcxx6 zlib1g; do dpkg-deb -x "$D/dl/$p.deb" "$D/sysroot"; done +[ -e "$D/sysroot/lib64" ] || ln -s usr/lib64 "$D/sysroot/lib64" +[ -e "$D/sysroot/lib" ] || ln -s usr/lib "$D/sysroot/lib" +for w in numpy ml_dtypes typing_extensions nki; do unzip -q -o "$D/dl/$w.whl" -d "$D/site"; done +echo "setup-oracle: ready; run NKI_ORACLE_DIR=$D seed/nki/gate-irnki.sh" diff --git a/seed/nki/vecadd.unit.om b/seed/nki/vecadd.unit.om new file mode 100644 index 000000000..e839d6327 --- /dev/null +++ b/seed/nki/vecadd.unit.om @@ -0,0 +1,5 @@ +note vecadd: out[i] = a[i] + b[i]. irnki lifts this scalar function to an NKI tile kernel. +note IR v1 carries uint lanes; `irnki f32` retypes the lanes to float32 (see README.md). +fn vecadd a uint b uint to uint +ret add a b +end