Open In Colab View Notebook on GitHub

🗣️ NLP Quickstart

Giskard is an open-source framework for testing all ML models, from LLMs to tabular models. Don’t hesitate to give the project a star on GitHub ⭐️ if you find it useful!

In this notebook, you’ll learn how to create comprehensive test suites for your model in a few lines of code, thanks to Giskard’s open-source Python library.

Use-case:

Outline:

  • Detect vulnerabilities automatically with Giskard’s scan

  • Automatically generate & curate a comprehensive test suite to test your model beyond accuracy-related metrics

Install dependencies

[ ]:
%pip install giskard --upgrade

Import libraries

[27]:
import numpy as np
import pandas as pd
from datasets import load_dataset
from scipy.special import softmax
from transformers import AutoModelForSequenceClassification, AutoTokenizer

from giskard import Dataset, Model, scan, testing

Define constants

[28]:
MODEL_NAME = "cardiffnlp/twitter-roberta-base-sentiment"

DATASET_CONFIG = {"path": "tweet_eval", "name": "sentiment", "split": "validation"}

LABEL_MAPPING = {0: "negative", 1: "neutral", 2: "positive"}

TEXT_COLUMN = "text"
TARGET_COLUMN = "label"

Dataset preparation

Load and preprocess data

[29]:
raw_data = load_dataset(**DATASET_CONFIG).to_pandas().iloc[:500]
raw_data = raw_data.replace({"label": LABEL_MAPPING})

Wrap dataset with Giskard

To prepare for the vulnerability scan, make sure to wrap your dataset using Giskard’s Dataset class. More details here.

[30]:
giskard_dataset = Dataset(
    df=raw_data,
    # A pandas.DataFrame that contains the raw data (before all the pre-processing steps) and the actual ground truth variable (target).
    target=TARGET_COLUMN,  # Ground truth variable.
    name="Tweets with sentiment",  # Optional.
)

Model building

Load model

[31]:
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)

Wrap model with Giskard

To prepare for the vulnerability scan, make sure to wrap your model using Giskard’s Model class. You can choose to either wrap the prediction function (preferred option) or the model object. More details here.

[32]:
def prediction_function(df: pd.DataFrame) -> np.ndarray:
    encoded_input = tokenizer(list(df[TEXT_COLUMN]), padding=True, return_tensors="pt")
    output = model(**encoded_input)
    return softmax(output["logits"].detach().numpy(), axis=1)


giskard_model = Model(
    model=prediction_function,  # A prediction function that encapsulates all the data pre-processing steps and that
    model_type="classification",  # Either regression, classification or text_generation.
    name="RoBERTa for sentiment classification",  # Optional
    classification_labels=list(LABEL_MAPPING.values()),  # Their order MUST be identical to the prediction_function's
    feature_names=[TEXT_COLUMN],  # Default: all columns of your dataset
)

Detect vulnerabilities in your model

Scan your model for vulnerabilities with Giskard

Giskard’s scan allows you to detect vulnerabilities in your model automatically. These include performance biases, unrobustness, data leakage, stochasticity, underconfidence, ethical issues, and more. For detailed information about the scan feature, please refer to our scan documentation.

[ ]:
results = scan(giskard_model, giskard_dataset)

If you are running in a notebook, you can display the scan report directly in the notebook using display(...), otherwise you can export the report to an HTML file. Check the API Reference for more details on the export methods available on the ScanReport class.

[34]:
display(results)

# Save it to a file
results.to_html("scan_report.html")

Generate comprehensive test suites automatically for your model

Generate test suites from the scan

The objects produced by the scan can be used as fixtures to generate a test suite that integrate all detected vulnerabilities. Test suites allow you to evaluate and validate your model’s performance, ensuring that it behaves as expected on a set of predefined test cases, and to identify any regressions or issues that might arise during development or updates.

[ ]:
test_suite = results.generate_test_suite("My first test suite")
test_suite.run()

Customize your suite by loading objects from the Giskard catalog

The Giskard open source catalog will enable to load:

  • Tests such as metamorphic, performance, prediction & data drift, statistical tests, etc

  • Slicing functions such as detectors of toxicity, hate, emotion, etc

  • Transformation functions such as generators of typos, paraphrase, style tune, etc

To create custom tests, refer to this page.

For demo purposes, we will load a simple unit test (test_f1) that checks if the test F1 score is above the given threshold. For more examples of tests and functions, refer to the Giskard catalog.

[ ]:
test_suite.add_test(testing.test_f1(model=giskard_model, dataset=giskard_dataset, threshold=0.7)).run()