Skip to content

Add kronecker, the Kronecker product of two matrices - #3513

Open
jachymb wants to merge 2 commits into
stan-dev:developfrom
jachymb:feature/kronecker
Open

jachymb wants to merge 2 commits into
stan-dev:developfrom
jachymb:feature/kronecker

Conversation

@jachymb

@jachymb jachymb commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

AI use disclosure: This was developed with the help of Claude Code (Opus 5.5).

Summary

Adds kronecker(A, B): for an $m \times n$ matrix $A$ and a $p \times q$ matrix $B$, the $mp \times nq$ block matrix whose block $(i, j)$ is $A_{ij} B$,

$$(A \otimes B)_{pi + k,\ qj + l} = A_{ij} B_{kl}.$$

It takes two real or two complex matrices, for the planned Stan signatures matrix kronecker(matrix, matrix) and complex_matrix kronecker(complex_matrix, complex_matrix) (stanc3 PR to follow).

  • prim/fun/kronecker.hpp: one template for every scalar except var (double, complex, std::complex<var>, and fvar, so there is no fwd overload). Column $qj + l$ of the result, read as a $p \times m$ matrix, is the outer product $B_{\cdot l} A_{\cdot j}^\top$, so the result is filled one column at a time with Eigen outer products. Eigen's unsupported kroneckerProduct, which loops over the $mn$ blocks, took 1.0–3.0x as long (1.0x at 2x2 ⊗ 100x100, 3.0x at 50x50 ⊗ 3x3); it was faster only for row vector ⊗ row vector (see Side Effects).
  • rev/fun/kronecker.hpp: analytic adjoints for Eigen::Matrix<var> and var_value<Eigen::MatrixXd>, also mixed with double matrices. With $G_c$ the column $c = qj + l$ of the result's adjoint read as a $p \times m$ matrix, the reverse pass adds $G_c^\top B_{\cdot l}$ to column $j$ of $\bar A$ and $G_c A_{\cdot j}$ to column $l$ of $\bar B$: two matrix-vector products per column. In a gradient of sum(K .* W):
    • from 5x5 ⊗ 5x5 up, Matrix<var> arguments take 0.8–1.1x the time of the prim template instantiated with var (one node per entry) and 32 instead of 40 bytes of arena memory per product entry;
    • from 10x10 ⊗ 10x10 up, var_value arguments are 3.3–4.9x faster than Matrix<var>.

Tests

  • prim/fun/kronecker_test.cpp: a real 2x3 ⊗ 3x2 and a complex 2x2 ⊗ 2x1 product against numpy.kron; a factor with no rows.
  • mix/fun/kronecker_test.cpp: expect_ad and expect_ad_matvar for all pairs of seven shapes (2x3, 3x2, 1x1, 3x1, 0x0, 0x2, 2x0), vector ⊗ row vector and row vector ⊗ matrix; expect_ad for a complex 2x2 ⊗ 3x1 product in both orders.
  • The expression tests pass with the explicit signatures kronecker(matrix, matrix) => matrix and kronecker(complex_matrix, complex_matrix) => complex_matrix.

Side Effects

None

Release notes

Added kronecker, the Kronecker product of two real or two complex matrices.

Checklist

  • Copyright holder: Jáchym Barvínek jachymb@gmail.com

    The copyright holder is typically you or your assignee, such as a university or company. By submitting this pull request, the copyright holder is agreeing to the license the submitted work under the following licenses:
    - Code: BSD 3-clause (https://opensource.org/licenses/BSD-3-Clause)
    - Documentation: CC-BY 4.0 (https://creativecommons.org/licenses/by/4.0/)

  • the basic tests are passing

    • unit tests pass (to run, use: ./runTests.py test/unit)
    • header checks pass, (make test-headers)
    • dependencies checks pass, (make test-math-dependencies)
    • docs build, (make doxygen)
    • code passes the built in C++ standards checks (make cpplint)
  • the code is written in idiomatic C++ and changes are documented in the doxygen

  • the new changes are tested

The prim template covers every scalar except var, including complex,
and fills the result one column at a time with Eigen outer products.
The rev overload has analytic adjoints for Matrix<var> and var_value
arguments, mixed with double matrices.
With one data operand, the reverse pass no longer allocates an adjoint
buffer for it or gathers the value of the var operand, which only the
data operand's adjoint would need.
@stan-buildbot

Copy link
Copy Markdown
Contributor
Name Old Result New Result Ratio Performance change( 1 - new / old )
stat_comp_benchmarks/benchmarks/gp_regr/gp_regr.stan 0.25 0.25 1.0 0.18% faster
stat_comp_benchmarks/benchmarks/gp_regr/gen_gp_data.stan 0.06 0.06 1.0 0.32% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 6.63 6.65 1.0 -0.27% slower
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.02 0.02 0.97 -2.64% slower
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 9.29 9.35 0.99 -0.6% slower
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 4.77 4.67 1.02 2.04% faster
stat_comp_benchmarks/benchmarks/sir/sir.stan 224.25 224.79 1.0 -0.24% slower
stat_comp_benchmarks/benchmarks/garch/garch.stan 1.0 1.01 0.99 -0.56% slower
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.69 0.7 1.0 -0.42% slower
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 42.89 44.01 0.97 -2.61% slower
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.59 0.6 0.98 -2.16% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 21.74 21.87 0.99 -0.57% slower
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.11 0.11 1.0 -0.16% slower
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.41 3.41 1.0 0.11% faster
performance.compilation 373.51 359.88 1.04 3.65% faster
Mean result: 0.9976335668073872

Jenkins Console Log
Jenkins Build Stages
Commit hash: 0ed527b361ff570d4ef4fd7c95e47dca0f433fa3

Machine information
Distributor ID:	Ubuntu
Description:	Ubuntu 20.04.3 LTS
Release:	20.04
Codename:	focal

CPU:

Architecture:                            x86_64
CPU op-mode(s):                          32-bit, 64-bit
Byte Order:                              Little Endian
Address sizes:                           43 bits physical, 48 bits virtual
CPU(s):                                  256
On-line CPU(s) list:                     0-255
Thread(s) per core:                      2
Core(s) per socket:                      64
Socket(s):                               2
NUMA node(s):                            2
Vendor ID:                               AuthenticAMD
CPU family:                              23
Model:                                   49
Model name:                              AMD EPYC 7742 64-Core Processor
Stepping:                                0
Frequency boost:                         enabled
CPU MHz:                                 1495.956
CPU max MHz:                             3416.0681
CPU min MHz:                             1500.0000
BogoMIPS:                                4491.80
Virtualization:                          AMD-V
L1d cache:                               4 MiB
L1i cache:                               4 MiB
L2 cache:                                64 MiB
L3 cache:                                512 MiB
NUMA node0 CPU(s):                       0-63,128-191
NUMA node1 CPU(s):                       64-127,192-255
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Old microcode:             Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Mitigation; untrained return thunk; SMT enabled with STIBP protection
Vulnerability Spec rstack overflow:      Mitigation; Safe RET
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; Retpolines; IBPB conditional; STIBP always-on; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Mitigation; IBPB before exit to userspace
Flags:                                   fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif v_spec_ctrl umip rdpid overflow_recov succor smca sev sev_es

G++:

g++ (Ubuntu 9.4.0-1ubuntu1~20.04) 9.4.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Clang:

clang version 10.0.0-4ubuntu1 
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin

@WardBrian

Copy link
Copy Markdown
Member

If I'm remembering discussions with @bob-carpenter correctly, this was more or less an intentional omission, since actually forming the matrix of the Kronecker product usually means you're hosed in terms of memory/compute. Unfortunately doing it lazily would require a bunch of changes to how the language generates code

@bob-carpenter

bob-carpenter commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

We don't even want to build the Kronecker product lazily. It needs to be kept structured so that, for example,

$\quad (A \otimes B)^{-1} = A^{-1} \otimes B^{-1}$

and if $A$ is $n \times n$ and $B$ is $m \times m$,

$\quad \det (A \otimes B) = (\det A)^n \cdot (\det B)^m$.

@jachymb

jachymb commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

I recently used Kronecker product in a model I was building and I was surprised Stan didn't have it so I offer this implementation. (I am doing a multivariate model with a GP latent, using the Kronecker product to construct the covariance matrix). But at least in my case a double for loop works just as well, so in case this is undesired, feel free to close the PR.

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants