Skip to content

Add native Hugging Face Hub integration (push_to_hub / from_pretrained) #109

Open

Description

@micedre

Motivation

We want to publish trained torchTextClassifiers models on the Hugging Face Hub under the InseeFr org so external users can reuse them. At the moment, there is no path to do this with the required automation/quality...

Proposal

Make the torchTextClassifiers wrapper class (and possibly TextClassificationModel) inherit from huggingface_hub.ModelHubMixin, so users can do:

from torchTextClassifiers import torchTextClassifiers

clf = torchTextClassifiers.from_pretrained("InseeFrLab/<model>", revision="v1.0.0")
clf.predict(...)

clf.push_to_hub("InseeFrLab/<model>")

Serialized artifact (self-contained, no pickle)

File Content
model.safetensors weights of all components
config.json architecture + hyperparameters (TextEmbedder, CategoricalVariableNet, ClassificationHead), task type (multiclass / multilabel), library version
tokenizer/ HF tokenizer files, or n-gram tokenizer params/vocab
labels.json index ↔ label code ↔ human-readable label
categorical.json vocabularies / encodings of categorical variables
README.md auto-generated model card

Reloading must only require pip install torchTextClassifiers==<version>.

Implementation notes/proposals

  • Implement _save_pretrained / _from_pretrained on the wrapper. PyTorchModelHubMixin alone only covers the nn.Module weights, not the tokenizer, labels or categorical encodings.
  • If v2 already has internal save / load methods, the mixin should wrap them rather than duplicate them.
  • Set class-level mixin metadata: library_name="torchtextclassifiers", repo_url, docs_url, tags=["text-classification", ...].
  • Override generate_model_card() so the YAML header includes library_name, pipeline_tag: text-classification, license, language, and optional datasets / model-index (metrics) passed in by the user.
  • Allow extra card fields to be passed through push_to_hub(...), e.g. dataset ID + revision, training code commit, metrics.
  • Save with safetensors only; never torch.save of full objects.
  • Keep huggingface_hub / safetensors as an optional extra (pip install torchTextClassifiers[hub]) if we want a lean core.

Open questions

  • Should from_pretrained warn or raise when the saved library version differs (major version) from the installed one?
  • Do we also want ONNX export for serving, or keep that in a separate issue?
  • Should we register torchtextclassifiers as a library on the Hub (huggingface.js) to get a "Use this model" snippet?

References

