Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
17 changes: 17 additions & 0 deletions docs/source/api/wrapper.rst
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ Main Class
~torchTextClassifiers.get_explanations
~torchTextClassifiers.save
~torchTextClassifiers.load
~torchTextClassifiers.save_pretrained
~torchTextClassifiers.from_pretrained
~torchTextClassifiers.push_to_hub

Usage Example
-------------
Expand All @@ -51,6 +54,20 @@ Usage Example
predictions = classifier.predict(new_texts)
probabilities = classifier.predict_proba(new_texts)

Hugging Face Hub
----------------

With the ``hub`` extra (``pip install "torchTextClassifiers[hub]"``), a classifier can be saved
and shared using ``save_pretrained``, ``from_pretrained`` and ``push_to_hub``. Files are written
as ``model.safetensors`` plus JSON (no pickle). Currently only models built from a
``ModelConfig`` with an ``NGramTokenizer`` are supported. See :doc:`../tutorials/hub_sharing`.

.. code-block:: python

classifier.save_pretrained("my_model/")
classifier.push_to_hub("my-org/my-model", model_card_kwargs={"license": "mit"})
classifier = torchTextClassifiers.from_pretrained("my-org/my-model")

See Also
--------

Expand Down
15 changes: 15 additions & 0 deletions docs/source/getting_started/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,21 @@ This installs:
- `transformers`: HuggingFace transformers
- `datasets`: HuggingFace datasets

### Hugging Face Hub Sharing

To save, load and share trained models via the Hugging Face Hub (`save_pretrained`, `from_pretrained`, `push_to_hub`):

```bash
uv sync --extra hub
# or: pip install "torchTextClassifiers[hub]"
```

This installs:
- `huggingface_hub`: Hub client and model card utilities
- `safetensors`: Pickle-free weight serialization

See {doc}`../tutorials/hub_sharing` for usage.

### Text Preprocessing

For additional text preprocessing utilities:
Expand Down
69 changes: 69 additions & 0 deletions docs/source/tutorials/hub_sharing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Sharing Models on the Hugging Face Hub

Save trained classifiers to disk, reload them, and publish them on the [Hugging Face Hub](https://huggingface.co/).

## Prerequisites

```bash
pip install "torchTextClassifiers[hub]"
```

The `hub` extra installs `huggingface_hub` and `safetensors`. Without it, the Hub methods raise an `ImportError` explaining how to install it; the rest of the library is unaffected.

:::{note}
Current limitations: only standard models built from a `ModelConfig` are supported (not custom models passed to `from_model`), and only the `NGramTokenizer` can be serialized. WordPiece and HuggingFace tokenizers are not yet supported.
:::

## Save and reload locally

```python
from torchTextClassifiers import torchTextClassifiers

classifier.save_pretrained("my_model/")

reloaded = torchTextClassifiers.from_pretrained("my_model/", device="cpu")
reloaded.predict(["some text"])
```

The directory contains:

| File | Content |
|------|---------|
| `model.safetensors` | Model weights |
| `config.json` | Model config, task type, tokenizer type, library version |
| `tokenizer/` | Serialized tokenizer |
| `labels.json` | Label mapping (when a value encoder is used) |
| `categorical.json` | Categorical variable mappings (if any) |

No pickle is used, so loading a model never executes arbitrary code.

## Push to the Hub

```python
classifier.push_to_hub(
"my-org/my-model",
model_card_kwargs={
"license": "mit",
"language": "fr",
"datasets": ["my-org/my-dataset"],
"metrics": {"accuracy": 0.91},
},
)

classifier = torchTextClassifiers.from_pretrained("my-org/my-model")
```

Authenticate beforehand with `huggingface-cli login` or pass `token=...`.

A model card with the YAML metadata and a usage snippet is generated automatically. Supported `model_card_kwargs` keys: `license`, `language`, `datasets`, `metrics` (`{name: value}`, reported against `datasets[0]`), `dataset_revision`, `training_code_commit`, `model_name`, `tags`. Any other key is listed as a bullet in the card body.

## Version compatibility

The library version is stored in `config.json`. When loading:

- Any version difference emits a warning.
- A **major** version mismatch raises a `RuntimeError`; pass `strict=False` to `from_pretrained` to try loading anyway.

## Choosing the device

`from_pretrained(..., device="auto")` picks CUDA when available, else CPU. Pass `"cpu"` or `"cuda"` to override.
16 changes: 16 additions & 0 deletions docs/source/tutorials/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ mixed_features
explainability
multilabel_classification
custom_model
hub_sharing
```

## Overview
Expand Down Expand Up @@ -132,6 +133,21 @@ Plug any PyTorch model into the torchTextClassifiers wrapper via `from_model`.
**Difficulty:** Advanced | **Time:** 30 minutes
:::


:::{grid-item-card} {fas}`cloud-arrow-up` Sharing on the Hugging Face Hub
:link: hub_sharing
:link-type: doc

Save, load and publish trained classifiers with `save_pretrained`, `from_pretrained` and `push_to_hub`.

**What you'll learn:**
- Pickle-free serialization (safetensors + JSON)
- Generating model cards
- Version compatibility checks

**Difficulty:** Intermediate | **Time:** 10 minutes
:::

::::

## Learning Path
Expand Down
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ dev = [
"pre-commit>=4.3.0",
"ruff>=0.14.3",
"ipywidgets>=8.1.8",
"huggingface_hub>=0.24",
"safetensors",
]
docs = [
"sphinx>=8.1.0",
Expand All @@ -51,6 +53,7 @@ docs = [
[project.optional-dependencies]
explainability = ["unidecode", "nltk", "captum"]
preprocess = ["unidecode", "nltk"]
hub = ["huggingface_hub>=0.24", "safetensors"]
huggingface = [
"tokenizers>=0.22.1",
"transformers>=4.57.1",
Expand Down
119 changes: 119 additions & 0 deletions tests/test_hub.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import json

import numpy as np
import pytest

pytest.importorskip("huggingface_hub")
pytest.importorskip("safetensors")

from torchTextClassifiers import ModelConfig, torchTextClassifiers
from torchTextClassifiers.model.components import AttentionConfig
from torchTextClassifiers.tokenizers import NGramTokenizer
from torchTextClassifiers.value_encoder import DictEncoder, ValueEncoder

TEXTS = [
"this is a positive example",
"this is a negative example",
"another positive case",
"another negative case",
"good example here",
"bad example here",
] * 3


def _tokenizer():
return NGramTokenizer(
min_count=1,
min_n=2,
max_n=4,
num_tokens=50,
len_word_ngrams=1,
training_text=TEXTS,
)


def _encoder(with_categorical):
labels = DictEncoder({"neg": 0, "pos": 1})
cats = {"c0": DictEncoder({"a": 0, "b": 1, "c": 2})} if with_categorical else None
return ValueEncoder(labels, cats)


@pytest.mark.parametrize("with_categorical", [False, True])
def test_round_trip(tmp_path, with_categorical):
import torch

torch.manual_seed(0)
enc = _encoder(with_categorical)
cfg = ModelConfig(
embedding_dim=8,
categorical_vocabulary_sizes=enc.vocabulary_sizes,
categorical_embedding_dims=4 if with_categorical else None,
num_classes=2,
)
clf = torchTextClassifiers(_tokenizer(), cfg, value_encoder=enc)

X = np.array(TEXTS[:6]).reshape(-1, 1)
if with_categorical:
X = np.column_stack([X, np.array(["a", "b", "c", "a", "b", "c"])])
before = clf.predict(X, device="cpu")

clf.save_pretrained(tmp_path)
for name in ["model.safetensors", "config.json", "labels.json", "README.md"]:
assert (tmp_path / name).exists(), name
assert (tmp_path / "tokenizer").is_dir()
assert (tmp_path / "categorical.json").exists() == with_categorical
assert not list(tmp_path.rglob("*.pkl"))
assert json.loads((tmp_path / "config.json").read_text())["task"] == "multiclass"

loaded = torchTextClassifiers.from_pretrained(str(tmp_path), device="cpu")
after = loaded.predict(X, device="cpu")
np.testing.assert_array_equal(before["prediction"], after["prediction"])
np.testing.assert_allclose(before["confidence"], after["confidence"], rtol=1e-5)


def test_model_card_and_kwargs(tmp_path):
cfg = ModelConfig(embedding_dim=8, num_classes=2)
clf = torchTextClassifiers(_tokenizer(), cfg)
card = clf.generate_model_card(
license="mit",
language="fr",
datasets=["org/data"],
metrics={"accuracy": 0.9},
training_code_commit="abc123",
)
text = str(card)
assert "library_name: torchtextclassifiers" in text
assert "pipeline_tag: text-classification" in text
assert "license: mit" in text
assert "abc123" in text
assert "model-index" in text


def test_custom_model_rejected(tmp_path):
cfg = ModelConfig(embedding_dim=8, num_classes=2)
clf = torchTextClassifiers(_tokenizer(), cfg)
clf._custom_model = True
with pytest.raises(NotImplementedError):
clf.save_pretrained(tmp_path)


def test_major_version_mismatch(tmp_path):
clf = torchTextClassifiers(_tokenizer(), ModelConfig(embedding_dim=8, num_classes=2))
clf.save_pretrained(tmp_path)
cfg_path = tmp_path / "config.json"
cfg = json.loads(cfg_path.read_text())
cfg["library_version"] = "99.0.0"
cfg_path.write_text(json.dumps(cfg))
with pytest.raises(RuntimeError):
torchTextClassifiers.from_pretrained(str(tmp_path))
with pytest.warns(UserWarning):
torchTextClassifiers.from_pretrained(str(tmp_path), strict=False, device="cpu")


def test_model_config_attention_round_trip():
cfg = ModelConfig(
embedding_dim=8,
num_classes=2,
attention_config=AttentionConfig(n_layers=1, n_head=2, n_kv_head=2),
)
assert ModelConfig.from_dict(cfg.to_dict()) == cfg
Loading
Loading