Skip to content

Commit 9b2add0

Browse files
committed
perf,fix(gemm,jit,tests,bench): update GEMM, JIT, conv/CUDA tests, and benchmarks
1 parent c28d82a commit 9b2add0

18 files changed

Lines changed: 16398 additions & 16309 deletions

‎.github/workflows/ci.yml‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ jobs:
6161
strategy:
6262
fail-fast: false
6363
matrix:
64-
os: [ubuntu-latest, windows-latest, macos-latest]
64+
os: [ubuntu-24.04, windows-latest, macos-latest]
6565
defaults:
6666
run:
6767
shell: bash
@@ -83,8 +83,9 @@ jobs:
8383
runs-on: ${{ matrix.os }}
8484
strategy:
8585
fail-fast: false
86+
# ubuntu-latest is now 26.04, which setup-python has no Python 3.9 for: the wheel jobs are pinned to 24.04
8687
matrix:
87-
os: [ubuntu-latest, windows-latest, macos-latest]
88+
os: [ubuntu-24.04, windows-latest, macos-latest]
8889
python: ["3.9", "3.10", "3.11", "3.12", "3.13"]
8990
exclude:
9091
# Not verified that actions/setup-python offers 3.9 for the Apple Silicon runners; remove to try it.
@@ -109,7 +110,7 @@ jobs:
109110
python tests/test_python_package.py
110111
python tests/test_python_ergonomics.py
111112
- name: Stub freshness
112-
if: matrix.os == 'ubuntu-latest' && matrix.python == '3.12'
113+
if: matrix.os == 'ubuntu-24.04' && matrix.python == '3.12'
113114
run: |
114115
python tools/gen_stubs.py
115116
git diff --exit-code -- python/oxideon

‎.github/workflows/release-python.yml‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,17 @@ permissions:
1010
contents: read
1111

