Skip to content

Commit efcaf3b

Browse files
committed
Add fixed-leaf pairwise floating summation
1 parent b1c6676 commit efcaf3b

7 files changed

Lines changed: 560 additions & 5 deletions

File tree

‎doc/native-arrays-0.1.md‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,45 @@ extrema follow the existing M4 contract, including deterministic signed-zero tie
7373
Products may overflow/underflow in serial order even where another grouping would
7474
not; no global relative-error promise is made near zero or overflow.
7575

76+
An explicit performance-oriented alternative is available for real floating sums:
77+
`ME_ARRAY_SUM_PAIRWISE`, or `me_graph_specialize_options.pairwise_sum = true`.
78+
The graph option applies only to single-region `sum` graphs; the map and
79+
accumulator must have the same float32/float64 dtype. Unsupported requests reject
80+
at specialization rather than silently changing policy. Zero/default options and
81+
callers using the original specialization-options struct size retain serial sums.
82+
83+
Pairwise mode partitions each reduction group's logical sequence into fixed
84+
128-element leaves. Each leaf uses eight independent accumulators, combines them
85+
in a balanced tree, then enters a bounded binary carry tree of leaf partials.
86+
Incomplete leaves survive iterator and reader boundaries. Masked positions
87+
contribute zero without loading their mapped value, and `initial` is added once
88+
to the completed sum. Empty sums preserve the ordinary identity/initial rules.
89+
Scratch for this tree is bounded independently of the number of elements.
90+
Axis selection, strided inputs and storage readers retain the same grouping.
91+
92+
This mode deliberately changes rounding, overflow/underflow behavior and floating
93+
flags relative to serial sums; it is not compensated or guaranteed correctly
94+
rounded. NaN payload selection is not promised to match serial execution.
95+
Results are invariant to iterator tile size, not to arbitrary caller partitioning:
96+
hosts must not split groups at thread-dependent boundaries and expect identical
97+
bytes. A future parallel adapter must preserve these logical leaves and the
98+
global tree. Strict graph execution does not enable this policy implicitly.
99+
100+
Block-oriented hosts can use the `ME_PAIRWISE_SUM_API` streaming interface.
101+
Initialize an invocation-local `me_pairwise_sum_state`, call
102+
`me_pairwise_sum_leaves` on globally aligned runs of complete 128-element leaves
103+
in parallel, then append their partials in logical order with
104+
`me_pairwise_sum_append`. Supply raw boundary fragments with
105+
`me_pairwise_sum_update`; append rejects a partially filled leaf. Call
106+
`me_pairwise_sum_finish` once at the end. Leaf output buffers must be disjoint
107+
from their inputs. State must not be shared concurrently. These helpers do not
108+
manage floating environments: hosts isolate and aggregate worker/merge flags.
109+
110+
With artifact tests enabled, `graph_pairwise` checks serial compatibility,
111+
tile-invariant float32/64 results, masks, reversed views, axes and nonfinite
112+
values. Run `build/tests/graph_pairwise --large` for a bounded-memory billion-lane
113+
ramp check and an informational resident serial/pairwise timing comparison.
114+
76115
The logical scheduler is serial. Floating flags aggregate through scoped native
77116
guards and caller fenv restoration; reporting is capability-qualified on WASM.
78117
Independent calls/buffers on a shared immutable artifact may run concurrently;

‎src/dsl_array.c‎

