Repository navigation
Open
Description
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_pretrainedon the wrapper.PyTorchModelHubMixinalone only covers thenn.Moduleweights, not the tokenizer, labels or categorical encodings. - If v2 already has internal
save/loadmethods, 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 includeslibrary_name,pipeline_tag: text-classification,license,language, and optionaldatasets/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
safetensorsonly; nevertorch.saveof full objects. - Keep
huggingface_hub/safetensorsas an optional extra (pip install torchTextClassifiers[hub]) if we want a lean core.
Open questions
- Should
from_pretrainedwarn 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
torchtextclassifiersas a library on the Hub (huggingface.js) to get a "Use this model" snippet?
References
Metadata
Metadata
Assignees
Labels
No labels
Activity
micedre commentedon Nov 24, 2026
@claude
claude commentedon Nov 24, 2026
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 currentsave/loadcode and wrote up what the Hub integration would involve. Tell me which parts to implement, or answer the open questions below.Findings
torchTextClassifiers.save()andload()(torchTextClassifiers/torchTextClassifiers.py:865-1018) rely heavily on pickle:metadata.pkl,tokenizer.pklandvalue_encoder.pklare pickled.from_model) pickle the wholenn.Moduleaspytorch_model.pkl..ckpt, which is loaded withweights_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, andsave/loadcould later be moved onto it.huggingface_hubandsafetensorsare not dependencies today.pyproject.tomlalready has optional extras (huggingface,explainability), so ahubextra fits the existing pattern.Proposed design
hub = ["huggingface_hub>=0.24", "safetensors"]inpyproject.toml.torchTextClassifiersinheritModelHubMixin, withlibrary_name="torchtextclassifiers",repo_url,docs_urlandtags=["text-classification", ...]. Guard the import so the core still works without the extra._save_pretrained(save_directory)writes:model.safetensors, frompytorch_model.state_dict().config.json:ModelConfig.to_dict(),ragged_multilabel, task type,num_classes, loss name andlibrary_version. The mixin serializes init kwargs, soModelConfig/TrainingConfigneed a JSON round-trip.tokenizer/: the HF tokenizer'ssave_pretrained, or JSON params and vocab for the n-gram tokenizer. This needs ato_dict/from_dict(orsave/load) on each tokenizer intokenizers/.labels.jsonandcategorical.json: fromValueEncoder(value_encoder/value_encoder.py), which also needs JSON (de)serialization.README.md: fromgenerate_model_card()._from_pretrained(...)rebuilds the tokenizer,ModelConfigandValueEncoderfrom JSON, constructs the instance, then loadsmodel.safetensors.generate_model_card()to emit YAML withlibrary_name,pipeline_tag: text-classification,license,language, and optionaldatasetsandmodel-index. Extra card fields would be passed through acard_kwargs-style argument onpush_to_hub.save_pretrainedthenfrom_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 thatimport torchTextClassifiersworks without the extra.Risks and gaps
from_model) can't be described byconfig.json, because the architecture is an arbitrarynn.Module. I suggest Hub support for standardModelConfig-built models only. Custom models would raise a clear error, or we would add an explicit architecture registry later.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
strict=False.huggingface.jsand 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 implementplus any scope or answer changes.· Branch:
claude/issue-109-20261124-1339micedre commentedon Nov 24, 2026
@claude implement with 2 PR, without breaking changes if possible (or not them in doc and upgrade version)
claude commentedon Nov 24, 2026
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 newtests/test_hub.pypasses (6 tests). The rest of the suite passes except 4 tests intests/test_pipeline.py. Those 4 fail only because captum isn't installed in my sandbox. I also couldn't collecttests/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
hub = ["huggingface_hub>=0.24", "safetensors"]inpyproject.toml.huggingface_hubandsafetensorsare also in the dev group.torchTextClassifiers/hub.py:import torchTextClassifiersstill works without the extra.torchTextClassifiersnow inheritsModelHubMixin, withlibrary_name,repo_url,docs_urlandtagsset. This givessave_pretrained,from_pretrainedandpush_to_hub._save_pretrainedwritesmodel.safetensors,config.json,tokenizer/,labels.json,categorical.json(when there are categorical variables) andREADME.md. It writes no pickle._from_pretrainedrebuilds the model from a local directory or a Hub repo. It acceptsdevice=andstrict=.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 throughpush_to_hub(..., model_card_kwargs={...}).ValueEncoder.labels_to_dict,categorical_to_dictandfrom_dicts.ModelConfig.from_dictnow rebuilds a nestedattention_config. Before, it left a plain dict.NGramTokenizernow savesoutput_dim. Older saved files still load, becauseoutput_dimis read with.get.No breaking changes. The existing
save()/load()are untouched. The Hub path is purely additive.Limits in PR 1
from_modelraise a clearNotImplementedError.NGramTokenizeris supported. Other tokenizers raiseNotImplementedError.LabelEncoderobjects come back asDictEncoder.Note on formatting: while running
ruff formatI accidentally reformatted a few lines intorchTextClassifiers.py(someassertstatements). 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 2after PR 1 is merged, or tell me to stack it on this branch.· Branch:
claude/issue-109-20261124-1343