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

Integrate AutoModelForSequenceClassification through PytorchModel #339

Conversation

abarbosa94
Copy link
Collaborator

Description

  • This PR adds an initial implementation for the HuggingFace SequenceClassification model with some initial functionality. I also organized imports using isort and made a few adjustments to increase flake8 compliance

This should be taken as an initial step toward: #238, #103, and #217

Implemented changes

  • Insert a description of the changes implemented in the pull request.
    • Modify the PyTorchModel prediction method to accept the HuggingFace model
    • Adds new tests that prove new feature
    • Add flake8 parametrization to tox
    • Modify some import ordering according to isort

Minimum acceptance criteria

  • Specify what is necessary for the PR to be merged with the main branch.
  • @mentions of the person that is apt to review these changes, e.g., @annahedstroem

@abarbosa94 abarbosa94 self-assigned this Mar 4, 2024
@abarbosa94 abarbosa94 requested a review from aaarrti March 4, 2024 15:16
@abarbosa94 abarbosa94 added the enhancement New feature or request label Mar 4, 2024
@abarbosa94 abarbosa94 changed the title Adds Initial HuggingFace integration to PytorchModel Integrate AutoModelForSequenceClassification through PytorchModel Mar 4, 2024
raise ValueError(
"When using HuggingFace pretrained models, please use Tokenizers output for `x`"
)
pred = self.model(**x, **model_predict_kwargs).logits
Copy link
Member

Choose a reason for hiding this comment

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

Should we also enable softmax here (post accessing the logits)? so that we convert the pred to softmax, if softmax=True? (we can add it as a class attribute above).

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I implemented this way, please see if you agree: 9a67c4c

pyproject.toml Outdated
@@ -36,7 +36,9 @@ dependencies = [
"scipy>=1.7.3",
"tqdm>=4.62.3",
"matplotlib>=3.3.4",
"typing_extensions; python_version <= '3.8'"
"typing_extensions; python_version <= '3.8'",
"transformers<=4.30.2; python_version == '3.7'",
Copy link
Member

Choose a reason for hiding this comment

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

I wonder if this should be a part of the base dependencies. I think it is better fitted to add it under 'torch' (see line 78/80 and below)?

Copy link
Collaborator

Choose a reason for hiding this comment

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

I'd say those should go into

[project.optional_dependecies]
transformers = [...]



@pytest.fixture(scope="session", autouse=True)
def mock_hf_text():
Copy link
Collaborator

Choose a reason for hiding this comment

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

contrary to the name, this is not a mock 🤷

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Haha, good catch! Just renamed it

Copy link
Collaborator Author

Choose a reason for hiding this comment

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


CIFAR_IMAGE_SIZE = 32
MNIST_IMAGE_SIZE = 28
BATCH_SIZE = 124
MINI_BATCH_SIZE = 8
RANDOM_SEED = 42

set_seed(42)
Copy link
Collaborator

Choose a reason for hiding this comment

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

I can't believe we have forgotten to set PRNG seed 🤦
Thanks for noticing!

Mb, to ensure each test runs with the same PRNG state, we could do

@pytest.fixture(scope='function', autouse=True)
def reset_prngs():
    # module names might be a bit wrong ;)
    torch.seed()
    np.seed()
    tf.keras.set_seed()
    random.seed()

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

set_seed from huggingface ensure all of these (and some others as well), but using autouse is a clever idea :) just did it!

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

return model


@pytest.fixture(scope="session", autouse=True)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Please remove autouse,
autouse=True will force the model to be loaded into memory every time any tests is executed, even if the test does not use it.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Sorry, just did it

elif isinstance(self.model, nn.Module):
pred_model = self.get_softmax_arg_model()
pred = pred_model(torch.Tensor(x).to(self.device), **model_predict_kwargs)
return pred
Copy link
Collaborator

Choose a reason for hiding this comment

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

Let's try not to return None, either tensor, or raise exception

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Done: 179da1e

