diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..0aaea00 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,83 @@ +# DPDFNet engineering instructions + +Reply to the user in Russian. Keep technical documentation in English. +The optimized Linux x86-64 runtime is in `optimized_inference/`. + +## Numerical changes + +- Preserve exact quantization, FP operation order, model weights and ABI. + Do not introduce approximate reciprocals, fast-math or implicit FMA. +- Keep an independent pre-change oracle when refactoring numerical helpers. +- Check both models and AVX2/VNNI, guarded memory, rounding modes, FTZ/DAZ, + sanitizer contracts, ISA restrictions and stream/state/reset equivalence. +- Keep experimental candidates separate from accepted runtime defaults. + +## Performance measurements + +- Mandatory entry point: read `optimized_inference/docs/BENCHMARK_LAB.md`, run + `just bench-test`, and use `just bench-session MANIFEST OUTPUT` for performance + studies. For manual sessions use `just bench-prepare`, `just bench-ready`, + `just bench-aa`, then `just bench-compare`, and always `just bench-restore`. + Do not replace this with ad-hoc taskset/IRQ/power scripts. Unsupported + hardware must fail clearly; extend and test the controller before proceeding. +- Reserve the complete discovered L3 domain from ordinary background work, + with housekeeping on another domain. Use the verified `steady` non-boost + frequency/idle policy as the laboratory baseline. Explicitly preregister + `boost` when testing dynamic frequency and original idle states; its readiness + checks frequency bounds, not stability. Readiness requires hardware-counter + calibration, not just governor/min/max readback. Record requested/measured + frequency and never pool or transfer gains across power profiles. +- Require an unchanged-binary A/A report before comparing candidates. Retain + failed precision gates as diagnostic results without optional sample + extensions. A quiet configuration does not itself prove adequate precision. +- Use the common library-loading measurement worker. Its CPU-time system + calls are outside measured series; batch observations are amortized means, + not individual-call latency. Keep per-call continuous/paced diagnostics + separate. Compile everything before preparation, freeze hashes and do not + rebuild or tune code/settings during the measured series. +- Finish builds and correctness tests before timing. Reserve one physical + core together with its SMT sibling using an isolated CPU partition; run + on one logical CPU and keep its sibling idle/offline. Affinity alone does + not exclude other work. Verify actual topology and CPU ownership first. +- Save original settings, arm an independent restoration watchdog and use + try/finally restoration. Verify CPU online state, IRQ/workqueue masks, + power policy, services and cgroups after completion or failure. +- Steer movable IRQs/workqueues away and record remaining kernel activity. + Do not promise zero interruptions or exclusive shared-cache/package use. +- Run benchmarks without privileges after setting up isolation. Separate + unprofiled latency from perf counters/sampling; normalize warmed counter + windows per call and check event support and multiplexing. +- Fix input hashes, warmup, cadence, process counts, balanced/randomized + order, A/A controls and acceptance criteria before collecting results. + For cadence/batch sweeps, declare explicit condition IDs, per-condition sample + units and counts, and one multiplicity family covering all compared profiles. + Use a small fixed discovery study and independent confirmation. Respect + requests for short studies; report limited precision instead of extending + the sample until a desirable result appears. +- Preregister process layout (`fixed` or `randomized`), verify effective ASLR + policy and address distributions, and retain the cohorts separately. Use + equal-length real library paths for fixed-layout comparisons. For full-audio + claims, test the decoded-PCM FFT/inference/IFFT callback and verify its spectra, + state and synthesized PCM before timing; spectral API timing alone is narrower. +- Preregister a practical noninferiority margin separately from useful gain. + Noninferiority is not proof of zero slowdown or superiority. Hosts without a + separate housekeeping L3 can receive numerical checks, not claims of strict + isolated performance under this laboratory contract. +- Retain raw observations, slow calls, binary/PGO hashes and failed attempts. + Preserve controller failure reasons and rollback verdicts in session logs. + A preparation-only retry must retain its failed audit and must not overwrite + a begun timing journal or change the registered plan. + Report mean and sample SD for calls and for process means separately, + paired process/block confidence intervals, tails and deadline misses. + Serially dependent calls are not independent statistical replicates. +- Compare incremental changes with the current selected implementation. + Never add overlapping gains or infer full-graph speed from a microbenchmark. + Assess continuous and paced workloads separately; record tested CPU scope. +- Document methods, numerical results, uncertainty and default/experimental + selection. Update affected architecture/build docs and the private backlog. + +## Completion + +Run appropriate checks and `git diff --check`. Do not push or deploy unless +requested. Include `Documentation:` with updated/not-needed entries in the +final response, alongside checks, measured effects and remaining limitations. diff --git a/justfile b/justfile new file mode 100644 index 0000000..0139b5a --- /dev/null +++ b/justfile @@ -0,0 +1,53 @@ +# Reproducible local CPU laboratory. All mutations are reversible and journaled. +set shell := ["bash", "-euo", "pipefail", "-c"] +set positional-arguments + +# Compile the common measurement/probe executable before isolating CPUs. +bench-tools: + mkdir -p .local/bench-lab + /usr/bin/gcc -O3 -Wall -Wextra -Werror -ffp-contract=off -mavx2 -mfma -Ioptimized_inference/include optimized_inference/tools/bench_lab/worker.c -ldl -lm -o .local/bench-lab/worker.tmp + mv .local/bench-lab/worker.tmp .local/bench-lab/worker + +# Reserve the discovered L3 domain and verify actual non-boost frequency. +bench-prepare cpu="3" frequency_khz="auto" ttl_seconds="1800" power_profile="steady": bench-tools + sudo -n python3 optimized_inference/tools/bench_lab/controller.py prepare --cpu "$1" --frequency-khz "$2" --ttl "$3" --power-profile "$4" --probe "$(pwd)/.local/bench-lab/worker" | tee .local/bench-lab/prepare.json + +# Refresh readiness, including three hardware-counter frequency probes. +bench-ready: + sudo -n python3 optimized_inference/tools/bench_lab/controller.py ready | tee .local/bench-lab/ready.json + +# Inspect current preparation/restoration state without another workload. +bench-status: + sudo -n python3 optimized_inference/tools/bench_lab/controller.py status + +# Run an absolute executable as the ordinary user on the reserved worker CPU. +bench-exec +command: + sudo -n python3 optimized_inference/tools/bench_lab/controller.py exec -- "$@" + +# Restore and independently read back every saved setting. Safe to repeat. +bench-restore: + sudo -n python3 optimized_inference/tools/bench_lab/controller.py restore | tee .local/bench-lab/restore.json + +# Behavioral tests do not modify the machine or require root. +bench-test: + python3 optimized_inference/tests/bench_lab_test.py + +# Fixed-size A/A control; refuses to reuse an existing output directory. +bench-aa manifest output: + python3 optimized_inference/tools/bench_lab/study.py aa "$1" "$2" + +# Comparison requires the unchanged-binary A/A report. +bench-compare manifest output aa_report: + python3 optimized_inference/tools/bench_lab/study.py compare "$1" "$2" --aa "$3" + +# Separate hardware counters and sampling; never used as latency results. +bench-profile manifest output: + python3 optimized_inference/tools/bench_lab/study.py profile "$1" "$2" + +# Recommended complete workflow: prepare, A/A, compare, profiles, finally restore. +bench-session manifest output: bench-tools + python3 optimized_inference/tools/bench_lab/study.py session "$1" "$2" + +# Continue after a fully collected A/A phase; never repeat collected samples. +bench-resume manifest output: bench-tools + python3 optimized_inference/tools/bench_lab/study.py resume "$1" "$2" diff --git a/optimized_inference/CMakeLists.txt b/optimized_inference/CMakeLists.txt index 1c88c8a..92ef080 100644 --- a/optimized_inference/CMakeLists.txt +++ b/optimized_inference/CMakeLists.txt @@ -41,6 +41,11 @@ endfunction() # Keep AVX-VNNI optional both at build time and at model initialization. # Baseline objects must remain executable on AVX2/FMA CPUs without VNNI. option(DPDF_ENABLE_AVX_VNNI "Build runtime-dispatched AVX-VNNI kernels" ON) +option(DPDF_ENABLE_QUANTIZE4_REFINEMENT "Enable experimental exact quantize4 range reuse" OFF) +option(DPDF_ENABLE_VNNI_QUANTIZE4 "Enable experimental exact four-row VNNI quantization" OFF) +if(DPDF_ENABLE_VNNI_QUANTIZE4 AND NOT DPDF_ENABLE_QUANTIZE4_REFINEMENT) + message(FATAL_ERROR "VNNI quantize4 requires DPDF_ENABLE_QUANTIZE4_REFINEMENT=ON") +endif() include(CheckCSourceCompiles) include(CMakePushCheckState) if(DPDF_ENABLE_AVX_VNNI) @@ -64,6 +69,12 @@ foreach(size IN ITEMS 2 8) target_include_directories(backend${size} PRIVATE include src src/private) target_compile_definitions(backend${size} PRIVATE DPDF_MODEL_SIZE=${size} DPDF_X86_DISPATCH DPDF_QASM64 DPDF_QFUSED64 DPDF_QPAIR_FIXED) + if(DPDF_ENABLE_VNNI_QUANTIZE4) + target_compile_definitions(backend${size} PRIVATE DPDF_VNNI_QUANTIZE4) + endif() + if(DPDF_ENABLE_QUANTIZE4_REFINEMENT) + target_compile_definitions(backend${size} PRIVATE DPDF_QUANTIZE4_REFINED) + endif() target_compile_options(backend${size} PRIVATE -include "${CMAKE_CURRENT_SOURCE_DIR}/src/private/namespace${size}.h" $<$:-fvisibility=hidden>) @@ -139,6 +150,35 @@ foreach(pair IN ITEMS "dpdfnet_train;tools/train.c" "dpdfnet_benchmark;benchmark endforeach() include(CTest) if(BUILD_TESTING) + # Compare batched quantization directly with the ordered per-row algorithm. + # Private implementation is included only in this standalone oracle target. + add_executable(quantize4_contract tests/quantize4_contract.c) + target_include_directories(quantize4_contract PRIVATE include src/private) + target_compile_definitions(quantize4_contract PRIVATE DPDF_MODEL_SIZE=2 DPDF_X86_DISPATCH) + target_compile_options(quantize4_contract PRIVATE -mavx2 -mfma -frounding-math) + target_link_libraries(quantize4_contract PRIVATE m) + dpdf_compile(quantize4_contract) + add_test(NAME quantize4_contract COMMAND quantize4_contract) + # Keep the candidate checked even when the selected baseline is built. + add_executable(quantize4_refined_contract tests/quantize4_contract.c) + target_include_directories(quantize4_refined_contract PRIVATE include src/private) + target_compile_definitions(quantize4_refined_contract PRIVATE + DPDF_MODEL_SIZE=2 DPDF_X86_DISPATCH DPDF_QUANTIZE4_REFINED) + target_compile_options(quantize4_refined_contract PRIVATE -mavx2 -mfma -frounding-math) + target_link_libraries(quantize4_refined_contract PRIVATE m) + dpdf_compile(quantize4_refined_contract) + add_test(NAME quantize4_refined_contract COMMAND quantize4_refined_contract) + if(DPDF_ENABLE_AVX_VNNI AND DPDF_COMPILER_HAS_AVX_VNNI) + add_executable(quantize4_contract_vnni tests/quantize4_contract.c) + target_include_directories(quantize4_contract_vnni PRIVATE include src/private) + target_compile_definitions(quantize4_contract_vnni PRIVATE + DPDF_MODEL_SIZE=2 DPDF_X86_DISPATCH DPDF_TEST_AVX_VNNI DPDF_VNNI_QUANTIZE4 DPDF_QUANTIZE4_REFINED) + target_compile_options(quantize4_contract_vnni PRIVATE -mavx2 -mfma -mavxvnni -frounding-math) + target_link_libraries(quantize4_contract_vnni PRIVATE m) + dpdf_compile(quantize4_contract_vnni) + add_test(NAME quantize4_contract_vnni COMMAND quantize4_contract_vnni) + set_tests_properties(quantize4_contract_vnni PROPERTIES SKIP_RETURN_CODE 77) + endif() add_executable(public_contract tests/public_contract.c) target_link_libraries(public_contract PRIVATE dpdfnet m) dpdf_compile(public_contract) @@ -158,7 +198,7 @@ if(BUILD_TESTING) "${CMAKE_CURRENT_SOURCE_DIR}/models/dpdfnet8_48khz_hr/weights.f32") foreach(size IN ITEMS 2 8) foreach(test IN ITEMS full_contract extended_contract layout_contract generated_gru_contract - conv_helpers_contract depthwise_contract int8_contract int8_dispatch_contract fused_contract pair_contract) + conv_helpers_contract depthwise_contract int8_contract int8_dispatch_contract fused_contract pair_contract cm_contract) set(target "model${size}_${test}") add_executable(${target} tests/${test}.c $) target_include_directories(${target} PRIVATE include src src/private) @@ -174,6 +214,9 @@ if(BUILD_TESTING) endif() dpdf_compile(${target}) add_test(NAME ${target} COMMAND ${target} "${CMAKE_CURRENT_SOURCE_DIR}/models/dpdfnet${size}_48khz_hr/weights.f32") + if(test STREQUAL "int8_contract" OR test STREQUAL "cm_contract") + set_tests_properties(${target} PROPERTIES SKIP_RETURN_CODE 77) + endif() endforeach() endforeach() # Scalar reference must retain its ordered multiply/add operations. @@ -190,6 +233,8 @@ if(BUILD_TESTING) endif() find_package(Python3 COMPONENTS Interpreter QUIET) if(Python3_Interpreter_FOUND) + add_test(NAME benchmark_lab COMMAND "${Python3_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/bench_lab_test.py") add_test(NAME benchmark_statistics COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/benchmark_statistics_test.py") if(BUILD_SHARED_LIBS) @@ -225,7 +270,7 @@ if(BUILD_TESTING) # Reuse the guarded scalar assembly oracles for each VNNI specialization. if(DPDF_ENABLE_AVX_VNNI AND DPDF_COMPILER_HAS_AVX_VNNI) foreach(size IN ITEMS 2 8) - set(vnni_contracts fused_contract pair_contract) + set(vnni_contracts fused_contract pair_contract cm_contract) if(size EQUAL 2) list(APPEND vnni_contracts wide_contract pair_fused_contract) endif() @@ -238,6 +283,9 @@ if(BUILD_TESTING) "SHELL:-include \"${CMAKE_CURRENT_SOURCE_DIR}/src/private/int8_vnni_aliases.h\"" -frounding-math -fno-tree-vectorize) target_compile_definitions(${target} PRIVATE DPDF_TEST_AVX_VNNI) + if(test STREQUAL "cm_contract") + target_compile_definitions(${target} PRIVATE DPDF_X86_DISPATCH DPDF_HAS_AVX_VNNI) + endif() target_link_libraries(${target} PRIVATE m) if(DPDF_PGO_MODE STREQUAL "GENERATE" AND size EQUAL 8) target_link_options(${target} PRIVATE -fprofile-generate=${DPDF_PROFILE_DIR}) @@ -248,6 +296,12 @@ if(BUILD_TESTING) endforeach() endforeach() endif() + if(DPDF_ENABLE_AVX_VNNI AND DPDF_COMPILER_HAS_AVX_VNNI AND Python3_Interpreter_FOUND) + add_test(NAME vnni_isa_contract COMMAND "${Python3_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/vnni_isa_contract.py" "${CMAKE_OBJDUMP}" + $ $ + COMMAND_EXPAND_LISTS) + endif() get_property(tests DIRECTORY PROPERTY TESTS) set_tests_properties(${tests} PROPERTIES TIMEOUT 120 ENVIRONMENT "ASAN_OPTIONS=halt_on_error=1:abort_on_error=1:handle_segv=0;UBSAN_OPTIONS=halt_on_error=1") diff --git a/optimized_inference/benchmarks/kernels.c b/optimized_inference/benchmarks/kernels.c index 1a94b63..3b30c2a 100644 --- a/optimized_inference/benchmarks/kernels.c +++ b/optimized_inference/benchmarks/kernels.c @@ -26,8 +26,8 @@ int main(int argc,char **argv) { if(iterations<100 || iterations>10000000) return 2; int kind=-1; const char *names[]={"depthwise2","depthwise3","pair40","pair48","batch40","row64", - "gates1","gates40","gates48","norm40","transpose"}; - for(int i=0;i<11;++i) if(!strcmp(argv[1],names[i])) kind=i; + "gates1","gates40","gates48","norm40","transpose","matrix128"}; + for(int i=0;i<12;++i) if(!strcmp(argv[1],names[i])) kind=i; if(kind<0) return 2; const size_t count=64*480; float *x=malloc(count*sizeof(float)),*b=malloc(count*sizeof(float)); @@ -35,7 +35,8 @@ int main(int argc,char **argv) { if(!x||!b||!w||!y||!z) return 2; for(size_t i=0;i ready-library inference -> IFFT/overlap-add callback. +Use individual paced conditions, not batch mode, for this worker. It uses the +same warmup, absolute cadence, per-process privilege/layout checks, CPPC feedback +and perf FIFO protocol as the C spectral worker. Add `audio_pipeline.py` and +`examples/dpdfnet.py` to manifest `extra_files`; pin NumPy's reported version. +This is a host-callback measurement, excluding device I/O, resampling, codecs, +audio-server scheduling and service concurrency. It is not a hardware-loopback +or production deployment test. Counter profiles must inherit the same worker +and input override; their durations remain excluded from latency inference. + +Before timing, regenerate spectra from the decoded PCM and compare them with +the pinned spectral fixtures. Compare complete synthesized PCM, every spectral +output and recurrent state for all selected libraries and both models. A final +checksum in a timing process is an additional guard, not a substitute for these +checks. State explicitly when regenerated public/stress fixtures do not reproduce +an unavailable historical corpus. + +## Practical noninferiority + +Declare `noninferiority_margin_percent` before collection (default 0.5%). +`passes_noninferiority` requires a qualified matching A/A control and a +family-adjusted gain-interval lower bound above the negative margin. It means +losses at or beyond that practical margin are excluded by this experiment's +model; it does not prove zero slowdown or useful acceleration. Report it +separately from `passes_acceptance`, deadline/fault checks and numerical gates. +An unqualified A/A cell remains inconclusive even if its point estimate is +positive. Do not increase the sample after inspecting its result. + +For multiple machines, require independent readiness and restoration on each. +A host with only one L3 domain cannot satisfy this backend's reserved-L3 plus +separate-housekeeping contract. Ready binaries may still receive low-priority +numerical portability checks there, with service health checked before/during/ +afterward, but do not label those runs isolated performance measurements. diff --git a/optimized_inference/docs/BUILD.md b/optimized_inference/docs/BUILD.md index 51f0cc7..8e9e7c2 100644 --- a/optimized_inference/docs/BUILD.md +++ b/optimized_inference/docs/BUILD.md @@ -9,6 +9,11 @@ the hand-written assembly uses the Linux System V ABI. ## Recommended release build +For performance studies, use the repository-root [benchmark laboratory](BENCHMARK_LAB.md) +and `just bench-session MANIFEST OUTPUT` after the numerical build gates. Its +prepare/readiness/restore recipes are mandatory for new performance claims; +plain benchmark affinity alone does not establish a quiet environment. + ```sh python3 tools/build.py --jobs 2 ``` @@ -154,6 +159,18 @@ query. The audio callback performs no feature detection or allocation. Only two private function pointers per quantized matrix (4,016 bytes for model 2 and 5,552 bytes for model 8 on x86-64). The public ABI is unchanged. +The K64N64 channel-major path also follows the matrix's selected ISA. +`model2_cm_contract_vnni` and `model8_cm_contract_vnni` exercise the VNNI +path against row-major projection, including floating-point control modes, +guard pages, nonfinite/subnormal inputs and overlap rejection. They skip +with status 77 when AVX-VNNI is unavailable. + +With Python available, `vnni_isa_contract` additionally disassembles both +backend object sets using the GCC toolchain's `objdump`. It rejects EVEX +instructions and verifies VEX `VPDPBUSD` encoding. This catches accidental +AVX-512 requirements that numerical tests on an AVX-512-capable CPU would +otherwise miss. Inline dot products must explicitly preserve this encoding. + The generated VNNI assembly keeps the addressing, floating-point instruction order, and ABI of the AVX2 assembly. Regenerate it after editing those sources: @@ -169,3 +186,123 @@ non-saturating `VPDPBUSD` preserves integer sums, quantization, scaling, and floating-point output. `int8_dispatch_contract` checks bitwise equality with the AVX2 implementation for both models, including single and paired kernels, row tiles and tails, extreme input values, and unaligned buffers. + +## Ryzen factorial performance recheck + +The [2026-11-10 recheck](https://github.com/varyagnord/DPDFNet/blob/6a078955909c29d857d8ad2bf02bdc01c9aa0a57/optimized_inference/validation/ryzen_vnni_retest_20261110.json) +compares baseline, CM-only, quantize4-only and their combination with separate +fresh model-8 PGO profiles. The benchmark source, compiler flags and weights +are identical across the four variants; model 2 remains non-PGO. + +CPU 3 was reserved through an isolated cpuset, its SMT sibling 15 was temporarily +offline, and movable IRQ/workqueue activity was redirected. Restoration was +verified after every phase. This excludes ordinary foreign userspace from the +worker, not all per-CPU kernel work, interrupts or shared-cache interference. + +The unprofiled experiment retains 576 fresh-process records and all 633,600 +individual call durations. Two randomized batches include balanced four-arm +blocks, two inputs, continuous and 10 ms paced execution, and A/A controls. +Report sample SD of process means separately from pooled per-call SD and SEM. +Use paired blocks, not individual calls, for effect intervals; preserve slow +observations and the preregistered multiplicity and A/A acceptance guards. + +Hardware counting/sampling is a separate phase. FIFO control starts counters +after warmup; its timings must not be used as unprofiled latency evidence. +The record includes 144 PMU jobs with fully scheduled event groups and 512 +exploratory microbench processes, including zero-row fallback and unchanged +row-path controls. Original raw artifacts and scripts are local under +`.local/retest-20261110/` at the repository root and are not bundled. + +CM's continuous call-time reduction was confirmed on this high-frequency +Ryzen core: 3.637% for model 2 and 1.609% for model 8. Neither the sub-percent +quantize4 increment nor its addition to CM passed the predeclared A/A guard. +No gain was confirmed at a 10 ms cadence. These measurements do not replace +the earlier study, establish a WCET bound, or imply compact-core/other-CPU gains. +## Exact quantize4 refinement experiment (2026-11-10) + +The range-reuse implementation is available for AVX2 and optional native VNNI. +Both experimental options default OFF: later studies confirm conditional gains, +but not global acceptance across models and workloads. See the [design and selection](QUANTIZE4_DESIGN.md) +and [aggregate evidence](https://github.com/varyagnord/DPDFNet/blob/6a078955909c29d857d8ad2bf02bdc01c9aa0a57/optimized_inference/validation/quantize4_refinement_20261110.json). + +From the repository root, configure an AVX2-only experimental build: + +```sh +cmake -S optimized_inference -B build-q4-avx2 \ + -DCMAKE_BUILD_TYPE=Release -DDPDF_ENABLE_AVX_VNNI=OFF \ + -DDPDF_ENABLE_QUANTIZE4_REFINEMENT=ON +``` + +For the native experiment, use a separate directory and additionally enable +VNNI quantize4: + +```sh +cmake -S optimized_inference -B build-q4-native \ + -DCMAKE_BUILD_TYPE=Release -DDPDF_ENABLE_QUANTIZE4_REFINEMENT=ON \ + -DDPDF_ENABLE_VNNI_QUANTIZE4=ON +``` + +Build and run CTest normally. Recreate model-8 PGO for each configuration; +do not reuse a profile from another option combination. The independent +`quantize4_refined_contract` and `quantize4_contract_vnni` check the candidate +even when the default library retains legacy quantization. + +The short study used eight paired blocks per ISA/model/cadence, two A/A pairs, +160 fresh processes / 56,000 calls and 40 separate hardware jobs. It retained +all call durations, call/run-mean SD, tails and adjusted paired intervals. +Every graph interval included zero. Helper-only active/all-empty means improved +12.198%/22.431%, which is not a full-model speedup. CPU 3 isolation and parked +SMT sibling 15 were fully restored. A reduced 16-fixture/32-model-job stream +check passed; the full 65-fixture suite was not repeated in this short study. + +The subsequent [isolated-L3 laboratory study](https://github.com/varyagnord/DPDFNet/blob/6a078955909c29d857d8ad2bf02bdc01c9aa0a57/optimized_inference/validation/quantize4_lab_20261110.json) +used the common dlopen worker, Boost off, verified nominal frequency and worker +deep-idle restriction. It retained 200 unprofiled processes / 60,800 calls plus +40 separate hardware jobs. Only native model-8 batch passed the planned A/A and +effect gates: +0.832% time reduction, adjusted interval [0.580,1.084]%. This is +a controlled non-boost result; ordinary-power and paced acceptance remains +outstanding, and both experimental options still default OFF. + +The [extended cadence/power matrix](https://github.com/varyagnord/DPDFNet/blob/6a078955909c29d857d8ad2bf02bdc01c9aa0a57/optimized_inference/validation/quantize4_regimes_20261110.json) +then covers 48 conditions with family size48, eight A/A and eight comparative +pairs each: 1,536 unprofiled processes, 442,368 calls and 192 separate counter +jobs. It confirms model-8 VNNI steady batch16/batch64/paced10 and isolated-Boost +continuous, with time reductions 0.971%/0.769%/0.835%/0.739%. Boost-paced +acceptance remains unconfirmed; ordinary full-audio deployment is not measured. +All settings are restored after each profile. See BENCHMARK_LAB.md for custom +conditions, power profiles and recovery of a fully collected A/A journal. + +## Final ready-binary qualification (2026-11-10) + +The [final qualification](https://github.com/varyagnord/DPDFNet/blob/6a078955909c29d857d8ad2bf02bdc01c9aa0a57/optimized_inference/validation/final_qualification_20261110.json) +covers both models on fast and compact Ryzen cores, steady and isolated Boost, +continuous spectral calls, paced10 spectral calls and a complete NumPy +FFT/inference/IFFT callback. One fixed plan retains 72 contrasts, 3,456 processes, +811,008 unprofiled calls, call/process SD, adjusted intervals, input/order splits +and 288 separate warmed PMU jobs. No slow observations were removed or sample +counts extended after inspecting results. Earlier layout/power cohorts were +not pooled. + +CM remains selected for both models. On fast/steady continuous calls its time +reductions are 3.127% for model 2 and 1.429% for model 8; model 8 also passes +paced10 (1.472%) and complete audio (1.448%). Native quantize4 adds 0.810% +[0.683,0.937]% continuous and 0.863% [0.513,1.213]% paced10 for model 8 in that +environment. No quantize4 model-2, AVX2 or complete-audio condition passes every +superiority gate. Compact/Boost native model-8 continuous passes practical +noninferiority at the 0.5% loss margin, not useful superiority. Both options +remain OFF. + +The complete regenerated 65-fixture numerical corpus passes 130 spectral/state +jobs and 130 PCM jobs on the PC; red passes 130 AVX2 portability jobs. All 130 +cross-host diagnostic digests match. The unavailable historical reference +corpus is not covered. Red has no VNNI or separate housekeeping L3, so it is +not a strict isolated speed test; its eight service health checks remain 200. +Production device/audio-server/service-load latency is not measured. + +Observed maximum call time is 2.787454 ms with zero 10 ms deadline misses and +zero major faults. Independent restoration verifies all CPUs online, original +power/idle/IRQ/workqueue/watchdog settings and irqbalance restored, no temporary +cgroup or workers, and global ASLR unchanged. Ready candidates additionally +pass 42 native and 32 AVX2 CTests; all 17 laboratory behavioral contracts pass. +Raw evidence/report/figures are in `.local/final-qualification-20261110/`. +No runtime default, commit, push or deployment is performed by this study. diff --git a/optimized_inference/docs/PERFORMANCE.md b/optimized_inference/docs/PERFORMANCE.md index 33ac22a..f14e5db 100644 --- a/optimized_inference/docs/PERFORMANCE.md +++ b/optimized_inference/docs/PERFORMANCE.md @@ -1,5 +1,7 @@ # Performance, memory and output quality +Latest verification (2026-11-08): a direct cumulative comparison from `afa8292` (before the three i7 optimization stages) to `cf16ba6` measures the combined result without adding historical component percentages. Continuous/performance time reductions are 11.948% / 9.019% for models 2 / 8; throughput increases are 13.569% / 9.913%. See [the direct cumulative study](#direct-cumulative-comparison-2026-11-08) for original-power results, SD/SE and adjusted intervals, and [portable evidence](https://github.com/varyagnord/DPDFNet/blob/6a078955909c29d857d8ad2bf02bdc01c9aa0a57/optimized_inference/validation/i7_7700t_total.json). Earlier incremental component measurements remain below. + The current defaults were selected separately for models 2 and 8 on an Intel Core i7-7700T. The older i7-8700 latency/quality records below describe the historical package baseline; they were not remeasured for these defaults. @@ -351,3 +353,205 @@ the historic 65-file release corpus described above and does not add perceptual quality scores. `tools/compare_streams.py` compares multiple library builds on every spectrum and complete recurrent state at every hop, including in-place buffers and reset replay. Keep these correctness jobs separate from timing. + +## Four-row exact quantization follow-up (2026-11-07) + +The AVX2 K64 batch and paired paths compute quantization parameters for four independent rows using packed exact division. Zero-range groups retain the previous per-row algorithm. The minimum remains AVX2/FMA; optional VNNI objects are byte-identical to baseline. Weights and ABI are unchanged. + +| Model | Baseline ms | Candidate ms | Time reduction | Adjusted interval | +| --- | ---: | ---: | ---: | ---: | +| 2 | 0.747387 | 0.737902 | 1.274% | [0.132, 2.403]% | +| 8 | 1.827997 | 1.807429 | 1.128% | [0.480, 1.772]% | + +Independent post-plan confirmation used 36 mirrored randomized blocks, two fresh processes per variant/block, 120 warmup and 500 timed hops, continuous neural calls, GCC14.2 PGO, performance governor/EPP, and an isolated physical i7-7700T core (CPU2 with sibling CPU6 reserved). The original screens did not pass their selection thresholds; the separately fixed follow-up and every screen are retained in the local evidence archive. The intervals use a family-four correction across two confirmations and two original-power guards. + +At the original powersave/balance_performance policy with 10ms cadence, model2 improved by 4.338% (adjusted interval [0.464, 8.062]%), while model8 remained inconclusive at 1.081% ([-2.307, 4.357]%). These are scoped local results, not end-to-end audio or cross-CPU speedup claims. + +Every spectrum and complete state matched baseline over 65 local EARS/stress streams (147,711 hops/model), including aliases/reset. The new direct quantization oracle covers 16,384 rounding/FTZ/DAZ cases and guard pages. PGO release, ASan/UBSan, AVX2-only, static and CPU-mask checks pass; six native VNNI contracts skip where that ISA is unavailable. No new perceptual quality scores are claimed. See [the portable result record](https://github.com/varyagnord/DPDFNet/blob/6a078955909c29d857d8ad2bf02bdc01c9aa0a57/optimized_inference/validation/i7_7700t_quantize4.json). Complete protocols, raw runs and logs are retained locally under `/home/varyagnord/reports/dpdfnet-opt-2026-11-07`. + + +## Model-8 original-power precision repeat (2026-11-08) + +The exact `98df765`/`26c7a9c` binaries were compared again at the original +powersave/balance_performance policy and 10 ms cadence. The fixed design uses +288 balanced randomized ABBA/BAAB blocks, 1,152 fresh processes, 120 warmup and +250 timed hops per process: 288,000 timed hops, twelve times the earlier guard. +Frame indices and recurrent history match that guard. The stopped 96×750 +workload-design pilot is archived separately and excluded; neither historical +data nor the pilot is pooled into the new estimate. No observations are removed. + +| Model | Time reduction | Primary 95% interval | Paired log-ratio SD | SE of mean log ratio | +| --- | ---: | ---: | ---: | ---: | +| 8 | +0.4627% | [-0.3447, +1.2636]% | 0.06965684 | 0.00410457 | + +The gain remains inconclusive in this power/cadence regime. Run means are +4.411520 ms (SD 0.387506) before and 4.393384 ms (SD 0.415042) after the change. +The paired arithmetic difference is 0.018136 ms, with SD 0.300840 ms, SE +0.017727 ms and 95% interval [-0.016756, +0.053027] ms. Pooled individual-hop SD +is 1.602747/1.604627 ms; this describes latency variation and is not the SE of +the mean effect. Complete blocks, rather than hops, are the statistical units. +Whole-block bootstrap, HAC lag 3 and moving-block bootstrap lengths 4/8 all retain +zero in their 95% intervals; balanced randomization p=0.26094. The old guard's +interval recomputed at the same 95% level is [-1.4950,+3.5917]%; the new interval +is 3.163 times narrower. Its historical family-four interval used 98.75%, so +comparing those different confidence levels directly would overstate precision. + +All slow runs remain. Calls above 10 ms were 0/1 and late completions 0/3, before/ +after; these few events do not establish a change in deadline-miss probability. +CPU 2 and sibling CPU 6 were reserved together as before. Ordinary work was +excluded from both; residual kernel/interrupt/package effects remain. Sampled +policy settings never changed, and CPU 6 user/nice counters did not advance. +Diagnostic monitoring began after the initial blocks. All isolation and power +settings were restored. See the [portable precision record](https://github.com/varyagnord/DPDFNet/blob/6a078955909c29d857d8ad2bf02bdc01c9aa0a57/optimized_inference/validation/i7_7700t_precision.json) +and local raw evidence under `/home/varyagnord/reports/dpdfnet-deep-2026-11-08`. + +## Channel-major pointwise follow-up (2026-11-08) + +The exact AVX2 K64×N64 pointwise path quantizes eight frequency positions directly from channel-major input and writes channel-major output with a register 4×8 transpose. It bypasses sixteen full float transposes per graph. Original min/max reduction, exact divisions, integer dot, correction/scaling/FMA and weights are retained. Other precision/shape/overlap/VNNI cases use the original chain. No new mandatory ISA is introduced. + +| Model | Baseline mean ± run SD, ms | Final mean ± run SD, ms | Time reduction | Adjusted interval | +| --- | ---: | ---: | ---: | ---: | +| 2 | 0.724998 ± 0.009977 | 0.682770 ± 0.007971 | 5.823% | [5.222, 6.421]% | +| 8 | 1.716139 ± 0.015128 | 1.661071 ± 0.014034 | 3.209% | [2.709, 3.707]% | + +Independent confirmation: 36 mirrored randomized blocks, 120 warmup and 750 timed hops per fresh process, continuous calls, performance governor/EPP, unchanged 800–3800 MHz bounds, GCC 14.2 PGO, physical CPU 2+6 reserved and workers only CPU 2. Family-eight intervals include confirmation/guards and reserved final-integration checks; discovery uses family twenty. All runs and negative outcomes remain. These percentages compare with `26c7a9c`; do not add historical gains. + +| Model | Original-power paced time reduction | Adjusted interval | Confirmed | +| --- | ---: | ---: | --- | +| 2 | 5.482% | [1.077, 9.690]% | yes | +| 8 | 0.793% | [-0.453, 2.023]% | no | + +The initial power guards use 24 blocks, 250 timed hops and 10 ms cadence. A separately fixed independent 288-block original-power model-8 repeat uses the final library; it is not pooled with its initial guard and replaces one reserved final guard within the unchanged family-eight budget. The larger model-8 quantize4 precision repeat above concerns a different code contrast. Neither power regime establishes cross-CPU or whole-audio-chain speedups. + +Other screened layout/K128/depth-specialization candidates did not establish a gain; two profile-motivated entry-prefetch variants regressed both models. The first layout-in prototype failed the decoder-skip regression before timing. The initial CM intrinsics prototype had two accumulator spills per K step; a fixed AVX2 register schedule removes those hot-loop accesses, with all correctness checks repeated before screening. None of these untimed refinements is presented as an independently timed component gain. + +Every spectrum and complete state matched on 65 local streams / 147,711 hops per model. Final contracts include 2,688 direct CM cases per model, scalar INT8 oracle with read-only guarded packing over 16 rounding/FTZ/DAZ modes, and byte-for-byte full graph parity across FP32/FP16/INT8 × all 16 masks × eight frames. Release/ASan-UBSan/AVX2-only/static and CPU-mask checks pass. Ten VNNI objects match baseline byte-for-byte; native VNNI execution/speed remains unavailable here. Seven public exports, libc/libm-only release dependencies, state ABI and owned heap are preserved. Measured/final identity or separate final confirmation is recorded. All isolation settings are restored. See the [portable deep result](https://github.com/varyagnord/DPDFNet/blob/6a078955909c29d857d8ad2bf02bdc01c9aa0a57/optimized_inference/validation/i7_7700t_deep.json). + +## Direct cumulative comparison (2026-11-08) + +This new fixed-count study directly compares `afa8292f3b8083c3daadd06dbcfe4ff877dd3172` with `cf16ba6f0e0332f65b689c6732ece60066dbefe6`. It covers GV/GVBSJ, four-row quantization and channel-major pointwise together. The baseline already includes the earlier W7A8/AVX2 runtime and optional VNNI; it is not the original PyTorch FP32 model. No component percentages or historical measurements are pooled. + +| Policy / cadence | Model | Baseline mean ± run SD, ms | Final mean ± run SD, ms | Time reduction (98.75% CI) | Throughput increase (98.75% CI) | +| --- | --- | ---: | ---: | ---: | ---: | +| performance / continuous | 2 | 0.775668 ± 0.010495 | 0.682981 ± 0.008152 | +11.948% [+11.784, +12.112]% | +13.569% [+13.358, +13.781]% | +| performance / continuous | 8 | 1.823240 ± 0.020046 | 1.658830 ± 0.022045 | +9.019% [+8.830, +9.207]% | +9.913% [+9.685, +10.141]% | +| original / 10 ms | 2 | 3.310288 ± 0.195274 | 2.884951 ± 0.188570 | +12.881% [+12.052, +13.702]% | +14.786% [+13.704, +15.878]% | +| original / 10 ms | 8 | 4.667054 ± 0.288936 | 4.668449 ± 0.333109 | +0.009% [-0.947, +0.955]% | +0.009% [-0.938, +0.965]% | + +Each model/policy cell uses 288 randomized ABBA/BAAB blocks, four fresh processes per block, 576 runs per version. Six fixed recorded inputs `original-00..05` have equal weight, 48 blocks/input and 24 orders of each type. Models are interleaved in randomized balanced round order. Every process has 120 warmup hops, followed by 600 continuous timed hops under performance governor/EPP or 250 paced timed hops at the saved powersave/balance_performance policy, with unchanged 800–3800 MHz bounds. The timed frame history matches between versions and never wraps. There are 4,608 main processes / 1,958,400 timed calls. Separate 24-block A/A controls in all four cells run before any main outcomes; all pass the fixed conditional-randomization gate. Including controls: 4,992 processes / 2,121,600 timed calls, excluding warmup, tests, training and trace probes. + +The statistical unit is the complete four-process block. The primary estimator averages block log ratios with equal input weights; SE uses within-input variances and a Welch–Satterthwaite t interval. The four aggregate model/policy contrasts use individual 98.75% intervals and Bonferroni-adjusted randomization p-values, giving at least 95% family coverage under the stated assumptions. Time reduction `100*(1-r)` and throughput increase `100*(1/r-1)` transform the same ratio and interval; they are different quantities. The arithmetic mean ± sample run SD above describes the run distribution and can differ slightly from the paired geometric effect. + +| Policy | Model | Paired difference mean, ms | Paired difference SD, ms | Stratified SE, ms | Log-ratio SD | Log-ratio SE | +| --- | --- | ---: | ---: | ---: | ---: | ---: | +| performance | 2 | 0.092687034 | 0.009311757 | 0.000550102 | 0.012546789 | 0.000741050 | +| performance | 8 | 0.164409731 | 0.024457542 | 0.001443593 | 0.013932929 | 0.000822406 | +| original | 2 | 0.425336912 | 0.184138090 | 0.010777615 | 0.064322660 | 0.003764199 | +| original | 8 | -0.001394759 | 0.298459584 | 0.017594557 | 0.064176725 | 0.003783676 | + +The original-power model-8 A/A control has a +2.996% point estimate and a t interval [0.115, 5.794]% excluding zero. Its conditional randomization raw p=0.02723 (adjusted p=0.10892) does not reach the prespecified halt threshold 0.0125; the gate passes according to that fixed rule. This discrepancy is retained explicitly. A/A is not subtracted as a fixed bias correction, and the main sample size is unchanged. Controls have only four blocks/input, versus 48 in each main cell. + +All slow runs remain, with no effect-based stopping or historical pooling. Secondary checks include 20,000 stratified whole-block bootstrap resamples, HAC lag 3, and 20,000 circular chronological residual-block resamples at lengths 4 and 8 after removing input effects; per-input and chronological-quarter effects are descriptive. Conditional randomization uses 100,000 balanced within-input assignments and the +1 correction. Individual-hop samples and pooled SD/p99/max/deadline statistics are preserved separately; individual hops are not counted as independent replications. Full numeric intervals, heterogeneity and sensitivity results are in the portable record. + +Both pinned revisions were rebuilt with GCC 14.2 and independently trained identical model-8 PGO streams (4,000 hops). Both resulting shared libraries match their corresponding archived binaries byte-for-byte; the final SO SHA256 is `d52b21267579dc3a75c22c35dc13a3d55bb3e68ddc1300ec568110c45f26c80a`. One byte-identical measurement executable resolves its own library through `$ORIGIN` in both directories. All input/weight and raw-sample hashes are checked. Baseline Release tests pass 21 / skip 6 VNNI; final tests pass 31 / skip 6. Fresh direct comparisons match every spectrum and complete state bitwise on 65 streams / 147,711 hops per model, including aliases, reset and canaries. No inference code changed for this study. + +CPU 2 and its HT sibling CPU 6 were reserved together as a cgroup v2 isolated partition; workers ran only on CPU 2 with UID 1000 and zero capabilities. Ordinary work was excluded from both logical CPUs, with movable IRQ/workqueues/watchdog steered away. All sampled policies and cpuset settings match the fixed condition; CPU 6 user/nice counters do not advance over the monitored intervals. Independent scheduler traces show only idle/bound kernel work on CPU 6. Residual bound kernel, interrupt, firmware and package effects remain. Every phase restored all saved settings, removed its cgroup and stopped the independent recovery timer. Telemetry did not select or exclude observations. + +These intervals concern repeated measurements on this CPU and six fixed inputs. The conditions differ in cadence, power policy and timed length, so their difference is not solely a governor effect. They do not establish cross-CPU performance or whole audio-pipeline acceleration. FFT, synthesis, I/O and model creation are excluded. AVX2+FMA remains the minimum; optional VNNI execution/speed is unavailable on this host. + +See [portable results and integrity](https://github.com/varyagnord/DPDFNet/blob/6a078955909c29d857d8ad2bf02bdc01c9aa0a57/optimized_inference/validation/i7_7700t_total.json), [all paired block observations](https://github.com/varyagnord/DPDFNet/blob/6a078955909c29d857d8ad2bf02bdc01c9aa0a57/optimized_inference/validation/i7_7700t_total_blocks.json). + +## Selected AVX2/VNNI defaults and final qualification (2026-11-10) + +Eligible INT8 K64N64 pointwise projections execute directly in channel-major +layout in both models. AVX2 retains its existing exact four-row quantizer; +VNNI uses the accepted CM kernel and ordinary row quantization elsewhere. +Disabling the four-row VNNI experiment does not disable model quantization. + +| Selected default, both models | AVX2 | AVX-VNNI | +| --- | --- | --- | +| Channel-major K64N64 projections | enabled | enabled | +| Legacy row-major four-row quantization | enabled | disabled | +| New range-reuse / empty-row refinement | disabled | disabled | + +`DPDF_ENABLE_AVX_VNNI=ON` builds optional runtime dispatch when the compiler +supports it; AVX2/FMA remains the fallback. Both experimental controls, +`DPDF_ENABLE_QUANTIZE4_REFINEMENT` and `DPDF_ENABLE_VNNI_QUANTIZE4`, default OFF. +The latter requires the former. No new public ABI, weight layout, persistent +cache, approximate reciprocal or implicit FMA is introduced. + +The [final qualification](https://github.com/varyagnord/DPDFNet/blob/6a078955909c29d857d8ad2bf02bdc01c9aa0a57/optimized_inference/validation/final_qualification_20261110.json) +compares pre-CM with CM native, refined quantize4 with CM-only native, and +refined with legacy AVX2. Both models are tested on fast/compact Ryzen cores, +with steady nominal frequency and isolated Boost, in continuous spectral, +paced10 spectral and complete NumPy FFT/inference/IFFT workloads. One fixed +family contains 72 primary contrasts. Each uses eight A/A and sixteen A/B +fresh-process pairs, balanced within two held-out timing inputs and both +orders. The inference units are process pairs, not serial calls. Every slow +call is retained; earlier randomized-layout studies are not pooled with this +fixed-layout cohort and sample counts are not extended after seeing results. + +The six conditions below meet all preregistered A/A, useful-effect and +operational gates. All are on the fast Ryzen core in the steady profile; +percentages are reductions in time, with family-adjusted paired-log intervals. + +| Contrast | Model | Workload | Time reduction | Adjusted interval | +| --- | ---: | --- | ---: | ---: | +| pre-CM -> CM | 2 | continuous | 3.127% | [2.887, 3.366]% | +| pre-CM -> CM | 8 | continuous | 1.429% | [1.307, 1.550]% | +| pre-CM -> CM | 8 | paced10 | 1.472% | [1.255, 1.687]% | +| pre-CM -> CM | 8 | full audio, 10 ms | 1.448% | [1.136, 1.758]% | +| CM -> CM + refined quantize4 | 8 | continuous | 0.810% | [0.683, 0.937]% | +| CM -> CM + refined quantize4 | 8 | paced10 | 0.863% | [0.513, 1.213]% | + +Only 10/72 A/A cells meet the planned 0.5% precision limit. A failed control +remains inconclusive even when its A/B interval is positive. Practical +noninferiority uses a separate predeclared 0.5% loss margin; it does not prove +zero loss or useful acceleration. Compact/Boost native model-8 continuous +passes that noninferiority gate, but not useful superiority. No model-2, +AVX2 or full-audio quantize4 condition passes every superiority gate. These +results support retaining CM and preserving quantize4 as an opt-in experiment, +not globally enabling the refinement on either model. Do not add component +percentages; the secondary direct cumulative analysis is explicitly exploratory +and reconstructs nonadjacent observations from the existing scheduled blocks. + +The plan retains 3,456 unprofiled processes / 811,008 calls and 288 separate +warmed PMU jobs. It reports individual-call and process-mean sample SD, tails, +deadline misses, measured CPPC frequency, subgroup descriptions and normalized +counter mean/SD. Observed maximum call time is 2.787454 ms, with no late +completions, calls at or above 10 ms, or major faults. This is not a WCET bound. +The complete callback excludes device I/O, resampling, codecs, audio-server +scheduling and service concurrency. No general speedup claim for every CPU or +Boost policy is made. + +All 65 regenerated public/stress fixtures (147,711 hops per model) pass +130 full spectrum/state/reset/four-alias jobs across five ready libraries on +Ryzen. Another 130 complete PCM jobs verify exact FFT-input reproduction and +bitwise equal synthesized PCM. Red i7-7700T passes 130 stream jobs across four +libraries; all 130 cross-host diagnostic digests match. Red has one shared L3 +and lacks VNNI, so its run verifies AVX2 numerical portability only. All eight +service health endpoints remain healthy and no service is reconfigured or +restarted. The unavailable historical reference corpus is not certified by +these regenerated fixtures. + +[Portable paired blocks](https://github.com/varyagnord/DPDFNet/blob/6a078955909c29d857d8ad2bf02bdc01c9aa0a57/optimized_inference/validation/final_qualification_blocks_20261110.json) +contain all 1,728 A/A and A/B pairs, their input/order, process means, call SD, +log ratios and raw-sample hashes. All 144 reported intervals were independently +reconstructed from this export before publication. Raw per-call arrays and +complete infrastructure journals remain in the local evidence archive; they +are not bundled. The original measurement source hashes describe the frozen +study, including pre-publication header whitespace. A later error-path fix +preserves controller failure/rollback JSON; it does not alter normal timing. + +Publication verification performs a fresh default PGO build: all 43 CTests +pass, including the 17 laboratory behavioral contracts. Its shared library is +byte-identical to the measured selected CM artifact, SHA-256 +`26efac06d424e8907a680cbda0ce61ac30a18a557b11cdb3f27f29466288c7ae`. +Ready refined candidates separately passed 42 native and 32 AVX2 contracts; +unchanged-source sanitizer/static/ISA gates are retained in the linked records. +All four laboratory sessions restored their settings, and independent final +readback verifies CPU online state, power/idle/IRQ/workqueue/watchdog policy, +irqbalance, absent temporary cgroup/workers, an inactive restoration timer and +unchanged global ASLR. +See [BENCHMARK_LAB.md](BENCHMARK_LAB.md) for the mandatory reproducible workflow +and [QUANTIZE4_DESIGN.md](QUANTIZE4_DESIGN.md) for exact refinement details. diff --git a/optimized_inference/docs/QUANTIZE4_DESIGN.md b/optimized_inference/docs/QUANTIZE4_DESIGN.md new file mode 100644 index 0000000..a874e0a --- /dev/null +++ b/optimized_inference/docs/QUANTIZE4_DESIGN.md @@ -0,0 +1,304 @@ +# Exact four-row quantization refinement + +Status: full registered qualification completed, 2026-11-10. Both experimental +build options remain OFF by default. Complete regenerated spectral/state/PCM +equivalence and red AVX2 portability passed for both models. The final +72-condition study confirms incremental native model-8 gains on the fast +Ryzen core at steady frequency: continuous +0.810%, paced10 +0.863%. Global +model-2/AVX2/full-audio/Boost-paced superiority remains unqualified. The selected +native path remains CM-only (`8ad669a`). See the +[final qualification](https://github.com/varyagnord/DPDFNet/blob/6a078955909c29d857d8ad2bf02bdc01c9aa0a57/optimized_inference/validation/final_qualification_20261110.json). +The earlier native quantize4 experiment is `1e2cb70`. + +## Implementation and selection + +`src/common/quantize_refined.inc` implements the shared helpers and candidate V. +`quantize_legacy.inc` preserves the selected baseline; `int8_kernels.inc` +selects between them at compile time. There is no new runtime branch or ABI. +The R and refactor-only diagnostic sources are retained in the local study. +Independent numerical contracts check the refined AVX2 and VNNI helpers even +when the baseline library is selected. The frozen oracle is intentionally +independent of both implementations. + +Enable `DPDF_ENABLE_QUANTIZE4_REFINEMENT=ON` for the AVX2 refinement. Additionally +enable `DPDF_ENABLE_VNNI_QUANTIZE4=ON` to apply it to native row-major VNNI +calls. The latter requires the former. Keep a fresh model-8 PGO profile per +configuration. These are experimental build controls, not performance presets. + +The [short refinement study](https://github.com/varyagnord/DPDFNet/blob/6a078955909c29d857d8ad2bf02bdc01c9aa0a57/optimized_inference/validation/quantize4_refinement_20261110.json) +contains 160 unprofiled processes / 56,000 calls, 16 helper discovery processes +covering all masks, and 40 separate hardware profiling jobs. CPU 3 was isolated +and sibling 15 parked; settings were restored. The helper's active/all-empty +time means decreased by 12.198%/22.431%; R regressed on some mixed masks. +Those microbench results do not establish a graph-level improvement. + +Continuous graph gain estimates for AVX2 models 2/8 were +0.113%/-0.226%, and +for native models 2/8 +0.298%/+0.588%. Every adjusted interval included zero; +paced improvements were also unconfirmed. Therefore neither default changes. +The final gated libraries are byte-identical to the measured candidate when +enabled, and to the original selected baseline when disabled, for both ISAs. + +The [isolated-L3 follow-up](https://github.com/varyagnord/DPDFNet/blob/6a078955909c29d857d8ad2bf02bdc01c9aa0a57/optimized_inference/validation/quantize4_lab_20261110.json) uses the +mandatory [benchmark laboratory](BENCHMARK_LAB.md). Native model-8 batch meets +its predeclared gate: +0.832%, adjusted interval [0.580,1.084]%, with matching +A/A precision qualified. No other condition meets all criteria. Do not combine +this verified non-boost result with earlier Boost-enabled percentages or promote +a global VNNI switch from one model/cadence under a different power policy. + +The [extended 48-condition matrix](https://github.com/varyagnord/DPDFNet/blob/6a078955909c29d857d8ad2bf02bdc01c9aa0a57/optimized_inference/validation/quantize4_regimes_20261110.json) +tests continuous calls, groups16/64 and 5/10/20 ms cadence under both registered +power profiles, with eight A/A pairs and eight comparison pairs per condition. +One family of 48 contrasts is used. Model-8 VNNI passes all gates for steady +batch16 (+0.971%, interval [0.653,1.288]%), steady batch64 (+0.769%, +[0.447,1.089]%), steady paced10 (+0.835%, [0.480,1.189]%), and isolated-Boost +continuous (+0.739%, [0.516,0.962]%). No other condition passes all gates. +Unqualified/too-small effects are not evidence of zero true benefit. + +The earlier short numerical stream check covered 16 fixtures / 32 model jobs rather +than the proposed 65 fixtures / 130 jobs, following the requested shorter run. +It includes 46,487 frames per model and the 17,996-frame recurrent history. +No historical PCM/perceptual corpus or other core/CPU was remeasured. The +confirmation used two previously known inputs, not a new held-out input corpus. + +## Objective and evidence + +Remove repeated range scans when one or more K64 rows are degenerate, while +sharing range and byte-packing code with the existing quantizer. Preserve exact +floating-point divisions, quantized bytes, scale bits and zero points. + +The completed [factorial recheck](https://github.com/varyagnord/DPDFNet/blob/6a078955909c29d857d8ad2bf02bdc01c9aa0a57/optimized_inference/validation/ryzen_vnni_retest_20261110.json) +found a useful diagnostic: ordinary batch40 improved with the old native +quantize4 experiment, but all-zero batch40 regressed by about 1.408%/3.146% +for models 2/8. These are kernel observations, not predicted improvements +from this design. At that stage, incremental full-graph benefit over CM was +unconfirmed. + +## Final ready-binary qualification + +The [final record](https://github.com/varyagnord/DPDFNet/blob/6a078955909c29d857d8ad2bf02bdc01c9aa0a57/optimized_inference/validation/final_qualification_20261110.json) retains +72 preregistered contrasts: CM versus pre-CM, refined quantize4 versus CM-only +native, and refined versus legacy AVX2; two models, three workloads, two Ryzen +core groups and two power profiles. Counts were fixed at eight A/A pairs and +sixteen comparison pairs per condition, family size 72, using two held-out +timing inputs. The fixed-layout cohort is separate from earlier randomized +layout studies. Total: 3,456 unprofiled processes, 811,008 calls and 288 separate +PMU jobs. + +The native model-8 fast/steady continuous gain is +0.810%, adjusted interval +[0.683,0.937]%; paced10 is +0.863%, [0.513,1.213]%. Both clear A/A precision +and useful-effect gates. Compact/Boost continuous model 8 meets practical +noninferiority at the predeclared 0.5% loss margin, but its useful-gain gate +does not pass. No model-2, AVX2 or full-audio quantize4 condition passes every +superiority gate. Only 10/72 A/A conditions qualify at 0.5%; failed precision +is retained as inconclusive, not zero benefit or evidence of a regression. + +All 65 regenerated public/stress fixtures (147,711 hops per model) pass +every-spectrum/state, reset/replay and four-alias checks for pre-CM and four +candidates. Another 130 complete PCM jobs verify exact FFT fixture reproduction +and bitwise equal synthesized PCM across all five libraries. Red i7-7700T +passes 130 stream jobs across four libraries; all 130 cross-host diagnostic +digests match. Its single shared L3 and lack of VNNI limit it to numerical +AVX2 checks; all eight service health endpoints remain HTTP 200. + +The original historical reference corpus was unavailable and is not certified +by these regenerated fixtures. Complete host callbacks were measured, but +device I/O, resampling, audio-server/service concurrency and hardware loopback +were not. The observed maximum 2.787454 ms and zero missed 10 ms deadlines are +finite observations, not WCET guarantees. A secondary direct cumulative +comparison uses existing nonadjacent block observations; it is explicitly +exploratory, not an added acceptance test or a sum of separate gains. + +All settings pass independent final restoration readback. Frozen binaries, +measurement sources, plans, every raw sample, call/process SD, intervals, +subgroups, counters and preparation-only failures are retained under +`.local/final-qualification-20261110/`. After collection, a separately tested +error-path fix preserves controller failure/rollback JSON in future logs; +it does not change the normal measurement path or numerical kernels. + +## Existing behavior and its cost + +The selected legacy `quantize4_64` in `src/common/quantize_legacy.inc` computes ranges row +by row. On the first `low == high`, it calls the original quantizer for all +four rows and returns. If the first degenerate row is index e (0 through 3), +this performs e+1 preliminary scans plus four fallback scans: five through +eight K64 scans. Computing every range once needs four. For an all-zero +group the scan count therefore falls from five to four, not eight to four. +This is work counting, not a proportional runtime prediction. + +The reduction includes zero in every range. A positive constant row has +range [0,c]; a negative constant row has [c,0]. Neither is degenerate. +Here, "empty" means the existing reduced `low == high` condition, not a +zero-length input, silence inferred from the source audio, or `scale == 0`. +Keep the current signed-zero, unordered-min/max and FTZ/DAZ behavior. + +## Shared internal structure + +Use private, compile-time helpers inside the shared AVX2/VNNI implementation: + +1. `range(x,k)` returns the existing low/high reduction, unchanged in its + lane accumulation and horizontal reduction order. +2. `pack(x,out,k,inv,zp)` retains the existing multiply-then-add sequence, + conversion, saturation to [0,254], and byte permutation. +3. The original single-row quantizer composes these helpers and retains its + scalar scale/zero-point calculations and degenerate early return. +4. The four-row quantizer computes four ranges once and forms an empty mask. + It then uses the same packing helper only for nonempty rows. + +These are conceptual names, not a new public API. Keep the constant-K64 +wrapper so GCC can specialize/unroll it. Do not force the generic K<=512 +wrapper to unroll or inline everywhere. Check actual assembly for duplicated +code and spills before imposing always-inline attributes. Extract helpers in +a separate change so source refactoring and new empty handling can be +compared independently. + +No heap allocation, context fields, persistent range cache, function-pointer +calls, CPU probes or new public configuration belong in this path. Reuse is +within this invocation: inputs change between frames. Do not cache ranges +across calls or introduce `restrict` without proving existing alias contracts. + +## Three group paths + +| Empty mask | Work | +| --- | --- | +| 0000 | Existing three packed exact divisions, then pack all four rows | +| 1111 | Write 256 zero bytes, four exact scales of 1 and four zero points of 0; no parameter divisions or packing | +| Other 14 masks | Reuse the four ranges; zero only empty rows; calculate and pack active rows without a rescan | + +Use one group test for all-active and one for all-empty. Initially keep the +four-row loop and conditional stores simple; benchmark before introducing +16-way dispatch, bit scans, manual unrolling, or branch-likelihood hints. +Do not add a separate input pass to detect silence. Compute the mask from +the ranges that are already required. + +## Mixed-group implementations to compare + +First implement a conservative mixed path: for each active row, compute the +original scalar parameters from its already available low/high, then pack it. +Empty rows get their original constants immediately. This establishes range +reuse without changing mixed-row division scheduling. Call this candidate R. + +Then compare candidate V, which keeps the three packed exact divisions even +in mixed groups. For empty lanes only, select a neutral low of +0 and span +of exactly 254 before the first division. For active lanes, retain the +original low and the exact `high-low` result. + +Conceptually, with selects performed using the original empty mask: + +```text +L = select(empty, +0, low) +D = select(empty, 254, high - low) +S = D / 254 +Z = clamp(round_MXCSR((-L) / S), 0, 254) +I = 1 / S +for each row: + if empty: output[0:64] = 0; scale = 1; zp = 0 + else: pack_using_existing_order(input, I, Z); scale = S; zp = Z +``` + +An empty lane now executes 254/254, signed-zero/1 and 1/1. All are exact; +it never executes a spurious 0/0 or 1/0. Do not calculate invalid divisions +first and blend their results afterward. With AVX2 there is no per-lane +arithmetic suppression from a final blend. Packing an empty row is skipped +entirely: do not use zero multiplied by an infinite inverse as a substitute +for the explicit zero output. + +Build the active-lane numerator with the original scalar unary-negation +semantics (sign-bit XOR is a candidate); verify against the oracle in every +rounding mode. The old packed helper's `0-low` must not silently become the +definition of scalar signed-zero behavior. Preserve active-lane overflow, +underflow and special-value behavior rather than "repairing" the scale. +In particular, a nonempty tiny range may produce a zero scale under some +FTZ/DAZ settings. That is not a reason to mark the row empty. + +R versus V is an empirical choice: fewer division instructions can lose to +extra selects, branches, register pressure or code layout. Sparse groups +may favor R. Choose one measured mixed implementation; do not add dynamic +CPU/vendor policy or mask-popcount thresholds without separate evidence. + +## Numerical contract and tests + +Required equivalence is bitwise output bytes, scale bits and zero points +against an independent frozen pre-change quantizer, under the supported +masked-exception environment. Preserve MXCSR control bits. The existing +contract does not prove identical sticky exception flags or trapping order: +`nearbyintf` and packed integer conversion can differ in flag behavior, and +batching changes operation order. Record flag differences diagnostically; +do not claim a new exception/trap contract or broaden it without a separate +decision. Do not replace the independent oracle with the refactored helper. + +Extend the current quantize4 test (which emphasizes first-row/all-row empty +cases) with the following matrix before speed measurement: + +- All 16 empty masks, each row position and mixed +0/-0 empty rows. +- Positive/negative constant nonzero rows, random rows, one nonzero element + in each of the 64 positions, and extrema in every SIMD lane. +- Four rounding modes times four FTZ/DAZ combinations; subnormal boundaries, + representable tiny nonzero ranges and scale underflow cases. +- Values near zero-point and packing rounding thresholds, saturation edges, + and large finite ranges. Diagnostic NaN/infinity cases preserve defined + baseline behavior; avoid treating undefined C float-to-int conversions as + a portable numerical oracle. +- Guarded input/output placements at both ends; canaries around the four + scales/zero points; input immutability. Retain network alias/reset tests. +- AVX2 and native VNNI builds for both models; ISA gates, sanitizer and static + builds, fresh model-8 PGO, and all 130 regenerated model/stream jobs. + +The baseline scalar output oracle must remain independent of extracted range +and packing helpers: otherwise the same refactoring bug can affect both sides. +Keep `-ffp-contract=off`; no fast-math, reciprocal approximation, Newton step, +changed reduction tree or unsolicited AVX-512 extension. + +## Measurement and selection + +First record the real empty-mask distribution in a separate diagnostic +driver on regenerated streams, including reset/startup and silence-like +fixtures. No counters or instrumentation in timed libraries. Source-audio +silence does not prove that recurrent intermediate rows are empty. + +Discovery microbenchmarks compare old helper, refactor-only, R and V using +all 16 masks, identical active rows and balanced randomized fresh processes. +Include batch40/pair40/pair48 and unchanged row64 controls. Retain isolated +helper measurements as diagnostics; final decisions use actual call sites. +Inspect division instructions, branches, text size and stack spills, then +collect hardware counters separately from unprofiled timing. Include branch +misses and frontend/L1I events because earlier sub-percent results were +sensitive to code shape. Test all-active performance explicitly: mixed-row +improvements must not conceal overhead in the common path. + +Freeze the selected discovery candidate, binary/PGO hashes and independent +confirmation plan before collecting confirmation data. The relevant final +contrast is **CM + refined quantize4 versus CM-only**, not a comparison that +credits it with CM's already accepted benefit. Old quantize4 + CM is an +additional diagnostic comparator. Check both models, continuous and 10 ms +cadence separately; retain AVX2 as a regression target. + +Reserve a physical core and its SMT sibling, keep the sibling idle/offline, +record residual kernel activity, and restore CPU/IRQ/workqueue settings. +Keep A/A controls, fixed sample counts, balanced order, held-out fixtures +and fresh processes. Report individual-call SD separately from run-mean SD, +paired block confidence intervals, P95/P99/max and deadline misses. Never +treat serially dependent calls as independent replicates or remove slow calls. +Set multiplicity correction, A/A precision requirement, minimum useful gain +and noninferiority margins before confirmation. An inconclusive guard is +inconclusive; do not extend the sample until it becomes favorable. + +Select only after numerical gates pass, mixed/all-empty regressions are +resolved, and the added full-graph benefit over CM clears those predefined +criteria. Preserve an experiment if only a microbenchmark improves. Validate +other core types/CPUs before making a broader claim. + +## Implementation order + +1. Freeze the old independent oracle and add complete mixed-mask coverage. +2. Extract shared range/packing helpers; run correctness and inspect codegen. +3. Implement R with one range scan per row and explicit empty outputs. +4. Implement V separately; validate neutral lanes and exact divisions. +5. Measure diagnostic mask frequencies and run controlled discovery. +6. Freeze one candidate and run independent CM-relative confirmation. + +Steps 1–6 and the full ready-binary qualification above are complete. The +regenerated 65-fixture stream/PCM corpus, compact-core coverage and red AVX2 +portability are no longer pending. Global promotion, qualified model-2/AVX2/ +full-audio/Boost-paced benefit, unavailable historical samples and production +device/service-load behavior remain outside the accepted result. The selected +runtime, model weights, ABI, dispatch and service deployment are unchanged. diff --git a/optimized_inference/src/common/extended_ops.c b/optimized_inference/src/common/extended_ops.c index 5ff786e..09f8082 100644 --- a/optimized_inference/src/common/extended_ops.c +++ b/optimized_inference/src/common/extended_ops.c @@ -51,6 +51,15 @@ dpdf_dense *dpdf_dense_create(const float *w,const float *bias,int k,int n,int p #endif return d; } +int dpdf_dense_run_cm64(dpdf_dense *d,const float *x,float *y,int rows) { +#ifdef DPDF_X86_DISPATCH + if(d->precision==8 && d->k==64 && d->n==64) + return dpdf_qaffine_cm64(d->q,x,d->bias,y,rows); +#else + (void)d;(void)x;(void)y;(void)rows; +#endif + return 0; +} void dpdf_dense_run(dpdf_dense *d,const float *x,float *y,int rows) { for (int start=0;start48) m=48; diff --git a/optimized_inference/src/common/int8.c b/optimized_inference/src/common/int8.c index 9e205ca..72a42ca 100644 --- a/optimized_inference/src/common/int8.c +++ b/optimized_inference/src/common/int8.c @@ -64,3 +64,12 @@ void dpdf_qaffine_pair(const dpdf_qmatrix *q0,const dpdf_qmatrix *q1,const float #define DPDF_QAFFINE_IMPL dpdf_qaffine_avx2 #define DPDF_QPAIR_IMPL dpdf_qaffine_pair_avx2 #include "int8_kernels.inc" + +/* Reuse the matrix's existing ISA selection; never probe inside the kernel. */ +int dpdf_qaffine_cm64(const dpdf_qmatrix *q,const float *x,const float *bias,float *y,int rows) { +#ifdef DPDF_HAS_AVX_VNNI + if (q && q->affine==dpdf_qaffine_vnni) + return dpdf_qaffine_cm64_vnni(q,x,bias,y,rows); +#endif + return qaffine_cm64_avx2(q,x,bias,y,rows); +} diff --git a/optimized_inference/src/common/int8_kernels.inc b/optimized_inference/src/common/int8_kernels.inc index 8fefbb2..26987a2 100644 --- a/optimized_inference/src/common/int8_kernels.inc +++ b/optimized_inference/src/common/int8_kernels.inc @@ -14,93 +14,12 @@ #define DPDF_USE_QPAIR_FUSED64 #endif -static void quantize(const float *x,int8_t *out,int k,float *scale,int *zp) { - __m256 lo=_mm256_setzero_ps(),hi=lo; - for (int j=0;j254) *zp=254; - __m256 inv=_mm256_set1_ps(1.0f / *scale),z=_mm256_set1_ps((float)*zp); - int j=0; - for (;j+31254) *zp=254; - __m256 inv=_mm256_set1_ps(1.0f / *scale),z=_mm256_set1_ps((float)*zp); - int j=0; - for (;j+31k,n=q->n; -#if DPDF_MODEL_SIZE == 2 || !defined(DPDF_INT8_VNNI) +#if DPDF_MODEL_SIZE == 2 || !defined(DPDF_INT8_VNNI) || defined(DPDF_VNNI_QUANTIZE4) if (k==64) { + #if !defined(DPDF_INT8_VNNI) || defined(DPDF_VNNI_QUANTIZE4) + for (int r=0;rk,n=q->n; -#if DPDF_MODEL_SIZE == 2 || !defined(DPDF_INT8_VNNI) +#if DPDF_MODEL_SIZE == 2 || !defined(DPDF_INT8_VNNI) || defined(DPDF_VNNI_QUANTIZE4) if (k==64) { for (int r=0;rk,n=q0->n; -#if DPDF_MODEL_SIZE == 2 || !defined(DPDF_INT8_VNNI) +#if DPDF_MODEL_SIZE == 2 || !defined(DPDF_INT8_VNNI) || defined(DPDF_VNNI_QUANTIZE4) if (k==64) { + #if !defined(DPDF_INT8_VNNI) || defined(DPDF_VNNI_QUANTIZE4) + for (int r=0;rk!=64 || q->n!=64 || q->affine!=DPDF_QAFFINE_IMPL || rows<=0 || rows>480 || rows%8) return 0; + size_t bytes=(size_t)rows*64*sizeof(float);uintptr_t a=(uintptr_t)x,b=(uintptr_t)y; + if(a<=b ? b-apacked+c*64+j*8)); + __m256i w1=_mm256_loadu_si256((const __m256i *)(q->packed+(c+8)*64+j*8)); + /* Bound scratch lifetimes to keep eight integer sums resident. + * The memory clobber orders activation writes before explicit loads. */ + const int8_t *a=activation+r*64+j; +#ifdef DPDF_INT8_VNNI + /* Eight resident sums, two weight vectors and one activation scratch. + * VPDPBUSD preserves the exact bounded integer reduction. */ + __asm__ volatile ( + "vpbroadcastd 0(%[a]), %%ymm14\n\t" + "%{vex%} vpdpbusd %[w0], %%ymm14, %[s0]\n\t" + "%{vex%} vpdpbusd %[w1], %%ymm14, %[t0]\n\t" + "vpbroadcastd 64(%[a]), %%ymm14\n\t" + "%{vex%} vpdpbusd %[w0], %%ymm14, %[s1]\n\t" + "%{vex%} vpdpbusd %[w1], %%ymm14, %[t1]\n\t" + "vpbroadcastd 128(%[a]), %%ymm14\n\t" + "%{vex%} vpdpbusd %[w0], %%ymm14, %[s2]\n\t" + "%{vex%} vpdpbusd %[w1], %%ymm14, %[t2]\n\t" + "vpbroadcastd 192(%[a]), %%ymm14\n\t" + "%{vex%} vpdpbusd %[w0], %%ymm14, %[s3]\n\t" + "%{vex%} vpdpbusd %[w1], %%ymm14, %[t3]\n\t" + : [s0] "+&x"(s0), [s1] "+&x"(s1), [s2] "+&x"(s2), [s3] "+&x"(s3), + [t0] "+&x"(t0), [t1] "+&x"(t1), [t2] "+&x"(t2), [t3] "+&x"(t3) + : [a] "r"(a), [w0] "x"(w0), [w1] "x"(w1) + : "ymm14","memory"); +#else + const __m256i ones=_mm256_set1_epi16(1); + __asm__ volatile ( + "vpbroadcastd 0(%[a]), %%ymm14\n\t" + "vpmaddubsw %[w0], %%ymm14, %%ymm15\n\t" + "vpmaddwd %[one], %%ymm15, %%ymm15\n\t" + "vpaddd %%ymm15, %[s0], %[s0]\n\t" + "vpmaddubsw %[w1], %%ymm14, %%ymm15\n\t" + "vpmaddwd %[one], %%ymm15, %%ymm15\n\t" + "vpaddd %%ymm15, %[t0], %[t0]\n\t" + "vpbroadcastd 64(%[a]), %%ymm14\n\t" + "vpmaddubsw %[w0], %%ymm14, %%ymm15\n\t" + "vpmaddwd %[one], %%ymm15, %%ymm15\n\t" + "vpaddd %%ymm15, %[s1], %[s1]\n\t" + "vpmaddubsw %[w1], %%ymm14, %%ymm15\n\t" + "vpmaddwd %[one], %%ymm15, %%ymm15\n\t" + "vpaddd %%ymm15, %[t1], %[t1]\n\t" + "vpbroadcastd 128(%[a]), %%ymm14\n\t" + "vpmaddubsw %[w0], %%ymm14, %%ymm15\n\t" + "vpmaddwd %[one], %%ymm15, %%ymm15\n\t" + "vpaddd %%ymm15, %[s2], %[s2]\n\t" + "vpmaddubsw %[w1], %%ymm14, %%ymm15\n\t" + "vpmaddwd %[one], %%ymm15, %%ymm15\n\t" + "vpaddd %%ymm15, %[t2], %[t2]\n\t" + "vpbroadcastd 192(%[a]), %%ymm14\n\t" + "vpmaddubsw %[w0], %%ymm14, %%ymm15\n\t" + "vpmaddwd %[one], %%ymm15, %%ymm15\n\t" + "vpaddd %%ymm15, %[s3], %[s3]\n\t" + "vpmaddubsw %[w1], %%ymm14, %%ymm15\n\t" + "vpmaddwd %[one], %%ymm15, %%ymm15\n\t" + "vpaddd %%ymm15, %[t3], %[t3]\n\t" + : [s0] "+&x"(s0), [s1] "+&x"(s1), [s2] "+&x"(s2), [s3] "+&x"(s3), [t0] "+&x"(t0), [t1] "+&x"(t1), [t2] "+&x"(t2), [t3] "+&x"(t3) + : [a] "r"(a),[w0] "x"(w0),[w1] "x"(w1),[one] "x"(ones) + : "ymm14","ymm15","memory"); +#endif + } + { + __m256i weight_sum=_mm256_loadu_si256((const __m256i *)(q->sum+c+0)); + __m256 weight_scale=_mm256_loadu_ps(q->scale+c+0),bias8=_mm256_loadu_ps(bias+c+0); + __m256 v0=_mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_add_epi32(s0,_mm256_mullo_epi32(weight_sum,_mm256_set1_epi32(-points[r+0])))),_mm256_mul_ps(_mm256_set1_ps(scales[r+0]),weight_scale),bias8); + __m256 v1=_mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_add_epi32(s1,_mm256_mullo_epi32(weight_sum,_mm256_set1_epi32(-points[r+1])))),_mm256_mul_ps(_mm256_set1_ps(scales[r+1]),weight_scale),bias8); + __m256 v2=_mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_add_epi32(s2,_mm256_mullo_epi32(weight_sum,_mm256_set1_epi32(-points[r+2])))),_mm256_mul_ps(_mm256_set1_ps(scales[r+2]),weight_scale),bias8); + __m256 v3=_mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_add_epi32(s3,_mm256_mullo_epi32(weight_sum,_mm256_set1_epi32(-points[r+3])))),_mm256_mul_ps(_mm256_set1_ps(scales[r+3]),weight_scale),bias8); + cm_store4(y,rows,f+r,c+0,v0,v1,v2,v3); + } + { + __m256i weight_sum=_mm256_loadu_si256((const __m256i *)(q->sum+c+8)); + __m256 weight_scale=_mm256_loadu_ps(q->scale+c+8),bias8=_mm256_loadu_ps(bias+c+8); + __m256 v0=_mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_add_epi32(t0,_mm256_mullo_epi32(weight_sum,_mm256_set1_epi32(-points[r+0])))),_mm256_mul_ps(_mm256_set1_ps(scales[r+0]),weight_scale),bias8); + __m256 v1=_mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_add_epi32(t1,_mm256_mullo_epi32(weight_sum,_mm256_set1_epi32(-points[r+1])))),_mm256_mul_ps(_mm256_set1_ps(scales[r+1]),weight_scale),bias8); + __m256 v2=_mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_add_epi32(t2,_mm256_mullo_epi32(weight_sum,_mm256_set1_epi32(-points[r+2])))),_mm256_mul_ps(_mm256_set1_ps(scales[r+2]),weight_scale),bias8); + __m256 v3=_mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_add_epi32(t3,_mm256_mullo_epi32(weight_sum,_mm256_set1_epi32(-points[r+3])))),_mm256_mul_ps(_mm256_set1_ps(scales[r+3]),weight_scale),bias8); + cm_store4(y,rows,f+r,c+8,v0,v1,v2,v3); + } + } + } + return 1; +} +#undef CM_TRANSPOSE8 + #undef DPDF_DOT4 diff --git a/optimized_inference/src/common/quantize_legacy.inc b/optimized_inference/src/common/quantize_legacy.inc new file mode 100644 index 0000000..a61adc0 --- /dev/null +++ b/optimized_inference/src/common/quantize_legacy.inc @@ -0,0 +1,149 @@ +/* Selected quantization baseline. Keep until the refinement passes confirmation. */ +static void quantize(const float *x,int8_t *out,int k,float *scale,int *zp) { + __m256 lo=_mm256_setzero_ps(),hi=lo; + for (int j=0;j254) *zp=254; + __m256 inv=_mm256_set1_ps(1.0f / *scale),z=_mm256_set1_ps((float)*zp); + int j=0; + for (;j+31254) *zp=254; + __m256 inv=_mm256_set1_ps(1.0f / *scale),z=_mm256_set1_ps((float)*zp); + int j=0; + for (;j+31254) *zp=254; + quantize_pack(x,out,k,1.0f / *scale,*zp); +} + +static void quantize(const float *x,int8_t *out,int k,float *scale,int *zp) { + float low,high; + quantize_range(x,k,&low,&high); + quantize_from_range(x,out,k,low,high,scale,zp); +} + +static inline __attribute__((always_inline,unused)) void quantize64( + const float *x,int8_t *out,float *scale,int *zp) { + float low,high; + quantize_range(x,64,&low,&high); + quantize_from_range(x,out,64,low,high,scale,zp); +} + +#if !defined(DPDF_INT8_VNNI) || defined(DPDF_VNNI_QUANTIZE4) +/* Each range is computed once. Empty means low==high with zero included, + * not a nonzero constant row, nor an active row whose scale underflows. */ +static void quantize4_64(const float *input,int8_t *output,float *scales,int *zps) { + float lows[4],highs[4],inverses[4]; + for (int row=0;row<4;++row) + quantize_range(input+row*64,64,lows+row,highs+row); + __m128 l=_mm_loadu_ps(lows),h=_mm_loadu_ps(highs); + __m128 empty=_mm_cmpeq_ps(l,h); + int mask=_mm_movemask_ps(empty); + if (mask==15) { + memset(output,0,256); + _mm_storeu_ps(scales,_mm_set1_ps(1.0f)); + _mm_storeu_si128((__m128i *)zps,_mm_setzero_si128()); + return; + } + __m128 span=_mm_sub_ps(h,l); + if (mask) { + /* Neutralize before division: empty lanes use 254/254, -0/1, 1/1. + * Blending results after a 0/0 would still raise invalid. */ + l=_mm_andnot_ps(empty,l); + span=_mm_blendv_ps(span,_mm_set1_ps(254.0f),empty); + } + __m128 s=_mm_div_ps(span,_mm_set1_ps(254.0f)); + _mm_storeu_ps(scales,s); + __m128 negative_low=_mm_xor_ps(l,_mm_set1_ps(-0.0f)); + __m128i points=_mm_cvtps_epi32(_mm_div_ps(negative_low,s)); + points=_mm_min_epi32(_mm_set1_epi32(254),_mm_max_epi32(_mm_setzero_si128(),points)); + _mm_storeu_si128((__m128i *)zps,points); + _mm_storeu_ps(inverses,_mm_div_ps(_mm_set1_ps(1.0f),s)); + if (!mask) { + for (int row=0;row<4;++row) + quantize_pack(input+row*64,output+row*64,64,inverses[row],zps[row]); + } else { + for (int row=0;row<4;++row) { + if (mask & (1<arena+38512)[i]=((m->arena+7792)[i]>0?(m->arena+77 /* 48: Conv /model/enc/erb_conv1/erb_conv1.0/Conv */ dpdf_convop_run(m->conv[1],(m->arena+38512),(m->arena+4896)); /* 49: Conv /model/enc/erb_conv1/erb_conv1.1/Conv */ +if (!dpdf_dense_run_cm64(m->dense[0],(m->arena+4896),(m->arena+15136),160)) { m->transpose((m->arena+4896),(m->arena+25376),64,160); dpdf_dense_run(m->dense[0],(m->arena+25376),(m->arena+69232),160); m->transpose((m->arena+69232),(m->arena+15136),160,64); +} /* 50: Relu /model/enc/erb_conv1/erb_conv1.3/Relu */ for (int i=0;i<10240;++i) (m->arena+4896)[i]=((m->arena+15136)[i]>0?(m->arena+15136)[i]:0.0f); /* 51: Conv /model/enc/erb_conv2/erb_conv2.0/Conv */ dpdf_convop_run(m->conv[2],(m->arena+4896),(m->arena+69232)); /* 52: Conv /model/enc/erb_conv2/erb_conv2.1/Conv */ +if (!dpdf_dense_run_cm64(m->dense[1],(m->arena+69232),(m->arena+74352),80)) { m->transpose((m->arena+69232),(m->arena+15136),64,80); dpdf_dense_run(m->dense[1],(m->arena+15136),(m->arena+20256),80); m->transpose((m->arena+20256),(m->arena+74352),80,64); +} /* 53: Relu /model/enc/erb_conv2/erb_conv2.3/Relu */ for (int i=0;i<5120;++i) (m->arena+69232)[i]=((m->arena+74352)[i]>0?(m->arena+74352)[i]:0.0f); /* 54: Conv /model/enc/erb_conv3/erb_conv3.0/Conv */ dpdf_convop_run(m->conv[3],(m->arena+69232),(m->arena+74352)); /* 55: Conv /model/enc/erb_conv3/erb_conv3.1/Conv */ +if (!dpdf_dense_run_cm64(m->dense[2],(m->arena+74352),(m->arena+76912),40)) { m->transpose((m->arena+74352),(m->arena+15136),64,40); dpdf_dense_run(m->dense[2],(m->arena+15136),(m->arena+17696),40); m->transpose((m->arena+17696),(m->arena+76912),40,64); +} /* 56: Relu /model/enc/erb_conv3/erb_conv3.3/Relu */ for (int i=0;i<2560;++i) (m->arena+74352)[i]=((m->arena+76912)[i]>0?(m->arena+76912)[i]:0.0f); /* 57: Slice /model/enc/dprnn_erb/blocks.0/inter_gru/Slice */ @@ -461,17 +467,21 @@ dpdf_convop_run(m->conv[5],((m->arena+2144)+288),(m->arena+25888)); for (int b=0;b<1;++b) memcpy((m->arena+28960)+b*6144+0,(m->arena+22816)+b*3072,3072*sizeof(float)); for (int b=0;b<1;++b) memcpy((m->arena+28960)+b*6144+3072,(m->arena+25888)+b*3072,3072*sizeof(float)); /* 74: Conv /model/enc/df_conv0/df_conv0.2/Conv */ +if (!dpdf_dense_run_cm64(m->dense[3],(m->arena+28960),(m->arena+22816),96)) { m->transpose((m->arena+28960),(m->arena+79472),64,96); dpdf_dense_run(m->dense[3],(m->arena+79472),(m->arena+85616),96); m->transpose((m->arena+85616),(m->arena+22816),96,64); +} /* 75: Relu /model/enc/df_conv0/df_conv0.4/Relu */ for (int i=0;i<6144;++i) (m->arena+28960)[i]=((m->arena+22816)[i]>0?(m->arena+22816)[i]:0.0f); /* 76: Conv /model/enc/df_conv1/df_conv1.0/Conv */ dpdf_convop_run(m->conv[6],(m->arena+28960),(m->arena+35104)); /* 77: Conv /model/enc/df_conv1/df_conv1.1/Conv */ +if (!dpdf_dense_run_cm64(m->dense[4],(m->arena+35104),(m->arena+22816),48)) { m->transpose((m->arena+35104),(m->arena+25888),64,48); dpdf_dense_run(m->dense[4],(m->arena+25888),(m->arena+76912),48); m->transpose((m->arena+76912),(m->arena+22816),48,64); +} /* 78: Relu /model/enc/df_conv1/df_conv1.3/Relu */ for (int i=0;i<3072;++i) (m->arena+25888)[i]=((m->arena+22816)[i]>0?(m->arena+22816)[i]:0.0f); /* 79: Slice /model/enc/dprnn_df/blocks.0/inter_gru/Slice */ @@ -610,9 +620,11 @@ for (int b=0;b<1;++b) memcpy((m->arena+79984)+b*5120+2560,(m->arena+25376)+b*256 for (int t1=0;t1<64;++t1) for (int t3=0;t3<40;++t3) for (int t4=0;t4<2;++t4) (m->arena+22816)[t1*80+t3*2+t4*1]=(m->arena+79984)[t1*40+t3*1+t4*2560]; /* 198: Reshape /model/erb_dec/convt3/convt3.0/Reshape_1 */ /* 199: Conv /model/erb_dec/convt3/convt3.1/Conv */ +if (!dpdf_dense_run_cm64(m->dense[171],(m->arena+22816),(m->arena+79984),80)) { m->transpose((m->arena+22816),(m->arena+85104),64,80); dpdf_dense_run(m->dense[171],(m->arena+85104),(m->arena+91760),80); m->transpose((m->arena+91760),(m->arena+79984),80,64); +} /* 200: Relu /model/erb_dec/convt3/convt3.3/Relu */ for (int i=0;i<5120;++i) (m->arena+22816)[i]=((m->arena+79984)[i]>0?(m->arena+79984)[i]:0.0f); /* 201: Conv /model/erb_dec/conv2p/conv2p.0/Conv */ @@ -633,9 +645,11 @@ for (int b=0;b<1;++b) memcpy((m->arena+79984)+b*10240+5120,(m->arena+69232)+b*51 for (int t1=0;t1<64;++t1) for (int t3=0;t3<80;++t3) for (int t4=0;t4<2;++t4) (m->arena+96880)[t1*160+t3*2+t4*1]=(m->arena+79984)[t1*80+t3*1+t4*5120]; /* 209: Reshape /model/erb_dec/convt2/convt2.0/Reshape_1 */ /* 210: Conv /model/erb_dec/convt2/convt2.1/Conv */ +if (!dpdf_dense_run_cm64(m->dense[172],(m->arena+96880),(m->arena+79984),160)) { m->transpose((m->arena+96880),(m->arena+107120),64,160); dpdf_dense_run(m->dense[172],(m->arena+107120),(m->arena+117360),160); m->transpose((m->arena+117360),(m->arena+79984),160,64); +} /* 211: Relu /model/erb_dec/convt2/convt2.3/Relu */ for (int i=0;i<10240;++i) (m->arena+90224)[i]=((m->arena+79984)[i]>0?(m->arena+79984)[i]:0.0f); /* 212: Conv /model/erb_dec/conv1p/conv1p.0/Conv */ @@ -659,9 +673,11 @@ for (int b=0;b<1;++b) memcpy((m->arena+127600)+b*30720+20480,(m->arena+100464)+b for (int t1=0;t1<64;++t1) for (int t3=0;t3<160;++t3) for (int t4=0;t4<3;++t4) (m->arena+79984)[t1*480+t3*3+t4*1]=(m->arena+127600)[t1*160+t3*1+t4*10240]; /* 221: Reshape /model/erb_dec/convt1/convt1.0/Reshape_1 */ /* 222: Conv /model/erb_dec/convt1/convt1.1/Conv */ +if (!dpdf_dense_run_cm64(m->dense[173],(m->arena+79984),(m->arena+110704),480)) { m->transpose((m->arena+79984),(m->arena+158320),64,480); dpdf_dense_run(m->dense[173],(m->arena+158320),(m->arena+189040),480); m->transpose((m->arena+189040),(m->arena+110704),480,64); +} /* 223: Relu /model/erb_dec/convt1/convt1.3/Relu */ for (int i=0;i<30720;++i) (m->arena+79984)[i]=((m->arena+110704)[i]>0?(m->arena+110704)[i]:0.0f); /* 224: Conv /model/erb_dec/conv0p/conv0p.0/Conv */ diff --git a/optimized_inference/src/models/dpdfnet8_48khz_hr/generated_model.c b/optimized_inference/src/models/dpdfnet8_48khz_hr/generated_model.c index 6925281..5996454 100644 --- a/optimized_inference/src/models/dpdfnet8_48khz_hr/generated_model.c +++ b/optimized_inference/src/models/dpdfnet8_48khz_hr/generated_model.c @@ -427,25 +427,31 @@ for (int i=0;i<30720;++i) (m->arena+38512)[i]=((m->arena+7792)[i]>0?(m->arena+77 /* 48: Conv /model/enc/erb_conv1/erb_conv1.0/Conv */ dpdf_convop_run(m->conv[1],(m->arena+38512),(m->arena+4896)); /* 49: Conv /model/enc/erb_conv1/erb_conv1.1/Conv */ +if (!dpdf_dense_run_cm64(m->dense[0],(m->arena+4896),(m->arena+15136),160)) { m->transpose((m->arena+4896),(m->arena+25376),64,160); dpdf_dense_run(m->dense[0],(m->arena+25376),(m->arena+69232),160); m->transpose((m->arena+69232),(m->arena+15136),160,64); +} /* 50: Relu /model/enc/erb_conv1/erb_conv1.3/Relu */ for (int i=0;i<10240;++i) (m->arena+4896)[i]=((m->arena+15136)[i]>0?(m->arena+15136)[i]:0.0f); /* 51: Conv /model/enc/erb_conv2/erb_conv2.0/Conv */ dpdf_convop_run(m->conv[2],(m->arena+4896),(m->arena+69232)); /* 52: Conv /model/enc/erb_conv2/erb_conv2.1/Conv */ +if (!dpdf_dense_run_cm64(m->dense[1],(m->arena+69232),(m->arena+74352),80)) { m->transpose((m->arena+69232),(m->arena+15136),64,80); dpdf_dense_run(m->dense[1],(m->arena+15136),(m->arena+20256),80); m->transpose((m->arena+20256),(m->arena+74352),80,64); +} /* 53: Relu /model/enc/erb_conv2/erb_conv2.3/Relu */ for (int i=0;i<5120;++i) (m->arena+69232)[i]=((m->arena+74352)[i]>0?(m->arena+74352)[i]:0.0f); /* 54: Conv /model/enc/erb_conv3/erb_conv3.0/Conv */ dpdf_convop_run(m->conv[3],(m->arena+69232),(m->arena+74352)); /* 55: Conv /model/enc/erb_conv3/erb_conv3.1/Conv */ +if (!dpdf_dense_run_cm64(m->dense[2],(m->arena+74352),(m->arena+76912),40)) { m->transpose((m->arena+74352),(m->arena+15136),64,40); dpdf_dense_run(m->dense[2],(m->arena+15136),(m->arena+17696),40); m->transpose((m->arena+17696),(m->arena+76912),40,64); +} /* 56: Relu /model/enc/erb_conv3/erb_conv3.3/Relu */ for (int i=0;i<2560;++i) (m->arena+74352)[i]=((m->arena+76912)[i]>0?(m->arena+76912)[i]:0.0f); /* 57: Slice /model/enc/dprnn_erb/blocks.0/inter_gru/Slice */ @@ -494,17 +500,21 @@ dpdf_convop_run(m->conv[5],((m->arena+2144)+288),(m->arena+82544)); for (int b=0;b<1;++b) memcpy((m->arena+85616)+b*6144+0,(m->arena+79472)+b*3072,3072*sizeof(float)); for (int b=0;b<1;++b) memcpy((m->arena+85616)+b*6144+3072,(m->arena+82544)+b*3072,3072*sizeof(float)); /* 86: Conv /model/enc/df_conv0/df_conv0.2/Conv */ +if (!dpdf_dense_run_cm64(m->dense[3],(m->arena+85616),(m->arena+76912),96)) { m->transpose((m->arena+85616),(m->arena+91760),64,96); dpdf_dense_run(m->dense[3],(m->arena+91760),(m->arena+97904),96); m->transpose((m->arena+97904),(m->arena+76912),96,64); +} /* 87: Relu /model/enc/df_conv0/df_conv0.4/Relu */ for (int i=0;i<6144;++i) (m->arena+83056)[i]=((m->arena+76912)[i]>0?(m->arena+76912)[i]:0.0f); /* 88: Conv /model/enc/df_conv1/df_conv1.0/Conv */ dpdf_convop_run(m->conv[6],(m->arena+83056),(m->arena+76912)); /* 89: Conv /model/enc/df_conv1/df_conv1.1/Conv */ +if (!dpdf_dense_run_cm64(m->dense[4],(m->arena+76912),(m->arena+79984),48)) { m->transpose((m->arena+76912),(m->arena+89200),64,48); dpdf_dense_run(m->dense[4],(m->arena+89200),(m->arena+92272),48); m->transpose((m->arena+92272),(m->arena+79984),48,64); +} /* 90: Relu /model/enc/df_conv1/df_conv1.3/Relu */ for (int i=0;i<3072;++i) (m->arena+76912)[i]=((m->arena+79984)[i]>0?(m->arena+79984)[i]:0.0f); /* 91: Slice /model/enc/dprnn_df/blocks.0/inter_gru/Slice */ @@ -661,9 +671,11 @@ for (int b=0;b<1;++b) memcpy((m->arena+116336)+b*5120+2560,(m->arena+76912)+b*25 for (int t1=0;t1<64;++t1) for (int t3=0;t3<40;++t3) for (int t4=0;t4<2;++t4) (m->arena+74352)[t1*80+t3*2+t4*1]=(m->arena+116336)[t1*40+t3*1+t4*2560]; /* 222: Reshape /model/erb_dec/convt3/convt3.0/Reshape_1 */ /* 223: Conv /model/erb_dec/convt3/convt3.1/Conv */ +if (!dpdf_dense_run_cm64(m->dense[171],(m->arena+74352),(m->arena+116336),80)) { m->transpose((m->arena+74352),(m->arena+121456),64,80); dpdf_dense_run(m->dense[171],(m->arena+121456),(m->arena+126576),80); m->transpose((m->arena+126576),(m->arena+116336),80,64); +} /* 224: Relu /model/erb_dec/convt3/convt3.3/Relu */ for (int i=0;i<5120;++i) (m->arena+74352)[i]=((m->arena+116336)[i]>0?(m->arena+116336)[i]:0.0f); /* 225: Conv /model/erb_dec/conv2p/conv2p.0/Conv */ @@ -684,9 +696,11 @@ for (int b=0;b<1;++b) memcpy((m->arena+69232)+b*10240+5120,(m->arena+126576)+b*5 for (int t1=0;t1<64;++t1) for (int t3=0;t3<80;++t3) for (int t4=0;t4<2;++t4) (m->arena+116336)[t1*160+t3*2+t4*1]=(m->arena+69232)[t1*80+t3*1+t4*5120]; /* 233: Reshape /model/erb_dec/convt2/convt2.0/Reshape_1 */ /* 234: Conv /model/erb_dec/convt2/convt2.1/Conv */ +if (!dpdf_dense_run_cm64(m->dense[172],(m->arena+116336),(m->arena+69232),160)) { m->transpose((m->arena+116336),(m->arena+131696),64,160); dpdf_dense_run(m->dense[172],(m->arena+131696),(m->arena+141936),160); m->transpose((m->arena+141936),(m->arena+69232),160,64); +} /* 235: Relu /model/erb_dec/convt2/convt2.3/Relu */ for (int i=0;i<10240;++i) (m->arena+116336)[i]=((m->arena+69232)[i]>0?(m->arena+69232)[i]:0.0f); /* 236: Conv /model/erb_dec/conv1p/conv1p.0/Conv */ @@ -710,9 +724,11 @@ for (int b=0;b<1;++b) memcpy((m->arena+152176)+b*30720+20480,(m->arena+126576)+b for (int t1=0;t1<64;++t1) for (int t3=0;t3<160;++t3) for (int t4=0;t4<3;++t4) (m->arena+116336)[t1*480+t3*3+t4*1]=(m->arena+152176)[t1*160+t3*1+t4*10240]; /* 245: Reshape /model/erb_dec/convt1/convt1.0/Reshape_1 */ /* 246: Conv /model/erb_dec/convt1/convt1.1/Conv */ +if (!dpdf_dense_run_cm64(m->dense[173],(m->arena+116336),(m->arena+147056),480)) { m->transpose((m->arena+116336),(m->arena+182896),64,480); dpdf_dense_run(m->dense[173],(m->arena+182896),(m->arena+213616),480); m->transpose((m->arena+213616),(m->arena+147056),480,64); +} /* 247: Relu /model/erb_dec/convt1/convt1.3/Relu */ for (int i=0;i<30720;++i) (m->arena+116336)[i]=((m->arena+147056)[i]>0?(m->arena+147056)[i]:0.0f); /* 248: Conv /model/erb_dec/conv0p/conv0p.0/Conv */ diff --git a/optimized_inference/src/private/extended_ops.h b/optimized_inference/src/private/extended_ops.h index 9367223..8281d3c 100644 --- a/optimized_inference/src/private/extended_ops.h +++ b/optimized_inference/src/private/extended_ops.h @@ -7,6 +7,7 @@ typedef struct dpdf_convop dpdf_convop; * Dense source is input-major; tiled=64 accepts [N/64,K,64] source packing. */ dpdf_dense *dpdf_dense_create(const float *,const float *,int,int,int,int); void dpdf_dense_destroy(dpdf_dense *); +int dpdf_dense_run_cm64(dpdf_dense *,const float *,float *,int); void dpdf_dense_run(dpdf_dense *,const float *,float *,int); size_t dpdf_dense_bytes(const dpdf_dense *); dpdf_convop *dpdf_convop_create(const float *,const float *,int,int,int,int,int,int,int,int,int,int,int,int,int,int); diff --git a/optimized_inference/src/private/int8_matrix.h b/optimized_inference/src/private/int8_matrix.h index 343aa74..91c2d90 100644 --- a/optimized_inference/src/private/int8_matrix.h +++ b/optimized_inference/src/private/int8_matrix.h @@ -21,6 +21,7 @@ void dpdf_qaffine_avx2(const dpdf_qmatrix *,const float *,const float *,float *, void dpdf_qaffine_pair_avx2(const dpdf_qmatrix *,const dpdf_qmatrix *,const float *, const float *,const float *,float *,float *,int); #ifdef DPDF_HAS_AVX_VNNI +int dpdf_qaffine_cm64_vnni(const dpdf_qmatrix *,const float *,const float *,float *,int); void dpdf_qaffine_vnni(const dpdf_qmatrix *,const float *,const float *,float *,int); void dpdf_qaffine_pair_vnni(const dpdf_qmatrix *,const dpdf_qmatrix *,const float *, const float *,const float *,float *,float *,int); diff --git a/optimized_inference/src/private/internal.h b/optimized_inference/src/private/internal.h index 0d1591c..0df64cc 100644 --- a/optimized_inference/src/private/internal.h +++ b/optimized_inference/src/private/internal.h @@ -13,6 +13,7 @@ typedef struct dpdf_qmatrix dpdf_qmatrix; dpdf_qmatrix *dpdf_qcreate(const float *, int, int); void dpdf_qdestroy(dpdf_qmatrix *); size_t dpdf_qbytes(const dpdf_qmatrix *); +int dpdf_qaffine_cm64(const dpdf_qmatrix *,const float *,const float *,float *,int); void dpdf_qaffine(const dpdf_qmatrix *, const float *, const float *, float *, int); void dpdf_qaffine_pair(const dpdf_qmatrix *, const dpdf_qmatrix *, const float *, const float *, const float *, float *, float *, int); diff --git a/optimized_inference/src/private/namespace2.h b/optimized_inference/src/private/namespace2.h index 3f534da..4e35262 100644 --- a/optimized_inference/src/private/namespace2.h +++ b/optimized_inference/src/private/namespace2.h @@ -90,3 +90,7 @@ #define dpdf_qaffine64_fused_vnni dpdfnet2_private_qaffine64_fused_vnni #define dpdf_qaffine256_fused_vnni dpdfnet2_private_qaffine256_fused_vnni #define dpdf_qaffine4pair64_fused_vnni dpdfnet2_private_qaffine4pair64_fused_vnni + +#define dpdf_qaffine_cm64 dpdfnet2_private_qaffine_cm64 +#define dpdf_qaffine_cm64_vnni dpdfnet2_private_qaffine_cm64_vnni +#define dpdf_dense_run_cm64 dpdfnet2_private_dense_run_cm64 diff --git a/optimized_inference/src/private/namespace8.h b/optimized_inference/src/private/namespace8.h index 31d9097..b790121 100644 --- a/optimized_inference/src/private/namespace8.h +++ b/optimized_inference/src/private/namespace8.h @@ -86,3 +86,7 @@ #define dpdf_qaffine64_fused_vnni dpdfnet8_private_qaffine64_fused_vnni #define dpdf_qaffine256_fused_vnni dpdfnet8_private_qaffine256_fused_vnni #define dpdf_qaffine4pair64_fused_vnni dpdfnet8_private_qaffine4pair64_fused_vnni + +#define dpdf_qaffine_cm64 dpdfnet8_private_qaffine_cm64 +#define dpdf_qaffine_cm64_vnni dpdfnet8_private_qaffine_cm64_vnni +#define dpdf_dense_run_cm64 dpdfnet8_private_dense_run_cm64 diff --git a/optimized_inference/tests/bench_lab_test.py b/optimized_inference/tests/bench_lab_test.py new file mode 100644 index 0000000..55d0e2b --- /dev/null +++ b/optimized_inference/tests/bench_lab_test.py @@ -0,0 +1,163 @@ +"""Behavioral contracts for root control logic; no privileged writes.""" +import importlib.util +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +SPEC = importlib.util.spec_from_file_location('lab', Path(__file__).resolve().parents[1] / 'tools/bench_lab/controller.py') +lab = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(lab) + + +class LabContracts(unittest.TestCase): + def test_cpu_masks_across_32bit_boundary(self): + self.assertEqual(lab.cpus('0-3,12-15'), {0,1,2,3,12,13,14,15}) + self.assertEqual(lab.cpumask({0,32,63}), '80000001,00000001') + with self.assertRaises(ValueError): + lab.cpus('1;reboot') + + def test_discovers_cache_domain_not_fixed_cpu_numbers(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d) + (root / 'online').write_text('0-7') + for path, value in {'cpu3/cache/index3/level':'3', 'cpu3/cache/index3/type':'Unified', + 'cpu3/cache/index3/shared_cpu_list':'2-3,6-7', + 'cpu3/topology/thread_siblings_list':'3,7'}.items(): + p=root/path;p.parent.mkdir(parents=True,exist_ok=True);p.write_text(value) + with patch.object(lab,'CPU',root): + online,reserved,siblings,house=lab.topology(3) + self.assertEqual(reserved,{2,3,6,7}) + self.assertEqual(siblings,{3,7}) + self.assertEqual(house,{0,1,4,5}) + + def test_journal_is_durable_before_write(self): + with tempfile.TemporaryDirectory() as d: + p=Path(d)/'setting';p.write_text('old') + state={'journal':[]};saved=[] + original=lab.write + def observed(path,value): + self.assertTrue(saved) + self.assertEqual(saved[-1][0]['before'],'old') + original(path,value) + with patch.object(lab,'save',lambda s:saved.append([x.copy() for x in s['journal']])),patch.object(lab,'write',observed): + lab.change(state,p,'new') + self.assertEqual(state['journal'][0]['applied'],'new') + + def test_optional_unwritable_irq_is_retained_as_diagnostic(self): + with tempfile.TemporaryDirectory() as d: + p=Path(d)/'irq';p.write_text('0-3');state={'journal':[]} + with patch.object(lab,'save'),patch.object(lab,'write',side_effect=PermissionError('managed IRQ')): + lab.change(state,p,'4-7',optional=True) + self.assertIn('error',state['journal'][0]) + self.assertEqual(p.read_text(),'0-3') + + def test_frequency_bound_order_handles_both_directions(self): + for initial,target in [((100,200),(300,300)),((300,400),(100,100)),((100,400),(200,200))]: + with tempfile.TemporaryDirectory() as d: + p=Path(d) + for name,value in zip(['scaling_min_freq','scaling_max_freq'],initial):(p/name).write_text(str(value)) + original=lab.write + def checked(path,value): + low=int(lab.read(p/'scaling_min_freq'));high=int(lab.read(p/'scaling_max_freq')) + self.assertTrue(int(value)<=high if Path(path).name=='scaling_min_freq' else int(value)>=low) + original(path,value) + with patch.object(lab,'write',checked):lab.set_limits(p,*target) + self.assertEqual((int(lab.read(p/'scaling_min_freq')),int(lab.read(p/'scaling_max_freq'))),target) + + def test_zombie_is_not_a_runnable_foreign_thread(self): + with patch.object(Path,'glob',return_value=[Path('/proc/42')]),patch.object(lab,'identity',return_value=dict(state='Z',flags=0)),patch.object(lab.os,'sched_getaffinity',side_effect=AssertionError('zombie must not count')): + self.assertEqual(lab.foreign_threads({'reserved':[0,1]}),[]) + + def test_changed_probe_is_rejected_before_execution(self): + with tempfile.TemporaryDirectory() as d: + p=Path(d)/'probe';p.write_text('changed') + with patch.object(lab,'verify'),patch.object(lab.subprocess,'check_output',side_effect=AssertionError('must not execute')): + with self.assertRaises(RuntimeError):lab.calibrate({'probe':str(p),'probe_sha256':'old'}) + + def test_boost_validation_is_not_fixed_frequency_validation(self): + r=[{'effective_khz':v} for v in [2000000,4000000,5000000]] + s=dict(power_profile='boost',worker_power=dict(scaling_min_freq='600000',scaling_max_freq='5300000')) + self.assertTrue(lab.frequency_qualified(r,s)) + self.assertFalse(lab.frequency_qualified(r,dict(power_profile='steady',frequency_khz=2000000))) + self.assertFalse(lab.frequency_qualified([{'effective_khz':9000000}],s)) + + def test_completed_restore_is_idempotent(self): + result={'restored':True,'errors':[]} + with patch.object(lab,'write',side_effect=AssertionError('unexpected mutation')): + self.assertEqual(lab.restore({'phase':'restored','restoration':result}),result) + + +class StudyContracts(unittest.TestCase): + @classmethod + def setUpClass(cls): + spec=importlib.util.spec_from_file_location('study',Path(__file__).resolve().parents[1]/'tools/bench_lab/study.py') + cls.study=importlib.util.module_from_spec(spec);spec.loader.exec_module(cls.study) + + def test_controller_failure_preserves_reason_and_rollback_verdict(self): + detail='{"error":"Frequency policy changed: scaling_min_freq","phase":"restored","restoration":{"restored":true}}' + failure=self.study.subprocess.CalledProcessError(1,['controller','prepare'],output=detail) + with patch.object(self.study.subprocess,'check_output',side_effect=failure): + with self.assertRaises(RuntimeError) as captured: + self.study.control('prepare') + self.assertIn('Frequency policy changed: scaling_min_freq',str(captured.exception)) + self.assertIn('"restored":true',str(captured.exception)) + + def test_order_balances_within_each_input(self): + from collections import defaultdict,Counter + m=dict(seed=123,aa_blocks=4,compare_blocks=8,variants={'native':{},'avx2':{}},models=[2,8],inputs=['x','y']) + for kind in ['aa','compare']: + jobs=self.study.schedule(m,kind);orders=defaultdict(Counter) + for j in jobs[::2]:orders[j['isa'],j['model'],j['mode'],j['input']][j['label']]+=1 + for v in orders.values():self.assertEqual(v['A'],v['B']) + if kind=='aa':self.assertTrue(all(j['arm']=='baseline' for j in jobs)) + + def test_custom_condition_order_and_cadence(self): + m=dict(seed=9,aa_blocks=8,compare_blocks=8,models=[2,8],variants={'native':{'baseline':'/a','candidate':'/b'}},inputs=['x','y'],worker='/worker',weights={'2':'/w2','8':'/w8'}, + conditions=[dict(id='batch64',worker_mode='batch',batch_size=64,calls=512),dict(id='paced20',worker_mode='paced',batch_size=1,calls=64,period_ns=20000000)]) + jobs=self.study.schedule(m,'aa') + self.assertEqual(len(jobs),64) + j=next(j for j in jobs if j['mode']=='paced20') + args=self.study.worker_args(m,j,Path('/raw')) + self.assertEqual(args[-3:],["paced:20000000","1","/raw"]) + self.assertEqual(len(set((j['mode'],j['model']) for j in jobs)),4) + + def test_summary_handles_explicit_family_and_conditions(self): + import array + with tempfile.TemporaryDirectory() as d: + root=Path(d);rows=[] + for block in range(4): + for label in ['A','B']: + name=f'{block}-{label}.f64';(root/name).write_bytes(array.array('d',[1.,1.]).tobytes()) + rows.append(dict(block=block,isa='native',model=2,mode='batch16',label=label,samples=name, + result=dict(mean_ms=1.,calls=2,observation_unit='batch_mean',reference_delta=2,delivered_delta=2,late=0,over_10ms=0,minor_faults=0,major_faults=0))) + m=dict(models=[2],variants={'native':{}},family_comparisons=48,conditions=[dict(id='batch16')]) + result=self.study.summarize(m,rows,'aa',root) + self.assertEqual(result['family_comparisons'],48) + self.assertEqual(result['conditions'][0]['gain_percent'],0.) + self.assertTrue(result['conditions'][0]['sensitivity_qualified']) + + def test_callback_uses_registered_worker_and_pcm_inputs(self): + m=dict(seed=3,aa_blocks=4,compare_blocks=4,models=[2],variants={'native':{'baseline':'/a','candidate':'/b'}},inputs=['spectra-x','spectra-y'],worker='/nn',weights={'2':'/w2'}, + conditions=[dict(id='audio10',worker_mode='paced',worker='/audio',inputs=['pcm-x','pcm-y'],period_ns=10000000,batch_size=1,calls=32)]) + jobs=self.study.schedule(m,'aa');self.assertEqual(set(j['input'] for j in jobs),{'pcm-x','pcm-y'}) + self.assertEqual(self.study.worker_args(m,jobs[0],Path('/raw'))[0],'/audio') + + def test_no_effect_not_a_speedup(self): + r=self.study.effect([0.]*4,.05/8) + self.assertEqual(r['gain_percent'],0) + self.assertEqual(r['interval_percent'],[0,0]) + + def test_retains_slow_observations_in_sd_and_tail(self): + r=self.study.describe([1.]*99+[20.]) + self.assertEqual(r['n'],100);self.assertEqual(r['p99'],20.) + self.assertGreater(r['sd'],1.) + + def test_comparison_requires_identical_binary_control(self): + with patch.object(self.study,'binary_manifest',return_value={'binary':'new'}): + with self.assertRaises(ValueError): + self.study.timing({},'compare','never-created',dict(kind='aa',hashes={'binary':'old'})) + + +if __name__=='__main__': + unittest.main() diff --git a/optimized_inference/tests/cm_contract.c b/optimized_inference/tests/cm_contract.c new file mode 100644 index 0000000..2366154 --- /dev/null +++ b/optimized_inference/tests/cm_contract.c @@ -0,0 +1,71 @@ +#define _GNU_SOURCE +#include "int8_matrix.h" +#include +#include +#include +#include +#include +#include +#include +#include +#define REQUIRE(X) do {if(!(X)){fprintf(stderr,"CM contract failed line %d\n",__LINE__);return 1;}} while(0) +static float from_bits(uint32_t bits) {float v;memcpy(&v,&bits,4);return v;} +static uint32_t seed=841009; +static float sample(void){seed=seed*1664525u+1013904223u;return ((int)(seed>>16)-32768)/8192.0f;} +int main(void) { + if(!dpdf_has_avx2()){puts("CM AVX2/FMA unavailable; skipped");return 77;} +#ifdef DPDF_TEST_AVX_VNNI + if(!dpdf_has_avx_vnni()){puts("CM AVX-VNNI unavailable; skipped");return 77;} +#endif + unsigned saved=_mm_getcsr(),rounds[]={_MM_ROUND_NEAREST,_MM_ROUND_DOWN,_MM_ROUND_UP,_MM_ROUND_TOWARD_ZERO}; + const int widths[]={8,40,48,80,96,160,480};size_t page=(size_t)sysconf(_SC_PAGESIZE),capacity=480*64*sizeof(float),span=(capacity+page-1)/page*page+page; + char *xm=mmap(0,span+page,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANONYMOUS,-1,0),*ym=mmap(0,span+page,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANONYMOUS,-1,0);REQUIRE(xm!=MAP_FAILED && ym!=MAP_FAILED);REQUIRE(!mprotect(xm+span,page,PROT_NONE) && !mprotect(ym+span,page,PROT_NONE)); + float *xr=malloc(capacity),*yr=malloc(capacity),*expected=malloc(capacity);REQUIRE(xr&&yr&&expected);int cases=0; + for(int mode=0;mode<4;++mode) for(int denorm=0;denorm<4;++denorm) { + _mm_setcsr((saved&~(0x6000|0x8040))|rounds[mode]|((denorm&1)?0x8000:0)|((denorm&2)?0x40:0)); + float w[64*64],bias[64];for(int i=0;i<64*64;++i)w[i]=sample();for(int i=0;i<64;++i)bias[i]=sample(); + dpdf_qmatrix *q=dpdf_qcreate(w,64,64);REQUIRE(q); +#ifdef DPDF_TEST_AVX_VNNI + q->affine=dpdf_qaffine_vnni; +#else + q->affine=dpdf_qaffine_avx2; +#endif + REQUIRE(dpdf_qaffine_cm64(NULL,xr,bias,expected,8)==0); + const int invalid_rows[]={-8,0,7,9,488}; + memset(expected,0xa5,32); + for(size_t i=0;ipacked,4096);REQUIRE(!mprotect(packed_map,packed_span,PROT_READ));int8_t *old=q->packed;q->packed=packed_end; + for(size_t wi=0;wi48)m=48;dpdf_qaffine(q,xr+f*64,bias,yr+f*64,m);} + for(int c=0;c<64;++c)for(int f=0;fpacked=old;munmap(packed_map,packed_span+page);dpdf_qdestroy(q); + } + _mm_setcsr(saved);munmap(xm,span+page);munmap(ym,span+page);free(xr);free(yr);free(expected); + printf("{\"cases\":%d,\"bitwise\":true,\"rounding_modes\":4,\"ftz_daz\":4,\"guarded_readonly_input_weights\":true,\"guarded_output\":true,\"unaligned\":true}\n",cases);return 0; +} diff --git a/optimized_inference/tests/extended_contract.c b/optimized_inference/tests/extended_contract.c index fe8db04..78fc5a0 100644 --- a/optimized_inference/tests/extended_contract.c +++ b/optimized_inference/tests/extended_contract.c @@ -9,14 +9,14 @@ int main(int argc,char **argv) { float *w=malloc(n*4),*a=malloc(state_size*4),*b=malloc(state_size*4);CHECK(w&&a&&b); FILE *f=fopen(argv[1],"rb");CHECK(f);CHECK(fread(w,4,n,f)==n);fclose(f); CHECK(!dpdf_model_create_config(w,n,0,7,0));CHECK(!dpdf_model_create_config(w,n,0,0,16)); - int precisions[]={0,16,8},masks[]={0,1,2,4,8,7,15}; + int precisions[]={0,16,8}; for (int p=0;p<3;++p) { int precision=precisions[p]; if (precision==16 && !dpdf_has_fp16()) {CHECK(!dpdf_model_create_config(w,n,0,16,15));continue;} if (precision==8 && !dpdf_has_avx2()) {CHECK(!dpdf_model_create_config(w,n,0,8,15));continue;} - for (int c=0;c<7;++c) { + for (int c=0;c<16;++c) { int tier=precision==16?3:precision==8?4:0; - dpdf_model *m=dpdf_model_create_config(w,n,tier,precision,masks[c]);CHECK(m); + dpdf_model *m=dpdf_model_create_config(w,n,tier,precision,c);CHECK(m); CHECK(dpdf_model_owned_bytes(m)>0);CHECK(!dpdf_model_init_state(a));CHECK(!dpdf_model_init_state(b)); float x[962],y[962],z[962]; for (int frame=0;frame<4;++frame) { @@ -30,5 +30,5 @@ int main(int argc,char **argv) { dpdf_model_destroy(m); } } - free(w);free(a);free(b);puts("All extended precision/family masks, aliasing and finite-state contracts passed");return 0; + free(w);free(a);free(b);puts("All 16 extended precision/family masks, aliasing and finite-state contracts passed");return 0; } diff --git a/optimized_inference/tests/int8_contract.c b/optimized_inference/tests/int8_contract.c index 6ba9c0e..60ec35a 100644 --- a/optimized_inference/tests/int8_contract.c +++ b/optimized_inference/tests/int8_contract.c @@ -1,3 +1,8 @@ +#define _GNU_SOURCE +#include "int8_matrix.h" +#include +#include +#include /* Independent scalar integer arithmetic checks the SIMD dot path, including * extreme signed values that would expose saturated pair sums. */ #include "internal.h" @@ -8,6 +13,16 @@ #include #define CHECK(x) do { if (!(x)) { fprintf(stderr,"INT8 test line %d\n",__LINE__); return 1; } } while (0) +typedef struct {void *mapping;size_t size;int8_t *old;} packed_guard; +static packed_guard protect_packed(dpdf_qmatrix *q) { + size_t page=(size_t)sysconf(_SC_PAGESIZE),bytes=(size_t)q->k*q->n,span=(bytes+page-1)/page*page; + void *mapping=mmap(NULL,span+page,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANONYMOUS,-1,0); + if(mapping==MAP_FAILED || mprotect((char *)mapping+span,page,PROT_NONE)) abort(); + int8_t *packed=(int8_t *)mapping+span-bytes;memcpy(packed,q->packed,bytes); + if(mprotect(mapping,span,PROT_READ)) abort(); + packed_guard result={mapping,span+page,q->packed};q->packed=packed;return result; +} +static void release_packed(dpdf_qmatrix *q,packed_guard g) {q->packed=g.old;munmap(g.mapping,g.size);} static uint32_t rng=0x194812; static float sample(void) { rng=rng*1664525u+1013904223u; @@ -30,7 +45,7 @@ static int row_contract(void) { for (int j=0;j +#include +#include +#include +#include +#include +#ifdef DPDF_TEST_AVX_VNNI +#include "../src/common/int8_vnni.c" +#else +#include "../src/common/int8.c" +#endif +#include "quantize_reference.h" + +static uint32_t seed=7711; +static float sample(void) { + seed=seed*1664525u+1013904223u; + return (int32_t)seed*0x1p-30f; +} +static void fill(float *x,int mask,int pattern) { + for (int r=0;r<4;++r) for (int j=0;j<64;++j) { + float v=sample(); + if (mask & (1<=7 && pattern<71) v=j==pattern-7 ? ((r&1)?-1.f:1.f) : 0; + else if (pattern==71) v=(j&1)?0x1.fffffep-1f:-0x1.000002p0f; + else if (pattern==72) v=(float)(j-32)*0x1p-140f; + else if (pattern==73) v=(float)(j-32)*0x1p-120f; + else if (pattern==74) v=(float)(j-32)/127.f; + x[r*64+j]=v; + } +} +int main(void) { +#ifdef DPDF_TEST_AVX_VNNI + __builtin_cpu_init(); + if (!__builtin_cpu_supports("avxvnni")) return 77; +#endif + long page=sysconf(_SC_PAGESIZE); + if (page<2048) return 2; + unsigned saved=_mm_getcsr(); + unsigned char *a=mmap(0,page*3,PROT_NONE,MAP_PRIVATE|MAP_ANONYMOUS,-1,0); + unsigned char *b=mmap(0,page*3,PROT_NONE,MAP_PRIVATE|MAP_ANONYMOUS,-1,0); + if (a==MAP_FAILED || b==MAP_FAILED || mprotect(a+page,page,PROT_READ|PROT_WRITE) || + mprotect(b+page,page,PROT_READ|PROT_WRITE)) return 2; + unsigned rounds[]={_MM_ROUND_NEAREST,_MM_ROUND_DOWN,_MM_ROUND_UP,_MM_ROUND_TOWARD_ZERO}; + int cases=0,flag_differences=0; + for (int place=0;place<3;++place) for (int mode=0;mode<4;++mode) + for (int denorm=0;denorm<4;++denorm) for (int mask=0;mask<16;++mask) + for (int pattern=0;pattern<96;++pattern) { + float *x=(float *)(place==0 ? a+page : a+2*page-1024-(place==2?4:0)); + int8_t *actual=(int8_t *)(place==0 ? b+page : b+2*page-256-(place==2?1:0)); + int8_t reference[256],single[256];float backup[256],ref[4],ss[4];int rz[4],sz[4]; + struct {uint32_t head;float values[4];uint32_t tail;} s={0x1937,{0},0x7291}; + struct {uint32_t head;int values[4];uint32_t tail;} z={0x5173,{0},0x9371}; + unsigned control=(saved&~(0x603f|0x8040))|rounds[mode]| + ((denorm&1)?0x8000:0)|((denorm&2)?0x40:0); + _mm_setcsr(control); + fill(x,mask,pattern);memcpy(backup,x,sizeof(backup)); + _mm_setcsr(control); + for (int r=0;r<4;++r) reference_quantize(x+r*64,reference+r*64,64,ref+r,rz+r); + unsigned reference_flags=_mm_getcsr()&63; + _mm_setcsr(control);memset(b+page,0x55,(size_t)page); + quantize4_64(x,actual,s.values,z.values); + unsigned actual_csr=_mm_getcsr(); + flag_differences+=reference_flags!=(actual_csr&63); + if ((actual_csr&~63u)!=control || memcmp(actual,reference,256) || + memcmp(s.values,ref,sizeof(ref)) || memcmp(z.values,rz,sizeof(rz)) || + memcmp(x,backup,sizeof(backup)) || s.head!=0x1937 || s.tail!=0x7291 || + z.head!=0x5173 || z.tail!=0x9371 || (mask==15 && (actual_csr&5))) goto fail; + for (unsigned char *p=b+page;p=(unsigned char *)actual+256) && *p!=0x55) goto fail; + _mm_setcsr(control); + for (int r=0;r<4;++r) quantize(x+r*64,single+r*64,64,ss+r,sz+r); + if (memcmp(single,reference,256)||memcmp(ss,ref,sizeof(ref))||memcmp(sz,rz,sizeof(rz))) goto fail; + cases++;continue; +fail: + _mm_setcsr(saved); + fprintf(stderr,"quantize4 mismatch place=%d mode=%d denorm=%d mask=%d pattern=%d\n",place,mode,denorm,mask,pattern); + return 1; + } + _mm_setcsr(saved);munmap(a,page*3);munmap(b,page*3); + printf("{\"cases\":%d,\"empty_masks\":16,\"rounding_modes\":4,\"FTZ_DAZ_combinations\":4,\"guarded_both_ends\":true,\"bitwise\":true,\"sticky_flag_differences_diagnostic_only\":%d}\n",cases,flag_differences); + return 0; +} diff --git a/optimized_inference/tests/quantize_reference.h b/optimized_inference/tests/quantize_reference.h new file mode 100644 index 0000000..9cbbfdd --- /dev/null +++ b/optimized_inference/tests/quantize_reference.h @@ -0,0 +1,43 @@ +/* Frozen pre-refinement SIMD oracle from 8ad669a; intentionally independent. */ +static void reference_quantize(const float *x,int8_t *out,int k,float *scale,int *zp) { + __m256 lo=_mm256_setzero_ps(),hi=lo; + for (int j=0;j254) *zp=254; + __m256 inv=_mm256_set1_ps(1.0f / *scale),z=_mm256_set1_ps((float)*zp); + int j=0; + for (;j+31 ready library -> IFFT host callback.""" +import os +os.environ.update(OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1',MKL_NUM_THREADS='1') +import sys,time,json,array,hashlib,statistics as stats,gc,resource,ctypes as ct +from pathlib import Path +import numpy as np +sys.path.insert(0,str(Path(__file__).resolve().parents[2]/'examples')) +from dpdfnet import Model +from audio_pipeline import AudioPipeline +libc=ct.CDLL(None,use_errno=True) +libc.personality.argtypes=[ct.c_ulong];libc.personality.restype=ct.c_int + +def raw_ns():return time.clock_gettime_ns(time.CLOCK_MONOTONIC_RAW) +def feedback(cpu): + a=Path(f'/sys/devices/system/cpu/cpu{cpu}/acpi_cppc/feedback_ctrs').read_text().split() + return tuple(int(v.split(':')[1]) for v in a) +def digest(model): + h=1469598103934665603 + for a in [model.state,model.output]: + for u in a.view(np.uint32).flat:h=((h^int(u))*1099511628211)&((1<<64)-1) + return f'{h:016x}' +def perf_command(ctl,ack,s): + if not ctl:return + ctl.write(s+'\n');ctl.flush() + first=ack.read(1) + while first==b'\x00':first=ack.read(1) + if first+b''.join(ack.read(1) for _ in range(3))!=b'ack\n':raise RuntimeError('Bad perf acknowledgement') + +def main(): + if len(sys.argv)!=9:raise ValueError('library model weights decoded-pcm calls paced:ns 1 raw-output') + library,model_id,weights,source,calls,mode,batch,output=sys.argv[1:] + calls=int(calls);model_id=int(model_id) + if int(batch)!=1 or calls<16 or not mode.startswith('paced:'):raise ValueError('Audio callback requires individual paced samples') + period=int(mode.split(':')[1]);audio=np.fromfile(source,dtype='deadline+period;deadline+=period + if finish>deadline:deadline=finish + cpu1=time.thread_time_ns();after=resource.getrusage(resource.RUSAGE_SELF);perf_command(ctl,ack,'disable') + ref1,del1=feedback(cpu) + Path(output).write_bytes(array.array('d',times).tobytes());ordered=sorted(times) + status=Path('/proc/self/status').read_text();nnp=int(next(x.split()[1] for x in status.splitlines() if x.startswith('NoNewPrivs:'))) + result=dict(cpu=cpu,uid=os.getuid(),no_new_privs=nnp,layout_randomization_disabled=bool(libc.personality(0xffffffff)&0x40000), + api_address=hex(ct.cast(model.lib.dpdfnet_process,ct.c_void_p).value),state_address=hex(model.state.ctypes.data), + reference_delta=ref1-ref0,delivered_delta=del1-del0,hardware_feedback_available=ref1>ref0 and del1>del0, + schema_version=1,period_ns=period,mode=mode,model=model_id,calls=calls,warmup=warmup,observations=calls,batch_size=1,observation_unit='call', + mean_ms=stats.mean(times),sample_sd_ms=stats.stdev(times),cpu_ms_per_call=(cpu1-cpu0)/1e6/calls, + p95_ms=ordered[int(calls*.95)],p99_ms=ordered[int(calls*.99)],max_ms=max(times),over_10ms=sum(t>=10 for t in times),late=late, + voluntary_switches=after.ru_nvcsw-before.ru_nvcsw,involuntary_switches=after.ru_nivcsw-before.ru_nivcsw, + minor_faults=after.ru_minflt-before.ru_minflt,major_faults=after.ru_majflt-before.ru_majflt, + checksum=digest(model),pipeline='documented_numpy_fft_nn_ifft',numpy_version=np.__version__) + print(json.dumps(result)) + if ctl:ctl.close();ack.close() +if __name__=='__main__':main() diff --git a/optimized_inference/tools/bench_lab/controller.py b/optimized_inference/tools/bench_lab/controller.py new file mode 100644 index 0000000..385ed14 --- /dev/null +++ b/optimized_inference/tools/bench_lab/controller.py @@ -0,0 +1,528 @@ +#!/usr/bin/env python3 +"""Reversible Linux benchmark laboratory. Root only controls the environment. + +State and rollback code are root-owned in /run. Workers always drop privileges. +No application build or arbitrary command is ever executed with root privileges. +""" +import argparse +import ctypes +import datetime +import fcntl +import hashlib +import json +import os +from pathlib import Path +import pwd +import shutil +import signal +import stat +import subprocess +import sys +import time +import uuid + +RUN = Path('/run/dpdfnet-bench-lab') +CG = Path('/sys/fs/cgroup/dpdfnetbenchlab.slice') +LEAF = CG / 'workers' +HOLDER = 'dpdfnet-bench-lab-holder.service' +TIMER = 'dpdfnet-bench-lab-restore' +CPU = Path('/sys/devices/system/cpu') + + +def read(path): + return Path(path).read_text().strip() + + +def write(path, value): + Path(path).write_text(str(value) + '\n') + + +def cpus(text): + result = set() + for item in text.split(','): + if not item: + continue + a = item.split('-') + if len(a) > 2 or not all(x.isdecimal() for x in a): + raise ValueError('Invalid CPU list') + result.update(range(int(a[0]), int(a[-1]) + 1)) + return result + + +def cpulist(values): + return ','.join(map(str, sorted(values))) + + +def cpumask(values): + value = sum(1 << cpu for cpu in values) + words = [] + while value: + words.append(f'{value & 0xffffffff:08x}') + value >>= 32 + return ','.join(reversed(words)) or '0' + + +def require(condition, message): + if not condition: + raise RuntimeError(message) + + +def command(*args): + return subprocess.check_output(list(map(str, args)), text=True, stderr=subprocess.STDOUT).strip() + + +def save(state): + temporary = RUN / 'state.tmp' + with temporary.open('w') as f: + json.dump(state, f, indent=2) + f.write('\n') + f.flush() + os.fsync(f.fileno()) + temporary.replace(RUN / 'state.json') + + +def load(): + require((RUN / 'state.json').exists(), 'No benchmark environment has been prepared') + return json.loads((RUN / 'state.json').read_text()) + + +def change(state, path, value, optional=False): + """Write-ahead rollback journal, including partially completed writes.""" + path = str(path) + before = read(path) + if before == str(value): + return + row = dict(path=path, before=before, requested=str(value)) + state['journal'].append(row) + save(state) + try: + write(path, value) + row['applied'] = read(path) + except OSError as error: + row['error'] = str(error) + if not optional: + save(state) + raise + save(state) + + +def identity(pid): + text = read(f'/proc/{pid}/stat') + fields = text[text.rindex(')') + 2:].split() + return dict(start=fields[19], state=fields[0], flags=int(fields[6]), comm=text[text.index('(') + 1:text.rindex(')')]) + + +def power_snapshot(): + names = ['scaling_governor', 'energy_performance_preference', 'scaling_min_freq', 'scaling_max_freq'] + return {str(p): {n: read(p / n) for n in names if (p / n).exists()} + for p in CPU.glob('cpufreq/policy*')} + + +def set_limits(policy, low, high): + """Avoid transient min > max both when lowering and when raising bounds.""" + require(0 < low <= high, 'Invalid frequency limits') + if low > int(read(policy / 'scaling_max_freq')): + write(policy / 'scaling_max_freq', high) + elif high < int(read(policy / 'scaling_min_freq')): + write(policy / 'scaling_min_freq', low) + write(policy / 'scaling_min_freq', low) + write(policy / 'scaling_max_freq', high) + + +def topology(cpu): + online = cpus(read(CPU / 'online')) + require(cpu in online, 'Worker CPU is offline') + cache = [] + for entry in (CPU / f'cpu{cpu}/cache').glob('index*'): + if read(entry / 'level') == '3' and read(entry / 'type') == 'Unified': + cache.append(cpus(read(entry / 'shared_cpu_list'))) + require(len(cache) == 1, 'Exactly one unified L3 domain is required') + reserved = cache[0] & online + siblings = cpus(read(CPU / f'cpu{cpu}/topology/thread_siblings_list')) & online + house = online - reserved + require(siblings <= reserved and house, 'No separate housekeeping CPU domain') + return online, reserved, siblings, house + + +def foreign_threads(state): + """Validate effective per-thread affinity; allowed masks alone are insufficient.""" + reserved = set(state['reserved']) + foreign = [] + for proc in Path('/proc').glob('[0-9]*'): + try: + ident = identity(int(proc.name)) + if ident['state'] == 'Z' or ident['flags'] & 0x200000: + continue + if str(CG.name) + '/workers' in read(proc / 'cgroup'): + continue + for task in (proc / 'task').iterdir(): + try: + if os.sched_getaffinity(int(task.name)) & reserved: + foreign.append(dict(pid=int(proc.name), tid=int(task.name))) + except ProcessLookupError: + pass + except (FileNotFoundError, ProcessLookupError): + pass + return foreign + + +def noise_snapshot(cpu): + result = dict(time_ns=time.time_ns()) + for name in ['interrupts', 'softirqs']: + lines = Path('/proc/' + name).read_text().splitlines() + column = lines[0].split().index('CPU' + str(cpu)) + 1 + values = {} + for line in lines[1:]: + fields = line.split() + try: + values[fields[0].rstrip(':')] = int(fields[column]) + except (IndexError, ValueError): + pass + result[name] = values + return result + + +def verify(state): + require(state['phase'] == 'ready', 'Environment is not ready') + require(hashlib.sha256(Path(__file__).resolve().read_bytes()).hexdigest() == state['controller_sha256'], 'Controller changed during the session') + require(hashlib.sha256(Path(state['probe']).read_bytes()).hexdigest() == state['probe_sha256'], 'Measurement worker changed during the session') + require(time.monotonic() < state['expires_monotonic'], 'Restoration deadline has expired') + require(command('systemctl', 'is-active', state['timer'] + '.timer') == 'active', 'Independent restoration timer is not active') + require(read(CG / 'cpuset.cpus.partition') == 'isolated', 'CPU partition is not isolated') + require(cpus(read(CG / 'cpuset.cpus.effective')) == set(state['reserved']) - set(state['parked']), 'L3 reservation changed') + require(cpus(read(LEAF / 'cpuset.cpus.effective')) == {state['cpu']}, 'Worker partition changed') + require(read(CPU / 'cpufreq/boost') == state['boost_during'], 'Boost policy changed') + require(read(CPU / 'online') == state['online_during'], 'CPU online state changed') + p = CPU / f"cpu{state['cpu']}/cpufreq" + for name, expected in state['worker_power'].items(): + require(read(p / name) == expected, 'Frequency policy changed: ' + name) + for entry in state['journal']: + if 'applied' in entry: + require(read(entry['path']) == entry['applied'], 'Setting changed: ' + entry['path']) + foreign = foreign_threads(state) + require(not foreign, 'Foreign threads may run in reserved L3 domain: ' + str(foreign[:8])) + return dict(structurally_ready=True, session_id=state['id'], cpu=state['cpu'], reserved_l3_cpus=state['reserved'], + housekeeping_cpus=state['house'], parked_siblings=state['parked'], + frequency_khz=state['frequency_khz'], power_profile=state['power_profile'], layout_profile=state.get('layout_profile','randomized'), foreign_userspace_threads=foreign, + restoration_timer=state['timer'] + '.timer', controller_sha256=state['controller_sha256'], worker_sha256=state['probe_sha256'], + worker_power=state['worker_power'], expires_at=state['expires_at'], + residual_kernel_work_possible=True, calibration=state.get('calibration'), noise=noise_snapshot(state['cpu'])) + + +def launch(state, argv): + verify(state) + require(argv and Path(argv[0]).is_absolute() and Path(argv[0]).is_file(), 'Use an absolute executable path') + require(state['uid'] > 0, 'Refusing a root benchmark worker') + write(LEAF / 'cgroup.procs', os.getpid()) + os.sched_setaffinity(0, {state['cpu']}) + libc = ctypes.CDLL(None, use_errno=True) + for cap in range(int(read('/proc/sys/kernel/cap_last_cap')) + 1): + require(libc.prctl(24, cap, 0, 0, 0) == 0, 'Cannot clear capability bounding set') + user = pwd.getpwuid(state['uid']) + os.initgroups(user.pw_name, state['gid']) + os.setgid(state['gid']) + os.setuid(state['uid']) + require(libc.prctl(38, 1, 0, 0, 0) == 0, 'Cannot set no_new_privs') + status = read('/proc/self/status') + for field in ['CapEff', 'CapPrm', 'CapAmb', 'CapBnd']: + require(int(next(x.split()[1] for x in status.splitlines() if x.startswith(field + ':')), 16) == 0, 'Worker retains capabilities') + os.environ.update(HOME=user.pw_dir, USER=user.pw_name, LOGNAME=user.pw_name, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1', MKL_NUM_THREADS='1', PYTHONHASHSEED='0') + libc.personality.argtypes=[ctypes.c_ulong];libc.personality.restype=ctypes.c_int + old=libc.personality(0xffffffff) + desired=(old|0x40000) if state.get('layout_profile','randomized')=='fixed' else (old&~0x40000) + require(old>=0 and libc.personality(desired)>=0, 'Cannot apply the requested process-only ASLR policy') + # The controller lock is CLOEXEC. No root file descriptor is passed to exec. + os.execv(argv[0], argv) + + +def frequency_qualified(rows, state): + import statistics + values = [r['effective_khz'] for r in rows] + if state['power_profile'] == 'steady': + mean = statistics.mean(values) + return abs(mean / state['frequency_khz'] - 1) <= .01 and statistics.stdev(values) / mean <= .003 + # Boost is deliberately variable. Validate limits without claiming stability. + low = int(state['worker_power']['scaling_min_freq']) + high = int(state['worker_power']['scaling_max_freq']) + return all(low * .97 <= value <= high * 1.03 for value in values) + + +def calibrate(state, repeats=3): + verify(state) + probe = Path(state['probe']) + require(hashlib.sha256(probe.read_bytes()).hexdigest() == state['probe_sha256'], 'Frequency probe changed') + reference_khz = state['reference_khz'] + rows = [] + for _ in range(repeats): + argv = [str(probe), 'probe', str(state['cpu']), '600'] + # This controller is single-threaded. The child drops privileges before + # exec; the parent retains the short control lock during calibration. + data = json.loads(subprocess.check_output(argv, preexec_fn=lambda: launch(state, argv), + text=True, timeout=15)) + data['effective_khz'] = reference_khz * data['delivered_delta'] / data['reference_delta'] + rows.append(data) + import statistics + mean = statistics.mean(r['effective_khz'] for r in rows) + sd = statistics.stdev(r['effective_khz'] for r in rows) + passed = frequency_qualified(rows, state) + result = dict(samples=rows, mean_khz=mean, sd_khz=sd, target_khz=state['frequency_khz'], + passed=passed, fixed_frequency=state['power_profile']=='steady', + method='CPPC delivered/reference hardware counters; nominal_perf == reference_perf', + tolerance_mean_percent=1 if state['power_profile']=='steady' else None, + tolerance_sd_percent=.3 if state['power_profile']=='steady' else None, dynamic_range_tolerance_percent=3 if state['power_profile']=='boost' else None, time_ns=time.time_ns()) + state['calibration'] = result + save(state) + require(result['passed'], 'Actual frequency does not satisfy the selected power profile: ' + json.dumps(result)) + return result + + +def restore(state): + if state['phase'] == 'restored': + return state['restoration'] + state['phase'] = 'restoring' + save(state) + errors = [] + def attempt(label, fn): + try: + fn() + except Exception as error: + errors.append(dict(action=label, error=str(error))) + if (LEAF / 'cgroup.kill').exists(): + attempt('kill benchmark workers', lambda: write(LEAF / 'cgroup.kill', 1)) + for cpu in state.get('parked', []): + attempt('online sibling ' + str(cpu), lambda cpu=cpu: write(CPU / f'cpu{cpu}/online', 1) if read(CPU / f'cpu{cpu}/online') != '1' else None) + if (CG / 'cpuset.cpus.partition').exists(): + attempt('release CPU partition', lambda: write(CG / 'cpuset.cpus.partition', 'member')) + # Restore boost before original frequency ranges (which may require boost). + attempt('restore boost', lambda: write(CPU / 'cpufreq/boost', state['boost_before'])) + for path, values in state['power_before'].items(): + def original_power(path=path, values=values): + p = Path(path) + set_limits(p, int(values['scaling_min_freq']), int(values['scaling_max_freq'])) + write(p / 'scaling_governor', values['scaling_governor']) + if 'energy_performance_preference' in values: + write(p / 'energy_performance_preference', values['energy_performance_preference']) + attempt('power ' + path, original_power) + for entry in reversed(state['journal']): + attempt(entry['path'], lambda entry=entry: write(entry['path'], entry['before']) if read(entry['path']) != entry['before'] else None) + for row in reversed(state['kernel_moves']): + def affinity(row=row): + try: + if identity(row['pid'])['start'] == row['start']: + os.sched_setaffinity(row['pid'], row['before']) + except (FileNotFoundError, ProcessLookupError): + pass + attempt('kernel affinity ' + str(row['pid']), affinity) + if LEAF.exists(): + def remove_leaf(): + for _ in range(100): + try: + LEAF.rmdir() + return + except OSError: + time.sleep(.02) + raise RuntimeError('Worker cgroup did not drain') + attempt('remove worker cgroup', remove_leaf) + unit_loaded = command('systemctl', 'show', '--property=LoadState', '--value', CG.name) != 'not-found' + cleanup = [('stop', HOLDER), ('set-property', '--runtime', CG.name, 'AllowedCPUs='), + ('stop', CG.name), ('revert', CG.name)] if unit_loaded else [] + cleanup.append(('stop', state['timer'] + '.timer')) + for args in cleanup: + if args[0] == 'stop' and command('systemctl', 'show', '--property=LoadState', '--value', args[1]) == 'not-found': + continue + attempt('systemctl ' + ' '.join(args), lambda args=args: command('systemctl', *args)) + if state['irqbalance_before'] == 'active': + attempt('restart irqbalance', lambda: command('systemctl', 'start', 'irqbalance')) + power = power_snapshot() + mismatches = [entry['path'] for entry in state['journal'] if read(entry['path']) != entry['before']] + result = dict(restored=not errors and not mismatches and power == state['power_before'] + and read(CPU / 'cpufreq/boost') == state['boost_before'] + and read(CPU / 'online') == state['online_before'] and not CG.exists() + and read('/sys/fs/cgroup/cgroup.subtree_control') == state['root_controllers_before'] + and subprocess.run(['systemctl', 'is-active', 'irqbalance'], capture_output=True, text=True).stdout.strip() == state['irqbalance_before'], + errors=errors, mismatched_files=mismatches, power_matches=power == state['power_before'], + online=read(CPU / 'online'), timestamp_ns=time.time_ns()) + state['restoration'] = result + state['phase'] = 'restored' if result['restored'] else 'restore_failed' + save(state) + require(result['restored'], 'Restoration incomplete: ' + json.dumps(result)) + return result + + +def prepare(args): + if (RUN / 'state.json').exists(): + previous = load() + require(previous['phase'] == 'restored', 'An environment already exists; run bench-ready or bench-restore') + shutil.copyfile(RUN / 'state.json', RUN / ('state-' + previous['id'] + '.json')) + require(read('/sys/devices/system/clocksource/clocksource0/current_clocksource') == 'tsc', 'This validated backend requires the stable-TSC clocksource') + require(not CG.exists(), 'Benchmark cgroup already exists') + for unit in [CG.name, HOLDER]: + for prop in ['FragmentPath', 'DropInPaths']: + require(not command('systemctl', 'show', '--property=' + prop, '--value', unit), 'Existing unit configuration must not be overwritten: ' + unit) + online, reserved, siblings, house = topology(args.cpu) + user = int(os.environ.get('SUDO_UID', '-1')) + require(user > 0, 'Prepare via sudo from an ordinary user account') + probe = Path(args.probe).resolve() + require(probe.is_file(), 'Compile the worker before preparing isolation') + cppc = CPU / f'cpu{args.cpu}/acpi_cppc' + nominal = int(read(cppc / 'nominal_freq')) * 1000 + require(nominal > 0 and read(cppc / 'nominal_perf') == read(cppc / 'reference_perf'), 'Unsupported CPPC reference frequency; refusing unverified frequency claims') + frequency = nominal if args.frequency_khz == 'auto' else int(args.frequency_khz) + require(args.power_profile == 'steady' or args.frequency_khz == 'auto', 'Boost profile requires automatic dynamic bounds') + require(int(read(CPU / f'cpu{args.cpu}/cpufreq/cpuinfo_min_freq')) <= frequency <= nominal, 'Choose a frequency no higher than the nominal non-boost frequency') + require(60 <= args.ttl <= 7200, 'Restoration timeout must be 60..7200 seconds') + state = dict(id=uuid.uuid4().hex, phase='preparing', controller_sha256=hashlib.sha256(Path(__file__).resolve().read_bytes()).hexdigest(), cpu=args.cpu, uid=user, + gid=int(os.environ['SUDO_GID']), reserved=sorted(reserved), siblings=sorted(siblings), + house=sorted(house), online_before=read(CPU / 'online'), parked=[], + power_before=power_snapshot(), boost_before=read(CPU / 'cpufreq/boost'), + root_controllers_before=read('/sys/fs/cgroup/cgroup.subtree_control'), + irqbalance_before=subprocess.run(['systemctl', 'is-active', 'irqbalance'],capture_output=True,text=True).stdout.strip(), + reference_khz=nominal, frequency_khz=frequency if args.power_profile=='steady' else None, + power_profile=args.power_profile, layout_profile=args.layout, boost_during='0' if args.power_profile=='steady' else '1', probe=str(probe), + probe_sha256=hashlib.sha256(probe.read_bytes()).hexdigest(), journal=[], kernel_moves=[], + unmovable_kernel=[], expires_at=time.time()+args.ttl, expires_monotonic=time.monotonic()+args.ttl, created_ns=time.time_ns()) + state['timer'] = TIMER + '-' + state['id'][:12] + save(state) + # Immutable rollback code survives edits/deletion of the workspace script. + shutil.copyfile(Path(__file__).resolve(), RUN / 'rollback.py') + os.chmod(RUN / 'rollback.py', 0o700) + try: + command('systemd-run', '--collect', '--unit='+state['timer'], '--on-active='+str(args.ttl)+'s', '--timer-property=AccuracySec=1s', + '/usr/bin/python3', RUN / 'rollback.py', 'restore', '--session', state['id']) + if state['irqbalance_before'] == 'active': + command('systemctl', 'stop', 'irqbalance') + command('systemd-run', '--unit='+HOLDER, '--slice='+CG.name, '--remain-after-exit', '--collect', + '--property=AllowedCPUs='+cpulist(reserved), '/usr/bin/true') + command('systemctl', 'set-property', '--runtime', CG.name, 'AllowedCPUs='+cpulist(reserved)) + write(CG / 'cpuset.cpus.partition', 'isolated') + write(CG / 'cgroup.subtree_control', '+cpuset') + LEAF.mkdir() + write(LEAF / 'cpuset.cpus', args.cpu) + write(LEAF / 'cpuset.mems', read(CG / 'cpuset.mems.effective')) + files = [Path('/proc/irq/default_smp_affinity'), Path('/sys/devices/virtual/workqueue/cpumask'), Path('/proc/sys/kernel/watchdog_cpumask')] + files += sorted(Path('/proc/irq').glob('[0-9]*/smp_affinity_list')) + for p in files: + current = read(p) + if p.name == 'smp_affinity_list': + if not cpus(current) & reserved: + continue + target = cpulist((cpus(current)-reserved) or house) + elif p.name == 'watchdog_cpumask': + target = cpulist(house) + else: + target = cpumask(house) + change(state, p, target, optional=p.name == 'smp_affinity_list') + for p in Path('/proc').glob('[0-9]*'): + pid = int(p.name) + try: + ident = identity(pid) + if pid == 2 or not ident['flags'] & 0x200000: + continue + affinity = os.sched_getaffinity(pid) + if not affinity & reserved: + continue + row = dict(pid=pid, start=ident['start'], before=sorted(affinity)) + state['kernel_moves'].append(row) + save(state) + try: + os.sched_setaffinity(pid, (affinity-reserved) or house) + except OSError as error: + state['kernel_moves'].pop() + state['unmovable_kernel'].append(dict(pid=pid, comm=ident['comm'], error=str(error))) + save(state) + except (FileNotFoundError, ProcessLookupError): + pass + write(CPU / 'cpufreq/boost', state['boost_during']) + p = CPU / f'cpu{args.cpu}/cpufreq' + write(p / 'scaling_governor', 'performance') + if (p / 'energy_performance_preference').exists(): + write(p / 'energy_performance_preference', 'performance') + if args.power_profile == 'steady': + set_limits(p, frequency, frequency) + else: + original = state['power_before'][str(p.resolve())] + set_limits(p, int(original['scaling_min_freq']), int(read(p / 'cpuinfo_max_freq'))) + state['worker_power'] = {n: read(p / n) for n in ['scaling_governor','energy_performance_preference','scaling_min_freq','scaling_max_freq'] if (p / n).exists()} + # Restrict deep idle on the worker only; this is a laboratory power policy. + for entry in (CPU / f'cpu{args.cpu}/cpuidle').glob('state*'): + if args.power_profile == 'steady' and int(read(entry / 'latency')) > 1: + change(state, entry / 'disable', 1) + for cpu in sorted(siblings-{args.cpu}): + state['parked'].append(cpu) + save(state) + write(CPU / f'cpu{cpu}/online', 0) + state['online_during'] = read(CPU / 'online') + state['phase'] = 'ready' + save(state) + verify(state) + # Let the package settle before the three hardware-counter probes. + time.sleep(2) + calibrate(state) + return verify(state) + except BaseException: + restore(state) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest='mode', required=True) + p = sub.add_parser('prepare') + p.add_argument('--cpu', type=int, default=3) + p.add_argument('--frequency-khz', default='auto') + p.add_argument('--power-profile', choices=['steady','boost'], default='steady') + p.add_argument('--layout', choices=['randomized','fixed'], default='randomized') + p.add_argument('--ttl', type=int, default=1800) + p.add_argument('--probe', required=True) + sub.add_parser('ready') + sub.add_parser('status') + p = sub.add_parser('restore') + p.add_argument('--session') + p = sub.add_parser('exec') + p.add_argument('command', nargs=argparse.REMAINDER) + args = parser.parse_args() + require(os.getuid() == 0, 'Run the controller via sudo') + RUN.mkdir(mode=0o700, exist_ok=True) + st = RUN.lstat() + require(stat.S_ISDIR(st.st_mode) and st.st_uid == 0 and not st.st_mode & 0o077, 'Unsafe state directory') + # No caller-selected state or lock paths; root must not follow user symlinks. + with (RUN / 'lock').open('a') as guard: + fcntl.flock(guard, fcntl.LOCK_EX) + if args.mode == 'prepare': + result = prepare(args) + elif args.mode == 'restore': + if args.session: + require(load()['id'] == args.session, 'Session changed; refusing to restore another session') + result = restore(load()) if (RUN / 'state.json').exists() else dict(restored=True, already_absent=True) + elif args.mode == 'exec': + # calibrate() starts an exec controller; release the parent lock first. + state = load() + argv = args.command[1:] if args.command[:1] == ['--'] else args.command + launch(state, argv) + return + else: + state = load() + if args.mode == 'ready': + try: + calibrate(state) + except BaseException: + restore(state) + raise + result = verify(state) if state['phase'] == 'ready' else state.get('restoration', dict(phase=state['phase'])) + print(json.dumps(result, indent=2)) + + +if __name__ == '__main__': + def interrupted(signum, frame): + raise KeyboardInterrupt(signum) + signal.signal(signal.SIGTERM, interrupted) + signal.signal(signal.SIGINT, interrupted) + try: + main() + except (Exception, KeyboardInterrupt) as error: + failure = dict(error=str(error), type=type(error).__name__) + if (RUN / 'state.json').exists(): + state = load() + failure.update(phase=state['phase'], restoration=state.get('restoration')) + print(json.dumps(failure), flush=True) + sys.exit(1) diff --git a/optimized_inference/tools/bench_lab/study.py b/optimized_inference/tools/bench_lab/study.py new file mode 100644 index 0000000..1173878 --- /dev/null +++ b/optimized_inference/tools/bench_lab/study.py @@ -0,0 +1,342 @@ +#!/usr/bin/env python3 +"""Fixed-size studies using the prepared lab; standard-library dependencies only.""" +import argparse +import array +import hashlib +import json +import math +import os +from pathlib import Path +import random +import signal +import statistics as stats +import subprocess +import sys +import time + +TOOLS = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(TOOLS)) +from compare_benchmarks import student_t_quantile +CONTROLLER = Path(__file__).resolve().with_name('controller.py') +ROOT = TOOLS.parents[1] + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def emit(path, value): + Path(path).write_text(json.dumps(value, indent=2) + '\n') + + +def control(*args): + try: + output=subprocess.check_output(['sudo','-n','/usr/bin/python3',str(CONTROLLER),*map(str,args)], text=True) + except subprocess.CalledProcessError as error: + # The controller emits its structured failure and rollback verdict to + # stdout. Preserve it in the session log instead of hiding it inside + # CalledProcessError.output when preparation fails before ownership. + detail=(error.output or '').strip() + raise RuntimeError('Laboratory controller failed: '+(detail or str(error))) from error + return json.loads(output) + + +def describe(values): + a=sorted(values);n=len(a) + return dict(n=n,mean=stats.mean(a),sd=stats.stdev(a) if n>1 else None, + min=a[0],p95=a[min(n-1,int(n*.95))],p99=a[min(n-1,int(n*.99))],max=a[-1]) + + +def effect(logs,alpha): + mean=stats.mean(logs) + half=student_t_quantile(1-alpha/2,len(logs)-1)*stats.stdev(logs)/math.sqrt(len(logs)) + return dict(gain_percent=100*(1-math.exp(mean)),interval_percent=[100*(1-math.exp(mean+half)),100*(1-math.exp(mean-half))], + paired_log_sd=stats.stdev(logs),paired_blocks=len(logs)) + + +def condition_specs(m): + return m.get('conditions', [dict(id='batch',worker_mode='batch',batch_size=m.get('batch_size',16),calls=m.get('calls',{}).get('batch',512)), + dict(id='paced',worker_mode='paced',period_ns=10000000,batch_size=1,calls=m.get('calls',{}).get('paced',100))]) + + +def condition(m,j): + if 'worker_mode' in j:return j + found=next((c for c in condition_specs(m) if c['id']==j['mode']),None) + if found:return found + return dict(worker_mode=j['mode'],batch_size=m['batch_size'] if j['mode']=='batch' else 1,calls=m['calls'][j['mode']]) + + +def config(path): + m=json.loads(Path(path).read_text()) + if m.get('schema_version')!=1:raise ValueError('Unsupported manifest') + for key in ['worker','inputs','variants','models','weights','seed','calls','batch_size','aa_blocks','compare_blocks']: + if key not in m:raise ValueError('Missing manifest field '+key) + if not 4<=m['aa_blocks']<=16 or not 4<=m['compare_blocks']<=32:raise ValueError('Use bounded fixed block counts') + if m['aa_blocks']%4 or m['compare_blocks']%4:raise ValueError('Blocks must balance both orders within two inputs (multiple of four)') + if len(m['inputs'])!=2 or len(set(m['inputs']))!=2:raise ValueError('This balanced plan requires two distinct input files') + if not m['models'] or len(set(m['models']))!=len(m['models']) or not set(m['models'])<={2,8}:raise ValueError('Models must be unique IDs 2 and/or 8') + if not m['variants']:raise ValueError('At least one ISA pair is required') + if not isinstance(m['batch_size'],int) or not 1<=m['batch_size']<=256:raise ValueError('Invalid batch size') + for mode in ['batch','continuous','paced']: + n=m['calls'][mode] + if not isinstance(n,int) or not 16<=n<=1000000:raise ValueError('Invalid call count') + if m['calls']['batch']%m['batch_size'] or m['calls']['batch']//m['batch_size']<2:raise ValueError('Need at least two complete batches') + for isa,arms in m['variants'].items(): + if set(arms)!={'baseline','candidate'}:raise ValueError('Need baseline and candidate for '+isa) + specs=condition_specs(m) + if len(set(c['id'] for c in specs))!=len(specs) or not specs:raise ValueError('Condition IDs must be unique') + for c in specs: + if c['worker_mode'] not in ['batch','continuous','paced']:raise ValueError('Unsupported condition mode') + n,b=c['calls'],c.get('batch_size',1) + if not isinstance(n,int) or not isinstance(b,int) or not 16<=n<=1000000 or not 1<=b<=256 or n%b or n//b<2:raise ValueError('Invalid condition size') + if c['worker_mode']!='batch' and b!=1:raise ValueError('Individual-call mode requires batch size 1') + if c['worker_mode']=='paced' and not 1000000<=c.get('period_ns',10000000)<=100000000:raise ValueError('Invalid cadence') + family=len(m['models'])*len(specs)*len(m['variants']) + if m.get('family_comparisons',family)1e-9:raise RuntimeError('Raw observation mismatch') + if abs(stats.stdev(data)-result['sample_sd_ms'])>1e-9:raise RuntimeError('SD mismatch') + if result['uid']==0 or result['no_new_privs']!=1:raise RuntimeError('Privileged worker') + if m.get('layout_profile','randomized')=='fixed' and not result.get('layout_randomization_disabled'):raise RuntimeError('ASLR policy not applied') + if not result['hardware_feedback_available']:raise RuntimeError('Hardware frequency feedback unavailable') + return dict(j,result=result,samples=str(raw.relative_to(out)),samples_sha256=sha(raw),started_ns=start,finished_ns=end) + + +def summarize(m,rows,kind,out): + conditions=[];family=m.get('family_comparisons',len(m['models'])*len(condition_specs(m))*len(m['variants'])) + keys=sorted(set((r['isa'],r['model'],r['mode']) for r in rows)) + for isa,model,mode in keys: + cell=[r for r in rows if (r['isa'],r['model'],r['mode'])==(isa,model,mode)] + logs=[] + for block in sorted(set(r['block'] for r in cell)): + p={r['label']:r for r in cell if r['block']==block} + logs.append(math.log(p['B']['result']['mean_ms']/p['A']['result']['mean_ms'])) + summary=effect(logs,.05/family) + arms={} + for label in ['A','B']: + runs=[r for r in cell if r['label']==label];raw=[] + for r in runs: + a=array.array('d');a.frombytes((out/r['samples']).read_bytes());raw.extend(a) + arms[label]=dict(run_means_ms=describe([r['result']['mean_ms'] for r in runs]),observations_ms=describe(raw), + observation_unit=runs[0]['result']['observation_unit'], + hardware_frequency_ratios=describe([r['result']['delivered_delta']/r['result']['reference_delta'] for r in runs]), + late=sum(r['result']['late'] for r in runs),over_10ms=sum(r['result']['over_10ms'] for r in runs), + minor_faults=sum(r['result']['minor_faults'] for r in runs),major_faults=sum(r['result']['major_faults'] for r in runs)) + summary.update(isa=isa,model=model,mode=mode,arms=arms) + if kind=='aa': + lo,hi=summary['interval_percent'] + summary['noise_envelope_percent']=max(abs(lo),abs(hi)) + summary['sensitivity_qualified']=summary['noise_envelope_percent']<=m.get('aa_noise_limit_percent',.5) + conditions.append(summary) + return dict(kind=kind,conditions=conditions,processes=len(rows),calls=sum(r['result']['calls'] for r in rows), + no_observations_removed=True,unit_of_inference='paired fresh-process block',family_comparisons=family, + alpha_family=.05,individual_interval_percent=100*(1-.05/family)) + + +def timing(m,kind,path,aa=None): + if kind=='compare' and (aa is None or aa.get('kind')!='aa' or aa.get('hashes')!=binary_manifest(m) or aa.get('manifest')!=m): + raise ValueError('Run A/A with exactly these binaries and inputs before comparison') + out=Path(path).resolve();out.mkdir(parents=True,exist_ok=False);(out/'samples').mkdir() + before=control('ready');emit(out/'ready-before.json',before) + jobs=schedule(m,kind) + frozen=binary_manifest(m) + emit(out/'plan.json',dict(kind=kind,manifest=m,hashes=frozen,schedule=jobs,created_ns=time.time_ns())) + emit(out/'noise-before.json',control('status')) + rows=[];checks={} + with (out/'runs.jsonl').open('x') as journal: + for j in jobs: + row=measurement(m,j,out);rows.append(row) + key=(j['model'],j['input'],j['mode']) + checksum=row['result']['checksum'] + if key in checks and checksum!=checks[key]:raise RuntimeError('Candidate state/output checksum mismatch') + checks[key]=checksum + journal.write(json.dumps(row)+'\n');journal.flush() + if len(rows)%8==0:print(kind,len(rows),'/',len(jobs),flush=True) + if binary_manifest(m)!=frozen:raise RuntimeError('Binary or input changed during the study') + emit(out/'noise-after.json',control('status')) + emit(out/'ready-after.json',control('ready')) + result=summarize(m,rows,kind,out) + result['hashes']=frozen + result['manifest']=m + if kind=='compare': + controls={(c['isa'],c['model'],c['mode']):c for c in aa['conditions']} + for c in result['conditions']: + a=controls[c['isa'],c['model'],c['mode']] + c['aa_noise_envelope_percent']=a['noise_envelope_percent'] + c['aa_qualified']=a['sensitivity_qualified'] + c['noninferiority_margin_percent']=m.get('noninferiority_margin_percent',.5) + c['passes_noninferiority']=c['aa_qualified'] and c['interval_percent'][0]>-c['noninferiority_margin_percent'] + c['passes_acceptance']=c['aa_qualified'] and c['interval_percent'][0]>max(a['noise_envelope_percent'],m.get('minimum_useful_gain_percent',.3)) and all(not arm['late'] and not arm['over_10ms'] and not arm['major_faults'] for arm in c['arms'].values()) + emit(out/'result.json',result) + return result + + +def recover_aa(m,out): + out=Path(out);plan=json.loads((out/'plan.json').read_text()) + if plan['manifest']!=m or plan['hashes']!=binary_manifest(m):raise ValueError('A/A recovery configuration changed') + jobs=schedule(m,'aa');rows=[json.loads(line) for line in (out/'runs.jsonl').read_text().splitlines()] + if len(rows)!=len(jobs):raise ValueError('Cannot resume an incomplete A/A collection') + for row,job in zip(rows,jobs): + if any(row[k]!=v for k,v in job.items()):raise ValueError('A/A schedule differs') + raw=out/row['samples'];a=array.array('d');a.frombytes(raw.read_bytes()) + if sha(raw)!=row['samples_sha256'] or len(a)!=row['result']['observations']:raise ValueError('A/A raw data differ') + if abs(stats.mean(a)-row['result']['mean_ms'])>1e-9 or abs(stats.stdev(a)-row['result']['sample_sd_ms'])>1e-9:raise ValueError('A/A metrics differ') + result=summarize(m,rows,'aa',out);result.update(hashes=plan['hashes'],manifest=m,recovered_from_complete_raw_journal=True) + emit(out/'result.json',result) + return result + + +def diagnostics(m,out): + out=Path(out);out.mkdir();(out/'samples').mkdir();rows=[] + for isa in m['variants']: + for model in m['models']: + for arm in ['baseline','candidate']: + j=dict(index=len(rows),isa=isa,model=model,arm=arm,mode='continuous',input=m['inputs'][0]) + rows.append(measurement(m,j,out)) + emit(out/'runs.json',rows) + return rows + + +def profiles(m,path): + out=Path(path).resolve();out.mkdir();(out/'samples').mkdir() + groups={'primary':'{cycles:u,instructions:u,branches:u,branch-misses:u,ref-cycles:u}', + 'frontend':'{cycles:u,instructions:u,L1-icache-load-misses:u,L1-dcache-load-misses:u,dTLB-load-misses:u}'} + jobs=[];rng=random.Random(m['seed']+2000) + groups={k:v for k,v in groups.items() if k in m.get('profile_groups',list(groups))} + selected=m.get('profile_conditions') + specs=[c for c in condition_specs(m) if c['id'] in selected] if selected else [dict(id='batch',worker_mode='batch',batch_size=16,calls=2048)] + for group in [*groups,*(['record'] if m.get('profile_sample',True) else [])]: + for rep in range(1 if group=='record' else m.get('profile_repetitions',2)): + cells=[(isa,model,arm,c) for isa in m['variants'] for model in m['models'] for arm in ['baseline','candidate'] for c in specs] + rng.shuffle(cells) + for isa,model,arm,c in cells: + jobs.append(dict(index=len(jobs),isa=isa,model=model,arm=arm,mode=c['id'],input=c.get('inputs',m['inputs'])[0],group=group,repeat=rep,worker=c.get('worker',m['worker']), + worker_mode=c['worker_mode'],batch_size=c.get('batch_size',1),period_ns=c.get('period_ns',10000000), + calls=m.get('profile_calls',{}).get(c['id'],c['calls']))) + emit(out/'plan.json',jobs);records=[] + for j in jobs: + stem=out/f"{j['index']:03d}";ctl=stem.with_suffix('.ctl');ack=stem.with_suffix('.ack') + for p in [ctl,ack]:os.mkfifo(p,0o600) + raw=out/'samples'/f"{j['index']:03d}.f64" + env=['sudo','-n','env','LC_ALL=C','DPDF_PERF_CONTROL='+str(ctl),'DPDF_PERF_ACK='+str(ack)] + cmd=[*env,'perf','record' if j['group']=='record' else 'stat','--delay=-1','--control=fifo:'+str(ctl)+','+str(ack)] + if j['group']=='record':cmd+=['--no-buildid-cache','-e','cycles:u','-F','1999','-o',str(stem.with_suffix('.data'))] + else:cmd+=['-j','-e',groups[j['group']]] + profile_m=m + cmd+=['--','/usr/bin/python3',str(CONTROLLER),'exec','--',*worker_args(profile_m,j,raw)] + try: + with stem.with_suffix('.log').open('w') as err,stem.with_suffix('.worker.json').open('w') as stdout: + subprocess.run(cmd,stdout=stdout,stderr=err,check=True,timeout=60) + row=dict(j,timing_excluded_from_speed_inference=True) + if j['group']!='record': + counters=[json.loads(line) for line in stem.with_suffix('.log').read_text().splitlines() if line.startswith('{')] + if len(counters)!=5 or any(float(c['pcnt-running'])<99.9 for c in counters):raise RuntimeError('Unsupported/multiplexed PMU group') + for c in counters:float(c['counter-value']) + row['counters']=counters;row['calls']=j['calls'] + else: + data=stem.with_suffix('.data');subprocess.run(['sudo','-n','chown',f'{os.getuid()}:{os.getgid()}',str(data)],check=True) + with stem.with_suffix('.samples.txt').open('w') as f:subprocess.run(['perf','script','--show-lost-events','-i',str(data),'-F','comm,pid,tid,time,event,ip,sym,dso'],stdout=f,check=True) + if 'PERF_RECORD_LOST' in stem.with_suffix('.samples.txt').read_text():raise RuntimeError('Lost hardware samples') + row['data_sha256']=sha(data) + records.append(row) + with (out/'hardware.jsonl').open('a') as f:f.write(json.dumps(row)+'\n') + print('profile',len(records),'/',len(jobs),flush=True) + finally: + ctl.unlink(missing_ok=True);ack.unlink(missing_ok=True) + emit(out/'result.json',dict(jobs=len(records),all_counters_running_100_percent=True,timing_excluded=True)) + return records + + +def report(out,aa,comparison): + lines=['# Isolated quantize4 comparison','','All raw observations are retained. Batch samples are amortized group means, not individual-call latency. Process/block pairs are statistical replicates. Power/idle policy is recorded in prepare.json; fixed and dynamic frequency profiles must be interpreted separately.','', + '| ISA | Model | Mode | Gain | Adjusted interval | Baseline mean ± run SD, µs | Candidate mean ± run SD, µs |','| --- | --- | --- | ---: | ---: | ---: | ---: |'] + for c in comparison['conditions']: + a=c['arms']['A']['run_means_ms'];b=c['arms']['B']['run_means_ms'];lo,hi=c['interval_percent'] + lines.append(f"| {c['isa']} | {c['model']} | {c['mode']} | {c['gain_percent']:+.3f}% | [{lo:+.3f},{hi:+.3f}]% | {a['mean']*1000:.3f} ± {a['sd']*1000:.3f} | {b['mean']*1000:.3f} ± {b['sd']*1000:.3f} |") + lines+=['','## A/A sensitivity','','| Model | Mode | A/A gain | Adjusted interval | Noise envelope | Qualified at planned limit |','| --- | --- | ---: | ---: | ---: | --- |'] + for c in aa['conditions']: + lo,hi=c['interval_percent'];lines.append(f"| {c['isa']} / {c['model']} | {c['mode']} | {c['gain_percent']:+.3f}% | [{lo:+.3f},{hi:+.3f}]% | {c['noise_envelope_percent']:.3f}% | {c['sensitivity_qualified']} |") + lines+=['','No optional sample extension or discarded slow call. A comparison whose matching A/A condition is unqualified remains diagnostic. No default promotion follows from this report automatically. See JSON for sample SD, tails, frequency ratios, faults, deadline misses and binary/input hashes.',''] + (out/'RESULTS.md').write_text('\n'.join(lines)) + + +def main(): + p=argparse.ArgumentParser(description=__doc__) + p.add_argument('mode',choices=['aa','compare','profile','session','resume']) + p.add_argument('manifest');p.add_argument('output');p.add_argument('--aa');a=p.parse_args();m=config(a.manifest) + if a.mode in ['aa','compare']: + timing(m,a.mode,a.output,json.loads(Path(a.aa).read_text()) if a.aa else None);return + if a.mode=='profile':profiles(m,a.output);return + out=Path(a.output).resolve() + if a.mode=='resume': + if not out.is_dir() or (out/'compare').exists():raise ValueError('Resume supports completed A/A with comparison not yet started') + aa=recover_aa(m,out/'aa') + archive=out/'diagnostics'/('aa-recovery-'+str(time.time_ns()));archive.mkdir(parents=True) + for name in ['prepare.json','restore.json']: + if (out/name).exists():(out/name).replace(archive/name) + else:out.mkdir(parents=True,exist_ok=False) + owned=False;session=None + try: + ready=control('prepare','--cpu',str(m.get('cpu',3)),'--frequency-khz',str(m.get('frequency_khz','auto')), + '--ttl',str(m.get('ttl_seconds',1800)),'--power-profile',m.get('power_profile','steady'),'--layout',m.get('layout_profile','randomized'),'--probe',str(Path(m['worker']).resolve())) + owned=True;session=ready['session_id'];emit(out/'prepare.json',ready) + if a.mode!='resume':aa=timing(m,'aa',out/'aa') + comparison=timing(m,'compare',out/'compare',aa) + if m.get('continuous_diagnostics',True):diagnostics(m,out/'continuous-diagnostics') + if m.get('hardware_profiles',True):profiles(m,out/'profiles') + emit(out/'ready-final.json',control('ready')) + report(out,aa,comparison) + finally: + if owned:emit(out/'restore.json',control('restore','--session',session)) + + +if __name__=='__main__': + def stop(*args):raise KeyboardInterrupt('interrupted') + signal.signal(signal.SIGTERM,stop);signal.signal(signal.SIGINT,stop) + main() diff --git a/optimized_inference/tools/bench_lab/worker.c b/optimized_inference/tools/bench_lab/worker.c new file mode 100644 index 0000000..b63135f --- /dev/null +++ b/optimized_inference/tools/bench_lab/worker.c @@ -0,0 +1,123 @@ +/* One measurement executable for every library. Kernel CPU-time accounting is + * outside the window; batch samples contain no clock calls between inferences. */ +#define _GNU_SOURCE +#include "../../include/dpdfnet.h" +#include "../support.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define CHECK(x) do {if(!(x)){fprintf(stderr,"bench worker line %d: %s\n",__LINE__,#x);return 1;}}while(0) +static int64_t ns(clockid_t c) {struct timespec t;if(clock_gettime(c,&t))abort();return (int64_t)t.tv_sec*INT64_C(1000000000)+t.tv_nsec;} +static int cmp(const void *a,const void *b){double x=*(const double *)a,y=*(const double *)b;return(x>y)-(xr0&&d1>d0); + printf("{\"reference_delta\":%"PRIu64",\"delivered_delta\":%"PRIu64",\"duration_ms\":%.6f,\"checksum\":%d}\n",r1-r0,d1-d0,(double)(end-begin)/1e6,_mm256_extract_epi32(a,0));return 0; +} +/* Prefault readable ELF mappings, including the worker's not-yet-executed + * measurement path, before warmup. No page locking or global VM changes. */ +static int prefault(struct dl_phdr_info *info,size_t size,void *opaque) { + (void)size;volatile unsigned char *sink=opaque; + for(int i=0;idlpi_phnum;++i) { + const ElfW(Phdr) *p=info->dlpi_phdr+i; + if(p->p_type!=PT_LOAD||!(p->p_flags&PF_R))continue; + const volatile unsigned char *base=(const volatile unsigned char *)(info->dlpi_addr+p->p_vaddr); + for(size_t j=0;jp_memsz;j+=4096)*sink^=base[j]; + } + return 0; +} +static int perf_command(FILE *ctl,FILE *ack,const char *s) { + if(!ctl)return 0; + if(fprintf(ctl,"%s\n",s)<0||fflush(ctl))return -1; + int c;do{c=fgetc(ack);}while(c==0); + if(c!='a'||fgetc(ack)!='c'||fgetc(ack)!='k'||fgetc(ack)!='\n')return -1; + return 0; +} +int main(int argc,char **argv) { + if(argc==4&&!strcmp(argv[1],"probe"))return probe(atoi(argv[2]),atoi(argv[3])); + CHECK(argc==9); /* library model weights input calls mode batch raw-samples */ + char *end;unsigned long calls=strtoul(argv[5],&end,10);CHECK(!*end&&calls>=16&&calls<=1000000); + unsigned long batch=strtoul(argv[7],&end,10);CHECK(!*end&&batch>=1&&batch<=256&&calls%batch==0); + int paced=!strcmp(argv[6],"paced")||!strncmp(argv[6],"paced:",6),batched=!strcmp(argv[6],"batch"); + CHECK(paced||batched||!strcmp(argv[6],"continuous"));CHECK(batched||batch==1); + int64_t period_ns=10000000; + if(!strncmp(argv[6],"paced:",6)) { + unsigned long value=strtoul(argv[6]+6,&end,10); + CHECK(!*end&&value>=1000000&&value<=100000000);period_ns=(int64_t)value; + } + void *lib=dlopen(argv[1],RTLD_NOW|RTLD_LOCAL);if(!lib){fprintf(stderr,"%s\n",dlerror());return 1;} + const dpdfnet_model_info *(*infofn)(dpdfnet_model_id); + dpdfnet_model *(*create)(dpdfnet_model_id,const float *,size_t); + int (*reset)(dpdfnet_model_id,float *); + int (*process)(dpdfnet_model *,const float *,const float *,float *,float *); + void (*destroy)(dpdfnet_model *); +#define SYM(x,n) do{*(void **)(&x)=dlsym(lib,n);CHECK(x);}while(0) + SYM(infofn,"dpdfnet_get_model_info");SYM(create,"dpdfnet_create");SYM(reset,"dpdfnet_init_state");SYM(process,"dpdfnet_process");SYM(destroy,"dpdfnet_destroy"); +#undef SYM + dpdfnet_model_id id=(dpdfnet_model_id)atoi(argv[2]);const dpdfnet_model_info *info=infofn(id);CHECK(info&&info->spectrum_floats==962); + float *w=read_weights(argv[3],info);CHECK(w);dpdfnet_model *m=create(id,w,info->weight_floats);free(w);CHECK(m); + FILE *f=fopen(argv[4],"rb");CHECK(f&&!fseek(f,0,SEEK_END));long bytes=ftell(f);CHECK(bytes>0&&bytes%(962*4)==0);rewind(f); + size_t frames=(size_t)bytes/(962*4);float *input=malloc((size_t)bytes);CHECK(input);CHECK(fread(input,1,(size_t)bytes,f)==(size_t)bytes);fclose(f); + for(size_t i=0;i<(size_t)bytes/4;++i)CHECK(isfinite(input[i])); + size_t observations=calls/batch;CHECK(observations>1);double *times=calloc(observations,sizeof(double));float *state=calloc(info->state_floats,sizeof(float));float output[962]={0};CHECK(times&&state&&!reset(id,state)); + FILE *ctl=NULL,*ack=NULL;const char *cp=getenv("DPDF_PERF_CONTROL"),*ap=getenv("DPDF_PERF_ACK"); + if(cp||ap){CHECK(cp&&ap);ctl=fopen(cp,"w");ack=fopen(ap,"r");CHECK(ctl&&ack);} + for(size_t i=0;i=10; + if(paced){int64_t finish=ns(CLOCK_MONOTONIC);late+=finish>deadline+period_ns;deadline+=period_ns;if(finish>deadline)deadline=finish;} + } + int64_t cpu1=ns(CLOCK_THREAD_CPUTIME_ID);CHECK(!getrusage(RUSAGE_SELF,&after));CHECK(!perf_command(ctl,ack,"disable")); + have_feedback=have_feedback&&!feedback(cpu,&ref1,&del1)&&ref1>ref0&&del1>del0; + if(ctl)fclose(ctl); + if(ack)fclose(ack); + f=fopen(argv[8],"wb");CHECK(f);CHECK(fwrite(times,sizeof(double),observations,f)==observations);CHECK(!fclose(f)); + double mean=0,m2=0; + for(size_t i=0;istate_floats;++i){uint32_t u;memcpy(&u,state+i,4);hash=(hash^u)*UINT64_C(1099511628211);} + for(size_t i=0;i<962;++i){uint32_t u;memcpy(&u,output+i,4);hash=(hash^u)*UINT64_C(1099511628211);} + printf("{\"layout_randomization_disabled\":%s,\"api_address\":\"%p\",\"state_address\":\"%p\",",(personality(0xffffffffUL)&ADDR_NO_RANDOMIZE)?"true":"false",(void *)process,(void *)state); + printf("\"period_ns\":%"PRId64",\"cpu\":%d,\"uid\":%u,\"no_new_privs\":%d,\"reference_delta\":%"PRIu64",\"delivered_delta\":%"PRIu64",\"hardware_feedback_available\":%s,",paced?period_ns:INT64_C(0),cpu,(unsigned)getuid(),prctl(PR_GET_NO_NEW_PRIVS,0,0,0,0),ref1-ref0,del1-del0,have_feedback?"true":"false"); + printf("\"schema_version\":1,\"mode\":\"%s\",\"model\":%d,\"calls\":%lu,\"warmup\":%zu,\"observations\":%zu,\"batch_size\":%lu,\"observation_unit\":\"%s\",\"mean_ms\":%.12f,\"sample_sd_ms\":%.12f,\"cpu_ms_per_call\":%.12f,\"p95_ms\":%.12f,\"p99_ms\":%.12f,\"max_ms\":%.12f,\"over_10ms\":%zu,\"late\":%zu,\"voluntary_switches\":%ld,\"involuntary_switches\":%ld,\"minor_faults\":%ld,\"major_faults\":%ld,\"checksum\":\"%016"PRIx64"\"}\n",argv[6],id,calls,warmup,observations,batch,batched?"batch_mean":"call",mean,sqrt(m2/(observations-1)),(double)(cpu1-cpu0)/1e6/calls,times[(observations*95)/100],times[(observations*99)/100],times[observations-1],over,late,after.ru_nvcsw-before.ru_nvcsw,after.ru_nivcsw-before.ru_nivcsw,after.ru_minflt-before.ru_minflt,after.ru_majflt-before.ru_majflt,hash); + free(times);free(state);free(input);destroy(m);dlclose(lib);return 0; +}