Skip to content

Check input dimensions - #76

Merged
rapids-bot[bot] merged 1 commit into
rapidsai:release/26.04from
chyunsu3:check_input_dims
Mar 23, 2026
Merged

Check input dimensions#76
rapids-bot[bot] merged 1 commit into
rapidsai:release/26.04from
chyunsu3:check_input_dims

Conversation

@chyunsu3

@chyunsu3 chyunsu3 commented Mar 5, 2026

Copy link
Copy Markdown
Contributor

Closes #72

@chyunsu3
chyunsu3 requested a review from a team as a code owner March 5, 2026 23:29
@chyunsu3 chyunsu3 added improvement Improves an existing functionality non-breaking Introduces a non-breaking change and removed Cython / Python labels Mar 5, 2026
@coderabbitai

coderabbitai Bot commented Mar 5, 2026

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d6425249-6fe5-4183-9d47-fae69d9729e5

📥 Commits

Reviewing files that changed from the base of the PR and between 98ac84c and ae8028b.

📒 Files selected for processing (4)
  • python/nvforest/nvforest/_base.py
  • python/nvforest/nvforest/_forest_inference.py
  • python/nvforest/nvforest/detail/forest_inference.pyx
  • python/nvforest/tests/test_nvforest.py
✅ Files skipped from review due to trivial changes (1)
  • python/nvforest/nvforest/_forest_inference.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • python/nvforest/tests/test_nvforest.py
  • python/nvforest/nvforest/detail/forest_inference.pyx

📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Exposed num_features property on forest inference models to query the expected number of input features.
  • Bug Fixes

    • Added input shape validation that prevents inference with incorrect feature dimensions, raising clear errors when mismatches occur.
  • Tests

    • Added tests validating proper error handling for inputs with incorrect feature dimensions.

Walkthrough

This pull request introduces input dimension validation to nvForest by adding a num_features property to the abstract interface and all concrete implementations, then enforcing that inference methods receive data with matching feature dimensions to the trained model.

Changes

Cohort / File(s) Summary
Abstract Interface
python/nvforest/nvforest/_base.py
Added abstract read-only property num_features: int to ForestInference base class.
Concrete Implementations
python/nvforest/nvforest/_forest_inference.py
Implemented num_features property in CPUForestInferenceClassifier, CPUForestInferenceRegressor, GPUForestInferenceClassifier, and GPUForestInferenceRegressor to delegate to underlying forest instance.
Validation Logic
python/nvforest/nvforest/detail/forest_inference.pyx
Added _validate_input_dims() method to enforce input is 2D and feature count matches self.num_features; integrated validation into predict(), predict_per_tree(), and apply() methods.
Test Coverage
python/nvforest/tests/test_nvforest.py
Added parametrized test test_incorrect_data_shape that verifies ValueError is raised when input feature count mismatches trained model dimensions.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 5.88% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Check input dimensions' clearly and concisely summarizes the primary change: adding validation of input data dimensions to ensure feature counts match the trained model.
Description check ✅ Passed The description 'Closes #72' is related to the changeset by referencing the linked issue that drives these dimension-checking requirements.
Linked Issues check ✅ Passed The PR fully implements the requirements from issue #72: adds num_features property to interfaces and implementations, validates input dimensions in predict/predict_per_tree/apply methods, and includes tests verifying ValueError is raised on dimension mismatches.
Out of Scope Changes check ✅ Passed All changes are scoped to implementing dimension validation as required by issue #72; no extraneous modifications to unrelated functionality were introduced.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
python/nvforest/nvforest/_base.py (1)

93-97: Consider adding a docstring for the new num_features property.

While other abstract properties in this file also lack docstrings, the coding guidelines recommend NumPy-style docstrings for public functions/properties. Consider adding a brief docstring for completeness, such as:

`@property`
`@abstractmethod`
def num_features(self) -> int:
    """Return the number of features expected by the model."""
    pass

As per coding guidelines: "All public functions should have NumPy-style docstrings."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@python/nvforest/nvforest/_base.py` around lines 93 - 97, Add a NumPy-style
docstring to the abstract property num_features in class _base (the `@property`
`@abstractmethod` def num_features(self) -> int) describing that it returns the
number of features expected by the model; keep it brief (one-line summary and
optional short description/returns section) consistent with other public APIs.
python/nvforest/tests/test_nvforest.py (1)

861-873: Good test coverage for the new feature validation.

The test correctly verifies:

  1. The num_features property returns the expected value.
  2. A ValueError is raised with a helpful message when input dimensions mismatch.

Consider extending coverage for completeness:

  • Test with both CPU and GPU devices (parameterize with @pytest.mark.parametrize("device", ("cpu", "gpu"))).
  • Test other inference methods (predict_proba, predict_per_tree, apply) that also validate input dimensions.
  • Test with too many features (e.g., 6 columns instead of 5), not just too few.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@python/nvforest/tests/test_nvforest.py` around lines 861 - 873, Extend
test_incorrect_data_shape to parametrize over device and to exercise all
inference methods that validate input shape: add
`@pytest.mark.parametrize`("device", ("cpu","gpu")) and call
nvforest.load_from_sklearn(clf, device=device) to get fm; keep the existing
assert on fm.num_features, then for each method name in
("predict","predict_proba","predict_per_tree","apply") use
pytest.raises(ValueError, match=f"Expected {n_features} features") to call
getattr(fm, method)(np.zeros((1, 4))) and also test too-many-features by calling
each method with np.zeros((1, n_features+1))); ensure you reference the existing
test_incorrect_data_shape and the fm object when adding these checks.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@python/nvforest/nvforest/_base.py`:
- Around line 93-97: Add a NumPy-style docstring to the abstract property
num_features in class _base (the `@property` `@abstractmethod` def
num_features(self) -> int) describing that it returns the number of features
expected by the model; keep it brief (one-line summary and optional short
description/returns section) consistent with other public APIs.

In `@python/nvforest/tests/test_nvforest.py`:
- Around line 861-873: Extend test_incorrect_data_shape to parametrize over
device and to exercise all inference methods that validate input shape: add
`@pytest.mark.parametrize`("device", ("cpu","gpu")) and call
nvforest.load_from_sklearn(clf, device=device) to get fm; keep the existing
assert on fm.num_features, then for each method name in
("predict","predict_proba","predict_per_tree","apply") use
pytest.raises(ValueError, match=f"Expected {n_features} features") to call
getattr(fm, method)(np.zeros((1, 4))) and also test too-many-features by calling
each method with np.zeros((1, n_features+1))); ensure you reference the existing
test_incorrect_data_shape and the fm object when adding these checks.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 33ad5435-6a1f-490a-9f35-905774c01955

📥 Commits

Reviewing files that changed from the base of the PR and between d8aa3ee and 47025ff.

📒 Files selected for processing (4)
  • python/nvforest/nvforest/_base.py
  • python/nvforest/nvforest/_forest_inference.py
  • python/nvforest/nvforest/detail/forest_inference.pyx
  • python/nvforest/tests/test_nvforest.py

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@python/nvforest/tests/test_nvforest.py`:
- Around line 877-880: The test currently only exercises
nvforest.load_from_sklearn; add a saved-model test that goes through the
serialized-load path (use nvforest.save_model or ForestInference.save if
available to write the model to a temporary file, then call nvforest.load_model
or ForestInference.load with device="cpu") to reproduce issue-72's validation
path; ensure the loaded model's feature count is validated by asserting expected
behavior (e.g., raises or matches num_features) after loading from disk so any
regression in the load_model / ForestInference.load path is caught.
- Around line 882-884: The test currently only asserts the error starts with
"Expected {n_features} features"; update the pytest.raises match to require the
actual received feature count (input_size) too so the exception message includes
both expected and actual counts. Locate the block using predict_func, fm,
input_size and n_features and change the match to assert something like
"Expected {n_features} features, got {input_size}" (or the project's chosen
wording) so the raised ValueError contains expected vs actual values.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 963bc909-d573-46fb-ae7c-8a886be0d654

📥 Commits

Reviewing files that changed from the base of the PR and between 47025ff and 1c077cf.

📒 Files selected for processing (1)
  • python/nvforest/tests/test_nvforest.py

Comment thread python/nvforest/tests/test_nvforest.py
Comment thread python/nvforest/tests/test_nvforest.py
@chyunsu3
chyunsu3 changed the base branch from main to release/26.04 March 19, 2026 03:04
@chyunsu3
chyunsu3 requested review from a team as code owners March 19, 2026 03:04
@chyunsu3
chyunsu3 requested a review from gforsyth March 19, 2026 03:04
@github-actions github-actions Bot added conda Relates to conda packaging and removed conda Relates to conda packaging labels Mar 19, 2026
@chyunsu3 chyunsu3 mentioned this pull request Mar 23, 2026
@csadorf
csadorf removed request for a team and gforsyth March 23, 2026 21:17
@chyunsu3

Copy link
Copy Markdown
Contributor Author

/merge

@rapids-bot
rapids-bot Bot merged commit 61d28da into rapidsai:release/26.04 Mar 23, 2026
57 checks passed
@chyunsu3
chyunsu3 deleted the check_input_dims branch March 23, 2026 21:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Cython / Python improvement Improves an existing functionality non-breaking Introduces a non-breaking change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEA] Check the dimensions of the input data passed to nvForest

3 participants