Lines changed: 163 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ static void a_load(const me_array_view *v, size_t offset, void *out) {
173173
}
174174
static bool a_axes(int rank, const me_array_options *o, bool *axes) {
175175
memset(axes, 0, ME_ARRAY_MAX_RANK * sizeof(bool));
176-
if (!o || o->version != ME_ARTIFACT_ARRAY_VERSION || o->reduction < ME_ARRAY_NONE || o->reduction > ME_ARRAY_ALL ||
176+
if (!o || o->version != ME_ARTIFACT_ARRAY_VERSION || o->reduction < ME_ARRAY_NONE || o->reduction > ME_ARRAY_SUM_PAIRWISE ||
177177
o->naxes < -1 || o->naxes > rank) return false;
178178
if (o->reduction == ME_ARRAY_NONE) return o->naxes == 0 && !o->initial && o->accumulator == ME_AUTO && !o->where;
179179
if (o->initial && (o->reduction == ME_ARRAY_ANY || o->reduction == ME_ARRAY_ALL)) return false;
@@ -193,7 +193,7 @@ static me_dtype a_dtype(me_dtype source, const me_array_options *o) {
193193
true;
194194
return a_width(o->accumulator) && compatible ? o->accumulator : ME_AUTO;
195195
}
196-
if ((o->reduction == ME_ARRAY_SUM || o->reduction == ME_ARRAY_PROD) &&
196+
if ((o->reduction == ME_ARRAY_SUM || o->reduction == ME_ARRAY_SUM_PAIRWISE || o->reduction == ME_ARRAY_PROD) &&
197197
!a_float(source) && !a_complex(source)) {
198198
return a_unsigned(source) && source != ME_BOOL ? ME_UINT64 : ME_INT64;
199199
}
@@ -207,6 +207,9 @@ me_artifact_status me_array_result_shape(const me_artifact *a, int rank, const i
207207
if (strcmp(me_artifact_schema_version(a), "0.1") || me_artifact_context_ndim(a) ||
208208
me_artifact_result_cardinality(a) != ME_ARTIFACT_ELEMENTWISE || !a_width(me_artifact_output_dtype(a))) return a_error(error, ME_ARTIFACT_ERR_UNSUPPORTED, "logical arrays require numeric elementwise rank-zero Menudet 0.1 beta");
209209
*dtype = a_dtype(me_artifact_output_dtype(a), o);
210+
if (o->reduction == ME_ARRAY_SUM_PAIRWISE &&
211+
(!a_float(*dtype) || *dtype != me_artifact_output_dtype(a)))
212+
return a_error(error, ME_ARTIFACT_ERR_UNSUPPORTED, "pairwise sum requires matching floating map and accumulator dtypes");
210213
if (*dtype == ME_AUTO) return a_error(error, ME_ARTIFACT_ERR_UNSUPPORTED, "unsupported accumulator signature");
211214
*out_rank = 0;
212215
for (int i = 0; i < rank; i++) {
@@ -343,6 +346,151 @@ static void a_combine(me_dtype dtype, int op, void *acc, const void *value) {
343346
a_cast(ME_UINT64,&z,dtype,acc);
344347
}
345348
}
349+
/* A fixed 128-lane logical leaf, with eight independent accumulators. Iterator
350+
* and reader boundaries never reset a leaf. Completed leaves enter a binary
351+
* carry tree; its depth is bounded by the number of bits in size_t. */
352+
typedef me_pairwise_sum_state a_pairwise_sum;
353+
static void a_pairwise_push(a_pairwise_sum *s, me_dtype dtype, uint64_t value) {
354+
size_t level = 0;
355+
while (s->occupied & ((size_t)1 << level)) {
356+
a_combine(dtype, ME_ARRAY_SUM, &s->tree[level], &value);
357+
value = s->tree[level];
358+
s->occupied &= ~((size_t)1 << level++);
359+
}
360+
s->tree[level] = value;
361+
s->occupied |= (size_t)1 << level;
362+
s->leaves++;
363+
}
364+
static void a_pairwise_leaf(a_pairwise_sum *s, me_dtype dtype) {
365+
uint64_t value = 0;
366+
if (dtype == ME_FLOAT64) {
367+
double *v = s->lanes.f64;
368+
double sum = ((v[0] + v[1]) + (v[2] + v[3])) +
369+
((v[4] + v[5]) + (v[6] + v[7]));
370+
memcpy(&value, &sum, sizeof(sum));
371+
} else {
372+
float *v = s->lanes.f32;
373+
float sum = ((v[0] + v[1]) + (v[2] + v[3])) +
374+
((v[4] + v[5]) + (v[6] + v[7]));
375+
memcpy(&value, &sum, sizeof(sum));
376+
}
377+
a_pairwise_push(s, dtype, value);
378+
memset(&s->lanes, 0, sizeof(s->lanes));
379+
s->used = 0;
380+
}
381+
static void a_pairwise_feed(a_pairwise_sum *s, me_dtype dtype, const void *values,
382+
const uint8_t *mask, size_t count) {
383+
size_t width = a_width(dtype), offset = 0;
384+
while (offset < count) {
385+
/* Keep full unmasked octets free of dynamic indexing and scalar
386+
* memcpy calls. Independent lanes permit ordinary SIMD/SLP without
387+
* fast-math or reassociation of any accumulator's additions. */
388+
if (!mask && !(s->used % 8) && count - offset >= 8) {
389+
#define PAIRWISE_OCTETS(type, member) do { \
390+
size_t end = count - offset; \
391+
if (end > ME_PAIRWISE_SUM_LEAF_ITEMS - s->used) end = ME_PAIRWISE_SUM_LEAF_ITEMS - s->used; \
392+
end = offset + (end & ~(size_t)7); \
393+
type *acc = s->lanes.member; \
394+
for (; offset < end; offset += 8, s->used += 8) { \
395+
type v[8]; \
396+
memcpy(v, (const uint8_t *)values + offset * sizeof(type), sizeof(v)); \
397+
acc[0] += v[0]; acc[1] += v[1]; \
398+
acc[2] += v[2]; acc[3] += v[3]; \
399+
acc[4] += v[4]; acc[5] += v[5]; \
400+
acc[6] += v[6]; acc[7] += v[7]; \
401+
} \
402+
} while (0)
403+
if (dtype == ME_FLOAT64) PAIRWISE_OCTETS(double, f64);
404+
else PAIRWISE_OCTETS(float, f32);
405+
#undef PAIRWISE_OCTETS
406+
if (s->used == ME_PAIRWISE_SUM_LEAF_ITEMS) a_pairwise_leaf(s, dtype);
407+
continue;
408+
}
409+
size_t n = 8 - s->used % 8;
410+
if (n > count - offset) n = count - offset;
411+
size_t first = s->used % 8;
412+
if (dtype == ME_FLOAT64) {
413+
for (size_t k = 0; k < n; k++) {
414+
double value = 0;
415+
if (!mask || mask[offset + k])
416+
memcpy(&value, (const uint8_t *)values + (offset + k)*width, width);
417+
s->lanes.f64[first + k] += value;
418+
}
419+
} else {
420+
for (size_t k = 0; k < n; k++) {
421+
float value = 0;
422+
if (!mask || mask[offset + k])
423+
memcpy(&value, (const uint8_t *)values + (offset + k)*width, width);
424+
s->lanes.f32[first + k] += value;
425+
}
426+
}
427+
offset += n;
428+
s->used += n;
429+
if (s->used == ME_PAIRWISE_SUM_LEAF_ITEMS) a_pairwise_leaf(s, dtype);
430+
}
431+
}
432+
static void a_pairwise_finish(a_pairwise_sum *s, me_dtype dtype, void *acc) {
433+
if (s->used) a_pairwise_leaf(s, dtype);
434+
/* Fold the newest (smallest) suffix into older, larger subtrees. */
435+
uint64_t tail = 0;
436+
bool found = false;
437+
for (size_t level = 0; level < sizeof(size_t)*CHAR_BIT; level++) {
438+
if (!(s->occupied & ((size_t)1 << level))) continue;
439+
if (found) a_combine(dtype, ME_ARRAY_SUM, &s->tree[level], &tail);
440+
tail = s->tree[level];
441+
found = true;
442+
}
443+
if (found) a_combine(dtype, ME_ARRAY_SUM, acc, &tail);
444+
}
445+
me_artifact_status me_pairwise_sum_init(me_pairwise_sum_state *s, me_dtype dtype) {
446+
if (!s || !a_float(dtype)) return ME_ARTIFACT_ERR_BINDING;
447+
memset(s, 0, sizeof(*s));
448+
s->dtype = dtype;
449+
return ME_ARTIFACT_SUCCESS;
450+
}
451+
me_artifact_status me_pairwise_sum_update(me_pairwise_sum_state *s, const void *values, size_t count) {
452+
if (!s || !a_float(s->dtype) || (count && !values) ||
453+
count > SIZE_MAX / a_width(s->dtype)) return ME_ARTIFACT_ERR_BINDING;
454+
if (s->leaves > SIZE_MAX / ME_PAIRWISE_SUM_LEAF_ITEMS || s->used >= ME_PAIRWISE_SUM_LEAF_ITEMS ||
455+
count > SIZE_MAX - s->leaves * ME_PAIRWISE_SUM_LEAF_ITEMS - s->used)
456+
return ME_ARTIFACT_ERR_BINDING;
457+
a_pairwise_feed(s, s->dtype, values, NULL, count);
458+
return ME_ARTIFACT_SUCCESS;
459+
}
460+
me_artifact_status me_pairwise_sum_append(me_pairwise_sum_state *s, const void *leaves, size_t count) {
461+
if (!s || !a_float(s->dtype) || s->used || (count && !leaves)) return ME_ARTIFACT_ERR_BINDING;
462+
if (s->leaves > SIZE_MAX / ME_PAIRWISE_SUM_LEAF_ITEMS ||
463+
count > SIZE_MAX / ME_PAIRWISE_SUM_LEAF_ITEMS - s->leaves)
464+
return ME_ARTIFACT_ERR_BINDING;
465+
size_t width = a_width(s->dtype);
466+
for (size_t i = 0; i < count; i++) {
467+
uint64_t value = 0;
468+
memcpy(&value, (const uint8_t *)leaves + i*width, width);
469+
a_pairwise_push(s, s->dtype, value);
470+
}
471+
return ME_ARTIFACT_SUCCESS;
472+
}
473+
me_artifact_status me_pairwise_sum_leaves(me_dtype dtype, const void *values,
474+
size_t count, void *leaves, size_t capacity) {
475+
size_t width = a_width(dtype);
476+
if (!a_float(dtype) || count % ME_PAIRWISE_SUM_LEAF_ITEMS || count > SIZE_MAX / width ||
477+
count / ME_PAIRWISE_SUM_LEAF_ITEMS > capacity / width ||
478+
(count && (!values || !leaves))) return ME_ARTIFACT_ERR_BINDING;
479+
a_pairwise_sum s = {0};
480+
for (size_t i = 0; i < count; i += ME_PAIRWISE_SUM_LEAF_ITEMS) {
481+
a_pairwise_feed(&s, dtype, (const uint8_t *)values + i*width, NULL, ME_PAIRWISE_SUM_LEAF_ITEMS);
482+
memcpy((uint8_t *)leaves + (i/ME_PAIRWISE_SUM_LEAF_ITEMS)*width, &s.tree[0], width);
483+
s.occupied = 0;
484+
s.leaves = 0;
485+
}
486+
return ME_ARTIFACT_SUCCESS;
487+
}
488+
me_artifact_status me_pairwise_sum_finish(me_pairwise_sum_state *s, void *output) {
489+
if (!s || !a_float(s->dtype) || !output) return ME_ARTIFACT_ERR_BINDING;
490+
memset(output, 0, a_width(s->dtype));
491+
a_pairwise_finish(s, s->dtype, output);
492+
return ME_ARTIFACT_SUCCESS;
493+
}
346494
static me_artifact_status a_run(const me_artifact *a, const me_array_view *inputs, int ninputs,
347495
int rank, const int64_t *shape, const me_array_options *o, void *output, size_t capacity,
348496
me_array_report *report, me_artifact_error *error, bool execute, bool identity_map,
@@ -351,6 +499,10 @@ static me_artifact_status a_run(const me_artifact *a, const me_array_view *input
351499
me_array_report local = {0}; if (!report) report = &local; memset(report,0,sizeof(*report));
352500
int rc = me_array_result_shape(a,rank,shape,o,&out_rank,out_shape,&dtype,error);
353501
if (rc) return rc;
502+
bool pairwise = o->reduction == ME_ARRAY_SUM_PAIRWISE;
503+
me_array_options normalized = *o;
504+
if (pairwise) normalized.reduction = ME_ARRAY_SUM;
505+
o = &normalized;
354506
me_array_view destination = {0};
355507
bool scatter = false;
356508
if (destination_view) {
@@ -456,6 +608,7 @@ static me_artifact_status a_run(const me_artifact *a, const me_array_view *input
456608
void *scratch = need_scratch ? malloc(tile * source_width) : NULL;
457609
if ((readers && !indices) || (o->where && !mask) || (need_scratch && !scratch)) { rc = ME_ARTIFACT_ERR_OOM; goto cleanup; }
458610
report->temporary_bytes = (indices ? tile * sizeof(size_t) : 0) + (mask ? tile : 0) + (scratch ? tile * source_width : 0);
611+
if (pairwise) report->temporary_bytes += sizeof(a_pairwise_sum);
459612
for (int b = 0; b < ninputs; b++) {
460613
const me_array_view *v = &inputs[binding[b]]; size_t w = a_width(v->dtype);
461614
if (!direct[b]) {
@@ -475,6 +628,8 @@ static me_artifact_status a_run(const me_artifact *a, const me_array_view *input
475628
bool gather = mask != NULL;
476629
for (int b = 0; b < ninputs; b++) gather |= !direct[b] && !(sources && sources[binding[b]].read);
477630
for (size_t g = 0; g < groups && !rc; g++) {
631+
a_pairwise_sum pairwise_state;
632+
if (pairwise) memset(&pairwise_state, 0, sizeof(pairwise_state));
478633
uint64_t acc = 0; bool initialized = false;
479634
unsigned char acc_complex[16] = {0};
480635
if (o->initial) { memcpy(&acc,o->initial,width); initialized = true; }
@@ -561,10 +716,14 @@ static me_artifact_status a_run(const me_artifact *a, const me_array_view *input
561716
}
562717
const void *values = direct_reduction ? buffers[0].data : o->reduction == ME_ARRAY_NONE ? NULL : scratch;
563718
bool handled = false;
719+
if (!rc && pairwise && values) {
720+
a_pairwise_feed(&pairwise_state, dtype, values, mask, count);
721+
handled = true;
722+
}
564723
/* Computed maps produce the same typed, contiguous tile as direct
565724
* inputs. Without a participation mask, reuse the serial typed
566725
* reducers instead of casting/dispatching once per mapped lane. */
567-
if (!rc && !mask && values &&
726+
if (!rc && !handled && !mask && values &&
568727
(o->reduction == ME_ARRAY_MIN || o->reduction == ME_ARRAY_MAX) &&
569728
dtype == me_artifact_output_dtype(a)) {
570729
uint64_t normalized = acc, result;
@@ -628,6 +787,7 @@ static me_artifact_status a_run(const me_artifact *a, const me_array_view *input
628787
begin += count;
629788
}
630789
if (!rc && o->reduction != ME_ARRAY_NONE) {
790+
if (pairwise) a_pairwise_finish(&pairwise_state, dtype, &acc);
631791
size_t offset = destination.offset + g*width;
632792
if (scatter) {
633793
int64_t coordinates[ME_ARRAY_MAX_RANK];

‎src/dsl_graph.c‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -820,8 +820,13 @@ me_graph_status me_graph_specialize(const me_graph_plan *p,
820820
g_error(error, -1, ME_GRAPH_SUCCESS, "");
821821
if (!out || !p || ninputs != p->ninputs || (ninputs && !inputs))
822822
return g_error(error, -1, ME_GRAPH_ERR_BINDING, "input metadata must exactly cover the graph");
823-
if (options && (options->struct_size != sizeof(*options) || options->version != ME_GRAPH_VERSION || options->tile_items > INT32_MAX))
823+
if (options && ((options->struct_size != sizeof(*options) &&
824+
options->struct_size != offsetof(me_graph_specialize_options, pairwise_sum)) ||
825+
options->version != ME_GRAPH_VERSION || options->tile_items > INT32_MAX))
824826
return g_error(error, -1, ME_GRAPH_ERR_FORMAT, "invalid specialization options");
827+
bool pairwise = options && options->struct_size == sizeof(*options) && options->pairwise_sum;
828+
if (pairwise && (p->nstages || p->reduction.reduction != ME_ARRAY_SUM))
829+
return g_error(error, -1, ME_GRAPH_ERR_UNSUPPORTED, "pairwise summation requires a single-region sum");
825830
me_graph_schedule *s = calloc(1, sizeof(*s));
826831
if (!s) return g_error(error, -1, ME_GRAPH_ERR_OOM, "schedule allocation failed");
827832
bool found[ME_MAX_VARS] = {0};
@@ -865,6 +870,7 @@ me_graph_status me_graph_specialize(const me_graph_plan *p,
865870
size_t total;
866871
if (!g_product(s->rank, s->shape, me_artifact_output_itemsize(p->map), &total)) goto fail;
867872
s->reduction = p->reduction;
873+
if (pairwise) s->reduction.reduction = ME_ARRAY_SUM_PAIRWISE;
868874
s->reduction.tile_items = options && options->tile_items ? options->tile_items : 1024;
869875
me_artifact_error native;
870876
int status = me_array_result_shape(p->map, s->rank, s->shape, &s->reduction,
@@ -887,6 +893,10 @@ me_graph_status me_graph_specialize(const me_graph_plan *p,
887893
for (int j = 0; j < p->ninputs; j++) if (p->map_indices[j] >= 0) per_item += g_width(p->types[j]);
888894
if (s->reduction.tile_items > SIZE_MAX / per_item) { message = "iterator scratch overflow"; goto fail; }
889895
s->scratch = s->reduction.tile_items * per_item;
896+
if (pairwise) {
897+
if (s->scratch > SIZE_MAX - 1024) { message = "pairwise scratch overflow"; goto fail; }
898+
s->scratch += 1024; /* Bounded binary tree plus eight leaf accumulators. */
899+
}
890900
atomic_fetch_add_explicit((atomic_uint *)&p->references, 1, memory_order_relaxed);
891901
s->plan = (me_graph_plan *)p; *out = s; return ME_GRAPH_SUCCESS;
892902
fail:

‎src/miniexpr_artifact.h‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#define MINIEXPR_ARTIFACT_H
77

88
#include "miniexpr.h"
9+
#include <limits.h>
910

1011
#ifdef __cplusplus
1112
extern "C" {
@@ -179,7 +180,29 @@ typedef struct {
179180
void *owner;
180181
} me_array_source;
181182
typedef enum { ME_ARRAY_NONE, ME_ARRAY_SUM, ME_ARRAY_PROD, ME_ARRAY_MIN,
182-
ME_ARRAY_MAX, ME_ARRAY_ANY, ME_ARRAY_ALL } me_array_reduction;
183+
ME_ARRAY_MAX, ME_ARRAY_ANY, ME_ARRAY_ALL,
184+
/* Opt-in fixed-block pairwise sum; same floating map/accumulator
185+
* dtype required. Existing SUM retains strict serial order. */
186+
ME_ARRAY_SUM_PAIRWISE } me_array_reduction;
187+
#define ME_PAIRWISE_SUM_API 1
188+
#define ME_PAIRWISE_SUM_LEAF_ITEMS 128
189+
/* Invocation-local streaming state. No FP environment management: hosts scope
190+
* their own arithmetic diagnostics. Append complete logical leaves in order;
191+
* update accepts raw boundary fragments. Never merge arbitrary storage sums. */
192+
typedef struct {
193+
union { float f32[8]; double f64[8]; } lanes;
194+
uint64_t tree[sizeof(size_t) * CHAR_BIT];
195+
size_t used, occupied, leaves;
196+
me_dtype dtype;
197+
} me_pairwise_sum_state;
198+
me_artifact_status me_pairwise_sum_init(me_pairwise_sum_state *state, me_dtype dtype);
199+
me_artifact_status me_pairwise_sum_update(me_pairwise_sum_state *state,
200+
const void *values, size_t count);
201+
me_artifact_status me_pairwise_sum_append(me_pairwise_sum_state *state,
202+
const void *leaves, size_t count);
203+
me_artifact_status me_pairwise_sum_leaves(me_dtype dtype, const void *values,
204+
size_t count, void *leaves, size_t capacity);
205+
me_artifact_status me_pairwise_sum_finish(me_pairwise_sum_state *state, void *output);
183206
typedef struct {
184207
unsigned version;
185208
me_array_reduction reduction;

0 commit comments

Comments
 (0)