Skip to content

mpn_mod: add batched AVX2 Montgomery 4x4 matrix power - #2823

Draft
Brian-Heckel wants to merge 1 commit into
flintlib:mainfrom
Brian-Heckel:mpn_mod/batched-mont
Draft

mpn_mod: add batched AVX2 Montgomery 4x4 matrix power#2823
Brian-Heckel wants to merge 1 commit into
flintlib:mainfrom
Brian-Heckel:mpn_mod/batched-mont

Conversation

@Brian-Heckel

@Brian-Heckel Brian-Heckel commented Sep 1, 2026

Copy link
Copy Markdown

Adds an AVX2 batched-Montgomery kernel for 4×4 matrices over Z/nZ and uses it to accelerate matrix powering (A^exp) called mpn_mod_mat_mul_batched_mont. On a 4×4 power over an odd modulus it is faster (1.60x) than the current generic path (gr_mat_pow_ui, which uses classical multiplies for 4×4), with the largest gains at smaller moduli. It falls back to the generic path whenever it does not apply. The matrix multiplication shouldn't be used for a generic multiply since conversion to Montgomery form has been profiled to end up taking more time than classic matrix multiplication. The mpn_mod_mat_mul_batched_mont is provided as a function but doesn't provide a speedup in itself. Tests and profiles are provided.

I'm leaving this as a draft in case details or specifics need to be addressed before merging.

Claude was used in the development and implementation of this PR.

Add an AVX2 batched-Montgomery kernel for 4x4 matrices over Z/nZ and use
it for matrix powering. Numbers are stored as 31-bit limbs with the four
output columns in the four AVX2 lanes; dot products sum their four
products into a wide accumulator and reduce with a single Montgomery REDC
(lazy reduction), valid for n < 2^246. The kernel is compile-time
specialized on the limb count s = ceil((bits+2)/31), so work scales with
the modulus size.
@Brian-Heckel
Brian-Heckel marked this pull request as draft September 2, 2026 04:32
@fredrik-johansson

Copy link
Copy Markdown
Collaborator

Interesting, but this is a lot of ad hoc code for one specific operation at one specific size. Some context is missing here: is there a particularly important application relying critically on 4x4 matrix powering with these bit sizes?

This looks like it would be more useful if:

  • not limited to one specific matrix size
  • based on machine_vectors to support other SIMD backends like NEON
  • the Montgomery kernel was designed to be reusable for other tasks (as you say, conversions take a lot of time, so it would be interesting to have an mpn_mod-like gr ring using the vector-friendly Montgomery representation internally)

Minor: bm_ctx_init should avoid fmpz operations.

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.

2 participants