Activity

  1. micedre commented on Nov 24, 2026

    @micedre
    CollaboratorAuthor
  2. claude commented on Nov 24, 2026

    @claude

    Claude finished @micedre's task in 25s —— View job


    Analysis of issue #109 (no code changes yet)

    Your comment only contained @claude, so I haven't made any changes. I read the current save/load code and wrote up what the Hub integration would involve. Tell me which parts to implement, or answer the open questions below.

    Findings

    torchTextClassifiers.save() and load() (torchTextClassifiers/torchTextClassifiers.py:865-1018) rely heavily on pickle:

    • metadata.pkl, tokenizer.pkl and value_encoder.pkl are pickled.
    • Custom models (from_model) pickle the whole nn.Module as pytorch_model.pkl.
    • Weights for standard models live inside a Lightning .ckpt, which is loaded with weights_only=False.

    This conflicts with the issue's "no pickle, safetensors only" requirement. The mixin therefore cannot just wrap the existing save/load. We need a second, pickle-free serialization path, and save/load could later be moved onto it.

    huggingface_hub and safetensors are not dependencies today. pyproject.toml already has optional extras (huggingface, explainability), so a hub extra fits the existing pattern.

    Proposed design

    1. Extra: hub = ["huggingface_hub>=0.24", "safetensors"] in pyproject.toml.
    2. Mixin: make torchTextClassifiers inherit ModelHubMixin, with library_name="torchtextclassifiers", repo_url, docs_url and tags=["text-classification", ...]. Guard the import so the core still works without the extra.
    3. _save_pretrained(save_directory) writes:
      • model.safetensors, from pytorch_model.state_dict().
      • config.json: ModelConfig.to_dict(), ragged_multilabel, task type, num_classes, loss name and library_version. The mixin serializes init kwargs, so ModelConfig/TrainingConfig need a JSON round-trip.
      • tokenizer/: the HF tokenizer's save_pretrained, or JSON params and vocab for the n-gram tokenizer. This needs a to_dict/from_dict (or save/load) on each tokenizer in tokenizers/.
      • labels.json and categorical.json: from ValueEncoder (value_encoder/value_encoder.py), which also needs JSON (de)serialization.
      • README.md: from generate_model_card().
    4. _from_pretrained(...) rebuilds the tokenizer, ModelConfig and ValueEncoder from JSON, constructs the instance, then loads model.safetensors.
    5. Model card: override generate_model_card() to emit YAML with library_name, pipeline_tag: text-classification, license, language, and optional datasets and model-index. Extra card fields would be passed through a card_kwargs-style argument on push_to_hub.
    6. Tests: a round-trip test with a local directory (save_pretrained then from_pretrained, asserting identical predictions) for the n-gram and WordPiece tokenizers, with and without categorical variables. Also a test with the Hub mocked, and a test that import torchTextClassifiers works without the extra.

    Risks and gaps

    • Custom models (from_model) can't be described by config.json, because the architecture is an arbitrary nn.Module. I suggest Hub support for standard ModelConfig-built models only. Custom models would raise a clear error, or we would add an explicit architecture registry later.
    • Tokenizers are the largest piece of work. Each one needs a pickle-free serialization.
    • The loss function is currently pickled in metadata. It isn't needed for inference, so it can be dropped or stored by name.
    • TextClassificationModel: I'd put the mixin only on the wrapper. The wrapper owns the tokenizer, encoder and labels, and the bare module can't be rebuilt on its own.

    Suggested answers to the open questions

    • Version mismatch: warn on a minor or patch difference and raise on a major difference. Allow an override such as strict=False.
    • ONNX export: keep it in a separate issue.
    • Registering on huggingface.js: do this after the first models are published. It's a small PR to huggingface.js and doesn't block the code.

    Next step

    Should I implement this? A reasonable split would be a first PR for the extra, mixin, config/weights and n-gram tokenizer, then a follow-up for the WordPiece tokenizer, model card and docs. Reply with @claude implement plus any scope or answer changes.
    · Branch: claude/issue-109-20261124-1339

  3. micedre commented on Nov 24, 2026

    @micedre
    CollaboratorAuthor

    @claude implement with 2 PR, without breaking changes if possible (or not them in doc and upgrade version)

  4. claude commented on Nov 24, 2026

    @claude

    Claude finished @micedre's task in 3m 32s —— View job • claude/issue-109-20261124-1343 • Create PR ➔


    PR 1 of 2 implemented (Hub core + n-gram tokenizer)

    I pushed the first half of the work to claude/issue-109-20261124-1343. The new tests/test_hub.py passes (6 tests). The rest of the suite passes except 4 tests in tests/test_pipeline.py. Those 4 fail only because captum isn't installed in my sandbox. I also couldn't collect tests/test_tokenizer.py (matplotlib missing here). I have not run those tests, and I did not test a real push to the Hub (no token or network access).

    Done

    • Optional extra hub = ["huggingface_hub>=0.24", "safetensors"] in pyproject.toml. huggingface_hub and safetensors are also in the dev group.
    • torchTextClassifiers/hub.py:
      • It holds the mixin base with a stub fallback, so import torchTextClassifiers still works without the extra.
      • It also holds the model card builder, the version check and the tokenizer registry.
    • torchTextClassifiers now inherits ModelHubMixin, with library_name, repo_url, docs_url and tags set. This gives save_pretrained, from_pretrained and push_to_hub.
    • _save_pretrained writes model.safetensors, config.json, tokenizer/, labels.json, categorical.json (when there are categorical variables) and README.md. It writes no pickle.
    • _from_pretrained rebuilds the model from a local directory or a Hub repo. It accepts device= and strict=.
    • Version check: a different major version raises unless strict=False. Any other difference only warns.
    • generate_model_card() writes the YAML header (library_name, pipeline_tag: text-classification, license, language, datasets, model-index). Extra fields go through push_to_hub(..., model_card_kwargs={...}).
    • ValueEncoder.labels_to_dict, categorical_to_dict and from_dicts.
    • ModelConfig.from_dict now rebuilds a nested attention_config. Before, it left a plain dict.
    • NGramTokenizer now saves output_dim. Older saved files still load, because output_dim is read with .get.
    • Round-trip tests with and without categorical variables (identical predictions), plus tests for the model card, major-version mismatch and the custom-model error.

    No breaking changes. The existing save() / load() are untouched. The Hub path is purely additive.

    Limits in PR 1

    • Models built with from_model raise a clear NotImplementedError.
    • Only NGramTokenizer is supported. Other tokenizers raise NotImplementedError.
    • Labels are stored as strings, and LabelEncoder objects come back as DictEncoder.

    Note on formatting: while running ruff format I accidentally reformatted a few lines in torchTextClassifiers.py (some assert statements). These are cosmetic only.

    PR 2 (not started)

    The WordPiece and HuggingFace tokenizer serialization, docs (README and a Hub guide) and model card polish. I can only push to this one branch, so PR 2 needs a branch based on this one. Comment @claude implement PR 2 after PR 1 is merged, or tell me to stack it on this branch.

    · Branch: claude/issue-109-20261124-1343

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions