Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.
Rust agent-skillsai-agentsclaude-codeclaude-code-plugincodexdeveloper-toolsffimcpmcp-servernapi-rsnodejsoptimizationperformanceprofilerpyo3pythonrewrite-it-in-rustrubyrusttypescript
python: port functions that take or return NumPy arrays (#49)
chessMane2c984d92a20
diff --git a/README.md b/README.mdindex 9bd7089..a44301b 100644--- a/README.md+++ b/README.md@@ -102,7 +102,7 @@ fast-anything ports the outermost loop it can, not the tiny function called insi| C and C++ (gcc, clang or Intel oneAPI icx/icpx: `clang -O2 main.c lib.c`) | the same C bridge, through LoadLibrary or dlopen | ✅ || C# / .NET 8+ (`dotnet run -c Release`) | the same C bridge, through NativeLibrary; profiled with EventPipe, nothing to install | ✅ |-It ports top-level, deterministic functions that take plain data (numbers, strings, lists, dicts, typed arrays…), including ones in your entry script when its main code sits under `if __name__ == "__main__":` (or `if __FILE__ == $0`, or `if (import.meta.main)` / `if (require.main === module)`). In Python that means module-level functions and `@staticmethod`s (dataclasses and NamedTuples count as plain data), in Java, C# and PHP static methods (and PHP functions), in Go plain functions, in C and C++ free functions and static methods. `scan` says why anything else can't move yet.+It ports top-level, deterministic functions that take plain data (numbers, strings, lists, dicts, typed arrays…), including ones in your entry script when its main code sits under `if __name__ == "__main__":` (or `if __FILE__ == $0`, or `if (import.meta.main)` / `if (require.main === module)`). In Python that means module-level functions and `@staticmethod`s (dataclasses, NamedTuples and numeric NumPy arrays count as plain data), in Java, C# and PHP static methods (and PHP functions), in Go plain functions, in C and C++ free functions and static methods. `scan` says why anything else can't move yet.With Intel oneAPI on Windows, run fast-anything from a shell where `setvars.bat` ran (it sets up the linker). SYCL kernels run on the device and aren't ported; with `-fsycl`, only host functions are profiled and ported.diff --git a/src/python.rs b/src/python.rsindex 5d9949c..3caf1d9 100644--- a/src/python.rs+++ b/src/python.rs@@ -13,6 +13,8 @@ use std::process::{Command, Output, Stdio};const RUNNER: &str = include_str!("python/runner.py");const PYO3: &str = "0.30";+/// rust-numpy, for NDArray parameters and results; its versions follow PyO3's.+const NUMPY: &str = "0.30";pub const DISABLE_ENV: &str = "FAST_ANYTHING_DISABLE";pub fn is_python(program: &str) -> bool {@@ -187,6 +189,13 @@ fn rust_type_in(annotation: &str, owned: bool, known: &dyn Fn(&str) -> Option<St_ => {if let Some(t) = known(a) {t+ } else if let Some(x) = inner(&["NDArray", "npt.NDArray", "np.typing.NDArray", "numpy.typing.NDArray"]) {+ let elem = numpy_elem(x)?;+ if owned {+ format!("Py<numpy::PyArrayDyn<{elem}>>")+ } else {+ format!("numpy::PyReadonlyArrayDyn<'_, {elem}>")+ }} else if let Some(x) = inner(&["list", "List", "Sequence"]) {format!("Vec<{}>", rust_type_in(x, true, known)?)} else if let Some(x) = inner(&["tuple", "Tuple"]) {@@ -219,6 +228,99 @@ fn rust_type_in(annotation: &str, owned: bool, known: &dyn Fn(&str) -> Option<St})}+/// Rust element type for a NumPy dtype in NDArray[...]: np.float64 -> f64.+fn numpy_elem(dtype: &str) -> Option<&'static str> {+ let d = dtype.trim_start_matches("numpy.").trim_start_matches("np.");+ Some(match d {+ "float64" | "double" => "f64",+ "float32" | "single" => "f32",+ "int64" => "i64",+ "int32" => "i32",+ "int16" => "i16",+ "int8" => "i8",+ "uint64" => "u64",+ "uint32" => "u32",+ "uint16" => "u16",+ "uint8" => "u8",+ "bool" | "bool_" => "bool",+ _ => return None,+ })+}++/// NumPy's name for a dtype string as recorded ("<f8" -> float64).+fn dtype_name(dtype: &str) -> &str {+ match dtype.trim_start_matches(['<', '>', '|', '=']) {+ "f8" => "float64",+ "f4" => "float32",+ "i8" => "int64",+ "i4" => "int32",+ "i2" => "int16",+ "i1" => "int8",+ "u8" => "uint64",+ "u4" => "uint32",+ "u2" => "uint16",+ "u1" => "uint8",+ "b1" => "bool",+ other => other,+ }+}++/// A recorded array as Python would show it: array([1.0, 2.5], dtype=float64), or just its shape.+fn array_value(dtype: &str, shape: &[Value], data: &str) -> String {+ let kind = dtype.trim_start_matches(['<', '>', '|', '=']);+ let name = dtype_name(dtype);+ let dims: Vec<String> = shape.iter().map(|d| d.to_string()).collect();+ let size: usize = kind.get(1..).and_then(|n| n.parse().ok()).unwrap_or(0);+ let bytes = base64_decode(data).filter(|_| dims.len() == 1 && size > 0 && size <= 8 && !dtype.starts_with('>'));+ let Some(bytes) = bytes else {+ let trailing = if dims.len() == 1 { "," } else { "" };+ return format!("array(shape=({}{trailing}), dtype={name})", dims.join(", "));+ };+ let mut values: Vec<String> = bytes+ .chunks_exact(size)+ .take(8)+ .map(|c| {+ let mut b = [0u8; 8];+ b[..size].copy_from_slice(c);+ match kind.as_bytes()[0] {+ b'f' if size == 8 => format!("{:?}", f64::from_le_bytes(b)),+ b'f' => format!("{:?}", f32::from_le_bytes([b[0], b[1], b[2], b[3]])),+ b'b' => (if b[0] != 0 { "True" } else { "False" }).to_string(),+ b'i' => {+ let shift = 64 - 8 * size as u32;+ ((i64::from_le_bytes(b) << shift) >> shift).to_string()+ }+ _ => u64::from_le_bytes(b).to_string(),+ }+ })+ .collect();+ if bytes.len() / size > 8 {+ values.push("…".into());+ }+ format!("array([{}], dtype={name})", values.join(", "))+}++fn base64_decode(text: &str) -> Option<Vec<u8>> {+ let digit = |c: u8| match c {+ b'A'..=b'Z' => Some(c - b'A'),+ b'a'..=b'z' => Some(c - b'a' + 26),+ b'0'..=b'9' => Some(c - b'0' + 52),+ b'+' => Some(62),+ b'/' => Some(63),+ _ => None,+ };+ let (mut out, mut acc, mut bits) = (Vec::new(), 0u32, 0);+ for c in text.bytes().filter(|&c| c != b'=') {+ acc = (acc << 6) | digit(c)? as u32;+ bits += 6;+ if bits >= 8 {+ bits -= 8;+ out.push((acc >> bits) as u8);+ }+ }+ Some(out)+}+/// Split "a,b[c,d],e" on top-level commas.fn split_top(s: &str) -> Vec<String> {let (mut depth, mut cur, mut out) = (0, String::new(), vec![]);@@ -400,16 +502,17 @@ pub fn lib_rs(hs: &Hotspot, port: &Port) -> String {)}-fn cargo_toml(port: &Port) -> String {+fn cargo_toml(port: &Port, numpy: bool) -> String {format!("# Rust port of {id}, generated by fast-anything.\n\[package]\nname = \"{ext}\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\n\n\[lib]\nname = \"{ext}\"\ncrate-type = [\"cdylib\"]\n\n\- [dependencies]\npyo3 = {{ version = \"{PYO3}\", features = [\"extension-module\", \"abi3-py310\"] }}\n\n\+ [dependencies]\npyo3 = {{ version = \"{PYO3}\", features = [\"extension-module\", \"abi3-py310\"] }}\n{numpy}\n\[profile.release]\nopt-level = 3\nlto = \"fat\"\ncodegen-units = 1\n\n\# A crate of its own, even inside another Cargo workspace.\n[workspace]\n",id = port.id,ext = port.ext,+ numpy = if numpy { format!("numpy = \"{NUMPY}\"\n") } else { String::new() },)}@@ -449,6 +552,14 @@ fn py_value(v: &Value) -> String {format!("__import__('base64').b64decode({s:?})")}Some((tag, Value::String(s))) if tag == "$float" => format!("float({s:?})"),+ Some((tag, Value::Array(p))) if tag == "$ndarray" && p.len() == 3 => array_value(+ p[0].as_str().unwrap_or_default(),+ p[1].as_array().map(Vec::as_slice).unwrap_or_default(),+ p[2].as_str().unwrap_or_default(),+ ),+ Some((tag, Value::Array(p))) if tag == "$npscalar" && p.len() == 2 => {+ format!("np.{}({})", dtype_name(p[0].as_str().unwrap_or_default()), py_value(&p[1]))+ }Some((tag, Value::Array(parts))) if tag == "$obj" && parts.len() == 3 => {let class = parts[1].as_str().unwrap_or_default();let fields: Vec<String> = parts[2]@@ -515,6 +626,9 @@ pub fn task_md(hs: &Hotspot, helpers: &[Hotspot], port: &Port, crate_dir: &Path)}notes.push('\n');}+ if lib_rs(hs, port).contains("numpy::") {+ notes.push_str("- Note: NDArray parameters arrive as `numpy::PyReadonlyArrayDyn` (`.as_array()` gives an ndarray view, `.as_slice()` a slice when contiguous); return arrays as `Py<numpy::PyArrayDyn<T>>`, e.g. `numpy::ndarray::Array::from(vec).into_dyn().into_pyarray(py).unbind()` with `use numpy::IntoPyArray`. verify compares shape, dtype and values.\n");+ }for p in &hs.params {if let Some(d) = p.default.as_deref().filter(|d| rust_default(d).is_none()) {notes.push_str(&format!(@@ -560,7 +674,7 @@ pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Relet dir = ctx.crate_dir(port);fs::create_dir_all(dir.join("src"))?;fs::create_dir_all(dir.join(".cargo"))?;- fs::write(dir.join("Cargo.toml"), cargo_toml(port))?;+ fs::write(dir.join("Cargo.toml"), cargo_toml(port, lib_rs(hs, port).contains("numpy::")))?;fs::write(dir.join(".cargo/config.toml"), backend::CARGO_CONFIG)?;let lib = dir.join("src/lib.rs");if !lib.exists() {@@ -940,6 +1054,72 @@ mod tests {assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));}+ #[test]+ fn numpy_arrays_map_and_render() {+ assert_eq!(rust_type("npt.NDArray[np.float64]", false).as_deref(), Some("numpy::PyReadonlyArrayDyn<'_, f64>"));+ assert_eq!(rust_type("NDArray[numpy.int32]", true).as_deref(), Some("Py<numpy::PyArrayDyn<i32>>"));+ assert_eq!(rust_type("list[npt.NDArray[np.uint8]]", false).as_deref(), Some("Vec<Py<numpy::PyArrayDyn<u8>>>"));+ assert_eq!(rust_type("npt.NDArray[np.complex128]", false), None);+ assert_eq!(rust_type("np.ndarray", false), None, "no dtype, no typed array");+ // [1.5, -2.0] as little-endian float64, [-1, 300] as int16+ let v: Value = serde_json::from_str(+ r#"[{"$ndarray": ["<f8", [2], "AAAAAAAA+D8AAAAAAAAAwA=="]}, {"$ndarray": ["<i2", [2], "//8sAQ=="]},+ {"$ndarray": ["<f8", [2, 3], ""]}, {"$npscalar": ["<f8", 0.5]}]"#,+ )+ .unwrap();+ assert_eq!(+ py_value(&v),+ "[array([1.5, -2.0], dtype=float64), array([-1, 300], dtype=int16), array(shape=(2, 3), dtype=float64), np.float64(0.5)]"+ );+ let hs = Hotspot {+ name: "f".into(),+ params: vec![crate::hotspot::Param {+ name: "xs".into(),+ annotation: Some("npt.NDArray[np.float64]".into()),+ ..Default::default()+ }],+ ..Hotspot::default()+ };+ assert!(cargo_toml(&port(), lib_rs(&hs, &port()).contains("numpy::")).contains("numpy = \"0.30\""));+ assert!(!cargo_toml(&port(), false).contains("numpy"));+ }++ #[test]+ fn numpy_values_in_the_runner() {+ let Some(python) = ["python3", "python"]+ .into_iter()+ .find(|p| Command::new(p).args(["-c", "import numpy"]).output().is_ok_and(|o| o.status.success()))+ else {+ eprintln!("no python with numpy on PATH, skipping");+ return;+ };+ let runner = std::env::temp_dir().join(format!("fa-runner-numpy-{}.py", std::process::id()));+ fs::write(&runner, RUNNER).unwrap();+ let check = "import runpy, sys, json, math\n\+ import numpy as np\n\+ ns = runpy.run_path(sys.argv[1])\n\+ enc, dec, same, edges, bigger, variants = (ns[k] for k in ('enc', 'dec', 'same', 'edges', 'bigger', 'variants'))\n\+ Unsupported = ns['Unsupported']\n\+ a = np.array([[1.5, -2.0, 3.0], [0.0, 4.0, 5.0]])\n\+ for v in (a, np.arange(5, dtype=np.int16), np.array([True, False]), np.float64(2.5), np.int32(7), [a[0], a[1]]):\n\+ \x20 back = dec(json.loads(json.dumps(enc(v))))\n\+ \x20 assert same(v, back), (v, back)\n\+ assert type(dec(json.loads(json.dumps(enc(np.int32(7)))))) is np.int32\n\+ assert not same(a, a.astype(np.float32)) and not same(a, a.tolist()) and not same(a, a[0])\n\+ assert same(np.array([math.nan, 1.0]), np.array([math.nan, 1.0 + 1e-12]))\n\+ assert same(np.float64(0.5), 0.5) and not same(np.int64(3), 3.0)\n\+ x = np.array([1.0, 2.0, 3.0])\n\+ e = edges(x); assert len(e[0]) == 0 and math.isnan(e[1][0]) and x[0] == 1.0\n\+ assert edges(np.array([1, 2], dtype=np.uint8))[1][0] == 0\n\+ assert list(bigger(x, 2)) == [1.0, 2.0, 3.0, 1.0, 2.0, 3.0]\n\+ import random; assert all(isinstance(v, np.ndarray) for v in variants(x, random.Random(0)))\n\+ try:\n enc(np.zeros(1 << 18)); raise SystemExit('big array recorded')\nexcept Unsupported: pass\n\+ try:\n enc(np.array(['a'])); raise SystemExit('str array recorded')\nexcept Unsupported: pass\n";+ let out = Command::new(python).args(["-I", "-c", check]).arg(&runner).output().unwrap();+ let _ = fs::remove_file(&runner);+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));+ }+#[test]fn spots_python() {assert!(is_python("python"));diff --git a/src/python/runner.py b/src/python/runner.pyindex 013f681..86d056d 100644--- a/src/python/runner.py+++ b/src/python/runner.py@@ -55,7 +55,28 @@ def find_class(module, qualname):return target+ARRAY_KINDS = "biuf" # NumPy dtypes recorded: bool, int, unsigned, float+MAX_ARRAY = 1 << 20 # bytes per recorded array, so recordings stay a sane size+++def enc_numpy(v):+ """An ndarray or NumPy scalar as plain data (only called for values from the numpy module)."""+ np = sys.modules["numpy"]+ if isinstance(v, np.ndarray):+ if v.dtype.kind not in ARRAY_KINDS:+ raise Unsupported("ndarray of " + str(v.dtype))+ if v.nbytes > MAX_ARRAY:+ raise Unsupported("ndarray over 1 MiB")+ a = np.ascontiguousarray(v)+ return {"$ndarray": [a.dtype.str, list(a.shape), base64.b64encode(a.tobytes()).decode("ascii")]}+ if isinstance(v, np.generic) and v.dtype.kind in ARRAY_KINDS:+ return {"$npscalar": [v.dtype.str, v.item()]}+ raise Unsupported(type(v).__name__)++def enc(v):+ if type(v).__module__ == "numpy" and "numpy" in sys.modules:+ return enc_numpy(v)if v is None or isinstance(v, (bool, int, str)):return vfields = record_fields(v)@@ -103,6 +124,13 @@ def dec(v):for k, i in values.items():object.__setattr__(obj, k, i)return obj+ if tag == "$ndarray":+ import numpy as np+ dtype, shape, data = x+ return np.frombuffer(base64.b64decode(data), dtype=np.dtype(dtype)).reshape(shape).copy()+ if tag == "$npscalar":+ import numpy as np+ return np.dtype(x[0]).type(x[1])raise ValueError("unknown tag " + tag)return v@@ -110,6 +138,17 @@ def dec(v):def same(a, b):"""Equality the way a caller would see it: list == tuple, floats within 1e-9, but 3 != 3.0(it prints differently)."""+ np = sys.modules.get("numpy")+ if np is not None:+ if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):+ if not (isinstance(a, np.ndarray) and isinstance(b, np.ndarray)) or a.shape != b.shape or a.dtype != b.dtype:+ return False+ if a.dtype.kind == "f":+ return bool(np.allclose(a, b, rtol=1e-9, atol=1e-12, equal_nan=True))+ return bool(np.array_equal(a, b))+ # a NumPy scalar compares like the Python number it holds (a.sum() vs a port's f64)+ a = a.item() if isinstance(a, np.generic) else a+ b = b.item() if isinstance(b, np.generic) else bif isinstance(a, bool) or isinstance(b, bool):return type(a) is type(b) and a == bfields = record_fields(a)@@ -584,9 +623,15 @@ def cmd_verify(job, _argv):SLICE_LENGTHS = (0, 1, 2, 3, 5, 8, 13, 21, 34, 55)+def is_array(value):+ np = sys.modules.get("numpy")+ return np is not None and isinstance(value, np.ndarray) and value.ndim >= 1++def variants(value, rng):- """Smaller versions of a list/str/bytes/tuple argument: empty, tiny, and random slices."""- if not isinstance(value, (list, tuple, str, bytes)) or len(value) < 2 or record_fields(value) is not None:+ """Smaller versions of a list/str/bytes/tuple argument (or an array, along its first axis): empty,+ tiny, and random slices."""+ if not (isinstance(value, (list, tuple, str, bytes)) or is_array(value)) or len(value) < 2 or record_fields(value) is not None:return []n = len(value)out = []@@ -618,6 +663,15 @@ def edges(value):value + NON_ASCII[3], ""]if isinstance(value, bytes):return [b"", value + b"\x00", b"\xff" + value]+ if is_array(value):+ if value.ndim != 1 or value.dtype.kind not in "iuf" or not len(value):+ return []+ out = [value[:0].copy()]+ for x in {"f": (math.nan, math.inf, -math.inf, -0.0), "i": (0, -1), "u": (0,)}[value.dtype.kind]:+ changed = value.copy()+ changed[0] = x+ out.append(changed)+ return outif isinstance(value, (list, tuple)) and value:out = [type(value)()]for e in edges(value[0])[:4]:@@ -630,7 +684,7 @@ def small(value):"""A short version of a recorded value, so edge cases stay cheap when the real inputs are big."""if record_fields(value) is not None:return value- if isinstance(value, (list, tuple)):+ if isinstance(value, (list, tuple)) or is_array(value):return value[:8]if isinstance(value, (str, bytes)):return value[:64]@@ -639,6 +693,10 @@ def small(value):def bigger(value, factor):"""The value repeated factor times (None past BIG items or characters)."""+ if is_array(value):+ if not len(value) or len(value) * factor > BIG:+ return None+ return sys.modules["numpy"].concatenate([value] * factor)if not isinstance(value, (list, tuple, str, bytes)) or not value or len(value) * factor > BIG:return Noneif record_fields(value) is not None: