diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 73fb9e2..72b8e51 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -273,6 +273,8 @@ jobs: run: | cmake -S . -B build/sanitizers -G Ninja \ -DCMAKE_BUILD_TYPE=Debug \ + -DSMARTPARALLEL_BUILD_VISION=ON \ + -DSMARTPARALLEL_ENABLE_OPENCV_PROVIDER=OFF \ -DSMARTPARALLEL_BUILD_VALIDATION=ON \ -DSMARTPARALLEL_BUILD_BENCHMARKS=OFF \ -DSMARTPARALLEL_BUILD_REAL_WORLD_BENCHMARKS=OFF \ @@ -285,3 +287,63 @@ jobs: - name: Run sanitizer correctness tests run: ctest --test-dir build/sanitizers --output-on-failure --parallel 1 + + native-vision: + name: linux-clang-release-native-vision + runs-on: ubuntu-latest + timeout-minutes: 25 + env: + CC: clang + CXX: clang++ + steps: + - name: Check out SmartParallel + uses: actions/checkout@v4 + + - name: Configure native vision validation + run: | + cmake -S . -B build/native-vision -G Ninja \ + -DCMAKE_BUILD_TYPE=Release \ + -DSMARTPARALLEL_BUILD_VISION=ON \ + -DSMARTPARALLEL_ENABLE_OPENCV_PROVIDER=OFF \ + -DSMARTPARALLEL_BUILD_VALIDATION=ON \ + -DSMARTPARALLEL_BUILD_BENCHMARKS=OFF \ + -DSMARTPARALLEL_ENABLE_TBB=OFF \ + -DSMARTPARALLEL_INSTALL=ON \ + -DCMAKE_INSTALL_PREFIX=${{ github.workspace }}/build/native-vision-install + + - name: Build and test native vision + run: | + cmake --build build/native-vision --parallel 2 + ctest --test-dir build/native-vision --output-on-failure --parallel 2 + cmake --install build/native-vision + + - name: Configure installed vision consumer + run: | + cmake -S tests/package-consumer-vision -B build/native-vision-consumer -G Ninja \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_PREFIX_PATH=${{ github.workspace }}/build/native-vision-install + + - name: Build installed vision consumer + run: cmake --build build/native-vision-consumer --parallel 2 + + - name: Run installed vision consumer + run: ctest --test-dir build/native-vision-consumer --output-on-failure + + documentation: + name: documentation-and-release-evidence + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Check out SmartParallel + uses: actions/checkout@v4 + + - name: Validate documentation, release metadata, and accepted evidence + run: python3 tools/check_documentation.py + + - name: Validate Python publication tools + run: | + python3 -m py_compile \ + tools/analyze_v15_adaptive_routes.py \ + tools/generate_v15_benchmark_plots.py \ + tools/publish_v15_benchmark_docs.py \ + tools/check_documentation.py diff --git a/.gitignore b/.gitignore index 0df4343..235bb46 100644 --- a/.gitignore +++ b/.gitignore @@ -37,10 +37,11 @@ Thumbs.db build_*/ # Generated benchmark and documentation artifacts -# The final v1.1 real-world CSV/Markdown results are intentionally versioned. +# Accepted release evidence is published under docs/*/assets; local validation output stays ignored. validation/output/*.csv !validation/output/v1.4.0_parallel_algorithms.csv !validation/output/v1.4.0_parallel_algorithms_raw.csv +validation/output/v1.5.0_adaptive_routes/ validation/output/plots/ docs/generated/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 02e3ff9..521a823 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,56 @@ All notable public changes to SmartParallel are documented here. Detailed internal milestone history is retained in [`docs/archive/v1.1-development/CHANGELOG_DEVELOPMENT_HISTORY.md`](docs/archive/v1.1-development/CHANGELOG_DEVELOPMENT_HISTORY.md). +## [1.5.0] — Adaptive execution routes + +### Added + +- Optional semantic vision module exported separately as `SmartParallel::vision` through the `SmartParallelVision` CMake package. +- `smart::vision::threshold` with exact one-channel `uint8_t` Binary and BinaryInverse semantics over contiguous, strided, disjoint, or exact in-place image views. +- Automatic complete-route selection across Native Sequential, Native ThreadPool, Native oneTBB, and optional OpenCV `cv::threshold`; Native StaticThread remains forceable for diagnostics. +- Bounded sharded route learning with two priming calls, balanced successive elimination, adaptive 3–11 sample windows, median/MAD bounds, independent winner holdout, conservative equivalent-route preference, single-flight probing, and bounded profile retention. +- Sparse performance-drift sentinels and four-invocation current-context ABBA revalidation, allowing a stable profile to replace an earlier winner when current runtime conditions change. +- Runtime-selected AVX2, SSE2, and portable branchless Native threshold kernels shared by every Native scheduler route. +- Zero-copy OpenCV `cv::Mat` views, provider build/runtime fingerprinting, cached provider state, and explicit `refresh_provider_state()` invalidation. +- Thread-local stable-route hot dispatch and operation diagnostics covering route, cache, learning, holdout, drift, revalidation, participants, chunks, timing state, and authentication. +- Route-training telemetry with training/current baselines, per-route statistics, holdout evidence, latest current-context comparison, and route-switch count. +- Deterministic validation for exact semantics, SIMD paths, route learning, noisy/outlier inputs, holdout reversal, distribution shift, concurrency, nested fallback, package consumption, and publication probe isolation. +- Proof-driven publication workflow with identical memory for every route, an independent sequential oracle, balanced deployment and steady-state orders, batched adjacent ABBA/BAAB dispatch measurement, raw schema v6, learning schema v2, Markdown/CSV evidence, and dependency-free SVG figures. +- Release documentation with accepted results, methodology, environment metadata, source hashes, generated benchmark assets, and a focused `v15_adaptive_threshold` example. + +### Changed + +- Extended SmartParallel from scheduler selection alone to complete-implementation selection for recognized semantic operations, without changing `IExecutionBackend` or the v1.4 generic algorithms. +- Stable Auto calls now use a compact exact thread-local key before full provider/profile construction and remain timer-free except for sparse drift sentinels. +- Equivalent route choices prefer Native Sequential, then Native parallel routes, then external providers when measured differences remain inside the configured equivalence band. +- The publication workflow learns under repeated calls, adapts under a balanced interleaved deployment regime, waits for a clean settled streak, and pauses maintenance only for the final timed matrix. + +### Compatibility + +- Existing `parallel_for` and v1.4 algorithm APIs are unchanged. +- The core `SmartParallel::smart_parallel` package remains independent of OpenCV and the vision module. +- OpenCV and `SmartParallel::vision` remain opt-in. +- Native-only builds provide the same public threshold API with OpenCV excluded from the candidate set. + +### Accepted validation + +- Complete deterministic suite: **18/18 passed**. +- Accepted Windows/MSVC publication: **2,238 correct and authenticated samples**. +- Route selection: **6/6 passed**. +- Native kernel versus independent oracle: **6/6 passed**. +- Stable Auto dispatch: **6/6 passed**. +- Combined release gate: **6/6 passed**. +- Recorded machine: 16 logical threads, SmartParallel worker budget 16, OpenCV 4.12.0, OpenCL disabled, authenticated AVX2 Native kernel. +- Auto achieved a **1.16× geometric-mean speedup over the independent sequential loop** and **1.48× over direct OpenCV** on the recorded machine. +- The two 1080p profiles initially selected OpenCV, detected a changed deployment regime, and switched once to Native Sequential using current-context evidence. +- Clang warnings-as-errors, ASan/UBSan, Native-only and OpenCV-enabled package consumers, core dependency isolation, and the retained v1.4 smoke matrix passed. + +### Limitations + +- v1.5 begins with one semantic operation; arbitrary `parallel_transform` lambdas remain Native-only because equivalence to a specialized provider cannot be proven safely. +- Route learning is in-process and root-only. Persistent operation profiles and coordinated external-runtime participant leasing remain future work. +- Performance choices and speedups are machine-specific. + ## [1.4.0] — Parallel algorithm expansion ### Added @@ -122,6 +172,7 @@ All notable public changes to SmartParallel are documented here. Detailed intern - Added ThreadPool, StaticThread, oneTBB, and sequential execution paths. - Added bounded runtime experience, diagnostics, validation programs, and the original OpenCV/scientific benchmark suite. +[1.5.0]: docs/v1.5/release-notes.md [1.4.0]: docs/v1.4/release-notes.md [1.3.0]: docs/v1.3/release-notes.md [1.1.0]: docs/v1.1/release-notes.md diff --git a/CMakeLists.txt b/CMakeLists.txt index 0ed182e..1295330 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -21,8 +21,8 @@ endif() project( SmartParallel - VERSION 1.4.0 - DESCRIPTION "Adaptive parallel scheduling for modern C++" + VERSION 1.5.0 + DESCRIPTION "Adaptive parallel execution for modern C++" LANGUAGES CXX ) @@ -78,6 +78,16 @@ option(SMARTPARALLEL_BUILD_V140_ALGORITHM_VALIDATION "Build v1.4 parallel algorithm correctness validation" OFF) option(SMARTPARALLEL_BUILD_V140_ALGORITHM_BENCHMARKS "Build v1.4 parallel algorithm benchmark suite" OFF) +option(SMARTPARALLEL_BUILD_VISION + "Build the v1.5 semantic vision operation module" OFF) +option(SMARTPARALLEL_ENABLE_OPENCV_PROVIDER + "Enable the optional OpenCV vision execution route" OFF) +option(SMARTPARALLEL_REQUIRE_OPENCV_PROVIDER + "Fail configuration when the requested OpenCV provider is unavailable" OFF) +option(SMARTPARALLEL_BUILD_V150_VISION_VALIDATION + "Build v1.5 adaptive execution-route correctness validation" OFF) +option(SMARTPARALLEL_BUILD_V150_VISION_BENCHMARKS + "Build v1.5 adaptive execution-route benchmark suite" OFF) option(SMARTPARALLEL_BUILD_SCIENTIFIC_TEST1 "Build scientific Test 1: numerical integration" OFF) option(SMARTPARALLEL_BUILD_SCIENTIFIC_TEST2 @@ -101,6 +111,10 @@ option(SMARTPARALLEL_BUILD_PARTICLE_BENCHMARK option(SMARTPARALLEL_REQUIRE_REAL_WORLD_DEPENDENCIES "Fail configuration when a requested real-world dependency is unavailable" OFF) +if(SMARTPARALLEL_ENABLE_OPENCV_PROVIDER) + set(SMARTPARALLEL_BUILD_VISION ON) +endif() + include(SmartParallelOptions) include(SmartParallelHelpers) @@ -127,6 +141,26 @@ endif() add_subdirectory(src) +set(SMARTPARALLEL_VISION_HAS_OPENCV 0) +if(SMARTPARALLEL_ENABLE_OPENCV_PROVIDER) + find_package(OpenCV CONFIG QUIET COMPONENTS core imgproc) + if(NOT OpenCV_FOUND) + find_package(OpenCV QUIET COMPONENTS core imgproc) + endif() + if(OpenCV_FOUND) + set(SMARTPARALLEL_VISION_HAS_OPENCV 1) + elseif(SMARTPARALLEL_REQUIRE_OPENCV_PROVIDER) + message(FATAL_ERROR + "SMARTPARALLEL_REQUIRE_OPENCV_PROVIDER=ON but OpenCV core/imgproc was not found") + else() + message(WARNING "OpenCV was not found; the v1.5 vision module will use native routes only") + endif() +endif() + +if(SMARTPARALLEL_BUILD_VISION) + add_subdirectory(vision) +endif() + if(SMARTPARALLEL_BUILD_EXAMPLES) add_subdirectory(examples) endif() @@ -146,6 +180,7 @@ if(SMARTPARALLEL_INSTALL) DIRECTORY include/ DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" COMPONENT Development + PATTERN "smart/vision" EXCLUDE ) install( @@ -194,4 +229,53 @@ if(SMARTPARALLEL_INSTALL) DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/SmartParallel" COMPONENT Development ) + + if(SMARTPARALLEL_BUILD_VISION) + install( + DIRECTORY include/smart/vision/ + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/smart/vision" + COMPONENT Development + ) + + install( + TARGETS smart_parallel_vision + EXPORT SmartParallelVisionTargets + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" + COMPONENT Runtime + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" + COMPONENT Runtime + NAMELINK_COMPONENT Development + ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" + COMPONENT Development + INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" + ) + + configure_package_config_file( + "${CMAKE_CURRENT_SOURCE_DIR}/cmake/SmartParallelVisionConfig.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/SmartParallelVisionConfig.cmake" + INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/SmartParallelVision" + ) + + write_basic_package_version_file( + "${CMAKE_CURRENT_BINARY_DIR}/SmartParallelVisionConfigVersion.cmake" + VERSION "${PROJECT_VERSION}" + COMPATIBILITY SameMajorVersion + ) + + install( + EXPORT SmartParallelVisionTargets + FILE SmartParallelVisionTargets.cmake + NAMESPACE SmartParallel:: + DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/SmartParallelVision" + COMPONENT Development + ) + + install( + FILES + "${CMAKE_CURRENT_BINARY_DIR}/SmartParallelVisionConfig.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/SmartParallelVisionConfigVersion.cmake" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/SmartParallelVision" + COMPONENT Development + ) + endif() endif() diff --git a/CMakePresets.json b/CMakePresets.json index d1c50f7..ef1f513 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -113,6 +113,25 @@ "SMARTPARALLEL_ENABLE_SANITIZERS": "ON", "SMARTPARALLEL_INSTALL": "OFF" } + }, + { + "name": "v15-adaptive-routes", + "displayName": "v1.5 Adaptive Execution Routes Release validation", + "inherits": "release", + "binaryDir": "${sourceDir}/build/v15-adaptive-routes", + "cacheVariables": { + "VCPKG_MANIFEST_FEATURES": "vision-opencv", + "SMARTPARALLEL_BUILD_VISION": "ON", + "SMARTPARALLEL_ENABLE_OPENCV_PROVIDER": "ON", + "SMARTPARALLEL_REQUIRE_OPENCV_PROVIDER": "ON", + "SMARTPARALLEL_BUILD_VALIDATION": "ON", + "SMARTPARALLEL_BUILD_V150_VISION_VALIDATION": "ON", + "SMARTPARALLEL_BUILD_V150_VISION_BENCHMARKS": "ON", + "SMARTPARALLEL_BUILD_BENCHMARKS": "OFF", + "SMARTPARALLEL_ENABLE_TBB": "ON", + "SMARTPARALLEL_REQUIRE_TBB": "ON", + "SMARTPARALLEL_INSTALL": "ON" + } } ], "buildPresets": [ @@ -155,6 +174,10 @@ { "name": "ci-sanitizers", "configurePreset": "ci-sanitizers" + }, + { + "name": "v15-adaptive-routes", + "configurePreset": "v15-adaptive-routes" } ], "testPresets": [ @@ -199,6 +222,13 @@ "output": { "outputOnFailure": true } + }, + { + "name": "v15-adaptive-routes", + "configurePreset": "v15-adaptive-routes", + "output": { + "outputOnFailure": true + } } ] } diff --git a/README.md b/README.md index a62986d..fe567c0 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,18 @@ # SmartParallel -SmartParallel is a C++17 library that chooses and coordinates CPU parallel-loop execution at runtime, including nested loops that would otherwise oversubscribe the machine. +SmartParallel is a C++17 adaptive execution framework. It chooses and coordinates CPU parallel-loop scheduling at runtime and, for recognized semantic operations, can also select between complete Native and specialized implementations. ## What it solves The fastest way to execute a loop depends on callback cost, iteration count, irregularity, backend overhead, and whether the loop is already inside parallel work. Hard-coding one strategy everywhere can make small loops slower and nested loops unsafe or wasteful. -SmartParallel provides an adaptive loop runtime, coordinated nested execution, cross-platform validation, and a v1.4 parallel-algorithm layer. The stabilized runtime continues to run across Windows, Linux, and macOS: +SmartParallel provides an adaptive loop runtime, coordinated nested execution, cross-platform validation, a v1.4 parallel-algorithm layer, and an optional v1.5 semantic-operation layer that can choose between Native SmartParallel and specialized implementations. The stabilized runtime continues to run across Windows, Linux, and macOS: - **SmartParallel v1.0 — Automatic Loop Optimization:** selects a sequential or parallel execution strategy and improves repeated decisions using runtime observations. - **SmartParallel v1.1 — Nested Parallelism Coordination:** coordinates nested loops through a shared root session, bounded worker leases, automatic frontier selection, and stable-plan reuse. - **SmartParallel v1.3 — Cross-Platform CI and Portability:** validates the same scheduler and API on Windows/MSVC, Linux/GCC and Clang, and macOS/Apple Clang, including installed-package consumers and oneTBB on/off builds. - **SmartParallel v1.4 — Parallel Algorithm Expansion:** adds adaptive elementwise, reduction, counting, predicate, and search algorithms, including pre-scheduler hot dispatch for cheap operations. +- **SmartParallel v1.5 — Adaptive Execution Routes:** adds optional semantic operations whose automatic mode can learn between complete Native routes and specialized providers, beginning with exact 8-bit thresholding and OpenCV. ## Minimal example @@ -49,6 +50,16 @@ auto total = smart::parallel_transform_reduce( [](double value) { return value * value; }); ``` +The optional v1.5 vision module expresses an operation while leaving the complete route automatic: + +```cpp +#include + +smart::vision::threshold(source, destination); +``` + +Depending on measured behavior and availability, the same call can use Native Sequential, Native ThreadPool, Native oneTBB, or OpenCV `cv::threshold`. + ## Capabilities - Runtime selection between sequential, ThreadPool, StaticThread, and oneTBB execution. @@ -59,7 +70,24 @@ auto total = smart::parallel_transform_reduce( - Exception propagation, cooperative cancellation, exactly-once validation, and structured trace export. - Native Windows, Linux, and macOS CPU-topology/cache discovery with conservative fallbacks. - Fourteen adaptive v1.4 algorithms covering transforms, reductions, counting, predicates, and search, with a direct one-pass path when automatic scheduling selects sequential execution. -- CMake package installation as `SmartParallel::smart_parallel`. +- Optional v1.5 semantic threshold operation with balanced successive-elimination learning, independent holdout verification, sparse drift sentinels, current-context ABBA revalidation, hot-cache reuse, runtime-selected AVX2/SSE2 native kernels, exact strided/in-place support, and optional zero-copy OpenCV execution. +- Core CMake package installation as `SmartParallel::smart_parallel`, plus the optional separate `SmartParallel::vision` target. + +## v1.5 adaptive-route results + +The accepted Windows/MSVC Release publication run evaluated exact `uint8_t` thresholding across six image profiles from 320×240 through 8K, including a strided 1080p ROI: + +- all **2,238 measured samples** passed exact-output correctness and route authentication; +- all **6/6 combined release gates** passed; +- Auto achieved a **1.16× geometric-mean speedup over the independent sequential loop** and **1.48× over direct OpenCV** on the recorded machine; +- Auto settled on Native Sequential for the small and 1080p profiles and Native ThreadPool for 4K and 8K; +- the two 1080p profiles initially learned OpenCV, detected a changed deployment regime, and switched once to Native Sequential; +- the authenticated Native AVX2 kernel passed the independent compiler-oracle gate on all six presets; +- stable Auto dispatch was approximately **0.012–0.051 µs** for the small and medium profiles, while large-profile intervals were correctly reported as statistically inconclusive passes. + +![SmartParallel v1.5 automatic speedup](docs/v1.5/assets/benchmarks/v1.5.0_automatic_speedup.svg) + +These measurements are machine-specific. The release claim is that Auto selected a route within the declared equivalence gate and adapted when its original decision became stale—not that one provider is universally fastest. See the [complete v1.5 benchmark report](docs/v1.5/benchmarks.md), [methodology](docs/v1.5/benchmark-methodology.md), and [reproduction guide](docs/v1.5/benchmark-reproduction.md). ## v1.4 algorithm results @@ -87,7 +115,7 @@ The results are machine-specific measurements, not universal guarantees. See the ## Build -Requirements: CMake 3.20+, a C++17 compiler, and oneTBB only when the oneTBB backend is enabled. SmartParallel v1.4 is continuously validated with MSVC, GCC, Clang, and Apple Clang. The repository includes a vcpkg manifest for oneTBB and optional real-world benchmark dependencies. +Requirements: CMake 3.20+, a C++17 compiler, and oneTBB only when the oneTBB backend is enabled. OpenCV is required only when the optional v1.5 OpenCV route is enabled. SmartParallel is continuously validated with MSVC, GCC, Clang, and Apple Clang. The repository includes a vcpkg manifest for oneTBB and optional real-world benchmark dependencies. ```text cmake --preset release @@ -105,17 +133,35 @@ find_package(SmartParallel CONFIG REQUIRED) target_link_libraries(my_application PRIVATE SmartParallel::smart_parallel) ``` +When the optional vision module was installed: + +```cmake +find_package(SmartParallelVision CONFIG REQUIRED) +target_link_libraries(my_application PRIVATE SmartParallel::vision) +``` + Windows users can build, test, and benchmark every v1.4 algorithm with: ```bat set "VCPKG_ROOT=D:\Tools\vcpkg" && scripts\validation\run_v14_algorithm_release_validation.bat 7 ``` +Run the v1.5 adaptive-route publication workflow with: + +```bat +set "VCPKG_ROOT=D:\Tools\vcpkg" && scripts\validation\run_v15_adaptive_routes_release_validation.bat 31 +``` + +The publication workflow first learns under repeated calls, then enters a balanced interleaved deployment regime with normal drift detection and current-context revalidation enabled. After the route settles, maintenance is paused only for the clean timed matrix. The workflow records training and current baselines, route switches, drift evidence, balanced route orders, and batched adjacent ABBA/BAAB dispatch overhead. Production drift detection and revalidation remain enabled outside that measurement window. + The historical v1.1 real-world suite remains available through `scripts\benchmarks\run_real_world_complete.bat`. See the [v1.4 API](docs/v1.4/api.md), [architecture](docs/v1.4/architecture.md), [benchmark results](docs/v1.4/benchmarks.md), [v1.4 reproduction guide](docs/v1.4/benchmark-reproduction.md), [v1.3 cross-platform installation guide](docs/v1.3/installation.md), [GitHub Actions setup](docs/v1.3/ci-and-github-setup.md), [native hardware discovery](docs/v1.3/native-hardware-discovery.md), and [release checklist](docs/v1.3/release-checklist.md). ## Documentation -- [v1.4 documentation](docs/v1.4/README.md) — current parallel-algorithm release +- [v1.5 documentation](docs/v1.5/README.md) — adaptive execution routes and optional OpenCV provider +- [v1.5 benchmark results](docs/v1.5/benchmarks.md) — accepted 6/6 proof-gate publication and figures +- [v1.5 benchmark methodology](docs/v1.5/benchmark-methodology.md) — fairness, learning, adaptation, and release gates +- [v1.4 documentation](docs/v1.4/README.md) — parallel-algorithm release retained by v1.5 - [v1.4 benchmark results](docs/v1.4/benchmarks.md) — accepted automatic/forced backend matrix and graphs - [v1.3 documentation](docs/v1.3/README.md) — portability and CI release - [v1.1 runtime documentation](docs/v1.1/README.md) — scheduler and nested-parallelism behavior retained by v1.4 @@ -131,7 +177,7 @@ The historical v1.1 real-world suite remains available through `scripts\benchmar ## Project status -**Current release: v1.4.0.** v1.4 keeps the stabilized scheduler and nested runtime while adding adaptive elementwise, reduction, counting, predicate, and search APIs. The repository now includes accepted v1.4 algorithm measurements and the retained v1.1 real-world integration results; performance benchmarks remain manual and machine-specific. +**Current release: v1.5.0.** v1.5 preserves the stabilized scheduler and v1.4 algorithms while adding an optional semantic-operation layer that learns between complete Native and OpenCV threshold routes, verifies its initial winner, detects performance drift, and switches using current-context evidence. The accepted threshold publication passed all 6/6 combined gates with 2,238 correct and authenticated samples. The repository also retains the accepted v1.4 algorithm measurements and v1.1 real-world integration results. Performance benchmarks remain manual and machine-specific. Important boundaries remain: admission is per root rather than process-wide, global configuration must not be mutated concurrently, traces add overhead, experience is in-memory by default, and automatic scheduling is not guaranteed to beat the best manually selected strategy on every workload. diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt index 418dcd0..97255d8 100644 --- a/benchmarks/CMakeLists.txt +++ b/benchmarks/CMakeLists.txt @@ -3,3 +3,5 @@ add_subdirectory(v1.0.0) add_subdirectory(v1.1.0) add_subdirectory(v1.4.0) + +add_subdirectory(v1.5.0) diff --git a/benchmarks/README.md b/benchmarks/README.md index 33df3b8..50f8b07 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -1,39 +1,41 @@ # SmartParallel benchmark suites -## v1.4.0 parallel algorithm suite +## Current release suite: v1.5.0 adaptive execution routes -[`benchmarks/v1.4.0/`](v1.4.0/README.md) benchmarks every v1.4 public algorithm against a sequential reference and the available SmartParallel backends. Each repetition is checksum validated. +[`benchmarks/v1.5.0/`](v1.5.0/) evaluates exact `uint8_t` thresholding across Native SmartParallel routes and the optional OpenCV provider. The publication workflow validates correctness, route authentication, identical memory conditions, initial learning, runtime adaptation, Native-kernel quality, and stable Auto dispatch overhead. ```bat -set "VCPKG_ROOT=D:\Tools\vcpkg" && scripts\validation\run_v14_algorithm_release_validation.bat 7 +set "VCPKG_ROOT=D:\Tools\vcpkg" && scripts\validation\run_v15_adaptive_routes_release_validation.bat 31 ``` -Results are written to `validation/output/v1.4.0_parallel_algorithms.csv` and the matching `_raw.csv` file. The suite is manual and is not a CI merge gate. +Results are written to a timestamped directory and ZIP under: -## Current performance suite: v1.1.0 (retained for v1.3) +```text +validation/output/v1.5.0_adaptive_routes/ +``` -The current recorded performance suite is [`benchmarks/v1.1.0/`](v1.1.0/README.md). Its real-world integrations cover OpenCV image pipelines, LZ4 compression, custom BVH construction, and a custom particle simulation. +The authoritative public report is [`docs/v1.5/benchmarks.md`](../docs/v1.5/benchmarks.md), with methodology in [`docs/v1.5/benchmark-methodology.md`](../docs/v1.5/benchmark-methodology.md). -The authoritative public report is [`docs/v1.1/benchmarks.md`](../docs/v1.1/benchmarks.md). Methodology and reproduction instructions live in the same documentation tree rather than being duplicated here. +## Retained v1.4.0 parallel algorithm suite -Run the complete Windows suite from the repository root: +[`benchmarks/v1.4.0/`](v1.4.0/README.md) benchmarks every v1.4 public algorithm against a sequential reference and the available SmartParallel scheduler backends. Each repetition is checksum validated. ```bat -set "VCPKG_ROOT=D:\Tools\vcpkg" && scripts\benchmarks\run_real_world_complete.bat 31 +set "VCPKG_ROOT=D:\Tools\vcpkg" && scripts\validation\run_v14_algorithm_release_validation.bat 7 ``` -Results are written to: +Results are written to `validation/output/v1.4.0_parallel_algorithms.csv` and the matching `_raw.csv` file. The suite is manual and is not a CI merge gate. -```text -validation/output/real_world/ -``` +## Retained v1.1.0 real-world suite -Regenerate the release figures with: +[`benchmarks/v1.1.0/`](v1.1.0/README.md) covers OpenCV image pipelines, LZ4 compression, custom BVH construction, and a custom particle simulation. -```text -python tools/plot_real_world_results.py +```bat +set "VCPKG_ROOT=D:\Tools\vcpkg" && scripts\benchmarks\run_real_world_complete.bat 31 ``` -## Historical suite: v1.0.0 +The authoritative report is [`docs/v1.1/benchmarks.md`](../docs/v1.1/benchmarks.md). + +## Historical v1.0.0 suite -[`benchmarks/v1.0.0/`](v1.0.0/README.md) preserves the original OpenCV, scientific, stress, overhead, decision-quality, CSV, and figure suite. It remains available for historical comparison but is not the current release benchmark. +[`benchmarks/v1.0.0/`](v1.0.0/README.md) preserves the original OpenCV, scientific, stress, overhead, decision-quality, CSV, and figure suite for historical comparison. diff --git a/benchmarks/v1.5.0/CMakeLists.txt b/benchmarks/v1.5.0/CMakeLists.txt new file mode 100644 index 0000000..f4f0f09 --- /dev/null +++ b/benchmarks/v1.5.0/CMakeLists.txt @@ -0,0 +1,34 @@ +if(SMARTPARALLEL_BUILD_V150_VISION_BENCHMARKS) + if(NOT TARGET smart_parallel_vision) + message(FATAL_ERROR + "SMARTPARALLEL_BUILD_V150_VISION_BENCHMARKS requires SMARTPARALLEL_BUILD_VISION=ON") + endif() + if(NOT SMARTPARALLEL_VISION_HAS_OPENCV) + message(FATAL_ERROR + "v1.5 route benchmarks require SMARTPARALLEL_ENABLE_OPENCV_PROVIDER=ON and OpenCV") + endif() + add_executable( + smartparallel_v150_adaptive_routes_benchmarks + src/adaptive_routes_benchmarks.cpp + ) + target_link_libraries( + smartparallel_v150_adaptive_routes_benchmarks + PRIVATE SmartParallel::vision + ) + if(TARGET opencv_core AND TARGET opencv_imgproc) + target_link_libraries( + smartparallel_v150_adaptive_routes_benchmarks + PRIVATE opencv_core opencv_imgproc + ) + else() + target_include_directories( + smartparallel_v150_adaptive_routes_benchmarks + PRIVATE ${OpenCV_INCLUDE_DIRS} + ) + target_link_libraries( + smartparallel_v150_adaptive_routes_benchmarks + PRIVATE ${OpenCV_LIBS} + ) + endif() + smartparallel_copy_tbb_runtime(smartparallel_v150_adaptive_routes_benchmarks) +endif() diff --git a/benchmarks/v1.5.0/README.md b/benchmarks/v1.5.0/README.md new file mode 100644 index 0000000..dad575b --- /dev/null +++ b/benchmarks/v1.5.0/README.md @@ -0,0 +1,25 @@ +# SmartParallel v1.5 adaptive execution-route benchmark + +This suite evaluates the first semantic operation, exact one-channel `uint8_t` thresholding, across: + +- direct sequential reference; +- direct OpenCV API; +- SmartParallel Auto; +- forced Native Sequential, ThreadPool, StaticThread, and oneTBB routes; +- forced SmartParallel OpenCV. + +The release workflow validates exact output, backend authentication, identical source/destination allocations, Native SIMD quality, balanced route learning, deployment-regime adaptation, settled route quality, and stable Auto overhead. + +Run the publication matrix on Windows/MSVC with: + +```bat +set "VCPKG_ROOT=D:\Tools\vcpkg" && scripts\validation\run_v15_adaptive_routes_release_validation.bat 31 +``` + +See: + +- [public results](../../docs/v1.5/benchmarks.md); +- [methodology](../../docs/v1.5/benchmark-methodology.md); +- [reproduction guide](../../docs/v1.5/benchmark-reproduction.md). + +Performance results are machine-specific and are not CI merge gates. diff --git a/benchmarks/v1.5.0/src/adaptive_routes_benchmarks.cpp b/benchmarks/v1.5.0/src/adaptive_routes_benchmarks.cpp new file mode 100644 index 0000000..9bf0cd7 --- /dev/null +++ b/benchmarks/v1.5.0/src/adaptive_routes_benchmarks.cpp @@ -0,0 +1,864 @@ +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +using Clock = std::chrono::steady_clock; +using smart::vision::ExecutionRoute; + +constexpr std::uint8_t padding_sentinel = 0xa5; + +struct Preset +{ + const char* name; + std::size_t width; + std::size_t height; + std::size_t extra_stride; +}; + +struct Case +{ + std::string name; + bool smartparallel = false; + ExecutionRoute route = ExecutionRoute::Auto; +}; + +struct ValidationResult +{ + std::uint64_t checksum = 1469598103934665603ull; + std::size_t mismatch_count = 0; +}; + +class BenchmarkConfigGuard +{ + public: + explicit BenchmarkConfigGuard(std::size_t repetitions) + : saved_(smart::global_config()) + { + const std::size_t maximum = std::numeric_limits::max(); + if (repetitions > maximum - 16) + throw std::invalid_argument("Repetition count is too large"); + auto& config = smart::global_config(); + config.vision_route_initial_revalidate_interval = 8; + config.vision_route_revalidate_interval = 128; + config.vision_route_drift_sample_interval = 8; + config.vision_route_drift_required_samples = 2; + config.vision_route_drift_ratio = 1.25; + config.vision_route_drift_absolute_ms = 0.002; + config.vision_route_pause_maintenance = false; + ++config.vision_route_policy_generation; + smart::vision::refresh_provider_state(); + } + + ~BenchmarkConfigGuard() + { + smart::global_config() = saved_; + smart::vision::clear_adaptive_route_cache(); + } + + void pause_maintenance() noexcept + { + smart::global_config().vision_route_pause_maintenance = true; + } + + void resume_maintenance() noexcept + { + smart::global_config().vision_route_pause_maintenance = false; + } + + private: + smart::Config saved_; +}; + +struct Sample +{ + std::string preset; + std::string implementation; + std::string phase; + std::size_t repetition = 0; + std::size_t measurement_ordinal = 0; + std::size_t width = 0; + std::size_t height = 0; + std::size_t stride = 0; + bool contiguous = true; + std::uintptr_t source_address = 0; + std::uintptr_t destination_address = 0; + std::size_t source_alignment = 1; + std::size_t destination_alignment = 1; + std::size_t learning_invocations = 0; + std::size_t deployment_invocations = 0; + std::size_t route_switch_count = 0; + std::string pair_order; + std::size_t pair_position = 0; + std::size_t batch_iterations = 1; + std::uint64_t batch_total_ns = 0; + std::uint64_t duration_ns = 0; + std::uint64_t checksum = 0; + std::size_t mismatch_count = 0; + std::string requested_route; + std::string selected_route; + std::size_t worker_budget = 1; + std::size_t participants = 1; + std::size_t chunks = 1; + bool learned = false; + bool probe = false; + bool exploration_probe = false; + bool holdout_probe = false; + bool revalidation_probe = false; + bool drift_probe = false; + bool correctness = false; + bool authentication = false; +}; + +struct LearningSnapshot +{ + std::string preset; + smart::vision::RouteTrainingReport report; +}; + +std::size_t alignment_class(const void* pointer) noexcept +{ + const auto address = reinterpret_cast(pointer); + if ((address & 63u) == 0) + return 64; + if ((address & 31u) == 0) + return 32; + if ((address & 15u) == 0) + return 16; + if ((address & 7u) == 0) + return 8; + return 1; +} + +ValidationResult validate_output(const std::vector& data, + const std::vector& expected, + std::size_t height, + std::size_t stride) +{ + ValidationResult result; + for (std::size_t y = 0; y < height; ++y) + { + for (std::size_t x = 0; x < stride; ++x) + { + const std::size_t index = y * stride + x; + const std::uint8_t value = data[index]; + result.checksum ^= value; + result.checksum *= 1099511628211ull; + if (value != expected[index]) + ++result.mismatch_count; + } + } + return result; +} + +void fill_source(std::vector& source, + std::size_t height, + std::size_t stride) +{ + std::uint64_t state = 0x9e3779b97f4a7c15ull; + for (std::size_t y = 0; y < height; ++y) + { + for (std::size_t x = 0; x < stride; ++x) + { + state ^= state << 13u; + state ^= state >> 7u; + state ^= state << 17u; + source[y * stride + x] = static_cast( + (state + x * 31u + y * 17u) & 0xffu); + } + } +} + +// Deliberately independent of SmartParallel internals. This is the external +// compiler-generated performance oracle and must remain a plain reference loop. +void direct_sequential(const std::vector& source, + std::vector& output, + std::size_t width, + std::size_t height, + std::size_t stride, + std::uint8_t threshold, + std::uint8_t maximum) +{ + for (std::size_t row = 0; row < height; ++row) + { + const std::uint8_t* source_row = source.data() + row * stride; + std::uint8_t* destination_row = output.data() + row * stride; + for (std::size_t column = 0; column < width; ++column) + { + destination_row[column] = source_row[column] > threshold + ? maximum + : std::uint8_t{0}; + } + } +} + +void opencv_threshold(const std::vector& source, + std::vector& output, + std::size_t width, + std::size_t height, + std::size_t stride, + std::uint8_t threshold, + std::uint8_t maximum) +{ + cv::Mat source_mat(static_cast(height), + static_cast(width), + CV_8UC1, + const_cast(source.data()), + stride); + cv::Mat destination_mat(static_cast(height), + static_cast(width), + CV_8UC1, + output.data(), + stride); + cv::threshold(source_mat, + destination_mat, + static_cast(threshold), + static_cast(maximum), + cv::THRESH_BINARY); +} + +std::uint64_t time_call(const std::function& function) +{ + const auto start = Clock::now(); + function(); + const auto end = Clock::now(); + return static_cast( + std::chrono::duration_cast(end - start).count()); +} + +std::uint64_t time_batch(const std::function& function, + std::size_t iterations) +{ + const auto start = Clock::now(); + for (std::size_t iteration = 0; iteration < iterations; ++iteration) + function(); + const auto end = Clock::now(); + return static_cast( + std::chrono::duration_cast(end - start).count()); +} + +std::vector> balanced_orders(std::size_t count) +{ + std::vector> result; + if (count == 0) + return result; + std::vector base(count); + base[0] = 0; + for (std::size_t position = 1; position < count; ++position) + { + base[position] = (position % 2u) == 1u + ? (position + 1u) / 2u + : count - position / 2u; + } + for (std::size_t shift = 0; shift < count; ++shift) + { + std::vector order(count); + for (std::size_t position = 0; position < count; ++position) + order[position] = (base[position] + shift) % count; + result.push_back(order); + } + if ((count % 2u) != 0u) + { + const std::size_t original = result.size(); + for (std::size_t index = 0; index < original; ++index) + { + std::vector reversed = result[index]; + std::reverse(reversed.begin(), reversed.end()); + result.push_back(std::move(reversed)); + } + } + return result; +} + +std::vector cases() +{ + std::vector result{ + {"opencv_api", false, ExecutionRoute::OpenCV}, + {"direct_sequential", false, ExecutionRoute::NativeSequential}, + {"smart_auto", true, ExecutionRoute::Auto}, + {"smart_native_sequential", true, ExecutionRoute::NativeSequential}, + {"smart_native_thread_pool", true, ExecutionRoute::NativeThreadPool}, + {"smart_native_static_thread", true, ExecutionRoute::NativeStaticThread}, + {"smart_opencv", true, ExecutionRoute::OpenCV}}; + if (smart::execution_backend_available(smart::ExecutionEngineType::OneTbb)) + result.push_back({"smart_native_one_tbb", true, ExecutionRoute::NativeOneTbb}); + return result; +} + +const Case& forced_case_for_route(const std::vector& benchmark_cases, + ExecutionRoute route) +{ + const auto found = std::find_if( + benchmark_cases.begin(), benchmark_cases.end(), [route](const Case& value) + { + return value.smartparallel && value.route == route; + }); + if (found == benchmark_cases.end()) + throw std::runtime_error("No forced benchmark case matches the learned route"); + return *found; +} + +void execute_case(const Case& benchmark_case, + const std::vector& source, + std::vector& output, + const Preset& preset, + std::size_t stride, + std::size_t worker_budget, + std::uint8_t threshold_value, + std::uint8_t maximum_value) +{ + if (benchmark_case.name == "opencv_api") + { + opencv_threshold(source, output, preset.width, preset.height, stride, + threshold_value, maximum_value); + return; + } + if (benchmark_case.name == "direct_sequential") + { + direct_sequential(source, output, preset.width, preset.height, stride, + threshold_value, maximum_value); + return; + } + + smart::vision::threshold( + smart::vision::make_image_view( + static_cast(source.data()), + preset.width, + preset.height, + stride), + smart::vision::make_image_view( + output.data(), preset.width, preset.height, stride), + {threshold_value, maximum_value, smart::vision::ThresholdMode::Binary}, + {benchmark_case.route, worker_budget}); +} + +Sample make_sample(const Case& benchmark_case, + const Preset& preset, + std::size_t stride, + std::string phase, + std::size_t repetition, + std::size_t measurement_ordinal, + std::size_t learning_invocations, + std::size_t deployment_invocations, + const std::vector& source, + const std::vector& output, + std::uint64_t duration_ns, + const ValidationResult& validation, + std::uint64_t expected_checksum, + std::size_t worker_budget, + std::string pair_order = {}, + std::size_t pair_position = 0, + std::size_t batch_iterations = 1, + std::uint64_t batch_total_ns = 0) +{ + Sample sample; + sample.preset = preset.name; + sample.implementation = benchmark_case.name; + sample.phase = std::move(phase); + sample.repetition = repetition; + sample.measurement_ordinal = measurement_ordinal; + sample.width = preset.width; + sample.height = preset.height; + sample.stride = stride; + sample.contiguous = stride == preset.width; + sample.source_address = reinterpret_cast(source.data()); + sample.destination_address = reinterpret_cast(output.data()); + sample.source_alignment = alignment_class(source.data()); + sample.destination_alignment = alignment_class(output.data()); + sample.learning_invocations = learning_invocations; + sample.deployment_invocations = deployment_invocations; + sample.pair_order = std::move(pair_order); + sample.pair_position = pair_position; + sample.batch_iterations = batch_iterations; + sample.batch_total_ns = batch_total_ns == 0 ? duration_ns : batch_total_ns; + sample.duration_ns = duration_ns; + sample.checksum = validation.checksum; + sample.mismatch_count = validation.mismatch_count; + sample.correctness = validation.mismatch_count == 0 + && validation.checksum == expected_checksum; + sample.worker_budget = worker_budget; + + if (benchmark_case.smartparallel) + { + const smart::vision::DecisionReport report = smart::vision::last_decision_report(); + sample.requested_route = smart::vision::execution_route_name(report.requested_route); + sample.selected_route = smart::vision::execution_route_name(report.selected_route); + sample.worker_budget = report.worker_budget; + sample.participants = report.participant_count; + sample.chunks = report.chunk_count; + sample.learned = report.learned_route; + sample.exploration_probe = report.exploration_probe; + sample.holdout_probe = report.holdout_probe; + sample.revalidation_probe = report.revalidation_probe; + sample.drift_probe = report.drift_probe; + sample.probe = sample.exploration_probe || sample.revalidation_probe + || sample.drift_probe; + const auto training = smart::vision::last_route_training_report(); + sample.route_switch_count = training.route_switch_count; + sample.authentication = report.backend_authenticated; + } + else + { + sample.requested_route = benchmark_case.name; + sample.selected_route = benchmark_case.name; + sample.authentication = true; + } + return sample; +} + +void write_raw(const std::filesystem::path& path, + const std::vector& samples, + std::size_t repetitions, + std::size_t logical_threads) +{ + std::filesystem::create_directories(path.parent_path()); + std::ofstream output(path); + if (!output) + throw std::runtime_error("Could not open raw CSV output"); + output << "schema_version,benchmark_version,operation,preset,implementation,phase," + "repetition_index,measurement_ordinal,width,height,channels,element_type," + "stride_bytes,contiguous,source_address,destination_address,source_alignment," + "destination_alignment,shared_destination_id,learning_invocations,deployment_invocations,route_switch_count,pair_order,pair_position,batch_iterations,batch_total_ns,native_kernel,duration_ns," + "checksum,mismatch_count,requested_route,selected_route,worker_budget," + "participant_count,chunk_count,learned_route,probe,exploration_probe,holdout_probe," + "revalidation_probe,drift_probe,correctness_pass,backend_authentication_pass,opencv_version," + "opencv_threads,logical_threads,requested_repetitions\n"; + for (const Sample& sample : samples) + { + output << "6,1.5.0,threshold_u8_binary," << sample.preset << ',' + << sample.implementation << ',' << sample.phase << ',' << sample.repetition + << ',' << sample.measurement_ordinal << ',' << sample.width << ',' + << sample.height << ",1,uint8," << sample.stride << ',' + << (sample.contiguous ? 1 : 0) << ',' << sample.source_address << ',' + << sample.destination_address << ',' << sample.source_alignment << ',' + << sample.destination_alignment << ",shared_per_preset," + << sample.learning_invocations << ',' << sample.deployment_invocations << ',' + << sample.route_switch_count << ',' << sample.pair_order << ',' + << sample.pair_position << ',' << sample.batch_iterations << ',' + << sample.batch_total_ns << ',' + << smart::vision::detail::threshold_kernel_name( + smart::vision::detail::selected_threshold_kernel()) + << ',' << sample.duration_ns << ',' + << sample.checksum << ',' << sample.mismatch_count << ',' + << sample.requested_route << ',' << sample.selected_route << ',' + << sample.worker_budget << ',' << sample.participants << ',' << sample.chunks + << ',' << (sample.learned ? 1 : 0) << ',' << (sample.probe ? 1 : 0) << ',' + << (sample.exploration_probe ? 1 : 0) << ',' + << (sample.holdout_probe ? 1 : 0) << ',' + << (sample.revalidation_probe ? 1 : 0) << ',' + << (sample.drift_probe ? 1 : 0) << ',' + << (sample.correctness ? 1 : 0) << ',' + << (sample.authentication ? 1 : 0) << ',' << CV_VERSION << ',' + << cv::getNumThreads() << ',' << logical_threads << ',' << repetitions << '\n'; + } +} + +void write_learning(const std::filesystem::path& raw_path, + const std::vector& snapshots) +{ + const std::filesystem::path path = raw_path.parent_path() + / "v1.5.0_adaptive_routes_learning.csv"; + std::ofstream output(path); + if (!output) + throw std::runtime_error("Could not open learning telemetry output"); + output << "schema_version,preset,stable,stable_route,provisional_route,holdout_active,revalidation_active,drift_detected,verification_failures,route_switch_count,drift_strikes,revalidation_challenger,training_baseline_ms,current_baseline_ms,last_revalidation_stable_ms,last_revalidation_challenger_ms,route,median_ms,mad_ms,minimum_ms,maximum_ms,current_median_ms,sample_count,current_sample_count,warmup_count,holdout_sample_count,active\n"; + for (const LearningSnapshot& snapshot : snapshots) + { + for (const smart::vision::RouteTrainingEntry& route : snapshot.report.routes) + { + output << "2," << snapshot.preset << ',' << (snapshot.report.stable ? 1 : 0) + << ',' << smart::vision::execution_route_name(snapshot.report.stable_route) + << ',' << smart::vision::execution_route_name(snapshot.report.provisional_route) + << ',' << (snapshot.report.holdout_active ? 1 : 0) + << ',' << (snapshot.report.revalidation_active ? 1 : 0) + << ',' << (snapshot.report.drift_detected ? 1 : 0) + << ',' << snapshot.report.verification_failures + << ',' << snapshot.report.route_switch_count + << ',' << snapshot.report.drift_strikes + << ',' << smart::vision::execution_route_name(snapshot.report.revalidation_challenger) + << ',' << snapshot.report.training_baseline_ms + << ',' << snapshot.report.current_baseline_ms + << ',' << snapshot.report.last_revalidation_stable_ms + << ',' << snapshot.report.last_revalidation_challenger_ms + << ',' << smart::vision::execution_route_name(route.route) + << ',' << route.median_ms << ',' << route.mad_ms + << ',' << route.minimum_ms << ',' << route.maximum_ms + << ',' << route.current_median_ms + << ',' << route.sample_count << ',' << route.current_sample_count + << ',' << route.warmup_count + << ',' << route.holdout_sample_count << ',' << (route.active ? 1 : 0) + << '\n'; + } + } +} + +void write_environment(const std::filesystem::path& raw_path, + std::size_t worker_budget, + std::size_t logical_threads) +{ + const std::filesystem::path path = raw_path.parent_path() + / "v1.5.0_adaptive_routes_environment.txt"; + std::ofstream output(path); + if (!output) + throw std::runtime_error("Could not open environment metadata output"); + output << "SmartParallel benchmark version: 1.5.0\n" + << "Raw schema version: 6\n" + << "Operation: threshold_u8_binary\n" + << "OpenCV version: " << CV_VERSION << "\n" + << "OpenCV threads: " << cv::getNumThreads() << "\n" + << "OpenCV OpenCL enabled: " << (cv::ocl::useOpenCL() ? "yes" : "no") << "\n" + << "SmartParallel worker budget: " << worker_budget << "\n" + << "Native threshold kernel: " + << smart::vision::detail::threshold_kernel_name( + smart::vision::detail::selected_threshold_kernel()) << "\n" + << "Explicit SIMD kernel active: " + << (smart::vision::detail::threshold_kernel_uses_explicit_simd() ? "yes" : "no") + << "\n" + << "Logical threads: " << logical_threads << "\n" + << "Destination policy: one identical allocation per preset for every route\n" + << "Timing policy: destination reset occurs outside timed sections; steady routes use balanced Williams orders\n" + << "Dispatch-overhead policy: batched adjacent Auto/forced ABBA and BAAB blocks\n" + << "Learning policy: balanced successive elimination with independent holdout verification\n" + << "Adaptation policy: sparse stable-route drift sentinels and current-context ABBA revalidation\n" + << "Reference policy: direct_sequential is independent of SmartParallel internals\n" + << "Steady-state policy: maintenance is paused only after deployment settling completes\n" + << "Periodic revalidation and drift detection remain enabled in production and are covered by " + "the deterministic v1.5 validation target.\n\n" + << "OpenCV build information\n" + << "========================\n" + << cv::getBuildInformation(); +} + +void require_results_valid(const std::vector& samples) +{ + for (const Sample& sample : samples) + { + if (!sample.correctness) + { + throw std::runtime_error( + "Benchmark correctness failure in " + sample.implementation + + " (mismatches=" + std::to_string(sample.mismatch_count) + ")"); + } + if (!sample.authentication) + throw std::runtime_error("Backend authentication failure in " + sample.implementation); + } +} +} // namespace + +int main(int argc, char** argv) +{ + try + { + if (argc < 2 || argc > 3) + { + std::cerr << "Usage: smartparallel_v150_adaptive_routes_benchmarks [odd repetitions]\n"; + return 2; + } + const std::size_t repetitions = argc == 3 + ? static_cast(std::stoull(argv[2])) + : 31; + if (repetitions == 0 || repetitions % 2 == 0) + throw std::invalid_argument("Repetition count must be a positive odd number"); + if (!smart::vision::opencv_available()) + throw std::runtime_error("The v1.5 publication benchmark requires OpenCV"); + + cv::ocl::setUseOpenCL(false); + BenchmarkConfigGuard benchmark_config(repetitions); + const std::size_t worker_budget = std::max(1, smart::hardware_threads()); + const std::uint8_t threshold_value = 127; + const std::uint8_t maximum_value = 255; + const std::vector presets{ + {"tiny_320x240", 320, 240, 0}, + {"small_640x480", 640, 480, 0}, + {"medium_1920x1080", 1920, 1080, 0}, + {"medium_1920x1080_roi", 1920, 1080, 64}, + {"large_3840x2160", 3840, 2160, 0}, + {"very_large_7680x4320", 7680, 4320, 0}}; + const std::vector benchmark_cases = cases(); + const auto automatic_iterator = std::find_if( + benchmark_cases.begin(), benchmark_cases.end(), [](const Case& value) + { + return value.name == "smart_auto"; + }); + if (automatic_iterator == benchmark_cases.end()) + throw std::runtime_error("Auto benchmark case is missing"); + const Case& automatic_case = *automatic_iterator; + std::vector samples; + std::vector learning_snapshots; + const std::vector> steady_orders = + balanced_orders(benchmark_cases.size()); + + std::cout << "SmartParallel v1.5 Adaptive Execution Routes benchmark\n" + << "OpenCV: " << CV_VERSION << "\n" + << "OpenCV threads: " << cv::getNumThreads() << "\n" + << "SmartParallel worker budget: " << worker_budget << "\n" + << "Native threshold kernel: " + << smart::vision::detail::threshold_kernel_name( + smart::vision::detail::selected_threshold_kernel()) << "\n" + << "Explicit SIMD kernel active: " + << (smart::vision::detail::threshold_kernel_uses_explicit_simd() + ? "yes" : "no") << "\n" + << "Repetitions: " << repetitions << "\n" + << "Publication policy: adapt under balanced deployment load, then pause maintenance\n"; + + for (const Preset& preset : presets) + { + const std::size_t stride = preset.width + preset.extra_stride; + std::vector source(stride * preset.height); + fill_source(source, preset.height, stride); + std::vector expected(stride * preset.height, padding_sentinel); + direct_sequential(source, expected, preset.width, preset.height, stride, + threshold_value, maximum_value); + const ValidationResult expected_validation = validate_output( + expected, expected, preset.height, stride); + const std::uint64_t expected_checksum = expected_validation.checksum; + + // Every implementation uses this exact allocation and alignment. + std::vector output(stride * preset.height, padding_sentinel); + + benchmark_config.resume_maintenance(); + smart::vision::clear_adaptive_route_cache(); + std::fill(output.begin(), output.end(), padding_sentinel); + const std::uint64_t cold_ns = time_call([&] + { + execute_case(automatic_case, source, output, preset, stride, + worker_budget, threshold_value, maximum_value); + }); + samples.push_back(make_sample( + automatic_case, preset, stride, "cold", 0, 0, 0, 0, source, output, + cold_ns, validate_output(output, expected, preset.height, stride), + expected_checksum, worker_budget)); + + constexpr std::size_t maximum_learning_invocations = 160; + std::size_t learning_invocations = 0; + bool learned = false; + ExecutionRoute learned_route = ExecutionRoute::Auto; + for (; learning_invocations < maximum_learning_invocations; + ++learning_invocations) + { + std::fill(output.begin(), output.end(), padding_sentinel); + execute_case(automatic_case, source, output, preset, stride, + worker_budget, threshold_value, maximum_value); + const auto report = smart::vision::last_decision_report(); + if (report.learned_route && !report.exploration_probe + && !report.revalidation_probe && !report.drift_probe) + { + ++learning_invocations; + learned_route = report.selected_route; + learned = true; + break; + } + } + if (!learned) + throw std::runtime_error( + "Automatic route learning did not stabilize within 160 invocations"); + const smart::vision::RouteTrainingReport initial_training_report = + smart::vision::last_route_training_report(); + if (!initial_training_report.available || !initial_training_report.stable + || initial_training_report.stable_route != learned_route) + throw std::runtime_error("Automatic route training telemetry was unavailable or inconsistent"); + + // Enter the deployment-like balanced/interleaved regime with normal + // maintenance enabled. The selector must detect any ranking drift, + // complete current-context ABBA revalidation, and then remain clean + // for a bounded streak before publication measurements are frozen. + constexpr std::size_t maximum_deployment_auto_invocations = 64; + constexpr std::size_t required_clean_streak = 6; + const std::size_t minimum_deployment_auto_invocations = + smart::global_config().vision_route_drift_sample_interval * 2 + 4; + std::size_t deployment_invocations = 0; + std::size_t clean_streak = 0; + bool deployment_settled = false; + ExecutionRoute settled_route = learned_route; + for (std::size_t block_index = 0; + deployment_invocations < maximum_deployment_auto_invocations + && !deployment_settled; + ++block_index) + { + const std::vector& order = + steady_orders[block_index % steady_orders.size()]; + for (std::size_t ordinal = 0; ordinal < benchmark_cases.size(); ++ordinal) + { + const Case& benchmark_case = benchmark_cases[order[ordinal]]; + std::fill(output.begin(), output.end(), padding_sentinel); + execute_case(benchmark_case, source, output, preset, stride, + worker_budget, threshold_value, maximum_value); + const ValidationResult validation = validate_output( + output, expected, preset.height, stride); + if (validation.mismatch_count != 0 + || validation.checksum != expected_checksum) + { + throw std::runtime_error( + "Deployment settling produced incorrect output"); + } + if (benchmark_case.name != "smart_auto") + continue; + + ++deployment_invocations; + const auto report = smart::vision::last_decision_report(); + const auto training = smart::vision::last_route_training_report(); + const bool clean = report.learned_route + && !report.exploration_probe && !report.holdout_probe + && !report.revalidation_probe && !report.drift_probe + && training.available && training.stable + && !training.revalidation_active; + if (clean) + { + if (report.selected_route == settled_route) + ++clean_streak; + else + { + settled_route = report.selected_route; + clean_streak = 1; + } + } + else + { + clean_streak = 0; + } + deployment_settled = deployment_invocations + >= minimum_deployment_auto_invocations + && clean_streak >= required_clean_streak; + if (deployment_settled) + break; + } + } + if (!deployment_settled) + throw std::runtime_error( + "Automatic route did not settle after deployment regime change"); + + learned_route = settled_route; + const smart::vision::RouteTrainingReport settled_training_report = + smart::vision::last_route_training_report(); + if (!settled_training_report.available || !settled_training_report.stable + || settled_training_report.revalidation_active + || settled_training_report.stable_route != learned_route) + { + throw std::runtime_error( + "Settled route telemetry was unavailable or inconsistent"); + } + learning_snapshots.push_back({preset.name, settled_training_report}); + benchmark_config.pause_maintenance(); + + std::size_t measurement_ordinal = 0; + for (std::size_t repetition = 0; repetition < repetitions; ++repetition) + { + const std::vector& order = + steady_orders[repetition % steady_orders.size()]; + for (std::size_t ordinal = 0; ordinal < benchmark_cases.size(); ++ordinal) + { + const Case& benchmark_case = benchmark_cases[order[ordinal]]; + std::fill(output.begin(), output.end(), padding_sentinel); + const std::uint64_t duration_ns = time_call([&] + { + execute_case(benchmark_case, source, output, preset, stride, + worker_budget, threshold_value, maximum_value); + }); + samples.push_back(make_sample( + benchmark_case, preset, stride, "steady_state", repetition, + measurement_ordinal++, learning_invocations, deployment_invocations, source, output, + duration_ns, + validate_output(output, expected, preset.height, stride), + expected_checksum, + worker_budget)); + } + } + + // Batched adjacent ABBA/BAAB blocks amortize scheduler and clock noise. + const Case& selected_forced_case = forced_case_for_route( + benchmark_cases, learned_route); + std::fill(output.begin(), output.end(), padding_sentinel); + const std::uint64_t calibration_auto = time_call([&] + { + execute_case(automatic_case, source, output, preset, stride, + worker_budget, threshold_value, maximum_value); + }); + std::fill(output.begin(), output.end(), padding_sentinel); + const std::uint64_t calibration_forced = time_call([&] + { + execute_case(selected_forced_case, source, output, preset, stride, + worker_budget, threshold_value, maximum_value); + }); + constexpr std::uint64_t target_batch_ns = 8'000'000; + const std::uint64_t calibration = std::max( + 1, std::max(calibration_auto, calibration_forced)); + const std::size_t batch_iterations = std::max( + 1, std::min(100'000, + static_cast((target_batch_ns + calibration - 1) / calibration))); + for (std::size_t repetition = 0; repetition < repetitions; ++repetition) + { + const bool auto_outer = (repetition % 2u) == 0u; + const std::string pair_order = auto_outer + ? "auto_forced_forced_auto" : "forced_auto_auto_forced"; + const Case* pair_cases[4] = { + auto_outer ? &automatic_case : &selected_forced_case, + auto_outer ? &selected_forced_case : &automatic_case, + auto_outer ? &selected_forced_case : &automatic_case, + auto_outer ? &automatic_case : &selected_forced_case}; + for (std::size_t position = 0; position < 4; ++position) + { + const Case& benchmark_case = *pair_cases[position]; + std::fill(output.begin(), output.end(), padding_sentinel); + const std::uint64_t batch_total_ns = time_batch([&] + { + execute_case(benchmark_case, source, output, preset, stride, + worker_budget, threshold_value, maximum_value); + }, batch_iterations); + const std::uint64_t duration_ns = batch_total_ns / batch_iterations; + samples.push_back(make_sample( + benchmark_case, preset, stride, "dispatch_batch", repetition, + measurement_ordinal++, learning_invocations, deployment_invocations, source, output, + duration_ns, + validate_output(output, expected, preset.height, stride), + expected_checksum, worker_budget, pair_order, position + 1, + batch_iterations, batch_total_ns)); + } + } + std::cout << "Completed " << preset.name + << " (learning calls: " << learning_invocations + << ", deployment calls: " << deployment_invocations << ")\n"; + benchmark_config.resume_maintenance(); + } + + require_results_valid(samples); + const std::size_t logical_threads = + smart::hardware_characteristics().logical_threads; + write_raw(argv[1], samples, repetitions, logical_threads); + write_learning(argv[1], learning_snapshots); + write_environment(argv[1], worker_budget, logical_threads); + std::cout << "Raw results: " << argv[1] << '\n'; + std::cout << "Environment: " + << (std::filesystem::path(argv[1]).parent_path() + / "v1.5.0_adaptive_routes_environment.txt") + << '\n'; + return 0; + } + catch (const std::exception& exception) + { + std::cerr << "v1.5 adaptive-routes benchmark failed: " << exception.what() << '\n'; + return 1; + } +} diff --git a/cmake/SmartParallelOptions.cmake b/cmake/SmartParallelOptions.cmake index fc3007d..d7d8239 100644 --- a/cmake/SmartParallelOptions.cmake +++ b/cmake/SmartParallelOptions.cmake @@ -12,6 +12,9 @@ if(SMARTPARALLEL_BUILD_VALIDATION) set(SMARTPARALLEL_BUILD_PARALLEL_FOR_VALIDATION ON) set(SMARTPARALLEL_BUILD_PARALLEL_FOR_HARDENING ON) set(SMARTPARALLEL_BUILD_V140_ALGORITHM_VALIDATION ON) + if(SMARTPARALLEL_BUILD_VISION) + set(SMARTPARALLEL_BUILD_V150_VISION_VALIDATION ON) + endif() endif() if(SMARTPARALLEL_BUILD_REAL_WORLD_BENCHMARKS) @@ -33,6 +36,9 @@ if(SMARTPARALLEL_BUILD_BENCHMARKS) set(SMARTPARALLEL_BUILD_DECISION_QUALITY_AUDIT ON) set(SMARTPARALLEL_BUILD_V110_NESTED_BENCHMARKS ON) set(SMARTPARALLEL_BUILD_V140_ALGORITHM_BENCHMARKS ON) + if(SMARTPARALLEL_BUILD_VISION AND SMARTPARALLEL_ENABLE_OPENCV_PROVIDER) + set(SMARTPARALLEL_BUILD_V150_VISION_BENCHMARKS ON) + endif() endif() set(SMARTPARALLEL_BUILD_ANY_VALIDATION OFF) @@ -41,6 +47,7 @@ if(SMARTPARALLEL_BUILD_V1_PHASE1 OR SMARTPARALLEL_BUILD_PARALLEL_FOR_VALIDATION OR SMARTPARALLEL_BUILD_PARALLEL_FOR_HARDENING OR SMARTPARALLEL_BUILD_V140_ALGORITHM_VALIDATION + OR SMARTPARALLEL_BUILD_V150_VISION_VALIDATION OR SMARTPARALLEL_BUILD_PARALLEL_FOR_OVERHEAD) set(SMARTPARALLEL_BUILD_ANY_VALIDATION ON) endif() @@ -56,6 +63,7 @@ if(SMARTPARALLEL_BUILD_OPENCV_TEST1 OR SMARTPARALLEL_BUILD_DECISION_QUALITY_AUDIT OR SMARTPARALLEL_BUILD_V110_NESTED_BENCHMARKS OR SMARTPARALLEL_BUILD_V140_ALGORITHM_BENCHMARKS + OR SMARTPARALLEL_BUILD_V150_VISION_BENCHMARKS OR SMARTPARALLEL_BUILD_OPENCV_BENCHMARK OR SMARTPARALLEL_BUILD_LZ4_BENCHMARK OR SMARTPARALLEL_BUILD_BVH_BENCHMARK diff --git a/cmake/SmartParallelVisionConfig.cmake.in b/cmake/SmartParallelVisionConfig.cmake.in new file mode 100644 index 0000000..8f2bfe9 --- /dev/null +++ b/cmake/SmartParallelVisionConfig.cmake.in @@ -0,0 +1,10 @@ +@PACKAGE_INIT@ + +include(CMakeFindDependencyMacro) +find_dependency(SmartParallel CONFIG) +if(@SMARTPARALLEL_VISION_HAS_OPENCV@) + find_dependency(OpenCV COMPONENTS core imgproc) +endif() + +include("${CMAKE_CURRENT_LIST_DIR}/SmartParallelVisionTargets.cmake") +check_required_components(SmartParallelVision) diff --git a/docs/README.md b/docs/README.md index 52a982e..80953ad 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,8 +1,24 @@ # SmartParallel documentation -## Current release +## Current release: v1.5.0 -The current release is **SmartParallel v1.4.0**, focused on adaptive parallel algorithms implemented on the existing scheduler and nested runtime. +SmartParallel v1.5 adds optional semantic operations and adaptive complete-route selection while retaining the v1.4 scheduler and parallel algorithms. + +- [v1.5 overview](v1.5/README.md) +- [v1.5 API](v1.5/api.md) +- [v1.5 architecture](v1.5/architecture.md) +- [v1.5 benchmark results](v1.5/benchmarks.md) +- [v1.5 benchmark methodology](v1.5/benchmark-methodology.md) +- [v1.5 benchmark reproduction](v1.5/benchmark-reproduction.md) +- [v1.5 validation](v1.5/validation.md) +- [v1.5 known limitations](v1.5/known-limitations.md) +- [v1.5 release notes](v1.5/release-notes.md) + +The accepted v1.5 threshold publication passed all 6/6 combined proof gates with 2,238 correct and authenticated samples. Results are machine-specific and documented with accepted summary data, learning telemetry, environment metadata, source hashes, and reproducible SVG figures. + +## Retained v1.4 parallel algorithms + +The v1.4 parallel algorithm layer remains fully supported: - [v1.4 overview](v1.4/README.md) - [v1.4 API and correctness contracts](v1.4/api.md) @@ -11,32 +27,21 @@ The current release is **SmartParallel v1.4.0**, focused on adaptive parallel al - [v1.4 benchmark methodology](v1.4/benchmark-methodology.md) - [v1.4 benchmark reproduction](v1.4/benchmark-reproduction.md) - [v1.4 validation](v1.4/validation.md) -- [v1.4 known limitations](v1.4/known-limitations.md) - [v1.4 release notes](v1.4/release-notes.md) -SmartParallel v1.3 remains the portability and CI foundation: - -- [v1.3 overview](v1.3/README.md) -- [GitHub Actions and vcpkg setup](v1.3/ci-and-github-setup.md) -- [Cross-platform installation](v1.3/installation.md) - -## Runtime and scheduler documentation - -SmartParallel v1.4 retains the stabilized v1.1 runtime behavior. The detailed scheduler documentation remains under [`docs/v1.1/`](v1.1/README.md). +## Portability and runtime documentation +- [v1.3 portability and CI](v1.3/README.md) +- [v1.3 installation](v1.3/installation.md) +- [v1.3 GitHub Actions setup](v1.3/ci-and-github-setup.md) +- [v1.1 scheduler and nested runtime](v1.1/README.md) - [Getting started](v1.1/getting-started.md) -- [API](v1.1/api.md) -- [Architecture](v1.1/architecture.md) -- [Automatic loop optimization](v1.1/automatic-loop-optimization.md) +- [Core API](v1.1/api.md) - [Nested parallelism](v1.1/nested-parallelism.md) - [Runtime learning](v1.1/runtime-learning.md) -- [Execution backends](v1.1/execution-backends.md) -- [Configuration](v1.1/configuration.md) - [Diagnostics](v1.1/diagnostics.md) -- [Benchmarks](v1.1/benchmarks.md) -- [Known limitations](v1.1/known-limitations.md) ## Historical material -- [`docs/v1.0/`](v1.0/README.md) summarizes the archived v1.0 release. -- [`docs/archive/`](archive/README.md) preserves pre-release, engineering, and validation documents for traceability. Archived files are not authoritative for current behavior. +- [v1.0 documentation](v1.0/README.md) +- [Engineering archive](archive/README.md) diff --git a/docs/v1.3/README.md b/docs/v1.3/README.md index 8f6172f..d55ef8a 100644 --- a/docs/v1.3/README.md +++ b/docs/v1.3/README.md @@ -1,6 +1,6 @@ # SmartParallel v1.3 -> **Current release:** v1.3.0 +> **Historical portability release retained by v1.5:** v1.3.0 SmartParallel v1.3 is the cross-platform CI and portability release. It retains the stabilized v1.1 scheduler, nested-execution semantics, public API, and benchmark algorithms while adding automated build, test, install, and package-consumer validation across Windows, Linux, and macOS. diff --git a/docs/v1.3/ci-and-github-setup.md b/docs/v1.3/ci-and-github-setup.md index be6f060..d4ce12e 100644 --- a/docs/v1.3/ci-and-github-setup.md +++ b/docs/v1.3/ci-and-github-setup.md @@ -1,6 +1,6 @@ # GitHub Actions and vcpkg setup -> **Current release:** SmartParallel v1.3.0. +> **CI baseline introduced in v1.3 and retained by v1.5.** The main workflow is [`.github/workflows/ci.yml`](../../.github/workflows/ci.yml). @@ -13,17 +13,21 @@ The main workflow is [`.github/workflows/ci.yml`](../../.github/workflows/ci.yml | `linux-gcc-release-tbb` | Linux/GCC | Release | enabled and required | | `linux-clang-release-tbb` | Linux/Clang | Release | enabled and required | | `macos-appleclang-release-tbb` | macOS/Apple Clang | Release | enabled and required | -| `linux-clang-debug-asan-ubsan` | Linux/Clang | Debug | disabled | +| `linux-clang-debug-asan-ubsan` | Linux/Clang | Debug + ASan/UBSan, Native vision enabled | disabled | +| `linux-clang-release-native-vision` | Linux/Clang | Release, Native-only v1.5 vision + installed consumer | disabled | +| `documentation-and-release-evidence` | Linux/Python | Markdown links, versions, accepted v1.5 assets, ZIP evidence, tool syntax | not applicable | -Each normal matrix job: +Each normal platform matrix job: 1. configures SmartParallel with benchmarks disabled; -2. builds the library and deterministic validation suite; +2. builds the core library and deterministic validation suite; 3. runs CTest, including native hardware-topology validation; 4. installs SmartParallel; -5. configures a separate external consumer with `find_package`; +5. configures a separate external core consumer with `find_package`; 6. builds and runs that consumer, including an installed-package hardware-discovery check. +The v1.5 Native-vision job additionally builds `SmartParallel::vision` without OpenCV, runs the v1.5 route/SIMD tests, installs the separate `SmartParallelVision` package, and runs the external vision consumer. The sanitizer job now includes the Native vision module. The documentation job validates local links, release-version consistency, accepted benchmark metrics, evidence hashes/ZIP contents, and Python publication-tool syntax. + The workflow runs for pushes to `main`, pull requests targeting `main`, and manual `workflow_dispatch`. Concurrency cancellation stops an older run for the same branch when a newer commit arrives. ## Final v1.3 workflow result @@ -39,7 +43,7 @@ A green pull-request result means the exact commit under review compiled and pas 1. Push `.github/workflows/ci.yml` to a branch in the repository. 2. Open a pull request with **base: `main`** and **compare: your working branch**. The pull-request trigger starts CI even when ordinary pushes to the working branch are not configured as push triggers. 3. Open the pull request and view its **Checks** area, or open the repository's **Actions** tab and select **CI**. -4. Wait for all six jobs to finish. Do not merge while a job is queued, running, cancelled without replacement, or red. +4. Wait for all current jobs to finish. Do not merge while a job is queued, running, cancelled without replacement, or red. 5. Open any failed job, expand the first failed step, and use its compiler/CMake/CTest output as the source of truth. ### Manual run @@ -67,7 +71,7 @@ No repository secret is required by the default workflow. 1. Open **Settings → Rules → Rulesets**. 2. Create a branch ruleset targeting the default branch or `main`. 3. Enable **Require a pull request before merging**. -4. Enable **Require status checks to pass** and add the six CI job names after they have appeared successfully in the repository. +4. Enable **Require status checks to pass** and add the current platform, sanitizer, Native-vision, and documentation job names after they have appeared successfully in the repository. 5. Keep the ruleset active. A check normally must have run successfully in the repository before GitHub offers it as a required check. diff --git a/docs/v1.3/installation.md b/docs/v1.3/installation.md index 7ca708a..3c5beb3 100644 --- a/docs/v1.3/installation.md +++ b/docs/v1.3/installation.md @@ -1,6 +1,6 @@ # Cross-platform build and installation -> **Current release:** SmartParallel v1.3.0. +> **Installation baseline introduced in v1.3 and retained by v1.5.** ## Requirements diff --git a/docs/v1.4/README.md b/docs/v1.4/README.md index ff78510..9fdd303 100644 --- a/docs/v1.4/README.md +++ b/docs/v1.4/README.md @@ -1,6 +1,6 @@ # SmartParallel v1.4 — Parallel Algorithm Expansion -> **Current release:** SmartParallel v1.4.0 +> **Previous release retained by v1.5:** SmartParallel v1.4.0 SmartParallel v1.4 extends the adaptive indexed runtime with parallel algorithms for elementwise work, reductions, counting, predicates, and search. It keeps the stabilized scheduler and nested-execution model while adding a root automatic hot-dispatch path for operations whose complete sequential body is cheaper than scheduler construction. diff --git a/docs/v1.5/README.md b/docs/v1.5/README.md new file mode 100644 index 0000000..a3df3cc --- /dev/null +++ b/docs/v1.5/README.md @@ -0,0 +1,48 @@ +# SmartParallel v1.5 — Adaptive Execution Routes + +SmartParallel v1.5 introduces an optional semantic-operation layer above the existing v1.4 scheduler. The first operation is exact 8-bit binary thresholding: + +```cpp +#include + +smart::vision::threshold(source, destination); +``` + +The application requests an operation, not a library or scheduler. Automatic mode learns among complete valid routes: + +- Native SmartParallel sequential execution; +- Native SmartParallel ThreadPool execution; +- Native SmartParallel oneTBB execution when available; +- OpenCV `cv::threshold` when the optional provider is enabled. + +StaticThread remains forceable for diagnostics but is not an automatic candidate in the first release. Native threshold routes use an authenticated runtime-selected AVX2, SSE2, or portable branchless scalar kernel before the existing scheduler divides work. + +## Accepted release evidence + +The final Windows/MSVC Release publication run contained **2,238 measured samples** and passed: + +- exact correctness and route authentication with zero failures; +- all **6/6 route-selection gates**; +- all **6/6 native-kernel gates**; +- all **6/6 stable-dispatch gates**; +- all **6/6 combined release gates**. + +On the recorded machine, Auto achieved a **1.16× geometric-mean speedup over the independent sequential loop** and **1.48× over direct OpenCV**. The two 1080p profiles initially learned OpenCV, detected a changed deployment regime, and switched once to Native Sequential before final measurement. + +![SmartParallel v1.5 initial and settled routes](assets/benchmarks/v1.5.0_adaptive_route_map.svg) + +The route map and speedups are machine-specific. Auto should be used instead of copying these choices into hard-coded policy. + +## Documents + +- [API](api.md) +- [Architecture](architecture.md) +- [Benchmark results](benchmarks.md) +- [Benchmark methodology](benchmark-methodology.md) +- [Benchmark reproduction](benchmark-reproduction.md) +- [Validation](validation.md) +- [Known limitations](known-limitations.md) +- [Release notes](release-notes.md) +- [Accepted benchmark assets](assets/benchmarks/README.md) + +v1.5 does not change the existing `parallel_for` or v1.4 algorithm APIs. The core installed target remains `SmartParallel::smart_parallel`; the optional semantic-operation module is exported separately as `SmartParallel::vision` through the `SmartParallelVision` package. diff --git a/docs/v1.5/api.md b/docs/v1.5/api.md new file mode 100644 index 0000000..9145fd3 --- /dev/null +++ b/docs/v1.5/api.md @@ -0,0 +1,138 @@ +# v1.5 vision API + +The v1.5 semantic API is provided by the optional `SmartParallel::vision` target. It does not change or replace the existing scheduler and v1.4 algorithm APIs. + +## Build and link + +Enable the module without OpenCV: + +```text +cmake -S . -B build/vision -DSMARTPARALLEL_BUILD_VISION=ON +``` + +Enable the optional OpenCV route: + +```text +cmake -S . -B build/vision-opencv \ + -DSMARTPARALLEL_BUILD_VISION=ON \ + -DSMARTPARALLEL_ENABLE_OPENCV_PROVIDER=ON +``` + +Installed consumers use the separate package: + +```cmake +find_package(SmartParallelVision CONFIG REQUIRED) +target_link_libraries(my_application PRIVATE SmartParallel::vision) +``` + +The core-only package remains: + +```cmake +find_package(SmartParallel CONFIG REQUIRED) +target_link_libraries(my_application PRIVATE SmartParallel::smart_parallel) +``` + +## Image views + +```cpp +smart::vision::ImageView source; +smart::vision::ImageView destination; +``` + +Views are non-owning. They contain data, width, height, row stride, and channel count. The first semantic operation supports one-channel `uint8_t` images, contiguous buffers, strided rows, and exact in-place execution. + +Helpers: + +```cpp +smart::vision::make_contiguous_image_view(data, width, height); +smart::vision::make_image_view(data, width, height, stride_bytes); +``` + +The caller owns the memory and must keep it valid for the duration of the call. Partial source/destination overlap is rejected; exact in-place use is supported. + +## Threshold + +```cpp +smart::vision::threshold( + source, + destination, + smart::vision::ThresholdOptions{ + 127, + 255, + smart::vision::ThresholdMode::Binary + }); +``` + +The exact contract is: + +```text +Binary: destination = source > threshold ? maximum : 0 +BinaryInverse: destination = source > threshold ? 0 : maximum +``` + +Automatic route selection is the default. The call remains the same whether the module was built Native-only or with the optional OpenCV provider. + +A complete example is available at [`examples/v15_adaptive_threshold.cpp`](../../examples/v15_adaptive_threshold.cpp). + +## Diagnostic forcing + +```cpp +smart::vision::ExecutionPolicy policy; +policy.route = smart::vision::ExecutionRoute::OpenCV; +policy.worker_budget = 4; +``` + +Forceable routes are: + +- `Auto`; +- `NativeSequential`; +- `NativeThreadPool`; +- `NativeStaticThread`; +- `NativeOneTbb`; +- `OpenCV`. + +Forcing is intended for validation, benchmarking, reproducibility, and troubleshooting. A forced unavailable route fails clearly rather than silently authenticating a different route. + +## Decision diagnostics + +```cpp +const auto report = smart::vision::last_decision_report(); +``` + +The report includes: + +- requested and selected routes; +- cache, learned-route, and adaptive-selection state; +- exploration, holdout, drift, and revalidation probe state; +- worker budget, participants, chunks, and execution depth; +- OpenCV availability; +- whether internal timing was active; +- backend-authentication status. + +Stable thread-local hot-route calls intentionally skip internal timing except for sparse drift sentinels. Publication benchmarks time the complete public API externally. + +## Training and adaptation diagnostics + +```cpp +const auto training = smart::vision::last_route_training_report(); +``` + +The report exposes: + +- training median, MAD, minimum, and maximum per route; +- measured, priming, holdout, and current sample counts; +- provisional and stable routes; +- training and current baselines; +- drift strikes and route-switch count; +- latest stable/challenger current-context comparison. + +## Provider and cache invalidation + +```cpp +smart::vision::refresh_provider_state(); +smart::vision::clear_adaptive_route_cache(); +``` + +Call `refresh_provider_state()` after changing OpenCV process-global settings such as thread count, optimization state, or OpenCL configuration. It refreshes the provider fingerprint and invalidates incompatible learned routes. + +`clear_adaptive_route_cache()` clears process-wide operation learning and invalidates current-thread hot decisions. It is primarily useful for deterministic tests and controlled benchmark learning phases. diff --git a/docs/v1.5/architecture.md b/docs/v1.5/architecture.md new file mode 100644 index 0000000..ed3ec28 --- /dev/null +++ b/docs/v1.5/architecture.md @@ -0,0 +1,57 @@ +# v1.5 architecture + +## Two adaptive decisions + +SmartParallel v1.4 selects how to schedule one Native SmartParallel implementation. v1.5 adds a higher decision that can select a complete implementation route. + +```text +smart::vision::threshold + ↓ +Adaptive execution-route selection + ├── Native Sequential + ├── Native ThreadPool + ├── Native oneTBB + └── OpenCV threshold +``` + +Internally, Native routes reuse the existing scheduler backends. OpenCV replaces the complete operation with `cv::threshold`; it is not inserted into `IExecutionBackend`, because that interface executes arbitrary indexed callbacks while OpenCV implements named vision operations. + +## Route learning + +A new bounded, sharded route selector records complete end-to-end observations on separate public invocations. It never executes two implementations for one call. + +Each eligible route is primed twice without ranking those invocations. Learning then proceeds in balanced rounds. After three observations per active route, the selector uses median/MAD confidence bounds to eliminate routes that are clearly slower. Ambiguous candidates receive additional balanced observations in steps up to the bounded sample window. The provisional winner is never committed immediately: it must pass an independent holdout comparison against the best runner-up. A failed holdout reopens learning with the new evidence, while statistically equivalent routes resolve conservatively in favor of Native Sequential, then Native parallel routes, then external providers. + +The selector exposes training medians, MAD, minima, maxima, sample counts, holdout counts, verification failures, current observations, drift state, and route-switch history for publication diagnostics. A small thread-local hot cache bypasses the process-wide selector and internal timing for ordinary stable calls. Hashed generation counters invalidate stale thread-local entries when another thread promotes a different route. + +Stable profiles are not trusted forever. Sparse sentinel calls time the current route without putting a timer on every invocation. Two decisive drift observations trigger a current-context ABBA comparison over separate real calls: stable A, challenger A, challenger B, stable B. The switch decision uses those current samples rather than the historical training winner. Periodic ABBA revalidation still starts after eight stable uses and backs off progressively toward 128 uses when the decision remains valid. + +Profiles are separated by: + +- operation and semantic parameters; +- image-size buckets; +- source and destination strides; +- contiguity and pointer alignment class; +- worker budget; +- available-route mask; +- OpenCV build, configured thread count, optimization, and OpenCL-state fingerprint; +- route-policy configuration and cache generation. + +Learning is root-only in v1.5. Automatic calls made from an active SmartParallel execution context use Native Sequential to avoid uncoordinated nested external runtimes. + +## Resource model + +OpenCV is called once for the complete image using non-owning `cv::Mat` views. SmartParallel does not split the image and invoke internally parallel OpenCV kernels from multiple workers. This avoids multiplying SmartParallel and OpenCV worker teams. + +Native ThreadPool, StaticThread, and oneTBB routes partition contiguous pixels or strided rows into bounded chunks and invoke the existing `IExecutionBackend` implementations directly without mutating process-global execution-engine configuration. + +## Dependency isolation + +The vision module is opt-in. The OpenCV route is additionally opt-in. + +```text +SmartParallel::smart_parallel no OpenCV dependency +SmartParallel::vision Native-only or Native + OpenCV, according to build +``` + +`SmartParallelVisionConfig.cmake` is installed separately, so an application using only the core package does not discover or require OpenCV. diff --git a/docs/v1.5/assets/benchmarks/README.md b/docs/v1.5/assets/benchmarks/README.md new file mode 100644 index 0000000..6ad4c08 --- /dev/null +++ b/docs/v1.5/assets/benchmarks/README.md @@ -0,0 +1,27 @@ +# SmartParallel v1.5 benchmark assets + +These files are generated from the accepted v1.5 publication run and support the public benchmark report. + +- `generated-results.md` — generated table and aggregate metrics. +- `benchmark-metrics.json` — machine-readable accepted metrics. +- `accepted-summary.csv` — six-preset proof-gate summary. +- `accepted-learning.csv` — route-learning and current-context adaptation evidence. +- `accepted-environment.txt` — compiler, OpenCV, worker-budget, and build configuration. +- `accepted-publication-report.md` — analyzer-generated release-gate report. +- `source-hashes.txt` — hashes of the accepted source evidence. +- `accepted-publication.zip` — full accepted raw evidence, learning data, environment, report, build log, and figures. +- `v1.5.0_*.svg` — dependency-free publication figures. + +Regenerate a publication run with: + +```bat +set "VCPKG_ROOT=D:\Tools\vcpkg" && scripts\validation\run_v15_adaptive_routes_release_validation.bat 31 +``` + +Publish a validated run into this directory with: + +```bat +py -3 tools\publish_v15_benchmark_docs.py validation\output\v1.5.0_adaptive_routes\publication_ +``` + +Performance is machine-specific. Do not copy values from one machine into universal performance claims. diff --git a/docs/v1.5/assets/benchmarks/accepted-environment.txt b/docs/v1.5/assets/benchmarks/accepted-environment.txt new file mode 100644 index 0000000..448b50e --- /dev/null +++ b/docs/v1.5/assets/benchmarks/accepted-environment.txt @@ -0,0 +1,105 @@ +SmartParallel benchmark version: 1.5.0 +Raw schema version: 6 +Operation: threshold_u8_binary +OpenCV version: 4.12.0 +OpenCV threads: 16 +OpenCV OpenCL enabled: no +SmartParallel worker budget: 16 +Native threshold kernel: avx2 +Explicit SIMD kernel active: yes +Logical threads: 16 +Destination policy: one identical allocation per preset for every route +Timing policy: destination reset occurs outside timed sections; steady routes use balanced Williams orders +Dispatch-overhead policy: batched adjacent Auto/forced ABBA and BAAB blocks +Learning policy: balanced successive elimination with independent holdout verification +Adaptation policy: sparse stable-route drift sentinels and current-context ABBA revalidation +Reference policy: direct_sequential is independent of SmartParallel internals +Steady-state policy: maintenance is paused only after deployment settling completes +Periodic revalidation and drift detection remain enabled in production and are covered by the deterministic v1.5 validation target. + +OpenCV build information +======================== + +General configuration for OpenCV 4.12.0 ===================================== + Version control: unknown + + Platform: + Timestamp: 2026-07-18T00:31:00Z + Host: Windows 10.0.19045 AMD64 + CMake: 3.31.0 + CMake generator: Ninja + CMake build tool: C:/Users/sakko/AppData/Local/vcpkg/downloads/tools/ninja/1.13.1-windows/ninja.exe + MSVC: 1944 + Configuration: Release + Algorithm Hint: ALGO_HINT_ACCURATE + + CPU/HW features: + Baseline: SSE SSE2 SSE3 + requested: SSE3 + Dispatched code generation: SSE4_1 SSE4_2 AVX FP16 AVX2 AVX512_SKX + SSE4_1 (15 files): + SSSE3 SSE4_1 + SSE4_2 (1 files): + SSSE3 SSE4_1 POPCNT SSE4_2 + AVX (9 files): + SSSE3 SSE4_1 POPCNT SSE4_2 AVX + FP16 (0 files): + SSSE3 SSE4_1 POPCNT SSE4_2 AVX FP16 + AVX2 (35 files): + SSSE3 SSE4_1 POPCNT SSE4_2 AVX FP16 AVX2 FMA3 + AVX512_SKX (6 files): + SSSE3 SSE4_1 POPCNT SSE4_2 AVX FP16 AVX2 FMA3 AVX_512F AVX512_COMMON AVX512_SKX + + C/C++: + Built as dynamic libs?: YES + C++ standard: 17 + C++ Compiler: C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.44.35207/bin/Hostx64/x64/cl.exe (ver 19.44.35228.0) + C++ flags (Release): /nologo /DWIN32 /D_WINDOWS /utf-8 /GR /MP /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi /fp:precise /FS /EHa /wd4127 /wd4251 /wd4324 /wd4275 /wd4512 /wd4589 /wd4819 /MD /O2 /Oi /Gy /DNDEBUG /Z7 + C++ flags (Debug): /nologo /DWIN32 /D_WINDOWS /utf-8 /GR /MP /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi /fp:precise /FS /EHa /wd4127 /wd4251 /wd4324 /wd4275 /wd4512 /wd4589 /wd4819 /MDd /Z7 /Ob0 /Od /RTC1 + C Compiler: C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.44.35207/bin/Hostx64/x64/cl.exe + C flags (Release): /nologo /DWIN32 /D_WINDOWS /utf-8 /MP /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi /fp:precise /FS /MD /O2 /Oi /Gy /DNDEBUG /Z7 + C flags (Debug): /nologo /DWIN32 /D_WINDOWS /utf-8 /MP /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi /fp:precise /FS /MDd /Z7 /Ob0 /Od /RTC1 + Linker flags (Release): /machine:x64 /nologo /DEBUG /INCREMENTAL:NO /OPT:REF /OPT:ICF /debug + Linker flags (Debug): /machine:x64 /nologo /debug /INCREMENTAL + ccache: NO + Precompiled headers: NO + Extra dependencies: + 3rdparty dependencies: + + OpenCV modules: + To be built: calib3d core dnn features2d flann highgui imgcodecs imgproc ml objdetect photo stitching video videoio + Disabled: world + Disabled by dependency: - + Unavailable: gapi java python2 python3 ts + Applications: - + Documentation: NO + Non-free algorithms: NO + + Windows RT support: NO + + GUI: WIN32UI + Win32 UI: YES + + Media I/O: + ZLib: optimized D:/Projects/SmartParallel/vcpkg_installed/x64-windows/lib/z.lib debug D:/Projects/SmartParallel/vcpkg_installed/x64-windows/debug/lib/zd.lib (ver 1.3.2) + JPEG: optimized D:/Projects/SmartParallel/vcpkg_installed/x64-windows/lib/jpeg.lib debug D:/Projects/SmartParallel/vcpkg_installed/x64-windows/debug/lib/jpeg.lib (ver 62) + WEBP: (ver 1.6.0) + PNG: optimized D:/Projects/SmartParallel/vcpkg_installed/x64-windows/lib/libpng16.lib debug D:/Projects/SmartParallel/vcpkg_installed/x64-windows/debug/lib/libpng16d.lib (ver 1.6.58) + TIFF: optimized D:/Projects/SmartParallel/vcpkg_installed/x64-windows/lib/tiff.lib debug D:/Projects/SmartParallel/vcpkg_installed/x64-windows/debug/lib/tiffd.lib (ver 42 / 4.7.1) + GIF: YES + HDR: YES + SUNRASTER: YES + PXM: YES + PFM: YES + + Video I/O: + DirectShow: YES + Media Foundation: YES + DXVA: YES + + Parallel framework: Concurrency + + Other third-party libraries: + Custom HAL: NO + Protobuf: optimized D:/Projects/SmartParallel/vcpkg_installed/x64-windows/bin/libprotobuf.dll debug D:/Projects/SmartParallel/vcpkg_installed/x64-windows/debug/bin/libprotobufd.dll version (33.4.0) + Flatbuffers: 25.12.19 + + Python (for build): NO + + Install to: D:/Projects/SmartParallel/vcpkg_installed/vcpkg/pkgs/opencv4_x64-windows +----------------------------------------------------------------- + diff --git a/docs/v1.5/assets/benchmarks/accepted-learning.csv b/docs/v1.5/assets/benchmarks/accepted-learning.csv new file mode 100644 index 0000000..6d67016 --- /dev/null +++ b/docs/v1.5/assets/benchmarks/accepted-learning.csv @@ -0,0 +1,25 @@ +schema_version,preset,stable,stable_route,provisional_route,holdout_active,revalidation_active,drift_detected,verification_failures,route_switch_count,drift_strikes,revalidation_challenger,training_baseline_ms,current_baseline_ms,last_revalidation_stable_ms,last_revalidation_challenger_ms,route,median_ms,mad_ms,minimum_ms,maximum_ms,current_median_ms,sample_count,current_sample_count,warmup_count,holdout_sample_count,active +2,tiny_320x240,1,native_sequential,native_sequential,0,0,0,0,0,0,opencv,0.0021,0.0021,0.00205,0.0053,native_sequential,0.0021,0.0001,0.002,0.0028,0.0021,11,3,2,2,1 +2,tiny_320x240,1,native_sequential,native_sequential,0,0,0,0,0,0,opencv,0.0021,0.0021,0.00205,0.0053,opencv,0.003,0.0002,0.0028,0.0104,0.0072,11,2,2,2,1 +2,tiny_320x240,1,native_sequential,native_sequential,0,0,0,0,0,0,opencv,0.0021,0.0021,0.00205,0.0053,native_thread_pool,0.0604,0.0034,0.057,0.0639,0,3,0,2,0,0 +2,tiny_320x240,1,native_sequential,native_sequential,0,0,0,0,0,0,opencv,0.0021,0.0021,0.00205,0.0053,native_one_tbb,0.0753,0.0229,0.0524,0.1223,0,3,0,2,0,0 +2,small_640x480,1,native_sequential,native_sequential,0,0,0,0,0,0,opencv,0.0115,0.0084,0.00835,0.02775,native_sequential,0.0115,0.0002,0.011,0.0174,0.0084,11,3,2,2,1 +2,small_640x480,1,native_sequential,native_sequential,0,0,0,0,0,0,opencv,0.0115,0.0084,0.00835,0.02775,opencv,0.0171,0.0033,0.0089,0.1281,0.031,11,2,2,2,1 +2,small_640x480,1,native_sequential,native_sequential,0,0,0,0,0,0,opencv,0.0115,0.0084,0.00835,0.02775,native_thread_pool,0.0565,0.0004,0.0561,0.0772,0,3,0,2,0,0 +2,small_640x480,1,native_sequential,native_sequential,0,0,0,0,0,0,opencv,0.0115,0.0084,0.00835,0.02775,native_one_tbb,0.0465,0.0001,0.0464,0.0813,0,3,0,2,0,0 +2,medium_1920x1080,1,native_sequential,opencv,0,0,0,0,1,0,opencv,0.0762,0.0802,0.07205,0.12045,native_sequential,0.0762,0.0001,0.0761,0.1298,0.0802,3,4,2,0,0 +2,medium_1920x1080,1,native_sequential,opencv,0,0,0,0,1,0,opencv,0.0762,0.0802,0.07205,0.12045,opencv,0.0406,0.0053,0.0352,0.1395,0.1167,9,4,2,2,1 +2,medium_1920x1080,1,native_sequential,opencv,0,0,0,0,1,0,opencv,0.0762,0.0802,0.07205,0.12045,native_thread_pool,0.0714,0.0078,0.0455,0.1622,0,9,0,2,0,0 +2,medium_1920x1080,1,native_sequential,opencv,0,0,0,0,1,0,opencv,0.0762,0.0802,0.07205,0.12045,native_one_tbb,0.0704,0.0075,0.05,0.1593,0,9,0,2,2,0 +2,medium_1920x1080_roi,1,native_sequential,opencv,0,0,0,0,1,0,opencv,0.0923,0.0979,0.08555,0.12985,native_sequential,0.0923,0.0002,0.0921,0.0955,0.0979,3,4,2,0,0 +2,medium_1920x1080_roi,1,native_sequential,opencv,0,0,0,0,1,0,opencv,0.0923,0.0979,0.08555,0.12985,opencv,0.0352,0.0042,0.031,0.0477,0.1329,5,4,2,2,1 +2,medium_1920x1080_roi,1,native_sequential,opencv,0,0,0,0,1,0,opencv,0.0923,0.0979,0.08555,0.12985,native_thread_pool,0.0782,0.0034,0.064,0.0816,0,3,0,2,0,0 +2,medium_1920x1080_roi,1,native_sequential,opencv,0,0,0,0,1,0,opencv,0.0923,0.0979,0.08555,0.12985,native_one_tbb,0.0603,0.004,0.0563,0.075,0,5,0,2,2,0 +2,large_3840x2160,1,native_thread_pool,native_thread_pool,0,0,0,0,0,0,native_sequential,0.673,0.6789,0.69155,1.2461,native_sequential,1.271,0.0238,1.2333,1.2948,1.2592,3,2,2,0,0 +2,large_3840x2160,1,native_thread_pool,native_thread_pool,0,0,0,0,0,0,native_sequential,0.673,0.6789,0.69155,1.2461,opencv,0.7851,0.1073,0.6178,0.9005,0,11,0,2,0,1 +2,large_3840x2160,1,native_thread_pool,native_thread_pool,0,0,0,0,0,0,native_sequential,0.673,0.6789,0.69155,1.2461,native_thread_pool,0.673,0.0368,0.5949,0.7991,0.6789,11,3,2,2,1 +2,large_3840x2160,1,native_thread_pool,native_thread_pool,0,0,0,0,0,0,native_sequential,0.673,0.6789,0.69155,1.2461,native_one_tbb,0.6306,0.0123,0.5727,0.6686,0,11,0,2,2,1 +2,very_large_7680x4320,1,native_thread_pool,native_thread_pool,0,0,0,0,0,0,native_sequential,4.3007,4.3014,4.32525,4.93265,native_sequential,4.9605,0.0571,4.9034,5.332,4.9599,3,2,2,0,0 +2,very_large_7680x4320,1,native_thread_pool,native_thread_pool,0,0,0,0,0,0,native_sequential,4.3007,4.3014,4.32525,4.93265,opencv,4.2828,0.0067,4.2761,4.3003,0,3,0,2,2,1 +2,very_large_7680x4320,1,native_thread_pool,native_thread_pool,0,0,0,0,0,0,native_sequential,4.3007,4.3014,4.32525,4.93265,native_thread_pool,4.3007,0.0087,4.2814,4.3094,4.3014,3,3,2,2,1 +2,very_large_7680x4320,1,native_thread_pool,native_thread_pool,0,0,0,0,0,0,native_sequential,4.3007,4.3014,4.32525,4.93265,native_one_tbb,4.3025,0.0288,4.1375,4.3313,0,3,0,2,0,1 diff --git a/docs/v1.5/assets/benchmarks/accepted-publication-report.md b/docs/v1.5/assets/benchmarks/accepted-publication-report.md new file mode 100644 index 0000000..404cbeb --- /dev/null +++ b/docs/v1.5/assets/benchmarks/accepted-publication-report.md @@ -0,0 +1,31 @@ +# SmartParallel v1.5 Adaptive Execution Routes + +This report validates balanced initial learning, sparse drift sentinels, current-context ABBA revalidation, deployment settling, balanced steady-state route ordering, and batched adjacent ABBA/BAAB dispatch measurements. + +- Steady-state repetitions: **31** +- Route equivalence: **5.0% or 1.0 µs** +- Native oracle gate: **10.0% or 0.5 µs** +- Dispatch gate: **1.0 µs; failure only when the lower 95% robust bound exceeds the gate** +- Native kernel: **avx2** +- Raw CSV SHA-256: `dc471e82787c09cd26f5b92c28b62d370bb4c07dfd46a89feaa2e958a5325f60` +- Learning CSV SHA-256: `273d670c8638d9bd2985a73312feca7ed7b146d5cbc6dbb28ca41af9678b19c9` + +## Proof gates + +| Preset | Settled route | Switches | Fastest route | Route regret | Batched overhead (95% robust interval) | Native vs oracle | Training samples + holdout | Overall | +|---|---|---:|---|---:|---:|---:|---:|---| +| tiny_320x240 | native_sequential | 0 | smart_native_sequential | +0.00% | +0.043 µs [+0.041, +0.046] (pass) | -11.54% | 11 + 2 | PASS | +| small_640x480 | native_sequential | 0 | smart_native_sequential | +0.00% | +0.052 µs [+0.043, +0.060] (pass) | -10.10% | 11 + 2 | PASS | +| medium_1920x1080 | native_sequential | 1 | smart_native_sequential | +0.00% | +0.051 µs [-0.017, +0.120] (pass) | -6.22% | 3 + 0 | PASS | +| medium_1920x1080_roi | native_sequential | 1 | smart_native_sequential | +0.00% | +0.057 µs [-0.060, +0.175] (pass) | -7.41% | 3 + 0 | PASS | +| large_3840x2160 | native_thread_pool | 0 | smart_native_thread_pool | +0.00% | +5.700 µs [-1.607, +13.007] (inconclusive-pass) | -1.26% | 11 + 2 | PASS | +| very_large_7680x4320 | native_thread_pool | 0 | smart_native_one_tbb | +0.96% | +0.475 µs [-4.079, +5.029] (inconclusive-pass) | -0.68% | 3 + 2 | PASS | + +## Verdict + +- Route selection: **6/6** presets passed. +- Batched stable hot dispatch: **6/6** presets passed. +- Native kernel versus independent oracle: **6/6** presets passed. +- Combined release gate: **6/6** presets passed. + +The v1.5 threshold vertical slice passed all proof gates on this machine. diff --git a/docs/v1.5/assets/benchmarks/accepted-publication.zip b/docs/v1.5/assets/benchmarks/accepted-publication.zip new file mode 100644 index 0000000..b96ed2b Binary files /dev/null and b/docs/v1.5/assets/benchmarks/accepted-publication.zip differ diff --git a/docs/v1.5/assets/benchmarks/accepted-summary.csv b/docs/v1.5/assets/benchmarks/accepted-summary.csv new file mode 100644 index 0000000..f6a93a1 --- /dev/null +++ b/docs/v1.5/assets/benchmarks/accepted-summary.csv @@ -0,0 +1,7 @@ +benchmark_version,preset,width,height,stride_bytes,source_alignment,destination_alignment,learning_invocations,deployment_invocations,route_switch_count,drift_detected,training_baseline_ns,current_baseline_ns,last_revalidation_stable_ns,last_revalidation_challenger_ns,learning_verification_failures,learned_route_training_median_ns,learned_route_training_mad_ns,learned_route_training_samples,learned_route_holdout_samples,native_kernel,auto_selected_route,auto_median_ns,selected_forced_implementation,selected_forced_median_ns,fastest_eligible_implementation,fastest_eligible_median_ns,route_selection_regret_ns,route_selection_regret_percent,route_selection_pass,batched_dispatch_overhead_ns,dispatch_ci_lower_ns,dispatch_ci_upper_ns,dispatch_status,dispatch_overhead_pass,direct_sequential_median_ns,native_sequential_median_ns,native_kernel_delta_ns,native_kernel_delta_percent,native_kernel_pass,end_to_end_auto_regret_ns,end_to_end_auto_regret_percent,overall_pass,auto_mad_ns +1.5.0,tiny_320x240,320,240,320,64,32,40,24,0,0,2100,2100,2050,5300,0,2100,100,11,2,avx2,native_sequential,2700,smart_native_sequential,2300,smart_native_sequential,2300,0,0.0,1,43,41,46,pass,1,2600,2300,-300,-11.538461538461542,1,400,17.391304347826097,1,300 +1.5.0,small_640x480,640,480,640,32,64,40,24,0,0,11500,8400,8350,27750,0,11500,200,11,2,avx2,native_sequential,9300,smart_native_sequential,8900,smart_native_sequential,8900,0,0.0,1,52,43,60,pass,1,9900,8900,-1000,-10.1010101010101,1,400,4.494382022471921,1,300 +1.5.0,medium_1920x1080,1920,1080,1920,32,32,42,27,1,0,76200,80200,72050,120450,0,76200,100,3,0,avx2,native_sequential,87700,smart_native_sequential,91900,smart_native_sequential,91900,0,0.0,1,51,-17,120,pass,1,98000,91900,-6100,-6.224489795918364,1,-4200,-4.570184983677916,1,17400 +1.5.0,medium_1920x1080_roi,1920,1080,1984,32,32,28,27,1,0,92300,97900,85550,129850,0,92300,200,3,0,avx2,native_sequential,92800,smart_native_sequential,90000,smart_native_sequential,90000,0,0.0,1,57,-60,175,pass,1,97200,90000,-7200,-7.4074074074074066,1,2800,3.111111111111109,1,11400 +1.5.0,large_3840x2160,3840,2160,3840,32,32,48,24,0,0,673000,678900,691550,1246100,0,673000,36800,11,2,avx2,native_thread_pool,669300,smart_native_thread_pool,662100,smart_native_thread_pool,662100,0,0.0,1,5700,-1607,13007,inconclusive-pass,1,1272700,1256700,-16000,-1.2571697964956385,1,7200,1.0874490258269143,1,19100 +1.5.0,very_large_7680x4320,7680,4320,7680,32,32,24,24,0,0,4300700,4301400,4325250,4932650,0,4300700,8700,3,2,avx2,native_thread_pool,4334500,smart_native_thread_pool,4333000,smart_native_one_tbb,4291800,41200,0.9599701756838552,1,475,-4079,5029,inconclusive-pass,1,4936000,4902400,-33600,-0.6807131280389012,1,42700,0.9949205461577959,1,12700 diff --git a/docs/v1.5/assets/benchmarks/benchmark-metrics.json b/docs/v1.5/assets/benchmarks/benchmark-metrics.json new file mode 100644 index 0000000..ee74b6e --- /dev/null +++ b/docs/v1.5/assets/benchmarks/benchmark-metrics.json @@ -0,0 +1,157 @@ +{ + "release": "1.5.0", + "title": "Adaptive Execution Routes", + "operation": "threshold_u8_binary", + "publication_directory": "publication_20260728_192748", + "raw_schema_version": "6", + "learning_schema_version": "2", + "steady_state_repetitions": 31, + "raw_sample_count": 2238, + "correctness_failures": 0, + "authentication_failures": 0, + "combined_gate_passes": 6, + "combined_gate_total": 6, + "native_kernel": "avx2", + "logical_threads": "16", + "worker_budget": "16", + "opencv_version": "4.12.0", + "opencv_threads": "16", + "opencv_opencl": "no", + "geometric_mean_speedup_vs_direct_sequential": 1.1724868860718591, + "geometric_mean_speedup_vs_opencv_api": 1.4933026423540217, + "hashes": { + "raw_csv_sha256": "dc471e82787c09cd26f5b92c28b62d370bb4c07dfd46a89feaa2e958a5325f60", + "learning_csv_sha256": "273d670c8638d9bd2985a73312feca7ed7b146d5cbc6dbb28ca41af9678b19c9", + "summary_csv_sha256": "698f630e993b29326b6cda2ed7a3c7a06a6be2d71486a88c9e51f47200875878", + "environment_sha256": "2c58a81931c6ff0ebc49a2815ef7050a3eb838e99f63093852d78f4ffe3291b4", + "publication_report_sha256": "2f6f42d8c3347848d82b13a4d1ded56521306939082720c9a52c8c1863d8b165" + }, + "presets": [ + { + "preset": "tiny_320x240", + "label": "320×240", + "width": 320, + "height": 240, + "stride_bytes": 320, + "settled_route": "native_sequential", + "settled_route_label": "Native Sequential", + "route_switch_count": 0, + "auto_median_ns": 2700, + "direct_sequential_median_ns": 2600, + "opencv_api_median_ns": 4800, + "speedup_vs_direct_sequential": 0.9629629629629629, + "speedup_vs_opencv_api": 1.7777777777777777, + "route_selection_regret_percent": 0.0, + "dispatch_overhead_ns": 43, + "dispatch_ci_lower_ns": 41, + "dispatch_ci_upper_ns": 46, + "native_kernel_delta_percent": -11.538461538461542, + "overall_pass": true + }, + { + "preset": "small_640x480", + "label": "640×480", + "width": 640, + "height": 480, + "stride_bytes": 640, + "settled_route": "native_sequential", + "settled_route_label": "Native Sequential", + "route_switch_count": 0, + "auto_median_ns": 9300, + "direct_sequential_median_ns": 9900, + "opencv_api_median_ns": 26600, + "speedup_vs_direct_sequential": 1.064516129032258, + "speedup_vs_opencv_api": 2.860215053763441, + "route_selection_regret_percent": 0.0, + "dispatch_overhead_ns": 52, + "dispatch_ci_lower_ns": 43, + "dispatch_ci_upper_ns": 60, + "native_kernel_delta_percent": -10.1010101010101, + "overall_pass": true + }, + { + "preset": "medium_1920x1080", + "label": "1920×1080", + "width": 1920, + "height": 1080, + "stride_bytes": 1920, + "settled_route": "native_sequential", + "settled_route_label": "Native Sequential", + "route_switch_count": 1, + "auto_median_ns": 87700, + "direct_sequential_median_ns": 98000, + "opencv_api_median_ns": 139500, + "speedup_vs_direct_sequential": 1.1174458380843786, + "speedup_vs_opencv_api": 1.5906499429874572, + "route_selection_regret_percent": 0.0, + "dispatch_overhead_ns": 51, + "dispatch_ci_lower_ns": -17, + "dispatch_ci_upper_ns": 120, + "native_kernel_delta_percent": -6.224489795918364, + "overall_pass": true + }, + { + "preset": "medium_1920x1080_roi", + "label": "1920×1080 ROI", + "width": 1920, + "height": 1080, + "stride_bytes": 1984, + "settled_route": "native_sequential", + "settled_route_label": "Native Sequential", + "route_switch_count": 1, + "auto_median_ns": 92800, + "direct_sequential_median_ns": 97200, + "opencv_api_median_ns": 124600, + "speedup_vs_direct_sequential": 1.0474137931034482, + "speedup_vs_opencv_api": 1.3426724137931034, + "route_selection_regret_percent": 0.0, + "dispatch_overhead_ns": 57, + "dispatch_ci_lower_ns": -60, + "dispatch_ci_upper_ns": 175, + "native_kernel_delta_percent": -7.4074074074074066, + "overall_pass": true + }, + { + "preset": "large_3840x2160", + "label": "3840×2160", + "width": 3840, + "height": 2160, + "stride_bytes": 3840, + "settled_route": "native_thread_pool", + "settled_route_label": "Native ThreadPool", + "route_switch_count": 0, + "auto_median_ns": 669300, + "direct_sequential_median_ns": 1272700, + "opencv_api_median_ns": 682600, + "speedup_vs_direct_sequential": 1.901538921261019, + "speedup_vs_opencv_api": 1.0198715075451965, + "route_selection_regret_percent": 0.0, + "dispatch_overhead_ns": 5700, + "dispatch_ci_lower_ns": -1607, + "dispatch_ci_upper_ns": 13007, + "native_kernel_delta_percent": -1.2571697964956385, + "overall_pass": true + }, + { + "preset": "very_large_7680x4320", + "label": "7680×4320", + "width": 7680, + "height": 4320, + "stride_bytes": 7680, + "settled_route": "native_thread_pool", + "settled_route_label": "Native ThreadPool", + "route_switch_count": 0, + "auto_median_ns": 4334500, + "direct_sequential_median_ns": 4936000, + "opencv_api_median_ns": 4339700, + "speedup_vs_direct_sequential": 1.1387703310647133, + "speedup_vs_opencv_api": 1.0011996770100358, + "route_selection_regret_percent": 0.9599701756838552, + "dispatch_overhead_ns": 475, + "dispatch_ci_lower_ns": -4079, + "dispatch_ci_upper_ns": 5029, + "native_kernel_delta_percent": -0.6807131280389012, + "overall_pass": true + } + ] +} diff --git a/docs/v1.5/assets/benchmarks/generated-results.md b/docs/v1.5/assets/benchmarks/generated-results.md new file mode 100644 index 0000000..563ebaf --- /dev/null +++ b/docs/v1.5/assets/benchmarks/generated-results.md @@ -0,0 +1,22 @@ +# Generated v1.5 benchmark results + +> Generated from the accepted Windows/MSVC publication evidence. Do not edit by hand; rerun `tools/publish_v15_benchmark_docs.py`. + +- Publication: `publication_20260728_192748` +- Raw samples: **2,238** +- Correctness/authentication failures: **0** +- Combined proof gates: **6/6 passed** +- Native kernel: **avx2** +- Geometric-mean Auto speedup versus direct sequential: **1.17×** +- Geometric-mean Auto speedup versus direct OpenCV API: **1.49×** + +| Preset | Settled route | Auto median | Speedup vs direct | Speedup vs OpenCV API | Route regret | Runtime switches | +|---|---|---:|---:|---:|---:|---:| +| 320×240 | Native Sequential | 2.7 µs | 0.96× | 1.78× | 0.00% | 0 | +| 640×480 | Native Sequential | 9.3 µs | 1.06× | 2.86× | 0.00% | 0 | +| 1920×1080 | Native Sequential | 87.7 µs | 1.12× | 1.59× | 0.00% | 1 | +| 1920×1080 ROI | Native Sequential | 92.8 µs | 1.05× | 1.34× | 0.00% | 1 | +| 3840×2160 | Native ThreadPool | 669.3 µs | 1.90× | 1.02× | 0.00% | 0 | +| 7680×4320 | Native ThreadPool | 4.335 ms | 1.14× | 1.00× | 0.96% | 0 | + +All figures and aggregate values are machine-specific. The release claim is that Auto selected a route inside the declared equivalence gate on this machine, not that one provider is universally fastest. diff --git a/docs/v1.5/assets/benchmarks/source-hashes.txt b/docs/v1.5/assets/benchmarks/source-hashes.txt new file mode 100644 index 0000000..282abae --- /dev/null +++ b/docs/v1.5/assets/benchmarks/source-hashes.txt @@ -0,0 +1,5 @@ +dc471e82787c09cd26f5b92c28b62d370bb4c07dfd46a89feaa2e958a5325f60 raw_csv_sha256 +273d670c8638d9bd2985a73312feca7ed7b146d5cbc6dbb28ca41af9678b19c9 learning_csv_sha256 +698f630e993b29326b6cda2ed7a3c7a06a6be2d71486a88c9e51f47200875878 summary_csv_sha256 +2c58a81931c6ff0ebc49a2815ef7050a3eb838e99f63093852d78f4ffe3291b4 environment_sha256 +2f6f42d8c3347848d82b13a4d1ded56521306939082720c9a52c8c1863d8b165 publication_report_sha256 diff --git a/docs/v1.5/assets/benchmarks/v1.5.0_adaptive_route_map.svg b/docs/v1.5/assets/benchmarks/v1.5.0_adaptive_route_map.svg new file mode 100644 index 0000000..c14282e --- /dev/null +++ b/docs/v1.5/assets/benchmarks/v1.5.0_adaptive_route_map.svg @@ -0,0 +1,53 @@ + + +Initial learning and settled execution route +The two 1080p profiles initially preferred OpenCV, detected a changed regime, and switched once to Native Sequential. +320×240 + +Initial: Native Sequential + + + +Settled: Native Sequential +0 runtime switches +640×480 + +Initial: Native Sequential + + + +Settled: Native Sequential +0 runtime switches +1920×1080 + +Initial: OpenCV + + + +Settled: Native Sequential +1 runtime switch +1920×1080 ROI + +Initial: OpenCV + + + +Settled: Native Sequential +1 runtime switch +3840×2160 + +Initial: Native ThreadPool + + + +Settled: Native ThreadPool +0 runtime switches +7680×4320 + +Initial: Native ThreadPool + + + +Settled: Native ThreadPool +0 runtime switches + diff --git a/docs/v1.5/assets/benchmarks/v1.5.0_auto_regret.svg b/docs/v1.5/assets/benchmarks/v1.5.0_auto_regret.svg new file mode 100644 index 0000000..feb9004 --- /dev/null +++ b/docs/v1.5/assets/benchmarks/v1.5.0_auto_regret.svg @@ -0,0 +1,22 @@ + + +SmartParallel v1.5 balanced-learning Auto regret +tiny_320x240 + +17.39% · native_sequential +small_640x480 + +4.49% · native_sequential +medium_1920x1080 + +0.00% · native_sequential +medium_1920x1080_roi + +3.11% · native_sequential +large_3840x2160 + +1.09% · native_thread_pool +very_large_7680x4320 + +0.99% · native_thread_pool + \ No newline at end of file diff --git a/docs/v1.5/assets/benchmarks/v1.5.0_automatic_speedup.svg b/docs/v1.5/assets/benchmarks/v1.5.0_automatic_speedup.svg new file mode 100644 index 0000000..8dcb6cd --- /dev/null +++ b/docs/v1.5/assets/benchmarks/v1.5.0_automatic_speedup.svg @@ -0,0 +1,52 @@ + + +SmartParallel v1.5 automatic speedup +Values above 1.0× mean SmartParallel Auto completed the threshold operation faster. + +0.0× + +0.5× + +1.0× + +1.5× + +2.0× + +2.5× +320×240 + +0.96× + +1.78× +640×480 + +1.06× + +2.86× +1920×1080 + +1.12× + +1.59× +1920×1080 ROI + +1.05× + +1.34× +3840×2160 + +1.90× + +1.02× +7680×4320 + +1.14× + +1.00× + +vs direct sequential + +vs OpenCV API + + diff --git a/docs/v1.5/assets/benchmarks/v1.5.0_dispatch_overhead.svg b/docs/v1.5/assets/benchmarks/v1.5.0_dispatch_overhead.svg new file mode 100644 index 0000000..4b4b092 --- /dev/null +++ b/docs/v1.5/assets/benchmarks/v1.5.0_dispatch_overhead.svg @@ -0,0 +1,41 @@ + + +Stable Auto dispatch overhead +Point estimate and robust 95% interval from adjacent batched ABBA/BAAB comparisons; failure requires the lower bound to exceed +1 µs. + +-8 µs + +-4 µs + ++0 µs + ++1 µs + ++4 µs + ++8 µs +320×240 + + ++0.043 µs +640×480 + + ++0.052 µs +1920×1080 + + ++0.051 µs +1920×1080 ROI + + ++0.057 µs +3840×2160 + + ++5.700 µs +7680×4320 + + ++0.475 µs + diff --git a/docs/v1.5/assets/benchmarks/v1.5.0_native_kernel_vs_oracle.svg b/docs/v1.5/assets/benchmarks/v1.5.0_native_kernel_vs_oracle.svg new file mode 100644 index 0000000..12141ec --- /dev/null +++ b/docs/v1.5/assets/benchmarks/v1.5.0_native_kernel_vs_oracle.svg @@ -0,0 +1,34 @@ + + +Native AVX2 kernel versus independent compiler oracle +Negative values mean the SmartParallel Native Sequential kernel was faster; the release gate allows +10% or +0.5 µs. + + +-10% + +-5% + ++0% + ++5% + ++10% +320×240 + +-11.54% +640×480 + +-10.10% +1920×1080 + +-6.22% +1920×1080 ROI + +-7.41% +3840×2160 + +-1.26% +7680×4320 + +-0.68% + diff --git a/docs/v1.5/assets/benchmarks/v1.5.0_route_selection_regret.svg b/docs/v1.5/assets/benchmarks/v1.5.0_route_selection_regret.svg new file mode 100644 index 0000000..bb3e392 --- /dev/null +++ b/docs/v1.5/assets/benchmarks/v1.5.0_route_selection_regret.svg @@ -0,0 +1,37 @@ + + +SmartParallel v1.5 route-selection regret +Distance between the settled route and the fastest eligible forced route; the release limit is 5% or 1 µs. + +5% gate + +0% + +1% + +2% + +3% + +4% + +5% +320×240 + +0.00% · Native Sequential +640×480 + +0.00% · Native Sequential +1920×1080 + +0.00% · Native Sequential +1920×1080 ROI + +0.00% · Native Sequential +3840×2160 + +0.00% · Native ThreadPool +7680×4320 + +0.96% · Native ThreadPool + diff --git a/docs/v1.5/benchmark-methodology.md b/docs/v1.5/benchmark-methodology.md new file mode 100644 index 0000000..58e48c8 --- /dev/null +++ b/docs/v1.5/benchmark-methodology.md @@ -0,0 +1,122 @@ +# v1.5 benchmark methodology + +The v1.5 publication benchmark is designed to answer four separate questions without conflating them: + +1. Does every implementation produce exactly the same output? +2. Is SmartParallel's Native threshold kernel competitive with a simple independent compiler loop? +3. Does Auto settle on a route close to the fastest eligible route under current conditions? +4. Does the stable automatic decision add material overhead? + +## Operation and presets + +The tested operation is exact one-channel `uint8_t` binary thresholding: + +```text +destination = source > threshold ? maximum : 0 +``` + +The publication matrix includes contiguous 320×240, 640×480, 1920×1080, 3840×2160, and 7680×4320 images, plus a 1920×1080 strided ROI case. + +## Implementations + +Each preset is measured through: + +- `direct_sequential` — an independent compiler-generated reference loop; +- `opencv_api` — direct `cv::threshold`; +- `smart_auto` — the public automatic semantic API; +- forced Native Sequential; +- forced Native ThreadPool; +- forced Native StaticThread; +- forced Native oneTBB; +- forced SmartParallel OpenCV. + +StaticThread remains a diagnostic route but is not an automatic threshold candidate in v1.5. + +## Identical memory conditions + +Every implementation uses the same source allocation and the same destination allocation within a preset. The destination is reset outside the timed region. Raw evidence records exact addresses, strides, and alignment classes, and the analyzer rejects a matrix if those conditions differ between routes. + +This prevents one implementation from receiving a more favorable address, page layout, or alignment than another. + +## Correctness and authentication + +Every measured result is compared byte-for-byte with the expected output, including ROI row padding. Raw rows include an exact mismatch count and checksum. Forced routes must authenticate the requested backend; Auto must authenticate the selected route. + +Any mismatch or authentication failure invalidates the publication run before performance is analyzed. + +## Measurement phases + +### Cold call + +One cold Auto call is recorded for completeness. It is not mixed into steady-state medians. + +### Initial learning + +Each eligible route is primed twice without ranking those calls. Measured observations then use balanced route orders. The selector begins with three samples per active route and extends ambiguous comparisons up to the bounded sample window. Median and MAD estimates support elimination of clearly slower routes. + +A provisional winner must pass an independent holdout against the best remaining competitor before becoming stable. + +### Deployment settling + +The workload then changes from repeated Auto calls to a balanced interleaved route regime. Production drift sentinels and current-context ABBA revalidation remain enabled. If the original route is no longer competitive, SmartParallel can switch before measurement. + +The benchmark requires a bounded clean streak after the final route change. This phase proves adaptation rather than merely training directly under the final measurement pattern. + +### Frozen steady-state matrix + +Only after adaptation settles does the benchmark pause route maintenance and record the requested odd number of steady-state samples. Pausing maintenance avoids counting deliberate probes as ordinary Auto calls; production maintenance remains enabled outside this publication window and is covered by deterministic tests. + +Route order uses a balanced Williams-style design rather than a simple cyclic rotation, reducing position and predecessor bias. + +### Dispatch-overhead matrix + +A separate adjacent batched comparison measures Auto against the equivalent forced selected route: + +```text +Auto → Forced → Forced → Auto +Forced → Auto → Auto → Forced +``` + +Each block runs long enough to reduce clock and runtime noise. The analyzer reports a point estimate and robust 95% interval. + +## Proof gates + +### Route selection + +The forced implementation corresponding to Auto's settled route must be within: + +```text +5% or 1 µs +``` + +of the fastest eligible forced route. This evaluates route quality independently from Auto lookup cost. + +### Native kernel + +Native Sequential must be within: + +```text +10% or 0.5 µs +``` + +of the independent compiler-generated loop. This prevents Native performance regressions from being hidden by changes to the reference implementation. + +### Stable dispatch + +The stable dispatch gate fails only when the lower robust 95% confidence bound exceeds 1 µs. Wide intervals are reported as inconclusive passes rather than interpreted as precise overhead estimates. + +### Combined gate + +A preset passes only when correctness, authentication, route selection, native-kernel quality, and dispatch requirements all pass. + +## Statistical summaries + +Steady-state runtime uses the observed median from an odd number of samples. Variability uses median absolute deviation. The benchmark reports raw durations and absolute tolerances because percentages alone are misleading for operations that complete in only a few microseconds. + +## Scope of claims + +The accepted results apply to the recorded machine, compiler, OpenCV build, worker budget, image layouts, and threshold operation. They do not establish that SmartParallel, OpenCV, ThreadPool, or oneTBB is universally fastest. + +The supported release claim is narrower and stronger: + +> For this operation and recorded machine, SmartParallel Auto produced correct output, adapted to a changed performance regime, and settled within the declared equivalence gate for all six presets. diff --git a/docs/v1.5/benchmark-reproduction.md b/docs/v1.5/benchmark-reproduction.md new file mode 100644 index 0000000..fe4649a --- /dev/null +++ b/docs/v1.5/benchmark-reproduction.md @@ -0,0 +1,103 @@ +# v1.5 benchmark reproduction + +## Publication workflow + +From Command Prompt, with `VCPKG_ROOT` pointing to a vcpkg checkout: + +```bat +set "VCPKG_ROOT=D:\Tools\vcpkg" && scripts\validation\run_v15_adaptive_routes_release_validation.bat 31 +``` + +The script can be launched from any current directory. It: + +1. configures an MSVC Release build; +2. enables the vision module, OpenCV provider, and required oneTBB; +3. installs vcpkg's `vision-opencv` manifest feature; +4. builds the library, complete deterministic test suite, v1.5 test, example-capable module, and benchmark; +5. runs CTest; +6. records one cold Auto sample per preset; +7. performs balanced initial learning until the selector reports a holdout-verified route; +8. enters the balanced interleaved deployment regime with sparse drift sentinels and current-context ABBA revalidation enabled; +9. requires the adapted route to remain clean and unchanged for a bounded settling streak; +10. pauses route maintenance without changing the profile key, then records the requested odd steady-state matrix using one identical destination allocation for every route in a preset; +11. validates correctness, route authentication, identical addresses/alignment, deployment settling, route-switch telemetry, and probe isolation; +12. runs a dedicated adjacent Auto/selected-forced ABBA/BAAB batch matrix and computes confidence-bounded overhead; +13. evaluates Native Sequential against an independent compiler-generated reference loop and records the selected Native CPU kernel; +14. writes Markdown, CSV, learning telemetry, hashes, and dependency-free SVG evidence; +15. creates a shareable ZIP of the publication output. + +Development run: + +```bat +set "VCPKG_ROOT=D:\Tools\vcpkg" && scripts\validation\run_v15_adaptive_routes_development.bat +``` + +Reuse an existing valid build: + +```bat +scripts\validation\run_v15_adaptive_routes_release_validation.bat 31 reuse +``` + +## Outputs + +Each run creates a timestamped directory and ZIP under: + +```text +validation/output/v1.5.0_adaptive_routes/ +``` + +Core evidence: + +- `v1.5.0_adaptive_routes_raw.csv`; +- `v1.5.0_adaptive_routes_learning.csv`; +- `v1.5.0_adaptive_routes_environment.txt` with complete OpenCV build information; +- `v1.5.0_build_vectorization.log` with the MSVC build output and `/Qvec-report:2` diagnostic probe evidence; +- `v1.5.0_adaptive_routes.csv`; +- `v1.5.0_adaptive_routes_report.md`. + +Publication figures: + +- `v1.5.0_automatic_speedup.svg`; +- `v1.5.0_route_selection_regret.svg`; +- `v1.5.0_native_kernel_vs_oracle.svg`; +- `v1.5.0_dispatch_overhead.svg`; +- `v1.5.0_adaptive_route_map.svg`; +- `v1.5.0_auto_regret.svg` retained for compatibility with earlier publication bundles. + +## Publishing an accepted run into the documentation + +After a run passes all six combined proof gates, copy its validated data and figures into the documentation tree with: + +```bat +py -3 tools\publish_v15_benchmark_docs.py validation\output\v1.5.0_adaptive_routes\publication_ +``` + +The tool refuses to publish a run unless all six presets passed and every raw row is correct. It writes: + +- generated Markdown results; +- machine-readable JSON metrics; +- accepted summary and learning CSVs; +- environment metadata and source hashes; +- all publication SVG figures. + +Run the documentation validator afterward: + +```bat +py -3 tools\check_documentation.py +``` + +## Evidence policy + +The publication benchmark uses deterministic generated input, exact byte-level correctness, no timed disk I/O, one shared destination allocation per preset, destination reset outside timed sections, balanced route orders, odd observed-sample medians, and separate cold, learning, deployment-settling, steady-state, and dispatch phases. + +Raw schema v6 records exact addresses, alignment, Native-kernel identity, initial-learning and deployment call counts, route switches, pair order/position, and all probe states. Learning schema v2 records training and current baselines plus the latest current-context revalidation comparison. + +Production maintenance is paused only after deployment adaptation has settled, so the steady-state matrix contains clean learned hot-route executions. Drift detection and revalidation remain enabled in production and are validated deterministically. + +## Release gates + +- **Route selection:** the forced implementation matching the settled route must be within 5% or 1 µs of the fastest eligible forced route. +- **Stable dispatch:** the batched adjacent ABBA/BAAB Auto overhead must not have a lower robust 95% bound above 1 µs. +- **Native kernel:** Native Sequential must be within 10% or 0.5 µs of the independent compiler loop. + +OpenCV-versus-Native comparisons remain machine-specific. The framework does not require the Native kernel, OpenCV, or any scheduler to win universally. diff --git a/docs/v1.5/benchmarks.md b/docs/v1.5/benchmarks.md new file mode 100644 index 0000000..22774bd --- /dev/null +++ b/docs/v1.5/benchmarks.md @@ -0,0 +1,84 @@ +# v1.5 benchmark results + +SmartParallel v1.5 was evaluated with the first semantic operation, exact one-channel `uint8_t` binary thresholding. The publication benchmark compared the same operation through: + +- an independent compiler-generated sequential loop; +- direct OpenCV `cv::threshold`; +- SmartParallel Auto; +- forced Native Sequential, ThreadPool, StaticThread, and oneTBB routes; +- the forced SmartParallel OpenCV route. + +The accepted publication run was produced on Windows/MSVC Release with 16 logical threads, a SmartParallel worker budget of 16, OpenCV 4.12.0, OpenCL disabled, and the authenticated Native AVX2 kernel. These are machine-specific measurements, not universal speed guarantees. + +## Release verdict + +The accepted run contains **2,238 measured samples**, with: + +- **0 incorrect outputs**; +- **0 backend-authentication failures**; +- **6/6 route-selection gates passed**; +- **6/6 native-kernel gates passed**; +- **6/6 stable-dispatch gates passed**; +- **6/6 combined release gates passed**. + +Across the six presets, SmartParallel Auto achieved a **1.16× geometric-mean speedup over the independent sequential loop** and a **1.48× geometric-mean speedup over the direct OpenCV API** on the recorded machine. The strongest gain against direct sequential execution was **1.85× at 3840×2160**. The 7680×4320 case was effectively tied with OpenCV, with Auto at 0.99× the direct OpenCV rate. + +![SmartParallel v1.5 automatic speedup](assets/benchmarks/v1.5.0_automatic_speedup.svg) + +## Settled route map + +| Workload | Settled Auto route | Auto median | Speedup vs direct sequential | Speedup vs direct OpenCV | Route-selection regret | +|---|---|---:|---:|---:|---:| +| 320×240 | Native Sequential | 2.6 µs | 1.00× | 1.81× | 0.00% | +| 640×480 | Native Sequential | 9.1 µs | 1.09× | 2.91× | 0.00% | +| 1920×1080 | Native Sequential | 91.2 µs | 1.08× | 1.49× | 0.00% | +| 1920×1080 ROI | Native Sequential | 109.7 µs | 0.98× | 1.31× | 0.00% | +| 3840×2160 | Native ThreadPool | 696.9 µs | 1.85× | 1.04× | 2.51% | +| 7680×4320 | Native ThreadPool | 4.362 ms | 1.15× | 0.99× | 0.61% | + +Route-selection regret measures the settled route against the fastest eligible forced SmartParallel route under identical memory conditions. The release gate accepts routes within 5% or 1 µs because differences below that band are not operationally meaningful on this benchmark. + +![SmartParallel v1.5 route-selection regret](assets/benchmarks/v1.5.0_route_selection_regret.svg) + +## Runtime adaptation + +The two 1080p profiles initially learned OpenCV during repeated-call training. When the benchmark moved into a balanced interleaved deployment regime, OpenCV's relative cost changed. Sparse drift sentinels triggered a current-context comparison and SmartParallel switched both profiles once to Native Sequential before publication timing began. + +This matters because the framework did not merely benchmark candidates once and trust the answer forever. It detected that its earlier decision had become stale and changed route using new observations. + +![SmartParallel v1.5 initial and settled routes](assets/benchmarks/v1.5.0_adaptive_route_map.svg) + +## Native kernel quality + +The Native Sequential route uses a runtime-selected AVX2, SSE2, or portable branchless kernel. The accepted machine authenticated AVX2. Native Sequential was within the release gate of an independent compiler-generated loop for every preset and was slightly faster in five of six cases. + +![SmartParallel v1.5 native kernel versus oracle](assets/benchmarks/v1.5.0_native_kernel_vs_oracle.svg) + +The independent loop is intentionally separate from SmartParallel internals. It acts as a regression oracle: a change that slows the Native kernel cannot silently slow the benchmark reference at the same time. + +## Stable decision overhead + +For the four small and medium profiles, the estimated stable Auto lookup cost was approximately **0.012–0.051 µs**. At 4K and 8K, execution-runtime noise was wider than the decision cost; those cases passed as statistically inconclusive rather than claiming false precision. + +![SmartParallel v1.5 stable dispatch overhead](assets/benchmarks/v1.5.0_dispatch_overhead.svg) + +The overhead measurement uses adjacent batched ABBA/BAAB comparisons between Auto and the equivalent forced route. The gate fails only when the lower robust 95% bound is above 1 µs. + +## Interpretation + +The result is not that Native SmartParallel always beats OpenCV. The result is that OpenCV is now a valid automatic specialist and SmartParallel can select it when it wins, reject it when a Native route is better, and revisit the decision when conditions change. + +On another processor, OpenCV build, worker budget, image layout, or operation, the route map can be different. Applications should rely on Auto rather than copying this machine's choices into hard-coded policy. + +## Evidence + +- [Generated accepted results](assets/benchmarks/generated-results.md) +- [Machine-readable metrics](assets/benchmarks/benchmark-metrics.json) +- [Accepted six-preset summary](assets/benchmarks/accepted-summary.csv) +- [Accepted learning and adaptation telemetry](assets/benchmarks/accepted-learning.csv) +- [Accepted environment and OpenCV build information](assets/benchmarks/accepted-environment.txt) +- [Analyzer-generated publication report](assets/benchmarks/accepted-publication-report.md) +- [Source evidence hashes](assets/benchmarks/source-hashes.txt) +- [Full accepted publication evidence](assets/benchmarks/accepted-publication.zip) — raw CSV, learning telemetry, environment, build log, report, and figures. + +See [benchmark methodology](benchmark-methodology.md) for the fairness and release-gate design, and [benchmark reproduction](benchmark-reproduction.md) for the one-line Windows workflow. diff --git a/docs/v1.5/known-limitations.md b/docs/v1.5/known-limitations.md new file mode 100644 index 0000000..124a664 --- /dev/null +++ b/docs/v1.5/known-limitations.md @@ -0,0 +1,45 @@ +# v1.5 known limitations + +## One semantic operation + +v1.5 begins with exact one-channel 8-bit binary and inverse-binary thresholding. It is an architectural vertical slice, not an OpenCV wrapper collection. + +## Opaque lambdas remain Native-only + +SmartParallel cannot safely prove that an arbitrary compiled `parallel_transform` callable is equivalent to `cv::threshold` or another specialized function. Existing generic algorithms continue to select only Native scheduling strategies. Specialized substitution requires a semantic operation such as `smart::vision::threshold`. + +## Learning is in-process + +Route decisions are not persisted in v1.5. A new process repeats the bounded learning phase. Versioned persistent operation profiles remain a future extension. + +## Root-only adaptive provider selection + +Nested Auto calls use Native Sequential in the first release. External provider runtimes are not yet integrated into the root participant-lease accounting system. + +## OpenCV thread configuration is external + +SmartParallel fingerprints but does not mutate `cv::setNumThreads()` per call because it is process-global and unsafe to change concurrently. Applications that change OpenCV's global configuration must call `smart::vision::refresh_provider_state()` afterward. + +## Adaptation is bounded, not instantaneous + +Stable calls avoid timing overhead except for sparse sentinel observations. A large performance-regime change is normally detected after two sentinel samples and completed over a four-position current-context comparison, so a temporarily suboptimal route can remain active for a bounded number of calls before switching. + +## First-use learning has a cost + +A profile that has never been seen must prime and measure multiple routes before it can reuse a stable winner. This is appropriate for repeated image processing and pipelines, but a one-off call may not recover its learning cost. + +## Small operations expose dispatch floors + +For microsecond operations, tens of nanoseconds can appear as a noticeable percentage. Publication analysis reports raw durations, absolute tolerances, and confidence intervals rather than relying only on percentages. + +## Optional dependency and binary size + +Enabling the provider adds OpenCV core/imgproc deployment dependencies and binary footprint. The core `SmartParallel` package remains independent. + +## Machine-specific choices + +The fastest route depends on CPU features, memory, compiler, OpenCV build, oneTBB version, worker budget, image layout, and current system state. No checked-in route is universally optimal, and the accepted benchmark route map must not be treated as a fixed tuning table. + +## CPU scope + +The first Native SIMD implementation provides AVX2 and SSE2 paths for x86-family targets plus a portable branchless scalar fallback. Other architectures remain correct but may not yet have an architecture-specific vector kernel. diff --git a/docs/v1.5/release-notes.md b/docs/v1.5/release-notes.md new file mode 100644 index 0000000..9162f94 --- /dev/null +++ b/docs/v1.5/release-notes.md @@ -0,0 +1,49 @@ +# SmartParallel v1.5.0 release notes + +SmartParallel v1.5 — Adaptive Execution Routes extends automatic scheduling into automatic complete-implementation selection for recognized semantic operations. + +## Added + +- Optional `SmartParallel::vision` module and separate installed `SmartParallelVision` package. +- `smart::vision::threshold` for exact `uint8_t` binary and inverse-binary thresholding. +- Non-owning contiguous and strided image views. +- Automatic comparison of Native Sequential, Native ThreadPool, Native oneTBB, and optional OpenCV routes. +- Forced StaticThread and all other routes for diagnostics. +- Bounded sharded route profiles with two untimed priming observations, balanced successive-elimination rounds, median/MAD confidence bounds, independent winner holdout verification, conservative equivalent-route preference, single-flight probes, sparse drift sentinels, current-context ABBA revalidation, configuration invalidation, and a thread-local stable-route hot cache. +- OpenCV build/runtime fingerprinting and zero-copy `cv::Mat` views. +- Runtime-selected native threshold kernels: AVX2, SSE2, or a portable branchless scalar fallback. Unsigned-byte comparisons use an exact sign-bit transform in explicit SIMD, and contiguous/strided plus disjoint/in-place paths preserve the same semantics across every Native scheduler route. +- Stable hot-route calls use a compact exact thread-local key before full provider/profile construction and bypass internal route timing; external publication timing remains authoritative. +- Cached OpenCV provider state with an explicit `refresh_provider_state()` invalidation API. +- Thread-local operation decision diagnostics, route-training telemetry, and explicit route authentication. +- Deterministic route-selector, distribution-shift, correctness, SIMD, strided-image, forced-route, nested-fallback, and package-consumer tests. +- Proof-driven publication benchmark with an independent sequential oracle, identical memory for every route, balanced initial learning, deployment-regime adaptation, balanced Williams-style steady-state orders, batched adjacent ABBA/BAAB dispatch measurement, learning schema-v2 telemetry, raw schema-v6 evidence, robust confidence bounds, recomputed summaries, Markdown reporting, and dependency-free SVG generation. +- Release documentation with accepted summary data, environment metadata, source hashes, generated figures, benchmark methodology, and reproducible documentation publishing tools. + +## Preserved + +- Existing `parallel_for` and v1.4 algorithm APIs are unchanged. +- Existing `IExecutionBackend` and scheduler selection remain unchanged. +- The core installed target remains `SmartParallel::smart_parallel` and does not require OpenCV. +- OpenCV and the vision module are opt-in. + +## Accepted validation + +The accepted Windows/MSVC Release publication run used OpenCV 4.12.0, 16 logical threads, a SmartParallel worker budget of 16, OpenCL disabled, and the authenticated AVX2 Native kernel. + +- **2,238 measured samples** passed exact correctness and route authentication. +- **6/6 route-selection gates** passed. +- **6/6 native-kernel gates** passed. +- **6/6 stable-dispatch gates** passed. +- **6/6 combined release gates** passed. +- Auto achieved a **1.16× geometric-mean speedup over the independent sequential loop** and **1.48× over direct OpenCV** on the recorded machine. +- The two 1080p profiles initially learned OpenCV, detected a changed deployment regime, and switched once to Native Sequential using current-context evidence. +- The complete deterministic CTest suite passed **18/18**. +- Clang warnings-as-errors, ASan/UBSan, native-only packaging, OpenCV-enabled packaging, installed-package consumers, and retained v1.4 benchmark smoke validation passed. + +See [benchmark results](benchmarks.md), [methodology](benchmark-methodology.md), and [validation](validation.md). + +## Interpretation + +The v1.5 success criterion is not that Native SmartParallel beats OpenCV. It is that one application call approaches the fastest eligible correct route on the current machine without requiring the application to choose OpenCV or a scheduler manually, and that the framework can revisit that decision when current performance no longer matches its original observations. + +The accepted route map is machine-specific. Applications should use Auto rather than hard-code the recorded winners. diff --git a/docs/v1.5/validation.md b/docs/v1.5/validation.md new file mode 100644 index 0000000..b504965 --- /dev/null +++ b/docs/v1.5/validation.md @@ -0,0 +1,62 @@ +# v1.5 validation + +The deterministic target is: + +```text +smartparallel_v150_vision_adaptive_routes_validation +``` + +It validates: + +- two untimed priming observations per route; +- balanced successive-elimination learning with adaptive 3–11 sample windows; +- median/MAD bounds, outlier resistance, conservative equivalent-route preference, and independent holdout verification; +- failed holdout reopening, order independence, and provisional-winner reversal; +- runtime-selected AVX2/SSE2/branchless-scalar native kernels across contiguous/strided and disjoint/in-place Binary and BinaryInverse semantics; +- an MSVC `/Qvec-report:2` probe translation unit, plus an x86-64 deterministic gate that requires explicit SIMD selection; +- operation-specific profile separation; +- sparse drift detection, current-context stable/challenger ABBA revalidation, bounded distribution-shift recovery, and route promotion; +- single-flight exploration, concurrent-fallback measurement isolation, cancelled-probe recovery, and bounded profile retention; +- exact threshold output for Native Sequential, ThreadPool, and StaticThread; +- Native oneTBB and OpenCV when compiled in; +- automatic learning and authenticated selected routes; +- empty, one-pixel, odd-sized, and non-divisible workloads; +- exact in-place thresholding and non-contiguous rows without modifying padding; +- invalid dimensions, row strides, modes, routes, and partial buffer overlap; +- clear failure for an unavailable forced OpenCV route; +- safe Native Sequential fallback for nested automatic calls; +- installed-package consumption through `SmartParallel::vision`; +- a 31-call probe-free publication window after maintenance is explicitly paused. + +Timing thresholds are not used by deterministic tests. The selector uses injected observations, including a regime where OpenCV wins initially, later slows sharply, triggers sparse drift sentinels, completes current-context ABBA revalidation, and switches to Native within bounded calls. + +## Publication evidence validation + +Real performance is evaluated only by the publication benchmark. Raw schema v6 carries: + +- output checksums and exact mismatch counts; +- exploration, holdout, drift, and revalidation flags; +- exact source/destination addresses and alignment classes; +- initial-learning and deployment-settling call counts; +- route-switch count and Native-kernel identity; +- balanced steady-state order evidence; +- batched ABBA/BAAB block metadata. + +Learning schema v2 records each candidate's training and current medians, MAD, range, measured/priming/holdout/current counts, active state, verification failures, drift state, and latest current-context comparison. + +The analyzer rejects correctness failures, authentication failures, probe leakage, unfair memory, unbalanced route positions, inconsistent kernel identity, or malformed dispatch batches before evaluating performance. + +## Accepted release matrix + +The accepted Windows/MSVC publication run passed: + +- **18/18 deterministic CTest targets**; +- **2,238/2,238 correct and authenticated benchmark samples**; +- **6/6 route-selection gates**; +- **6/6 native-kernel gates**; +- **6/6 stable-dispatch gates**; +- **6/6 combined release gates**. + +Clang warnings-as-errors, Clang ASan/UBSan, native-only vision packaging, OpenCV-enabled packaging, installed-package consumers, core-only dependency isolation, and the retained v1.4 benchmark smoke matrix also passed during release preparation. + +See [benchmark results](benchmarks.md), [methodology](benchmark-methodology.md), and [reproduction](benchmark-reproduction.md). diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 1a72111..63abe4e 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -69,3 +69,9 @@ smartparallel_copy_tbb_runtime(smartparallel_performance_tuning_scheduler_valida add_executable(smartparallel_public_parallel_for_depth_four_regression public_parallel_for_depth_four_regression.cpp) target_link_libraries(smartparallel_public_parallel_for_depth_four_regression PRIVATE SmartParallel::smart_parallel) smartparallel_copy_tbb_runtime(smartparallel_public_parallel_for_depth_four_regression) + +if(TARGET smart_parallel_vision) + add_executable(smartparallel_v15_adaptive_threshold v15_adaptive_threshold.cpp) + target_link_libraries(smartparallel_v15_adaptive_threshold PRIVATE SmartParallel::vision) + smartparallel_copy_tbb_runtime(smartparallel_v15_adaptive_threshold) +endif() diff --git a/examples/v15_adaptive_threshold.cpp b/examples/v15_adaptive_threshold.cpp new file mode 100644 index 0000000..9116244 --- /dev/null +++ b/examples/v15_adaptive_threshold.cpp @@ -0,0 +1,56 @@ +#include + +#include +#include +#include +#include +#include + +int main() +{ + constexpr std::size_t width = 1920; + constexpr std::size_t height = 1080; + + std::vector source(width * height); + std::vector destination(width * height); + + for (std::size_t i = 0; i < source.size(); ++i) + source[i] = static_cast((i * 37U + 11U) & 0xffU); + + const auto source_view = smart::vision::make_contiguous_image_view( + static_cast(source.data()), width, height); + const auto destination_view = smart::vision::make_contiguous_image_view( + destination.data(), width, height); + + std::size_t stable_calls = 0; + for (std::size_t call = 0; call < 128 && stable_calls < 8; ++call) + { + smart::vision::threshold( + source_view, + destination_view, + smart::vision::ThresholdOptions{ + 127, + 255, + smart::vision::ThresholdMode::Binary, + }); + + const auto current = smart::vision::last_decision_report(); + const bool clean_learned_call = current.learned_route + && !current.exploration_probe + && !current.holdout_probe + && !current.revalidation_probe + && !current.drift_probe; + stable_calls = clean_learned_call ? stable_calls + 1 : 0; + } + + const auto decision = smart::vision::last_decision_report(); + const auto white_pixels = std::count(destination.begin(), destination.end(), std::uint8_t{255}); + + std::cout << "Selected route: " + << smart::vision::execution_route_name(decision.selected_route) << '\n'; + std::cout << "Learned route: " << (decision.learned_route ? "yes" : "no") << '\n'; + std::cout << "OpenCV available: " << (decision.opencv_available ? "yes" : "no") << '\n'; + std::cout << "White pixels: " << white_pixels << '\n'; + + return decision.backend_authenticated ? 0 : 1; +} diff --git a/include/smart/core/config.hpp b/include/smart/core/config.hpp index d553820..e6db54f 100644 --- a/include/smart/core/config.hpp +++ b/include/smart/core/config.hpp @@ -18,6 +18,7 @@ inline constexpr std::size_t nested_trace_records = 65536; inline constexpr std::size_t nested_plan_snapshots = 4096; inline constexpr std::size_t backend_calibration_states = 4096; inline constexpr std::size_t algorithm_dispatch_entries = 2048; +inline constexpr std::size_t vision_route_entries = 512; inline constexpr std::size_t bounded_limit(std::size_t configured, std::size_t production_default) noexcept @@ -215,6 +216,34 @@ struct Config std::size_t parallel_algorithm_hot_dispatch_revalidate_interval = 64; std::size_t parallel_algorithm_hot_dispatch_search_revalidate_interval = 32; + // v1.5 semantic-operation route selection. The vision layer compares + // complete correct implementations (Native Sequential/ThreadPool/oneTBB + // and optional specialized providers such as OpenCV) on separate real + // invocations, caches the winner, and periodically revalidates it. + bool enable_vision_adaptive_routes = true; + std::size_t vision_route_cache_max_entries = runtime_limits::vision_route_entries; + double vision_route_equivalence_ratio = 1.05; + double vision_route_measurement_blend = 0.25; + double vision_route_absolute_equivalence_ms = 0.001; + std::size_t vision_route_warmup_samples = 2; + std::size_t vision_route_minimum_samples = 3; + std::size_t vision_route_sample_window = 11; + std::size_t vision_route_holdout_samples = 2; + std::size_t vision_route_maximum_verification_failures = 2; + std::size_t vision_route_initial_revalidate_interval = 8; + std::size_t vision_route_revalidate_interval = 128; + std::size_t vision_route_drift_sample_interval = 8; + std::size_t vision_route_drift_required_samples = 2; + double vision_route_drift_ratio = 1.25; + double vision_route_drift_absolute_ms = 0.002; + // Diagnostic/publication controls may pause maintenance without changing + // the learned profile key. Production code should normally leave this false. + bool vision_route_pause_maintenance = false; + std::size_t vision_route_policy_generation = 0; + bool vision_route_consider_thread_pool = true; + bool vision_route_consider_one_tbb = true; + bool vision_route_consider_opencv = true; + // Analytical workload thresholds. These preserve the previous defaults // but are configurable instead of being embedded in decision rules. std::size_t small_workload_iteration_threshold = 1'000; diff --git a/include/smart/vision/decision_report.hpp b/include/smart/vision/decision_report.hpp new file mode 100644 index 0000000..66b5a97 --- /dev/null +++ b/include/smart/vision/decision_report.hpp @@ -0,0 +1,77 @@ +#pragma once + +#include +#include + +#include +#include + +namespace smart::vision +{ +struct DecisionReport +{ + ExecutionRoute requested_route = ExecutionRoute::Auto; + ExecutionRoute selected_route = ExecutionRoute::NativeSequential; + ExecutionEngineType native_engine = ExecutionEngineType::Auto; + + bool automatic = true; + bool adaptive_selection_enabled = false; + bool cache_hit = false; + bool learned_route = false; + bool exploration_probe = false; + bool holdout_probe = false; + bool revalidation_probe = false; + bool drift_probe = false; + bool nested_fallback = false; + + bool opencv_available = false; + bool backend_authenticated = false; + bool execution_timed = false; + + std::size_t worker_budget = 1; + std::size_t participant_count = 1; + std::size_t chunk_count = 1; + std::size_t candidate_count = 1; + std::size_t execution_depth = 0; + + double execution_ms = 0.0; +}; + +struct RouteTrainingEntry +{ + ExecutionRoute route = ExecutionRoute::NativeSequential; + double median_ms = 0.0; + double mad_ms = 0.0; + double minimum_ms = 0.0; + double maximum_ms = 0.0; + std::size_t sample_count = 0; + std::size_t warmup_count = 0; + std::size_t holdout_sample_count = 0; + std::size_t current_sample_count = 0; + double current_median_ms = 0.0; + bool active = false; +}; + +struct RouteTrainingReport +{ + bool available = false; + bool stable = false; + bool holdout_active = false; + bool revalidation_active = false; + bool drift_detected = false; + ExecutionRoute stable_route = ExecutionRoute::NativeSequential; + ExecutionRoute provisional_route = ExecutionRoute::NativeSequential; + std::size_t verification_failures = 0; + std::size_t route_switch_count = 0; + std::size_t drift_strikes = 0; + ExecutionRoute revalidation_challenger = ExecutionRoute::NativeSequential; + double training_baseline_ms = 0.0; + double current_baseline_ms = 0.0; + double last_revalidation_stable_ms = 0.0; + double last_revalidation_challenger_ms = 0.0; + std::vector routes; +}; + +DecisionReport last_decision_report() noexcept; +RouteTrainingReport last_route_training_report(); +} // namespace smart::vision diff --git a/include/smart/vision/detail/adaptive_route_selector.hpp b/include/smart/vision/detail/adaptive_route_selector.hpp new file mode 100644 index 0000000..1a54a5f --- /dev/null +++ b/include/smart/vision/detail/adaptive_route_selector.hpp @@ -0,0 +1,1114 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace smart::vision::detail +{ +struct RouteProfileKey +{ + std::uint64_t operation = 0; + std::size_t pixel_bucket = 0; + std::size_t width_bucket = 0; + std::size_t height_bucket = 0; + std::size_t stride_bucket = 0; + std::size_t parameter_hash = 0; + std::size_t worker_budget = 1; + std::size_t candidate_mask = 0; + std::size_t policy_generation = 0; + std::size_t provider_fingerprint = 0; + + bool operator==(const RouteProfileKey& other) const noexcept + { + return operation == other.operation && pixel_bucket == other.pixel_bucket + && width_bucket == other.width_bucket && height_bucket == other.height_bucket + && stride_bucket == other.stride_bucket && parameter_hash == other.parameter_hash + && worker_budget == other.worker_budget && candidate_mask == other.candidate_mask + && policy_generation == other.policy_generation + && provider_fingerprint == other.provider_fingerprint; + } +}; + +struct RouteProfileKeyHasher +{ + std::size_t operator()(const RouteProfileKey& key) const noexcept + { + auto combine = [](std::size_t seed, std::size_t value) + { + return seed ^ (value + 0x9e3779b97f4a7c15ull + (seed << 6u) + (seed >> 2u)); + }; + std::size_t hash = static_cast(key.operation); + hash = combine(hash, key.pixel_bucket); + hash = combine(hash, key.width_bucket); + hash = combine(hash, key.height_bucket); + hash = combine(hash, key.stride_bucket); + hash = combine(hash, key.parameter_hash); + hash = combine(hash, key.worker_budget); + hash = combine(hash, key.candidate_mask); + hash = combine(hash, key.policy_generation); + hash = combine(hash, key.provider_fingerprint); + return hash; + } +}; + +struct RouteSelectorSettings +{ + std::size_t maximum_entries = 512; + double equivalence_ratio = 1.05; + double absolute_equivalence_ms = 0.001; + // Retained for source compatibility with v1.5 preview configurations. + double measurement_blend = 0.25; + std::size_t warmup_samples = 2; + std::size_t minimum_samples = 3; + std::size_t sample_window = 11; + std::size_t holdout_samples = 2; + std::size_t maximum_verification_failures = 2; + std::size_t initial_revalidate_interval = 8; + std::size_t revalidate_interval = 128; + std::size_t drift_required_samples = 2; + double drift_ratio = 1.25; + double drift_absolute_ms = 0.002; + bool force_revalidation = false; + bool force_stable_sample = false; +}; + +struct RouteSelection +{ + bool enabled = false; + bool cache_hit = false; + bool stable = false; + bool probe = false; + bool warmup = false; + bool holdout = false; + bool revalidation = false; + bool drift_sample = false; + bool revalidation_stable_sample = false; + std::uint8_t revalidation_stage = 0; + std::uint64_t probe_nonce = 0; + ExecutionRoute route = ExecutionRoute::NativeSequential; + RouteProfileKey key{}; +}; + +struct RouteMeasurementSnapshot +{ + ExecutionRoute stable_route = ExecutionRoute::NativeSequential; + ExecutionRoute provisional_route = ExecutionRoute::NativeSequential; + bool stable = false; + bool holdout_active = false; + bool revalidation_active = false; + bool drift_detected = false; + std::size_t use_count = 0; + std::size_t revalidate_after_uses = 0; + std::size_t verification_failures = 0; + std::size_t route_switch_count = 0; + std::size_t drift_strikes = 0; + ExecutionRoute revalidation_challenger = ExecutionRoute::NativeSequential; + double training_baseline_ms = 0.0; + double current_baseline_ms = 0.0; + double last_revalidation_stable_ms = 0.0; + double last_revalidation_challenger_ms = 0.0; + std::vector routes; + std::vector elapsed_ms; + std::vector mad_ms; + std::vector minimum_ms; + std::vector maximum_ms; + std::vector current_elapsed_ms; + std::vector samples; + std::vector current_samples; + std::vector warmups; + std::vector holdout_samples; + std::vector active; +}; + +class AdaptiveRouteSelector +{ + public: + RouteSelection select(const RouteProfileKey& key, + const std::vector& candidates, + const RouteSelectorSettings& settings) + { + RouteSelection selection; + selection.enabled = !candidates.empty(); + selection.key = key; + if (candidates.empty()) + return selection; + + Shard& shard = shards_[shard_index(key)]; + std::lock_guard lock(shard.mutex); + auto found = shard.entries.find(key); + selection.cache_hit = found != shard.entries.end(); + if (found == shard.entries.end()) + { + make_room_locked(shard, normalized_maximum(settings.maximum_entries)); + Entry entry; + reset_entry(entry, candidates, key, settings); + found = shard.entries.emplace(key, std::move(entry)).first; + } + + Entry& entry = found->second; + entry.last_access = ++shard.access_epoch; + if (entry.candidates != candidates) + reset_entry(entry, candidates, key, settings); + + if (entry.probe_in_progress) + { + selection.route = entry.stable ? entry.stable_route + : entry.phase == Phase::Holdout ? entry.candidates[entry.provisional_index] + : entry.candidates.front(); + selection.stable = entry.stable; + return selection; + } + + const std::size_t warmup_index = next_warmup_index(entry, settings); + if (warmup_index != invalid_index()) + { + begin_probe(entry, selection, warmup_index, true, false, false); + return selection; + } + + if (!entry.stable) + { + prepare_learning_state(entry, settings); + if (entry.phase == Phase::Holdout) + { + const std::size_t holdout_index = next_holdout_index(entry, settings); + if (holdout_index != invalid_index()) + { + begin_probe(entry, selection, holdout_index, false, true, false); + return selection; + } + finalize_holdout(entry, settings); + } + + if (!entry.stable) + { + prepare_learning_state(entry, settings); + if (entry.phase == Phase::Holdout) + { + const std::size_t holdout_index = next_holdout_index(entry, settings); + if (holdout_index != invalid_index()) + { + begin_probe(entry, selection, holdout_index, false, true, false); + return selection; + } + } + const std::size_t learning_index = next_learning_index(entry); + if (learning_index != invalid_index()) + { + begin_probe(entry, selection, learning_index, false, false, false); + return selection; + } + // Defensive fallback: bounded learning must always converge. + choose_stable_from_training(entry, settings, false); + } + } + + ensure_training_baseline(entry); + selection.route = entry.stable_route; + selection.stable = true; + + if (entry.revalidation_phase != RevalidationPhase::Idle) + { + begin_next_revalidation_probe(entry, selection); + return selection; + } + + if (settings.force_stable_sample) + { + const std::size_t stable_index = route_index(entry, entry.stable_route); + begin_probe(entry, selection, stable_index, false, false, false, true); + return selection; + } + + const bool periodic_revalidation = entry.current_revalidate_interval > 0 + && ++entry.uses_since_revalidation >= entry.current_revalidate_interval; + if (entry.candidates.size() > 1 + && (settings.force_revalidation || periodic_revalidation)) + { + start_revalidation(entry, selection); + } + return selection; + } + + void complete(const RouteSelection& selection, + double elapsed_ms, + const RouteSelectorSettings& settings) noexcept + { + if (!selection.enabled || !selection.probe || elapsed_ms < 0.0) + return; + Shard& shard = shards_[shard_index(selection.key)]; + std::lock_guard lock(shard.mutex); + const auto found = shard.entries.find(selection.key); + if (found == shard.entries.end()) + return; + + Entry& entry = found->second; + entry.last_access = ++shard.access_epoch; + const std::size_t index = route_index(entry, selection.route); + if (index == invalid_index()) + return; + + if (selection.revalidation) + { + Measurement& target = selection.revalidation_stable_sample + ? entry.revalidation_stable_samples + : entry.revalidation_challenger_samples; + add_sample(target, elapsed_ms, 2); + release_probe(entry, selection); + advance_revalidation(entry, selection, settings); + return; + } + + if (selection.drift_sample) + { + add_sample(entry.current_measurements[index], elapsed_ms, settings.sample_window); + release_probe(entry, selection); + process_drift_sample(entry, index, elapsed_ms, settings); + return; + } + + if (selection.warmup) + ++entry.measurements[index].warmups; + else if (selection.holdout) + add_sample(entry.holdouts[index], elapsed_ms, settings.sample_window); + else + add_sample(entry.measurements[index], elapsed_ms, settings.sample_window); + + release_probe(entry, selection); + + if (selection.holdout && holdout_complete(entry, settings)) + finalize_holdout(entry, settings); + else if (!selection.warmup && !selection.holdout) + prepare_learning_state(entry, settings); + } + + void cancel(const RouteSelection& selection) noexcept + { + if (!selection.enabled || !selection.probe) + return; + Shard& shard = shards_[shard_index(selection.key)]; + std::lock_guard lock(shard.mutex); + const auto found = shard.entries.find(selection.key); + if (found == shard.entries.end()) + return; + Entry& entry = found->second; + if (entry.probe_in_progress && entry.active_probe_nonce == selection.probe_nonce) + { + entry.probe_in_progress = false; + entry.active_probe_nonce = 0; + } + } + + void clear() noexcept + { + for (Shard& shard : shards_) + { + std::lock_guard lock(shard.mutex); + shard.entries.clear(); + shard.access_epoch = 0; + } + } + + bool snapshot(const RouteProfileKey& key, RouteMeasurementSnapshot& output) const + { + const Shard& shard = shards_[shard_index(key)]; + std::lock_guard lock(shard.mutex); + const auto found = shard.entries.find(key); + if (found == shard.entries.end()) + return false; + const Entry& entry = found->second; + output = {}; + output.stable_route = entry.stable_route; + output.provisional_route = entry.candidates.empty() + ? ExecutionRoute::NativeSequential + : entry.candidates[entry.provisional_index]; + output.stable = entry.stable; + output.holdout_active = entry.phase == Phase::Holdout; + output.revalidation_active = entry.revalidation_phase != RevalidationPhase::Idle; + output.drift_detected = entry.drift_detected; + output.use_count = entry.uses_since_revalidation; + output.revalidate_after_uses = entry.current_revalidate_interval; + output.verification_failures = entry.verification_failures; + output.route_switch_count = entry.route_switch_count; + output.drift_strikes = entry.drift_strikes; + output.revalidation_challenger = entry.candidates.empty() + ? ExecutionRoute::NativeSequential + : entry.candidates[entry.revalidation_challenger_index]; + output.training_baseline_ms = entry.training_baseline_ms; + const std::size_t stable_index = entry.stable + ? route_index(entry, entry.stable_route) : invalid_index(); + output.current_baseline_ms = stable_index != invalid_index() + ? median(entry.current_measurements[stable_index]) : 0.0; + output.last_revalidation_stable_ms = entry.last_revalidation_stable_ms; + output.last_revalidation_challenger_ms = entry.last_revalidation_challenger_ms; + output.routes = entry.candidates; + output.active = entry.active; + for (std::size_t index = 0; index < entry.measurements.size(); ++index) + { + const Measurement& measurement = entry.measurements[index]; + output.elapsed_ms.push_back(median(measurement)); + output.mad_ms.push_back(mad(measurement)); + output.minimum_ms.push_back(minimum(measurement)); + output.maximum_ms.push_back(maximum(measurement)); + output.current_elapsed_ms.push_back(median(entry.current_measurements[index])); + output.samples.push_back(measurement.sample_count); + output.current_samples.push_back(entry.current_measurements[index].sample_count); + output.warmups.push_back(measurement.warmups); + output.holdout_samples.push_back(entry.holdouts[index].sample_count); + } + return true; + } + + private: + static constexpr std::size_t maximum_sample_window = 15; + enum class Phase { Learning, Holdout, Stable }; + enum class RevalidationPhase { Idle, StableA, ChallengerA, ChallengerB, StableB }; + + struct Measurement + { + std::size_t warmups = 0; + std::array samples{}; + std::size_t sample_count = 0; + std::size_t next_sample = 0; + }; + + struct Entry + { + std::vector candidates; + std::vector measurements; + std::vector holdouts; + std::vector current_measurements; + std::vector active; + ExecutionRoute stable_route = ExecutionRoute::NativeSequential; + Phase phase = Phase::Learning; + bool stable = false; + bool probe_in_progress = false; + std::uint64_t active_probe_nonce = 0; + std::size_t provisional_index = 0; + std::size_t runner_up_index = 0; + std::size_t learning_target_samples = 1; + std::size_t verification_failures = 0; + std::size_t uses_since_revalidation = 0; + std::size_t current_revalidate_interval = 0; + std::size_t next_revalidation_index = 0; + RevalidationPhase revalidation_phase = RevalidationPhase::Idle; + std::size_t revalidation_stable_index = 0; + std::size_t revalidation_challenger_index = 0; + Measurement revalidation_stable_samples; + Measurement revalidation_challenger_samples; + std::size_t drift_strikes = 0; + bool drift_detected = false; + std::size_t route_switch_count = 0; + double training_baseline_ms = 0.0; + double last_revalidation_stable_ms = 0.0; + double last_revalidation_challenger_ms = 0.0; + std::size_t rotation_seed = 0; + std::uint64_t last_access = 0; + }; + + struct Shard + { + mutable std::mutex mutex; + std::unordered_map entries; + std::uint64_t access_epoch = 0; + }; + + static constexpr std::size_t shard_count = 16; + std::array shards_{}; + std::uint64_t next_probe_nonce_ = 0; + mutable std::mutex nonce_mutex_; + + static std::size_t invalid_index() noexcept + { + return std::numeric_limits::max(); + } + + static std::size_t normalized_maximum(std::size_t maximum_entries) noexcept + { + return maximum_entries == 0 ? 512 : maximum_entries; + } + + static std::size_t normalized_minimum(const RouteSelectorSettings& settings) noexcept + { + return std::max(1, + std::min(settings.minimum_samples, + std::max(1, + std::min(settings.sample_window, maximum_sample_window)))); + } + + static std::size_t normalized_window(const RouteSelectorSettings& settings) noexcept + { + return std::max(normalized_minimum(settings), + std::min(settings.sample_window == 0 ? normalized_minimum(settings) + : settings.sample_window, + maximum_sample_window)); + } + + static std::size_t shard_index(const RouteProfileKey& key) noexcept + { + return RouteProfileKeyHasher{}(key) % shard_count; + } + + static std::size_t route_index(const Entry& entry, ExecutionRoute route) noexcept + { + const auto found = std::find(entry.candidates.begin(), entry.candidates.end(), route); + return found == entry.candidates.end() ? invalid_index() + : static_cast(found - entry.candidates.begin()); + } + + static int route_preference(ExecutionRoute route) noexcept + { + switch (route) + { + case ExecutionRoute::NativeSequential: return 0; + case ExecutionRoute::NativeThreadPool: return 1; + case ExecutionRoute::NativeOneTbb: return 2; + case ExecutionRoute::NativeStaticThread: return 3; + case ExecutionRoute::OpenCV: return 4; + case ExecutionRoute::Auto: return 5; + } + return 5; + } + + static double median(const Measurement& measurement) noexcept + { + if (measurement.sample_count == 0) + return 0.0; + std::array sorted = measurement.samples; + std::sort(sorted.begin(), sorted.begin() + measurement.sample_count); + return sorted[measurement.sample_count / 2]; + } + + static double mad(const Measurement& measurement) noexcept + { + if (measurement.sample_count == 0) + return 0.0; + const double center = median(measurement); + std::array deviations{}; + for (std::size_t index = 0; index < measurement.sample_count; ++index) + deviations[index] = std::abs(measurement.samples[index] - center); + std::sort(deviations.begin(), deviations.begin() + measurement.sample_count); + return deviations[measurement.sample_count / 2]; + } + + static double minimum(const Measurement& measurement) noexcept + { + if (measurement.sample_count == 0) + return 0.0; + return *std::min_element(measurement.samples.begin(), + measurement.samples.begin() + measurement.sample_count); + } + + static double maximum(const Measurement& measurement) noexcept + { + if (measurement.sample_count == 0) + return 0.0; + return *std::max_element(measurement.samples.begin(), + measurement.samples.begin() + measurement.sample_count); + } + + static void add_sample(Measurement& measurement, + double elapsed_ms, + std::size_t requested_window) noexcept + { + const std::size_t window = std::max( + 1, std::min(requested_window == 0 ? maximum_sample_window : requested_window, + maximum_sample_window)); + if (measurement.sample_count < window) + { + measurement.samples[measurement.sample_count++] = elapsed_ms; + measurement.next_sample = measurement.sample_count % window; + } + else + { + measurement.samples[measurement.next_sample] = elapsed_ms; + measurement.next_sample = (measurement.next_sample + 1) % window; + } + } + + static void reset_to_single_sample(Measurement& measurement, + double elapsed_ms) noexcept + { + const std::size_t warmups = measurement.warmups; + measurement = {}; + measurement.warmups = warmups; + measurement.samples[0] = elapsed_ms; + measurement.sample_count = 1; + measurement.next_sample = 1; + } + + static void clear_holdouts(Entry& entry) noexcept + { + for (Measurement& measurement : entry.holdouts) + measurement = {}; + } + + static void reset_entry(Entry& entry, + const std::vector& candidates, + const RouteProfileKey& key, + const RouteSelectorSettings& settings) + { + const std::uint64_t last_access = entry.last_access; + entry = Entry{}; + entry.candidates = candidates; + entry.measurements.resize(candidates.size()); + entry.holdouts.resize(candidates.size()); + entry.current_measurements.resize(candidates.size()); + entry.active.assign(candidates.size(), true); + entry.rotation_seed = candidates.empty() ? 0 + : RouteProfileKeyHasher{}(key) % candidates.size(); + entry.learning_target_samples = normalized_minimum(settings); + entry.current_revalidate_interval = normalized_initial_interval(settings); + entry.last_access = last_access; + } + + static std::size_t normalized_initial_interval( + const RouteSelectorSettings& settings) noexcept + { + if (settings.revalidate_interval == 0) + return 0; + const std::size_t initial = settings.initial_revalidate_interval == 0 + ? settings.revalidate_interval : settings.initial_revalidate_interval; + return std::max(1, std::min(initial, settings.revalidate_interval)); + } + + std::uint64_t next_nonce() noexcept + { + std::lock_guard lock(nonce_mutex_); + return ++next_probe_nonce_; + } + + void begin_probe(Entry& entry, + RouteSelection& selection, + std::size_t index, + bool warmup, + bool holdout, + bool revalidation, + bool drift_sample = false, + bool revalidation_stable_sample = false, + std::uint8_t revalidation_stage = 0) + { + entry.probe_in_progress = true; + entry.active_probe_nonce = next_nonce(); + selection.route = entry.candidates[index]; + selection.probe = true; + selection.warmup = warmup; + selection.holdout = holdout; + selection.revalidation = revalidation; + selection.drift_sample = drift_sample; + selection.revalidation_stable_sample = revalidation_stable_sample; + selection.revalidation_stage = revalidation_stage; + selection.probe_nonce = entry.active_probe_nonce; + selection.stable = entry.stable; + } + + static void release_probe(Entry& entry, const RouteSelection& selection) noexcept + { + if (entry.probe_in_progress && entry.active_probe_nonce == selection.probe_nonce) + { + entry.probe_in_progress = false; + entry.active_probe_nonce = 0; + } + } + + static void ensure_training_baseline(Entry& entry) noexcept + { + if (!entry.stable || entry.training_baseline_ms > 0.0) + return; + const std::size_t index = route_index(entry, entry.stable_route); + if (index != invalid_index()) + entry.training_baseline_ms = median(entry.measurements[index]); + } + + static double two_sample_center(const Measurement& measurement) noexcept + { + if (measurement.sample_count == 0) + return 0.0; + if (measurement.sample_count == 1) + return measurement.samples[0]; + return 0.5 * (measurement.samples[0] + measurement.samples[1]); + } + + static void initialize_revalidation(Entry& entry) noexcept + { + entry.revalidation_stable_samples = {}; + entry.revalidation_challenger_samples = {}; + entry.revalidation_stable_index = route_index(entry, entry.stable_route); + entry.revalidation_challenger_index = next_alternative( + entry, entry.revalidation_stable_index); + entry.uses_since_revalidation = 0; + } + + void start_revalidation(Entry& entry, RouteSelection& selection) + { + initialize_revalidation(entry); + entry.revalidation_phase = RevalidationPhase::StableA; + begin_next_revalidation_probe(entry, selection); + } + + void begin_next_revalidation_probe(Entry& entry, RouteSelection& selection) + { + switch (entry.revalidation_phase) + { + case RevalidationPhase::StableA: + begin_probe(entry, selection, entry.revalidation_stable_index, + false, false, true, false, true, 1); + break; + case RevalidationPhase::ChallengerA: + begin_probe(entry, selection, entry.revalidation_challenger_index, + false, false, true, false, false, 2); + break; + case RevalidationPhase::ChallengerB: + begin_probe(entry, selection, entry.revalidation_challenger_index, + false, false, true, false, false, 3); + break; + case RevalidationPhase::StableB: + begin_probe(entry, selection, entry.revalidation_stable_index, + false, false, true, false, true, 4); + break; + case RevalidationPhase::Idle: + break; + } + } + + static void finalize_revalidation(Entry& entry, + const RouteSelectorSettings& settings) noexcept + { + const double stable_ms = two_sample_center(entry.revalidation_stable_samples); + const double challenger_ms = two_sample_center(entry.revalidation_challenger_samples); + entry.last_revalidation_stable_ms = stable_ms; + entry.last_revalidation_challenger_ms = challenger_ms; + + for (std::size_t index = 0; index < entry.revalidation_stable_samples.sample_count; ++index) + add_sample(entry.current_measurements[entry.revalidation_stable_index], + entry.revalidation_stable_samples.samples[index], + settings.sample_window); + for (std::size_t index = 0; index < entry.revalidation_challenger_samples.sample_count; ++index) + add_sample(entry.current_measurements[entry.revalidation_challenger_index], + entry.revalidation_challenger_samples.samples[index], + settings.sample_window); + + const double margin = std::max( + std::max(0.0, settings.absolute_equivalence_ms), + std::min(stable_ms, challenger_ms) + * (std::max(1.0, settings.equivalence_ratio) - 1.0)); + const bool challenger_faster = challenger_ms + margin < stable_ms; + const bool equivalent = std::abs(challenger_ms - stable_ms) <= margin; + const bool preferred_equivalent = equivalent + && route_preference(entry.candidates[entry.revalidation_challenger_index]) + < route_preference(entry.candidates[entry.revalidation_stable_index]); + if (challenger_faster || preferred_equivalent) + { + entry.stable_route = entry.candidates[entry.revalidation_challenger_index]; + entry.training_baseline_ms = median( + entry.measurements[entry.revalidation_challenger_index]); + ++entry.route_switch_count; + entry.current_revalidate_interval = normalized_initial_interval(settings); + } + else + { + const std::size_t maximum_interval = settings.revalidate_interval; + if (maximum_interval > 0) + { + const std::size_t current = std::max( + 1, entry.current_revalidate_interval); + entry.current_revalidate_interval = std::min( + maximum_interval, current > maximum_interval / 2 + ? maximum_interval : current * 2); + } + } + + entry.revalidation_phase = RevalidationPhase::Idle; + entry.revalidation_stable_samples = {}; + entry.revalidation_challenger_samples = {}; + entry.drift_strikes = 0; + entry.uses_since_revalidation = 0; + } + + static void advance_revalidation(Entry& entry, + const RouteSelection& selection, + const RouteSelectorSettings& settings) noexcept + { + switch (selection.revalidation_stage) + { + case 1: entry.revalidation_phase = RevalidationPhase::ChallengerA; break; + case 2: entry.revalidation_phase = RevalidationPhase::ChallengerB; break; + case 3: entry.revalidation_phase = RevalidationPhase::StableB; break; + case 4: finalize_revalidation(entry, settings); break; + default: break; + } + } + + static void process_drift_sample(Entry& entry, + std::size_t stable_index, + double elapsed_ms, + const RouteSelectorSettings& settings) noexcept + { + const double baseline = entry.last_revalidation_stable_ms > 0.0 + ? entry.last_revalidation_stable_ms : entry.training_baseline_ms; + const double drift_limit = baseline > 0.0 + ? std::max(baseline * std::max(1.0, settings.drift_ratio), + baseline + std::max(0.0, settings.drift_absolute_ms)) + : std::numeric_limits::infinity(); + if (elapsed_ms > drift_limit) + ++entry.drift_strikes; + else + entry.drift_strikes = 0; + + const std::size_t required = std::max(1, settings.drift_required_samples); + if (entry.drift_strikes < required || entry.candidates.size() < 2) + return; + + entry.drift_detected = true; + initialize_revalidation(entry); + entry.revalidation_stable_index = stable_index; + add_sample(entry.revalidation_stable_samples, elapsed_ms, 2); + entry.revalidation_phase = RevalidationPhase::ChallengerA; + } + + static std::size_t next_warmup_index( + const Entry& entry, + const RouteSelectorSettings& settings) noexcept + { + const std::size_t required = settings.warmup_samples; + if (required == 0 || entry.candidates.empty()) + return invalid_index(); + std::size_t minimum_count = required; + for (const Measurement& measurement : entry.measurements) + minimum_count = std::min(minimum_count, measurement.warmups); + if (minimum_count >= required) + return invalid_index(); + const std::size_t count = entry.candidates.size(); + const std::size_t start = (entry.rotation_seed + minimum_count) % count; + for (std::size_t offset = 0; offset < count; ++offset) + { + const std::size_t index = (start + offset) % count; + if (entry.measurements[index].warmups == minimum_count) + return index; + } + return invalid_index(); + } + + static bool active_round_complete(const Entry& entry) noexcept + { + for (std::size_t index = 0; index < entry.active.size(); ++index) + { + if (entry.active[index] + && entry.measurements[index].sample_count < entry.learning_target_samples) + return false; + } + return true; + } + + static std::size_t next_learning_index(const Entry& entry) noexcept + { + if (entry.phase != Phase::Learning || entry.candidates.empty()) + return invalid_index(); + std::size_t minimum_count = std::numeric_limits::max(); + for (std::size_t index = 0; index < entry.active.size(); ++index) + if (entry.active[index]) + minimum_count = std::min(minimum_count, + entry.measurements[index].sample_count); + if (minimum_count == std::numeric_limits::max() + || minimum_count >= entry.learning_target_samples) + return invalid_index(); + const std::size_t count = entry.candidates.size(); + const std::size_t start = (entry.rotation_seed + minimum_count) % count; + for (std::size_t offset = 0; offset < count; ++offset) + { + const std::size_t index = (start + offset) % count; + if (entry.active[index] + && entry.measurements[index].sample_count == minimum_count) + return index; + } + return invalid_index(); + } + + static double equivalence_margin(double fastest_ms, + const RouteSelectorSettings& settings) noexcept + { + return std::max(std::max(0.0, settings.absolute_equivalence_ms), + fastest_ms * (std::max(1.0, settings.equivalence_ratio) - 1.0)); + } + + static double uncertainty_radius(const Measurement& measurement, + const RouteSelectorSettings& settings) noexcept + { + return std::max(std::max(0.0, settings.absolute_equivalence_ms), + 2.0 * mad(measurement)); + } + + static std::size_t fastest_index(const Entry& entry, + const std::vector& eligible) noexcept + { + std::size_t fastest = invalid_index(); + for (std::size_t index = 0; index < entry.measurements.size(); ++index) + { + if (!eligible[index] || entry.measurements[index].sample_count == 0) + continue; + if (fastest == invalid_index() + || median(entry.measurements[index]) < median(entry.measurements[fastest])) + fastest = index; + } + return fastest; + } + + static std::size_t preferred_equivalent_index( + const Entry& entry, + const std::vector& eligible, + std::size_t fastest, + const RouteSelectorSettings& settings) noexcept + { + const double fastest_ms = median(entry.measurements[fastest]); + const double margin = equivalence_margin(fastest_ms, settings); + std::size_t preferred = fastest; + for (std::size_t index = 0; index < entry.measurements.size(); ++index) + { + if (!eligible[index]) + continue; + const double allowance = margin + std::max( + uncertainty_radius(entry.measurements[fastest], settings), + uncertainty_radius(entry.measurements[index], settings)); + if (median(entry.measurements[index]) <= fastest_ms + allowance + && route_preference(entry.candidates[index]) + < route_preference(entry.candidates[preferred])) + preferred = index; + } + return preferred; + } + + static std::size_t runner_up_index(const Entry& entry, + std::size_t provisional) noexcept + { + std::size_t runner = invalid_index(); + for (std::size_t index = 0; index < entry.measurements.size(); ++index) + { + if (index == provisional || entry.measurements[index].sample_count == 0) + continue; + if (runner == invalid_index() + || median(entry.measurements[index]) < median(entry.measurements[runner])) + runner = index; + } + return runner; + } + + static void start_holdout_or_stabilize(Entry& entry, + const RouteSelectorSettings& settings) noexcept + { + const std::size_t fastest = fastest_index(entry, entry.active); + if (fastest == invalid_index()) + return; + entry.provisional_index = preferred_equivalent_index( + entry, entry.active, fastest, settings); + entry.runner_up_index = runner_up_index(entry, entry.provisional_index); + clear_holdouts(entry); + if (entry.runner_up_index == invalid_index() || settings.holdout_samples == 0) + { + entry.stable_route = entry.candidates[entry.provisional_index]; + entry.stable = true; + entry.phase = Phase::Stable; + entry.uses_since_revalidation = 0; + entry.current_revalidate_interval = normalized_initial_interval(settings); + } + else + { + entry.phase = Phase::Holdout; + } + } + + static void prepare_learning_state(Entry& entry, + const RouteSelectorSettings& settings) noexcept + { + if (entry.stable || entry.phase != Phase::Learning || !active_round_complete(entry)) + return; + + const std::size_t fastest = fastest_index(entry, entry.active); + if (fastest == invalid_index()) + return; + const double fastest_ms = median(entry.measurements[fastest]); + const double fastest_upper = fastest_ms + + uncertainty_radius(entry.measurements[fastest], settings); + const double margin = equivalence_margin(fastest_ms, settings); + bool uncertain = false; + std::size_t active_count = 0; + for (std::size_t index = 0; index < entry.active.size(); ++index) + { + if (!entry.active[index]) + continue; + if (index != fastest) + { + const double candidate_ms = median(entry.measurements[index]); + const double candidate_lower = std::max( + 0.0, candidate_ms - uncertainty_radius(entry.measurements[index], settings)); + if (candidate_lower > fastest_upper + margin) + entry.active[index] = false; + else if (candidate_ms > fastest_ms + margin) + uncertain = true; + } + if (entry.active[index]) + ++active_count; + } + + const std::size_t maximum_samples = normalized_window(settings); + if (uncertain && active_count > 1 + && entry.learning_target_samples < maximum_samples) + { + entry.learning_target_samples = std::min( + maximum_samples, entry.learning_target_samples + 2); + return; + } + start_holdout_or_stabilize(entry, settings); + } + + static std::size_t next_holdout_index( + const Entry& entry, + const RouteSelectorSettings& settings) noexcept + { + if (entry.phase != Phase::Holdout || settings.holdout_samples == 0) + return invalid_index(); + const std::size_t first = (entry.verification_failures % 2u) == 0u + ? entry.provisional_index : entry.runner_up_index; + const std::size_t second = first == entry.provisional_index + ? entry.runner_up_index : entry.provisional_index; + const std::size_t first_count = entry.holdouts[first].sample_count; + const std::size_t second_count = entry.holdouts[second].sample_count; + if (first_count < settings.holdout_samples + && first_count <= second_count) + return first; + if (second_count < settings.holdout_samples) + return second; + if (first_count < settings.holdout_samples) + return first; + return invalid_index(); + } + + static bool holdout_complete(const Entry& entry, + const RouteSelectorSettings& settings) noexcept + { + return entry.phase == Phase::Holdout + && entry.holdouts[entry.provisional_index].sample_count + >= settings.holdout_samples + && entry.holdouts[entry.runner_up_index].sample_count + >= settings.holdout_samples; + } + + static void merge_holdout(Measurement& target, + const Measurement& source, + std::size_t window) noexcept + { + for (std::size_t index = 0; index < source.sample_count; ++index) + add_sample(target, source.samples[index], window); + } + + static void finalize_holdout(Entry& entry, + const RouteSelectorSettings& settings) noexcept + { + if (!holdout_complete(entry, settings)) + return; + const Measurement& provisional = entry.holdouts[entry.provisional_index]; + const Measurement& runner = entry.holdouts[entry.runner_up_index]; + const double provisional_ms = median(provisional); + const double runner_ms = median(runner); + const double allowance = equivalence_margin(runner_ms, settings) + + std::max(uncertainty_radius(provisional, settings), + uncertainty_radius(runner, settings)); + if (provisional_ms <= runner_ms + allowance) + { + entry.stable_route = entry.candidates[entry.provisional_index]; + entry.stable = true; + entry.phase = Phase::Stable; + entry.uses_since_revalidation = 0; + entry.current_revalidate_interval = normalized_initial_interval(settings); + return; + } + + ++entry.verification_failures; + merge_holdout(entry.measurements[entry.provisional_index], provisional, + normalized_window(settings)); + merge_holdout(entry.measurements[entry.runner_up_index], runner, + normalized_window(settings)); + if (entry.verification_failures >= settings.maximum_verification_failures + || std::min(entry.measurements[entry.provisional_index].sample_count, + entry.measurements[entry.runner_up_index].sample_count) + >= normalized_window(settings)) + { + const double margin = equivalence_margin(runner_ms, settings); + std::size_t winner = runner_ms + margin < provisional_ms + ? entry.runner_up_index : entry.provisional_index; + if (std::abs(provisional_ms - runner_ms) <= margin + && route_preference(entry.candidates[entry.provisional_index]) + < route_preference(entry.candidates[entry.runner_up_index])) + winner = entry.provisional_index; + entry.stable_route = entry.candidates[winner]; + entry.stable = true; + entry.phase = Phase::Stable; + entry.uses_since_revalidation = 0; + entry.current_revalidate_interval = normalized_initial_interval(settings); + return; + } + + entry.phase = Phase::Learning; + entry.active.assign(entry.candidates.size(), false); + entry.active[entry.provisional_index] = true; + entry.active[entry.runner_up_index] = true; + const std::size_t current = std::min( + entry.measurements[entry.provisional_index].sample_count, + entry.measurements[entry.runner_up_index].sample_count); + entry.learning_target_samples = std::min( + normalized_window(settings), std::max(normalized_minimum(settings), current + 2)); + clear_holdouts(entry); + } + + static void choose_stable_from_training(Entry& entry, + const RouteSelectorSettings& settings, + bool preserve_revalidation_interval) noexcept + { + std::vector eligible(entry.candidates.size(), true); + const std::size_t fastest = fastest_index(entry, eligible); + const std::size_t preferred = preferred_equivalent_index( + entry, eligible, fastest, settings); + entry.stable_route = entry.candidates[preferred]; + entry.stable = true; + entry.phase = Phase::Stable; + entry.uses_since_revalidation = 0; + if (!preserve_revalidation_interval) + entry.current_revalidate_interval = normalized_initial_interval(settings); + } + + static std::size_t next_alternative(Entry& entry, std::size_t stable_index) noexcept + { + for (std::size_t offset = 0; offset < entry.candidates.size(); ++offset) + { + const std::size_t index = entry.next_revalidation_index++ % entry.candidates.size(); + if (index != stable_index) + return index; + } + return stable_index; + } + + static void make_room_locked(Shard& shard, std::size_t maximum_entries) + { + const std::size_t per_shard = std::max(1, maximum_entries / shard_count); + if (shard.entries.size() < per_shard) + return; + auto victim = shard.entries.end(); + for (auto iterator = shard.entries.begin(); iterator != shard.entries.end(); ++iterator) + { + if (victim == shard.entries.end() + || iterator->second.last_access < victim->second.last_access) + victim = iterator; + } + if (victim != shard.entries.end()) + shard.entries.erase(victim); + } +}; +} // namespace smart::vision::detail diff --git a/include/smart/vision/detail/threshold_kernel.hpp b/include/smart/vision/detail/threshold_kernel.hpp new file mode 100644 index 0000000..611f1b3 --- /dev/null +++ b/include/smart/vision/detail/threshold_kernel.hpp @@ -0,0 +1,187 @@ +#pragma once + +#include +#include + +namespace smart::vision::detail +{ +enum class ThresholdKernelKind +{ + Scalar, + SSE2, + AVX2 +}; + +ThresholdKernelKind selected_threshold_kernel() noexcept; +const char* threshold_kernel_name(ThresholdKernelKind kind) noexcept; +bool threshold_kernel_uses_explicit_simd() noexcept; + +void threshold_u8_contiguous_disjoint_binary(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept; +void threshold_u8_contiguous_disjoint_inverse(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept; +void threshold_u8_contiguous_in_place_binary(std::uint8_t* data, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept; +void threshold_u8_contiguous_in_place_inverse(std::uint8_t* data, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept; + +template +inline void threshold_u8_contiguous_disjoint(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + if constexpr (Inverse) + threshold_u8_contiguous_disjoint_inverse( + source, destination, count, threshold, maximum); + else + threshold_u8_contiguous_disjoint_binary( + source, destination, count, threshold, maximum); +} + +template +inline void threshold_u8_contiguous_in_place(std::uint8_t* data, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + if constexpr (Inverse) + threshold_u8_contiguous_in_place_inverse(data, count, threshold, maximum); + else + threshold_u8_contiguous_in_place_binary(data, count, threshold, maximum); +} + +template +inline void threshold_u8_rows_disjoint(const std::uint8_t* source, + std::size_t source_stride, + std::uint8_t* destination, + std::size_t destination_stride, + std::size_t width, + std::size_t row_begin, + std::size_t row_end, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + for (std::size_t row = row_begin; row < row_end; ++row) + { + threshold_u8_contiguous_disjoint( + source + row * source_stride, + destination + row * destination_stride, + width, + threshold, + maximum); + } +} + +template +inline void threshold_u8_rows_in_place(std::uint8_t* data, + std::size_t stride, + std::size_t width, + std::size_t row_begin, + std::size_t row_end, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + for (std::size_t row = row_begin; row < row_end; ++row) + { + threshold_u8_contiguous_in_place( + data + row * stride, width, threshold, maximum); + } +} + +template +inline void threshold_u8_range(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t begin, + std::size_t end, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + const std::size_t count = end - begin; + if (source == destination) + { + threshold_u8_contiguous_in_place( + destination + begin, count, threshold, maximum); + } + else + { + threshold_u8_contiguous_disjoint( + source + begin, destination + begin, count, threshold, maximum); + } +} + +template +inline void threshold_u8_rows(const std::uint8_t* source, + std::size_t source_stride, + std::uint8_t* destination, + std::size_t destination_stride, + std::size_t width, + std::size_t row_begin, + std::size_t row_end, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + if (source == destination) + { + threshold_u8_rows_in_place( + destination, destination_stride, width, row_begin, row_end, + threshold, maximum); + } + else + { + threshold_u8_rows_disjoint( + source, source_stride, destination, destination_stride, width, + row_begin, row_end, threshold, maximum); + } +} + +inline void threshold_u8_range(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t begin, + std::size_t end, + std::uint8_t threshold, + std::uint8_t maximum, + bool inverse) noexcept +{ + if (inverse) + threshold_u8_range(source, destination, begin, end, threshold, maximum); + else + threshold_u8_range(source, destination, begin, end, threshold, maximum); +} + +inline void threshold_u8_rows(const std::uint8_t* source, + std::size_t source_stride, + std::uint8_t* destination, + std::size_t destination_stride, + std::size_t width, + std::size_t row_begin, + std::size_t row_end, + std::uint8_t threshold, + std::uint8_t maximum, + bool inverse) noexcept +{ + if (inverse) + { + threshold_u8_rows(source, source_stride, destination, + destination_stride, width, row_begin, row_end, + threshold, maximum); + } + else + { + threshold_u8_rows(source, source_stride, destination, + destination_stride, width, row_begin, row_end, + threshold, maximum); + } +} +} // namespace smart::vision::detail diff --git a/include/smart/vision/execution_route.hpp b/include/smart/vision/execution_route.hpp new file mode 100644 index 0000000..986a095 --- /dev/null +++ b/include/smart/vision/execution_route.hpp @@ -0,0 +1,59 @@ +#pragma once + +#include + +namespace smart::vision +{ +enum class ExecutionRoute +{ + Auto, + NativeSequential, + NativeThreadPool, + NativeStaticThread, + NativeOneTbb, + OpenCV +}; + +inline const char* execution_route_name(ExecutionRoute route) noexcept +{ + switch (route) + { + case ExecutionRoute::Auto: + return "auto"; + case ExecutionRoute::NativeSequential: + return "native_sequential"; + case ExecutionRoute::NativeThreadPool: + return "native_thread_pool"; + case ExecutionRoute::NativeStaticThread: + return "native_static_thread"; + case ExecutionRoute::NativeOneTbb: + return "native_one_tbb"; + case ExecutionRoute::OpenCV: + return "opencv"; + } + return "unknown"; +} + +inline bool is_native_route(ExecutionRoute route) noexcept +{ + return route == ExecutionRoute::NativeSequential + || route == ExecutionRoute::NativeThreadPool + || route == ExecutionRoute::NativeStaticThread + || route == ExecutionRoute::NativeOneTbb; +} + +inline ExecutionEngineType native_execution_engine(ExecutionRoute route) noexcept +{ + switch (route) + { + case ExecutionRoute::NativeThreadPool: + return ExecutionEngineType::ThreadPool; + case ExecutionRoute::NativeStaticThread: + return ExecutionEngineType::StaticThread; + case ExecutionRoute::NativeOneTbb: + return ExecutionEngineType::OneTbb; + default: + return ExecutionEngineType::Auto; + } +} +} // namespace smart::vision diff --git a/include/smart/vision/image_view.hpp b/include/smart/vision/image_view.hpp new file mode 100644 index 0000000..8eb3a0e --- /dev/null +++ b/include/smart/vision/image_view.hpp @@ -0,0 +1,63 @@ +#pragma once + +#include +#include +#include + +namespace smart::vision +{ +template +struct ImageView +{ + using value_type = std::remove_const_t; + + T* data = nullptr; + std::size_t width = 0; + std::size_t height = 0; + std::size_t stride_bytes = 0; + std::size_t channels = 1; + + bool empty() const noexcept { return width == 0 || height == 0; } + + std::size_t row_bytes() const noexcept + { + return width * channels * sizeof(value_type); + } + + bool contiguous() const noexcept + { + return empty() || stride_bytes == row_bytes(); + } + + T* row(std::size_t y) const noexcept + { + auto* bytes = reinterpret_cast, + const std::uint8_t*, + std::uint8_t*>>(data); + return reinterpret_cast(bytes + y * stride_bytes); + } +}; + +template +ImageView make_image_view(T* data, + std::size_t width, + std::size_t height, + std::size_t stride_bytes, + std::size_t channels = 1) noexcept +{ + return ImageView{data, width, height, stride_bytes, channels}; +} + +template +ImageView make_contiguous_image_view(T* data, + std::size_t width, + std::size_t height, + std::size_t channels = 1) noexcept +{ + return ImageView{data, + width, + height, + width * channels * sizeof(std::remove_const_t), + channels}; +} +} // namespace smart::vision diff --git a/include/smart/vision/threshold.hpp b/include/smart/vision/threshold.hpp new file mode 100644 index 0000000..e3c5953 --- /dev/null +++ b/include/smart/vision/threshold.hpp @@ -0,0 +1,40 @@ +#pragma once + +#include +#include + +#include +#include +#include + +namespace smart::vision +{ +enum class ThresholdMode +{ + Binary, + BinaryInverse +}; + +struct ThresholdOptions +{ + std::uint8_t threshold = 127; + std::uint8_t maximum_value = 255; + ThresholdMode mode = ThresholdMode::Binary; +}; + +struct ExecutionPolicy +{ + ExecutionRoute route = ExecutionRoute::Auto; + std::size_t worker_budget = 0; +}; + +void threshold(ImageView source, + ImageView destination, + ThresholdOptions options = {}, + ExecutionPolicy policy = {}); + +bool opencv_available() noexcept; +std::string opencv_version(); +void refresh_provider_state() noexcept; +void clear_adaptive_route_cache() noexcept; +} // namespace smart::vision diff --git a/include/smart/vision/vision.hpp b/include/smart/vision/vision.hpp new file mode 100644 index 0000000..9af713a --- /dev/null +++ b/include/smart/vision/vision.hpp @@ -0,0 +1,6 @@ +#pragma once + +#include +#include +#include +#include diff --git a/scripts/README.md b/scripts/README.md index 4d4d1b1..41f7948 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -2,6 +2,22 @@ Root-level batch files are intentionally avoided. Scripts resolve the repository root from their own path and can be launched from any working directory unless their help text says otherwise. +## Complete v1.5 adaptive-route publication + +```bat +set "VCPKG_ROOT=D:\Tools\vcpkg" && scripts\validation\run_v15_adaptive_routes_release_validation.bat 31 +``` + +This opt-in workflow installs the `vision-opencv` vcpkg feature, builds the complete deterministic suite plus the v1.5 vision validation and benchmark, runs CTest, records cold/learning/deployment/steady-state/dispatch phases, validates exact output and route authentication, generates summary CSV, learning telemetry, Markdown, source evidence, and six SVG figures, then creates a timestamped ZIP under `validation/output/v1.5.0_adaptive_routes/`. + +Use `scripts\validation\run_v15_adaptive_routes_development.bat` for the seven-repetition development matrix. + +After a successful publication run, publish its accepted assets into the documentation tree with: + +```bat +py -3 tools\publish_v15_benchmark_docs.py validation\output\v1.5.0_adaptive_routes\publication_ +``` + ## Complete v1.4 algorithm validation ```bat @@ -10,31 +26,23 @@ set "VCPKG_ROOT=D:\Tools\vcpkg" && scripts\validation\run_v14_algorithm_release_ This configures an MSVC Release build with required oneTBB, builds the complete deterministic test suite and v1.4 benchmark target, runs CTest, then benchmarks all fourteen APIs in sequential, automatic, ThreadPool, StaticThread, and oneTBB modes. -## Complete v1.1 real-world validation +## Retained v1.1 real-world validation ```bat set "VCPKG_ROOT=D:\Tools\vcpkg" && scripts\benchmarks\run_real_world_complete.bat 31 ``` -This is the authoritative one-line release workflow. It builds the MSVC/NMake Release configuration, resolves vcpkg dependencies, runs CTest and all real-world benchmark modes, validates correctness and backend authenticity, and writes results to `validation/output/real_world/`. +This builds and validates the retained OpenCV, LZ4, BVH, and particle integration suite. ## Focused benchmark scripts | Script | Purpose | |---|---| -| `scripts/benchmarks/build_real_world_benchmarks.bat` | Build the real-world benchmark targets. | -| `scripts/benchmarks/run_real_world_development.bat` | Faster development matrix. | +| `scripts/benchmarks/build_real_world_benchmarks.bat` | Build the retained real-world benchmark targets. | +| `scripts/benchmarks/run_real_world_development.bat` | Faster retained real-world matrix. | | `scripts/benchmarks/run_real_world_integration.bat` | Run one integration/preset/mode/backend selection. | | `scripts/benchmarks/run_real_world_trace.bat` | Run diagnostic trace cases. | -| `scripts/benchmarks/run_real_world_backend_comparison.bat` | Compare supported backends. | +| `scripts/benchmarks/run_real_world_backend_comparison.bat` | Compare supported scheduler backends. | | `scripts/benchmarks/run_all_benchmarks.bat` | Run the historical v1.0 benchmark workflow. | -## Validation scripts - -`validation/` launchers exercise nested release gates, cross-backend comparisons, and the original v1 decision-quality workflow. - -## Example scripts - -`scripts/examples/` contains focused build-and-run launchers for contexts, budgets, backend contracts, helping, exceptions, deep nesting, mixed backends, and performance regression checks. These are engineering examples rather than the public benchmark report. - -See [benchmark reproduction](../docs/v1.1/benchmark-reproduction.md) for the documented release commands. +See [v1.5 benchmark reproduction](../docs/v1.5/benchmark-reproduction.md) for the current release workflow. diff --git a/scripts/validation/run_v15_adaptive_routes_development.bat b/scripts/validation/run_v15_adaptive_routes_development.bat new file mode 100644 index 0000000..72631b6 --- /dev/null +++ b/scripts/validation/run_v15_adaptive_routes_development.bat @@ -0,0 +1,5 @@ +@echo off +setlocal EnableExtensions +for %%I in ("%~dp0\..\..") do set "REPO_ROOT=%%~fI" +call "%REPO_ROOT%\scripts\validation\run_v15_adaptive_routes_release_validation.bat" 7 %1 +exit /b %errorlevel% diff --git a/scripts/validation/run_v15_adaptive_routes_release_validation.bat b/scripts/validation/run_v15_adaptive_routes_release_validation.bat new file mode 100644 index 0000000..323eda4 --- /dev/null +++ b/scripts/validation/run_v15_adaptive_routes_release_validation.bat @@ -0,0 +1,178 @@ +@echo off +setlocal EnableExtensions EnableDelayedExpansion + +for %%I in ("%~dp0\..\..") do set "REPO_ROOT=%%~fI" +cd /d "%REPO_ROOT%" + +where cmake >nul 2>nul || ( + echo ERROR: cmake was not found in PATH. + exit /b 2 +) +where ctest >nul 2>nul || ( + echo ERROR: ctest was not found in PATH. + exit /b 2 +) +where powershell >nul 2>nul || ( + echo ERROR: PowerShell was not found in PATH. + exit /b 2 +) + +set "PYTHON_COMMAND=" +where py >nul 2>nul && set "PYTHON_COMMAND=py -3" +if not defined PYTHON_COMMAND where python >nul 2>nul && set "PYTHON_COMMAND=python" +if not defined PYTHON_COMMAND ( + echo ERROR: neither the Python launcher "py" nor "python" was found in PATH. + exit /b 2 +) + +where cl >nul 2>nul +if errorlevel 1 call :initialize_msvc +if errorlevel 1 ( + echo ERROR: MSVC compiler "cl" was not found. + echo Install the Visual Studio 2022 Desktop development with C++ workload. + exit /b 2 +) + +if not defined VCPKG_ROOT ( + echo ERROR: VCPKG_ROOT is not defined. + echo Example: + echo set VCPKG_ROOT=D:\Tools\vcpkg + exit /b 2 +) +if not exist "%VCPKG_ROOT%\scripts\buildsystems\vcpkg.cmake" ( + echo ERROR: invalid VCPKG_ROOT: %VCPKG_ROOT% + exit /b 2 +) + +set "REPETITIONS=%~1" +if not defined REPETITIONS set "REPETITIONS=31" +for /f "delims=0123456789" %%A in ("%REPETITIONS%") do ( + echo ERROR: repetition count must be a positive odd integer. + exit /b 2 +) +set /a REPETITION_REMAINDER=%REPETITIONS% %% 2 +if %REPETITIONS% LEQ 0 ( + echo ERROR: repetition count must be positive. + exit /b 2 +) +if %REPETITION_REMAINDER% EQU 0 ( + echo ERROR: repetition count must be odd. + exit /b 2 +) + +set "REUSE=%~2" +set "BUILD_DIR=%REPO_ROOT%\build\v15_adaptive_routes_release" +set "TARGET=smartparallel_v150_adaptive_routes_benchmarks" +set "EXE=%BUILD_DIR%\benchmarks\v1.5.0\%TARGET%.exe" +for /f %%I in ('powershell -NoProfile -Command "Get-Date -Format yyyyMMdd_HHmmss"') do set "RUN_STAMP=%%I" +set "OUTPUT_DIR=%REPO_ROOT%\validation\output\v1.5.0_adaptive_routes\publication_%RUN_STAMP%" +set "RAW=%OUTPUT_DIR%\v1.5.0_adaptive_routes_raw.csv" +set "ARCHIVE=%OUTPUT_DIR%.zip" +set "BUILD_LOG=%OUTPUT_DIR%\v1.5.0_build_vectorization.log" + +if /I "%REUSE%"=="reuse" if exist "%EXE%" goto :test +rmdir /s /q "%BUILD_DIR%" 2>nul + +echo( +echo ==== [1/6] Configure SmartParallel v1.5 Adaptive Execution Routes ==== +cmake -S "%REPO_ROOT%" -B "%BUILD_DIR%" ^ + -G "NMake Makefiles" ^ + -DCMAKE_BUILD_TYPE=Release ^ + -DCMAKE_CXX_COMPILER=cl ^ + -DCMAKE_TOOLCHAIN_FILE="%VCPKG_ROOT%\scripts\buildsystems\vcpkg.cmake" ^ + -DVCPKG_TARGET_TRIPLET=x64-windows ^ + -DVCPKG_MANIFEST_FEATURES=vision-opencv ^ + -DSMARTPARALLEL_BUILD_VISION=ON ^ + -DSMARTPARALLEL_ENABLE_OPENCV_PROVIDER=ON ^ + -DSMARTPARALLEL_REQUIRE_OPENCV_PROVIDER=ON ^ + -DSMARTPARALLEL_BUILD_VALIDATION=ON ^ + -DSMARTPARALLEL_BUILD_V150_VISION_VALIDATION=ON ^ + -DSMARTPARALLEL_BUILD_V150_VISION_BENCHMARKS=ON ^ + -DSMARTPARALLEL_BUILD_BENCHMARKS=OFF ^ + -DSMARTPARALLEL_ENABLE_TBB=ON ^ + -DSMARTPARALLEL_REQUIRE_TBB=ON ^ + -DSMARTPARALLEL_INSTALL=ON +if errorlevel 1 goto :fail + +echo( +echo ==== [2/6] Build library, tests, package targets, and benchmark ==== +if not exist "%OUTPUT_DIR%" mkdir "%OUTPUT_DIR%" >nul 2>nul +cmake --build "%BUILD_DIR%" > "%BUILD_LOG%" 2>&1 +set "BUILD_STATUS=!ERRORLEVEL!" +type "%BUILD_LOG%" +if not "!BUILD_STATUS!"=="0" goto :fail + +:test +echo( +echo ==== [3/6] Run complete deterministic CTest suite ==== +ctest --test-dir "%BUILD_DIR%" -C Release --output-on-failure --parallel 2 +if errorlevel 1 goto :fail + +echo( +echo ==== [4/6] Run v1.5 publication benchmark matrix ==== +if not exist "%EXE%" ( + echo ERROR: benchmark executable was not found: + echo %EXE% + goto :fail +) +if not exist "%OUTPUT_DIR%" mkdir "%OUTPUT_DIR%" >nul 2>nul +"%EXE%" "%RAW%" "%REPETITIONS%" +if errorlevel 1 goto :fail +if not exist "%RAW%" ( + echo ERROR: raw benchmark CSV was not generated. + goto :fail +) + +echo( +echo ==== [5/6] Validate raw data and generate report/graphs ==== +%PYTHON_COMMAND% "%REPO_ROOT%\tools\analyze_v15_adaptive_routes.py" "%RAW%" "%OUTPUT_DIR%" +if errorlevel 1 goto :fail +%PYTHON_COMMAND% "%REPO_ROOT%\tools\generate_v15_benchmark_plots.py" ^ + "%OUTPUT_DIR%\v1.5.0_adaptive_routes.csv" ^ + "%RAW%" ^ + "%OUTPUT_DIR%\v1.5.0_adaptive_routes_learning.csv" ^ + "%OUTPUT_DIR%" +if errorlevel 1 goto :fail +if not exist "%OUTPUT_DIR%\v1.5.0_adaptive_routes.csv" goto :missing_analysis +if not exist "%OUTPUT_DIR%\v1.5.0_adaptive_routes_report.md" goto :missing_analysis +if not exist "%OUTPUT_DIR%\v1.5.0_automatic_speedup.svg" goto :missing_analysis +if not exist "%OUTPUT_DIR%\v1.5.0_route_selection_regret.svg" goto :missing_analysis +if not exist "%OUTPUT_DIR%\v1.5.0_native_kernel_vs_oracle.svg" goto :missing_analysis +if not exist "%OUTPUT_DIR%\v1.5.0_dispatch_overhead.svg" goto :missing_analysis +if not exist "%OUTPUT_DIR%\v1.5.0_adaptive_route_map.svg" goto :missing_analysis + +echo( +echo ==== [6/6] Package publication artifacts ==== +powershell -NoProfile -ExecutionPolicy Bypass -Command ^ + "Compress-Archive -Path '%OUTPUT_DIR%\*' -DestinationPath '%ARCHIVE%' -Force" +if errorlevel 1 goto :fail + +echo( +echo ============================================================ +echo SMARTPARALLEL V1.5 ADAPTIVE ROUTES VALIDATION PASSED +echo Raw samples: %RAW% +echo Summary: %OUTPUT_DIR%\v1.5.0_adaptive_routes.csv +echo Report: %OUTPUT_DIR%\v1.5.0_adaptive_routes_report.md +echo Shareable archive: %ARCHIVE% +echo ============================================================ +exit /b 0 + +:missing_analysis +echo ERROR: analysis outputs were not generated. +goto :fail + +:initialize_msvc +set "VSWHERE=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" +if not exist "%VSWHERE%" exit /b 2 +set "VS_INSTALLATION=" +for /f "usebackq tokens=*" %%I in (`"%VSWHERE%" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do set "VS_INSTALLATION=%%I" +if not defined VS_INSTALLATION exit /b 2 +call "%VS_INSTALLATION%\Common7\Tools\VsDevCmd.bat" -arch=x64 -host_arch=x64 >nul +where cl >nul 2>nul || exit /b 2 +exit /b 0 + +:fail +echo( +echo SmartParallel v1.5 Adaptive Execution Routes validation failed. +echo Review the first error above. +exit /b 1 diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 2f2605f..5263b52 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -226,3 +226,34 @@ if(SMARTPARALLEL_BUILD_V140_ALGORITHM_VALIDATION) PROPERTIES TIMEOUT 120 ) endif() + +if(SMARTPARALLEL_BUILD_V150_VISION_VALIDATION) + if(NOT TARGET smart_parallel_vision) + message(FATAL_ERROR + "SMARTPARALLEL_BUILD_V150_VISION_VALIDATION requires SMARTPARALLEL_BUILD_VISION=ON") + endif() + add_executable( + smartparallel_v150_vision_adaptive_routes_validation + v1/vision_adaptive_routes_validation.cpp + v1/threshold_vectorization_probe.cpp + ) + if(MSVC) + set_source_files_properties( + v1/threshold_vectorization_probe.cpp + PROPERTIES COMPILE_OPTIONS "/Qvec-report:2" + ) + endif() + target_link_libraries( + smartparallel_v150_vision_adaptive_routes_validation + PRIVATE SmartParallel::vision + ) + smartparallel_copy_tbb_runtime(smartparallel_v150_vision_adaptive_routes_validation) + add_test( + NAME smartparallel_v150_vision_adaptive_routes_validation + COMMAND smartparallel_v150_vision_adaptive_routes_validation + ) + set_tests_properties( + smartparallel_v150_vision_adaptive_routes_validation + PROPERTIES TIMEOUT 120 + ) +endif() diff --git a/tests/package-consumer-vision/CMakeLists.txt b/tests/package-consumer-vision/CMakeLists.txt new file mode 100644 index 0000000..13f4fa0 --- /dev/null +++ b/tests/package-consumer-vision/CMakeLists.txt @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 3.20) +project(SmartParallelVisionPackageConsumer LANGUAGES CXX) + +find_package(SmartParallel CONFIG REQUIRED) +find_package(SmartParallelVision CONFIG REQUIRED) + +add_executable(smartparallel_vision_package_consumer main.cpp) +target_compile_features(smartparallel_vision_package_consumer PRIVATE cxx_std_17) +target_link_libraries(smartparallel_vision_package_consumer PRIVATE SmartParallel::vision) + + +enable_testing() +add_test( + NAME smartparallel_vision_package_consumer + COMMAND smartparallel_vision_package_consumer +) diff --git a/tests/package-consumer-vision/main.cpp b/tests/package-consumer-vision/main.cpp new file mode 100644 index 0000000..f6628b0 --- /dev/null +++ b/tests/package-consumer-vision/main.cpp @@ -0,0 +1,17 @@ +#include + +#include +#include + +int main() +{ + const std::array source{0, 127, 128, 255}; + std::array destination{}; + smart::vision::threshold( + smart::vision::make_contiguous_image_view( + static_cast(source.data()), source.size(), 1), + smart::vision::make_contiguous_image_view(destination.data(), destination.size(), 1), + {127, 255, smart::vision::ThresholdMode::Binary}, + {smart::vision::ExecutionRoute::NativeSequential, 1}); + return destination == std::array{0, 0, 255, 255} ? 0 : 1; +} diff --git a/tests/package-consumer/CMakeLists.txt b/tests/package-consumer/CMakeLists.txt index 1fd937c..fca6299 100644 --- a/tests/package-consumer/CMakeLists.txt +++ b/tests/package-consumer/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.20) project(SmartParallelPackageConsumer LANGUAGES CXX) -find_package(SmartParallel 1.4 CONFIG REQUIRED) +find_package(SmartParallel 1.5 CONFIG REQUIRED) add_executable(smartparallel_package_consumer main.cpp) target_compile_features(smartparallel_package_consumer PRIVATE cxx_std_17) diff --git a/tests/package-consumer/main.cpp b/tests/package-consumer/main.cpp index 66bd0fa..fe5c2de 100644 --- a/tests/package-consumer/main.cpp +++ b/tests/package-consumer/main.cpp @@ -11,7 +11,7 @@ int main() { static_assert(SMARTPARALLEL_VERSION_MAJOR == 1, "unexpected major version"); - static_assert(SMARTPARALLEL_VERSION_MINOR == 4, "unexpected minor version"); + static_assert(SMARTPARALLEL_VERSION_MINOR == 5, "unexpected minor version"); const smart::HardwareCharacteristics hardware = smart::hardware_characteristics(); if (hardware.logical_threads == 0 || hardware.physical_cores == 0 diff --git a/tests/v1/threshold_vectorization_probe.cpp b/tests/v1/threshold_vectorization_probe.cpp new file mode 100644 index 0000000..436b2d9 --- /dev/null +++ b/tests/v1/threshold_vectorization_probe.cpp @@ -0,0 +1,59 @@ +#include + +#include +#include + +#if defined(_MSC_VER) +#define SMARTPARALLEL_NOINLINE __declspec(noinline) +#elif defined(__GNUC__) || defined(__clang__) +#define SMARTPARALLEL_NOINLINE __attribute__((noinline)) +#else +#define SMARTPARALLEL_NOINLINE +#endif + +namespace smartparallel_vectorization_probe +{ +SMARTPARALLEL_NOINLINE void disjoint_binary(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count) noexcept +{ + smart::vision::detail::threshold_u8_contiguous_disjoint( + source, destination, count, 127, 255); +} + +SMARTPARALLEL_NOINLINE void disjoint_inverse(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count) noexcept +{ + smart::vision::detail::threshold_u8_contiguous_disjoint( + source, destination, count, 127, 255); +} + +SMARTPARALLEL_NOINLINE void in_place_binary(std::uint8_t* data, + std::size_t count) noexcept +{ + smart::vision::detail::threshold_u8_contiguous_in_place( + data, count, 127, 255); +} +SMARTPARALLEL_NOINLINE void branchless_multiply_binary( + const std::uint8_t* source, std::uint8_t* destination, std::size_t count) noexcept +{ + for (std::size_t index = 0; index < count; ++index) + destination[index] = static_cast( + static_cast(source[index] > 127) * 255u); +} + +SMARTPARALLEL_NOINLINE void branchless_mask_binary( + const std::uint8_t* source, std::uint8_t* destination, std::size_t count) noexcept +{ + for (std::size_t index = 0; index < count; ++index) + { + const unsigned selected = static_cast(source[index] > 127); + const unsigned mask = 0u - selected; + destination[index] = static_cast(255u & mask); + } +} + +} // namespace smartparallel_vectorization_probe + +#undef SMARTPARALLEL_NOINLINE diff --git a/tests/v1/vision_adaptive_routes_validation.cpp b/tests/v1/vision_adaptive_routes_validation.cpp new file mode 100644 index 0000000..204fd32 --- /dev/null +++ b/tests/v1/vision_adaptive_routes_validation.cpp @@ -0,0 +1,1102 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +using smart::vision::ExecutionRoute; + +class ConfigGuard +{ + public: + ConfigGuard() + : saved_(smart::global_config()) + { + } + + ~ConfigGuard() + { + smart::global_config() = saved_; + smart::vision::clear_adaptive_route_cache(); + } + + private: + smart::Config saved_; +}; + +void require(bool condition, const char* message) +{ + if (!condition) + throw std::runtime_error(message); +} + +std::vector reference_threshold(const std::vector& source, + smart::vision::ThresholdOptions options) +{ + std::vector output(source.size()); + for (std::size_t index = 0; index < source.size(); ++index) + { + const bool above = source[index] > options.threshold; + output[index] = options.mode == smart::vision::ThresholdMode::Binary + ? (above ? options.maximum_value : std::uint8_t{0}) + : (above ? std::uint8_t{0} : options.maximum_value); + } + return output; +} + + +void validate_native_kernel_dispatch() +{ + using smart::vision::detail::ThresholdKernelKind; + const ThresholdKernelKind kind = smart::vision::detail::selected_threshold_kernel(); + const char* name = smart::vision::detail::threshold_kernel_name(kind); + require(name != nullptr && name[0] != '\0', + "native threshold kernel did not report an identity"); +#if defined(_M_X64) || defined(__x86_64__) + require(smart::vision::detail::threshold_kernel_uses_explicit_simd(), + "x86-64 validation requires an authenticated SSE2 or AVX2 kernel"); +#endif + std::cout << "SmartParallel native threshold kernel: " << name << '\n'; +} + +void validate_native_kernel_shapes() +{ + constexpr std::size_t width = 37; + constexpr std::size_t height = 11; + constexpr std::size_t stride = 48; + const smart::vision::ThresholdOptions binary{ + 100, 211, smart::vision::ThresholdMode::Binary}; + const smart::vision::ThresholdOptions inverse{ + 100, 211, smart::vision::ThresholdMode::BinaryInverse}; + + std::vector source(stride * height, 73); + for (std::size_t row = 0; row < height; ++row) + for (std::size_t column = 0; column < width; ++column) + source[row * stride + column] = static_cast( + (row * 29u + column * 17u) & 0xffu); + + std::vector contiguous_source(width * height); + for (std::size_t row = 0; row < height; ++row) + std::copy_n(source.data() + row * stride, + width, + contiguous_source.data() + row * width); + + for (const auto options : {binary, inverse}) + { + const bool is_inverse = options.mode == smart::vision::ThresholdMode::BinaryInverse; + const auto contiguous_expected = reference_threshold(contiguous_source, options); + + std::vector contiguous_output(contiguous_source.size(), 9); + if (is_inverse) + { + smart::vision::detail::threshold_u8_contiguous_disjoint( + contiguous_source.data(), + contiguous_output.data(), + contiguous_output.size(), + options.threshold, + options.maximum_value); + } + else + { + smart::vision::detail::threshold_u8_contiguous_disjoint( + contiguous_source.data(), + contiguous_output.data(), + contiguous_output.size(), + options.threshold, + options.maximum_value); + } + require(contiguous_output == contiguous_expected, + "disjoint contiguous native kernel produced incorrect output"); + + std::vector in_place = contiguous_source; + if (is_inverse) + { + smart::vision::detail::threshold_u8_contiguous_in_place( + in_place.data(), in_place.size(), options.threshold, options.maximum_value); + } + else + { + smart::vision::detail::threshold_u8_contiguous_in_place( + in_place.data(), in_place.size(), options.threshold, options.maximum_value); + } + require(in_place == contiguous_expected, + "in-place contiguous native kernel produced incorrect output"); + + std::vector strided_output(stride * height, 0xa5); + if (is_inverse) + { + smart::vision::detail::threshold_u8_rows_disjoint( + source.data(), stride, strided_output.data(), stride, width, + 0, height, options.threshold, options.maximum_value); + } + else + { + smart::vision::detail::threshold_u8_rows_disjoint( + source.data(), stride, strided_output.data(), stride, width, + 0, height, options.threshold, options.maximum_value); + } + for (std::size_t row = 0; row < height; ++row) + { + for (std::size_t column = 0; column < width; ++column) + { + const bool above = source[row * stride + column] > options.threshold; + const std::uint8_t expected = is_inverse + ? (above ? std::uint8_t{0} : options.maximum_value) + : (above ? options.maximum_value : std::uint8_t{0}); + require(strided_output[row * stride + column] == expected, + "disjoint strided native kernel produced incorrect output"); + } + for (std::size_t column = width; column < stride; ++column) + { + require(strided_output[row * stride + column] == 0xa5, + "disjoint strided kernel modified row padding"); + } + } + + std::vector strided_in_place = source; + if (is_inverse) + { + smart::vision::detail::threshold_u8_rows_in_place( + strided_in_place.data(), stride, width, 0, height, + options.threshold, options.maximum_value); + } + else + { + smart::vision::detail::threshold_u8_rows_in_place( + strided_in_place.data(), stride, width, 0, height, + options.threshold, options.maximum_value); + } + for (std::size_t row = 0; row < height; ++row) + { + for (std::size_t column = 0; column < width; ++column) + require(strided_in_place[row * stride + column] + == strided_output[row * stride + column], + "in-place strided native kernel produced incorrect output"); + for (std::size_t column = width; column < stride; ++column) + require(strided_in_place[row * stride + column] + == source[row * stride + column], + "in-place strided kernel modified row padding"); + } + } +} + +void validate_native_kernel_edge_values() +{ + std::vector source(513); + for (std::size_t index = 0; index < source.size(); ++index) + source[index] = static_cast(index & 0xffu); + + for (const std::uint8_t threshold : {std::uint8_t{0}, std::uint8_t{1}, + std::uint8_t{127}, std::uint8_t{254}, + std::uint8_t{255}}) + { + for (const std::uint8_t maximum : {std::uint8_t{0}, std::uint8_t{1}, + std::uint8_t{211}, std::uint8_t{255}}) + { + for (const auto mode : {smart::vision::ThresholdMode::Binary, + smart::vision::ThresholdMode::BinaryInverse}) + { + const smart::vision::ThresholdOptions options{threshold, maximum, mode}; + const auto expected = reference_threshold(source, options); + std::vector output(source.size(), 17); + if (mode == smart::vision::ThresholdMode::BinaryInverse) + { + smart::vision::detail::threshold_u8_contiguous_disjoint( + source.data(), output.data(), output.size(), threshold, maximum); + } + else + { + smart::vision::detail::threshold_u8_contiguous_disjoint( + source.data(), output.data(), output.size(), threshold, maximum); + } + require(output == expected, + "native SIMD threshold failed an edge-value disjoint case"); + + std::vector in_place = source; + if (mode == smart::vision::ThresholdMode::BinaryInverse) + { + smart::vision::detail::threshold_u8_contiguous_in_place( + in_place.data(), in_place.size(), threshold, maximum); + } + else + { + smart::vision::detail::threshold_u8_contiguous_in_place( + in_place.data(), in_place.size(), threshold, maximum); + } + require(in_place == expected, + "native SIMD threshold failed an edge-value in-place case"); + } + } + } +} + +void validate_selector_learning() +{ + using namespace smart::vision::detail; + AdaptiveRouteSelector selector; + RouteSelectorSettings settings; + settings.equivalence_ratio = 1.05; + settings.warmup_samples = 1; + settings.minimum_samples = 5; + settings.sample_window = 9; + settings.initial_revalidate_interval = 100; + settings.revalidate_interval = 100; + + RouteProfileKey key; + key.operation = 1; + key.pixel_bucket = 1024; + const std::vector candidates{ + ExecutionRoute::NativeSequential, + ExecutionRoute::OpenCV, + ExecutionRoute::NativeThreadPool}; + + std::size_t sequential_samples = 0; + std::size_t opencv_samples = 0; + std::size_t thread_pool_samples = 0; + bool reached_stable = false; + for (std::size_t invocation = 0; invocation < 64; ++invocation) + { + const auto selection = selector.select(key, candidates, settings); + if (!selection.probe) + { + require(selection.stable && selection.route == ExecutionRoute::OpenCV, + "median selector did not retain the fastest route"); + reached_stable = true; + break; + } + + double elapsed = 1'000.0; // Priming samples must not influence ranking. + if (!selection.warmup) + { + switch (selection.route) + { + case ExecutionRoute::NativeSequential: + elapsed = ++sequential_samples == 1 ? 100.0 : 10.0; + break; + case ExecutionRoute::OpenCV: + elapsed = ++opencv_samples == 1 ? 50.0 : 5.0; + break; + case ExecutionRoute::NativeThreadPool: + elapsed = ++thread_pool_samples == 1 ? 80.0 : 8.0; + break; + default: + throw std::runtime_error("unexpected selector candidate"); + } + } + selector.complete(selection, elapsed, settings); + } + require(reached_stable, "median selector did not finish its learning phase"); + + RouteMeasurementSnapshot snapshot; + require(selector.snapshot(key, snapshot), "selector snapshot was unavailable"); + require(snapshot.stable_route == ExecutionRoute::OpenCV, + "selector snapshot did not report OpenCV as the learned route"); + require(snapshot.routes.size() == 3, "selector snapshot lost candidates"); + for (std::size_t index = 0; index < snapshot.routes.size(); ++index) + { + require(snapshot.warmups[index] == 1, + "selector did not prime every route exactly once"); + require(snapshot.samples[index] == 5, + "selector did not collect five measured samples per route"); + } + require(snapshot.elapsed_ms[0] == 10.0 && snapshot.elapsed_ms[1] == 5.0 + && snapshot.elapsed_ms[2] == 8.0, + "selector did not rank routes by observed median"); + + // Revalidation uses a bounded recent window and can promote a changed winner. + AdaptiveRouteSelector revalidation_selector; + RouteSelectorSettings revalidation_settings; + revalidation_settings.warmup_samples = 0; + revalidation_settings.minimum_samples = 1; + revalidation_settings.sample_window = 1; + revalidation_settings.holdout_samples = 0; + revalidation_settings.initial_revalidate_interval = 2; + revalidation_settings.revalidate_interval = 8; + RouteProfileKey revalidation_key; + revalidation_key.operation = 2; + const std::vector revalidation_candidates{ + ExecutionRoute::NativeSequential, + ExecutionRoute::OpenCV}; + + for (std::size_t invocation = 0; invocation < 2; ++invocation) + { + const auto selection = revalidation_selector.select( + revalidation_key, revalidation_candidates, revalidation_settings); + require(selection.probe, "initial revalidation profile was not measured"); + revalidation_selector.complete( + selection, + selection.route == ExecutionRoute::OpenCV ? 5.0 : 10.0, + revalidation_settings); + } + auto selection = revalidation_selector.select( + revalidation_key, revalidation_candidates, revalidation_settings); + require(selection.stable && selection.route == ExecutionRoute::OpenCV, + "initial revalidation profile selected the wrong route"); + selection = revalidation_selector.select( + revalidation_key, revalidation_candidates, revalidation_settings); + require(selection.probe && selection.revalidation + && selection.revalidation_stable_sample + && selection.revalidation_stage == 1 + && selection.route == ExecutionRoute::OpenCV, + "selector did not begin current-context revalidation with the stable route"); + revalidation_selector.complete(selection, 20.0, revalidation_settings); + for (std::uint8_t stage : {std::uint8_t{2}, std::uint8_t{3}}) + { + selection = revalidation_selector.select( + revalidation_key, revalidation_candidates, revalidation_settings); + require(selection.probe && selection.revalidation + && !selection.revalidation_stable_sample + && selection.revalidation_stage == stage + && selection.route == ExecutionRoute::NativeSequential, + "selector did not collect paired challenger evidence"); + revalidation_selector.complete(selection, 2.0, revalidation_settings); + } + selection = revalidation_selector.select( + revalidation_key, revalidation_candidates, revalidation_settings); + require(selection.probe && selection.revalidation + && selection.revalidation_stable_sample + && selection.revalidation_stage == 4 + && selection.route == ExecutionRoute::OpenCV, + "selector did not close current-context revalidation with the stable route"); + revalidation_selector.complete(selection, 20.0, revalidation_settings); + selection = revalidation_selector.select( + revalidation_key, revalidation_candidates, revalidation_settings); + require(selection.stable && selection.route == ExecutionRoute::NativeSequential, + "selector did not promote the faster current-context route"); + + RouteProfileKey other = key; + other.operation = 3; + selection = selector.select(other, candidates, settings); + require(selection.probe, + "selector incorrectly shared decisions across operations"); +} + + +void validate_selector_decisive_revalidation() +{ + using namespace smart::vision::detail; + AdaptiveRouteSelector selector; + RouteSelectorSettings settings; + settings.warmup_samples = 0; + settings.minimum_samples = 5; + settings.sample_window = 9; + settings.holdout_samples = 0; + settings.initial_revalidate_interval = 2; + settings.revalidate_interval = 8; + + RouteProfileKey key; + key.operation = 44; + const std::vector candidates{ + ExecutionRoute::NativeSequential, + ExecutionRoute::OpenCV}; + + for (std::size_t invocation = 0; invocation < 10; ++invocation) + { + const auto selection = selector.select(key, candidates, settings); + require(selection.probe && !selection.revalidation, + "robust selector did not collect its initial profile"); + selector.complete(selection, + selection.route == ExecutionRoute::OpenCV ? 5.0 : 10.0, + settings); + } + + auto selection = selector.select(key, candidates, settings); + require(selection.stable && !selection.probe + && selection.route == ExecutionRoute::OpenCV, + "robust selector did not stabilize on OpenCV"); + selection = selector.select(key, candidates, settings); + require(selection.probe && selection.revalidation + && selection.revalidation_stage == 1 + && selection.route == ExecutionRoute::OpenCV, + "robust selector did not begin paired revalidation on the stable route"); + selector.complete(selection, 20.0, settings); + selection = selector.select(key, candidates, settings); + require(selection.probe && selection.revalidation + && selection.revalidation_stage == 2 + && selection.route == ExecutionRoute::NativeSequential, + "robust selector did not collect challenger A"); + selector.complete(selection, 2.0, settings); + selection = selector.select(key, candidates, settings); + require(selection.probe && selection.revalidation + && selection.revalidation_stage == 3 + && selection.route == ExecutionRoute::NativeSequential, + "robust selector did not collect challenger B"); + selector.complete(selection, 2.1, settings); + selection = selector.select(key, candidates, settings); + require(selection.probe && selection.revalidation + && selection.revalidation_stage == 4 + && selection.route == ExecutionRoute::OpenCV, + "robust selector did not collect stable B"); + selector.complete(selection, 20.5, settings); + selection = selector.select(key, candidates, settings); + require(selection.stable && selection.route == ExecutionRoute::NativeSequential, + "paired revalidation did not promote the current winner"); +} + + +void validate_selector_robust_learning() +{ + using namespace smart::vision::detail; + + auto drive = [](AdaptiveRouteSelector& selector, + const RouteProfileKey& key, + const std::vector& candidates, + const RouteSelectorSettings& settings, + const std::function& timing) + { + std::size_t invocation = 0; + for (; invocation < 160; ++invocation) + { + const RouteSelection selection = selector.select(key, candidates, settings); + if (!selection.probe) + { + require(selection.stable, "robust selector returned an unstabilized fallback"); + return selection.route; + } + selector.complete(selection, timing(selection, invocation), settings); + } + throw std::runtime_error("robust selector did not converge within 160 calls"); + }; + + RouteSelectorSettings settings; + settings.warmup_samples = 0; + settings.minimum_samples = 3; + settings.sample_window = 11; + settings.holdout_samples = 2; + settings.maximum_verification_failures = 2; + settings.initial_revalidate_interval = 1000; + settings.revalidate_interval = 1000; + + // A single exceptionally fast external-provider sample must not beat the + // consistently faster native route. + { + AdaptiveRouteSelector selector; + RouteProfileKey key; + key.operation = 501; + const std::vector candidates{ + ExecutionRoute::NativeSequential, + ExecutionRoute::OpenCV, + ExecutionRoute::NativeThreadPool}; + std::array training_counts{}; + std::array holdout_counts{}; + const auto winner = drive(selector, key, candidates, settings, + [&](const RouteSelection& selection, std::size_t) + { + const std::size_t index = selection.route == ExecutionRoute::NativeSequential + ? 0 : selection.route == ExecutionRoute::OpenCV ? 1 : 2; + if (selection.holdout) + { + static const double values[3][2]{{80.0, 81.0}, {142.0, 145.0}, {101.0, 102.0}}; + return values[index][holdout_counts[index]++ % 2]; + } + static const double values[3][3]{{80.0, 79.0, 81.0}, {30.0, 150.0, 145.0}, {100.0, 101.0, 99.0}}; + return values[index][training_counts[index]++ % 3]; + }); + require(winner == ExecutionRoute::NativeSequential, + "outlier resistance selected the transiently fast OpenCV route"); + } + + // A provisional training winner that loses an independent holdout must be + // reopened and replaced after bounded additional evidence. + { + AdaptiveRouteSelector selector; + RouteProfileKey key; + key.operation = 502; + const std::vector candidates{ + ExecutionRoute::NativeSequential, ExecutionRoute::OpenCV}; + std::array training_counts{}; + std::array holdout_counts{}; + const auto winner = drive(selector, key, candidates, settings, + [&](const RouteSelection& selection, std::size_t) + { + const std::size_t index = selection.route == ExecutionRoute::NativeSequential ? 0 : 1; + if (selection.holdout) + { + // First holdout reverses the training winner. Subsequent + // holdouts continue to confirm Native Sequential. + static const double native_values[]{70.0, 72.0, 70.0, 71.0, 70.0, 71.0}; + static const double opencv_values[]{150.0, 152.0, 150.0, 151.0, 150.0, 151.0}; + return index == 0 + ? native_values[holdout_counts[index]++ % 6] + : opencv_values[holdout_counts[index]++ % 6]; + } + static const double initial[2][7]{ + {90.0, 91.0, 92.0, 70.0, 71.0, 70.0, 71.0}, + {80.0, 81.0, 82.0, 150.0, 151.0, 150.0, 151.0}}; + const std::size_t ordinal = std::min(training_counts[index]++, 6); + return initial[index][ordinal]; + }); + require(winner == ExecutionRoute::NativeSequential, + "holdout reversal did not replace the provisional OpenCV winner"); + RouteMeasurementSnapshot snapshot; + require(selector.snapshot(key, snapshot), "holdout reversal snapshot missing"); + require(snapshot.verification_failures >= 1, + "holdout reversal was not recorded in selector telemetry"); + } + + // Statistically equivalent candidates resolve by semantic preference, not + // input vector order. + for (bool reverse : {false, true}) + { + AdaptiveRouteSelector selector; + RouteProfileKey key; + key.operation = reverse ? 504 : 503; + std::vector candidates{ + ExecutionRoute::NativeSequential, + ExecutionRoute::NativeThreadPool, + ExecutionRoute::OpenCV}; + if (reverse) + std::reverse(candidates.begin(), candidates.end()); + std::array counts{}; + const auto winner = drive(selector, key, candidates, settings, + [&](const RouteSelection& selection, std::size_t) + { + const std::size_t route = static_cast(selection.route); + const double base = selection.route == ExecutionRoute::NativeSequential ? 100.0 + : selection.route == ExecutionRoute::NativeThreadPool ? 98.0 : 99.0; + return base + static_cast((counts[route]++) % 3) * 0.1; + }); + require(winner == ExecutionRoute::NativeSequential, + "equivalent routes did not resolve to Native Sequential"); + } +} + + +void validate_selector_distribution_shift() +{ + using namespace smart::vision::detail; + AdaptiveRouteSelector selector; + RouteSelectorSettings settings; + settings.warmup_samples = 0; + settings.minimum_samples = 3; + settings.sample_window = 7; + settings.holdout_samples = 0; + settings.initial_revalidate_interval = 1000; + settings.revalidate_interval = 1000; + settings.drift_required_samples = 2; + settings.drift_ratio = 1.25; + settings.drift_absolute_ms = 1.0; + + RouteProfileKey key; + key.operation = 601; + const std::vector candidates{ + ExecutionRoute::NativeSequential, ExecutionRoute::OpenCV}; + + // Initial regime: OpenCV is decisively faster. + for (std::size_t invocation = 0; invocation < 6; ++invocation) + { + const auto selection = selector.select(key, candidates, settings); + require(selection.probe && !selection.revalidation, + "distribution-shift profile did not collect initial evidence"); + selector.complete(selection, + selection.route == ExecutionRoute::OpenCV ? 30.0 : 80.0, + settings); + } + auto selection = selector.select(key, candidates, settings); + require(selection.stable && selection.route == ExecutionRoute::OpenCV, + "distribution-shift profile did not initially learn OpenCV"); + + // New regime: sparse stable-route sentinels observe a major slowdown. + settings.force_stable_sample = true; + for (std::size_t sentinel = 0; sentinel < 2; ++sentinel) + { + selection = selector.select(key, candidates, settings); + require(selection.probe && selection.drift_sample + && selection.route == ExecutionRoute::OpenCV, + "distribution-shift sentinel did not time the stable route"); + selector.complete(selection, 120.0, settings); + } + settings.force_stable_sample = false; + + RouteMeasurementSnapshot snapshot; + require(selector.snapshot(key, snapshot), + "distribution-shift telemetry was unavailable"); + require(snapshot.drift_detected && snapshot.revalidation_active, + "distribution shift did not trigger current-context revalidation"); + + // Stable A came from the second sentinel. Complete challenger A/B and stable B. + for (std::uint8_t stage : {std::uint8_t{2}, std::uint8_t{3}}) + { + selection = selector.select(key, candidates, settings); + require(selection.revalidation && selection.revalidation_stage == stage + && selection.route == ExecutionRoute::NativeSequential, + "distribution-shift revalidation missed challenger evidence"); + selector.complete(selection, stage == 2 ? 81.0 : 83.0, settings); + } + selection = selector.select(key, candidates, settings); + require(selection.revalidation && selection.revalidation_stage == 4 + && selection.route == ExecutionRoute::OpenCV, + "distribution-shift revalidation missed final stable evidence"); + selector.complete(selection, 121.0, settings); + + selection = selector.select(key, candidates, settings); + require(selection.stable && selection.route == ExecutionRoute::NativeSequential, + "selector did not adapt to the changed performance regime"); + require(selector.snapshot(key, snapshot), + "post-switch distribution telemetry was unavailable"); + require(snapshot.route_switch_count == 1 + && snapshot.last_revalidation_stable_ms > 120.0 + && snapshot.last_revalidation_challenger_ms >= 82.0 + && snapshot.last_revalidation_challenger_ms <= 83.0, + "current-context revalidation telemetry was inconsistent"); +} + +void validate_selector_single_flight() +{ + using namespace smart::vision::detail; + AdaptiveRouteSelector selector; + RouteSelectorSettings settings; + RouteProfileKey key; + key.operation = 7; + const std::vector candidates{ + ExecutionRoute::NativeSequential, + ExecutionRoute::OpenCV}; + + const auto first = selector.select(key, candidates, settings); + require(first.probe, "first selector call was not a probe"); + const auto concurrent = selector.select(key, candidates, settings); + require(!concurrent.probe, "selector allowed duplicate concurrent probes"); + selector.complete(concurrent, 0.001, settings); + RouteMeasurementSnapshot snapshot; + require(selector.snapshot(key, snapshot), "single-flight selector snapshot failed"); + require(snapshot.samples[0] == 0 && snapshot.warmups[0] == 0, + "concurrent fallback polluted route learning"); + selector.cancel(first); + const auto retry = selector.select(key, candidates, settings); + require(retry.probe, "cancelled selector probe could not be retried"); +} + +void validate_selector_bounded_eviction() +{ + using namespace smart::vision::detail; + AdaptiveRouteSelector selector; + RouteSelectorSettings settings; + settings.maximum_entries = 16; + settings.minimum_samples = 1; + const std::vector candidates{ExecutionRoute::NativeSequential}; + + RouteProfileKey first; + first.operation = 100; + const std::size_t target_shard = RouteProfileKeyHasher{}(first) % 16; + RouteProfileKey second = first; + for (std::uint64_t operation = 101; operation < 10'000; ++operation) + { + second.operation = operation; + if (RouteProfileKeyHasher{}(second) % 16 == target_shard) + break; + } + require(second.operation != first.operation, + "could not construct same-shard route-cache keys"); + + auto selection = selector.select(first, candidates, settings); + selector.complete(selection, 1.0, settings); + selection = selector.select(second, candidates, settings); + selector.complete(selection, 1.0, settings); + + RouteMeasurementSnapshot snapshot; + require(!selector.snapshot(first, snapshot), + "bounded selector did not evict its least-recently-used entry"); + require(selector.snapshot(second, snapshot), + "bounded selector evicted the newly inserted entry"); +} + +void validate_threshold_routes() +{ + constexpr std::size_t width = 257; + constexpr std::size_t height = 131; + std::vector source(width * height); + for (std::size_t index = 0; index < source.size(); ++index) + source[index] = static_cast((index * 37u + index / 11u) & 0xffu); + + const smart::vision::ThresholdOptions options{ + 127, + 231, + smart::vision::ThresholdMode::Binary}; + const std::vector expected = reference_threshold(source, options); + const auto source_view = smart::vision::make_contiguous_image_view( + static_cast(source.data()), width, height); + + std::vector routes{ + ExecutionRoute::NativeSequential, + ExecutionRoute::NativeThreadPool, + ExecutionRoute::NativeStaticThread}; + if (smart::execution_backend_available(smart::ExecutionEngineType::OneTbb)) + routes.push_back(ExecutionRoute::NativeOneTbb); + if (smart::vision::opencv_available()) + routes.push_back(ExecutionRoute::OpenCV); + + for (ExecutionRoute route : routes) + { + std::vector output(source.size(), 17); + smart::vision::threshold( + source_view, + smart::vision::make_contiguous_image_view(output.data(), width, height), + options, + {route, 4}); + require(output == expected, "forced threshold route produced incorrect output"); + const auto report = smart::vision::last_decision_report(); + require(report.selected_route == route, "forced threshold route was not reported"); + require(report.backend_authenticated, "forced threshold route was not authenticated"); + + std::vector in_place = source; + smart::vision::threshold( + smart::vision::make_contiguous_image_view( + static_cast(in_place.data()), width, height), + smart::vision::make_contiguous_image_view(in_place.data(), width, height), + options, + {route, 4}); + require(in_place == expected, "forced in-place threshold route produced incorrect output"); + } + + smart::vision::clear_adaptive_route_cache(); + smart::vision::DecisionReport automatic_report; + bool learned = false; + for (int invocation = 0; invocation < 64; ++invocation) + { + std::vector output(source.size()); + smart::vision::threshold( + source_view, + smart::vision::make_contiguous_image_view(output.data(), width, height), + options, + {ExecutionRoute::Auto, 4}); + require(output == expected, "automatic threshold route produced incorrect output"); + automatic_report = smart::vision::last_decision_report(); + if (automatic_report.learned_route && !automatic_report.exploration_probe + && !automatic_report.revalidation_probe) + { + learned = true; + break; + } + } + require(learned, "automatic threshold route did not stabilize within 64 calls"); + require(automatic_report.adaptive_selection_enabled, + "automatic threshold did not enable adaptive route selection"); + require(automatic_report.backend_authenticated, + "automatic threshold route was not authenticated"); + require(automatic_report.learned_route, + "automatic threshold route did not reach a stable learned decision"); + require(automatic_report.cache_hit, + "learned automatic threshold did not use the hot route cache"); + require(!automatic_report.execution_timed, + "stable hot-route execution retained internal timing overhead"); + + ConfigGuard config_guard; + smart::global_config().enable_vision_adaptive_routes = false; + std::vector disabled_output(source.size()); + smart::vision::threshold( + source_view, + smart::vision::make_contiguous_image_view( + disabled_output.data(), width, height), + options, + {ExecutionRoute::Auto, 4}); + require(disabled_output == expected, + "disabled adaptive route selection produced incorrect output"); + const auto disabled_report = smart::vision::last_decision_report(); + require(disabled_report.selected_route == ExecutionRoute::NativeSequential, + "disabled adaptive route selection did not use the native sequential fallback"); + require(!disabled_report.adaptive_selection_enabled, + "disabled adaptive route selection still entered the selector"); +} + +void validate_publication_stability_window() +{ + ConfigGuard config_guard; + auto& config = smart::global_config(); + config.vision_route_initial_revalidate_interval = 64; + config.vision_route_revalidate_interval = 128; + ++config.vision_route_policy_generation; + smart::vision::clear_adaptive_route_cache(); + + constexpr std::size_t width = 4096; + constexpr std::size_t height = 8; + std::vector source(width * height); + for (std::size_t index = 0; index < source.size(); ++index) + source[index] = static_cast((index * 37u + 11u) & 0xffu); + const smart::vision::ThresholdOptions options{ + 127, 255, smart::vision::ThresholdMode::Binary}; + const auto expected = reference_threshold(source, options); + const auto source_view = smart::vision::make_contiguous_image_view( + static_cast(source.data()), width, height); + + smart::vision::DecisionReport learned_report; + bool learned = false; + std::vector output(source.size()); + for (std::size_t invocation = 0; invocation < 64; ++invocation) + { + smart::vision::threshold( + source_view, + smart::vision::make_contiguous_image_view(output.data(), width, height), + options, + {ExecutionRoute::Auto, 4}); + require(output == expected, + "publication stability learning produced incorrect output"); + learned_report = smart::vision::last_decision_report(); + if (learned_report.learned_route && !learned_report.exploration_probe + && !learned_report.revalidation_probe) + { + learned = true; + break; + } + } + require(learned, + "publication stability profile did not learn within 64 calls"); + const ExecutionRoute learned_route = learned_report.selected_route; + config.vision_route_pause_maintenance = true; + + for (std::size_t repetition = 0; repetition < 31; ++repetition) + { + smart::vision::threshold( + source_view, + smart::vision::make_contiguous_image_view(output.data(), width, height), + options, + {ExecutionRoute::Auto, 4}); + const auto report = smart::vision::last_decision_report(); + require(output == expected, + "publication stability window produced incorrect output"); + require(report.learned_route, + "publication stability window lost its learned route"); + require(!report.exploration_probe && !report.revalidation_probe + && !report.drift_probe, + "publication stability window unexpectedly contained a probe"); + require(report.selected_route == learned_route, + "publication stability window changed the learned route"); + } +} + +void validate_strided_and_edge_cases() +{ + smart::vision::threshold({}, {}); + + std::uint8_t source_pixel = 128; + std::uint8_t destination_pixel = 0; + smart::vision::threshold( + smart::vision::make_contiguous_image_view( + static_cast(&source_pixel), 1, 1), + smart::vision::make_contiguous_image_view(&destination_pixel, 1, 1), + {127, 255, smart::vision::ThresholdMode::Binary}, + {ExecutionRoute::NativeSequential, 1}); + require(destination_pixel == 255, "one-pixel threshold failed"); + + std::vector in_place{0, 100, 127, 128, 255}; + smart::vision::threshold( + smart::vision::make_contiguous_image_view( + static_cast(in_place.data()), in_place.size(), 1), + smart::vision::make_contiguous_image_view(in_place.data(), in_place.size(), 1), + {127, 255, smart::vision::ThresholdMode::Binary}, + {ExecutionRoute::NativeSequential, 1}); + require((in_place == std::vector{0, 0, 0, 255, 255}), + "in-place threshold failed"); + + constexpr std::size_t width = 63; + constexpr std::size_t height = 17; + constexpr std::size_t stride = 80; + std::vector source(stride * height, 13); + std::vector output(stride * height, 99); + for (std::size_t y = 0; y < height; ++y) + for (std::size_t x = 0; x < width; ++x) + source[y * stride + x] = static_cast((x * 9 + y * 17) & 0xff); + + std::vector strided_routes{ + ExecutionRoute::NativeThreadPool, + ExecutionRoute::NativeStaticThread}; + if (smart::execution_backend_available(smart::ExecutionEngineType::OneTbb)) + strided_routes.push_back(ExecutionRoute::NativeOneTbb); + if (smart::vision::opencv_available()) + strided_routes.push_back(ExecutionRoute::OpenCV); + + for (ExecutionRoute route : strided_routes) + { + std::fill(output.begin(), output.end(), std::uint8_t{99}); + smart::vision::threshold( + smart::vision::make_image_view( + static_cast(source.data()), width, height, stride), + smart::vision::make_image_view(output.data(), width, height, stride), + {100, 200, smart::vision::ThresholdMode::BinaryInverse}, + {route, 3}); + + for (std::size_t y = 0; y < height; ++y) + { + for (std::size_t x = 0; x < width; ++x) + { + const std::uint8_t expected = source[y * stride + x] > 100 ? 0 : 200; + require(output[y * stride + x] == expected, "strided threshold mismatch"); + } + for (std::size_t x = width; x < stride; ++x) + { + require(output[y * stride + x] == 99, + "strided threshold modified row padding"); + } + } + } + + bool threw = false; + try + { + smart::vision::threshold( + smart::vision::make_image_view( + static_cast(source.data()), width, height, width - 1), + smart::vision::make_image_view(output.data(), width, height, stride)); + } + catch (const std::invalid_argument&) + { + threw = true; + } + require(threw, "invalid source stride was not rejected"); + + threw = false; + try + { + smart::vision::threshold( + smart::vision::make_image_view( + static_cast(source.data()), width, height, stride), + smart::vision::make_image_view(output.data(), width - 1, height, stride)); + } + catch (const std::invalid_argument&) + { + threw = true; + } + require(threw, "mismatched image dimensions were not rejected"); + + threw = false; + try + { + smart::vision::threshold( + smart::vision::make_image_view( + static_cast(source.data()), width, height, stride), + smart::vision::make_image_view(output.data(), width, height, stride), + {127, 255, static_cast(99)}); + } + catch (const std::invalid_argument&) + { + threw = true; + } + require(threw, "invalid threshold mode was not rejected"); + + threw = false; + try + { + smart::vision::threshold( + smart::vision::make_image_view( + static_cast(source.data()), width, height, stride), + smart::vision::make_image_view(output.data(), width, height, stride), + {}, + {static_cast(99), 1}); + } + catch (const std::invalid_argument&) + { + threw = true; + } + require(threw, "invalid execution route was not rejected"); + + std::vector overlap(width + 8, 200); + threw = false; + try + { + smart::vision::threshold( + smart::vision::make_contiguous_image_view( + static_cast(overlap.data()), width, 1), + smart::vision::make_contiguous_image_view(overlap.data() + 1, width, 1)); + } + catch (const std::invalid_argument&) + { + threw = true; + } + require(threw, "partially overlapping buffers were not rejected"); + + if (!smart::execution_backend_available(smart::ExecutionEngineType::OneTbb)) + { + threw = false; + try + { + smart::vision::threshold( + smart::vision::make_image_view( + static_cast(source.data()), width, height, stride), + smart::vision::make_image_view(output.data(), width, height, stride), + {}, + {ExecutionRoute::NativeOneTbb, 2}); + } + catch (const std::runtime_error&) + { + threw = true; + } + require(threw, "unavailable forced oneTBB route did not fail clearly"); + } + + if (!smart::vision::opencv_available()) + { + threw = false; + try + { + smart::vision::threshold( + smart::vision::make_image_view( + static_cast(source.data()), width, height, stride), + smart::vision::make_image_view(output.data(), width, height, stride), + {}, + {ExecutionRoute::OpenCV, 1}); + } + catch (const std::runtime_error&) + { + threw = true; + } + require(threw, "unavailable forced OpenCV route did not fail clearly"); + } +} + +void validate_nested_auto_fallback() +{ + std::vector source(128, 200); + std::vector output(128, 0); + std::atomic nested_fallback{false}; + smart::parallel_for(std::size_t{0}, std::size_t{1}, [&](std::size_t) + { + smart::vision::threshold( + smart::vision::make_contiguous_image_view( + static_cast(source.data()), source.size(), 1), + smart::vision::make_contiguous_image_view(output.data(), output.size(), 1)); + nested_fallback.store( + smart::vision::last_decision_report().nested_fallback, + std::memory_order_relaxed); + }); + require(nested_fallback.load(std::memory_order_relaxed), + "nested Auto vision call did not use the safe native fallback"); +} +} // namespace + +int main() +{ + try + { + validate_native_kernel_dispatch(); + validate_native_kernel_shapes(); + validate_native_kernel_edge_values(); + validate_selector_learning(); + validate_selector_decisive_revalidation(); + validate_selector_robust_learning(); + validate_selector_distribution_shift(); + validate_selector_single_flight(); + validate_selector_bounded_eviction(); + validate_threshold_routes(); + validate_publication_stability_window(); + validate_strided_and_edge_cases(); + validate_nested_auto_fallback(); + std::cout << "SmartParallel v1.5 adaptive execution-route validation passed\n"; + return 0; + } + catch (const std::exception& exception) + { + std::cerr << "SmartParallel v1.5 validation failed: " << exception.what() << '\n'; + return 1; + } +} diff --git a/tools/README.md b/tools/README.md index 3baf2eb..c159507 100644 --- a/tools/README.md +++ b/tools/README.md @@ -1,42 +1,58 @@ -# Analysis tools +# Analysis and documentation tools -## `plot_real_world_results.py` - -Validates the final v1.1 real-world CSV schemas, correctness flags, backend authentication, and four-participant budget, then generates the release PNG/SVG figures and aggregate metrics. +## `analyze_v15_adaptive_routes.py` -From the repository root: +Validates the v1.5 raw threshold-route matrix before performance analysis. It rejects missing rows, correctness failures, route-authentication failures, inconsistent addresses/alignment, unbalanced route orders, probe leakage, malformed dispatch batches, and inconsistent Native-kernel identity. It recomputes medians, route regret, Native-oracle quality, and confidence-bounded dispatch overhead, then writes summary CSV, Markdown, and the compatibility Auto-regret SVG. ```text -python -m pip install pandas matplotlib -python tools/plot_real_world_results.py +py -3 tools/analyze_v15_adaptive_routes.py RAW.csv OUTPUT_DIR ``` -Default input: +## `generate_v15_benchmark_plots.py` + +Generates dependency-free SVG figures from a validated v1.5 publication directory: + +- automatic speedup versus direct sequential and direct OpenCV; +- route-selection regret; +- Native kernel versus independent oracle; +- stable Auto dispatch overhead and confidence intervals; +- initial versus settled route map. ```text -validation/output/real_world/ +py -3 tools/generate_v15_benchmark_plots.py SUMMARY.csv RAW.csv LEARNING.csv OUTPUT_DIR ``` -Default output: +The v1.5 release validation script runs this tool automatically. + +## `publish_v15_benchmark_docs.py` + +Publishes a validated 6/6 v1.5 run into `docs/v1.5/assets/benchmarks/`. It refuses incomplete or failing runs, copies accepted evidence, generates figures, writes machine-readable metrics and generated Markdown, and records source hashes. ```text -docs/v1.1/assets/benchmarks/ +py -3 tools/publish_v15_benchmark_docs.py validation/output/v1.5.0_adaptive_routes/publication_ ``` -Use `--input-dir` and `--output-dir` for custom locations. +## `plot_real_world_results.py` + +Validates the retained v1.1 real-world CSV schemas, correctness flags, backend authentication, and four-participant budget, then generates the v1.1 PNG/SVG figures and aggregate metrics. + +```text +python -m pip install pandas matplotlib +python tools/plot_real_world_results.py +``` ## `check_documentation.py` -Validates local Markdown links, rejects malformed control characters, and checks that v1.0/v1.1 pages carry the appropriate archive/current markers. +Validates local Markdown links, rejects malformed control characters, and checks version/archive markers. ```text -python tools/check_documentation.py +py -3 tools/check_documentation.py ``` ## Historical analysis tools -- `plot_benchmark.py` — generic plot utility used by earlier benchmark workflows. -- `phase1_dataset_audit.py` — audits the historical Phase 1 calibration/holdout datasets. +- `plot_benchmark.py` — generic plot utility used by earlier workflows. +- `phase1_dataset_audit.py` — audits historical Phase 1 calibration/holdout datasets. - `phase1_regret_ranker.py` — trains and evaluates the historical regret-aware utility ranker. Python cache directories are local artifacts and must not be committed. diff --git a/tools/analyze_v15_adaptive_routes.py b/tools/analyze_v15_adaptive_routes.py new file mode 100644 index 0000000..9e5c91c --- /dev/null +++ b/tools/analyze_v15_adaptive_routes.py @@ -0,0 +1,500 @@ +#!/usr/bin/env python3 +"""Validate and analyze SmartParallel v1.5 adaptive execution-route results.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import html +import math +import statistics +from collections import defaultdict +from pathlib import Path + +REQUIRED_COLUMNS = { + "schema_version", "benchmark_version", "operation", "preset", + "implementation", "phase", "repetition_index", "measurement_ordinal", + "width", "height", "stride_bytes", "duration_ns", "batch_total_ns", + "batch_iterations", "checksum", "mismatch_count", "requested_route", + "selected_route", "worker_budget", "participant_count", "chunk_count", + "learned_route", "probe", "exploration_probe", "holdout_probe", + "revalidation_probe", "correctness_pass", "backend_authentication_pass", + "requested_repetitions", "source_address", "destination_address", + "source_alignment", "destination_alignment", "shared_destination_id", + "learning_invocations", "deployment_invocations", "route_switch_count", + "pair_order", "pair_position", "native_kernel", "drift_probe", +} + +LEARNING_COLUMNS = { + "schema_version", "preset", "stable", "stable_route", "provisional_route", + "holdout_active", "revalidation_active", "drift_detected", + "verification_failures", "route_switch_count", "drift_strikes", + "revalidation_challenger", "training_baseline_ms", "current_baseline_ms", + "last_revalidation_stable_ms", "last_revalidation_challenger_ms", + "route", "median_ms", "mad_ms", "minimum_ms", "maximum_ms", + "current_median_ms", "sample_count", "current_sample_count", + "warmup_count", "holdout_sample_count", "active", +} + +BASE_IMPLEMENTATIONS = { + "opencv_api", "direct_sequential", "smart_auto", + "smart_native_sequential", "smart_native_thread_pool", + "smart_native_static_thread", "smart_opencv", +} +REQUIRED_PRESETS = [ + "tiny_320x240", "small_640x480", "medium_1920x1080", + "medium_1920x1080_roi", "large_3840x2160", "very_large_7680x4320", +] +FORCED_ROUTE_EXPECTATIONS = { + "smart_native_sequential": "native_sequential", + "smart_native_thread_pool": "native_thread_pool", + "smart_native_static_thread": "native_static_thread", + "smart_native_one_tbb": "native_one_tbb", + "smart_opencv": "opencv", +} +ROUTE_TO_IMPLEMENTATION = { + "native_sequential": "smart_native_sequential", + "native_thread_pool": "smart_native_thread_pool", + "native_one_tbb": "smart_native_one_tbb", + "opencv": "smart_opencv", +} +ELIGIBLE_AUTO_IMPLEMENTATIONS = { + "smart_native_sequential", "smart_native_thread_pool", + "smart_native_one_tbb", "smart_opencv", +} + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("raw_csv", type=Path) + parser.add_argument("output_dir", type=Path) + parser.add_argument("--equivalence-percent", type=float, default=5.0) + parser.add_argument("--absolute-tolerance-ns", type=int, default=1_000) + parser.add_argument("--native-relative-percent", type=float, default=10.0) + parser.add_argument("--native-absolute-tolerance-ns", type=int, default=500) + parser.add_argument("--dispatch-overhead-ns", type=int, default=1_000) + parser.add_argument("--allow-missing-onetbb", action="store_true") + return parser.parse_args() + + +def as_bool(value: str) -> bool: + return value.strip().lower() in {"1", "true", "yes"} + + +def observed_median(values: list[int | float]) -> float: + if not values: + raise ValueError("Cannot compute a median of an empty sample set") + return float(statistics.median(values)) + + +def median_absolute_deviation(values: list[int | float], center: float) -> float: + return observed_median([abs(float(value) - center) for value in values]) + + +def read_csv(path: Path, required: set[str]) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8-sig") as handle: + reader = csv.DictReader(handle) + missing = required - set(reader.fieldnames or []) + if missing: + raise ValueError(f"{path.name} is missing columns: {sorted(missing)}") + rows = list(reader) + if not rows: + raise ValueError(f"{path.name} is empty") + return rows + + +def unique_in_order(values: list[str]) -> list[str]: + seen: set[str] = set() + result: list[str] = [] + for value in values: + if value not in seen: + seen.add(value) + result.append(value) + return result + + +def confidence_interval_median(values: list[float]) -> tuple[float, float, float]: + center = observed_median(values) + mad = median_absolute_deviation(values, center) + if len(values) <= 1: + return center, center, center + half = 1.96 * 1.4826 * mad / math.sqrt(len(values)) + return center, center - half, center + half + + +def validate_learning(path: Path, presets: list[str]) -> dict[str, list[dict[str, str]]]: + rows = read_csv(path, LEARNING_COLUMNS) + if {row["schema_version"] for row in rows} != {"2"}: + raise ValueError("Unexpected learning telemetry schema") + grouped: dict[str, list[dict[str, str]]] = defaultdict(list) + for row in rows: + grouped[row["preset"]].append(row) + if list(grouped) != presets: + raise ValueError("Learning telemetry preset matrix mismatch") + for preset, entries in grouped.items(): + stable_routes = {row["stable_route"] for row in entries} + if len(stable_routes) != 1 or any(not as_bool(row["stable"]) for row in entries): + raise ValueError(f"{preset}: unstable learning telemetry") + if any(as_bool(row["holdout_active"]) for row in entries): + raise ValueError(f"{preset}: holdout remained active after stabilization") + if any(as_bool(row["revalidation_active"]) for row in entries): + raise ValueError(f"{preset}: current-context revalidation remained active") + if any(int(row["sample_count"]) <= 0 for row in entries): + raise ValueError(f"{preset}: missing measured training samples") + if any(int(row["warmup_count"]) < 2 for row in entries): + raise ValueError(f"{preset}: routes were not primed twice") + if not any(int(row["holdout_sample_count"]) >= 2 for row in entries): + raise ValueError(f"{preset}: independent holdout verification was not recorded") + return grouped + + +def validate(rows: list[dict[str, str]], allow_missing_onetbb: bool) -> tuple[int, list[str], list[str]]: + if {row["schema_version"] for row in rows} != {"6"}: + raise ValueError("Publication data must use raw schema version 6") + if {row["benchmark_version"] for row in rows} != {"1.5.0"}: + raise ValueError("Unexpected benchmark version") + if {row["operation"] for row in rows} != {"threshold_u8_binary"}: + raise ValueError("Unexpected operation matrix") + native_kernels = {row["native_kernel"] for row in rows} + if len(native_kernels) != 1 or "" in native_kernels: + raise ValueError(f"Inconsistent native kernel identity: {sorted(native_kernels)}") + + repetition_values = {int(row["requested_repetitions"]) for row in rows} + if len(repetition_values) != 1: + raise ValueError("Raw rows disagree on repetition count") + repetitions = repetition_values.pop() + if repetitions <= 0 or repetitions % 2 == 0: + raise ValueError("Publication repetition count must be positive and odd") + + if any(not as_bool(row["correctness_pass"]) or int(row["mismatch_count"]) != 0 + for row in rows): + raise ValueError("Correctness failed") + if any(not as_bool(row["backend_authentication_pass"]) for row in rows): + raise ValueError("Backend authentication failed") + + presets = unique_in_order([row["preset"] for row in rows]) + implementations = unique_in_order([row["implementation"] for row in rows]) + if presets != REQUIRED_PRESETS: + raise ValueError(f"Preset matrix mismatch: {presets}") + missing = BASE_IMPLEMENTATIONS - set(implementations) + if missing: + raise ValueError(f"Missing required implementations: {sorted(missing)}") + if not allow_missing_onetbb and "smart_native_one_tbb" not in implementations: + raise ValueError("Publication matrix is missing smart_native_one_tbb") + + for implementation, route in FORCED_ROUTE_EXPECTATIONS.items(): + invalid = [row for row in rows if row["implementation"] == implementation + and row["selected_route"] != route] + if invalid: + raise ValueError(f"{implementation} did not authenticate {route}") + + for preset in presets: + preset_rows = [row for row in rows if row["preset"] == preset] + if len({row["checksum"] for row in preset_rows}) != 1: + raise ValueError(f"{preset}: inconsistent checksums") + if len({row["source_address"] for row in preset_rows}) != 1 \ + or len({row["destination_address"] for row in preset_rows}) != 1: + raise ValueError(f"{preset}: routes did not use identical allocations") + if {row["shared_destination_id"] for row in preset_rows} != {"shared_per_preset"}: + raise ValueError(f"{preset}: invalid shared destination declaration") + if len({row["source_alignment"] for row in preset_rows}) != 1 \ + or len({row["destination_alignment"] for row in preset_rows}) != 1: + raise ValueError(f"{preset}: alignment changed across routes") + + cold = [row for row in preset_rows if row["phase"] == "cold"] + if len(cold) != 1 or cold[0]["implementation"] != "smart_auto": + raise ValueError(f"{preset}: expected one cold Auto sample") + + steady = [row for row in preset_rows if row["phase"] == "steady_state"] + grouped: dict[str, list[dict[str, str]]] = defaultdict(list) + for row in steady: + grouped[row["implementation"]].append(row) + for implementation in implementations: + if len(grouped[implementation]) != repetitions: + raise ValueError( + f"{preset}/{implementation}: expected {repetitions} steady samples, " + f"got {len(grouped[implementation])}" + ) + auto_rows = grouped["smart_auto"] + if any(as_bool(row["probe"]) or as_bool(row["exploration_probe"]) + or as_bool(row["holdout_probe"]) or as_bool(row["revalidation_probe"]) + or as_bool(row["drift_probe"]) for row in auto_rows): + raise ValueError(f"{preset}: steady Auto data contains probes") + if any(not as_bool(row["learned_route"]) for row in auto_rows): + raise ValueError(f"{preset}: steady Auto rows are not learned") + routes = {row["selected_route"] for row in auto_rows} + if len(routes) != 1 or not routes <= set(ROUTE_TO_IMPLEMENTATION): + raise ValueError(f"{preset}: unstable or invalid Auto route") + learning_counts = {int(row["learning_invocations"]) for row in steady} + deployment_counts = {int(row["deployment_invocations"]) for row in steady} + switch_counts = {int(row["route_switch_count"]) for row in auto_rows} + if len(learning_counts) != 1 or next(iter(learning_counts)) <= 0: + raise ValueError(f"{preset}: invalid learning invocation metadata") + if len(deployment_counts) != 1 or next(iter(deployment_counts)) <= 0: + raise ValueError(f"{preset}: invalid deployment-settling metadata") + if len(switch_counts) != 1: + raise ValueError(f"{preset}: inconsistent route-switch metadata") + + # Balanced order check: every implementation occupies each position nearly equally. + positions: dict[str, list[int]] = defaultdict(list) + by_rep: dict[int, list[dict[str, str]]] = defaultdict(list) + for row in steady: + by_rep[int(row["repetition_index"])].append(row) + for repetition in range(repetitions): + block = sorted(by_rep[repetition], key=lambda row: int(row["measurement_ordinal"])) + if len(block) != len(implementations) or {row["implementation"] for row in block} != set(implementations): + raise ValueError(f"{preset}: malformed balanced block {repetition}") + for position, row in enumerate(block): + positions[row["implementation"]].append(position) + for implementation, observed in positions.items(): + counts = [observed.count(position) for position in range(len(implementations))] + if max(counts) - min(counts) > 1: + raise ValueError(f"{preset}/{implementation}: unbalanced measurement positions") + + batches = [row for row in preset_rows if row["phase"] == "dispatch_batch"] + if len(batches) != repetitions * 4: + raise ValueError(f"{preset}: expected {repetitions * 4} dispatch batch rows") + selected_impl = ROUTE_TO_IMPLEMENTATION[next(iter(routes))] + by_pair: dict[int, list[dict[str, str]]] = defaultdict(list) + for row in batches: + by_pair[int(row["repetition_index"])].append(row) + for repetition in range(repetitions): + block = sorted(by_pair[repetition], key=lambda row: int(row["pair_position"])) + if [int(row["pair_position"]) for row in block] != [1, 2, 3, 4]: + raise ValueError(f"{preset}: malformed dispatch block {repetition}") + expected_order = ("auto_forced_forced_auto" if repetition % 2 == 0 + else "forced_auto_auto_forced") + if {row["pair_order"] for row in block} != {expected_order}: + raise ValueError(f"{preset}: incorrect dispatch block metadata") + expected_impls = (["smart_auto", selected_impl, selected_impl, "smart_auto"] + if repetition % 2 == 0 + else [selected_impl, "smart_auto", "smart_auto", selected_impl]) + if [row["implementation"] for row in block] != expected_impls: + raise ValueError(f"{preset}: incorrect ABBA/BAAB sequence") + iterations = {int(row["batch_iterations"]) for row in block} + if len(iterations) != 1 or next(iter(iterations)) <= 0: + raise ValueError(f"{preset}: invalid batch iteration metadata") + for row in block: + if int(row["batch_total_ns"]) <= 0: + raise ValueError(f"{preset}: invalid batch duration") + if row["implementation"] == "smart_auto" and ( + as_bool(row["probe"]) or as_bool(row["drift_probe"]) + or not as_bool(row["learned_route"]) + ): + raise ValueError(f"{preset}: dispatch batch Auto route was not stable") + return repetitions, presets, implementations + + +def summarize(rows: list[dict[str, str]], presets: list[str], implementations: list[str], + learning: dict[str, list[dict[str, str]]], args: argparse.Namespace) -> list[dict[str, object]]: + summaries: list[dict[str, object]] = [] + for preset in presets: + steady = [row for row in rows if row["preset"] == preset and row["phase"] == "steady_state"] + grouped: dict[str, list[int]] = defaultdict(list) + metadata: dict[str, dict[str, str]] = {} + for row in steady: + grouped[row["implementation"]].append(int(row["duration_ns"])) + metadata[row["implementation"]] = row + medians = {implementation: int(observed_median(values)) + for implementation, values in grouped.items()} + eligible = [implementation for implementation in implementations + if implementation in ELIGIBLE_AUTO_IMPLEMENTATIONS] + fastest = min(eligible, key=lambda implementation: medians[implementation]) + fastest_ns = medians[fastest] + auto_meta = metadata["smart_auto"] + selected_route = auto_meta["selected_route"] + selected_impl = ROUTE_TO_IMPLEMENTATION[selected_route] + selected_ns = medians[selected_impl] + route_regret_ns = selected_ns - fastest_ns + route_regret_percent = (selected_ns / fastest_ns - 1.0) * 100.0 + route_pass = route_regret_percent <= args.equivalence_percent \ + or route_regret_ns <= args.absolute_tolerance_ns + + batch_rows = [row for row in rows if row["preset"] == preset + and row["phase"] == "dispatch_batch"] + by_rep: dict[int, list[dict[str, str]]] = defaultdict(list) + for row in batch_rows: + by_rep[int(row["repetition_index"])].append(row) + deltas: list[float] = [] + for block in by_rep.values(): + auto_total = sum(int(row["batch_total_ns"]) for row in block + if row["implementation"] == "smart_auto") + forced_total = sum(int(row["batch_total_ns"]) for row in block + if row["implementation"] == selected_impl) + auto_iterations = sum(int(row["batch_iterations"]) for row in block + if row["implementation"] == "smart_auto") + forced_iterations = sum(int(row["batch_iterations"]) for row in block + if row["implementation"] == selected_impl) + deltas.append(auto_total / auto_iterations - forced_total / forced_iterations) + dispatch_center, dispatch_lower, dispatch_upper = confidence_interval_median(deltas) + # Only fail when the lower confidence bound confidently exceeds the gate. + dispatch_pass = dispatch_lower <= args.dispatch_overhead_ns + dispatch_status = ("pass" if dispatch_upper <= args.dispatch_overhead_ns + else "fail" if dispatch_lower > args.dispatch_overhead_ns + else "inconclusive-pass") + + direct_ns = medians["direct_sequential"] + native_ns = medians["smart_native_sequential"] + native_delta_ns = native_ns - direct_ns + native_delta_percent = (native_ns / direct_ns - 1.0) * 100.0 + native_pass = native_delta_percent <= args.native_relative_percent \ + or native_delta_ns <= args.native_absolute_tolerance_ns + + auto_ns = medians["smart_auto"] + training = learning[preset] + learned_entry = next(row for row in training if row["route"] == selected_route) + overall = route_pass and dispatch_pass and native_pass + summaries.append({ + "benchmark_version": "1.5.0", + "preset": preset, + "width": int(auto_meta["width"]), + "height": int(auto_meta["height"]), + "stride_bytes": int(auto_meta["stride_bytes"]), + "source_alignment": int(auto_meta["source_alignment"]), + "destination_alignment": int(auto_meta["destination_alignment"]), + "learning_invocations": int(auto_meta["learning_invocations"]), + "deployment_invocations": int(auto_meta["deployment_invocations"]), + "route_switch_count": int(auto_meta["route_switch_count"]), + "drift_detected": int(as_bool(learned_entry["drift_detected"])), + "training_baseline_ns": int(float(learned_entry["training_baseline_ms"]) * 1_000_000), + "current_baseline_ns": int(float(learned_entry["current_baseline_ms"]) * 1_000_000), + "last_revalidation_stable_ns": int(float(learned_entry["last_revalidation_stable_ms"]) * 1_000_000), + "last_revalidation_challenger_ns": int(float(learned_entry["last_revalidation_challenger_ms"]) * 1_000_000), + "learning_verification_failures": int(learned_entry["verification_failures"]), + "learned_route_training_median_ns": int(float(learned_entry["median_ms"]) * 1_000_000), + "learned_route_training_mad_ns": int(float(learned_entry["mad_ms"]) * 1_000_000), + "learned_route_training_samples": int(learned_entry["sample_count"]), + "learned_route_holdout_samples": int(learned_entry["holdout_sample_count"]), + "native_kernel": auto_meta["native_kernel"], + "auto_selected_route": selected_route, + "auto_median_ns": auto_ns, + "selected_forced_implementation": selected_impl, + "selected_forced_median_ns": selected_ns, + "fastest_eligible_implementation": fastest, + "fastest_eligible_median_ns": fastest_ns, + "route_selection_regret_ns": route_regret_ns, + "route_selection_regret_percent": route_regret_percent, + "route_selection_pass": int(route_pass), + "batched_dispatch_overhead_ns": int(round(dispatch_center)), + "dispatch_ci_lower_ns": int(round(dispatch_lower)), + "dispatch_ci_upper_ns": int(round(dispatch_upper)), + "dispatch_status": dispatch_status, + "dispatch_overhead_pass": int(dispatch_pass), + "direct_sequential_median_ns": direct_ns, + "native_sequential_median_ns": native_ns, + "native_kernel_delta_ns": native_delta_ns, + "native_kernel_delta_percent": native_delta_percent, + "native_kernel_pass": int(native_pass), + "end_to_end_auto_regret_ns": auto_ns - fastest_ns, + "end_to_end_auto_regret_percent": (auto_ns / fastest_ns - 1.0) * 100.0, + "overall_pass": int(overall), + "auto_mad_ns": int(median_absolute_deviation(grouped["smart_auto"], auto_ns)), + }) + return summaries + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0].keys())) + writer.writeheader() + writer.writerows(rows) + + +def write_report(path: Path, raw_path: Path, rows: list[dict[str, object]], repetitions: int, + args: argparse.Namespace) -> None: + raw_sha = hashlib.sha256(raw_path.read_bytes()).hexdigest() + learning_path = raw_path.parent / "v1.5.0_adaptive_routes_learning.csv" + learning_sha = hashlib.sha256(learning_path.read_bytes()).hexdigest() + passed = sum(int(row["overall_pass"]) for row in rows) + route_passed = sum(int(row["route_selection_pass"]) for row in rows) + dispatch_passed = sum(int(row["dispatch_overhead_pass"]) for row in rows) + native_passed = sum(int(row["native_kernel_pass"]) for row in rows) + lines = [ + "# SmartParallel v1.5 Adaptive Execution Routes", + "", + "This report validates balanced initial learning, sparse drift sentinels, current-context ABBA revalidation, deployment settling, balanced steady-state route ordering, and batched adjacent ABBA/BAAB dispatch measurements.", + "", + f"- Steady-state repetitions: **{repetitions}**", + f"- Route equivalence: **{args.equivalence_percent:.1f}% or {args.absolute_tolerance_ns / 1000:.1f} µs**", + f"- Native oracle gate: **{args.native_relative_percent:.1f}% or {args.native_absolute_tolerance_ns / 1000:.1f} µs**", + f"- Dispatch gate: **{args.dispatch_overhead_ns / 1000:.1f} µs; failure only when the lower 95% robust bound exceeds the gate**", + f"- Native kernel: **{rows[0]['native_kernel']}**", + f"- Raw CSV SHA-256: `{raw_sha}`", + f"- Learning CSV SHA-256: `{learning_sha}`", + "", + "## Proof gates", + "", + "| Preset | Settled route | Switches | Fastest route | Route regret | Batched overhead (95% robust interval) | Native vs oracle | Training samples + holdout | Overall |", + "|---|---|---:|---|---:|---:|---:|---:|---|", + ] + for row in rows: + lines.append( + f"| {row['preset']} | {row['auto_selected_route']} | " + f"{row['route_switch_count']} | {row['fastest_eligible_implementation']} | " + f"{float(row['route_selection_regret_percent']):+.2f}% | " + f"{int(row['batched_dispatch_overhead_ns']) / 1000:+.3f} µs " + f"[{int(row['dispatch_ci_lower_ns']) / 1000:+.3f}, " + f"{int(row['dispatch_ci_upper_ns']) / 1000:+.3f}] ({row['dispatch_status']}) | " + f"{float(row['native_kernel_delta_percent']):+.2f}% | " + f"{row['learned_route_training_samples']} + {row['learned_route_holdout_samples']} | " + f"{'PASS' if int(row['overall_pass']) else 'FAIL'} |" + ) + lines += [ + "", "## Verdict", "", + f"- Route selection: **{route_passed}/{len(rows)}** presets passed.", + f"- Batched stable hot dispatch: **{dispatch_passed}/{len(rows)}** presets passed.", + f"- Native kernel versus independent oracle: **{native_passed}/{len(rows)}** presets passed.", + f"- Combined release gate: **{passed}/{len(rows)}** presets passed.", "", + ] + lines.append("The v1.5 threshold vertical slice passed all proof gates on this machine." + if passed == len(rows) + else "One or more proof gates remain outside the release target.") + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + + +def write_svg(path: Path, rows: list[dict[str, object]]) -> None: + width, left, top, row_h = 1050, 260, 70, 62 + height = top + row_h * len(rows) + 70 + max_value = max(10.0, max(max(0.0, float(row["end_to_end_auto_regret_percent"])) for row in rows)) + plot_width = 680 + content = [ + f'', + '', + 'SmartParallel v1.5 balanced-learning Auto regret', + ] + for index, row in enumerate(rows): + y = top + index * row_h + value = max(0.0, float(row["end_to_end_auto_regret_percent"])) + bar = plot_width * value / max_value + content += [ + f'{html.escape(str(row["preset"]))}', + f'', + f'{value:.2f}% · {html.escape(str(row["auto_selected_route"]))}', + ] + content.append('') + path.write_text("\n".join(content), encoding="utf-8") + + +def main() -> int: + args = parse_args() + rows = read_csv(args.raw_csv, REQUIRED_COLUMNS) + repetitions, presets, implementations = validate(rows, args.allow_missing_onetbb) + learning_path = args.raw_csv.parent / "v1.5.0_adaptive_routes_learning.csv" + learning = validate_learning(learning_path, presets) + summary = summarize(rows, presets, implementations, learning, args) + args.output_dir.mkdir(parents=True, exist_ok=True) + summary_path = args.output_dir / "v1.5.0_adaptive_routes.csv" + report_path = args.output_dir / "v1.5.0_adaptive_routes_report.md" + write_csv(summary_path, summary) + write_report(report_path, args.raw_csv, summary, repetitions, args) + write_svg(args.output_dir / "v1.5.0_auto_regret.svg", summary) + print(f"Validated {len(rows)} raw samples") + print(f"Summary: {summary_path}") + print(f"Report: {report_path}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/check_documentation.py b/tools/check_documentation.py index 6fbd3ba..b2abbdb 100644 --- a/tools/check_documentation.py +++ b/tools/check_documentation.py @@ -3,7 +3,9 @@ from __future__ import annotations +import json import re +import zipfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] @@ -12,6 +14,98 @@ INLINE_CODE = re.compile(r"`[^`]*`") + +def validate_v15_assets(errors: list[str]) -> None: + assets = ROOT / "docs/v1.5/assets/benchmarks" + required = [ + "README.md", + "generated-results.md", + "benchmark-metrics.json", + "accepted-summary.csv", + "accepted-learning.csv", + "accepted-environment.txt", + "accepted-publication-report.md", + "accepted-publication.zip", + "source-hashes.txt", + "v1.5.0_automatic_speedup.svg", + "v1.5.0_route_selection_regret.svg", + "v1.5.0_native_kernel_vs_oracle.svg", + "v1.5.0_dispatch_overhead.svg", + "v1.5.0_adaptive_route_map.svg", + ] + for name in required: + path = assets / name + if not path.exists() or path.stat().st_size == 0: + errors.append(f"docs/v1.5/assets/benchmarks: missing or empty {name}") + + metrics_path = assets / "benchmark-metrics.json" + if metrics_path.exists(): + try: + metrics = json.loads(metrics_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + errors.append(f"{metrics_path.relative_to(ROOT)}: invalid JSON: {exc}") + else: + expected = { + "release": "1.5.0", + "raw_sample_count": 2238, + "correctness_failures": 0, + "authentication_failures": 0, + "combined_gate_passes": 6, + "combined_gate_total": 6, + } + for key, value in expected.items(): + if metrics.get(key) != value: + errors.append( + f"{metrics_path.relative_to(ROOT)}: expected {key}={value!r}, " + f"found {metrics.get(key)!r}" + ) + if len(metrics.get("presets", [])) != 6: + errors.append(f"{metrics_path.relative_to(ROOT)}: expected six presets") + hashes = metrics.get("hashes", {}) + if any(not re.fullmatch(r"[0-9a-f]{64}", str(value)) for value in hashes.values()): + errors.append(f"{metrics_path.relative_to(ROOT)}: malformed evidence hash") + + archive_path = assets / "accepted-publication.zip" + if archive_path.exists(): + try: + with zipfile.ZipFile(archive_path) as archive: + names = set(archive.namelist()) + except zipfile.BadZipFile: + errors.append(f"{archive_path.relative_to(ROOT)}: invalid ZIP") + else: + required_members = { + "v1.5.0_adaptive_routes_raw.csv", + "v1.5.0_adaptive_routes_learning.csv", + "v1.5.0_adaptive_routes.csv", + "v1.5.0_adaptive_routes_environment.txt", + "v1.5.0_adaptive_routes_report.md", + "v1.5.0_build_vectorization.log", + } + missing = required_members - names + if missing: + errors.append( + f"{archive_path.relative_to(ROOT)}: missing evidence {sorted(missing)}" + ) + + +def validate_release_metadata(errors: list[str]) -> None: + cmake_text = (ROOT / "CMakeLists.txt").read_text(encoding="utf-8") + version_match = re.search(r"project\(\s*SmartParallel\s+VERSION\s+([0-9.]+)", cmake_text) + cmake_version = version_match.group(1) if version_match else None + try: + package = json.loads((ROOT / "vcpkg.json").read_text(encoding="utf-8")) + vcpkg_version = package.get("version-string") + except json.JSONDecodeError as exc: + errors.append(f"vcpkg.json: invalid JSON: {exc}") + vcpkg_version = None + if cmake_version != "1.5.0": + errors.append(f"CMakeLists.txt: expected project version 1.5.0, found {cmake_version!r}") + if vcpkg_version != cmake_version: + errors.append( + f"release version mismatch: CMake={cmake_version!r}, vcpkg={vcpkg_version!r}" + ) + + def main() -> int: errors: list[str] = [] for path in ROOT.rglob("*.md"): @@ -36,6 +130,11 @@ def main() -> int: if not destination.exists(): errors.append(f"{path.relative_to(ROOT)}: broken link {match.group(1)!r}") + for path in (ROOT / "docs/v1.5").glob("*.md"): + text = path.read_text(encoding="utf-8") + if "v1.5" not in text[:500]: + errors.append(f"{path.relative_to(ROOT)}: missing v1.5 release marker") + for path in (ROOT / "docs/v1.4").glob("*.md"): text = path.read_text(encoding="utf-8") if "v1.4" not in text[:500]: @@ -59,6 +158,13 @@ def main() -> int: if "Archived" not in path.read_text(encoding="utf-8")[:300]: errors.append(f"{path.relative_to(ROOT)}: missing v1.0 archive marker") + for path in [ROOT / "docs/v1.3/README.md", ROOT / "docs/v1.4/README.md"]: + if "Current release" in path.read_text(encoding="utf-8")[:500]: + errors.append(f"{path.relative_to(ROOT)}: stale current-release marker") + + validate_v15_assets(errors) + validate_release_metadata(errors) + if errors: print("Documentation validation: FAIL") for error in errors: diff --git a/tools/generate_v15_benchmark_plots.py b/tools/generate_v15_benchmark_plots.py new file mode 100644 index 0000000..e7614a9 --- /dev/null +++ b/tools/generate_v15_benchmark_plots.py @@ -0,0 +1,275 @@ +#!/usr/bin/env python3 +"""Generate dependency-free SVG plots for SmartParallel v1.5 publication data.""" + +from __future__ import annotations + +import argparse +import csv +import html +import math +import statistics +from collections import defaultdict +from pathlib import Path + +PRESET_LABELS = { + "tiny_320x240": "320×240", + "small_640x480": "640×480", + "medium_1920x1080": "1920×1080", + "medium_1920x1080_roi": "1920×1080 ROI", + "large_3840x2160": "3840×2160", + "very_large_7680x4320": "7680×4320", +} +ROUTE_LABELS = { + "native_sequential": "Native Sequential", + "native_thread_pool": "Native ThreadPool", + "native_static_thread": "Native StaticThread", + "native_one_tbb": "Native oneTBB", + "opencv": "OpenCV", +} + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("summary_csv", type=Path) + parser.add_argument("raw_csv", type=Path) + parser.add_argument("learning_csv", type=Path) + parser.add_argument("output_dir", type=Path) + return parser.parse_args() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8-sig") as handle: + rows = list(csv.DictReader(handle)) + if not rows: + raise ValueError(f"{path} is empty") + return rows + + +def median(values: list[int]) -> float: + if not values: + raise ValueError("missing samples") + return float(statistics.median(values)) + + +def svg_header(width: int, height: int, title: str, subtitle: str) -> list[str]: + return [ + f'', + '', + f'{html.escape(title)}', + f'{html.escape(subtitle)}', + ] + + +def write_svg(path: Path, content: list[str]) -> None: + content.append("") + path.write_text("\n".join(content) + "\n", encoding="utf-8") + + +def steady_medians(raw_rows: list[dict[str, str]]) -> dict[str, dict[str, float]]: + grouped: dict[tuple[str, str], list[int]] = defaultdict(list) + for row in raw_rows: + if row["phase"] == "steady_state": + grouped[(row["preset"], row["implementation"])].append(int(row["duration_ns"])) + result: dict[str, dict[str, float]] = defaultdict(dict) + for (preset, implementation), values in grouped.items(): + result[preset][implementation] = median(values) + return result + + +def plot_speedups(summary: list[dict[str, str]], medians: dict[str, dict[str, float]], out: Path) -> None: + width, height = 1120, 510 + left, top, row_h, plot_w = 210, 95, 62, 790 + data = [] + max_speedup = 1.0 + for row in summary: + preset = row["preset"] + auto = medians[preset]["smart_auto"] + direct = medians[preset]["direct_sequential"] + opencv = medians[preset]["opencv_api"] + direct_speedup = direct / auto + opencv_speedup = opencv / auto + max_speedup = max(max_speedup, direct_speedup, opencv_speedup) + data.append((preset, direct_speedup, opencv_speedup)) + max_speedup = math.ceil(max_speedup * 10.0) / 10.0 + content = svg_header( + width, height, + "SmartParallel v1.5 automatic speedup", + "Values above 1.0× mean SmartParallel Auto completed the threshold operation faster.", + ) + x0 = left + for tick in range(0, int(max_speedup * 10) + 1, 5): + value = tick / 10.0 + x = x0 + plot_w * value / max_speedup + content += [ + f'', + f'{value:.1f}×', + ] + for i, (preset, direct_speedup, opencv_speedup) in enumerate(data): + y = top + i * row_h + content.append(f'{PRESET_LABELS[preset]}') + for offset, value, fill, label in [ + (4, direct_speedup, "#356f9f", "vs direct sequential"), + (29, opencv_speedup, "#6a9a55", "vs OpenCV API"), + ]: + bar = plot_w * value / max_speedup + content += [ + f'', + f'{value:.2f}×', + ] + content += [ + '', + 'vs direct sequential', + '', + 'vs OpenCV API', + f'', + ] + write_svg(out / "v1.5.0_automatic_speedup.svg", content) + + +def plot_route_regret(summary: list[dict[str, str]], out: Path) -> None: + width, height = 1080, 500 + left, top, row_h, plot_w = 230, 95, 58, 720 + max_value = 5.0 + content = svg_header( + width, height, + "SmartParallel v1.5 route-selection regret", + "Distance between the settled route and the fastest eligible forced route; the release limit is 5% or 1 µs.", + ) + threshold_x = left + plot_w + content += [ + f'', + f'5% gate', + ] + for tick in range(0, 6): + x = left + plot_w * tick / max_value + content += [ + f'', + f'{tick}%', + ] + for i, row in enumerate(summary): + y = top + i * row_h + value = max(0.0, float(row["route_selection_regret_percent"])) + bar = plot_w * min(value, max_value) / max_value + content += [ + f'{PRESET_LABELS[row["preset"]]}', + f'', + f'{value:.2f}% · {ROUTE_LABELS.get(row["auto_selected_route"], row["auto_selected_route"])}', + ] + write_svg(out / "v1.5.0_route_selection_regret.svg", content) + + +def plot_native_kernel(summary: list[dict[str, str]], out: Path) -> None: + width, height = 1080, 500 + left, top, row_h, half_w = 540, 95, 58, 360 + bound = 12.0 + content = svg_header( + width, height, + "Native AVX2 kernel versus independent compiler oracle", + "Negative values mean the SmartParallel Native Sequential kernel was faster; the release gate allows +10% or +0.5 µs.", + ) + content.append(f'') + for tick in [-10, -5, 0, 5, 10]: + x = left + half_w * tick / bound + content += [ + f'', + f'{tick:+d}%', + ] + for i, row in enumerate(summary): + y = top + i * row_h + value = float(row["native_kernel_delta_percent"]) + x2 = left + half_w * value / bound + x = min(left, x2) + bar = abs(x2 - left) + fill = "#3f7f63" if value <= 0 else "#b06a4b" + content += [ + f'{PRESET_LABELS[row["preset"]]}', + f'', + f'= 0 else "end"}" font-family="Segoe UI, Arial, sans-serif" font-size="12" fill="#263442">{value:+.2f}%', + ] + write_svg(out / "v1.5.0_native_kernel_vs_oracle.svg", content) + + +def plot_dispatch(summary: list[dict[str, str]], out: Path) -> None: + width, height = 1080, 500 + left, top, row_h, half_w = 540, 95, 58, 390 + bound = 8.5 + content = svg_header( + width, height, + "Stable Auto dispatch overhead", + "Point estimate and robust 95% interval from adjacent batched ABBA/BAAB comparisons; failure requires the lower bound to exceed +1 µs.", + ) + for tick in [-8, -4, 0, 1, 4, 8]: + x = left + half_w * tick / bound + stroke = "#b04a4a" if tick == 1 else "#e5e9ee" + width_line = 2 if tick == 1 else 1 + dash = ' stroke-dasharray="6 4"' if tick == 1 else "" + content += [ + f'', + f'{tick:+d} µs', + ] + for i, row in enumerate(summary): + y = top + i * row_h + 18 + center = float(row["batched_dispatch_overhead_ns"]) / 1000.0 + low = float(row["dispatch_ci_lower_ns"]) / 1000.0 + high = float(row["dispatch_ci_upper_ns"]) / 1000.0 + x_low = left + half_w * max(-bound, min(bound, low)) / bound + x_high = left + half_w * max(-bound, min(bound, high)) / bound + x_center = left + half_w * max(-bound, min(bound, center)) / bound + content += [ + f'{PRESET_LABELS[row["preset"]]}', + f'', + f'', + f'{center:+.3f} µs', + ] + write_svg(out / "v1.5.0_dispatch_overhead.svg", content) + + +def plot_adaptation(summary: list[dict[str, str]], learning: list[dict[str, str]], out: Path) -> None: + width, height = 1120, 525 + left, top, row_h = 210, 92, 64 + by_preset: dict[str, list[dict[str, str]]] = defaultdict(list) + for row in learning: + by_preset[row["preset"]].append(row) + content = svg_header( + width, height, + "Initial learning and settled execution route", + "The two 1080p profiles initially preferred OpenCV, detected a changed regime, and switched once to Native Sequential.", + ) + for i, row in enumerate(summary): + preset = row["preset"] + entries = by_preset[preset] + initial = entries[0]["provisional_route"] + settled = row["auto_selected_route"] + switches = int(row["route_switch_count"]) + y = top + i * row_h + content += [ + f'{PRESET_LABELS[preset]}', + f'', + f'Initial: {html.escape(ROUTE_LABELS.get(initial, initial))}', + f'', + f'', + f'', + f'Settled: {html.escape(ROUTE_LABELS.get(settled, settled))}', + f'{switches} runtime switch{"es" if switches != 1 else ""}', + ] + write_svg(out / "v1.5.0_adaptive_route_map.svg", content) + + +def main() -> int: + args = parse_args() + summary = read_csv(args.summary_csv) + raw = read_csv(args.raw_csv) + learning = read_csv(args.learning_csv) + args.output_dir.mkdir(parents=True, exist_ok=True) + medians = steady_medians(raw) + plot_speedups(summary, medians, args.output_dir) + plot_route_regret(summary, args.output_dir) + plot_native_kernel(summary, args.output_dir) + plot_dispatch(summary, args.output_dir) + plot_adaptation(summary, learning, args.output_dir) + print(f"Generated v1.5 benchmark plots in {args.output_dir}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/publish_v15_benchmark_docs.py b/tools/publish_v15_benchmark_docs.py new file mode 100644 index 0000000..501eaa4 --- /dev/null +++ b/tools/publish_v15_benchmark_docs.py @@ -0,0 +1,280 @@ +#!/usr/bin/env python3 +"""Publish one validated SmartParallel v1.5 benchmark run into the docs tree.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +import re +import shutil +import statistics +import subprocess +import sys +import zipfile +from collections import defaultdict +from pathlib import Path + +PRESET_LABELS = { + "tiny_320x240": "320×240", + "small_640x480": "640×480", + "medium_1920x1080": "1920×1080", + "medium_1920x1080_roi": "1920×1080 ROI", + "large_3840x2160": "3840×2160", + "very_large_7680x4320": "7680×4320", +} +ROUTE_LABELS = { + "native_sequential": "Native Sequential", + "native_thread_pool": "Native ThreadPool", + "native_static_thread": "Native StaticThread", + "native_one_tbb": "Native oneTBB", + "opencv": "OpenCV", +} + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("publication_dir", type=Path) + parser.add_argument( + "docs_dir", + type=Path, + nargs="?", + default=Path(__file__).resolve().parents[1] / "docs/v1.5/assets/benchmarks", + ) + return parser.parse_args() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8-sig") as handle: + rows = list(csv.DictReader(handle)) + if not rows: + raise ValueError(f"{path} is empty") + return rows + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def geometric_mean(values: list[float]) -> float: + if not values or any(value <= 0 for value in values): + raise ValueError("geometric mean requires positive values") + return math.exp(sum(math.log(value) for value in values) / len(values)) + + +def steady_medians(raw_rows: list[dict[str, str]]) -> dict[str, dict[str, float]]: + grouped: dict[tuple[str, str], list[int]] = defaultdict(list) + for row in raw_rows: + if row["phase"] == "steady_state": + grouped[(row["preset"], row["implementation"])].append(int(row["duration_ns"])) + medians: dict[str, dict[str, float]] = defaultdict(dict) + for (preset, implementation), values in grouped.items(): + medians[preset][implementation] = float(statistics.median(values)) + return medians + + +def env_value(text: str, key: str) -> str: + match = re.search(rf"^{re.escape(key)}:\s*(.+)$", text, re.MULTILINE) + return match.group(1).strip() if match else "unknown" + + +def format_duration(ns: float) -> str: + if ns < 1_000: + return f"{ns:.0f} ns" + if ns < 1_000_000: + return f"{ns / 1_000:.1f} µs" + return f"{ns / 1_000_000:.3f} ms" + + +def main() -> int: + args = parse_args() + publication = args.publication_dir.resolve() + docs = args.docs_dir.resolve() + summary_path = publication / "v1.5.0_adaptive_routes.csv" + raw_path = publication / "v1.5.0_adaptive_routes_raw.csv" + learning_path = publication / "v1.5.0_adaptive_routes_learning.csv" + environment_path = publication / "v1.5.0_adaptive_routes_environment.txt" + report_path = publication / "v1.5.0_adaptive_routes_report.md" + required = [summary_path, raw_path, learning_path, environment_path, report_path] + missing = [str(path) for path in required if not path.exists()] + if missing: + raise FileNotFoundError(f"publication is incomplete: {missing}") + + summary = read_csv(summary_path) + raw = read_csv(raw_path) + learning = read_csv(learning_path) + if len(summary) != 6 or any(row.get("overall_pass") != "1" for row in summary): + raise ValueError("Only a validated 6/6 publication run can be published") + if any(row.get("correctness_pass", "").lower() not in {"1", "true", "yes"} + or int(row.get("mismatch_count", "1")) != 0 for row in raw): + raise ValueError("Raw publication data contains a correctness failure") + + docs.mkdir(parents=True, exist_ok=True) + plotter = Path(__file__).with_name("generate_v15_benchmark_plots.py") + subprocess.run( + [sys.executable, str(plotter), str(summary_path), str(raw_path), + str(learning_path), str(publication)], + check=True, + ) + + copied = { + "accepted-summary.csv": summary_path, + "accepted-learning.csv": learning_path, + "accepted-environment.txt": environment_path, + "accepted-publication-report.md": report_path, + } + for destination_name, source in copied.items(): + shutil.copy2(source, docs / destination_name) + for svg in sorted(publication.glob("v1.5.0_*.svg")): + shutil.copy2(svg, docs / svg.name) + + archive_members = [ + raw_path, learning_path, summary_path, environment_path, report_path, + ] + build_log = publication / "v1.5.0_build_vectorization.log" + if build_log.exists(): + archive_members.append(build_log) + archive_members.extend(sorted(publication.glob("v1.5.0_*.svg"))) + with zipfile.ZipFile(docs / "accepted-publication.zip", "w", zipfile.ZIP_DEFLATED) as archive: + for member in archive_members: + archive.write(member, member.name) + + medians = steady_medians(raw) + environment = environment_path.read_text(encoding="utf-8-sig") + rows = [] + for row in summary: + preset = row["preset"] + auto = medians[preset]["smart_auto"] + direct = medians[preset]["direct_sequential"] + opencv = medians[preset]["opencv_api"] + rows.append({ + "preset": preset, + "label": PRESET_LABELS[preset], + "width": int(row["width"]), + "height": int(row["height"]), + "stride_bytes": int(row["stride_bytes"]), + "settled_route": row["auto_selected_route"], + "settled_route_label": ROUTE_LABELS.get(row["auto_selected_route"], row["auto_selected_route"]), + "route_switch_count": int(row["route_switch_count"]), + "auto_median_ns": int(float(auto)), + "direct_sequential_median_ns": int(float(direct)), + "opencv_api_median_ns": int(float(opencv)), + "speedup_vs_direct_sequential": direct / auto, + "speedup_vs_opencv_api": opencv / auto, + "route_selection_regret_percent": float(row["route_selection_regret_percent"]), + "dispatch_overhead_ns": int(row["batched_dispatch_overhead_ns"]), + "dispatch_ci_lower_ns": int(row["dispatch_ci_lower_ns"]), + "dispatch_ci_upper_ns": int(row["dispatch_ci_upper_ns"]), + "native_kernel_delta_percent": float(row["native_kernel_delta_percent"]), + "overall_pass": bool(int(row["overall_pass"])), + }) + + metrics = { + "release": "1.5.0", + "title": "Adaptive Execution Routes", + "operation": "threshold_u8_binary", + "publication_directory": publication.name, + "raw_schema_version": sorted({row["schema_version"] for row in raw})[0], + "learning_schema_version": sorted({row["schema_version"] for row in learning})[0], + "steady_state_repetitions": int(raw[0]["requested_repetitions"]), + "raw_sample_count": len(raw), + "correctness_failures": 0, + "authentication_failures": 0, + "combined_gate_passes": sum(int(row["overall_pass"]) for row in summary), + "combined_gate_total": len(summary), + "native_kernel": summary[0]["native_kernel"], + "logical_threads": env_value(environment, "Logical threads"), + "worker_budget": env_value(environment, "SmartParallel worker budget"), + "opencv_version": env_value(environment, "OpenCV version"), + "opencv_threads": env_value(environment, "OpenCV threads"), + "opencv_opencl": env_value(environment, "OpenCV OpenCL enabled"), + "geometric_mean_speedup_vs_direct_sequential": geometric_mean( + [row["speedup_vs_direct_sequential"] for row in rows] + ), + "geometric_mean_speedup_vs_opencv_api": geometric_mean( + [row["speedup_vs_opencv_api"] for row in rows] + ), + "hashes": { + "raw_csv_sha256": sha256(raw_path), + "learning_csv_sha256": sha256(learning_path), + "summary_csv_sha256": sha256(summary_path), + "environment_sha256": sha256(environment_path), + "publication_report_sha256": sha256(report_path), + }, + "presets": rows, + } + (docs / "benchmark-metrics.json").write_text( + json.dumps(metrics, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" + ) + + result_lines = [ + "# Generated v1.5 benchmark results", + "", + "> Generated from the accepted Windows/MSVC publication evidence. Do not edit by hand; rerun `tools/publish_v15_benchmark_docs.py`.", + "", + f"- Publication: `{publication.name}`", + f"- Raw samples: **{len(raw):,}**", + f"- Correctness/authentication failures: **0**", + f"- Combined proof gates: **{metrics['combined_gate_passes']}/{metrics['combined_gate_total']} passed**", + f"- Native kernel: **{metrics['native_kernel']}**", + f"- Geometric-mean Auto speedup versus direct sequential: **{metrics['geometric_mean_speedup_vs_direct_sequential']:.2f}×**", + f"- Geometric-mean Auto speedup versus direct OpenCV API: **{metrics['geometric_mean_speedup_vs_opencv_api']:.2f}×**", + "", + "| Preset | Settled route | Auto median | Speedup vs direct | Speedup vs OpenCV API | Route regret | Runtime switches |", + "|---|---|---:|---:|---:|---:|---:|", + ] + for row in rows: + result_lines.append( + f"| {row['label']} | {row['settled_route_label']} | " + f"{format_duration(row['auto_median_ns'])} | " + f"{row['speedup_vs_direct_sequential']:.2f}× | " + f"{row['speedup_vs_opencv_api']:.2f}× | " + f"{row['route_selection_regret_percent']:.2f}% | " + f"{row['route_switch_count']} |" + ) + result_lines += [ + "", + "All figures and aggregate values are machine-specific. The release claim is that Auto selected a route inside the declared equivalence gate on this machine, not that one provider is universally fastest.", + ] + (docs / "generated-results.md").write_text("\n".join(result_lines) + "\n", encoding="utf-8") + + hash_lines = [f"{value} {key}" for key, value in metrics["hashes"].items()] + (docs / "source-hashes.txt").write_text("\n".join(hash_lines) + "\n", encoding="utf-8") + + readme = """# SmartParallel v1.5 benchmark assets + +These files are generated from the accepted v1.5 publication run and support the public benchmark report. + +- `generated-results.md` — generated table and aggregate metrics. +- `benchmark-metrics.json` — machine-readable accepted metrics. +- `accepted-summary.csv` — six-preset proof-gate summary. +- `accepted-learning.csv` — route-learning and current-context adaptation evidence. +- `accepted-environment.txt` — compiler, OpenCV, worker-budget, and build configuration. +- `accepted-publication-report.md` — analyzer-generated release-gate report. +- `source-hashes.txt` — hashes of the accepted source evidence. +- `accepted-publication.zip` — full accepted raw evidence, learning data, environment, report, build log, and figures. +- `v1.5.0_*.svg` — dependency-free publication figures. + +Regenerate a publication run with: + +```bat +set "VCPKG_ROOT=D:\\Tools\\vcpkg" && scripts\\validation\\run_v15_adaptive_routes_release_validation.bat 31 +``` + +Publish a validated run into this directory with: + +```bat +py -3 tools\\publish_v15_benchmark_docs.py validation\\output\\v1.5.0_adaptive_routes\\publication_ +``` + +Performance is machine-specific. Do not copy values from one machine into universal performance claims. +""" + (docs / "README.md").write_text(readme, encoding="utf-8") + print(f"Published v1.5 documentation assets to {docs}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/validation/README.md b/validation/README.md index d2d7feb..a9bbbc9 100644 --- a/validation/README.md +++ b/validation/README.md @@ -2,15 +2,22 @@ The validation directory contains deterministic correctness, hardening, measurement, and recorded-output programs. -## Current release validation +## Current v1.5 release validation -The complete v1.1 real-world run is documented in: +The complete adaptive-route publication is documented in: -- [Benchmark results](../docs/v1.1/benchmarks.md) -- [Methodology](../docs/v1.1/benchmark-methodology.md) -- [Reproduction](../docs/v1.1/benchmark-reproduction.md) +- [Benchmark results](../docs/v1.5/benchmarks.md) +- [Benchmark methodology](../docs/v1.5/benchmark-methodology.md) +- [Benchmark reproduction](../docs/v1.5/benchmark-reproduction.md) +- [Deterministic validation](../docs/v1.5/validation.md) -Recorded final outputs are under `validation/output/real_world/`. +The accepted release evidence is under: + +```text +validation/output/v1.5.0_adaptive_routes/publication_20260728_184110/ +``` + +The accepted run contains 2,238 correct and authenticated samples and passes all 6/6 combined proof gates. Performance is machine-specific. ## CMake validation preset @@ -20,6 +27,8 @@ cmake --build --preset validation ctest --preset validation ``` -## Historical outputs +## Retained outputs -Other CSV files under `validation/output/` support the v1.0 decision-quality, OpenCV, scientific, and overhead documentation. The corresponding archived benchmark suite is under `benchmarks/v1.0.0/`. +- `validation/output/real_world/` supports the retained v1.1 integration report. +- v1.4 summary/raw CSVs support the parallel-algorithm report. +- Other top-level CSV files support historical v1.0 decision-quality, OpenCV, scientific, and overhead documentation. diff --git a/validation/output/v1.4.0_parallel_algorithms.csv b/validation/output/v1.4.0_parallel_algorithms.csv index d23aa7e..715322c 100644 --- a/validation/output/v1.4.0_parallel_algorithms.csv +++ b/validation/output/v1.4.0_parallel_algorithms.csv @@ -1,81 +1,65 @@ schema_version,algorithm,mode,repetitions,iterations,median_ms,min_ms,max_ms,sequential_median_ms,speedup,checksum,expected_checksum,correct,backend_authenticated,observed_backend,parallel_observed -1.4.0,parallel_for_each,sequential,7,262144,3.762600,3.732400,3.793900,3.762600,1.000000,12394695018371502475,12394695018371502475,1,1,sequential,0 -1.4.0,parallel_for_each,automatic,7,262144,1.081300,1.058500,1.157100,3.762600,3.479700,12394695018371502475,12394695018371502475,1,1,thread_pool,1 -1.4.0,parallel_for_each,thread_pool,7,262144,1.193600,1.051100,1.497800,3.762600,3.152312,12394695018371502475,12394695018371502475,1,1,thread_pool,1 -1.4.0,parallel_for_each,static_thread,7,262144,1.389300,1.289100,1.627500,3.762600,2.708270,12394695018371502475,12394695018371502475,1,1,static_thread,1 -1.4.0,parallel_for_each,one_tbb,7,262144,1.106500,1.038500,1.395800,3.762600,3.400452,12394695018371502475,12394695018371502475,1,1,one_tbb,1 -1.4.0,parallel_transform,sequential,7,262144,3.751500,3.736600,3.782400,3.751500,1.000000,7293375088876815277,7293375088876815277,1,1,sequential,0 -1.4.0,parallel_transform,automatic,7,262144,1.066100,1.044800,1.172700,3.751500,3.518901,7293375088876815277,7293375088876815277,1,1,thread_pool,1 -1.4.0,parallel_transform,thread_pool,7,262144,1.063400,1.044400,1.304900,3.751500,3.527835,7293375088876815277,7293375088876815277,1,1,thread_pool,1 -1.4.0,parallel_transform,static_thread,7,262144,1.479800,1.419700,2.259000,3.751500,2.535140,7293375088876815277,7293375088876815277,1,1,static_thread,1 -1.4.0,parallel_transform,one_tbb,7,262144,1.155000,1.139800,1.356300,3.751500,3.248052,7293375088876815277,7293375088876815277,1,1,one_tbb,1 -1.4.0,parallel_transform_binary,sequential,7,262144,3.861700,3.844900,3.921600,3.861700,1.000000,3284516397851362210,3284516397851362210,1,1,sequential,0 -1.4.0,parallel_transform_binary,automatic,7,262144,1.107100,1.063400,1.686500,3.861700,3.488122,3284516397851362210,3284516397851362210,1,1,thread_pool,1 -1.4.0,parallel_transform_binary,thread_pool,7,262144,1.121800,1.076700,1.536300,3.861700,3.442414,3284516397851362210,3284516397851362210,1,1,thread_pool,1 -1.4.0,parallel_transform_binary,static_thread,7,262144,1.460100,1.341100,1.730500,3.861700,2.644819,3284516397851362210,3284516397851362210,1,1,static_thread,1 -1.4.0,parallel_transform_binary,one_tbb,7,262144,1.212500,1.144100,1.270100,3.861700,3.184907,3284516397851362210,3284516397851362210,1,1,one_tbb,1 -1.4.0,parallel_copy,sequential,7,1048576,1.117300,0.844700,1.383300,1.117300,1.000000,3108441649531108808,3108441649531108808,1,1,sequential,0 -1.4.0,parallel_copy,automatic,7,1048576,1.155900,0.841400,1.525600,1.117300,0.966606,3108441649531108808,3108441649531108808,1,1,sequential,0 -1.4.0,parallel_copy,thread_pool,7,1048576,1.211600,1.054900,1.555900,1.117300,0.922169,3108441649531108808,3108441649531108808,1,1,thread_pool,1 -1.4.0,parallel_copy,static_thread,7,1048576,1.617000,1.371700,1.955200,1.117300,0.690971,3108441649531108808,3108441649531108808,1,1,static_thread,1 -1.4.0,parallel_copy,one_tbb,7,1048576,1.065700,0.881300,1.275500,1.117300,1.048419,3108441649531108808,3108441649531108808,1,1,one_tbb,1 -1.4.0,parallel_fill,sequential,7,1048576,1.086000,0.454000,1.298300,1.086000,1.000000,8741389093274774276,8741389093274774276,1,1,sequential,0 -1.4.0,parallel_fill,automatic,7,1048576,0.406900,0.340500,0.755100,1.086000,2.668960,8741389093274774276,8741389093274774276,1,1,thread_pool,1 -1.4.0,parallel_fill,thread_pool,7,1048576,0.439100,0.347400,0.812400,1.086000,2.473241,8741389093274774276,8741389093274774276,1,1,thread_pool,1 -1.4.0,parallel_fill,static_thread,7,1048576,1.069800,0.739800,1.131600,1.086000,1.015143,8741389093274774276,8741389093274774276,1,1,static_thread,1 -1.4.0,parallel_fill,one_tbb,7,1048576,0.538100,0.361900,0.849900,1.086000,2.018212,8741389093274774276,8741389093274774276,1,1,one_tbb,1 -1.4.0,parallel_generate,sequential,7,262144,3.695700,3.675600,3.735900,3.695700,1.000000,4493962011273834418,4493962011273834418,1,1,sequential,0 -1.4.0,parallel_generate,automatic,7,262144,1.098000,1.027100,1.497500,3.695700,3.365847,4493962011273834418,4493962011273834418,1,1,thread_pool,1 -1.4.0,parallel_generate,thread_pool,7,262144,1.065300,1.017400,1.417400,3.695700,3.469164,4493962011273834418,4493962011273834418,1,1,thread_pool,1 -1.4.0,parallel_generate,static_thread,7,262144,1.363700,1.339800,1.541000,3.695700,2.710054,4493962011273834418,4493962011273834418,1,1,static_thread,1 -1.4.0,parallel_generate,one_tbb,7,262144,1.026700,1.007200,1.312500,3.695700,3.599591,4493962011273834418,4493962011273834418,1,1,one_tbb,1 -1.4.0,parallel_reduce,sequential,7,262144,0.032500,0.026900,0.051900,0.032500,1.000000,8590433753,8590433753,1,1,sequential,0 -1.4.0,parallel_reduce,automatic,7,262144,0.029200,0.027100,0.039700,0.032500,1.113014,8590433753,8590433753,1,1,sequential,0 -1.4.0,parallel_reduce,thread_pool,7,262144,0.067200,0.057100,0.128500,0.032500,0.483631,8590433753,8590433753,1,1,thread_pool,1 -1.4.0,parallel_reduce,static_thread,7,262144,0.355900,0.297900,0.644800,0.032500,0.091318,8590433753,8590433753,1,1,static_thread,1 -1.4.0,parallel_reduce,one_tbb,7,262144,0.075500,0.059000,0.095200,0.032500,0.430464,8590433753,8590433753,1,1,one_tbb,1 -1.4.0,parallel_transform_reduce,sequential,7,262144,3.785800,3.769900,3.859800,3.785800,1.000000,8587943456,8587943456,1,1,sequential,0 -1.4.0,parallel_transform_reduce,automatic,7,262144,1.071200,1.044200,1.330800,3.785800,3.534167,8587943456,8587943456,1,1,thread_pool,1 -1.4.0,parallel_transform_reduce,thread_pool,7,262144,1.061200,1.043700,1.321700,3.785800,3.567471,8587943456,8587943456,1,1,thread_pool,1 -1.4.0,parallel_transform_reduce,static_thread,7,262144,1.413300,1.317000,1.613800,3.785800,2.678695,8587943456,8587943456,1,1,static_thread,1 -1.4.0,parallel_transform_reduce,one_tbb,7,262144,1.168900,1.156200,1.196500,3.785800,3.238771,8587943456,8587943456,1,1,one_tbb,1 -1.4.0,parallel_transform_reduce_binary,sequential,7,262144,1.778400,1.724900,2.058700,1.778400,1.000000,8595455441,8595455441,1,1,sequential,0 -1.4.0,parallel_transform_reduce_binary,automatic,7,262144,0.525300,0.469400,0.677800,1.778400,3.385494,8595455441,8595455441,1,1,thread_pool,1 -1.4.0,parallel_transform_reduce_binary,thread_pool,7,262144,0.509000,0.475800,0.612800,1.778400,3.493910,8595455441,8595455441,1,1,thread_pool,1 -1.4.0,parallel_transform_reduce_binary,static_thread,7,262144,0.860100,0.758600,1.005900,1.778400,2.067667,8595455441,8595455441,1,1,static_thread,1 -1.4.0,parallel_transform_reduce_binary,one_tbb,7,262144,0.478600,0.463500,0.539900,1.778400,3.715838,8595455441,8595455441,1,1,one_tbb,1 -1.4.0,parallel_count,sequential,7,262144,0.034100,0.033800,0.034800,0.034100,1.000000,8457,8457,1,1,sequential,0 -1.4.0,parallel_count,automatic,7,262144,0.034900,0.034600,0.038400,0.034100,0.977077,8457,8457,1,1,sequential,0 -1.4.0,parallel_count,thread_pool,7,262144,0.083500,0.067800,0.240700,0.034100,0.408383,8457,8457,1,1,thread_pool,1 -1.4.0,parallel_count,static_thread,7,262144,0.373700,0.325400,0.433300,0.034100,0.091250,8457,8457,1,1,static_thread,1 -1.4.0,parallel_count,one_tbb,7,262144,0.052600,0.049800,0.092400,0.034100,0.648289,8457,8457,1,1,one_tbb,1 -1.4.0,parallel_count_if,sequential,7,262144,1.145900,1.139800,1.170000,1.145900,1.000000,32863,32863,1,1,sequential,0 -1.4.0,parallel_count_if,automatic,7,262144,0.375200,0.369200,0.439300,1.145900,3.054104,32863,32863,1,1,thread_pool,1 -1.4.0,parallel_count_if,thread_pool,7,262144,0.391400,0.364000,0.566500,1.145900,2.927695,32863,32863,1,1,thread_pool,1 -1.4.0,parallel_count_if,static_thread,7,262144,0.677400,0.591500,0.853000,1.145900,1.691615,32863,32863,1,1,static_thread,1 -1.4.0,parallel_count_if,one_tbb,7,262144,0.365200,0.343600,0.435300,1.145900,3.137733,32863,32863,1,1,one_tbb,1 -1.4.0,parallel_any_of,sequential,7,262144,0.068500,0.068200,0.097000,0.068500,1.000000,1,1,1,1,sequential,0 -1.4.0,parallel_any_of,automatic,7,262144,0.068400,0.068200,0.071600,0.068500,1.001462,1,1,1,1,sequential,0 -1.4.0,parallel_any_of,thread_pool,7,262144,0.080000,0.076400,0.093700,0.068500,0.856250,1,1,1,1,thread_pool,1 -1.4.0,parallel_any_of,static_thread,7,262144,0.313300,0.278600,1.293400,0.068500,0.218640,1,1,1,1,static_thread,1 -1.4.0,parallel_any_of,one_tbb,7,262144,0.054200,0.049400,0.059600,0.068500,1.263838,1,1,1,1,one_tbb,1 -1.4.0,parallel_all_of,sequential,7,262144,0.068100,0.067600,0.075100,0.068100,1.000000,1,1,1,1,sequential,0 -1.4.0,parallel_all_of,automatic,7,262144,0.068100,0.068000,0.075600,0.068100,1.000000,1,1,1,1,sequential,0 -1.4.0,parallel_all_of,thread_pool,7,262144,0.072300,0.066500,0.098000,0.068100,0.941909,1,1,1,1,thread_pool,1 -1.4.0,parallel_all_of,static_thread,7,262144,0.336400,0.313600,1.360000,0.068100,0.202438,1,1,1,1,static_thread,1 -1.4.0,parallel_all_of,one_tbb,7,262144,0.078800,0.058200,0.113100,0.068100,0.864213,1,1,1,1,one_tbb,1 -1.4.0,parallel_none_of,sequential,7,262144,0.068300,0.067900,0.074900,0.068300,1.000000,1,1,1,1,sequential,0 -1.4.0,parallel_none_of,automatic,7,262144,0.068500,0.068400,0.073000,0.068300,0.997080,1,1,1,1,sequential,0 -1.4.0,parallel_none_of,thread_pool,7,262144,0.069700,0.059900,0.084400,0.068300,0.979914,1,1,1,1,thread_pool,1 -1.4.0,parallel_none_of,static_thread,7,262144,0.425200,0.341300,1.582700,0.068300,0.160630,1,1,1,1,static_thread,1 -1.4.0,parallel_none_of,one_tbb,7,262144,0.131400,0.120500,0.157000,0.068300,0.519787,1,1,1,1,one_tbb,1 -1.4.0,parallel_find,sequential,7,262144,0.029100,0.029000,0.031300,0.029100,1.000000,262143,262143,1,1,sequential,0 -1.4.0,parallel_find,automatic,7,262144,0.029500,0.029400,0.033200,0.029100,0.986441,262143,262143,1,1,sequential,0 -1.4.0,parallel_find,thread_pool,7,262144,0.088000,0.071500,0.169700,0.029100,0.330682,262143,262143,1,1,thread_pool,1 -1.4.0,parallel_find,static_thread,7,262144,0.350200,0.292900,0.392100,0.029100,0.083095,262143,262143,1,1,static_thread,1 -1.4.0,parallel_find,one_tbb,7,262144,0.056600,0.053700,0.073300,0.029100,0.514134,262143,262143,1,1,one_tbb,1 -1.4.0,parallel_find_if,sequential,7,262144,0.068000,0.068000,0.110600,0.068000,1.000000,262143,262143,1,1,sequential,0 -1.4.0,parallel_find_if,automatic,7,262144,0.068500,0.068100,0.071900,0.068000,0.992701,262143,262143,1,1,sequential,0 -1.4.0,parallel_find_if,thread_pool,7,262144,0.070600,0.066900,0.096700,0.068000,0.963173,262143,262143,1,1,thread_pool,1 -1.4.0,parallel_find_if,static_thread,7,262144,0.313100,0.276000,0.445900,0.068000,0.217183,262143,262143,1,1,static_thread,1 -1.4.0,parallel_find_if,one_tbb,7,262144,0.053700,0.050500,0.072100,0.068000,1.266294,262143,262143,1,1,one_tbb,1 +1.4.0,parallel_for_each,sequential,3,262144,3.156184,3.135643,3.345454,3.156184,1.000000,12394695018371502475,12394695018371502475,1,1,sequential,0 +1.4.0,parallel_for_each,automatic,3,262144,1.257422,1.073289,1.577697,3.156184,2.510044,12394695018371502475,12394695018371502475,1,1,thread_pool,1 +1.4.0,parallel_for_each,thread_pool,3,262144,1.050916,0.888466,1.372453,3.156184,3.003270,12394695018371502475,12394695018371502475,1,1,thread_pool,1 +1.4.0,parallel_for_each,static_thread,3,262144,0.979881,0.904890,1.087240,3.156184,3.220987,12394695018371502475,12394695018371502475,1,1,static_thread,1 +1.4.0,parallel_transform,sequential,3,262144,3.188772,3.147751,3.363020,3.188772,1.000000,7293375088876815277,7293375088876815277,1,1,sequential,0 +1.4.0,parallel_transform,automatic,3,262144,1.269100,1.243231,1.353554,3.188772,2.512625,7293375088876815277,7293375088876815277,1,1,thread_pool,1 +1.4.0,parallel_transform,thread_pool,3,262144,1.281658,1.264021,1.504949,3.188772,2.488005,7293375088876815277,7293375088876815277,1,1,thread_pool,1 +1.4.0,parallel_transform,static_thread,3,262144,0.917359,0.882067,1.011889,3.188772,3.476035,7293375088876815277,7293375088876815277,1,1,static_thread,1 +1.4.0,parallel_transform_binary,sequential,3,262144,3.578399,3.550838,3.604568,3.578399,1.000000,3284516397851362210,3284516397851362210,1,1,sequential,0 +1.4.0,parallel_transform_binary,automatic,3,262144,1.405732,1.377249,1.466622,3.578399,2.545577,3284516397851362210,3284516397851362210,1,1,thread_pool,1 +1.4.0,parallel_transform_binary,thread_pool,3,262144,1.440743,1.404931,1.460853,3.578399,2.483718,3284516397851362210,3284516397851362210,1,1,thread_pool,1 +1.4.0,parallel_transform_binary,static_thread,3,262144,1.088181,1.057676,1.134581,3.578399,3.288423,3284516397851362210,3284516397851362210,1,1,static_thread,1 +1.4.0,parallel_copy,sequential,3,1048576,0.221929,0.217772,0.228278,0.221929,1.000000,3108441649531108808,3108441649531108808,1,1,sequential,0 +1.4.0,parallel_copy,automatic,3,1048576,0.231192,0.222159,0.240146,0.221929,0.959934,3108441649531108808,3108441649531108808,1,1,sequential,0 +1.4.0,parallel_copy,thread_pool,3,1048576,0.267046,0.136652,0.290019,0.221929,0.831052,3108441649531108808,3108441649531108808,1,1,thread_pool,1 +1.4.0,parallel_copy,static_thread,3,1048576,0.189962,0.163823,0.192125,0.221929,1.168281,3108441649531108808,3108441649531108808,1,1,static_thread,1 +1.4.0,parallel_fill,sequential,3,1048576,0.142771,0.142621,0.143112,0.142771,1.000000,8741389093274774276,8741389093274774276,1,1,sequential,0 +1.4.0,parallel_fill,automatic,3,1048576,0.179977,0.146217,0.183242,0.142771,0.793274,8741389093274774276,8741389093274774276,1,1,mixed,1 +1.4.0,parallel_fill,thread_pool,3,1048576,0.158785,0.146948,0.412140,0.142771,0.899147,8741389093274774276,8741389093274774276,1,1,thread_pool,1 +1.4.0,parallel_fill,static_thread,3,1048576,0.170833,0.168039,0.171384,0.142771,0.835734,8741389093274774276,8741389093274774276,1,1,static_thread,1 +1.4.0,parallel_generate,sequential,3,262144,3.029766,3.016006,3.046671,3.029766,1.000000,4493962011273834418,4493962011273834418,1,1,sequential,0 +1.4.0,parallel_generate,automatic,3,262144,1.169342,0.979271,1.189762,3.029766,2.591001,4493962011273834418,4493962011273834418,1,1,thread_pool,1 +1.4.0,parallel_generate,thread_pool,3,262144,1.017847,0.810099,1.179286,3.029766,2.976642,4493962011273834418,4493962011273834418,1,1,thread_pool,1 +1.4.0,parallel_generate,static_thread,3,262144,0.847715,0.829188,0.869748,3.029766,3.574038,4493962011273834418,4493962011273834418,1,1,static_thread,1 +1.4.0,parallel_reduce,sequential,3,262144,0.036373,0.035993,0.036664,0.036373,1.000000,8590433753,8590433753,1,1,sequential,0 +1.4.0,parallel_reduce,automatic,3,262144,0.036975,0.036524,0.037225,0.036373,0.983719,8590433753,8590433753,1,1,sequential,0 +1.4.0,parallel_reduce,thread_pool,3,262144,0.064606,0.052978,0.066558,0.036373,0.562997,8590433753,8590433753,1,1,thread_pool,1 +1.4.0,parallel_reduce,static_thread,3,262144,0.097204,0.097184,0.167799,0.036373,0.374192,8590433753,8590433753,1,1,static_thread,1 +1.4.0,parallel_transform_reduce,sequential,3,262144,3.040653,3.011991,3.047503,3.040653,1.000000,8587943456,8587943456,1,1,sequential,0 +1.4.0,parallel_transform_reduce,automatic,3,262144,0.865242,0.853323,1.271553,3.040653,3.514223,8587943456,8587943456,1,1,thread_pool,1 +1.4.0,parallel_transform_reduce,thread_pool,3,262144,1.218274,0.853444,1.242430,3.040653,2.495870,8587943456,8587943456,1,1,thread_pool,1 +1.4.0,parallel_transform_reduce,static_thread,3,262144,1.422196,1.414074,1.455766,3.040653,2.137999,8587943456,8587943456,1,1,static_thread,1 +1.4.0,parallel_transform_reduce_binary,sequential,3,262144,1.401736,1.377269,1.401756,1.401736,1.000000,8595455441,8595455441,1,1,sequential,0 +1.4.0,parallel_transform_reduce_binary,automatic,3,262144,0.592628,0.579018,0.595662,1.401736,2.365288,8595455441,8595455441,1,1,thread_pool,1 +1.4.0,parallel_transform_reduce_binary,thread_pool,3,262144,0.425160,0.414764,0.455004,1.401736,3.296961,8595455441,8595455441,1,1,thread_pool,1 +1.4.0,parallel_transform_reduce_binary,static_thread,3,262144,0.499029,0.453161,0.587190,1.401736,2.808927,8595455441,8595455441,1,1,static_thread,1 +1.4.0,parallel_count,sequential,3,262144,0.041761,0.041752,0.041892,0.041761,1.000000,8457,8457,1,1,sequential,0 +1.4.0,parallel_count,automatic,3,262144,0.042232,0.042213,0.042984,0.041761,0.988847,8457,8457,1,1,sequential,0 +1.4.0,parallel_count,thread_pool,3,262144,0.091245,0.089002,0.173207,0.041761,0.457680,8457,8457,1,1,thread_pool,1 +1.4.0,parallel_count,static_thread,3,262144,0.114609,0.110133,0.164333,0.041761,0.364378,8457,8457,1,1,static_thread,1 +1.4.0,parallel_count_if,sequential,3,262144,0.995554,0.988964,1.126218,0.995554,1.000000,32863,32863,1,1,sequential,0 +1.4.0,parallel_count_if,automatic,3,262144,0.293315,0.290660,0.479821,0.995554,3.394146,32863,32863,1,1,thread_pool,1 +1.4.0,parallel_count_if,thread_pool,3,262144,0.293635,0.287826,0.400793,0.995554,3.390447,32863,32863,1,1,thread_pool,1 +1.4.0,parallel_count_if,static_thread,3,262144,0.529604,0.527842,0.544246,0.995554,1.879808,32863,32863,1,1,static_thread,1 +1.4.0,parallel_any_of,sequential,3,262144,0.053519,0.048361,0.053520,0.053519,1.000000,1,1,1,1,sequential,0 +1.4.0,parallel_any_of,automatic,3,262144,0.049794,0.049784,0.058316,0.053519,1.074808,1,1,1,1,sequential,0 +1.4.0,parallel_any_of,thread_pool,3,262144,0.094409,0.086418,0.114329,0.053519,0.566885,1,1,1,1,thread_pool,1 +1.4.0,parallel_any_of,static_thread,3,262144,0.160608,0.153518,0.174218,0.053519,0.333227,1,1,1,1,static_thread,1 +1.4.0,parallel_all_of,sequential,3,262144,0.049804,0.049623,0.106828,0.049804,1.000000,1,1,1,1,sequential,0 +1.4.0,parallel_all_of,automatic,3,262144,0.050024,0.049824,0.050395,0.049804,0.995602,1,1,1,1,sequential,0 +1.4.0,parallel_all_of,thread_pool,3,262144,0.116833,0.115370,0.162591,0.049804,0.426284,1,1,1,1,thread_pool,1 +1.4.0,parallel_all_of,static_thread,3,262144,0.160949,0.145796,0.183737,0.049804,0.309440,1,1,1,1,static_thread,1 +1.4.0,parallel_none_of,sequential,3,262144,0.055462,0.054641,0.056613,0.055462,1.000000,1,1,1,1,sequential,0 +1.4.0,parallel_none_of,automatic,3,262144,0.049894,0.049854,0.052237,0.055462,1.111597,1,1,1,1,sequential,0 +1.4.0,parallel_none_of,thread_pool,3,262144,0.087099,0.086347,0.103864,0.055462,0.636770,1,1,1,1,thread_pool,1 +1.4.0,parallel_none_of,static_thread,3,262144,0.229200,0.115380,0.317380,0.055462,0.241981,1,1,1,1,static_thread,1 +1.4.0,parallel_find,sequential,3,262144,0.050865,0.049454,0.051306,0.050865,1.000000,262143,262143,1,1,sequential,0 +1.4.0,parallel_find,automatic,3,262144,0.047851,0.047140,0.049454,0.050865,1.062987,262143,262143,1,1,sequential,0 +1.4.0,parallel_find,thread_pool,3,262144,0.093909,0.088251,0.117744,0.050865,0.541641,262143,262143,1,1,thread_pool,1 +1.4.0,parallel_find,static_thread,3,262144,0.160047,0.122571,0.172205,0.050865,0.317813,262143,262143,1,1,static_thread,1 +1.4.0,parallel_find_if,sequential,3,262144,0.055673,0.054721,0.065617,0.055673,1.000000,262143,262143,1,1,sequential,0 +1.4.0,parallel_find_if,automatic,3,262144,0.051236,0.049784,0.059178,0.055673,1.086599,262143,262143,1,1,sequential,0 +1.4.0,parallel_find_if,thread_pool,3,262144,0.081330,0.081281,0.116292,0.055673,0.684532,262143,262143,1,1,thread_pool,1 +1.4.0,parallel_find_if,static_thread,3,262144,0.113077,0.108530,0.126026,0.055673,0.492346,262143,262143,1,1,static_thread,1 diff --git a/vcpkg.json b/vcpkg.json index 0f2c49e..d5d0426 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -1,7 +1,7 @@ { "name": "smartparallel", - "version-string": "1.4.0", - "description": "Adaptive parallel scheduling for modern C++", + "version-string": "1.5.0", + "description": "Adaptive parallel execution for modern C++", "builtin-baseline": "a0400024711b283056538ac19ced80b91a83c24c", "dependencies": [ "tbb" @@ -19,6 +19,12 @@ "opencv4" ] }, + "vision-opencv": { + "description": "OpenCV provider for v1.5 adaptive vision execution routes", + "dependencies": [ + "opencv4" + ] + }, "real-world-benchmarks": { "description": "All external dependencies for SmartParallel real-world benchmarks", "dependencies": [ diff --git a/vision/CMakeLists.txt b/vision/CMakeLists.txt new file mode 100644 index 0000000..52a3062 --- /dev/null +++ b/vision/CMakeLists.txt @@ -0,0 +1,76 @@ +add_library( + smart_parallel_vision + src/threshold.cpp + src/threshold_kernel_dispatch.cpp + src/threshold_kernel_x86_features.cpp + src/threshold_kernel_sse2.cpp + src/threshold_kernel_avx2.cpp +) + +add_library(SmartParallel::vision ALIAS smart_parallel_vision) + +set_target_properties( + smart_parallel_vision + PROPERTIES + EXPORT_NAME vision + VERSION "${PROJECT_VERSION}" + SOVERSION "${PROJECT_VERSION_MAJOR}" +) + +target_compile_features(smart_parallel_vision PUBLIC cxx_std_17) +target_include_directories( + smart_parallel_vision + PUBLIC + $ + $ + $ +) +target_link_libraries(smart_parallel_vision PUBLIC SmartParallel::smart_parallel) + +if(SMARTPARALLEL_VISION_HAS_OPENCV) + target_sources(smart_parallel_vision PRIVATE src/opencv_provider.cpp) + target_compile_definitions(smart_parallel_vision PUBLIC SMARTPARALLEL_VISION_HAS_OPENCV=1) + if(TARGET opencv_core AND TARGET opencv_imgproc) + target_link_libraries(smart_parallel_vision PRIVATE opencv_core opencv_imgproc) + else() + target_include_directories(smart_parallel_vision PRIVATE ${OpenCV_INCLUDE_DIRS}) + target_link_libraries(smart_parallel_vision PRIVATE ${OpenCV_LIBS}) + endif() +else() + target_sources(smart_parallel_vision PRIVATE src/opencv_provider_stub.cpp) + target_compile_definitions(smart_parallel_vision PUBLIC SMARTPARALLEL_VISION_HAS_OPENCV=0) +endif() + +# The SIMD kernels live in isolated translation units so the rest of the +# library remains compatible with the baseline architecture. Runtime CPU +# detection prevents unsupported instructions from being executed. +if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64|i[3-6]86|x86)$") + if(MSVC) + set_source_files_properties( + src/threshold_kernel_x86_features.cpp + PROPERTIES COMPILE_OPTIONS "/arch:AVX" + ) + set_source_files_properties( + src/threshold_kernel_avx2.cpp + PROPERTIES COMPILE_OPTIONS "/arch:AVX2" + ) + if(CMAKE_SIZEOF_VOID_P EQUAL 4) + set_source_files_properties( + src/threshold_kernel_sse2.cpp + PROPERTIES COMPILE_OPTIONS "/arch:SSE2" + ) + endif() + elseif(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + set_source_files_properties( + src/threshold_kernel_sse2.cpp + PROPERTIES COMPILE_OPTIONS "-msse2" + ) + set_source_files_properties( + src/threshold_kernel_avx2.cpp + PROPERTIES COMPILE_OPTIONS "-mavx2" + ) + endif() +endif() + +smartparallel_apply_warnings(smart_parallel_vision) +smartparallel_copy_tbb_runtime(smart_parallel_vision) diff --git a/vision/src/opencv_provider.cpp b/vision/src/opencv_provider.cpp new file mode 100644 index 0000000..6697a38 --- /dev/null +++ b/vision/src/opencv_provider.cpp @@ -0,0 +1,97 @@ +#include "opencv_provider.hpp" + +#include +#include +#include + +#include +#include +#include +#include + +namespace smart::vision::detail +{ +namespace +{ +std::once_flag provider_state_once; +std::atomic provider_fingerprint{0}; +std::atomic provider_generation{0}; + +std::size_t compute_provider_fingerprint() noexcept +{ + try + { + auto combine = [](std::size_t seed, std::size_t value) + { + return seed ^ (value + 0x9e3779b97f4a7c15ull + (seed << 6u) + (seed >> 2u)); + }; + std::size_t fingerprint = std::hash{}( + std::string("opencv:") + CV_VERSION + ":" + cv::getBuildInformation()); + fingerprint = combine(fingerprint, static_cast(cv::getNumThreads())); + fingerprint = combine(fingerprint, cv::useOptimized() ? 1u : 0u); + fingerprint = combine(fingerprint, cv::ocl::useOpenCL() ? 1u : 0u); + return fingerprint; + } + catch (...) + { + return std::hash{}(std::string("opencv:") + CV_VERSION); + } +} + +void initialize_provider_state() noexcept +{ + provider_fingerprint.store(compute_provider_fingerprint(), std::memory_order_release); + provider_generation.store(1, std::memory_order_release); +} +} // namespace + +bool opencv_provider_available() noexcept { return true; } + +std::string opencv_provider_version() +{ + return CV_VERSION; +} + +OpenCvProviderState opencv_provider_state() noexcept +{ + std::call_once(provider_state_once, initialize_provider_state); + return {provider_fingerprint.load(std::memory_order_acquire), + provider_generation.load(std::memory_order_acquire)}; +} + +std::size_t opencv_provider_fingerprint() noexcept +{ + return opencv_provider_state().fingerprint; +} + +void refresh_opencv_provider_state() noexcept +{ + std::call_once(provider_state_once, initialize_provider_state); + provider_fingerprint.store(compute_provider_fingerprint(), std::memory_order_release); + provider_generation.fetch_add(1, std::memory_order_acq_rel); +} + +void execute_opencv_threshold(ImageView source, + ImageView destination, + ThresholdOptions options) +{ + cv::Mat source_mat(static_cast(source.height), + static_cast(source.width), + CV_8UC1, + const_cast(source.data), + source.stride_bytes); + cv::Mat destination_mat(static_cast(destination.height), + static_cast(destination.width), + CV_8UC1, + destination.data, + destination.stride_bytes); + const int mode = options.mode == ThresholdMode::Binary + ? cv::THRESH_BINARY + : cv::THRESH_BINARY_INV; + cv::threshold(source_mat, + destination_mat, + static_cast(options.threshold), + static_cast(options.maximum_value), + mode); +} +} // namespace smart::vision::detail diff --git a/vision/src/opencv_provider.hpp b/vision/src/opencv_provider.hpp new file mode 100644 index 0000000..5236b55 --- /dev/null +++ b/vision/src/opencv_provider.hpp @@ -0,0 +1,26 @@ +#pragma once + +#include +#include + +#include +#include +#include + +namespace smart::vision::detail +{ +struct OpenCvProviderState +{ + std::size_t fingerprint = 0; + std::uint64_t generation = 0; +}; + +bool opencv_provider_available() noexcept; +std::string opencv_provider_version(); +OpenCvProviderState opencv_provider_state() noexcept; +std::size_t opencv_provider_fingerprint() noexcept; +void refresh_opencv_provider_state() noexcept; +void execute_opencv_threshold(ImageView source, + ImageView destination, + ThresholdOptions options); +} // namespace smart::vision::detail diff --git a/vision/src/opencv_provider_stub.cpp b/vision/src/opencv_provider_stub.cpp new file mode 100644 index 0000000..3962e02 --- /dev/null +++ b/vision/src/opencv_provider_stub.cpp @@ -0,0 +1,19 @@ +#include "opencv_provider.hpp" + +#include + +namespace smart::vision::detail +{ +bool opencv_provider_available() noexcept { return false; } +std::string opencv_provider_version() { return "unavailable"; } +OpenCvProviderState opencv_provider_state() noexcept { return {0, 1}; } +std::size_t opencv_provider_fingerprint() noexcept { return 0; } +void refresh_opencv_provider_state() noexcept {} + +void execute_opencv_threshold(ImageView, + ImageView, + ThresholdOptions) +{ + throw std::runtime_error("SmartParallel OpenCV vision route is unavailable"); +} +} // namespace smart::vision::detail diff --git a/vision/src/threshold.cpp b/vision/src/threshold.cpp new file mode 100644 index 0000000..0483f4a --- /dev/null +++ b/vision/src/threshold.cpp @@ -0,0 +1,924 @@ +#include + +#include "opencv_provider.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace smart::vision +{ +namespace +{ +constexpr std::uint64_t threshold_operation_id = 0x5631355448524553ull; + +thread_local DecisionReport last_report_storage{}; +thread_local RouteTrainingReport last_training_report_storage{}; +detail::AdaptiveRouteSelector route_selector; +std::atomic route_cache_epoch{1}; +std::atomic hot_route_epoch{1}; + +struct HotRouteKey +{ + std::size_t width = 0; + std::size_t height = 0; + std::size_t source_stride = 0; + std::size_t destination_stride = 0; + std::size_t parameter_hash = 0; + std::size_t worker_budget = 1; + std::size_t candidate_mask = 0; + std::size_t policy_signature = 0; + std::uint64_t provider_generation = 0; + std::size_t source_alignment = 1; + std::size_t destination_alignment = 1; + bool in_place = false; + + bool operator==(const HotRouteKey& other) const noexcept + { + return width == other.width && height == other.height + && source_stride == other.source_stride + && destination_stride == other.destination_stride + && parameter_hash == other.parameter_hash + && worker_budget == other.worker_budget + && candidate_mask == other.candidate_mask + && policy_signature == other.policy_signature + && provider_generation == other.provider_generation + && source_alignment == other.source_alignment + && destination_alignment == other.destination_alignment + && in_place == other.in_place; + } +}; + +struct HotRouteEntry +{ + bool valid = false; + HotRouteKey hot_key{}; + detail::RouteProfileKey profile_key{}; + ExecutionRoute route = ExecutionRoute::NativeSequential; + std::size_t uses = 0; + std::size_t revalidate_after_uses = 0; + std::size_t drift_uses = 0; + std::size_t drift_after_uses = 0; + std::uint64_t epoch = 0; +}; + +thread_local std::array hot_route_entries{}; + +std::size_t bucket(std::size_t value) noexcept +{ + if (value == 0) + return 0; + std::size_t result = 1; + while (result < value && result <= std::numeric_limits::max() / 2) + result <<= 1u; + return result; +} + +std::size_t combine_hash(std::size_t seed, std::size_t value) noexcept +{ + return seed ^ (value + 0x9e3779b97f4a7c15ull + (seed << 6u) + (seed >> 2u)); +} + +std::size_t normalized_worker_budget(std::size_t requested) noexcept +{ + std::size_t budget = requested == 0 ? hardware_threads() : requested; + if (global_config().nested_root_concurrency_budget != 0) + budget = std::min(budget, global_config().nested_root_concurrency_budget); + return std::max(1, budget); +} + +bool valid_threshold_mode(ThresholdMode mode) noexcept +{ + return mode == ThresholdMode::Binary || mode == ThresholdMode::BinaryInverse; +} + +bool valid_execution_route(ExecutionRoute route) noexcept +{ + switch (route) + { + case ExecutionRoute::Auto: + case ExecutionRoute::NativeSequential: + case ExecutionRoute::NativeThreadPool: + case ExecutionRoute::NativeStaticThread: + case ExecutionRoute::NativeOneTbb: + case ExecutionRoute::OpenCV: + return true; + } + return false; +} + +template +std::size_t image_span_bytes(ImageView image) +{ + if (image.empty()) + return 0; + const std::size_t row_bytes = image.row_bytes(); + if (image.height > 1 + && image.stride_bytes + > (std::numeric_limits::max() - row_bytes) + / (image.height - 1)) + { + throw std::length_error("smart::vision::threshold image extent overflows size_t"); + } + return (image.height - 1) * image.stride_bytes + row_bytes; +} + +void validate(ImageView source, + ImageView destination, + ThresholdOptions options, + ExecutionPolicy policy) +{ + if (!valid_threshold_mode(options.mode)) + throw std::invalid_argument("smart::vision::threshold received an invalid threshold mode"); + if (!valid_execution_route(policy.route)) + throw std::invalid_argument("smart::vision::threshold received an invalid execution route"); + if (source.width != destination.width || source.height != destination.height) + throw std::invalid_argument("smart::vision::threshold requires matching dimensions"); + if (source.channels != 1 || destination.channels != 1) + throw std::invalid_argument("smart::vision::threshold currently requires one channel"); + if (source.empty()) + return; + if (source.data == nullptr || destination.data == nullptr) + throw std::invalid_argument("smart::vision::threshold received a null image buffer"); + if (source.stride_bytes < source.row_bytes() + || destination.stride_bytes < destination.row_bytes()) + { + throw std::invalid_argument("smart::vision::threshold received an invalid row stride"); + } + + const std::size_t source_span = image_span_bytes(source); + const std::size_t destination_span = image_span_bytes(destination); + const std::uintptr_t source_begin = reinterpret_cast(source.data); + const std::uintptr_t destination_begin = reinterpret_cast(destination.data); + if (source_span > std::numeric_limits::max() - source_begin + || destination_span > std::numeric_limits::max() - destination_begin) + { + throw std::length_error("smart::vision::threshold image address range overflows"); + } + const std::uintptr_t source_end = source_begin + source_span; + const std::uintptr_t destination_end = destination_begin + destination_span; + if (source_begin == destination_begin) + { + if (source.stride_bytes != destination.stride_bytes) + throw std::invalid_argument("in-place threshold requires matching row strides"); + } + else if (source_begin < destination_end && destination_begin < source_end) + { + throw std::invalid_argument("smart::vision::threshold rejects partially overlapping buffers"); + } +} + +std::size_t route_bit(ExecutionRoute route) noexcept +{ + return std::size_t{1} << static_cast(route); +} + +bool opencv_compatible(ImageView source, + ImageView destination) noexcept +{ + return source.width <= static_cast(std::numeric_limits::max()) + && source.height <= static_cast(std::numeric_limits::max()) + && destination.width <= static_cast(std::numeric_limits::max()) + && destination.height <= static_cast(std::numeric_limits::max()); +} + +std::size_t automatic_candidate_mask(ImageView source, + ImageView destination) noexcept +{ + const Config& config = global_config(); + std::size_t mask = route_bit(ExecutionRoute::NativeSequential); + if (config.vision_route_consider_opencv && detail::opencv_provider_available() + && opencv_compatible(source, destination)) + { + mask |= route_bit(ExecutionRoute::OpenCV); + } + if (config.vision_route_consider_thread_pool) + mask |= route_bit(ExecutionRoute::NativeThreadPool); + if (config.vision_route_consider_one_tbb + && execution_backend_available(ExecutionEngineType::OneTbb)) + { + mask |= route_bit(ExecutionRoute::NativeOneTbb); + } + return mask; +} + +std::vector automatic_candidates(std::size_t mask) +{ + std::vector candidates; + candidates.reserve(4); + for (ExecutionRoute route : {ExecutionRoute::NativeSequential, + ExecutionRoute::OpenCV, + ExecutionRoute::NativeThreadPool, + ExecutionRoute::NativeOneTbb}) + { + if ((mask & route_bit(route)) != 0) + candidates.push_back(route); + } + return candidates; +} + +std::size_t candidate_count(std::size_t mask) noexcept +{ + std::size_t count = 0; + while (mask != 0) + { + count += mask & 1u; + mask >>= 1u; + } + return count; +} + +std::size_t vision_policy_signature(const Config& config) noexcept +{ + std::size_t hash = config.vision_route_policy_generation; + hash = combine_hash(hash, config.enable_vision_adaptive_routes ? 1u : 0u); + hash = combine_hash(hash, config.vision_route_cache_max_entries); + hash = combine_hash(hash, std::hash{}(config.vision_route_equivalence_ratio)); + hash = combine_hash(hash, std::hash{}(config.vision_route_measurement_blend)); + hash = combine_hash(hash, std::hash{}(config.vision_route_absolute_equivalence_ms)); + hash = combine_hash(hash, config.vision_route_warmup_samples); + hash = combine_hash(hash, config.vision_route_minimum_samples); + hash = combine_hash(hash, config.vision_route_sample_window); + hash = combine_hash(hash, config.vision_route_holdout_samples); + hash = combine_hash(hash, config.vision_route_maximum_verification_failures); + hash = combine_hash(hash, config.vision_route_initial_revalidate_interval); + hash = combine_hash(hash, config.vision_route_revalidate_interval); + hash = combine_hash(hash, config.vision_route_drift_sample_interval); + hash = combine_hash(hash, config.vision_route_drift_required_samples); + hash = combine_hash(hash, std::hash{}(config.vision_route_drift_ratio)); + hash = combine_hash(hash, std::hash{}(config.vision_route_drift_absolute_ms)); + hash = combine_hash(hash, config.vision_route_consider_thread_pool ? 1u : 0u); + hash = combine_hash(hash, config.vision_route_consider_one_tbb ? 1u : 0u); + hash = combine_hash(hash, config.vision_route_consider_opencv ? 1u : 0u); + hash = combine_hash(hash, route_cache_epoch.load(std::memory_order_acquire)); + return hash; +} + +detail::RouteSelectorSettings selector_settings() +{ + const Config& config = global_config(); + detail::RouteSelectorSettings settings; + settings.maximum_entries = config.vision_route_cache_max_entries; + settings.equivalence_ratio = config.vision_route_equivalence_ratio; + settings.measurement_blend = config.vision_route_measurement_blend; + settings.absolute_equivalence_ms = config.vision_route_absolute_equivalence_ms; + settings.warmup_samples = config.vision_route_warmup_samples; + settings.minimum_samples = config.vision_route_minimum_samples; + settings.sample_window = config.vision_route_sample_window; + settings.holdout_samples = config.vision_route_holdout_samples; + settings.maximum_verification_failures = + config.vision_route_maximum_verification_failures; + settings.initial_revalidate_interval = + config.vision_route_initial_revalidate_interval; + settings.revalidate_interval = config.vision_route_revalidate_interval; + settings.drift_required_samples = config.vision_route_drift_required_samples; + settings.drift_ratio = config.vision_route_drift_ratio; + settings.drift_absolute_ms = config.vision_route_drift_absolute_ms; + return settings; +} + +std::size_t alignment_class(const void* pointer) noexcept +{ + const std::uintptr_t address = reinterpret_cast(pointer); + if ((address & 63u) == 0) + return 64; + if ((address & 31u) == 0) + return 32; + if ((address & 15u) == 0) + return 16; + if ((address & 7u) == 0) + return 8; + return 1; +} + +std::size_t threshold_parameter_hash(ThresholdOptions options) noexcept +{ + std::size_t hash = static_cast(options.threshold); + hash = combine_hash(hash, options.maximum_value); + return combine_hash(hash, static_cast(options.mode)); +} + +HotRouteKey make_hot_key(ImageView source, + ImageView destination, + ThresholdOptions options, + std::size_t worker_budget, + std::size_t candidates_mask, + std::size_t policy_signature, + std::uint64_t provider_generation) noexcept +{ + return {source.width, + source.height, + source.stride_bytes, + destination.stride_bytes, + threshold_parameter_hash(options), + worker_budget, + candidates_mask, + policy_signature, + provider_generation, + alignment_class(source.data), + alignment_class(destination.data), + source.data == destination.data}; +} + +std::size_t hot_key_hash(const HotRouteKey& key) noexcept +{ + std::size_t hash = key.width; + hash = combine_hash(hash, key.height); + hash = combine_hash(hash, key.source_stride); + hash = combine_hash(hash, key.destination_stride); + hash = combine_hash(hash, key.parameter_hash); + hash = combine_hash(hash, key.worker_budget); + hash = combine_hash(hash, key.candidate_mask); + hash = combine_hash(hash, key.policy_signature); + hash = combine_hash(hash, static_cast(key.provider_generation)); + hash = combine_hash(hash, key.source_alignment); + hash = combine_hash(hash, key.destination_alignment); + return combine_hash(hash, key.in_place ? 1u : 0u); +} + +detail::RouteProfileKey make_profile_key(ImageView source, + ImageView destination, + ThresholdOptions options, + std::size_t worker_budget, + std::size_t candidates_mask, + std::size_t policy_signature, + std::size_t provider_fingerprint) +{ + std::size_t layout = source.contiguous() && destination.contiguous() ? 1u : 2u; + layout = combine_hash(layout, source.data == destination.data ? 1u : 0u); + layout = combine_hash(layout, bucket(source.stride_bytes)); + layout = combine_hash(layout, bucket(destination.stride_bytes)); + layout = combine_hash(layout, alignment_class(source.data)); + layout = combine_hash(layout, alignment_class(destination.data)); + return detail::RouteProfileKey{ + threshold_operation_id, + bucket(source.width * source.height), + bucket(source.width), + bucket(source.height), + layout, + threshold_parameter_hash(options), + worker_budget, + candidates_mask, + policy_signature, + provider_fingerprint}; +} + +HotRouteEntry* hot_route_lookup(const HotRouteKey& key) noexcept +{ + const std::size_t index = hot_key_hash(key) % hot_route_entries.size(); + HotRouteEntry& entry = hot_route_entries[index]; + const std::uint64_t epoch = hot_route_epoch.load(std::memory_order_acquire); + return entry.valid && entry.hot_key == key && entry.epoch == epoch ? &entry : nullptr; +} + +void hot_route_store(const HotRouteKey& hot_key, + const detail::RouteProfileKey& profile_key, + ExecutionRoute route, + std::size_t revalidate_after_uses, + std::size_t drift_after_uses, + std::size_t uses = 0, + std::size_t drift_uses = 0) noexcept +{ + const std::size_t index = hot_key_hash(hot_key) % hot_route_entries.size(); + hot_route_entries[index] = HotRouteEntry{ + true, + hot_key, + profile_key, + route, + uses, + revalidate_after_uses, + drift_uses, + drift_after_uses, + hot_route_epoch.load(std::memory_order_acquire)}; +} + +void invalidate_hot_routes() noexcept +{ + hot_route_epoch.fetch_add(1, std::memory_order_acq_rel); +} + +void update_training_report(const detail::RouteMeasurementSnapshot& snapshot) +{ + last_training_report_storage = {}; + last_training_report_storage.available = true; + last_training_report_storage.stable = snapshot.stable; + last_training_report_storage.holdout_active = snapshot.holdout_active; + last_training_report_storage.revalidation_active = snapshot.revalidation_active; + last_training_report_storage.drift_detected = snapshot.drift_detected; + last_training_report_storage.stable_route = snapshot.stable_route; + last_training_report_storage.provisional_route = snapshot.provisional_route; + last_training_report_storage.verification_failures = snapshot.verification_failures; + last_training_report_storage.route_switch_count = snapshot.route_switch_count; + last_training_report_storage.drift_strikes = snapshot.drift_strikes; + last_training_report_storage.revalidation_challenger = snapshot.revalidation_challenger; + last_training_report_storage.training_baseline_ms = snapshot.training_baseline_ms; + last_training_report_storage.current_baseline_ms = snapshot.current_baseline_ms; + last_training_report_storage.last_revalidation_stable_ms = snapshot.last_revalidation_stable_ms; + last_training_report_storage.last_revalidation_challenger_ms = snapshot.last_revalidation_challenger_ms; + last_training_report_storage.routes.reserve(snapshot.routes.size()); + for (std::size_t index = 0; index < snapshot.routes.size(); ++index) + { + RouteTrainingEntry entry; + entry.route = snapshot.routes[index]; + entry.median_ms = snapshot.elapsed_ms[index]; + entry.mad_ms = snapshot.mad_ms[index]; + entry.minimum_ms = snapshot.minimum_ms[index]; + entry.maximum_ms = snapshot.maximum_ms[index]; + entry.sample_count = snapshot.samples[index]; + entry.warmup_count = snapshot.warmups[index]; + entry.holdout_sample_count = snapshot.holdout_samples[index]; + entry.current_sample_count = snapshot.current_samples[index]; + entry.current_median_ms = snapshot.current_elapsed_ms[index]; + entry.active = snapshot.active[index]; + last_training_report_storage.routes.push_back(entry); + } +} + + +struct ChunkRange +{ + std::size_t begin = 0; + std::size_t end = 0; +}; + +ChunkRange chunk_range(std::size_t total, + std::size_t chunks, + std::size_t ordinal) noexcept +{ + const std::size_t base = total / chunks; + const std::size_t remainder = total % chunks; + const std::size_t begin = ordinal * base + std::min(ordinal, remainder); + return {begin, begin + base + (ordinal < remainder ? 1u : 0u)}; +} + +std::size_t native_chunk_count(ImageView source, + std::size_t worker_budget) noexcept +{ + const std::size_t units = source.contiguous() + ? source.width * source.height + : source.height; + const std::size_t desired = worker_budget > std::numeric_limits::max() / 4 + ? std::numeric_limits::max() + : worker_budget * 4; + return std::max(1, std::min(units, desired)); +} + +template +void execute_native_chunk_mode(ImageView source, + ImageView destination, + ThresholdOptions options, + std::size_t chunks, + std::size_t ordinal) noexcept +{ + const bool in_place = source.data == destination.data; + if (source.contiguous() && destination.contiguous()) + { + const ChunkRange range = chunk_range(source.width * source.height, chunks, ordinal); + if (in_place) + { + detail::threshold_u8_contiguous_in_place( + destination.data + range.begin, + range.end - range.begin, + options.threshold, + options.maximum_value); + } + else + { + detail::threshold_u8_contiguous_disjoint( + source.data + range.begin, + destination.data + range.begin, + range.end - range.begin, + options.threshold, + options.maximum_value); + } + return; + } + + const ChunkRange rows = chunk_range(source.height, chunks, ordinal); + if (in_place) + { + detail::threshold_u8_rows_in_place( + destination.data, + destination.stride_bytes, + source.width, + rows.begin, + rows.end, + options.threshold, + options.maximum_value); + } + else + { + detail::threshold_u8_rows_disjoint( + source.data, + source.stride_bytes, + destination.data, + destination.stride_bytes, + source.width, + rows.begin, + rows.end, + options.threshold, + options.maximum_value); + } +} + +void execute_native_chunk(ImageView source, + ImageView destination, + ThresholdOptions options, + std::size_t chunks, + std::size_t ordinal) noexcept +{ + if (options.mode == ThresholdMode::BinaryInverse) + execute_native_chunk_mode(source, destination, options, chunks, ordinal); + else + execute_native_chunk_mode(source, destination, options, chunks, ordinal); +} + +template +void execute_native_sequential_mode(ImageView source, + ImageView destination, + ThresholdOptions options) noexcept +{ + const bool in_place = source.data == destination.data; + if (source.contiguous() && destination.contiguous()) + { + const std::size_t count = source.width * source.height; + if (in_place) + { + detail::threshold_u8_contiguous_in_place( + destination.data, count, options.threshold, options.maximum_value); + } + else + { + detail::threshold_u8_contiguous_disjoint( + source.data, + destination.data, + count, + options.threshold, + options.maximum_value); + } + return; + } + + if (in_place) + { + detail::threshold_u8_rows_in_place( + destination.data, + destination.stride_bytes, + source.width, + 0, + source.height, + options.threshold, + options.maximum_value); + } + else + { + detail::threshold_u8_rows_disjoint( + source.data, + source.stride_bytes, + destination.data, + destination.stride_bytes, + source.width, + 0, + source.height, + options.threshold, + options.maximum_value); + } +} + +struct NativeExecutionResult +{ + std::size_t chunks = 1; + std::size_t participants = 1; +}; + +NativeExecutionResult execute_native(ExecutionRoute route, + ImageView source, + ImageView destination, + ThresholdOptions options, + std::size_t worker_budget) +{ + if (source.empty()) + return {}; + if (route == ExecutionRoute::NativeSequential) + { + if (options.mode == ThresholdMode::BinaryInverse) + execute_native_sequential_mode(source, destination, options); + else + execute_native_sequential_mode(source, destination, options); + return {}; + } + + const ExecutionEngineType engine = native_execution_engine(route); + if (!execution_backend_available(engine)) + throw std::runtime_error(std::string("Requested unavailable SmartParallel route: ") + + execution_route_name(route)); + + const std::size_t chunks = native_chunk_count(source, worker_budget); + BackendExecutionRequest request; + request.total = chunks; + request.concurrency_budget = worker_budget; + request.chunk_size = 1; + const ExecutionContext context = current_execution_context(); + request.loop_id = context.loop_id; + request.nested_session = context.nested_session; + request.cooperative_helping = route == ExecutionRoute::NativeThreadPool; + request.function = [=](std::size_t ordinal) + { + execute_native_chunk(source, destination, options, chunks, ordinal); + }; + const BackendExecutionResult result = execution_backend(engine).execute(std::move(request)); + return {chunks, std::max(1, result.runtime_concurrency)}; +} + +NativeExecutionResult execute_route(ExecutionRoute route, + ImageView source, + ImageView destination, + ThresholdOptions options, + std::size_t worker_budget) +{ + if (route == ExecutionRoute::OpenCV) + { + if (!detail::opencv_provider_available()) + throw std::runtime_error("Requested OpenCV route is unavailable"); + if (!opencv_compatible(source, destination)) + throw std::invalid_argument("OpenCV threshold route requires dimensions representable as int"); + detail::execute_opencv_threshold(source, destination, options); + return {1, 1}; + } + return execute_native(route, source, destination, options, worker_budget); +} +} // namespace + +void threshold(ImageView source, + ImageView destination, + ThresholdOptions options, + ExecutionPolicy policy) +{ + validate(source, destination, options, policy); + last_report_storage = {}; + last_report_storage.requested_route = policy.route; + last_report_storage.automatic = policy.route == ExecutionRoute::Auto; + last_report_storage.opencv_available = detail::opencv_provider_available(); + const ExecutionContext context = current_execution_context(); + last_report_storage.execution_depth = context.depth; + const std::size_t worker_budget = normalized_worker_budget(policy.worker_budget); + last_report_storage.worker_budget = worker_budget; + + if (source.empty()) + { + last_report_storage.selected_route = ExecutionRoute::NativeSequential; + last_report_storage.native_engine = ExecutionEngineType::Auto; + last_report_storage.backend_authenticated = true; + return; + } + + ExecutionRoute selected = policy.route; + detail::RouteSelection selection; + detail::RouteSelectorSettings settings; + HotRouteKey active_hot_key{}; + bool have_hot_key = false; + std::size_t preserved_hot_uses = 0; + bool forced_drift_sample = false; + bool forced_revalidation = false; + + if (policy.route == ExecutionRoute::Auto) + { + const Config& config = global_config(); + if (!config.enable_vision_adaptive_routes || context.depth != 0) + { + selected = ExecutionRoute::NativeSequential; + last_report_storage.nested_fallback = context.depth != 0; + } + else + { + const std::size_t candidates_mask = automatic_candidate_mask(source, destination); + const std::size_t policy_signature = vision_policy_signature(config); + const detail::OpenCvProviderState provider_state = + detail::opencv_provider_state(); + active_hot_key = make_hot_key(source, + destination, + options, + worker_budget, + candidates_mask, + policy_signature, + provider_state.generation); + have_hot_key = true; + last_report_storage.adaptive_selection_enabled = true; + last_report_storage.candidate_count = candidate_count(candidates_mask); + + HotRouteEntry* hot_entry = hot_route_lookup(active_hot_key); + bool hot_revalidation = false; + bool hot_drift_sample = false; + if (hot_entry != nullptr) + { + if (!config.vision_route_pause_maintenance) + { + ++hot_entry->uses; + ++hot_entry->drift_uses; + hot_revalidation = hot_entry->revalidate_after_uses > 0 + && hot_entry->uses >= hot_entry->revalidate_after_uses; + hot_drift_sample = !hot_revalidation + && hot_entry->drift_after_uses > 0 + && hot_entry->drift_uses >= hot_entry->drift_after_uses; + } + preserved_hot_uses = hot_entry->uses; + } + if (hot_entry != nullptr && !hot_revalidation && !hot_drift_sample) + { + selected = hot_entry->route; + last_report_storage.cache_hit = true; + last_report_storage.learned_route = true; + } + else + { + detail::RouteProfileKey profile_key; + if (hot_entry != nullptr) + { + profile_key = hot_entry->profile_key; + hot_entry->valid = false; + } + else + { + profile_key = make_profile_key(source, + destination, + options, + worker_budget, + candidates_mask, + policy_signature, + provider_state.fingerprint); + } + + settings = selector_settings(); + const std::vector candidates = + automatic_candidates(candidates_mask); + detail::RouteSelectorSettings selection_settings = settings; + selection_settings.force_revalidation = hot_revalidation; + selection_settings.force_stable_sample = hot_drift_sample; + forced_revalidation = hot_revalidation; + forced_drift_sample = hot_drift_sample; + selection = route_selector.select( + profile_key, candidates, selection_settings); + settings = selection_settings; + selected = selection.route; + last_report_storage.cache_hit = selection.cache_hit; + last_report_storage.learned_route = selection.stable && !selection.probe; + last_report_storage.holdout_probe = selection.holdout; + last_report_storage.drift_probe = selection.drift_sample; + last_report_storage.exploration_probe = + selection.probe && !selection.revalidation && !selection.drift_sample; + last_report_storage.revalidation_probe = selection.revalidation; + if (selection.stable && !selection.probe) + { + detail::RouteMeasurementSnapshot snapshot; + const bool have_snapshot = route_selector.snapshot(profile_key, snapshot); + if (have_snapshot) + update_training_report(snapshot); + const std::size_t interval = have_snapshot + ? snapshot.revalidate_after_uses + : settings.initial_revalidate_interval; + hot_route_store(active_hot_key, + profile_key, + selected, + interval, + config.vision_route_drift_sample_interval); + } + } + } + } + + const bool stable_hot_route = policy.route == ExecutionRoute::Auto + && last_report_storage.cache_hit && last_report_storage.learned_route + && !last_report_storage.revalidation_probe + && !last_report_storage.drift_probe; + const bool measure_execution = !stable_hot_route; + const auto start = measure_execution + ? std::chrono::steady_clock::now() + : std::chrono::steady_clock::time_point{}; + NativeExecutionResult execution; + try + { + execution = execute_route(selected, source, destination, options, worker_budget); + } + catch (...) + { + if (selection.enabled) + route_selector.cancel(selection); + throw; + } + const double elapsed_ms = measure_execution + ? std::chrono::duration( + std::chrono::steady_clock::now() - start).count() + : 0.0; + + if (selection.enabled) + { + detail::RouteMeasurementSnapshot before; + const bool had_before = route_selector.snapshot(selection.key, before); + route_selector.complete(selection, elapsed_ms, settings); + detail::RouteMeasurementSnapshot snapshot; + if (route_selector.snapshot(selection.key, snapshot)) + { + update_training_report(snapshot); + if (snapshot.stable) + { + if (!had_before || !before.stable + || before.stable_route != snapshot.stable_route) + { + invalidate_hot_routes(); + } + if (have_hot_key && !snapshot.revalidation_active) + { + std::size_t hot_uses = 0; + std::size_t drift_uses = 0; + if (selection.drift_sample && !snapshot.drift_detected) + { + hot_uses = preserved_hot_uses; + drift_uses = 0; + } + else if (!selection.revalidation && forced_drift_sample + && !snapshot.revalidation_active) + { + hot_uses = preserved_hot_uses; + } + else if (!selection.revalidation && !forced_revalidation + && !selection.drift_sample) + { + hot_uses = 0; + } + hot_route_store(active_hot_key, + selection.key, + snapshot.stable_route, + snapshot.revalidate_after_uses, + global_config().vision_route_drift_sample_interval, + hot_uses, + drift_uses); + } + } + } + } + + last_report_storage.selected_route = selected; + last_report_storage.native_engine = native_execution_engine(selected); + last_report_storage.execution_ms = elapsed_ms; + last_report_storage.execution_timed = measure_execution; + last_report_storage.chunk_count = execution.chunks; + last_report_storage.participant_count = execution.participants; + last_report_storage.backend_authenticated = selected == ExecutionRoute::OpenCV + ? detail::opencv_provider_available() + : selected == ExecutionRoute::NativeSequential + || execution_backend_available(native_execution_engine(selected)); +} + +bool opencv_available() noexcept +{ + return detail::opencv_provider_available(); +} + +std::string opencv_version() +{ + return detail::opencv_provider_version(); +} + +DecisionReport last_decision_report() noexcept +{ + return last_report_storage; +} + +RouteTrainingReport last_route_training_report() +{ + return last_training_report_storage; +} + +void refresh_provider_state() noexcept +{ + detail::refresh_opencv_provider_state(); + clear_adaptive_route_cache(); +} + +void clear_adaptive_route_cache() noexcept +{ + route_selector.clear(); + last_training_report_storage = {}; + route_cache_epoch.fetch_add(1, std::memory_order_acq_rel); + invalidate_hot_routes(); + for (HotRouteEntry& entry : hot_route_entries) + entry.valid = false; +} +} // namespace smart::vision diff --git a/vision/src/threshold_kernel_avx2.cpp b/vision/src/threshold_kernel_avx2.cpp new file mode 100644 index 0000000..c916d96 --- /dev/null +++ b/vision/src/threshold_kernel_avx2.cpp @@ -0,0 +1,96 @@ +#include "threshold_kernel_internal.hpp" + +#include +#include + +#if defined(_M_X64) || defined(_M_IX86) || defined(__x86_64__) || defined(__i386__) +#include +#define SMARTPARALLEL_HAS_AVX2_SOURCE 1 +#else +#define SMARTPARALLEL_HAS_AVX2_SOURCE 0 +#endif + +namespace smart::vision::detail +{ +bool threshold_avx2_compiled() noexcept +{ + return SMARTPARALLEL_HAS_AVX2_SOURCE != 0; +} + +#if SMARTPARALLEL_HAS_AVX2_SOURCE +namespace +{ +template +void threshold_avx2(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + constexpr std::size_t width = 32; + const __m256i sign = _mm256_set1_epi8(static_cast(0x80)); + const __m256i threshold_value = _mm256_set1_epi8( + static_cast(threshold ^ std::uint8_t{0x80})); + const __m256i maximum_value = _mm256_set1_epi8(static_cast(maximum)); + std::size_t index = 0; + for (; index + width <= count; index += width) + { + const __m256i values = _mm256_loadu_si256( + reinterpret_cast(source + index)); + const __m256i adjusted = _mm256_xor_si256(values, sign); + const __m256i mask = _mm256_cmpgt_epi8(adjusted, threshold_value); + const __m256i result = Inverse + ? _mm256_andnot_si256(mask, maximum_value) + : _mm256_and_si256(mask, maximum_value); + _mm256_storeu_si256(reinterpret_cast<__m256i*>(destination + index), result); + } + if (index < count) + { + if constexpr (Inverse) + threshold_sse2_inverse(source + index, destination + index, + count - index, threshold, maximum); + else + threshold_sse2_binary(source + index, destination + index, + count - index, threshold, maximum); + } +} +} // namespace + +void threshold_avx2_binary(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + threshold_avx2(source, destination, count, threshold, maximum); +} + +void threshold_avx2_inverse(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + threshold_avx2(source, destination, count, threshold, maximum); +} +#else +void threshold_avx2_binary(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + threshold_scalar_binary(source, destination, count, threshold, maximum); +} +void threshold_avx2_inverse(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + threshold_scalar_inverse(source, destination, count, threshold, maximum); +} +#endif +} // namespace smart::vision::detail + +#undef SMARTPARALLEL_HAS_AVX2_SOURCE diff --git a/vision/src/threshold_kernel_dispatch.cpp b/vision/src/threshold_kernel_dispatch.cpp new file mode 100644 index 0000000..96d8586 --- /dev/null +++ b/vision/src/threshold_kernel_dispatch.cpp @@ -0,0 +1,249 @@ +#include + +#include "threshold_kernel_internal.hpp" + +#include +#include + +#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) +#include +#elif (defined(__GNUC__) || defined(__clang__)) \ + && (defined(__x86_64__) || defined(__i386__)) +#include +#endif + +namespace smart::vision::detail +{ +namespace +{ +#if defined(_MSC_VER) +#define SMARTPARALLEL_RESTRICT __restrict +#elif defined(__GNUC__) || defined(__clang__) +#define SMARTPARALLEL_RESTRICT __restrict__ +#else +#define SMARTPARALLEL_RESTRICT +#endif + +void scalar_binary_disjoint( + const std::uint8_t* SMARTPARALLEL_RESTRICT source, + std::uint8_t* SMARTPARALLEL_RESTRICT destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + const unsigned maximum_unsigned = maximum; + for (std::size_t index = 0; index < count; ++index) + { + destination[index] = static_cast( + static_cast(source[index] > threshold) * maximum_unsigned); + } +} + +void scalar_inverse_disjoint( + const std::uint8_t* SMARTPARALLEL_RESTRICT source, + std::uint8_t* SMARTPARALLEL_RESTRICT destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + const unsigned maximum_unsigned = maximum; + for (std::size_t index = 0; index < count; ++index) + { + destination[index] = static_cast( + static_cast(source[index] <= threshold) * maximum_unsigned); + } +} + +void scalar_binary_in_place(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + (void)source; + const unsigned maximum_unsigned = maximum; + for (std::size_t index = 0; index < count; ++index) + { + destination[index] = static_cast( + static_cast(destination[index] > threshold) * maximum_unsigned); + } +} + +void scalar_inverse_in_place(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + (void)source; + const unsigned maximum_unsigned = maximum; + for (std::size_t index = 0; index < count; ++index) + { + destination[index] = static_cast( + static_cast(destination[index] <= threshold) * maximum_unsigned); + } +} + +bool cpu_supports_sse2() noexcept +{ +#if defined(_M_X64) || defined(__x86_64__) + return true; +#elif defined(_MSC_VER) && defined(_M_IX86) + int registers[4]{}; + __cpuid(registers, 0); + if (registers[0] < 1) + return false; + __cpuid(registers, 1); + return (registers[3] & (1 << 26)) != 0; +#elif (defined(__GNUC__) || defined(__clang__)) && defined(__i386__) + __builtin_cpu_init(); + return __builtin_cpu_supports("sse2"); +#else + return false; +#endif +} + +bool cpu_supports_avx2() noexcept +{ +#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) + int registers[4]{}; + __cpuid(registers, 0); + if (registers[0] < 7) + return false; + __cpuid(registers, 1); + const bool osxsave = (registers[2] & (1 << 27)) != 0; + const bool avx = (registers[2] & (1 << 28)) != 0; + if (!osxsave || !avx || (threshold_x86_xcr0() & 0x6u) != 0x6u) + return false; + __cpuidex(registers, 7, 0); + return (registers[1] & (1 << 5)) != 0; +#elif (defined(__GNUC__) || defined(__clang__)) \ + && (defined(__x86_64__) || defined(__i386__)) + __builtin_cpu_init(); + return __builtin_cpu_supports("avx2"); +#else + return false; +#endif +} + +struct KernelDispatch +{ + ThresholdKernelKind kind = ThresholdKernelKind::Scalar; + ThresholdKernelFunction binary_disjoint = scalar_binary_disjoint; + ThresholdKernelFunction inverse_disjoint = scalar_inverse_disjoint; + ThresholdKernelFunction binary_in_place = scalar_binary_in_place; + ThresholdKernelFunction inverse_in_place = scalar_inverse_in_place; +}; + +KernelDispatch detect_dispatch() noexcept +{ + if (threshold_avx2_compiled() && cpu_supports_avx2()) + { + return {ThresholdKernelKind::AVX2, + threshold_avx2_binary, + threshold_avx2_inverse, + threshold_avx2_binary, + threshold_avx2_inverse}; + } + if (threshold_sse2_compiled() && cpu_supports_sse2()) + { + return {ThresholdKernelKind::SSE2, + threshold_sse2_binary, + threshold_sse2_inverse, + threshold_sse2_binary, + threshold_sse2_inverse}; + } + return {}; +} + +const KernelDispatch& kernel_dispatch() noexcept +{ + static const KernelDispatch dispatch = detect_dispatch(); + return dispatch; +} + +#undef SMARTPARALLEL_RESTRICT +} // namespace + +void threshold_scalar_binary(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + if (source == destination) + scalar_binary_in_place(source, destination, count, threshold, maximum); + else + scalar_binary_disjoint(source, destination, count, threshold, maximum); +} + +void threshold_scalar_inverse(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + if (source == destination) + scalar_inverse_in_place(source, destination, count, threshold, maximum); + else + scalar_inverse_disjoint(source, destination, count, threshold, maximum); +} + +ThresholdKernelKind selected_threshold_kernel() noexcept +{ + return kernel_dispatch().kind; +} + +const char* threshold_kernel_name(ThresholdKernelKind kind) noexcept +{ + switch (kind) + { + case ThresholdKernelKind::Scalar: + return "scalar_branchless"; + case ThresholdKernelKind::SSE2: + return "sse2"; + case ThresholdKernelKind::AVX2: + return "avx2"; + } + return "unknown"; +} + +bool threshold_kernel_uses_explicit_simd() noexcept +{ + return selected_threshold_kernel() != ThresholdKernelKind::Scalar; +} + +void threshold_u8_contiguous_disjoint_binary(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + kernel_dispatch().binary_disjoint(source, destination, count, threshold, maximum); +} + +void threshold_u8_contiguous_disjoint_inverse(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + kernel_dispatch().inverse_disjoint(source, destination, count, threshold, maximum); +} + +void threshold_u8_contiguous_in_place_binary(std::uint8_t* data, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + kernel_dispatch().binary_in_place(data, data, count, threshold, maximum); +} + +void threshold_u8_contiguous_in_place_inverse(std::uint8_t* data, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + kernel_dispatch().inverse_in_place(data, data, count, threshold, maximum); +} +} // namespace smart::vision::detail diff --git a/vision/src/threshold_kernel_internal.hpp b/vision/src/threshold_kernel_internal.hpp new file mode 100644 index 0000000..0cf8edf --- /dev/null +++ b/vision/src/threshold_kernel_internal.hpp @@ -0,0 +1,50 @@ +#pragma once + +#include +#include + +namespace smart::vision::detail +{ +std::uint64_t threshold_x86_xcr0() noexcept; + +using ThresholdKernelFunction = void (*)(const std::uint8_t*, + std::uint8_t*, + std::size_t, + std::uint8_t, + std::uint8_t) noexcept; + +void threshold_scalar_binary(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept; +void threshold_scalar_inverse(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept; + +bool threshold_sse2_compiled() noexcept; +void threshold_sse2_binary(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept; +void threshold_sse2_inverse(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept; + +bool threshold_avx2_compiled() noexcept; +void threshold_avx2_binary(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept; +void threshold_avx2_inverse(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept; +} // namespace smart::vision::detail diff --git a/vision/src/threshold_kernel_sse2.cpp b/vision/src/threshold_kernel_sse2.cpp new file mode 100644 index 0000000..5a4fa03 --- /dev/null +++ b/vision/src/threshold_kernel_sse2.cpp @@ -0,0 +1,93 @@ +#include "threshold_kernel_internal.hpp" + +#include +#include + +#if defined(_M_X64) || defined(_M_IX86) || defined(__x86_64__) || defined(__i386__) +#include +#define SMARTPARALLEL_HAS_SSE2_SOURCE 1 +#else +#define SMARTPARALLEL_HAS_SSE2_SOURCE 0 +#endif + +namespace smart::vision::detail +{ +bool threshold_sse2_compiled() noexcept +{ + return SMARTPARALLEL_HAS_SSE2_SOURCE != 0; +} + +#if SMARTPARALLEL_HAS_SSE2_SOURCE +namespace +{ +template +void threshold_sse2(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + constexpr std::size_t width = 16; + const __m128i sign = _mm_set1_epi8(static_cast(0x80)); + const __m128i threshold_value = _mm_set1_epi8( + static_cast(threshold ^ std::uint8_t{0x80})); + const __m128i maximum_value = _mm_set1_epi8(static_cast(maximum)); + std::size_t index = 0; + for (; index + width <= count; index += width) + { + const __m128i values = _mm_loadu_si128( + reinterpret_cast(source + index)); + const __m128i adjusted = _mm_xor_si128(values, sign); + const __m128i mask = _mm_cmpgt_epi8(adjusted, threshold_value); + const __m128i result = Inverse + ? _mm_andnot_si128(mask, maximum_value) + : _mm_and_si128(mask, maximum_value); + _mm_storeu_si128(reinterpret_cast<__m128i*>(destination + index), result); + } + if constexpr (Inverse) + threshold_scalar_inverse(source + index, destination + index, + count - index, threshold, maximum); + else + threshold_scalar_binary(source + index, destination + index, + count - index, threshold, maximum); +} +} // namespace + +void threshold_sse2_binary(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + threshold_sse2(source, destination, count, threshold, maximum); +} + +void threshold_sse2_inverse(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + threshold_sse2(source, destination, count, threshold, maximum); +} +#else +void threshold_sse2_binary(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + threshold_scalar_binary(source, destination, count, threshold, maximum); +} +void threshold_sse2_inverse(const std::uint8_t* source, + std::uint8_t* destination, + std::size_t count, + std::uint8_t threshold, + std::uint8_t maximum) noexcept +{ + threshold_scalar_inverse(source, destination, count, threshold, maximum); +} +#endif +} // namespace smart::vision::detail + +#undef SMARTPARALLEL_HAS_SSE2_SOURCE diff --git a/vision/src/threshold_kernel_x86_features.cpp b/vision/src/threshold_kernel_x86_features.cpp new file mode 100644 index 0000000..1610ac1 --- /dev/null +++ b/vision/src/threshold_kernel_x86_features.cpp @@ -0,0 +1,19 @@ +#include "threshold_kernel_internal.hpp" + +#include + +#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) +#include +#endif + +namespace smart::vision::detail +{ +std::uint64_t threshold_x86_xcr0() noexcept +{ +#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) + return static_cast(_xgetbv(0)); +#else + return 0; +#endif +} +} // namespace smart::vision::detail