diff --git a/docs/source/api/wrapper.rst b/docs/source/api/wrapper.rst index 1290cf7..b7fa1c2 100644 --- a/docs/source/api/wrapper.rst +++ b/docs/source/api/wrapper.rst @@ -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 ------------- @@ -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 -------- diff --git a/docs/source/getting_started/installation.md b/docs/source/getting_started/installation.md index e1e746e..ad7cb34 100644 --- a/docs/source/getting_started/installation.md +++ b/docs/source/getting_started/installation.md @@ -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: diff --git a/docs/source/tutorials/hub_sharing.md b/docs/source/tutorials/hub_sharing.md new file mode 100644 index 0000000..13e79d9 --- /dev/null +++ b/docs/source/tutorials/hub_sharing.md @@ -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. diff --git a/docs/source/tutorials/index.md b/docs/source/tutorials/index.md index 160f53c..bb8581f 100644 --- a/docs/source/tutorials/index.md +++ b/docs/source/tutorials/index.md @@ -11,6 +11,7 @@ mixed_features explainability multilabel_classification custom_model +hub_sharing ``` ## Overview @@ -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 diff --git a/pyproject.toml b/pyproject.toml index 9f9d5ca..25c59fd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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", @@ -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", diff --git a/tests/test_hub.py b/tests/test_hub.py new file mode 100644 index 0000000..8010d63 --- /dev/null +++ b/tests/test_hub.py @@ -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 diff --git a/torchTextClassifiers/hub.py b/torchTextClassifiers/hub.py new file mode 100644 index 0000000..f27f93f --- /dev/null +++ b/torchTextClassifiers/hub.py @@ -0,0 +1,223 @@ +"""Hugging Face Hub integration helpers (optional ``hub`` extra). + +``huggingface_hub`` and ``safetensors`` are optional dependencies +(``pip install torchTextClassifiers[hub]``). When ``huggingface_hub`` is missing, the +base class below is a stub whose Hub methods raise a helpful ``ImportError``, so the +core library keeps working without the extra. +""" + +import json +import warnings +from importlib import metadata +from pathlib import Path +from typing import Any, Dict, Optional + +try: + from huggingface_hub import ModelCard, ModelCardData, ModelHubMixin + + HAS_HUB = True +except ImportError: # pragma: no cover - exercised only without the extra + HAS_HUB = False + +LIBRARY_NAME = "torchtextclassifiers" +REPO_URL = "https://github.com/InseeFrLab/torchTextClassifiers" +DOCS_URL = "https://inseefrlab.github.io/torchTextClassifiers/" + +CONFIG_FILE = "config.json" +WEIGHTS_FILE = "model.safetensors" +LABELS_FILE = "labels.json" +CATEGORICAL_FILE = "categorical.json" +TOKENIZER_DIR = "tokenizer" +FORMAT_VERSION = 1 + +_MISSING_MSG = ( + "Hugging Face Hub support requires the 'hub' extra: pip install 'torchTextClassifiers[hub]'" +) + +if HAS_HUB: + HubBase = ModelHubMixin +else: + + class HubBase: # type: ignore[no-redef] + """Stub used when ``huggingface_hub`` is not installed.""" + + def __init_subclass__(cls, **kwargs): + super().__init_subclass__() + + @classmethod + def from_pretrained(cls, *args, **kwargs): + raise ImportError(_MISSING_MSG) + + def push_to_hub(self, *args, **kwargs): + raise ImportError(_MISSING_MSG) + + def save_pretrained(self, *args, **kwargs): + raise ImportError(_MISSING_MSG) + + +def require_hub() -> None: + if not HAS_HUB: + raise ImportError(_MISSING_MSG) + try: + import safetensors # noqa: F401 + except ImportError as e: # pragma: no cover + raise ImportError(_MISSING_MSG) from e + + +def library_version() -> str: + try: + return metadata.version("torchtextclassifiers") + except metadata.PackageNotFoundError: + from torchTextClassifiers import __version__ + + return __version__ + + +def _major(version: str) -> Optional[int]: + try: + return int(version.split(".")[0]) + except (ValueError, IndexError): + return None + + +def check_version(saved: Optional[str], strict: bool = True) -> None: + """Warn on any version difference; raise on a major mismatch when ``strict``.""" + current = library_version() + if saved is None or saved == current: + return + msg = f"Model was saved with torchTextClassifiers {saved}, but version {current} is installed." + if strict and _major(saved) is not None and _major(saved) != _major(current): + raise RuntimeError(msg + " Pass strict=False to try loading anyway.") + warnings.warn(msg, stacklevel=3) + + +# ---------------------------------------------------------------------- +# Tokenizer (pickle-free) serialization +# ---------------------------------------------------------------------- + + +def save_tokenizer(tokenizer, directory: Path) -> str: + """Save ``tokenizer`` in ``directory`` and return its registered type name.""" + from torchTextClassifiers.tokenizers import NGramTokenizer + + if isinstance(tokenizer, NGramTokenizer): + tokenizer.save_pretrained(str(directory)) + return "NGramTokenizer" + raise NotImplementedError( + f"Hub serialization is not supported yet for tokenizer {type(tokenizer).__name__}. " + "Currently supported: NGramTokenizer." + ) + + +def load_tokenizer(tokenizer_type: str, directory: Path): + from torchTextClassifiers.tokenizers import NGramTokenizer + + if tokenizer_type == "NGramTokenizer": + return NGramTokenizer.load(str(directory / "tokenizer.json")) + raise ValueError(f"Unknown tokenizer type in config.json: {tokenizer_type!r}") + + +# ---------------------------------------------------------------------- +# Model card +# ---------------------------------------------------------------------- + +_CARD_BODY = """ +# {model_name} + +Text classifier trained with [torchTextClassifiers]({repo_url}). + +## Usage + +```bash +pip install "torchTextClassifiers[hub]"=={version} +``` + +```python +from torchTextClassifiers import torchTextClassifiers + +clf = torchTextClassifiers.from_pretrained("{repo_id}") +clf.predict(["some text"]) +``` + +## Model details + +- Task: {task} +- Number of classes: {num_classes} +- Library version: {version} +{extra} +""" + + +def build_model_card( + clf, + *, + license: Optional[str] = None, + language: Optional[Any] = None, + datasets: Optional[list] = None, + metrics: Optional[Dict[str, float]] = None, + model_name: Optional[str] = None, + repo_id: Optional[str] = None, + dataset_revision: Optional[str] = None, + training_code_commit: Optional[str] = None, + tags: Optional[list] = None, + **extra_fields, +): + """Build the model card (YAML header + markdown body) for a classifier.""" + require_hub() + model_name = model_name or (repo_id.split("/")[-1] if repo_id else "torchtextclassifiers-model") + all_tags = ["text-classification", LIBRARY_NAME] + list(tags or []) + + eval_results = None + if metrics and datasets: + from huggingface_hub import EvalResult + + eval_results = [ + EvalResult( + task_type="text-classification", + dataset_type=datasets[0], + dataset_name=datasets[0], + dataset_revision=dataset_revision, + metric_type=name, + metric_value=value, + ) + for name, value in metrics.items() + ] + + card_data = ModelCardData( + library_name=LIBRARY_NAME, + pipeline_tag="text-classification", + tags=all_tags, + license=license, + language=language, + datasets=datasets, + eval_results=eval_results, + model_name=model_name, + ) + + extra_lines = [] + if training_code_commit: + extra_lines.append(f"- Training code commit: `{training_code_commit}`") + if dataset_revision and datasets: + extra_lines.append(f"- Dataset revision: `{dataset_revision}`") + if metrics and not datasets: + extra_lines += [f"- {k}: {v}" for k, v in metrics.items()] + extra_lines += [f"- {k}: {v}" for k, v in extra_fields.items()] + + body = _CARD_BODY.format( + model_name=model_name, + repo_url=REPO_URL, + repo_id=repo_id or "/", + version=library_version(), + task="multilabel" if clf.ragged_multilabel else "multiclass", + num_classes=clf.num_classes, + extra="\n".join(extra_lines), + ) + return ModelCard(f"---\n{card_data.to_yaml()}\n---\n{body}") + + +def write_json(path: Path, data: Any) -> None: + path.write_text(json.dumps(data, indent=2, ensure_ascii=False, sort_keys=True)) + + +def read_json(path: Path) -> Any: + return json.loads(path.read_text()) diff --git a/torchTextClassifiers/tokenizers/ngram.py b/torchTextClassifiers/tokenizers/ngram.py index fae323e..602e08b 100644 --- a/torchTextClassifiers/tokenizers/ngram.py +++ b/torchTextClassifiers/tokenizers/ngram.py @@ -424,6 +424,7 @@ def save_pretrained(self, save_directory: str): "preprocess": self.preprocess, "vocab_size": self.vocab_size, "nwords": self.nwords, + "output_dim": self.output_dim, } with open(f"{save_directory}/tokenizer.json", "w") as f: @@ -457,6 +458,7 @@ def build_from_config(cls, config): num_tokens=config["num_tokens"], len_word_ngrams=config["len_word_ngrams"], preprocess=config["preprocess"], + output_dim=config.get("output_dim"), training_text=None, ) diff --git a/torchTextClassifiers/torchTextClassifiers.py b/torchTextClassifiers/torchTextClassifiers.py index 4da2f09..30b02b0 100644 --- a/torchTextClassifiers/torchTextClassifiers.py +++ b/torchTextClassifiers/torchTextClassifiers.py @@ -23,6 +23,7 @@ ) from torch import nn +from torchTextClassifiers import hub as _hub from torchTextClassifiers.dataset import TextClassificationDataset from torchTextClassifiers.model import TextClassificationModel, TextClassificationModule from torchTextClassifiers.model.components import ( @@ -66,6 +67,10 @@ def to_dict(self) -> Dict[str, Any]: @classmethod def from_dict(cls, data: Dict[str, Any]) -> "ModelConfig": + data = dict(data) + # ``to_dict`` (dataclasses.asdict) flattens nested dataclasses into dicts + if isinstance(data.get("attention_config"), dict): + data["attention_config"] = AttentionConfig(**data["attention_config"]) return cls(**data) @@ -98,7 +103,13 @@ def to_dict(self) -> Dict[str, Any]: return data -class torchTextClassifiers: +class torchTextClassifiers( + _hub.HubBase, + library_name=_hub.LIBRARY_NAME, + repo_url=_hub.REPO_URL, + docs_url=_hub.DOCS_URL, + tags=["text-classification", _hub.LIBRARY_NAME], +): """Generic text classifier framework supporting multiple architectures. Given a tokenizer and model configuration, this class initializes: @@ -400,7 +411,9 @@ def train( X_val_checked: Optional[Dict[str, Any]] = None if X_val is not None and y_val is not None: - X_val_checked, y_val = self._check_XY(X_val, y_val, training_config.raw_categorical_inputs, training_config.raw_labels) + X_val_checked, y_val = self._check_XY( + X_val, y_val, training_config.raw_categorical_inputs, training_config.raw_labels + ) val_sample_weights = self._check_sample_weights( val_sample_weights, X_val_checked["text"].shape[0] ) @@ -579,9 +592,9 @@ def _check_sample_weights( @staticmethod def _check_text_col(X): - assert isinstance( - X, np.ndarray - ), "X must be a numpy array of shape (N,d), with the first column being the text and the rest being the categorical variables." + assert isinstance(X, np.ndarray), ( + "X must be a numpy array of shape (N,d), with the first column being the text and the rest being the categorical variables." + ) try: if X.ndim > 1: @@ -654,9 +667,9 @@ def _check_X(self, X: np.ndarray, raw_categorical_inputs: bool) -> Dict[str, Any def _check_Y(self, Y, raw_labels: bool) -> np.ndarray: if self.ragged_multilabel: - assert isinstance( - Y, list - ), "Y must be a list of lists for ragged multilabel classification." + assert isinstance(Y, list), ( + "Y must be a list of lists for ragged multilabel classification." + ) for row in Y: assert isinstance(row, list), "Each element of Y must be a list of labels." @@ -664,9 +677,9 @@ def _check_Y(self, Y, raw_labels: bool) -> np.ndarray: else: assert isinstance(Y, np.ndarray), "Y must be a numpy array of shape (N,) or (N,1)." - assert ( - len(Y.shape) == 1 or len(Y.shape) == 2 - ), "Y must be a numpy array of shape (N,) or (N, num_labels)." + assert len(Y.shape) == 1 or len(Y.shape) == 2, ( + "Y must be a numpy array of shape (N,) or (N, num_labels)." + ) if raw_labels: if self.value_encoder is None: @@ -699,7 +712,7 @@ def predict( top_k=1, explain_with_label_attention: bool = False, explain_with_captum=False, - device='cpu' + device="cpu", ): """ Args: @@ -1017,6 +1030,132 @@ def load(cls, path: Union[str, Path], device: str = "auto") -> "torchTextClassif logger.info(f"Model loaded successfully from {path}") return instance + # ------------------------------------------------------------------ + # Hugging Face Hub integration (``pip install torchTextClassifiers[hub]``) + # ------------------------------------------------------------------ + + def _save_pretrained(self, save_directory: Path) -> None: + """Pickle-free serialization used by ``save_pretrained`` / ``push_to_hub``. + + Writes ``model.safetensors``, ``config.json``, ``tokenizer/``, ``labels.json`` and + (if any) ``categorical.json``. Only models built from a ``ModelConfig`` are supported. + """ + _hub.require_hub() + from safetensors.torch import save_model + + if getattr(self, "_custom_model", False): + raise NotImplementedError( + "Hub serialization is not supported for custom models built with `from_model`." + ) + + save_directory = Path(save_directory) + save_directory.mkdir(parents=True, exist_ok=True) + + tokenizer_type = _hub.save_tokenizer(self.tokenizer, save_directory / _hub.TOKENIZER_DIR) + + save_model(self.pytorch_model.cpu().eval(), str(save_directory / _hub.WEIGHTS_FILE)) + if hasattr(self, "device"): + self.pytorch_model.to(self.device) + + config = { + "format_version": _hub.FORMAT_VERSION, + "library_name": _hub.LIBRARY_NAME, + "library_version": _hub.library_version(), + "task": "multilabel" if self.ragged_multilabel else "multiclass", + "ragged_multilabel": self.ragged_multilabel, + "num_classes": self.num_classes, + "model_config": self.model_config.to_dict(), + "tokenizer_type": tokenizer_type, + "has_value_encoder": self.value_encoder is not None, + } + _hub.write_json(save_directory / _hub.CONFIG_FILE, config) + + if self.value_encoder is not None: + _hub.write_json(save_directory / _hub.LABELS_FILE, self.value_encoder.labels_to_dict()) + categorical = self.value_encoder.categorical_to_dict() + if categorical is not None: + _hub.write_json(save_directory / _hub.CATEGORICAL_FILE, categorical) + + @classmethod + def _from_pretrained( + cls, + *, + model_id: str, + revision: Optional[str] = None, + cache_dir: Optional[Union[str, Path]] = None, + force_download: bool = False, + local_files_only: bool = False, + token: Optional[Union[str, bool]] = None, + device: str = "auto", + strict: bool = True, + **model_kwargs, + ) -> "torchTextClassifiers": + """Rebuild an instance from a local directory or a Hub repo. + + Args: + device: Device to load the model on ('auto', 'cpu', 'cuda', ...). + strict: Raise if the saved major library version differs from the installed one + (otherwise only warn). + """ + _hub.require_hub() + from huggingface_hub import snapshot_download + from safetensors.torch import load_model + + if Path(model_id).is_dir(): + directory = Path(model_id) + else: + directory = Path( + snapshot_download( + repo_id=model_id, + revision=revision, + cache_dir=cache_dir, + force_download=force_download, + local_files_only=local_files_only, + token=token, + ) + ) + + config = _hub.read_json(directory / _hub.CONFIG_FILE) + _hub.check_version(config.get("library_version"), strict=strict) + + tokenizer = _hub.load_tokenizer(config["tokenizer_type"], directory / _hub.TOKENIZER_DIR) + + value_encoder = None + if config.get("has_value_encoder"): + categorical_path = directory / _hub.CATEGORICAL_FILE + value_encoder = ValueEncoder.from_dicts( + _hub.read_json(directory / _hub.LABELS_FILE), + _hub.read_json(categorical_path) if categorical_path.exists() else None, + ) + + instance = cls( + tokenizer=tokenizer, + model_config=ModelConfig.from_dict(config["model_config"]), + ragged_multilabel=config["ragged_multilabel"], + value_encoder=value_encoder, + ) + + resolved_device = ( + torch.device("cuda" if torch.cuda.is_available() else "cpu") + if device == "auto" + else torch.device(device) + ) + load_model(instance.pytorch_model, str(directory / _hub.WEIGHTS_FILE)) + instance.pytorch_model.to(resolved_device).eval() + instance.device = resolved_device + return instance + + def generate_model_card(self, *args, **kwargs): + """Generate the model card. + + Pass extra fields through ``push_to_hub(..., model_card_kwargs={...})``. Supported keys: + ``license``, ``language``, ``datasets`` (list of dataset ids), ``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. + """ + return _hub.build_model_card(self, **kwargs) + def __repr__(self): model_type = ( self.lightning_module.__repr__() diff --git a/torchTextClassifiers/value_encoder/value_encoder.py b/torchTextClassifiers/value_encoder/value_encoder.py index 27cd903..2dcd3fb 100644 --- a/torchTextClassifiers/value_encoder/value_encoder.py +++ b/torchTextClassifiers/value_encoder/value_encoder.py @@ -290,3 +290,58 @@ def _decode_col(enc, col: np.ndarray) -> np.ndarray: def __call__(self, array: np.ndarray) -> np.ndarray: return self.transform(array) + + # ------------------------------------------------------------------ + # JSON (de)serialization (pickle-free, used by the Hugging Face Hub integration) + # ------------------------------------------------------------------ + + @staticmethod + def _encoder_to_mapping(enc) -> dict[str, int]: + """Return a JSON-friendly ``{str(value): index}`` mapping for any supported encoder.""" + if isinstance(enc, DictEncoder): + return {str(k): int(v) for k, v in enc.mapping.items()} + if hasattr(enc, "classes_"): + return {str(c): i for i, c in enumerate(enc.classes_)} + raise TypeError(f"Unsupported encoder type: {type(enc)}") + + def labels_to_dict(self) -> dict: + """Serialize the label encoder(s) (index <-> label) to a JSON-friendly dict. + + Values are stored as strings (``transform`` already casts inputs to ``str``). + Encoders are restored as :class:`DictEncoder` objects. + """ + multi_level = isinstance(self.label_encoder, list) + encoders = self.label_encoder if multi_level else [self.label_encoder] + levels = [] + for enc in encoders: + label2id = self._encoder_to_mapping(enc) + levels.append( + { + "label2id": label2id, + "id2label": {str(i): lab for lab, i in label2id.items()}, + } + ) + return {"multi_level": multi_level, "levels": levels} + + def categorical_to_dict(self) -> Optional[dict]: + """Serialize categorical encoders to a JSON-friendly dict (``None`` if there are none).""" + if self.categorical_encoders is None: + return None + return { + "encoders": { + name: self._encoder_to_mapping(enc) + for name, enc in self.categorical_encoders.items() + } + } + + @classmethod + def from_dicts(cls, labels: dict, categorical: Optional[dict] = None) -> "ValueEncoder": + """Rebuild a ValueEncoder from :meth:`labels_to_dict` / :meth:`categorical_to_dict`.""" + label_encoders = [DictEncoder(lvl["label2id"]) for lvl in labels["levels"]] + label_encoder = label_encoders if labels.get("multi_level") else label_encoders[0] + categorical_encoders = None + if categorical is not None: + categorical_encoders = { + name: DictEncoder(mapping) for name, mapping in categorical["encoders"].items() + } + return cls(label_encoder, categorical_encoders) diff --git a/uv.lock b/uv.lock index aac3a58..b243aa0 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.11" resolution-markers = [ "python_full_version >= '3.12'", @@ -250,7 +250,7 @@ name = "cffi" version = "2.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pycparser", marker = "implementation_name != 'PyPy'" }, + { name = "pycparser" }, ] sdist = { url = "https://files.pythonhosted.org/packages/eb/56/b1ba7935a17738ae8453301356628e8147c79dbb825bcbc73dc7401f9846/cffi-2.0.0.tar.gz", hash = "sha256:44d1b5909021139fe36001ae048dbdde8214afa20200eda0f64c068cac5d5529", size = 523588, upload-time = "2025-09-08T23:24:04.541Z" } wheels = [ @@ -3252,6 +3252,10 @@ explainability = [ { name = "nltk" }, { name = "unidecode" }, ] +hub = [ + { name = "huggingface-hub" }, + { name = "safetensors" }, +] huggingface = [ { name = "datasets" }, { name = "tokenizers" }, @@ -3265,6 +3269,7 @@ preprocess = [ [package.dev-dependencies] dev = [ { name = "captum" }, + { name = "huggingface-hub" }, { name = "ipywidgets" }, { name = "nltk" }, { name = "pandas" }, @@ -3272,6 +3277,7 @@ dev = [ { name = "pyarrow" }, { name = "pytest" }, { name = "ruff" }, + { name = "safetensors" }, { name = "scikit-learn" }, { name = "unidecode" }, ] @@ -3293,20 +3299,23 @@ docs = [ requires-dist = [ { name = "captum", marker = "extra == 'explainability'" }, { name = "datasets", marker = "extra == 'huggingface'", specifier = ">=4.3.0" }, + { name = "huggingface-hub", marker = "extra == 'hub'", specifier = ">=0.24" }, { name = "nltk", marker = "extra == 'explainability'" }, { name = "nltk", marker = "extra == 'preprocess'" }, { name = "numpy", specifier = ">=1.26.4" }, { name = "pytorch-lightning", specifier = ">=2.4.0" }, + { name = "safetensors", marker = "extra == 'hub'" }, { name = "tokenizers", marker = "extra == 'huggingface'", specifier = ">=0.22.1" }, { name = "transformers", marker = "extra == 'huggingface'", specifier = ">=4.57.1" }, { name = "unidecode", marker = "extra == 'explainability'" }, { name = "unidecode", marker = "extra == 'preprocess'" }, ] -provides-extras = ["explainability", "preprocess", "huggingface"] +provides-extras = ["explainability", "preprocess", "hub", "huggingface"] [package.metadata.requires-dev] dev = [ { name = "captum" }, + { name = "huggingface-hub", specifier = ">=0.24" }, { name = "ipywidgets", specifier = ">=8.1.8" }, { name = "nltk" }, { name = "pandas" }, @@ -3314,6 +3323,7 @@ dev = [ { name = "pyarrow" }, { name = "pytest", specifier = ">=9.0.1,<10" }, { name = "ruff", specifier = ">=0.14.3" }, + { name = "safetensors" }, { name = "scikit-learn" }, { name = "unidecode" }, ]