Skip to content

additive_chi2_kernel rejects read-only input arrays (buffer source array is read-only) #35446

Open

Description

@nulltracer-maker

Warning

This issue is not yet ready for a PR. If you are interested in contributing to scikit-learn, please have a look at our contributing guidelines, and in particular the sections for new contributors and the "Needs triage" label.

Introduce yourself

No response

Describe the bug and give evidence about its user-facing impact

sklearn.metrics.pairwise.additive_chi2_kernel raises a Cython buffer error when given a read-only NumPy array, while an identical writable array works. The related public API chi2_kernel is affected as well.

This affects users working with read-only data, such as memory-mapped arrays loaded through joblib.load(mmap_mode="r") or np.memmap. These arrays are valid NumPy inputs, and computing a chi-squared kernel only requires reading the feature values, not modifying them. Currently, users must make an unnecessary writable copy before calling these functions, which can increase memory usage for large datasets.

Other pairwise functions, such as euclidean_distances and manhattan_distances, accept the same read-only input, suggesting inconsistent handling across public APIs.

I encountered this while checking whether Cython buffer requirements are compatible with NumPy arrays accepted by public Python APIs.

A related issue, #25484, discussed improving support for read-only buffers through const memoryviews. This report identifies a specific remaining case in _chi2_kernel_fast.

Steps/Code to Reproduce

import numpy as np
from sklearn.metrics.pairwise import additive_chi2_kernel, chi2_kernel

rs = np.random.RandomState(0)
X = np.abs(rs.rand(30, 4))

X_ro = X.copy()
X_ro.setflags(write=False)

# Writable input: works
additive_chi2_kernel(X)
chi2_kernel(X)

# Identical read-only input: fails
additive_chi2_kernel(X_ro)
chi2_kernel(X_ro)

Expected Results

Both additive_chi2_kernel and chi2_kernel should accept read-only NumPy arrays and return the same results as for identical writable arrays.

These functions only need to read the input feature values and do not need to modify the caller's arrays. The public API documentation does not specify a writable-input requirement.

Ideally, read-only inputs should be supported without requiring an unnecessary copy.

Actual Results

Both additive_chi2_kernel and chi2_kernel raise:

ValueError: buffer source array is read-only

The error originates from the Cython implementation _chi2_kernel_fast in sklearn/metrics/_pairwise_fast.pyx.

In sklearn/metrics/pairwise.py, additive_chi2_kernel validates the inputs through check_pairwise_arrays, which does not guarantee writable arrays, and then passes them to _chi2_kernel_fast.

The Cython kernel declares its arguments as non-const memoryviews:

def _chi2_kernel_fast(
    floating[:, :] X,
    floating[:, :] Y,
    floating[:, :] result
):

However, the kernel only reads X and Y to compute pairwise chi-squared distances. The computed values are written to the separately allocated result array. Neither input is modified.

Consequently, the Cython buffer interface unnecessarily requires the input arrays to be writable.

Versions

System:
    python: 3.12.16 (main, Nov 11 2026, 00:09:12) [Clang 23.1.3 ]
executable: python
   machine: macOS-26.5.1-arm64-arm-64bit

Python dependencies:
      sklearn: 1.9.1
          pip: 26.3
   setuptools: 84.2.1
        numpy: 2.5.5
        scipy: 1.18.1
       Cython: 3.3.1
       pandas: 3.1.1
   matplotlib: 3.11.2
       joblib: 1.6.0
threadpoolctl: 3.8.0
     narwhals: 2.28.0

Built with OpenMP: True

Interest in fixing the bug

I would be happy to help investigate and test a fix.

The likely root cause is that _chi2_kernel_fast declares both input arrays as non-const Cython memoryviews, although it only reads them.

A possible fix would be to declare X and Y as const while keeping result writable:

def _chi2_kernel_fast(
const floating[:, :] X,
const floating[:, :] Y,
floating[:, :] result
):

Alternatively, the Python wrapper could create writable copies only when necessary, although the const approach would avoid unnecessary memory allocations.

Activity

  1. KinjalGoswami68 commented on Nov 18, 2026

    @KinjalGoswami68

    Can reproduce on windows 11, python 3.14.3, sklearn 1.9.1, numpy 2.5.5 (pypi wheel). both additive_chi2_kernel and chi2_kernel raise the same ValueError on a read-only array, writable copy is fine. euclidean_distances takes a read-only array without complaint.
    The const change looks like the same fix _sparse_manhattan got in _pairwise_fast.pyx. happy to take this once triaged and add a regression test for it.

  2. vnigoated commented on Nov 24, 2026

    @vnigoated

    I can reproduce this on current main. Declaring the X and Y memoryviews of _chi2_kernel_fast as const (as was done for _sparse_manhattan) fixes it. I have a fix with a non-regression test ready and would like to open a PR once this is triaged.

  3. rvcreationworld commented on Nov 25, 2026

    @rvcreationworld

    Hi maintainers,

    I investigated this issue and reproduced the ValueError: buffer source array is read-only when passing arrays with writeable=False into both additive_chi2_kernel and chi2_kernel.

    Root Cause Analysis

    In sklearn/metrics/pairwise_fast.pyx, the Cython function definitions for _chi2_kernel_fast and _additive_chi2_kernel_fast type their memoryviews as mutable buffers:

    floating[:, :] X, floating[:, :] Y

    Because the buffer protocol enforces write permissions unless explicitly marked read-only, passing a read-only buffer triggers a runtime failure, even though these kernels only perform read operations.

    Proposed Fix

    1. Update memoryview parameter signatures in pairwise_fast.pyx to use the const modifier:
      const floating[:, :] X, const floating[:, :] Y
    2. Verify that pointer casting inside internal loops respects const qualifiers across GCC, Clang, and MSVC.
    3. Add unit tests in sklearn/metrics/tests/test_pairwise.py covering both float32 and float64 read-only arrays (via arr.flags.writeable = False).

    I have a branch passing local tests and would be glad to open a PR if this design direction looks good to you.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugNeeds Triage

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions