Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement hypothesis-based tests for linear models #4952

Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
fe6d204
Implement first prototype for hypothesis-based linear model testing.
csadorf Oct 26, 2022
cb98126
Fix copyright years.
csadorf Oct 27, 2022
fed4b6c
Adjust comments spacing to make flake8 happy.
csadorf Oct 27, 2022
ff26882
Fix and clarify assumptions.
csadorf Oct 27, 2022
01ee031
Remove max_examples override.
csadorf Oct 27, 2022
0b1a5d8
Document search strategies.
csadorf Oct 27, 2022
d7af241
Mention hypothesis strategies in developer guide.
csadorf Oct 27, 2022
dedc1ba
Datasets output values shape is either (n_samples,) or (n_samples, n_…
csadorf Oct 27, 2022
80ae1cb
fixup! Datasets output values shape is either (n_samples,) or (n_samp…
csadorf Oct 27, 2022
fab7c72
Load hypothesis profiles based on test configuration.
csadorf Oct 28, 2022
23966fa
Increase min number of samples for split_datasets() default datasets.
csadorf Oct 28, 2022
8f18663
Slightly adjust strategy definition and extend documentation.
csadorf Nov 1, 2022
fa69180
Extend and further clarify needed assumptions.
csadorf Nov 1, 2022
31346db
Declare expected failure for test_linear_regression_model_default test.
csadorf Nov 1, 2022
53dcf8f
Drop assumption for unused variable.
csadorf Nov 1, 2022
f2a0953
Improve customizability of hypothesis regression_datasets() strategy.
csadorf Nov 4, 2022
c8c100b
Adjust hypothesis profiles for more reasonable runtimes.
csadorf Nov 2, 2022
bf71841
Suppress data_too_large hypothesis healthcheck.
csadorf Nov 4, 2022
258b233
Use a more sensible strategy for n_informative.
csadorf Nov 4, 2022
79ad0cd
Improve implementation of the split_datasets() strategy.
csadorf Nov 4, 2022
3dd7036
Adjust default sizes for standard_regression_datasets strategy.
csadorf Nov 4, 2022
e9beee9
fixup! Improve customizability of hypothesis regression_datasets() st…
csadorf Nov 4, 2022
c17c991
Add additional test for standard_dataset strategy.
csadorf Nov 4, 2022
35dfbf1
fixup! Improve implementation of the split_datasets() strategy.
csadorf Nov 7, 2022
af49c89
Find hypothesis strategy to pass test_linear_regression_model_default.
csadorf Nov 7, 2022
779a23f
Refactor required assumptions into dedicated functions.
csadorf Nov 2, 2022
af41aa2
Implement test_linear_regression_model_default_generalized as stop-gap.
csadorf Nov 7, 2022
1f99c1f
Minor fixup of the documentation.
csadorf Nov 8, 2022
22fcb64
Suppress too_slow healtcheck for flaky test.
csadorf Nov 8, 2022
117496a
Merge branch 'branch-22.12' into fea-hypothesis-based-testing-for-cpu…
csadorf Nov 9, 2022
706f1ac
Suppress too_slow healthcheck for test_split_regression_datasets.
csadorf Nov 11, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions python/cuml/testing/strategies.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Copyright (c) 2019-2022, NVIDIA CORPORATION.
csadorf marked this conversation as resolved.
Show resolved Hide resolved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from hypothesis import assume
from hypothesis.extra.numpy import arrays, floating_dtypes
from hypothesis.strategies import booleans, composite, floats, integers
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split


@composite
def datasets(
wphicks marked this conversation as resolved.
Show resolved Hide resolved
draw,
dtypes=floating_dtypes(),
n_samples=integers(min_value=0, max_value=200),
n_features=integers(min_value=0, max_value=200),
):
xs = draw(n_samples)
ys = draw(n_features)
X = arrays(dtype=dtypes, shape=(xs, ys))
y = arrays(dtype=dtypes, shape=(xs, 1))
return draw(X), draw(y)


@composite
def split_datasets(
draw,
datasets=datasets(),
train_sizes=floats(min_value=0.1, max_value=1.0, exclude_max=True),
):
X, y = draw(datasets)
ts = draw(train_sizes)
assume(int(len(X) * ts) > 0) # train_test_split limitation
return train_test_split(X, y, train_size=ts)


@composite
def regression_datasets(
draw,
dtypes=floating_dtypes(),
n_samples=integers(min_value=0, max_value=200),
n_features=integers(min_value=0, max_value=200),
n_informatives=integers(min_value=0, max_value=200),
is_normal=booleans(),
):
if draw(is_normal):
dtype_ = draw(dtypes)
X, y = make_regression(
n_samples=draw(n_samples),
n_features=draw(n_features),
n_informative=draw(n_informatives),
)
return X.astype(dtype_), y.astype(dtype_)
else:
return draw(
datasets(
dtypes=dtypes,
n_samples=n_samples,
n_features=n_features,
)
)
15 changes: 15 additions & 0 deletions python/cuml/testing/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,21 @@
import pytest


def array_difference(a, b, with_sign=True):
"""
Utility function to compute the difference between 2 arrays.
"""
a = to_nparray(a)
b = to_nparray(b)

if len(a) == 0 and len(b) == 0:
return 0

if not with_sign:
a, b = np.abs(a), np.abs(b)
return np.sum(np.abs(a - b))
Copy link
Member

Choose a reason for hiding this comment

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

A common issue we've had is that sometimes it is very hard to diagnose the error or magnitude of errors when tests fail, adding some printing when failing here might be highly benefitial

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This function does not directly fail tests, but only computes the difference between arrays a and b similar to array_equal(). I use it as a target function to steer hypothesis towards larger errors.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Implemented in #4973 .



def array_equal(a, b, unit_tol=1e-4, total_tol=1e-4, with_sign=True):
"""
Utility function to compare 2 numpy arrays. Two individual elements
Expand Down
48 changes: 44 additions & 4 deletions python/cuml/tests/test_linear_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,24 @@
import cupy as cp
import numpy as np
import pytest
from hypothesis import (
assume,
example,
given,
settings,
strategies as st,
target
)
from hypothesis.extra.numpy import floating_dtypes
from distutils.version import LooseVersion
import cudf
from cuml import ElasticNet as cuElasticNet
from cuml import LinearRegression as cuLinearRegression
from cuml import LogisticRegression as cuLog
from cuml import Ridge as cuRidge
from cuml.testing.strategies import split_datasets, regression_datasets
from cuml.testing.utils import (
array_difference,
array_equal,
small_regression_dataset,
small_classification_dataset,
Expand Down Expand Up @@ -193,10 +204,38 @@ def test_linear_regression_single_column():
model.fit(cp.random.rand(46341), cp.random.rand(46341))


@pytest.mark.parametrize("datatype", [np.float32, np.float64])
def test_linear_regression_model_default(datatype):

X_train, X_test, y_train, y_test = small_regression_dataset(datatype)
@given(
split_datasets(
regression_datasets(
# Two assumptions required for cuml.LinearRegression:
n_samples=st.integers(
min_value=20, max_value=200
csadorf marked this conversation as resolved.
Show resolved Hide resolved
), # assuming min(train_size)=0.1
dtypes=floating_dtypes(sizes=(32, 64)),
)
)
)
@example(small_regression_dataset(np.float32))
@example(small_regression_dataset(np.float64))
@settings(
deadline=5000, max_examples=20
) # TODO: re-evaluate max_examples after benchmarking
def test_linear_regression_model_default(dataset):

X_train, X_test, y_train, y_test = dataset
n_rows, n_cols = X_train.shape

## Required assumptions:
# sklinearRegression:
assume(n_cols >= 1)
assume((X_train > 0).any())
assume((y_train > 0).any())
assume(np.isfinite(X_train).all())
assume(np.isfinite(y_train).all())
# cuml.LinearRegression:
wphicks marked this conversation as resolved.
Show resolved Hide resolved
assume(n_rows >= 2)
# both:
assume(n_cols >= 1)

# Initialization of cuML's linear regression model
cuols = cuLinearRegression()
Expand All @@ -211,6 +250,7 @@ def test_linear_regression_model_default(datatype):

skols_predict = skols.predict(X_test)

target(float(array_difference(skols_predict, cuols_predict)))
assert array_equal(skols_predict, cuols_predict, 1e-1, with_sign=True)


Expand Down
54 changes: 54 additions & 0 deletions python/cuml/tests/test_strategies.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Copyright (c) 2019-2022, NVIDIA CORPORATION.
csadorf marked this conversation as resolved.
Show resolved Hide resolved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from cuml.testing.strategies import (
datasets,
regression_datasets,
split_datasets,
)
from hypothesis import given


@given(datasets())
def test_datasets(dataset):
X, y = dataset

assert X.ndim == 2
assert y.ndim in (0, 1, 2)


@given(split_datasets())
def test_split_datasets(split_dataset):
X_train, X_test, y_train, y_test = split_dataset

assert X_train.ndim == X_test.ndim == 2
assert y_train.ndim == y_test.ndim
assert y_train.ndim in (0, 1, 2)


@given(regression_datasets())
def test_regression_datasets(dataset):
X, y = dataset

assert X.ndim == 2
assert y.ndim in (0, 1, 2)


@given(split_datasets(datasets=regression_datasets()))
def test_split_regression_datasets(split_dataset):
X_train, X_test, y_train, y_test = split_dataset

assert X_train.ndim == X_test.ndim == 2
assert y_train.ndim == y_test.ndim
assert y_train.ndim in (0, 1, 2)