1212
jobs:
13+
# A tag that does not match the crate version would upload a wheel under the wrong version (PyPI never lets a version be re-used).
14+
check-version:
15+
runs-on: ubuntu-latest
16+
if: startsWith(github.ref, 'refs/tags/v')
17+
steps:
18+
- uses: actions/checkout@v4
19+
- name: Tag matches the workspace version
20+
run: |
21+
version=$(grep -m1 '^version' Cargo.toml | cut -d'"' -f2)
22+
test "v$version" = "${GITHUB_REF_NAME}" || { echo "tag ${GITHUB_REF_NAME} != Cargo.toml version v$version"; exit 1; }
23+
1324
linux:
1425
runs-on: ${{ matrix.os }}
1526
strategy:
@@ -102,10 +113,10 @@ jobs:
102113
strategy:
103114
fail-fast: false
104115
matrix:
105-
os: [ubuntu-latest, windows-latest, macos-14]
116+
os: [ubuntu-24.04, windows-latest, macos-14]
106117
python: ["3.9", "3.10", "3.11", "3.12", "3.13"]
107118
include:
108-
- os: ubuntu-latest
119+
- os: ubuntu-24.04
109120
artifact: wheels-linux-x86_64
110121
- os: windows-latest
111122
artifact: wheels-windows-x86_64
@@ -136,7 +147,7 @@ jobs:
136147
name: Publish to PyPI
137148
runs-on: ubuntu-latest
138149
if: startsWith(github.ref, 'refs/tags/v')
139-
needs: [linux, windows, macos, sdist, test-wheels]
150+
needs: [check-version, linux, windows, macos, sdist, test-wheels]
140151
permissions:
141152
id-token: write
142153
environment:
@@ -147,4 +158,6 @@ jobs:
147158
pattern: wheels-*
148159
path: dist
149160
merge-multiple: true
161+
- name: Check the package metadata and README rendering
162+
run: python -m pip install twine && python -m twine check --strict dist/*
150163
- uses: pypa/gh-action-pypi-publish@release/v1

‎README.md‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,15 @@ Most deep learning stacks force a trade-off: either you use Python on top of a m
3030

3131
## Getting Started
3232

33+
### Install from PyPI
34+
35+
```bash
36+
pip install oxideon # prebuilt wheels: Linux (x86_64, aarch64), macOS (Intel, Apple Silicon), Windows (x86_64); Python 3.9+
37+
```
38+
39+
One wheel serves every supported Python version (the extension is `abi3`). On other platforms `pip` builds from the source
40+
distribution, which needs a Rust toolchain (1.85+).
41+
3342
### Build from source (Python + Rust)
3443

3544
```bash
@@ -350,7 +359,7 @@ Environment notes (mostly Windows):
350359
cannot show them, run Python with `-X utf8` (or set `PYTHONUTF8=1`).
351360
- **CUDA kernels.** The `.cu` kernels need NVRTC. Without it the CUDA tests print `skipped: no CUDA device / NVRTC` and pass, and the
352361
operations fall back to the host. Install it with `pip install --target <dir> nvidia-cuda-nvrtc-cu12` and set
353-
`OXIDEON_NVRTC_SITE=<dir>` (see `backend/nvrtc.rs` for the search order); `cuda_bench` then reports its launched kernels.
362+
`OXIDEON_NVRTC_SITE=<dir>` (see `backend/nvrtc.rs` for the search order); `cuda_bench` then reports its launched kernels. Set `OXIDEON_REQUIRE_CUDA=1` on a machine that has a GPU so that `cuda_end_to_end` fails, instead of skipping, when NVRTC is missing.
354363
- **Interop example.** `examples/python_interop_showcase.py` also needs `pillow`, `pandas`, `polars`, `networkx` and `sympy`.
355364

356365
---

‎benchmarks/accuracy_vs_pytorch.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
"""
1414
import math
1515
import os
16+
import shutil
1617
import subprocess
1718
import sys
1819
import tempfile
@@ -200,6 +201,13 @@ def verdict_of(bw, bm):
200201
def measure(only=()):
201202
"""Runs the cases (all, or the names in `only`); returns {name: (worst_ox, worst_torch, x_better, mean_ox, mean_torch, x_better, verdict)}."""
202203
work = Path(tempfile.mkdtemp(prefix="oxideon_accuracy_"))
204+
try:
205+
return _measure(only, work)
206+
finally:
207+
shutil.rmtree(work, ignore_errors=True) # the inputs and outputs are tens of megabytes per run
208+
209+
210+
def _measure(only, work):
203211
manifest = []
204212
selected = {k: v for k, v in cases.items() if not only or k in only}
205213
for name, (inputs, _, _) in selected.items():

‎benchmarks/core_ops_bench_compare.py‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,29 @@
4040
ALL_MODES = ["fastest", "balanced", "highest"]
4141
MARKDOWN = "--markdown" in sys.argv
4242
WITH_ACCURACY = "--no-accuracy" not in sys.argv
43-
MODES = ALL_MODES
44-
REPEAT = int(sys.argv[sys.argv.index("--repeat") + 1]) if "--repeat" in sys.argv else 1
45-
if "--modes" in sys.argv:
46-
MODES = sys.argv[sys.argv.index("--modes") + 1].split(",")
43+
44+
45+
def option(flag, default):
46+
"""The value after `flag` (a usage error if there is none)."""
47+
if flag not in sys.argv:
48+
return default
49+
i = sys.argv.index(flag)
50+
if i + 1 >= len(sys.argv) or sys.argv[i + 1].startswith("--"):
51+
sys.exit(f"{flag} needs a value (see the docstring of {Path(__file__).name})")
52+
return sys.argv[i + 1]
53+
54+
55+
MODES = option("--modes", ",".join(ALL_MODES)).split(",")
56+
for _mode in MODES:
57+
# Oxideon only warns about an unknown OXIDEON_PRECISION and runs in balanced, which would label balanced numbers with the typo
58+
if _mode not in ALL_MODES:
59+
sys.exit(f"unknown precision mode {_mode!r}; use a comma-separated list of {', '.join(ALL_MODES)}")
60+
try:
61+
REPEAT = int(option("--repeat", "1"))
62+
except ValueError:
63+
sys.exit("--repeat needs a whole number")
64+
if REPEAT < 1:
65+
sys.exit("--repeat needs a positive number")
4766

4867
# benchmarks whose time depends on the precision mode (the others are measured once, in the default mode)
4968
MODE_DEPENDENT = {"gelu 1M", "matmul 512", "matmul 1024", "matmul 256x4096x256", "conv2d 8x16x64x64 k3", "conv2d 4x64x56x56 k3", "mlp train step b256"}

‎crates/oxideon-core/src/gemm.rs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,14 +132,16 @@ pub fn precision_mode() -> PrecisionMode {
132132
if v != MODE_UNSET {
133133
return from(v);
134134
}
135-
let mode = match std::env::var("OXIDEON_PRECISION") {
135+
// threads that reach this point together all get the same answer, and the warning is printed once
136+
static FROM_ENV: std::sync::OnceLock<PrecisionMode> = std::sync::OnceLock::new();
137+
let mode = *FROM_ENV.get_or_init(|| match std::env::var("OXIDEON_PRECISION") {
136138
Ok(n) => PrecisionMode::parse(&n).unwrap_or_else(|| {
137139
// a typo must not silently change the numerics
138140
eprintln!("oxideon: ignoring OXIDEON_PRECISION={n:?} (expected fastest, balanced or highest); using balanced");
139141
PrecisionMode::Balanced
140142
}),
141143
Err(_) => PrecisionMode::Balanced,
142-
};
144+
});
143145
// a concurrent explicit `set_precision_mode` wins over the environment
144146
let _ = PRECISION.compare_exchange(MODE_UNSET, mode as u8, std::sync::atomic::Ordering::Relaxed, std::sync::atomic::Ordering::Relaxed);
145147
from(PRECISION.load(std::sync::atomic::Ordering::Relaxed))

‎crates/oxideon-core/src/grad_checkpoint.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ mod tests {
8080
let x = Tensor::from_slice(&[1.0f32; 64], &[64]).unwrap();
8181
x.set_requires_grad(true).unwrap();
8282
let d = std::sync::Arc::clone(&drop);
83-
let y = checkpoint(move |ins| d.forward(&ins[0]), &[x.clone()]).unwrap();
83+
let y = checkpoint(move |ins| d.forward(&ins[0]), std::slice::from_ref(&x)).unwrap();
8484
let before = crate::rng::get_rng_state();
8585
y.sum().unwrap().backward().unwrap();
8686
// x = 1, so y is exactly the mask and d(sum y)/dx must be that same mask

‎crates/oxideon-core/src/nn/functional_ext.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -841,7 +841,7 @@ mod fused_layer_norm_tests {
841841
let second = |f: &dyn Fn(&Tensor) -> Tensor| {
842842
let x = t(4 * 6, &[4, 6], 0.5).requires_grad_(true);
843843
let y = f(&x).mul(&t(24, &[4, 6], 7.0)).unwrap().sum().unwrap();
844-
let g = crate::tensor::grad(&[y], &[x.clone()], None, true).unwrap()[0].clone().unwrap();
844+
let g = crate::tensor::grad(&[y], std::slice::from_ref(&x), None, true).unwrap()[0].clone().unwrap();
845845
let z = g.square().unwrap().sum().unwrap();
846846
crate::tensor::grad(&[z], &[x], None, false).unwrap()[0].clone().unwrap()
847847
};

‎crates/oxideon-core/src/trace.rs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ mod tests {
200200
let x = Tensor::randn(&[3, 4]).unwrap();
201201

202202
let eager = l2.forward(&l1.forward(&x).unwrap().relu().unwrap()).unwrap();
203-
let compiled = trace_and_compile(&[x.clone()], |ins| {
203+
let compiled = trace_and_compile(std::slice::from_ref(&x), |ins| {
204204
let h = l1.forward(&ins[0])?.relu()?;
205205
Ok(vec![l2.forward(&h)?])
206206
})
@@ -216,7 +216,7 @@ mod tests {
216216
fn unsupported_ops_are_rejected_instead_of_frozen_into_constants() {
217217
let x = Tensor::from_slice(&[1.0f32, 2.0, 3.0, 4.0], &[2, 2]).unwrap();
218218
// `sum_axis` has no graph lowering: tracing must say so, not bake in this call's value
219-
let r = trace_and_compile(&[x.clone()], |ins| Ok(vec![ins[0].sum_axis(1, false)?]));
219+
let r = trace_and_compile(std::slice::from_ref(&x), |ins| Ok(vec![ins[0].sum_axis(1, false)?]));
220220
assert!(r.is_err(), "an unsupported op must not silently trace");
221221
assert!(format!("{:?}", r.err().unwrap()).contains("not supported"));
222222
}
@@ -228,10 +228,10 @@ mod tests {
228228
let w = Tensor::randn(&[4, 3, 3, 3]).unwrap();
229229
let b = Tensor::randn(&[4]).unwrap();
230230
for (stride, pad, dil) in [((1, 1), (1, 1), (1, 1)), ((2, 2), (1, 1), (1, 1)), ((1, 2), (0, 2), (1, 1)), ((1, 1), (2, 2), (2, 2)), ((3, 2), (0, 1), (1, 1))] {
231-
let compiled = trace_and_compile(&[x.clone()], |ins| Ok(vec![ins[0].conv2d(&w, Some(&b), stride, pad, dil)?])).unwrap();
231+
let compiled = trace_and_compile(std::slice::from_ref(&x), |ins| Ok(vec![ins[0].conv2d(&w, Some(&b), stride, pad, dil)?])).unwrap();
232232
// different data than the traced call: the lowered conv must be the real conv, not a replay
233233
let x2 = Tensor::randn(&[2, 3, 11, 10]).unwrap();
234-
let got = compiled.run(&[x2.clone()]).unwrap()[0].to_vec::<f32>().unwrap();
234+
let got = compiled.run(std::slice::from_ref(&x2)).unwrap()[0].to_vec::<f32>().unwrap();
235235
let want = x2.conv2d(&w, Some(&b), stride, pad, dil).unwrap().to_vec::<f32>().unwrap();
236236
for (a, b) in got.iter().zip(&want) {
237237
assert!((a - b).abs() < 1e-3, "stride {stride:?} pad {pad:?} dil {dil:?}: {a} vs {b}");

‎crates/oxideon-core/src/train_loop.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,9 @@ impl TrainLoop {
256256
if self.config.checkpoint_every > 0 && step % self.config.checkpoint_every == 0 && self.checkpoints.is_some() {
257257
let (e, m) = if epoch_over { (epoch + 1, 0) } else { (epoch, micro) };
258258
let st = self.snapshot(model, opt, e, step, m)?;
259-
self.checkpoints.as_mut().unwrap().save(&st, false)?;
259+
if let Some(ck) = self.checkpoints.as_mut() {
260+
ck.save(&st, false)?;
261+
}
260262
}
261263
let mut stop = done(step, &self.config);
262264
for cb in &mut self.callbacks {

0 commit comments

Comments
 (0)