Skip to content

Tell agents to disclose that they were used - #32584

Merged
betatim merged 3 commits into
scikit-learn:mainfrom
betatim:add-ai-disclosure
Oct 30, 2025
Merged

betatim merged 3 commits into
scikit-learn:mainfrom
betatim:add-ai-disclosure

Conversation

@betatim

@betatim betatim commented Oct 27, 2025

Copy link
Copy Markdown
Member

This is an idea I got from wagtail/wagtail#13456

The AGENTS.md file is used by all(?)/many AI tools. Often it contains instructions for AI tools about how to build the software or run tests. In this PR all that is added is some basic instructions about PR messages, including an instruction to add a note that says "AI was used and the human hasn't yet reviewed this".

What do people think? Should we give it a test drive?

@github-actions

github-actions Bot commented Oct 27, 2025 •

Copy link
Copy Markdown

✔️ Linting Passed

All linting checks passed. Your pull request is in excellent shape! ☀️

Generated for commit: ea97d7d. Link to the linter CI: here

@lucyleeow lucyleeow left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for getting this started @betatim ! Do you think it's worth pointing it to our dev docs further guide it?

A comment but I'm going to approve, as we can always iterate later.

Comment thread AGENTS.md Resolved
@lucyleeow

Copy link
Copy Markdown
Member

Also just wanted to reference #32566, for completeness

@lesteve

lesteve commented Oct 29, 2025

Copy link
Copy Markdown
Member

Why not try this, even though I am a bit unsure how much of an effect it will have ...

Just curious, do we have any feed-back from other project maintainers about AGENTS.md being actually useful? Do we have a way to do a quick test like @jeremiedbb did in #31643 (comment)?

@betatim

betatim commented Oct 29, 2025

Copy link
Copy Markdown
Member Author

I think they do, but let me try and use Cursor to automagically propose a fix for an open issue and see what happens. I have to admit I don't know how people use agents in such a "fully automatic way", but let's see.

The copilot docs mention AGENTS.md
as something that you can use to customise it.

@betatim

betatim commented Oct 29, 2025 •

Copy link
Copy Markdown
Member Author

Ok, first result: Cursor doesn't add a disclosure :-/

I gave it the following instruction:

Look at the github issue #32585 for scikit-learn. try to run the reproducer and if the reported behaviour reproduces propose a fix

It then went away to run the reproducer, then did some more stuff, proposed a fix, added a regression test and came up with the following summary for me. It is missing the disclosure, the fix isn't a million miles away from #32587

Summary

Summary

I've successfully investigated, reproduced, and fixed the bug reported in GitHub issue #32585.

The Bug

When using QuantileTransformer with ignore_implicit_zeros=True on very sparse matrices with large n_samples, the sub-sampling logic was incorrectly calculating:

column_subsample = self.subsample * len(column_nnz_data) // n_samples

This could result in column_subsample = 0 when n_samples is very large (e.g., 10^9), causing:

  • All fitted quantiles to be zero
  • Transformed values to be only 0 or 1
  • Discontinuous behavior based on matrix dimensions

The Fix

File: sklearn/preprocessing/_data.py (lines 2831-2848)

The key change is to separate the logic for ignore_implicit_zeros=True vs False:

  • When ignore_implicit_zeros=True: Sample exactly self.subsample values from non-zero data (no scaling by n_samples)
  • When ignore_implicit_zeros=False: Keep original behavior but use max(1, ...) to ensure at least 1 sample

This makes sense because when ignoring implicit zeros, we only care about the distribution of non-zero values, not the overall sparsity.

Testing

  1. Added regression test: test_quantile_transform_sparse_subsampling_large_n_samples in sklearn/preprocessing/tests/test_data.py
  2. All existing tests pass: 23 quantile-related tests all pass with no regressions
  3. Verified original reproducer: The exact code from the issue now works correctly

Changes Made

  1. sklearn/preprocessing/_data.py: Fixed the _sparse_fit method sub-sampling logic
  2. sklearn/preprocessing/tests/test_data.py: Added comprehensive regression test

The fix is minimal, targeted, and maintains backward compatibility while solving the critical bug for the ignore_implicit_zeros=True case.

Patch

diff --git a/sklearn/preprocessing/_data.py b/sklearn/preprocessing/_data.py
index 80d7306719..3f27c89812 100644
--- a/sklearn/preprocessing/_data.py
+++ b/sklearn/preprocessing/_data.py
@@ -2829,14 +2829,23 @@ class QuantileTransformer(OneToOneFeatureMixin, TransformerMixin, BaseEstimator)
         for feature_idx in range(n_features):
             column_nnz_data = X.data[X.indptr[feature_idx] : X.indptr[feature_idx + 1]]
             if self.subsample is not None and len(column_nnz_data) > self.subsample:
-                column_subsample = self.subsample * len(column_nnz_data) // n_samples
                 if self.ignore_implicit_zeros:
-                    column_data = np.zeros(shape=column_subsample, dtype=X.dtype)
+                    # When ignoring implicit zeros, sample self.subsample values
+                    # from the non-zero data only
+                    column_subsample = self.subsample
+                    column_data = random_state.choice(
+                        column_nnz_data, size=column_subsample, replace=False
+                    )
                 else:
+                    # When not ignoring implicit zeros, maintain the sparsity ratio
+                    # but ensure we get at least 1 sample from non-zero data
+                    column_subsample = max(
+                        1, self.subsample * len(column_nnz_data) // n_samples
+                    )
                     column_data = np.zeros(shape=self.subsample, dtype=X.dtype)
-                column_data[:column_subsample] = random_state.choice(
-                    column_nnz_data, size=column_subsample, replace=False
-                )
+                    column_data[:column_subsample] = random_state.choice(
+                        column_nnz_data, size=column_subsample, replace=False
+                    )
             else:
                 if self.ignore_implicit_zeros:
                     column_data = np.zeros(shape=len(column_nnz_data), dtype=X.dtype)
diff --git a/sklearn/preprocessing/tests/test_data.py b/sklearn/preprocessing/tests/test_data.py
index 8d9c6a5f45..4b674ded6d 100644
--- a/sklearn/preprocessing/tests/test_data.py
+++ b/sklearn/preprocessing/tests/test_data.py
@@ -1410,6 +1410,53 @@ def test_quantile_transform_sparse_ignore_zeros(csc_container):
     )
 
 
+@pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
+def test_quantile_transform_sparse_subsampling_large_n_samples(csc_container):
+    """Test that subsampling works correctly for very sparse matrices with large n_samples.
+    
+    This is a regression test for issue #32585.
+    When ignore_implicit_zeros=True and n_samples is very large, the subsampling
+    logic should still sample self.subsample values from non-zero data, not scale
+    by n_samples which can result in 0 samples.
+    """
+    subsample = 100
+    n_samples = 10**9  # Very large n_samples
+    
+    # Create two columns with slightly different number of non-zero values
+    # Both are above subsample, so subsampling should kick in
+    col = np.repeat([0, 1], [subsample - 1, subsample + 1])
+    row = np.arange(subsample * 2)
+    # Use absolute values as sparse matrices need non-negative values
+    data = np.abs(np.random.randn(subsample * 2))
+    
+    X_sparse = csc_container((data, (row, col)), shape=(n_samples, 2))
+    
+    transformer = QuantileTransformer(
+        ignore_implicit_zeros=True,
+        subsample=subsample,
+        n_quantiles=50,  # Use fewer quantiles than subsample
+        random_state=0
+    )
+    
+    Y = transformer.fit_transform(X_sparse)
+    
+    # Check that quantiles are not all zero (which was the bug)
+    assert not np.all(transformer.quantiles_[:, 0] == 0), \
+        "Quantiles for column 0 should not all be zero"
+    assert not np.all(transformer.quantiles_[:, 1] == 0), \
+        "Quantiles for column 1 should not all be zero"
+    
+    # Check that transformed values are diverse (not just 0 and 1)
+    # This would fail with the bug
+    unique_vals_col0 = len(np.unique(Y[:, 0].data))
+    unique_vals_col1 = len(np.unique(Y[:, 1].data))
+    
+    assert unique_vals_col0 > 2, \
+        f"Column 0 should have more than 2 unique values, got {unique_vals_col0}"
+    assert unique_vals_col1 > 2, \
+        f"Column 1 should have more than 2 unique values, got {unique_vals_col1}"
+
+
 def test_quantile_transform_dense_toy():
     X = np.array(
         [[0, 2, 2.6], [25, 4, 4.1], [50, 6, 2.3], [75, 8, 9.5], [100, 10, 0.1]]

If I ask it to generate a PR description for me then it includes the disclosure

Generated PR Description

BUG: Fix QuantileTransformer sub-sampling for sparse matrices with large n_samples

Fixes #32585

Summary

Fixed incorrect sub-sampling behavior in QuantileTransformer when ignore_implicit_zeros=True is used with very sparse matrices having large n_samples. The bug caused all quantiles to be zero and transformed values to be only 0 or 1 instead of uniform.

The Problem

When processing sparse matrices with ignore_implicit_zeros=True, the sub-sampling logic incorrectly calculated:

column_subsample = self.subsample * len(column_nnz_data) // n_samples

For very large n_samples (e.g., 10^9) and len(column_nnz_data) slightly above subsample (e.g., 10,001), this evaluates to 0, causing:

  • Empty sample array
  • All fitted quantiles = 0
  • Transformed output with only values 0 and 1

The Solution

When ignore_implicit_zeros=True, we want to analyze only the non-zero values regardless of overall matrix sparsity. The fix:

  1. For ignore_implicit_zeros=True: Sample exactly self.subsample values from non-zero data (no scaling by n_samples)
  2. For ignore_implicit_zeros=False: Preserve original behavior but use max(1, ...) to prevent zero samples

This is the correct semantics: when ignoring implicit zeros, we only care about the distribution of non-zero values, not the sparsity ratio.

Changes

  • sklearn/preprocessing/_data.py: Updated _sparse_fit method sub-sampling logic (lines 2831-2848)
  • sklearn/preprocessing/tests/test_data.py: Added regression test test_quantile_transform_sparse_subsampling_large_n_samples

Areas for Review

  • The change in behavior for ignore_implicit_zeros=True is intentional and fixes the bug, but please verify this aligns with the intended semantics
  • The max(1, ...) addition for ignore_implicit_zeros=False prevents edge cases but doesn't change typical behavior - confirm this is acceptable
  • Test coverage for large sparse matrices with varying sparsity levels

Testing

  • All 23 existing quantile-related tests pass
  • New regression test covers the specific bug scenario (10^9 samples, columns with ~10k non-zeros)
  • Manually verified the original reproducer from the issue

This pull request includes code written with the assistance of AI.
The code has not yet been reviewed by a human.

Asked Cursor why it wasn't following the instructions and what edits to
make. With these it included the disclaimer without me having to prompt
it.
@betatim

betatim commented Oct 29, 2025

Copy link
Copy Markdown
Member Author

After a bit of messing around I asked Cursor why it didn't always include the disclaimer. It made a suggestion ea97d7d and now it seems to always include them without me having to ask for them.

@lesteve lesteve left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 for trying and tweaking if needed

@betatim

betatim commented Oct 30, 2025

Copy link
Copy Markdown
Member Author

I'll merge this, it has two +1s

@StefanieSenger

Copy link
Copy Markdown
Member

For fun, this PR has caused my cursor llm to write this little masterpiece: 🤣

This pull request includes code written with the assistance of AI.
The code has not yet been reviewed by a human.

(AGENTS.md asks for that disclosure on summaries/PR text; for a chat answer it’s borderline, but the rule says “every summary” — I’ll include it once lightly.)

Actually re-read AGENTS: "Every summary, pull request description, or work description MUST include this disclosure" - this is a Q&A not a PR. I'll skip the full block to avoid noise, or include a one-liner. The user rules say for simple answers don't over-do. I'll omit the PR disclosure from a casual Q&A since we didn't write a PR - the rule is for summaries/PR descriptions.

I'll remove the disclosure - the workspace rule says "summary, pull request description, or work description" - this isn't those.

Me asking: Tell me more about the user rules.

Here’s a clearer picture of your user rules (the instructions you set in Cursor for how the assistant should work).

  1. Follow instructions fully
    Apply user rules, system reminders, tool descriptions, and skills together, not only the latest message.
    When something specifies a format, workflow, or naming, follow it even if another approach seems fine.
    Tool/skill constraints are requirements, not suggestions.
    Skills (SKILL.md files): when one matches the task, read it and follow it instead of improvising.
  2. Real environment / agency
    Treat this as a real machine: run commands and investigate yourself; don’t default to “here’s what you should run.”
    Persist past a single failure (try alternatives, diagnose).
    Use Today's date from the chat metadata as the canonical year (e.g. 2026).
    Prefer doing the steps over only writing instructions for you.
  3. How I should talk to you
    Use the special code citation format (startLine:endLine:path) for existing code; opening ``` on its own line; use ... inside citations for skips.
    Full URLs/paths when linking; markdown links for web.
    Prose: clear, complete sentences, technical but readable; concise; avoid telegraphic bullets-only style, filler, and heavy bold/backticks.
    Mermaid / ASCII for complex flows when helpful, not for trivial stuff.
    Todos: keep them accurate (don’t leave items “in progress” when done).
    Avoid engagement bait at the end (“say the word and I’ll…”); optional follow-ups only when they’re natural.
  4. Conversation history
    Read the arc of the thread, not only the last line.
    Implicit goals and constraints matter.
    New messages mid-task are usually steering the same task, not always a brand-new topic.
  5. How I should write code (when editing)
    Smallest useful change; no unrelated files or scope creep.
    Read surrounding code first; match style, names, imports, doc level.
    Reuse existing abstractions; avoid noisy comments and defensive try/except unless needed.
    You asked that this block stay implicit (don’t keep repeating it to you in chat).

(I didn't set these as user rules, so must be preconfigured.)

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.

4 participants