Skip to content

Reuse converted arrays during L2 embedding normalization - #1769

Open
Afloat16 wants to merge 1 commit into
serengil:masterfrom
Afloat16:perf/reuse-l2-embedding-arrays-20261127
Open

Afloat16 wants to merge 1 commit into
serengil:masterfrom
Afloat16:perf/reuse-l2-embedding-arrays-20261127

Conversation

@Afloat16

Copy link
Copy Markdown
Contributor

What has been done

L2 postprocessing converts each nonzero Python embedding list to a NumPy array twice: once implicitly inside np.linalg.norm, and again before division. This also happens for every row of the model output passed by representation.represent(..., l2_normalize=True).

Create the array once and reuse it for the norm and division. The change preserves the existing row-by-row behavior, output values and list layout, including zero vectors, empty rows, unequal row lengths and unchanged caller input. It does not change the normalization formula or batch allocation strategy.

Validation

Seven model-independent regression tests pass against both the base and the patch. They cover scalar-vector and batch results, integer-valued inputs, zero and signed-zero values, empty/unequal rows, input ownership, and 128/512/4096-dimensional vectors with element-for-element reference equality.

PYTHONPATH=. python -m unittest discover -s tests/unit -p test_l2_embedding_values.py -v

The included benchmark imports the actual baseline and patched normalization modules. It alternates their order, uses two warm-up runs followed by ten measured runs per version, and checks output equality before timing.

Batch × dimensions Base median Patched median Base / patched
1 × 128 0.0187 ms 0.0148 ms 1.265×
64 × 128 0.7995 ms 0.5596 ms 1.429×
64 × 512 2.7879 ms 1.6896 ms 1.650×
512 × 512 23.1286 ms 15.4041 ms 1.501×
64 × 4096 20.6625 ms 13.2555 ms 1.559×
512 × 4096 181.0389 ms 120.1891 ms 1.506×

Measured on Linux x86_64, Python 3.12.14 and NumPy 2.3.5, using base 8cec026045be164e14b510c55c1264e743dc4999. These measurements cover L2 postprocessing of already computed embeddings; they are not end-to-end model inference results.

git show 8cec026045be164e14b510c55c1264e743dc4999:deepface/modules/normalization.py > /tmp/normalization-before.py
PYTHONPATH=. python experiments/benchmark_l2_normalization.py \
  --baseline /tmp/normalization-before.py --output /tmp/l2-results.json

The benchmark writes all individual timings and environment details to the requested JSON file. Full model inference tests and the repository-wide lint suite were not run locally.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant