Repository navigation
Native copies of int, float and complex for C extensions - #24
Ivo Horák (horakivo) wants to merge 5 commits into
Conversation
Values that cross into C no longer always get a Java wrapper plus a native stub. Shared native state (NativeComplex): one native block holds the allocators that C and Java share without upcalls, the borrowed-reference stack and the downcall depth. Generated downcall invokers (and vectorcall slot calls) enter and leave the depth; when the outermost downcall returns, the counts on the borrowed stack are dropped. - complex: an exact complex is passed to C as a native PyComplexObject from a size-class allocator. A list of exact complex values stores counted pointers to such structs (ComplexPtrSequenceStorage); PComplex keeps an unowned pointer and serial so a value read from such a list is the same object when stored or passed again. PyComplex_FromDoubles and exact complex allocation/deallocation in C use the same allocator. - int: an exact int that does not fit the tagged pointer (up to 120 bits) is passed as a native PyLongObject with no Java companion; the Java value stays a long. PyLong_From*/PyLong_As* handle these in C. - float: an exact float that cannot be tagged is passed as a native PyFloatObject from a 64-byte small-block pool that PyObject_Malloc and Java share. An instance of a static native float subclass that is only (type, ob_fval) is held in Java as a value copy (PNativeFloat) instead of a native object with a weak reference and lookup entry. Lifetime: a copy passed as an argument or borrowed result holds a count on the borrowed stack until the outermost C call returns; C that increfs it keeps it. Items that a container holds (dict and list items, PyDict_Next) are still promoted to objects with stable stubs, as before. A copy that C keeps without its own reference past the outermost call is freed under it. Also included, experimental and opt-in: classes with __slots__ that set __native_layout__ = True (and derive directly from object) get instances whose slots live in native reference-counted structs, with a pointer-aware list storage for them and pins on dict, cell, global and attribute stores. No class in the standard library or the tests sets it. The pins, the list storage and the struct paths are guarded by an assumption that holds until such a class is created. What runs for every program: a bytecode fast path for stores to __slots__ attributes (shape- cached, like the existing load fast path), and a profiled "native instance" type check on slot reads and writes. __graalpython__ gains measurement helpers: complex_counters, native_long_live, slots_counters (counters need -Dgraalpy.complexCounters or -Dgraalpy.slotsCounters) and native_quiesce.
…ith memcpy GCC rejects the previous cast of the value field's address to a block pointer under -Werror=strict-aliasing. Clang accepted it. The stored bytes are the same.
ReleaseNativeArgsTupleNode asserted (with detailed assertions) that every element of the args tuple is still the pointer that converting the managed argument again yields. That holds for stubs, handles and tagged values, but not for arguments that cross as native value copies (int, float, complex): each conversion makes a new struct, so the check failed for correct tuples, and the conversion done by the check itself allocated a further copy. For an element that is a value copy, compare the struct's type and value with the managed argument (value for int, raw bits for float and complex, type and bits for value-type float subclasses) and require that it is still alive; other elements keep the pointer check.
The commit that copies exact complex, int and float values to native structs also carried an inactive experiment: classes with __slots__ that set __native_layout__ = True got instances whose slots live in native reference-counted structs, with a pointer-aware list storage for them and pins on dict, cell, global and attribute stores. Nothing sets that attribute, and none of it is needed by the value copies, so it is removed: - PNativeLayoutObject, NativeInstance, NativeSlotNodes and InstPtrSequenceStorage, and the InstPtr storage type; - the instance-word kind of ComplexPtrSequenceStorage, which now holds complex pointers only, and the InstPtr specializations in the sequence storage nodes and list literals; - the pins in PCell, DynamicObjectStorage, ObjectHashMap, the attribute, global and name writes and ObjectSequenceStorage, the native-layout object.__new__, hash, id and slot descriptor paths, the class registration in TypeNodes and the class id in PythonClass; - the native-layout branches of the bytecode slot read fast path, the slot store fast path that came with them, and the all-None list literal path; - the "is" specialization for native-layout instances and the native_quiesce and slots_counters builtins.
PComplex had three extra fields for the native copies: an exact-type flag and the pointer and serial of the struct it was last stored to or read from. They made every complex object 24 bytes larger, including the many temporaries of pure-Python complex arithmetic that never reach native memory, and pure-Python complex code allocated correspondingly more. The exact-type flag is now derived from the object's class. The pointer and serial served two purposes: storing the same complex object again reused its struct, and two values read from the same struct were "is" each other. A store now always makes a new struct, and exact complex numbers compare by value under "is", like floats already do, so values read from a list of complex numbers are still identical to what was stored. As with floats, two equal exact complex numbers created independently are now "is" each other.
This comment has been minimized.
This comment has been minimized.
Merging this PR will regress 2 benchmarks1 warning
Warning Please fix the performance issues or acknowledge them on CodSpeed. Performance Changes
Tip Investigate this regression by commenting Comparing Footnotes
|
Draft, do not merge. Stacked on #21 (
perf/capi-fast-paths). This is the numeric half of #22, split out so it can be measured and reviewed without the string half.What it does
When C asks for an
int,floatorcomplex, it gets a native struct with CPython's layout that holds a copy of the value, instead of a stub for the Java object. C reads the value directly, and the copy needs no entry in the handle table and no weak reference.211eaee7: the native copies for int, float and complex.54223a2c: free-list links written withmemcpy(strict aliasing).74e80002: the check of released argument tuples compares values for these types.507a3ea6: removes the opt-in native layout experiment.480a1571: no extra fields oncomplex; see the limits below.What it leaves out, compared with #22
The native copies of
strand everything that only exists for them. Strings have an open trade-off between identity through containers and memory (see #22); numbers do not.Known limits
480a1571changes whatismeans for exact complex numbers: they compare by value, the way GraalPy already treats floats, socomplex(1, 2) is complex(1, 2)isTrue(it isFalseon CPython and wasFalsehere). In exchange acomplexobject carries no extra fields; before this commit every complex was 24 bytes larger, also in pure Python code.l[0] is cafterl = [c]stays true. If strict identity is preferred, the alternative is one pointer field per complex (8 bytes); the commit can be dropped on its own.507a3ea6removes an opt-in experiment (__native_layout__on a class with__slots__) that came with the first commit, including a bytecode fast path for stores to__slots__attributes. After it, the bytecode interpreter is identical to the base.Measured
One benchmark run of 480a157 against three runs of the base, median iteration time on the benchmark host (geometric mean of the ratios, below 1 is faster): real packages 1.00, C API micro 0.79, pure Python 0.99.
c-many-shortlived-objs24.5 to 30.9 s down to 2.1 s,c-arith-binop23.2 to 3.6 s down to 0.32 s,c-arith-binop4.7 s down to 1.3 s.c-list-iterating-obj0.74 to 0.87 s,c-magic-iter3.24 to 3.67 s,c-magic-bool,c-call-method-noargs, bothc-issubtyperows and others).c-arith-binoppeak RSS 483 MB to 1,553 MB.lxml-xpathis 1.84 to 1.93 s on the base and 2.19 s here (one run).mandelbrot3is within the base's range, so the extra bytes oncomplexwere the cause of the slowdown seen on Native copies of int, float, complex and str for C extensions #22.So on its own this half pays off only where C code handles many numbers one object at a time, and it has a cost on calls that do not involve numbers at all.
Testing
Assertions build on macOS: all 758 C API tests pass (9 skipped), and 1,854 tagged standard-library tests (
test_capi,test_float,test_long,test_complex,test_str,test_struct,test_array,test_json,test_pyexpat) pass, the same as on the base commit. Elide CI (Linux x86-64, assertions on) passes on 480a157.🤖 Generated with Claude Code