pyproject.toml Outdated
@@ -36,7 +36,9 @@ dependencies = [
"scipy>=1.7.3",
"tqdm>=4.62.3",
"matplotlib>=3.3.4",
"typing_extensions; python_version <= '3.8'"
"typing_extensions; python_version <= '3.8'",
"transformers<=4.30.2; python_version == '3.7'",
Copy link
Collaborator

Choose a reason for hiding this comment

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

I'd say those should go into

[project.optional_dependecies]
transformers = [...]

raise ValueError(
"When using HuggingFace pretrained models, please use Tokenizers output for `x`"
)
pred = self.model(**x, **model_predict_kwargs).logits
Copy link
Collaborator

Choose a reason for hiding this comment

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

just return self.model(**x, **model_predict_kwargs).logits

Copy link
Collaborator Author

@abarbosa94 abarbosa94 Mar 18, 2024

Choose a reason for hiding this comment

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

I did slightly different (in 179da1e) to handle and raise the softmax param properly. Could you see if you agree? Thanks

Copy link
Member

Choose a reason for hiding this comment

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

I think that looks great :D @abarbosa94

Copy link
Collaborator

Choose a reason for hiding this comment

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

you're right, it looks a bit different now. Can we also remove pred = None at the top?

tox.ini Show resolved Hide resolved
tox.ini Show resolved Hide resolved
pyproject.toml Outdated
@@ -52,6 +52,7 @@ dynamic = ["version"]
#
[project.optional-dependencies]
tests = [
"cachetools>=5.3.3",
Copy link
Collaborator

Choose a reason for hiding this comment

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

Why do we need cachetools for tests?
If it is used by library it must be in [project.dependecies] otherwise users can face issues after installation

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

You're right, removing it

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Done: 179da1e

tests/functions/test_pytorch_model.py Show resolved Hide resolved
@codecov-commenter
Copy link

codecov-commenter commented Mar 15, 2024

Codecov Report

Attention: Patch coverage is 95.83333% with 1 lines in your changes are missing coverage. Please review.

Project coverage is 91.20%. Comparing base (8d88cd7) to head (4afbfec).

Files Patch % Lines
quantus/helpers/model/pytorch_model.py 95.83% 1 Missing ⚠️

❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #339   +/-   ##
=======================================
  Coverage   91.19%   91.20%           
=======================================
  Files          66       66           
  Lines        3906     3921   +15     
=======================================
+ Hits         3562     3576   +14     
- Misses        344      345    +1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@abarbosa94 abarbosa94 force-pushed the u/andrebarbosa/integration-v0-huggingface branch from aba53a7 to 179da1e Compare March 18, 2024 13:12
@annahedstroem
Copy link
Member

based on the tesing, it looks like we need to add transformers also to the tests and not only full: https://github.com/understandable-machine-intelligence-lab/Quantus/actions/runs/8328433263/job/22788366589?pr=339

@annahedstroem annahedstroem merged commit b0b6cda into understandable-machine-intelligence-lab:main Mar 19, 2024
6 of 7 checks passed
Copy link
Collaborator

@aaarrti aaarrti left a comment

Choose a reason for hiding this comment

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

Please make sure Quantus is usable without transformers installation

],
)
def test_huggingface_classifier_predict(hf_model, data, softmax, model_kwargs, expected):
model = PyTorchModel(model=hf_model, softmax=softmax, model_predict_kwargs=model_kwargs)
Copy link
Collaborator

Choose a reason for hiding this comment

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

I though softmax must be a bool, or?

return model


@pytest.fixture(scope="session", autouse=False)
Copy link
Collaborator

Choose a reason for hiding this comment

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

autouse=False is the default

import torch
from torch import nn
from functools import lru_cache
from transformers import PreTrainedModel
Copy link
Collaborator

Choose a reason for hiding this comment

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

This will cause ModuleNotFoundError when user tries to import Quantus without transformers installed.

@@ -104,8 +81,39 @@ zennit = [
"quantus[torch]",
"zennit>=0.5.1"
]
transformers = [
"quantus[torch, tensorflow]",
Copy link
Collaborator

Choose a reason for hiding this comment

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

quantus[torch] should be enough

@@ -85,7 +60,9 @@ torch = [
"torchvision<=0.12.0; python_version == '3.7'",
"torchvision>=0.15.1; sys_platform != 'linux' and python_version > '3.7'",
"torchvision>=0.14.0, <0.15.1; sys_platform == 'linux' and python_version > '3.7' and python_version <= '3.10'",
"torchvision>=0.15.1; sys_platform == 'linux' and python_version >= '3.11'"
"torchvision>=0.15.1; sys_platform == 'linux' and python_version >= '3.11'",
"transformers<=4.30.2; python_version == '3.7'",
Copy link
Collaborator

Choose a reason for hiding this comment

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

please remove transformers from torch = [...] section

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants