Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -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.
53 changes: 53 additions & 0 deletions justfile
Original file line number Diff line number Diff line change
@@ -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"
58 changes: 56 additions & 2 deletions optimized_inference/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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"
$<$<COMPILE_LANGUAGE:C>:-fvisibility=hidden>)
Expand Down Expand Up @@ -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)
Expand All @@ -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_OBJECTS:backend${size}>)
target_include_directories(${target} PRIVATE include src src/private)
Expand All @@ -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.
Expand All @@ -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)
Expand Down Expand Up @@ -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()
Expand All @@ -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})
Expand All @@ -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}"
$<TARGET_OBJECTS:backend2> $<TARGET_OBJECTS:backend8>
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")
Expand Down
10 changes: 6 additions & 4 deletions optimized_inference/benchmarks/kernels.c
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,17 @@ 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));
float *w=malloc(count*sizeof(float)),*y=malloc(count*sizeof(float)),*z=malloc(count*sizeof(float));
if(!x||!b||!w||!y||!z) return 2;
for(size_t i=0;i<count;++i){x[i]=sample();b[i]=sample();w[i]=sample();y[i]=0;z[i]=0;}
dpdf_qmatrix *q0=dpdf_qcreate(w,64,192),*q1=dpdf_qcreate(w+64*192,64,192);
if(!q0||!q1) return 2;
dpdf_qmatrix *q128=dpdf_qcreate(w,128,64);
if(!q0||!q1||!q128) return 2;
int64_t start=0,cpu_start=0,warm_deadline=ns(CLOCK_MONOTONIC)+INT64_C(100000000);
for(int i=-1000;i<iterations;++i) {
if(i==0 && ns(CLOCK_MONOTONIC)<warm_deadline) i=-1000;
Expand All @@ -53,13 +54,14 @@ int main(int argc,char **argv) {
case 6: case 7: case 8: dpdf_gates_avx2(x,b,w,y,kind==6?1:kind==7?40:48); break;
case 9: dpdf_norm_residual_avx2(y,x,b,w,w+64,1e-5f,40); break;
case 10: dpdf_transpose_avx2(x,y,64,48); break;
case 11: dpdf_qaffine(q128,x,b,y,40); break;
}
}
int64_t elapsed=ns(CLOCK_MONOTONIC)-start,cpu=ns(CLOCK_THREAD_CPUTIME_ID)-cpu_start;
uint32_t checksum=0;
for(size_t i=0;i<count;++i){uint32_t value;memcpy(&value,y+i,4);checksum=checksum*33+value;}
printf("{\"kernel\":\"%s\",\"iterations\":%d,\"mean_ms\":%.12f,\"cpu_ms\":%.12f,\"checksum\":%u,\"measurement\":\"hot-cache amortized call time, not per-call latency\"}\n",
names[kind],iterations,(double)elapsed/iterations/1e6,(double)cpu/iterations/1e6,checksum);
dpdf_qdestroy(q0);dpdf_qdestroy(q1);free(x);free(b);free(w);free(y);free(z);
dpdf_qdestroy(q0);dpdf_qdestroy(q1);dpdf_qdestroy(q128);free(x);free(b);free(w);free(y);free(z);
return 0;
}
Loading
Loading