Last active
October 28, 2026 06:22
-
-
Save nmsmith/cc281165b853d4ad9d2b2eedd8459db1 to your computer and use it in GitHub Desktop.
[Mojo] Pattern matching benchmark (tagged vs. tagless enum encodings)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """Compare compact/tagged Shape storage with native/proposed matching. | |
| Build with Mojo 1.2.0: | |
| mojo build -O3 -D ASSERT=none shape_benchmarks.mojo -o shape_benchmarks | |
| ./shape_benchmarks [exponent=24] [repetitions=21] [workers=logical CPUs] | |
| The program runs one-worker and multi-worker versions of calculate_volume and | |
| count_boxes, under both pattern-matching protocols. Copying is a shared control, | |
| so it runs once per worker count. Positive throughput differences favor compact. | |
| calculate_volume returns volume for boxes and area for rectangles, as in Lukas's | |
| original benchmark. All products/checksums use UInt64 arithmetic modulo 2**64. | |
| The new (proposed) pattern-matching protocol is a source-level model: Mojo 1.2 | |
| does not use its hooks. Its case bodies and payload projections are unchanged; | |
| only case selection changes. All three dimension words are initialized, with at | |
| most one zero. | |
| Read top to bottom: representations, operations, timing/reporting, input checks, | |
| and main. Native threading support is at the bottom; the benchmark code uses | |
| ordinary typed spans. No Python, MAX package, or companion files are needed. | |
| Original representations and native matching bodies: | |
| https://gist.github.com/lsh/745fe8101a88b3d6b0d2c044ee37d277 | |
| Revision b4fa160b9526d270b897b523c214c07d61bfb057. | |
| """ | |
| from std.memory import MaybeUninit | |
| from std.sys import size_of, CompilationTarget, argv | |
| from std.sys.info import num_logical_cores | |
| from std.builtin.variadics import _MLIR | |
| from std.utils._nicheable import UnsafeSingleNicheable | |
| from std.collections.optional import OptionalReg | |
| from std.time import perf_counter_ns | |
| from std.builtin.sort import sort | |
| from std.benchmark import keep | |
| from std.ffi import external_call, c_int, c_uint | |
| from std.atomic import Atomic, Ordering | |
| # === Representations and matching operations === | |
| struct NonZeroUInt32(TrivialRegisterPassable, UnsafeSingleNicheable): | |
| """A nonzero dimension whose optional representation uses zero for None.""" | |
| var _value: UInt32 | |
| def __init__(out self, value: UInt32) raises: | |
| """Reject zero before storing a dimension.""" | |
| if value == 0: | |
| raise Error("a dimension must be nonzero") | |
| self._value = value | |
| @staticmethod | |
| @inline(.always) | |
| def write_niche(memory: MutPointer[MaybeUninit[Self], _]): | |
| """Write the zero representation used by OptionalReg for None.""" | |
| memory.unsafe_bitcast[UInt32]().unsafe_store(0) | |
| @staticmethod | |
| @inline(.always) | |
| def isa_niche(memory: ImmPointer[MaybeUninit[Self], _]) -> Bool: | |
| """Recognize the zero representation of an absent dimension.""" | |
| return memory.unsafe_bitcast[UInt32]()[] == 0 | |
| def dimension_value(value: OptionalReg[NonZeroUInt32]) -> UInt32: | |
| """Return a stored dimension or zero; used only to verify copied shapes.""" | |
| return value.value()._value if value else UInt32(0) | |
| # Each payload overlays the part of `Shape` that holds its extents, so | |
| # `_unsafe_get_enum_payload` can return a reference into the shape. | |
| @fieldwise_init | |
| struct ShapeBox(TrivialRegisterPassable): | |
| var width: NonZeroUInt32 | |
| var height: NonZeroUInt32 | |
| var depth: NonZeroUInt32 | |
| @fieldwise_init | |
| struct ShapeRectXY(TrivialRegisterPassable): | |
| var width: NonZeroUInt32 | |
| var height: NonZeroUInt32 | |
| @fieldwise_init | |
| struct ShapeRectXZ(TrivialRegisterPassable): | |
| var width: NonZeroUInt32 | |
| # Always zero; it overlays the missing `y` between the two extents. | |
| var height: UInt32 | |
| var depth: NonZeroUInt32 | |
| @fieldwise_init | |
| struct ShapeRectYZ(TrivialRegisterPassable): | |
| var height: NonZeroUInt32 | |
| var depth: NonZeroUInt32 | |
| struct Shape(EnumLike, Equatable, TrivialRegisterPassable): | |
| """A box or an axis-aligned rectangle. | |
| The missing extent is stored as zero and is the discriminant: | |
| ```text | |
| Box: [width, height, depth] | |
| RectXY: [width, height, 0] | |
| RectXZ: [width, 0, depth] | |
| RectYZ: [ 0, height, depth] | |
| ``` | |
| At most one extent is ever zero. | |
| """ | |
| var x: OptionalReg[NonZeroUInt32] | |
| var y: OptionalReg[NonZeroUInt32] | |
| var z: OptionalReg[NonZeroUInt32] | |
| @staticmethod | |
| def Box( | |
| width: NonZeroUInt32, height: NonZeroUInt32, depth: NonZeroUInt32 | |
| ) -> Self: | |
| """Construct a box with all three dimensions present.""" | |
| return Self(x=width, y=height, z=depth) | |
| @staticmethod | |
| def RectXY(width: NonZeroUInt32, height: NonZeroUInt32) -> Self: | |
| """Construct an XY rectangle; store zero for its missing depth.""" | |
| return Self(x=width, y=height, z=None) | |
| @staticmethod | |
| def RectXZ(width: NonZeroUInt32, depth: NonZeroUInt32) -> Self: | |
| """Construct an XZ rectangle; store zero for its missing height.""" | |
| return Self(x=width, y=None, z=depth) | |
| @staticmethod | |
| def RectYZ(height: NonZeroUInt32, depth: NonZeroUInt32) -> Self: | |
| """Construct a YZ rectangle; store zero for its missing width.""" | |
| return Self(x=None, y=height, z=depth) | |
| def __init__( | |
| out self, | |
| *, | |
| x: OptionalReg[NonZeroUInt32], | |
| y: OptionalReg[NonZeroUInt32], | |
| z: OptionalReg[NonZeroUInt32], | |
| ): | |
| """Initialize the stored fields without changing their layout.""" | |
| self.x = x | |
| self.y = y | |
| self.z = z | |
| def __eq__(self, other: Self) -> Bool: | |
| """Compare the stored dimensions; used only for copy validation.""" | |
| return (dimension_value(self.x) == dimension_value(other.x) | |
| and dimension_value(self.y) == dimension_value(other.y) | |
| and dimension_value(self.z) == dimension_value(other.z)) | |
| comptime _enum_case_names = ParameterList.of[ | |
| "Box".value, "RectXY".value, "RectXZ".value, "RectYZ".value | |
| ].values | |
| comptime _enum_case_types: _MLIR.KGENParamListType[AnyType] = TypeList.of[ | |
| Trait=AnyType, ShapeBox, ShapeRectXY, ShapeRectXZ, ShapeRectYZ | |
| ].values | |
| # Proposed protocol; native Mojo 1.2 match ignores this method. | |
| @inline(.always) | |
| def _is_enum_case[case_id: Int](self) -> Bool: | |
| """Return whether the enum's current value matches the provided `case_id`. | |
| The case ID is a compile-time parameter, allowing the code to be specialized | |
| at the call site. Notice how this differs from `_get_enum_discriminant`. | |
| """ | |
| comptime if case_id == 0: | |
| return Bool(self.x) and Bool(self.y) and Bool(self.z) | |
| elif case_id == 1: | |
| return not self.z | |
| elif case_id == 2: | |
| return not self.y | |
| else: | |
| comptime assert case_id == 3 | |
| return not self.x | |
| @inline(.always) | |
| def _get_enum_discriminant(self) -> Int: | |
| """Return the runtime case index required by Mojo 1.2 match.""" | |
| if not self.x: | |
| return 3 | |
| if not self.y: | |
| return 2 | |
| if not self.z: | |
| return 1 | |
| return 0 | |
| @inline(.always) | |
| def _unsafe_get_enum_payload[ | |
| id: Int | |
| ](ref self) -> ref[self] TypeList[Trait=AnyType, Self._enum_case_types]()[ | |
| id | |
| ]: | |
| """Borrow a payload view; the caller must first establish its case.""" | |
| comptime Payload = TypeList[Trait=AnyType, Self._enum_case_types]()[id] | |
| comptime offset = 1 if id == 3 else 0 | |
| return ( | |
| Pointer(to=self) | |
| .unsafe_bitcast[UInt32]() | |
| .unsafe_offset(offset) | |
| .unsafe_bitcast[Payload]() | |
| .unsafe_origin_cast[origin_of(self)]()[] | |
| ) | |
| struct Shape2(EnumLike, Equatable, TrivialRegisterPassable): | |
| """The same cases as `Shape`, discriminated by an explicit `UInt8` tag. | |
| The extents keep `Shape`'s layout, with the missing one zeroed, so both | |
| share the payload structs. | |
| """ | |
| var x: UInt32 | |
| var y: UInt32 | |
| var z: UInt32 | |
| var _tag: UInt8 | |
| @staticmethod | |
| def Box( | |
| width: NonZeroUInt32, height: NonZeroUInt32, depth: NonZeroUInt32 | |
| ) -> Self: | |
| """Construct a box with all three dimensions present.""" | |
| return Self(width._value, height._value, depth._value, tag=0) | |
| @staticmethod | |
| def RectXY(width: NonZeroUInt32, height: NonZeroUInt32) -> Self: | |
| """Construct an XY rectangle; store zero for its missing depth.""" | |
| return Self(width._value, height._value, 0, tag=1) | |
| @staticmethod | |
| def RectXZ(width: NonZeroUInt32, depth: NonZeroUInt32) -> Self: | |
| """Construct an XZ rectangle; store zero for its missing height.""" | |
| return Self(width._value, 0, depth._value, tag=2) | |
| @staticmethod | |
| def RectYZ(height: NonZeroUInt32, depth: NonZeroUInt32) -> Self: | |
| """Construct a YZ rectangle; store zero for its missing width.""" | |
| return Self(0, height._value, depth._value, tag=3) | |
| def __init__(out self, x: UInt32, y: UInt32, z: UInt32, *, tag: UInt8): | |
| """Initialize the stored fields without changing their layout.""" | |
| self.x = x | |
| self.y = y | |
| self.z = z | |
| self._tag = tag | |
| def __eq__(self, other: Self) -> Bool: | |
| """Compare stored values; used only for copy validation.""" | |
| return ( | |
| self._tag == other._tag | |
| and self.x == other.x | |
| and self.y == other.y | |
| and self.z == other.z | |
| ) | |
| comptime _enum_case_names = Shape._enum_case_names | |
| comptime _enum_case_types = Shape._enum_case_types | |
| # The proposed protocol tests this stored tag directly. | |
| @inline(.always) | |
| def _is_enum_case[case_id: Int](self) -> Bool: | |
| """Return whether the enum's current value matches the provided `case_id`. | |
| """ | |
| comptime assert 0 <= case_id < 4 | |
| return self._tag == UInt8(case_id) | |
| @inline(.always) | |
| def _get_enum_discriminant(self) -> Int: | |
| """Return the runtime case index required by Mojo 1.2 match.""" | |
| return Int(self._tag) | |
| @inline(.always) | |
| def _unsafe_get_enum_payload[ | |
| id: Int | |
| ](ref self) -> ref[self] TypeList[Trait=AnyType, Self._enum_case_types]()[ | |
| id | |
| ]: | |
| """Borrow a payload view; the caller must first establish its case.""" | |
| comptime Payload = TypeList[Trait=AnyType, Self._enum_case_types]()[id] | |
| comptime offset = 1 if id == 3 else 0 | |
| return ( | |
| Pointer(to=self) | |
| .unsafe_bitcast[UInt32]() | |
| .unsafe_offset(offset) | |
| .unsafe_bitcast[Payload]() | |
| .unsafe_origin_cast[origin_of(self)]()[] | |
| ) | |
| def calculate_volume(shape: Shape) -> UInt64: | |
| """Calculate box volume or rectangle area using native match.""" | |
| match shape: | |
| case .Box(b): | |
| return ( | |
| UInt64(b.width._value) | |
| * UInt64(b.height._value) | |
| * UInt64(b.depth._value) | |
| ) | |
| case .RectXY(r): | |
| return UInt64(r.width._value) * UInt64(r.height._value) | |
| case .RectXZ(r): | |
| return UInt64(r.width._value) * UInt64(r.depth._value) | |
| case .RectYZ(r): | |
| return UInt64(r.height._value) * UInt64(r.depth._value) | |
| def calculate_volume(shape: Shape2) -> UInt64: | |
| """Calculate box volume or rectangle area using native match.""" | |
| match shape: | |
| case .Box(b): | |
| return ( | |
| UInt64(b.width._value) | |
| * UInt64(b.height._value) | |
| * UInt64(b.depth._value) | |
| ) | |
| case .RectXY(r): | |
| return UInt64(r.width._value) * UInt64(r.height._value) | |
| case .RectXZ(r): | |
| return UInt64(r.width._value) * UInt64(r.depth._value) | |
| case .RectYZ(r): | |
| return UInt64(r.height._value) * UInt64(r.depth._value) | |
| def count_boxes(shape: Shape) -> UInt64: | |
| """Return one for a Box and zero for a rectangle using native match.""" | |
| match shape: | |
| case .Box(_): | |
| return 1 | |
| case _: | |
| return 0 | |
| def count_boxes(shape: Shape2) -> UInt64: | |
| """Return one for a Box and zero for a rectangle using native match.""" | |
| match shape: | |
| case .Box(_): | |
| return 1 | |
| case _: | |
| return 0 | |
| # Below is the hypothetical lowering of `match` if Mojo's pattern matching used | |
| # the new `EnumLike._is_enum_case` rather than `EnumLike._get_enum_discriminant`. | |
| # Cases are checked in the Shape's preferred order. | |
| @inline(.always) | |
| def calculate_volume_predicate(shape: Shape) -> UInt64: | |
| """The same volume calculation as before, with the proposed direct-case-test lowering.""" | |
| if shape._is_enum_case[3](): | |
| ref p = shape._unsafe_get_enum_payload[3]() | |
| return UInt64(p.height._value) * UInt64(p.depth._value) | |
| elif shape._is_enum_case[2](): | |
| ref p = shape._unsafe_get_enum_payload[2]() | |
| return UInt64(p.width._value) * UInt64(p.depth._value) | |
| elif shape._is_enum_case[1](): | |
| ref p = shape._unsafe_get_enum_payload[1]() | |
| return UInt64(p.width._value) * UInt64(p.height._value) | |
| else: | |
| ref p = shape._unsafe_get_enum_payload[0]() | |
| return UInt64(p.width._value) * UInt64(p.height._value) * UInt64(p.depth._value) | |
| @inline(.always) | |
| def calculate_volume_predicate(shape: Shape2) -> UInt64: | |
| """The same volume calculation as before, with the proposed direct-case-test lowering.""" | |
| if shape._is_enum_case[0](): | |
| ref p = shape._unsafe_get_enum_payload[0]() | |
| return UInt64(p.width._value) * UInt64(p.height._value) * UInt64(p.depth._value) | |
| elif shape._is_enum_case[1](): | |
| ref p = shape._unsafe_get_enum_payload[1]() | |
| return UInt64(p.width._value) * UInt64(p.height._value) | |
| elif shape._is_enum_case[2](): | |
| ref p = shape._unsafe_get_enum_payload[2]() | |
| return UInt64(p.width._value) * UInt64(p.depth._value) | |
| else: | |
| ref p = shape._unsafe_get_enum_payload[3]() | |
| return UInt64(p.height._value) * UInt64(p.depth._value) | |
| @inline(.always) | |
| def count_boxes_predicate(shape: Shape) -> UInt64: | |
| """Return one for a Box using the proposed direct case test.""" | |
| return UInt64(shape._is_enum_case[0]()) | |
| @inline(.always) | |
| def count_boxes_predicate(shape: Shape2) -> UInt64: | |
| """Return one for a Box using the proposed direct case test.""" | |
| return UInt64(shape._is_enum_case[0]()) | |
| # === Timing and reporting === | |
| def format_decimal[places: Int](value: Float64) -> String: | |
| """Format a number with a fixed number of decimal places for the table.""" | |
| var scale = 10 ** places | |
| var rounded = Int(abs(value) * Float64(scale) + 0.5) | |
| var fraction = String(scale + rounded % scale) | |
| var sign = "-" if value < 0 else "" | |
| return String(t"{sign}{rounded // scale}.{fraction[byte=1:]}") | |
| def column(var text: String, width: Int) -> String: | |
| """Pad an ASCII table cell so the terminal output lines up.""" | |
| while text.byte_length() < width: | |
| text += " " | |
| return text^ | |
| def benchmark_pair[Run: def(Bool) -> UInt64]( | |
| run: Run, workers: Int, matching: String, workload: String, | |
| expected: UInt64, repetitions: Int, | |
| ) raises: | |
| """Time the compact/tagged pair, verify checksums, and print their medians. | |
| run(False) processes the compact array; run(True) processes the tagged one. | |
| Both get two untimed warmups. Each repetition then runs both, alternating | |
| which comes first to distribute drift. Only run() is timed. A mismatched | |
| checksum raises an error after timing. The final percentage compares work | |
| per second: 100 * (tagged_time / compact_time - 1). | |
| """ | |
| for _ in range(2): | |
| if run(False) != expected or run(True) != expected: | |
| raise Error("warmup checksum mismatch") | |
| var compact_times = List[Int](capacity=repetitions) | |
| var tagged_times = List[Int](capacity=repetitions) | |
| for repetition in range(repetitions): | |
| for turn in range(2): | |
| var tagged = Bool((repetition + turn) % 2) | |
| var start = perf_counter_ns() | |
| var result = run(tagged) | |
| var elapsed = perf_counter_ns() - start | |
| if result != expected: | |
| raise Error("timed checksum mismatch") | |
| if tagged: | |
| tagged_times.append(elapsed) | |
| else: | |
| compact_times.append(elapsed) | |
| sort(Span(compact_times)) | |
| sort(Span(tagged_times)) | |
| var compact_ns = Float64(compact_times[repetitions // 2]) | |
| var tagged_ns = Float64(tagged_times[repetitions // 2]) | |
| var difference = 100 * (tagged_ns / compact_ns - 1) | |
| var sign = "+" if difference >= 0 else "" | |
| print(t"{column(String(workers), 7)} | {column(matching, 9)} | {column(workload, 16)} | {column(format_decimal[3](compact_ns / 1e6), 10)} | {column(format_decimal[3](tagged_ns / 1e6), 9)} | {sign}{format_decimal[1](difference)}%") | |
| def run_benchmarks(mut pool: WorkerPool, data: Dataset, repetitions: Int) raises: | |
| """Run the two pattern-matching protocols on the same data, then a shared copy control. | |
| The closures below choose compact or tagged storage once per whole scan. | |
| WorkerPool.sum specializes its inner loop for the supplied function: there | |
| is no per-shape function-pointer dispatch. All arrays already exist before | |
| timing. The copies are verified value by value after their timed passes. | |
| """ | |
| def native_volume(tagged: Bool) {mut pool, imm data} -> UInt64: | |
| """Run a whole-array calculation using native match.""" | |
| if tagged: | |
| return pool.sum[Shape2, calculate_volume](Span(data.tagged)) | |
| return pool.sum[Shape, calculate_volume](Span(data.compact)) | |
| benchmark_pair(native_volume, pool.worker_count, "native", "calculate_volume", | |
| data.expected_volume, repetitions) | |
| def predicate_volume(tagged: Bool) {mut pool, imm data} -> UInt64: | |
| """Run the same whole-array calculation using direct case tests.""" | |
| if tagged: | |
| return pool.sum[Shape2, calculate_volume_predicate](Span(data.tagged)) | |
| return pool.sum[Shape, calculate_volume_predicate](Span(data.compact)) | |
| benchmark_pair(predicate_volume, pool.worker_count, "predicate", "calculate_volume", | |
| data.expected_volume, repetitions) | |
| def native_count_boxes(tagged: Bool) {mut pool, imm data} -> UInt64: | |
| """Count boxes across the chosen array using native match.""" | |
| if tagged: | |
| return pool.sum[Shape2, count_boxes](Span(data.tagged)) | |
| return pool.sum[Shape, count_boxes](Span(data.compact)) | |
| benchmark_pair(native_count_boxes, pool.worker_count, "native", "count_boxes", | |
| data.expected_boxes, repetitions) | |
| def predicate_count_boxes(tagged: Bool) {mut pool, imm data} -> UInt64: | |
| """Count boxes across the chosen array using direct case tests.""" | |
| if tagged: | |
| return pool.sum[Shape2, count_boxes_predicate](Span(data.tagged)) | |
| return pool.sum[Shape, count_boxes_predicate](Span(data.compact)) | |
| benchmark_pair(predicate_count_boxes, pool.worker_count, "predicate", "count_boxes", | |
| data.expected_boxes, repetitions) | |
| # Different initial contents ensure a copy that writes nothing would fail. | |
| var compact_copy = List[Shape](length=len(data.compact), | |
| fill=Shape.RectXY(NonZeroUInt32(7), NonZeroUInt32(11))) | |
| var tagged_copy = List[Shape2](length=len(data.tagged), | |
| fill=Shape2.RectXY(NonZeroUInt32(7), NonZeroUInt32(11))) | |
| def copy_shapes(tagged: Bool) {mut pool, imm data, mut compact_copy, mut tagged_copy} -> UInt64: | |
| """Copy the chosen array into its preallocated destination.""" | |
| if tagged: | |
| return pool.copy(Span(data.tagged), Span[mut=True](tagged_copy)) | |
| return pool.copy(Span(data.compact), Span[mut=True](compact_copy)) | |
| benchmark_pair(copy_shapes, pool.worker_count, "shared", "copy", | |
| UInt64(len(data.compact)), repetitions) | |
| validate_copy(Span(data.compact), Span(compact_copy)) | |
| validate_copy(Span(data.tagged), Span(tagged_copy)) | |
| # === Inputs and untimed correctness checks === | |
| def make_shapes(kind: Int, x: UInt32, y: UInt32, z: UInt32) raises -> Tuple[Shape, Shape2]: | |
| """Construct the same logical shape in both layouts; reject zero dimensions.""" | |
| var width = NonZeroUInt32(x) | |
| var height = NonZeroUInt32(y) | |
| var depth = NonZeroUInt32(z) | |
| if kind == 0: | |
| return (Shape.Box(width, height, depth), Shape2.Box(width, height, depth)) | |
| elif kind == 1: | |
| return (Shape.RectXY(width, height), Shape2.RectXY(width, height)) | |
| elif kind == 2: | |
| return (Shape.RectXZ(width, depth), Shape2.RectXZ(width, depth)) | |
| else: | |
| return (Shape.RectYZ(height, depth), Shape2.RectYZ(height, depth)) | |
| def reference_volume(kind: Int, x: UInt32, y: UInt32, z: UInt32) -> UInt64: | |
| """Untimed reference calculation from input values, independent of enum decoding.""" | |
| if kind == 0: | |
| return UInt64(x) * UInt64(y) * UInt64(z) | |
| elif kind == 1: | |
| return UInt64(x) * UInt64(y) | |
| elif kind == 2: | |
| return UInt64(x) * UInt64(z) | |
| else: | |
| return UInt64(y) * UInt64(z) | |
| def next_random(mut state: UInt64) -> UInt64: | |
| """Generate reproducible xorshift64* values; used only to initialize inputs.""" | |
| state ^= state >> 12 | |
| state ^= state << 25 | |
| state ^= state >> 27 | |
| return state * 2685821657736338717 | |
| struct Dataset: | |
| """Matching input arrays and independently calculated expected checksums.""" | |
| var compact: List[Shape] | |
| var tagged: List[Shape2] | |
| var expected_volume: UInt64 | |
| var expected_boxes: UInt64 | |
| def __init__(out self, n: Int) raises: | |
| """Generate n shapes with seed 42, four cases, and dimensions from 1 to 1000.""" | |
| self.compact = List[Shape](capacity=n) | |
| self.tagged = List[Shape2](capacity=n) | |
| self.expected_volume = 0 | |
| self.expected_boxes = 0 | |
| var state: UInt64 = 42 | |
| for _ in range(n): | |
| var kind = Int(next_random(state) & 3) | |
| var x = UInt32(next_random(state) % 1000 + 1) | |
| var y = UInt32(next_random(state) % 1000 + 1) | |
| var z = UInt32(next_random(state) % 1000 + 1) | |
| var pair = make_shapes(kind, x, y, z) | |
| self.compact.append(pair[0]) | |
| self.tagged.append(pair[1]) | |
| self.expected_volume += reference_volume(kind, x, y, z) | |
| self.expected_boxes += UInt64(kind == 0) | |
| def validate_matching() raises: | |
| """Check both pattern-matching protocols and both shape layouts on all cases and boundary-sized dimensions. | |
| The four dimensions below exercise small values, the high bit, and UInt32's | |
| maximum. All 4 cases * 4**3 dimension combinations are checked against the | |
| independent reference, including UInt64 product overflow. Nothing is timed. | |
| Aggregate scans are checked separately by every benchmark_pair invocation. | |
| """ | |
| var dimensions: List[UInt32] = [1, 2, 0x80000000, 0xFFFFFFFF] | |
| for kind in range(4): | |
| for x in dimensions: | |
| for y in dimensions: | |
| for z in dimensions: | |
| var pair = make_shapes(kind, x, y, z) | |
| var expected = reference_volume(kind, x, y, z) | |
| if (calculate_volume(pair[0]) != expected | |
| or calculate_volume(pair[1]) != expected | |
| or calculate_volume_predicate(pair[0]) != expected | |
| or calculate_volume_predicate(pair[1]) != expected): | |
| raise Error("calculate_volume boundary check failed") | |
| var boxes = UInt64(kind == 0) | |
| if (count_boxes(pair[0]) != boxes or count_boxes(pair[1]) != boxes | |
| or count_boxes_predicate(pair[0]) != boxes | |
| or count_boxes_predicate(pair[1]) != boxes): | |
| raise Error("count_boxes boundary check failed") | |
| def validate_copy[T: Equatable, a: ImmOrigin, b: ImmOrigin]( | |
| source: Span[T, a], destination: Span[T, b], | |
| ) raises: | |
| """Compare every copied value with its source, outside the timed interval.""" | |
| for i in range(len(source)): | |
| if source[i] != destination[i]: | |
| raise Error("copied value disagrees with source") | |
| def main() raises: | |
| """Parse the three run settings and execute the one-worker and multi-worker modes.""" | |
| comptime assert size_of[Shape]() == 12 and size_of[Shape2]() == 16 | |
| var args = argv() | |
| var exponent = Int(String(args[1])) if len(args) > 1 else 24 | |
| var repetitions = Int(String(args[2])) if len(args) > 2 else 21 | |
| var workers = Int(String(args[3])) if len(args) > 3 else num_logical_cores() | |
| if not (0 <= exponent <= 27 and repetitions > 0 and 1 <= workers <= 256): | |
| raise Error("usage: shape_benchmarks [exponent 0..27] [repetitions >0] [workers 1..256]") | |
| validate_matching() | |
| var data = Dataset(1 << exponent) | |
| print(t"N={len(data.compact)}, repetitions={repetitions}; compact=12 bytes, tagged=16 bytes") | |
| print("Times are medians in ms; positive throughput difference favors compact.") | |
| print("Workers | Matching | Workload | Compact ms | Tagged ms | Compact throughput difference") | |
| var worker_counts: List[Int] = [1] | |
| if workers != 1: | |
| worker_counts.append(workers) | |
| for worker_count in worker_counts: | |
| var pool = WorkerPool(worker_count) | |
| pool.start() | |
| run_benchmarks(pool, data, repetitions) | |
| print("PASS: matching checks, scan checksums, and copied values agree.") | |
| # === Native worker support === | |
| # This POSIX pool supplies native workers without an additional package and | |
| # keeps threads alive between passes. The raw pointers below cross | |
| # the C thread boundary. | |
| comptime CHUNK_SIZE = 32768 | |
| comptime VoidPtr = OpaquePointer[mut=True, MutUntrackedOrigin] | |
| comptime NullableVoidPtr = Optional[VoidPtr] | |
| comptime ChunkFunction = def(VoidPtr, Int, Int) thin abi("C") -> UInt64 | |
| @fieldwise_init | |
| struct ReadJob[T: Copyable](TrivialRegisterPassable): | |
| """A typed array view shared read-only during one parallel scan.""" | |
| var values: Span[Self.T, ImmUntrackedOrigin] | |
| @inline(.never) | |
| def sum_chunk[T: Copyable, operation: def(T) thin -> UInt64]( | |
| context: VoidPtr, start: Int, end: Int, | |
| ) abi("C") -> UInt64: | |
| """Sum one disjoint chunk, with operation specialized at compile time.""" | |
| ref job = context.unsafe_bitcast[ReadJob[T]]()[] | |
| var total: UInt64 = 0 | |
| var values = job.values[start:end] | |
| for i in range(len(values)): | |
| total += operation(values[i]) | |
| return total | |
| @fieldwise_init | |
| struct CopyJob[T: ImplicitlyCopyable & Deinitable](TrivialRegisterPassable): | |
| """Source and destination views for one parallel copy of disjoint arrays.""" | |
| var source: Span[Self.T, ImmUntrackedOrigin] | |
| var destination: Span[mut=True, Self.T, MutUntrackedOrigin] | |
| @inline(.never) | |
| def copy_chunk[T: ImplicitlyCopyable & Deinitable](context: VoidPtr, start: Int, end: Int) abi("C") -> UInt64: | |
| """Assign each value in this chunk and return the number copied.""" | |
| ref job = context.unsafe_bitcast[CopyJob[T]]()[] | |
| var source = job.source[start:end] | |
| var destination = job.destination[start:end] | |
| for i in range(len(source)): | |
| destination[i] = source[i] | |
| return UInt64(len(source)) | |
| @fieldwise_init | |
| struct Work(TrivialRegisterPassable): | |
| """The function, borrowed context, and array length for one pool pass.""" | |
| var function: ChunkFunction | |
| var context: VoidPtr | |
| var length: Int | |
| @fieldwise_init | |
| struct Worker(Copyable, Movable): | |
| """One thread's handles and result; padding separates result slots by cache lines.""" | |
| var start: VoidPtr | |
| var done: VoidPtr | |
| var queue: Pointer[Atomic[Int64], MutUntrackedOrigin] | |
| var work: Optional[Work] | |
| var stop: Bool | |
| var result: UInt64 | |
| var padding: SIMD[.uint64, 16] | |
| def worker_entry(context: VoidPtr) abi("C") -> NullableVoidPtr: | |
| """Wait for a pass, claim chunks until none remain, publish the sum, and repeat.""" | |
| comptime if CompilationTarget.is_macos(): | |
| # QOS_CLASS_USER_INITIATED requests throughput rather than background scheduling. | |
| _ = external_call["pthread_set_qos_class_self_np", c_int](c_uint(0x19), c_int(0)) | |
| var worker = context.unsafe_bitcast[Worker]() | |
| while True: | |
| wait_semaphore(worker[].start) | |
| if worker[].stop: | |
| return None | |
| var work = worker[].work.value() | |
| var total: UInt64 = 0 | |
| while True: | |
| var start = Int(worker[].queue[].fetch_add[ordering=Ordering.RELAXED](CHUNK_SIZE)) | |
| if start >= work.length: | |
| break | |
| total += work.function(work.context, start, min(start + CHUNK_SIZE, work.length)) | |
| worker[].result = total | |
| post_semaphore(worker[].done) | |
| struct WorkerPool: | |
| """Persistent threads with typed sum/copy operations and blocking completion. | |
| start() is called once after construction. Each pass divides the input into | |
| disjoint chunks. Threads claim chunks dynamically so faster cores can take | |
| more work. All threads finish before sum()/copy() returns. Thread creation | |
| is outside timing; wakeup, scheduling, and completion are inside timing. | |
| """ | |
| var worker_count: Int | |
| var queue: Atomic[Int64] | |
| var workers: List[Worker] | |
| var threads: List[UInt64] | |
| var done: VoidPtr | |
| def __init__(out self, worker_count: Int) raises: | |
| """Allocate stable worker contexts and blocking semaphores; do not launch yet.""" | |
| comptime assert CompilationTarget.is_macos() or CompilationTarget.is_linux() | |
| comptime assert size_of[Int]() == 8 | |
| self.worker_count = worker_count | |
| self.queue = Atomic[Int64](0) | |
| self.workers = List[Worker](capacity=worker_count) | |
| self.threads = List[UInt64](capacity=worker_count) | |
| var prefix = "/mjs-" + String(external_call["getpid", c_int]()) | |
| self.done = new_semaphore(prefix + "-d") | |
| for i in range(worker_count): | |
| self.workers.append(Worker(new_semaphore(prefix + "-" + String(i)), self.done, | |
| Pointer(to=self.queue).unsafe_origin_cast[MutUntrackedOrigin](), | |
| None, False, 0, SIMD[.uint64, 16](0))) | |
| def start(mut self): | |
| """Launch native threads after this non-movable pool reaches its final location.""" | |
| for i in range(self.worker_count): | |
| self.workers[i].queue = Pointer(to=self.queue).unsafe_origin_cast[MutUntrackedOrigin]() | |
| var thread: UInt64 = 0 | |
| if external_call["pthread_create", c_int](Pointer(to=thread), NullableVoidPtr(), | |
| worker_entry, self.workers.unsafe_ptr().unsafe_offset(i).unsafe_origin_cast[MutUntrackedOrigin]()) != 0: | |
| external_call["abort", NoneType]() | |
| self.threads.append(thread) | |
| def sum[T: Copyable, operation: def(T) thin -> UInt64, origin: ImmOrigin]( | |
| mut self, values: Span[T, origin], | |
| ) -> UInt64: | |
| """Apply operation to every value in parallel and sum the UInt64 results. | |
| The untracked view is confined to this synchronous thread boundary. | |
| keep() retains both the context and the caller's tracked array view | |
| until every worker has completed. Workers only read this array. | |
| """ | |
| var job = ReadJob[T](Span(unsafe_ptr=values.unsafe_ptr().unsafe_origin_cast[ImmUntrackedOrigin](), | |
| length=len(values))) | |
| var result = self.run(sum_chunk[T, operation], Pointer(to=job).unsafe_bitcast[NoneType]().unsafe_origin_cast[MutUntrackedOrigin](), len(values)) | |
| keep(job) | |
| keep(values) | |
| return result | |
| def copy[T: ImplicitlyCopyable & Deinitable, source_origin: ImmOrigin, destination_origin: MutOrigin]( | |
| mut self, source: Span[T, source_origin], destination: Span[mut=True, T, destination_origin], | |
| ) -> UInt64: | |
| """Copy disjoint equally sized arrays in parallel; return the number of values. | |
| The input/output loans remain alive until all threads finish. The | |
| atomic chunk queue ensures no two threads write the same element. | |
| """ | |
| var job = CopyJob[T]( | |
| Span(unsafe_ptr=source.unsafe_ptr().unsafe_origin_cast[ImmUntrackedOrigin](), length=len(source)), | |
| Span(unsafe_ptr=destination.unsafe_ptr().unsafe_origin_cast[MutUntrackedOrigin](), length=len(destination))) | |
| var result = self.run(copy_chunk[T], Pointer(to=job).unsafe_bitcast[NoneType]().unsafe_origin_cast[MutUntrackedOrigin](), len(source)) | |
| keep(job) | |
| keep(source) | |
| keep(destination) | |
| return result | |
| def run(mut self, function: ChunkFunction, context: VoidPtr, length: Int) -> UInt64: | |
| """Publish one chunk operation, wait for every thread, and combine partial sums.""" | |
| self.queue.store[ordering=Ordering.RELAXED](0) | |
| for ref worker in self.workers: | |
| worker.work = Work(function, context, length) | |
| post_semaphore(worker.start) | |
| for _ in range(self.worker_count): | |
| wait_semaphore(self.done) | |
| var total: UInt64 = 0 | |
| for ref worker in self.workers: | |
| total += worker.result | |
| return total | |
| def __deinit__(deinit self): | |
| """Stop and join the threads before freeing contexts and semaphore handles.""" | |
| for i in range(len(self.threads)): | |
| self.workers[i].stop = True | |
| post_semaphore(self.workers[i].start) | |
| for thread in self.threads: | |
| if external_call["pthread_join", c_int](thread, NullableVoidPtr()) != 0: | |
| external_call["abort", NoneType]() | |
| for ref worker in self.workers: | |
| _ = external_call["sem_close", c_int](worker.start) | |
| _ = external_call["sem_close", c_int](self.done) | |
| def new_semaphore(var name: String) raises -> VoidPtr: | |
| """Create a blocking POSIX semaphore and unlink its name immediately.""" | |
| # O_CREAT | O_EXCL have different numeric values on Darwin and Linux. | |
| comptime flags = 0x200 | 0x800 if CompilationTarget.is_macos() else 0x40 | 0x80 | |
| var result = external_call["sem_open", NullableVoidPtr, num_fixed_args=2]( | |
| name.as_c_string_span(), c_int(flags), c_uint(0o600), c_uint(0)) | |
| if not result: | |
| raise Error("sem_open failed") | |
| var semaphore = result.value() | |
| if Int(semaphore) == -1: | |
| raise Error("sem_open failed") | |
| if external_call["sem_unlink", c_int](name.as_c_string_span()) != 0: | |
| _ = external_call["sem_close", c_int](semaphore) | |
| raise Error("sem_unlink failed") | |
| return semaphore | |
| def wait_semaphore(semaphore: VoidPtr): | |
| """Block until signalled; retry if an OS signal interrupts the wait.""" | |
| comptime errno_function = "__error" if CompilationTarget.is_macos() else "__errno_location" | |
| while external_call["sem_wait", c_int](semaphore) != 0: | |
| var error = external_call[errno_function, Pointer[c_int, MutUntrackedOrigin]]()[] | |
| if error != 4: # EINTR on macOS/Linux. | |
| external_call["abort", NoneType]() | |
| def post_semaphore(semaphore: VoidPtr): | |
| """Signal that a worker may start, or that a worker has finished.""" | |
| if external_call["sem_post", c_int](semaphore) != 0: | |
| external_call["abort", NoneType]() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment