Skip to content

Multi-implementation + cost selection (generalize beyond sort) #147

Closed

Description

@godofecht

Summary

Axiom §§2, 20–21 separate intent (transform Spectrum from Frame) from implementations (scalar_fft / simd_fft / gpu_fft) with cost models; the compiler picks under hard/soft constraints (require / prefer / deploy profiles).

Flow already has a thin version of this for ordering:

The same pattern should become a general language mechanism, not a sort special-case—especially for DSP (FFT, filters), ML (tiny vs large model), and numerics (insertion vs radix).

Proposal

  1. Intent surface (existing or small sugar): name what must hold (Sorted, Spectrum, Prediction).
  2. Implementation registry: multiple lowerings with:
    • supports (cpu / simd / gpu)
    • symbolic or annotated cost (time / memory / transfer)
    • optional when guards (e.g. n < 32)
  3. Constraint vocabulary (start minimal):
    • hard: require latency < …, require memory < …, @rt_safe / no_allocation
    • soft: prefer minimise latency | energy | memory (profiles later)
  4. First consumers after sort: one audio transform and/or one ML path already in-tree.

Why not “become Axiom”

Flow’s primary abstraction remains evolution through time (VISION.md). This issue only steals Axiom’s intent ≠ implementation ≠ plan split where Flow already needs adaptive selection.

Acceptance

  • Design sketch: how impls are declared (attribute? implement block? stdlib registry?)
  • Ordering Phase 2 uses the same selector API as the general mechanism
  • At least two impls for one non-sort transform with a constraint that flips the choice
  • Soft prefer may stay parsed-only until a cost IR exists
  • Record syntax/design choice in docs/project/Questions.md before shipping sugar

Related

Activity

  1. godofecht commented on Aug 6, 2026

    @godofecht
    ContributorAuthor

    Landed on branch lang/plans-and-ordering.

    The mechanism

    src/flow/plan_selector.py knows nothing about sorting. It holds:

    • Facts: the immutable bag of what the compiler knows at one site.
    • Implementation: one lowering, declaring an applicability predicate, a scratch claim, a cost model, a tie-break rank, and a resolution string.
    • select(facts, location, detail): runs every implementation registered for the construct, applies the hard resource budget, keeps the cheapest survivor, and returns a record of the whole decision.

    The applicability predicate returns None to mean yes, and otherwise the sentence the report prints:

    register(
        Implementation(
            name="binary_search",
            construct="search",
            summary="lower-bound binary search; provenance proves the array is ascending",
            applicable=lambda f: (
                None
                if f.get("input_order", "unknown").startswith("asc")
                else f"input is not proven to be in ascending order "
                     f"(provenance: {f.get('input_order')})"
            ),
            cost=lambda f: math.log2(max(2.0, float(f.n))),
            rank=0,
            resolution="sort the array immediately before searching it",
        )
    )

    Writing the rejection as a sentence rather than a boolean is the design. A constraint that cannot explain itself is not worth having, and it is what makes #146 possible at all.

    Two constructs

    src/flow/ordering_plans.py registers eight implementations across two constructs.

    sort, six lowerings: already_ordered, reverse_in_place, counting, insertion, natural_merge, bottom_up_merge.

    search, new surface xs |> find(t) yielding the first matching index or -1, two lowerings: linear_scan and binary_search.

    They deliberately share facts. input_order is produced by the ordering-hints pass (#145) for sort and consumed by search:

    xs |> sort            # xs is now provably ascending
    let i = xs |> find(t) # so this is a binary search, not a scan
    

    That is the constraint flipping the choice this issue asks for. Insert a call taking xs between those lines and the fact is gone, the search drops back to a linear scan, and --explain says so.

    Constraint vocabulary, so far

    Hard, and enforced:

    • Applicability predicates over data facts (element kind, key range, provenance, size).
    • One resource budget: compiler-introduced scratch is capped at 256 KiB, because the merge plans buffer on the C stack. A candidate over budget is rejected before its cost is consulted, and the rejection names the budget and the overrun.

    Soft: cost minimisation only. Costs are estimated element operations from an annotated model, comparable within one construct and meaningless across constructs. The report says "not measurements" on every run so nobody quotes them as timings. Where a model was calibrated against a real measurement, the constant carries a comment pointing at the benchmark.

    Two escape hatches on the sort surface: adaptive asserts the input has structure and shifts the run estimate; general pins the general-purpose plan and drops every hint, which is what makes an honest benchmark baseline possible.

    Deliberately not built: require latency < …, prefer minimise energy, deploy profiles, and a supports cpu / simd / gpu axis. Those need a cost IR with real units. The current model has one dimension and admits it.

    Acceptance

    • Design sketch of how impls are declared: a stdlib-side registry, register(Implementation(...)), documented in docs/language/explainable-compilation.md "How a construct joins in"
    • Ordering Phase 2 uses the same selector API as the general mechanism: it is the general mechanism; sort has no private path
    • At least two impls for one non-sort transform with a constraint that flips the choice: search, flipped by input_order
    • Soft prefer stays unbuilt until a cost IR exists
    • Record the syntax choice in docs/project/Questions.md. The only new surface is xs |> find(t) plus the general policy word; both are documented in docs/language/ordering.md but not yet in Questions.md.

    What is left

    The first consumer outside ordering. An audio transform or an ML path would exercise the parts a sort cannot: a supports axis, transfer costs, a second cost dimension. Until then this is a working mechanism on two constructs, which was the point of keeping it small.

    Tests: tests/unit/test_plan_selector.py, 30 cases. Roughly half run against implementations invented in the test file so the selector's own contract is tested without any sort in the picture.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions