From a4a9f9b654d7ada6a18ed3476f08e62067438222 Mon Sep 17 00:00:00 2001 From: "claude[bot]" <41898282+claude[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:46:49 +0000 Subject: [PATCH 1/4] feat: add Hugging Face Hub integration (save_pretrained / from_pretrained / push_to_hub) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pickle-free serialization via safetensors + JSON for standard models using NGramTokenizer. Adds optional 'hub' extra, model card generation, version check. Refs #109 Co-authored-by: Cédric Couralet <243027+micedre@users.noreply.github.com> Co-Authored-By: Claude Sonnet 5.5 --- pyproject.toml | 3 + tests/test_hub.py | 119 ++++++++++ torchTextClassifiers/hub.py | 223 ++++++++++++++++++ torchTextClassifiers/tokenizers/ngram.py | 2 + torchTextClassifiers/torchTextClassifiers.py | 163 ++++++++++++- .../value_encoder/value_encoder.py | 55 +++++ 6 files changed, 553 insertions(+), 12 deletions(-) create mode 100644 tests/test_hub.py create mode 100644 torchTextClassifiers/hub.py 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 7ca946b..fcbb58b 100644 --- a/torchTextClassifiers/value_encoder/value_encoder.py +++ b/torchTextClassifiers/value_encoder/value_encoder.py @@ -243,3 +243,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) From ea97856c9945e8bcea4baf6dd22d4f693f731ff2 Mon Sep 17 00:00:00 2001 From: "claude[bot]" <41898282+claude[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:58:07 +0000 Subject: [PATCH 2/4] chore: update uv.lock for hub dependencies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cédric Couralet <243027+micedre@users.noreply.github.com> Co-Authored-By: Claude Sonnet 5.5 --- uv.lock | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) 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" }, ] From 3ff3e825080a478b66305c45882e043caf3ef69f Mon Sep 17 00:00:00 2001 From: "claude[bot]" <41898282+claude[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:15:01 +0000 Subject: [PATCH 3/4] docs: document Hugging Face Hub integration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cédric Couralet <243027+micedre@users.noreply.github.com> Co-Authored-By: Claude Sonnet 5.5 --- docs/source/api/wrapper.rst | 135 +++-- docs/source/getting_started/installation.md | 325 +++++------ docs/source/tutorials/hub_sharing.md | 69 +++ docs/source/tutorials/index.md | 588 ++++++++++---------- 4 files changed, 617 insertions(+), 500 deletions(-) create mode 100644 docs/source/tutorials/hub_sharing.md diff --git a/docs/source/api/wrapper.rst b/docs/source/api/wrapper.rst index 1290cf7..23ebd94 100644 --- a/docs/source/api/wrapper.rst +++ b/docs/source/api/wrapper.rst @@ -1,59 +1,76 @@ -torchTextClassifiers Wrapper -============================= - -The main wrapper class for text classification tasks. - -.. currentmodule:: torchTextClassifiers.torchTextClassifiers - -Main Class ----------- - -.. autoclass:: torchTextClassifiers - :members: - :undoc-members: - :show-inheritance: - :inherited-members: - :special-members: __init__ - - .. rubric:: Methods - - .. autosummary:: - :nosignatures: - - ~torchTextClassifiers.train - ~torchTextClassifiers.predict - ~torchTextClassifiers.predict_proba - ~torchTextClassifiers.get_explanations - ~torchTextClassifiers.save - ~torchTextClassifiers.load - -Usage Example -------------- - -.. code-block:: python - - from torchTextClassifiers import torchTextClassifiers, ModelConfig, TrainingConfig - from torchTextClassifiers.tokenizers import WordPieceTokenizer - - # Create tokenizer - tokenizer = WordPieceTokenizer() - tokenizer.train(texts, vocab_size=1000) - - # Configure model - model_config = ModelConfig(embedding_dim=64, num_classes=2) - training_config = TrainingConfig(num_epochs=10, batch_size=16, lr=1e-3) - - # Create and train classifier - classifier = torchTextClassifiers(tokenizer=tokenizer, model_config=model_config) - classifier.train(X_text=texts, y=labels, training_config=training_config) - - # Make predictions - predictions = classifier.predict(new_texts) - probabilities = classifier.predict_proba(new_texts) - -See Also --------- - -* :doc:`configs` - Configuration classes -* :doc:`tokenizers` - Tokenizer options -* :doc:`model` - Underlying PyTorch models +torchTextClassifiers Wrapper +============================= + +The main wrapper class for text classification tasks. + +.. currentmodule:: torchTextClassifiers.torchTextClassifiers + +Main Class +---------- + +.. autoclass:: torchTextClassifiers + :members: + :undoc-members: + :show-inheritance: + :inherited-members: + :special-members: __init__ + + .. rubric:: Methods + + .. autosummary:: + :nosignatures: + + ~torchTextClassifiers.train + ~torchTextClassifiers.predict + ~torchTextClassifiers.predict_proba + ~torchTextClassifiers.get_explanations + ~torchTextClassifiers.save + ~torchTextClassifiers.load + ~torchTextClassifiers.save_pretrained + ~torchTextClassifiers.from_pretrained + ~torchTextClassifiers.push_to_hub + +Usage Example +------------- + +.. code-block:: python + + from torchTextClassifiers import torchTextClassifiers, ModelConfig, TrainingConfig + from torchTextClassifiers.tokenizers import WordPieceTokenizer + + # Create tokenizer + tokenizer = WordPieceTokenizer() + tokenizer.train(texts, vocab_size=1000) + + # Configure model + model_config = ModelConfig(embedding_dim=64, num_classes=2) + training_config = TrainingConfig(num_epochs=10, batch_size=16, lr=1e-3) + + # Create and train classifier + classifier = torchTextClassifiers(tokenizer=tokenizer, model_config=model_config) + classifier.train(X_text=texts, y=labels, training_config=training_config) + + # Make predictions + 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 +-------- + +* :doc:`configs` - Configuration classes +* :doc:`tokenizers` - Tokenizer options +* :doc:`model` - Underlying PyTorch models diff --git a/docs/source/getting_started/installation.md b/docs/source/getting_started/installation.md index e1e746e..1c95355 100644 --- a/docs/source/getting_started/installation.md +++ b/docs/source/getting_started/installation.md @@ -1,155 +1,170 @@ -# Installation - -## Requirements - -torchTextClassifiers requires: - -- **Python**: 3.11 or higher -- **PyTorch**: Will be installed automatically as a dependency via pytorch-lightning -- **Operating System**: Linux, macOS, or Windows - -## Installation from Source - -Currently, torchTextClassifiers is available only from source. Clone the repository and install using [uv](https://github.com/astral-sh/uv), a fast Python package installer and resolver. - -```bash -# Clone the repository -git clone https://github.com/InseeFrLab/torchTextClassifiers.git -cd torchTextClassifiers - -# Install with uv -uv sync -``` - -## Optional Dependencies - -torchTextClassifiers comes with optional dependency groups for additional features: - -### Explainability Support - -For model interpretation and explainability features: - -```bash -uv sync --extra explainability -``` - -This installs: -- `captum`: For attribution analysis -- `nltk`: For text preprocessing -- `unidecode`: For text normalization - -### HuggingFace Integration - -To use HuggingFace tokenizers: - -```bash -uv sync --extra huggingface -``` - -This installs: -- `tokenizers`: Fast tokenizers -- `transformers`: HuggingFace transformers -- `datasets`: HuggingFace datasets - -### Text Preprocessing - -For additional text preprocessing utilities: - -```bash -uv sync --extra preprocess -``` - -This installs: -- `nltk`: Natural language toolkit -- `unidecode`: Text normalization - -### All Optional Dependencies - -Install all extras at once: - -```bash -uv sync --all-extras -``` - -### Development Dependencies - -If you want to contribute to the project: - -```bash -uv sync --group dev -``` - -## Verification - -Verify your installation by running: - -```python -import torchTextClassifiers -print(torchTextClassifiers.__version__) # Should print: 0.0.0-dev -``` - -Or try a simple import: - -```python -from torchTextClassifiers import torchTextClassifiers, ModelConfig, TrainingConfig -from torchTextClassifiers.tokenizers import WordPieceTokenizer - -print("Installation successful!") -``` - -## GPU Support - -torchTextClassifiers uses PyTorch Lightning, which automatically detects and uses GPUs if available. - -To use GPUs, make sure you have: -1. CUDA-compatible GPU -2. CUDA toolkit installed -3. PyTorch installed with CUDA support - -Check GPU availability: - -```python -import torch -print(f"GPU available: {torch.cuda.is_available()}") -print(f"GPU count: {torch.cuda.device_count()}") -``` - -## Troubleshooting - -### Import Errors - -If you encounter import errors, make sure you've installed the package: - -```bash -# Reinstall -uv sync -``` - -### Dependency Conflicts - -If you have dependency conflicts, try creating a fresh virtual environment: - -```bash -# Create new virtual environment with uv -uv venv -source .venv/bin/activate # On Windows: .venv\Scripts\activate -uv sync -``` - -### PyTorch Installation Issues - -If PyTorch installation fails, uv will handle it automatically through pytorch-lightning. If you need a specific PyTorch version, you can specify it in your environment before running: - -```bash -# For CPU-only PyTorch -export PYTORCH_INDEX_URL="https://download.pytorch.org/whl/cpu" -uv sync - -# For GPU (CUDA 11.8) -export PYTORCH_INDEX_URL="https://download.pytorch.org/whl/cu118" -uv sync -``` - -## Next Steps - -Now that you have torchTextClassifiers installed, head over to the {doc}`quickstart` to build your first classifier! +# Installation + +## Requirements + +torchTextClassifiers requires: + +- **Python**: 3.11 or higher +- **PyTorch**: Will be installed automatically as a dependency via pytorch-lightning +- **Operating System**: Linux, macOS, or Windows + +## Installation from Source + +Currently, torchTextClassifiers is available only from source. Clone the repository and install using [uv](https://github.com/astral-sh/uv), a fast Python package installer and resolver. + +```bash +# Clone the repository +git clone https://github.com/InseeFrLab/torchTextClassifiers.git +cd torchTextClassifiers + +# Install with uv +uv sync +``` + +## Optional Dependencies + +torchTextClassifiers comes with optional dependency groups for additional features: + +### Explainability Support + +For model interpretation and explainability features: + +```bash +uv sync --extra explainability +``` + +This installs: +- `captum`: For attribution analysis +- `nltk`: For text preprocessing +- `unidecode`: For text normalization + +### HuggingFace Integration + +To use HuggingFace tokenizers: + +```bash +uv sync --extra huggingface +``` + +This installs: +- `tokenizers`: Fast tokenizers +- `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: + +```bash +uv sync --extra preprocess +``` + +This installs: +- `nltk`: Natural language toolkit +- `unidecode`: Text normalization + +### All Optional Dependencies + +Install all extras at once: + +```bash +uv sync --all-extras +``` + +### Development Dependencies + +If you want to contribute to the project: + +```bash +uv sync --group dev +``` + +## Verification + +Verify your installation by running: + +```python +import torchTextClassifiers +print(torchTextClassifiers.__version__) # Should print: 0.0.0-dev +``` + +Or try a simple import: + +```python +from torchTextClassifiers import torchTextClassifiers, ModelConfig, TrainingConfig +from torchTextClassifiers.tokenizers import WordPieceTokenizer + +print("Installation successful!") +``` + +## GPU Support + +torchTextClassifiers uses PyTorch Lightning, which automatically detects and uses GPUs if available. + +To use GPUs, make sure you have: +1. CUDA-compatible GPU +2. CUDA toolkit installed +3. PyTorch installed with CUDA support + +Check GPU availability: + +```python +import torch +print(f"GPU available: {torch.cuda.is_available()}") +print(f"GPU count: {torch.cuda.device_count()}") +``` + +## Troubleshooting + +### Import Errors + +If you encounter import errors, make sure you've installed the package: + +```bash +# Reinstall +uv sync +``` + +### Dependency Conflicts + +If you have dependency conflicts, try creating a fresh virtual environment: + +```bash +# Create new virtual environment with uv +uv venv +source .venv/bin/activate # On Windows: .venv\Scripts\activate +uv sync +``` + +### PyTorch Installation Issues + +If PyTorch installation fails, uv will handle it automatically through pytorch-lightning. If you need a specific PyTorch version, you can specify it in your environment before running: + +```bash +# For CPU-only PyTorch +export PYTORCH_INDEX_URL="https://download.pytorch.org/whl/cpu" +uv sync + +# For GPU (CUDA 11.8) +export PYTORCH_INDEX_URL="https://download.pytorch.org/whl/cu118" +uv sync +``` + +## Next Steps + +Now that you have torchTextClassifiers installed, head over to the {doc}`quickstart` to build your first classifier! 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..0a0de7e 100644 --- a/docs/source/tutorials/index.md +++ b/docs/source/tutorials/index.md @@ -1,286 +1,302 @@ -# Tutorials - -Step-by-step guides to learn torchTextClassifiers through practical examples. - -```{toctree} -:maxdepth: 2 - -basic_classification -multiclass_classification -mixed_features -explainability -multilabel_classification -custom_model -``` - -## Overview - -These tutorials guide you through common text classification tasks, from basic binary classification to advanced multiclass scenarios. - -## Available Tutorials - -### Getting Started - -::::{grid} 1 -:gutter: 3 - -:::{grid-item-card} {fas}`star` Binary Classification -:link: basic_classification -:link-type: doc - -**Recommended first tutorial** - -Build a sentiment classifier for product reviews. Learn the complete workflow from data preparation to evaluation. - -**What you'll learn:** -- Creating and training tokenizers -- Configuring models -- Training with validation data -- Making predictions -- Evaluating performance - -**Difficulty:** Beginner | **Time:** 15 minutes -::: - -:::: - -### Intermediate Tutorials - -::::{grid} 1 1 2 2 -:gutter: 3 - -:::{grid-item-card} {fas}`layer-group` Multiclass Classification -:link: multiclass_classification -:link-type: doc - -Classify text into 3+ categories with proper handling of class imbalance and evaluation metrics. - -**What you'll learn:** -- Multiclass model configuration -- Class distribution analysis -- Reproducibility with seeds -- Confusion matrices -- Advanced evaluation metrics - -**Difficulty:** Intermediate | **Time:** 20 minutes -::: - -:::{grid-item-card} {fas}`puzzle-piece` Mixed Features -:link: mixed_features -:link-type: doc - -Combine text with categorical variables for improved classification performance. - -**What you'll learn:** -- Adding categorical features alongside text -- Configuring categorical embeddings -- Comparing performance improvements -- Feature combination strategies - -**Difficulty:** Intermediate | **Time:** 25 minutes -::: - -:::: - -### Advanced Tutorials - -::::{grid} 1 1 2 2 -:gutter: 3 - -:::{grid-item-card} {fas}`lightbulb` Explainability -:link: explainability -:link-type: doc - -Understand which words and characters drive your model's predictions. - -**What you'll learn:** -- Generating attribution scores with Captum -- Word-level and character-level visualizations -- Identifying influential tokens -- Interactive explainability mode - -**Difficulty:** Advanced | **Time:** 30 minutes -::: - -:::{grid-item-card} {fas}`tags` Multilabel Classification -:link: multilabel_classification -:link-type: doc - -Assign multiple labels to each text sample for complex classification scenarios. - -**What you'll learn:** -- Ragged lists vs. one-hot encoding -- Configuring BCEWithLogitsLoss -- Multilabel evaluation metrics -- Handling variable labels per sample - -**Difficulty:** Advanced | **Time:** 30 minutes -::: - -:::{grid-item-card} {fas}`puzzle-piece` Custom Architectures -:link: custom_model -:link-type: doc - -Plug any PyTorch model into the torchTextClassifiers wrapper via `from_model`. - -**What you'll learn:** -- When to go beyond `TextClassificationModel` -- The required `forward` / `num_classes` / `categorical_variable_net` interface -- Using `contrib` classes as reference implementations -- Multi-task classification with `MultiLevelTextClassificationModel` - -**Difficulty:** Advanced | **Time:** 30 minutes -::: - -:::: - -## Learning Path - -We recommend following this learning path: - -```{mermaid} -graph LR - A[Quick Start] --> B[Binary Classification] - B --> C[Multiclass Classification] - C --> D[Mixed Features] - C --> F[Multilabel Classification] - D --> E[Explainability] - F --> E - D --> G[Custom Architectures] - F --> G - - style A fill:#e3f2fd - style B fill:#bbdefb - style C fill:#90caf9 - style D fill:#64b5f6 - style E fill:#1976d2 - style F fill:#42a5f5 - style G fill:#0d47a1 -``` - -1. **Start with**: {doc}`../getting_started/quickstart` - Get familiar with the basics -2. **Then**: {doc}`basic_classification` - Understand the complete workflow -3. **Next**: {doc}`multiclass_classification` - Handle multiple classes -4. **Branch out**: {doc}`mixed_features` for categorical features OR {doc}`multilabel_classification` for multiple labels -5. **Master**: {doc}`explainability` - Understand your model's predictions - -## Tutorial Format - -Each tutorial follows a consistent structure: - -**Learning Objectives** -: What you'll be able to do after completing the tutorial - -**Prerequisites** -: What you need to know before starting - -**Complete Code** -: Full working example you can copy and run - -**Step-by-Step Walkthrough** -: Detailed explanation of each step - -**Customization** -: How to adapt the code to your needs - -**Common Issues** -: Troubleshooting tips and solutions - -**Next Steps** -: Where to go after finishing - -## Tips for Learning - -### Run the Code - -Don't just read - run the examples! Modify them to see what happens: - -```python -# Try different values -model_config = ModelConfig( - embedding_dim=128, # Was 64 - what changes? - num_classes=2 -) -``` - -### Start Simple - -Begin with the Quick Start, then move to Binary Classification. Don't skip ahead! - -### Use Your Own Data - -Once you understand the examples, try them with your own text data: - -```python -# Your data -my_texts = ["your", "text", "samples"] -my_labels = [0, 1, 0] - -# Same workflow -classifier.train(my_texts, my_labels, training_config) -``` - -### Experiment - -- Try different tokenizers (WordPiece vs NGram) -- Adjust hyperparameters (learning rate, embedding dim) -- Compare model sizes -- Test different batch sizes - -### Read the Errors - -Error messages are helpful! They often tell you exactly what's wrong: - -```python -# Error: num_classes=2 but got label 3 -# Solution: Check your labels - should be 0, 1 (not 1, 2, 3) -``` - -## Getting Help - -Stuck on a tutorial? Here's how to get help: - -1. **Check Common Issues**: Each tutorial has a troubleshooting section -2. **Read the API docs**: {doc}`../api/index` for detailed parameter descriptions -3. **Review architecture**: {doc}`../architecture/overview` for how components work -4. **Ask questions**: [GitHub Discussions](https://github.com/InseeFrLab/torchTextClassifiers/discussions) -5. **Report bugs**: [GitHub Issues](https://github.com/InseeFrLab/torchTextClassifiers/issues) - -## Additional Resources - -### Example Scripts - -All tutorials are based on runnable examples in the repository: - -- [examples/basic_classification.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/basic_classification.py) -- [examples/multiclass_classification.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/multiclass_classification.py) -- [examples/using_additional_features.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/using_additional_features.py) -- [examples/advanced_training.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/advanced_training.py) -- [examples/simple_explainability_example.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/simple_explainability_example.py) - -### Jupyter Notebooks - -Interactive notebooks for hands-on learning: - -- [Basic example notebook](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/notebooks/example.ipynb) -- [Multilabel classification notebook](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/notebooks/multilabel_classification.ipynb) - -## Contributing - -Want to contribute a tutorial? We welcome: - -- New use cases -- Alternative approaches -- Real-world examples -- Performance tips - -See our [contributing guidelines](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/CONTRIBUTING.md) to get started! - -## What's Next? - -Ready to start? Choose your path: - -- **New to text classification?** Start with {doc}`../getting_started/quickstart` -- **Want to dive deeper?** Begin with {doc}`basic_classification` -- **Ready for multiclass?** Jump to {doc}`multiclass_classification` -- **Need API details?** Check {doc}`../api/index` +# Tutorials + +Step-by-step guides to learn torchTextClassifiers through practical examples. + +```{toctree} +:maxdepth: 2 + +basic_classification +multiclass_classification +mixed_features +explainability +multilabel_classification +custom_model +hub_sharing +``` + +## Overview + +These tutorials guide you through common text classification tasks, from basic binary classification to advanced multiclass scenarios. + +## Available Tutorials + +### Getting Started + +::::{grid} 1 +:gutter: 3 + +:::{grid-item-card} {fas}`star` Binary Classification +:link: basic_classification +:link-type: doc + +**Recommended first tutorial** + +Build a sentiment classifier for product reviews. Learn the complete workflow from data preparation to evaluation. + +**What you'll learn:** +- Creating and training tokenizers +- Configuring models +- Training with validation data +- Making predictions +- Evaluating performance + +**Difficulty:** Beginner | **Time:** 15 minutes +::: + +:::: + +### Intermediate Tutorials + +::::{grid} 1 1 2 2 +:gutter: 3 + +:::{grid-item-card} {fas}`layer-group` Multiclass Classification +:link: multiclass_classification +:link-type: doc + +Classify text into 3+ categories with proper handling of class imbalance and evaluation metrics. + +**What you'll learn:** +- Multiclass model configuration +- Class distribution analysis +- Reproducibility with seeds +- Confusion matrices +- Advanced evaluation metrics + +**Difficulty:** Intermediate | **Time:** 20 minutes +::: + +:::{grid-item-card} {fas}`puzzle-piece` Mixed Features +:link: mixed_features +:link-type: doc + +Combine text with categorical variables for improved classification performance. + +**What you'll learn:** +- Adding categorical features alongside text +- Configuring categorical embeddings +- Comparing performance improvements +- Feature combination strategies + +**Difficulty:** Intermediate | **Time:** 25 minutes +::: + +:::: + +### Advanced Tutorials + +::::{grid} 1 1 2 2 +:gutter: 3 + +:::{grid-item-card} {fas}`lightbulb` Explainability +:link: explainability +:link-type: doc + +Understand which words and characters drive your model's predictions. + +**What you'll learn:** +- Generating attribution scores with Captum +- Word-level and character-level visualizations +- Identifying influential tokens +- Interactive explainability mode + +**Difficulty:** Advanced | **Time:** 30 minutes +::: + +:::{grid-item-card} {fas}`tags` Multilabel Classification +:link: multilabel_classification +:link-type: doc + +Assign multiple labels to each text sample for complex classification scenarios. + +**What you'll learn:** +- Ragged lists vs. one-hot encoding +- Configuring BCEWithLogitsLoss +- Multilabel evaluation metrics +- Handling variable labels per sample + +**Difficulty:** Advanced | **Time:** 30 minutes +::: + +:::{grid-item-card} {fas}`puzzle-piece` Custom Architectures +:link: custom_model +:link-type: doc + +Plug any PyTorch model into the torchTextClassifiers wrapper via `from_model`. + +**What you'll learn:** +- When to go beyond `TextClassificationModel` +- The required `forward` / `num_classes` / `categorical_variable_net` interface +- Using `contrib` classes as reference implementations +- Multi-task classification with `MultiLevelTextClassificationModel` + +**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 + +We recommend following this learning path: + +```{mermaid} +graph LR + A[Quick Start] --> B[Binary Classification] + B --> C[Multiclass Classification] + C --> D[Mixed Features] + C --> F[Multilabel Classification] + D --> E[Explainability] + F --> E + D --> G[Custom Architectures] + F --> G + + style A fill:#e3f2fd + style B fill:#bbdefb + style C fill:#90caf9 + style D fill:#64b5f6 + style E fill:#1976d2 + style F fill:#42a5f5 + style G fill:#0d47a1 +``` + +1. **Start with**: {doc}`../getting_started/quickstart` - Get familiar with the basics +2. **Then**: {doc}`basic_classification` - Understand the complete workflow +3. **Next**: {doc}`multiclass_classification` - Handle multiple classes +4. **Branch out**: {doc}`mixed_features` for categorical features OR {doc}`multilabel_classification` for multiple labels +5. **Master**: {doc}`explainability` - Understand your model's predictions + +## Tutorial Format + +Each tutorial follows a consistent structure: + +**Learning Objectives** +: What you'll be able to do after completing the tutorial + +**Prerequisites** +: What you need to know before starting + +**Complete Code** +: Full working example you can copy and run + +**Step-by-Step Walkthrough** +: Detailed explanation of each step + +**Customization** +: How to adapt the code to your needs + +**Common Issues** +: Troubleshooting tips and solutions + +**Next Steps** +: Where to go after finishing + +## Tips for Learning + +### Run the Code + +Don't just read - run the examples! Modify them to see what happens: + +```python +# Try different values +model_config = ModelConfig( + embedding_dim=128, # Was 64 - what changes? + num_classes=2 +) +``` + +### Start Simple + +Begin with the Quick Start, then move to Binary Classification. Don't skip ahead! + +### Use Your Own Data + +Once you understand the examples, try them with your own text data: + +```python +# Your data +my_texts = ["your", "text", "samples"] +my_labels = [0, 1, 0] + +# Same workflow +classifier.train(my_texts, my_labels, training_config) +``` + +### Experiment + +- Try different tokenizers (WordPiece vs NGram) +- Adjust hyperparameters (learning rate, embedding dim) +- Compare model sizes +- Test different batch sizes + +### Read the Errors + +Error messages are helpful! They often tell you exactly what's wrong: + +```python +# Error: num_classes=2 but got label 3 +# Solution: Check your labels - should be 0, 1 (not 1, 2, 3) +``` + +## Getting Help + +Stuck on a tutorial? Here's how to get help: + +1. **Check Common Issues**: Each tutorial has a troubleshooting section +2. **Read the API docs**: {doc}`../api/index` for detailed parameter descriptions +3. **Review architecture**: {doc}`../architecture/overview` for how components work +4. **Ask questions**: [GitHub Discussions](https://github.com/InseeFrLab/torchTextClassifiers/discussions) +5. **Report bugs**: [GitHub Issues](https://github.com/InseeFrLab/torchTextClassifiers/issues) + +## Additional Resources + +### Example Scripts + +All tutorials are based on runnable examples in the repository: + +- [examples/basic_classification.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/basic_classification.py) +- [examples/multiclass_classification.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/multiclass_classification.py) +- [examples/using_additional_features.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/using_additional_features.py) +- [examples/advanced_training.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/advanced_training.py) +- [examples/simple_explainability_example.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/simple_explainability_example.py) + +### Jupyter Notebooks + +Interactive notebooks for hands-on learning: + +- [Basic example notebook](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/notebooks/example.ipynb) +- [Multilabel classification notebook](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/notebooks/multilabel_classification.ipynb) + +## Contributing + +Want to contribute a tutorial? We welcome: + +- New use cases +- Alternative approaches +- Real-world examples +- Performance tips + +See our [contributing guidelines](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/CONTRIBUTING.md) to get started! + +## What's Next? + +Ready to start? Choose your path: + +- **New to text classification?** Start with {doc}`../getting_started/quickstart` +- **Want to dive deeper?** Begin with {doc}`basic_classification` +- **Ready for multiclass?** Jump to {doc}`multiclass_classification` +- **Need API details?** Check {doc}`../api/index` From e5532ed144cc1a8e7b648d3b1fecefd610316991 Mon Sep 17 00:00:00 2001 From: "claude[bot]" <41898282+claude[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:15:10 +0000 Subject: [PATCH 4/4] docs: restore CRLF line endings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cédric Couralet <243027+micedre@users.noreply.github.com> Co-Authored-By: Claude Sonnet 5.5 --- docs/source/api/wrapper.rst | 152 ++--- docs/source/getting_started/installation.md | 340 +++++------ docs/source/tutorials/index.md | 604 ++++++++++---------- 3 files changed, 548 insertions(+), 548 deletions(-) diff --git a/docs/source/api/wrapper.rst b/docs/source/api/wrapper.rst index 23ebd94..b7fa1c2 100644 --- a/docs/source/api/wrapper.rst +++ b/docs/source/api/wrapper.rst @@ -1,76 +1,76 @@ -torchTextClassifiers Wrapper -============================= - -The main wrapper class for text classification tasks. - -.. currentmodule:: torchTextClassifiers.torchTextClassifiers - -Main Class ----------- - -.. autoclass:: torchTextClassifiers - :members: - :undoc-members: - :show-inheritance: - :inherited-members: - :special-members: __init__ - - .. rubric:: Methods - - .. autosummary:: - :nosignatures: - - ~torchTextClassifiers.train - ~torchTextClassifiers.predict - ~torchTextClassifiers.predict_proba - ~torchTextClassifiers.get_explanations - ~torchTextClassifiers.save - ~torchTextClassifiers.load - ~torchTextClassifiers.save_pretrained - ~torchTextClassifiers.from_pretrained - ~torchTextClassifiers.push_to_hub - -Usage Example -------------- - -.. code-block:: python - - from torchTextClassifiers import torchTextClassifiers, ModelConfig, TrainingConfig - from torchTextClassifiers.tokenizers import WordPieceTokenizer - - # Create tokenizer - tokenizer = WordPieceTokenizer() - tokenizer.train(texts, vocab_size=1000) - - # Configure model - model_config = ModelConfig(embedding_dim=64, num_classes=2) - training_config = TrainingConfig(num_epochs=10, batch_size=16, lr=1e-3) - - # Create and train classifier - classifier = torchTextClassifiers(tokenizer=tokenizer, model_config=model_config) - classifier.train(X_text=texts, y=labels, training_config=training_config) - - # Make predictions - 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 --------- - -* :doc:`configs` - Configuration classes -* :doc:`tokenizers` - Tokenizer options -* :doc:`model` - Underlying PyTorch models +torchTextClassifiers Wrapper +============================= + +The main wrapper class for text classification tasks. + +.. currentmodule:: torchTextClassifiers.torchTextClassifiers + +Main Class +---------- + +.. autoclass:: torchTextClassifiers + :members: + :undoc-members: + :show-inheritance: + :inherited-members: + :special-members: __init__ + + .. rubric:: Methods + + .. autosummary:: + :nosignatures: + + ~torchTextClassifiers.train + ~torchTextClassifiers.predict + ~torchTextClassifiers.predict_proba + ~torchTextClassifiers.get_explanations + ~torchTextClassifiers.save + ~torchTextClassifiers.load + ~torchTextClassifiers.save_pretrained + ~torchTextClassifiers.from_pretrained + ~torchTextClassifiers.push_to_hub + +Usage Example +------------- + +.. code-block:: python + + from torchTextClassifiers import torchTextClassifiers, ModelConfig, TrainingConfig + from torchTextClassifiers.tokenizers import WordPieceTokenizer + + # Create tokenizer + tokenizer = WordPieceTokenizer() + tokenizer.train(texts, vocab_size=1000) + + # Configure model + model_config = ModelConfig(embedding_dim=64, num_classes=2) + training_config = TrainingConfig(num_epochs=10, batch_size=16, lr=1e-3) + + # Create and train classifier + classifier = torchTextClassifiers(tokenizer=tokenizer, model_config=model_config) + classifier.train(X_text=texts, y=labels, training_config=training_config) + + # Make predictions + 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 +-------- + +* :doc:`configs` - Configuration classes +* :doc:`tokenizers` - Tokenizer options +* :doc:`model` - Underlying PyTorch models diff --git a/docs/source/getting_started/installation.md b/docs/source/getting_started/installation.md index 1c95355..ad7cb34 100644 --- a/docs/source/getting_started/installation.md +++ b/docs/source/getting_started/installation.md @@ -1,170 +1,170 @@ -# Installation - -## Requirements - -torchTextClassifiers requires: - -- **Python**: 3.11 or higher -- **PyTorch**: Will be installed automatically as a dependency via pytorch-lightning -- **Operating System**: Linux, macOS, or Windows - -## Installation from Source - -Currently, torchTextClassifiers is available only from source. Clone the repository and install using [uv](https://github.com/astral-sh/uv), a fast Python package installer and resolver. - -```bash -# Clone the repository -git clone https://github.com/InseeFrLab/torchTextClassifiers.git -cd torchTextClassifiers - -# Install with uv -uv sync -``` - -## Optional Dependencies - -torchTextClassifiers comes with optional dependency groups for additional features: - -### Explainability Support - -For model interpretation and explainability features: - -```bash -uv sync --extra explainability -``` - -This installs: -- `captum`: For attribution analysis -- `nltk`: For text preprocessing -- `unidecode`: For text normalization - -### HuggingFace Integration - -To use HuggingFace tokenizers: - -```bash -uv sync --extra huggingface -``` - -This installs: -- `tokenizers`: Fast tokenizers -- `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: - -```bash -uv sync --extra preprocess -``` - -This installs: -- `nltk`: Natural language toolkit -- `unidecode`: Text normalization - -### All Optional Dependencies - -Install all extras at once: - -```bash -uv sync --all-extras -``` - -### Development Dependencies - -If you want to contribute to the project: - -```bash -uv sync --group dev -``` - -## Verification - -Verify your installation by running: - -```python -import torchTextClassifiers -print(torchTextClassifiers.__version__) # Should print: 0.0.0-dev -``` - -Or try a simple import: - -```python -from torchTextClassifiers import torchTextClassifiers, ModelConfig, TrainingConfig -from torchTextClassifiers.tokenizers import WordPieceTokenizer - -print("Installation successful!") -``` - -## GPU Support - -torchTextClassifiers uses PyTorch Lightning, which automatically detects and uses GPUs if available. - -To use GPUs, make sure you have: -1. CUDA-compatible GPU -2. CUDA toolkit installed -3. PyTorch installed with CUDA support - -Check GPU availability: - -```python -import torch -print(f"GPU available: {torch.cuda.is_available()}") -print(f"GPU count: {torch.cuda.device_count()}") -``` - -## Troubleshooting - -### Import Errors - -If you encounter import errors, make sure you've installed the package: - -```bash -# Reinstall -uv sync -``` - -### Dependency Conflicts - -If you have dependency conflicts, try creating a fresh virtual environment: - -```bash -# Create new virtual environment with uv -uv venv -source .venv/bin/activate # On Windows: .venv\Scripts\activate -uv sync -``` - -### PyTorch Installation Issues - -If PyTorch installation fails, uv will handle it automatically through pytorch-lightning. If you need a specific PyTorch version, you can specify it in your environment before running: - -```bash -# For CPU-only PyTorch -export PYTORCH_INDEX_URL="https://download.pytorch.org/whl/cpu" -uv sync - -# For GPU (CUDA 11.8) -export PYTORCH_INDEX_URL="https://download.pytorch.org/whl/cu118" -uv sync -``` - -## Next Steps - -Now that you have torchTextClassifiers installed, head over to the {doc}`quickstart` to build your first classifier! +# Installation + +## Requirements + +torchTextClassifiers requires: + +- **Python**: 3.11 or higher +- **PyTorch**: Will be installed automatically as a dependency via pytorch-lightning +- **Operating System**: Linux, macOS, or Windows + +## Installation from Source + +Currently, torchTextClassifiers is available only from source. Clone the repository and install using [uv](https://github.com/astral-sh/uv), a fast Python package installer and resolver. + +```bash +# Clone the repository +git clone https://github.com/InseeFrLab/torchTextClassifiers.git +cd torchTextClassifiers + +# Install with uv +uv sync +``` + +## Optional Dependencies + +torchTextClassifiers comes with optional dependency groups for additional features: + +### Explainability Support + +For model interpretation and explainability features: + +```bash +uv sync --extra explainability +``` + +This installs: +- `captum`: For attribution analysis +- `nltk`: For text preprocessing +- `unidecode`: For text normalization + +### HuggingFace Integration + +To use HuggingFace tokenizers: + +```bash +uv sync --extra huggingface +``` + +This installs: +- `tokenizers`: Fast tokenizers +- `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: + +```bash +uv sync --extra preprocess +``` + +This installs: +- `nltk`: Natural language toolkit +- `unidecode`: Text normalization + +### All Optional Dependencies + +Install all extras at once: + +```bash +uv sync --all-extras +``` + +### Development Dependencies + +If you want to contribute to the project: + +```bash +uv sync --group dev +``` + +## Verification + +Verify your installation by running: + +```python +import torchTextClassifiers +print(torchTextClassifiers.__version__) # Should print: 0.0.0-dev +``` + +Or try a simple import: + +```python +from torchTextClassifiers import torchTextClassifiers, ModelConfig, TrainingConfig +from torchTextClassifiers.tokenizers import WordPieceTokenizer + +print("Installation successful!") +``` + +## GPU Support + +torchTextClassifiers uses PyTorch Lightning, which automatically detects and uses GPUs if available. + +To use GPUs, make sure you have: +1. CUDA-compatible GPU +2. CUDA toolkit installed +3. PyTorch installed with CUDA support + +Check GPU availability: + +```python +import torch +print(f"GPU available: {torch.cuda.is_available()}") +print(f"GPU count: {torch.cuda.device_count()}") +``` + +## Troubleshooting + +### Import Errors + +If you encounter import errors, make sure you've installed the package: + +```bash +# Reinstall +uv sync +``` + +### Dependency Conflicts + +If you have dependency conflicts, try creating a fresh virtual environment: + +```bash +# Create new virtual environment with uv +uv venv +source .venv/bin/activate # On Windows: .venv\Scripts\activate +uv sync +``` + +### PyTorch Installation Issues + +If PyTorch installation fails, uv will handle it automatically through pytorch-lightning. If you need a specific PyTorch version, you can specify it in your environment before running: + +```bash +# For CPU-only PyTorch +export PYTORCH_INDEX_URL="https://download.pytorch.org/whl/cpu" +uv sync + +# For GPU (CUDA 11.8) +export PYTORCH_INDEX_URL="https://download.pytorch.org/whl/cu118" +uv sync +``` + +## Next Steps + +Now that you have torchTextClassifiers installed, head over to the {doc}`quickstart` to build your first classifier! diff --git a/docs/source/tutorials/index.md b/docs/source/tutorials/index.md index 0a0de7e..bb8581f 100644 --- a/docs/source/tutorials/index.md +++ b/docs/source/tutorials/index.md @@ -1,302 +1,302 @@ -# Tutorials - -Step-by-step guides to learn torchTextClassifiers through practical examples. - -```{toctree} -:maxdepth: 2 - -basic_classification -multiclass_classification -mixed_features -explainability -multilabel_classification -custom_model -hub_sharing -``` - -## Overview - -These tutorials guide you through common text classification tasks, from basic binary classification to advanced multiclass scenarios. - -## Available Tutorials - -### Getting Started - -::::{grid} 1 -:gutter: 3 - -:::{grid-item-card} {fas}`star` Binary Classification -:link: basic_classification -:link-type: doc - -**Recommended first tutorial** - -Build a sentiment classifier for product reviews. Learn the complete workflow from data preparation to evaluation. - -**What you'll learn:** -- Creating and training tokenizers -- Configuring models -- Training with validation data -- Making predictions -- Evaluating performance - -**Difficulty:** Beginner | **Time:** 15 minutes -::: - -:::: - -### Intermediate Tutorials - -::::{grid} 1 1 2 2 -:gutter: 3 - -:::{grid-item-card} {fas}`layer-group` Multiclass Classification -:link: multiclass_classification -:link-type: doc - -Classify text into 3+ categories with proper handling of class imbalance and evaluation metrics. - -**What you'll learn:** -- Multiclass model configuration -- Class distribution analysis -- Reproducibility with seeds -- Confusion matrices -- Advanced evaluation metrics - -**Difficulty:** Intermediate | **Time:** 20 minutes -::: - -:::{grid-item-card} {fas}`puzzle-piece` Mixed Features -:link: mixed_features -:link-type: doc - -Combine text with categorical variables for improved classification performance. - -**What you'll learn:** -- Adding categorical features alongside text -- Configuring categorical embeddings -- Comparing performance improvements -- Feature combination strategies - -**Difficulty:** Intermediate | **Time:** 25 minutes -::: - -:::: - -### Advanced Tutorials - -::::{grid} 1 1 2 2 -:gutter: 3 - -:::{grid-item-card} {fas}`lightbulb` Explainability -:link: explainability -:link-type: doc - -Understand which words and characters drive your model's predictions. - -**What you'll learn:** -- Generating attribution scores with Captum -- Word-level and character-level visualizations -- Identifying influential tokens -- Interactive explainability mode - -**Difficulty:** Advanced | **Time:** 30 minutes -::: - -:::{grid-item-card} {fas}`tags` Multilabel Classification -:link: multilabel_classification -:link-type: doc - -Assign multiple labels to each text sample for complex classification scenarios. - -**What you'll learn:** -- Ragged lists vs. one-hot encoding -- Configuring BCEWithLogitsLoss -- Multilabel evaluation metrics -- Handling variable labels per sample - -**Difficulty:** Advanced | **Time:** 30 minutes -::: - -:::{grid-item-card} {fas}`puzzle-piece` Custom Architectures -:link: custom_model -:link-type: doc - -Plug any PyTorch model into the torchTextClassifiers wrapper via `from_model`. - -**What you'll learn:** -- When to go beyond `TextClassificationModel` -- The required `forward` / `num_classes` / `categorical_variable_net` interface -- Using `contrib` classes as reference implementations -- Multi-task classification with `MultiLevelTextClassificationModel` - -**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 - -We recommend following this learning path: - -```{mermaid} -graph LR - A[Quick Start] --> B[Binary Classification] - B --> C[Multiclass Classification] - C --> D[Mixed Features] - C --> F[Multilabel Classification] - D --> E[Explainability] - F --> E - D --> G[Custom Architectures] - F --> G - - style A fill:#e3f2fd - style B fill:#bbdefb - style C fill:#90caf9 - style D fill:#64b5f6 - style E fill:#1976d2 - style F fill:#42a5f5 - style G fill:#0d47a1 -``` - -1. **Start with**: {doc}`../getting_started/quickstart` - Get familiar with the basics -2. **Then**: {doc}`basic_classification` - Understand the complete workflow -3. **Next**: {doc}`multiclass_classification` - Handle multiple classes -4. **Branch out**: {doc}`mixed_features` for categorical features OR {doc}`multilabel_classification` for multiple labels -5. **Master**: {doc}`explainability` - Understand your model's predictions - -## Tutorial Format - -Each tutorial follows a consistent structure: - -**Learning Objectives** -: What you'll be able to do after completing the tutorial - -**Prerequisites** -: What you need to know before starting - -**Complete Code** -: Full working example you can copy and run - -**Step-by-Step Walkthrough** -: Detailed explanation of each step - -**Customization** -: How to adapt the code to your needs - -**Common Issues** -: Troubleshooting tips and solutions - -**Next Steps** -: Where to go after finishing - -## Tips for Learning - -### Run the Code - -Don't just read - run the examples! Modify them to see what happens: - -```python -# Try different values -model_config = ModelConfig( - embedding_dim=128, # Was 64 - what changes? - num_classes=2 -) -``` - -### Start Simple - -Begin with the Quick Start, then move to Binary Classification. Don't skip ahead! - -### Use Your Own Data - -Once you understand the examples, try them with your own text data: - -```python -# Your data -my_texts = ["your", "text", "samples"] -my_labels = [0, 1, 0] - -# Same workflow -classifier.train(my_texts, my_labels, training_config) -``` - -### Experiment - -- Try different tokenizers (WordPiece vs NGram) -- Adjust hyperparameters (learning rate, embedding dim) -- Compare model sizes -- Test different batch sizes - -### Read the Errors - -Error messages are helpful! They often tell you exactly what's wrong: - -```python -# Error: num_classes=2 but got label 3 -# Solution: Check your labels - should be 0, 1 (not 1, 2, 3) -``` - -## Getting Help - -Stuck on a tutorial? Here's how to get help: - -1. **Check Common Issues**: Each tutorial has a troubleshooting section -2. **Read the API docs**: {doc}`../api/index` for detailed parameter descriptions -3. **Review architecture**: {doc}`../architecture/overview` for how components work -4. **Ask questions**: [GitHub Discussions](https://github.com/InseeFrLab/torchTextClassifiers/discussions) -5. **Report bugs**: [GitHub Issues](https://github.com/InseeFrLab/torchTextClassifiers/issues) - -## Additional Resources - -### Example Scripts - -All tutorials are based on runnable examples in the repository: - -- [examples/basic_classification.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/basic_classification.py) -- [examples/multiclass_classification.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/multiclass_classification.py) -- [examples/using_additional_features.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/using_additional_features.py) -- [examples/advanced_training.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/advanced_training.py) -- [examples/simple_explainability_example.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/simple_explainability_example.py) - -### Jupyter Notebooks - -Interactive notebooks for hands-on learning: - -- [Basic example notebook](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/notebooks/example.ipynb) -- [Multilabel classification notebook](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/notebooks/multilabel_classification.ipynb) - -## Contributing - -Want to contribute a tutorial? We welcome: - -- New use cases -- Alternative approaches -- Real-world examples -- Performance tips - -See our [contributing guidelines](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/CONTRIBUTING.md) to get started! - -## What's Next? - -Ready to start? Choose your path: - -- **New to text classification?** Start with {doc}`../getting_started/quickstart` -- **Want to dive deeper?** Begin with {doc}`basic_classification` -- **Ready for multiclass?** Jump to {doc}`multiclass_classification` -- **Need API details?** Check {doc}`../api/index` +# Tutorials + +Step-by-step guides to learn torchTextClassifiers through practical examples. + +```{toctree} +:maxdepth: 2 + +basic_classification +multiclass_classification +mixed_features +explainability +multilabel_classification +custom_model +hub_sharing +``` + +## Overview + +These tutorials guide you through common text classification tasks, from basic binary classification to advanced multiclass scenarios. + +## Available Tutorials + +### Getting Started + +::::{grid} 1 +:gutter: 3 + +:::{grid-item-card} {fas}`star` Binary Classification +:link: basic_classification +:link-type: doc + +**Recommended first tutorial** + +Build a sentiment classifier for product reviews. Learn the complete workflow from data preparation to evaluation. + +**What you'll learn:** +- Creating and training tokenizers +- Configuring models +- Training with validation data +- Making predictions +- Evaluating performance + +**Difficulty:** Beginner | **Time:** 15 minutes +::: + +:::: + +### Intermediate Tutorials + +::::{grid} 1 1 2 2 +:gutter: 3 + +:::{grid-item-card} {fas}`layer-group` Multiclass Classification +:link: multiclass_classification +:link-type: doc + +Classify text into 3+ categories with proper handling of class imbalance and evaluation metrics. + +**What you'll learn:** +- Multiclass model configuration +- Class distribution analysis +- Reproducibility with seeds +- Confusion matrices +- Advanced evaluation metrics + +**Difficulty:** Intermediate | **Time:** 20 minutes +::: + +:::{grid-item-card} {fas}`puzzle-piece` Mixed Features +:link: mixed_features +:link-type: doc + +Combine text with categorical variables for improved classification performance. + +**What you'll learn:** +- Adding categorical features alongside text +- Configuring categorical embeddings +- Comparing performance improvements +- Feature combination strategies + +**Difficulty:** Intermediate | **Time:** 25 minutes +::: + +:::: + +### Advanced Tutorials + +::::{grid} 1 1 2 2 +:gutter: 3 + +:::{grid-item-card} {fas}`lightbulb` Explainability +:link: explainability +:link-type: doc + +Understand which words and characters drive your model's predictions. + +**What you'll learn:** +- Generating attribution scores with Captum +- Word-level and character-level visualizations +- Identifying influential tokens +- Interactive explainability mode + +**Difficulty:** Advanced | **Time:** 30 minutes +::: + +:::{grid-item-card} {fas}`tags` Multilabel Classification +:link: multilabel_classification +:link-type: doc + +Assign multiple labels to each text sample for complex classification scenarios. + +**What you'll learn:** +- Ragged lists vs. one-hot encoding +- Configuring BCEWithLogitsLoss +- Multilabel evaluation metrics +- Handling variable labels per sample + +**Difficulty:** Advanced | **Time:** 30 minutes +::: + +:::{grid-item-card} {fas}`puzzle-piece` Custom Architectures +:link: custom_model +:link-type: doc + +Plug any PyTorch model into the torchTextClassifiers wrapper via `from_model`. + +**What you'll learn:** +- When to go beyond `TextClassificationModel` +- The required `forward` / `num_classes` / `categorical_variable_net` interface +- Using `contrib` classes as reference implementations +- Multi-task classification with `MultiLevelTextClassificationModel` + +**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 + +We recommend following this learning path: + +```{mermaid} +graph LR + A[Quick Start] --> B[Binary Classification] + B --> C[Multiclass Classification] + C --> D[Mixed Features] + C --> F[Multilabel Classification] + D --> E[Explainability] + F --> E + D --> G[Custom Architectures] + F --> G + + style A fill:#e3f2fd + style B fill:#bbdefb + style C fill:#90caf9 + style D fill:#64b5f6 + style E fill:#1976d2 + style F fill:#42a5f5 + style G fill:#0d47a1 +``` + +1. **Start with**: {doc}`../getting_started/quickstart` - Get familiar with the basics +2. **Then**: {doc}`basic_classification` - Understand the complete workflow +3. **Next**: {doc}`multiclass_classification` - Handle multiple classes +4. **Branch out**: {doc}`mixed_features` for categorical features OR {doc}`multilabel_classification` for multiple labels +5. **Master**: {doc}`explainability` - Understand your model's predictions + +## Tutorial Format + +Each tutorial follows a consistent structure: + +**Learning Objectives** +: What you'll be able to do after completing the tutorial + +**Prerequisites** +: What you need to know before starting + +**Complete Code** +: Full working example you can copy and run + +**Step-by-Step Walkthrough** +: Detailed explanation of each step + +**Customization** +: How to adapt the code to your needs + +**Common Issues** +: Troubleshooting tips and solutions + +**Next Steps** +: Where to go after finishing + +## Tips for Learning + +### Run the Code + +Don't just read - run the examples! Modify them to see what happens: + +```python +# Try different values +model_config = ModelConfig( + embedding_dim=128, # Was 64 - what changes? + num_classes=2 +) +``` + +### Start Simple + +Begin with the Quick Start, then move to Binary Classification. Don't skip ahead! + +### Use Your Own Data + +Once you understand the examples, try them with your own text data: + +```python +# Your data +my_texts = ["your", "text", "samples"] +my_labels = [0, 1, 0] + +# Same workflow +classifier.train(my_texts, my_labels, training_config) +``` + +### Experiment + +- Try different tokenizers (WordPiece vs NGram) +- Adjust hyperparameters (learning rate, embedding dim) +- Compare model sizes +- Test different batch sizes + +### Read the Errors + +Error messages are helpful! They often tell you exactly what's wrong: + +```python +# Error: num_classes=2 but got label 3 +# Solution: Check your labels - should be 0, 1 (not 1, 2, 3) +``` + +## Getting Help + +Stuck on a tutorial? Here's how to get help: + +1. **Check Common Issues**: Each tutorial has a troubleshooting section +2. **Read the API docs**: {doc}`../api/index` for detailed parameter descriptions +3. **Review architecture**: {doc}`../architecture/overview` for how components work +4. **Ask questions**: [GitHub Discussions](https://github.com/InseeFrLab/torchTextClassifiers/discussions) +5. **Report bugs**: [GitHub Issues](https://github.com/InseeFrLab/torchTextClassifiers/issues) + +## Additional Resources + +### Example Scripts + +All tutorials are based on runnable examples in the repository: + +- [examples/basic_classification.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/basic_classification.py) +- [examples/multiclass_classification.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/multiclass_classification.py) +- [examples/using_additional_features.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/using_additional_features.py) +- [examples/advanced_training.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/advanced_training.py) +- [examples/simple_explainability_example.py](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/examples/simple_explainability_example.py) + +### Jupyter Notebooks + +Interactive notebooks for hands-on learning: + +- [Basic example notebook](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/notebooks/example.ipynb) +- [Multilabel classification notebook](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/notebooks/multilabel_classification.ipynb) + +## Contributing + +Want to contribute a tutorial? We welcome: + +- New use cases +- Alternative approaches +- Real-world examples +- Performance tips + +See our [contributing guidelines](https://github.com/InseeFrLab/torchTextClassifiers/blob/main/CONTRIBUTING.md) to get started! + +## What's Next? + +Ready to start? Choose your path: + +- **New to text classification?** Start with {doc}`../getting_started/quickstart` +- **Want to dive deeper?** Begin with {doc}`basic_classification` +- **Ready for multiclass?** Jump to {doc}`multiclass_classification` +- **Need API details?** Check {doc}`../api/index`