source
stringclasses 40
values | file_type
stringclasses 1
value | chunk
stringlengths 3
512
| id
int64 0
1.5k
|
---|---|---|---|
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | <!--⚠️ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
--> | 1,100 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | The Hugging Face Hub makes hosting and sharing models with the community easy. It supports
[dozens of libraries](https://huggingface.co/docs/hub/models-libraries) in the Open Source ecosystem. We are always
working on expanding this support to push collaborative Machine Learning forward. The `huggingface_hub` library plays a
key role in this process, allowing any Python script to easily push and load files.
There are four main ways to integrate a library with the Hub: | 1,101 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | There are four main ways to integrate a library with the Hub:
1. **Push to Hub:** implement a method to upload a model to the Hub. This includes the model weights, as well as
[the model card](https://huggingface.co/docs/huggingface_hub/how-to-model-cards) and any other relevant information
or data necessary to run the model (for example, training logs). This method is often called `push_to_hub()`. | 1,102 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | or data necessary to run the model (for example, training logs). This method is often called `push_to_hub()`.
2. **Download from Hub:** implement a method to load a model from the Hub. The method should download the model
configuration/weights and load the model. This method is often called `from_pretrained` or `load_from_hub()`.
3. **Inference API:** use our servers to run inference on models supported by your library for free. | 1,103 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | 3. **Inference API:** use our servers to run inference on models supported by your library for free.
4. **Widgets:** display a widget on the landing page of your models on the Hub. It allows users to quickly try a model
from the browser.
In this guide, we will focus on the first two topics. We will present the two main approaches you can use to integrate
a library, with their advantages and drawbacks. Everything is summarized at the end of the guide to help you choose | 1,104 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | a library, with their advantages and drawbacks. Everything is summarized at the end of the guide to help you choose
between the two. Please keep in mind that these are only guidelines that you are free to adapt to you requirements.
If you are interested in Inference and Widgets, you can follow [this guide](https://huggingface.co/docs/hub/models-adding-libraries#set-up-the-inference-api).
In both cases, you can reach out to us if you are integrating a library with the Hub and want to be listed | 1,105 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | In both cases, you can reach out to us if you are integrating a library with the Hub and want to be listed
[in our docs](https://huggingface.co/docs/hub/models-libraries). | 1,106 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | The first approach to integrate a library to the Hub is to actually implement the `push_to_hub` and `from_pretrained`
methods by yourself. This gives you full flexibility on which files you need to upload/download and how to handle inputs
specific to your framework. You can refer to the two [upload files](./upload) and [download files](./download) guides
to learn more about how to do that. This is, for example how the FastAI integration is implemented (see [`push_to_hub_fastai`] | 1,107 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | to learn more about how to do that. This is, for example how the FastAI integration is implemented (see [`push_to_hub_fastai`]
and [`from_pretrained_fastai`]).
Implementation can differ between libraries, but the workflow is often similar. | 1,108 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | This is how a `from_pretrained` method usually looks like:
```python
def from_pretrained(model_id: str) -> MyModelClass:
# Download model from Hub
cached_model = hf_hub_download(
repo_id=repo_id,
filename="model.pkl",
library_name="fastai",
library_version=get_fastai_version(),
)
# Load model
return load_model(cached_model)
``` | 1,109 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | The `push_to_hub` method often requires a bit more complexity to handle repo creation, generate the model card and save weights.
A common approach is to save all of these files in a temporary folder, upload it and then delete it.
```python
def push_to_hub(model: MyModelClass, repo_name: str) -> None:
api = HfApi()
# Create repo if not existing yet and get the associated repo_id
repo_id = api.create_repo(repo_name, exist_ok=True) | 1,110 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | # Create repo if not existing yet and get the associated repo_id
repo_id = api.create_repo(repo_name, exist_ok=True)
# Save all files in a temporary directory and push them in a single commit
with TemporaryDirectory() as tmpdir:
tmpdir = Path(tmpdir)
# Save weights
save_model(model, tmpdir / "model.safetensors")
# Generate model card
card = generate_model_card(model)
(tmpdir / "README.md").write_text(card)
# Save logs
# Save figures
# Save evaluation metrics
# ... | 1,111 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | # Save logs
# Save figures
# Save evaluation metrics
# ...
# Push to hub
return api.upload_folder(repo_id=repo_id, folder_path=tmpdir)
```
This is of course only an example. If you are interested in more complex manipulations (delete remote files, upload
weights on the fly, persist weights locally, etc.) please refer to the [upload files](./upload) guide. | 1,112 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | While being flexible, this approach has some drawbacks, especially in terms of maintenance. Hugging Face users are often
used to additional features when working with `huggingface_hub`. For example, when loading files from the Hub, it is
common to offer parameters like:
- `token`: to download from a private repo
- `revision`: to download from a specific branch
- `cache_dir`: to cache files in a specific directory
- `force_download`/`local_files_only`: to reuse the cache or not | 1,113 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | - `cache_dir`: to cache files in a specific directory
- `force_download`/`local_files_only`: to reuse the cache or not
- `proxies`: configure HTTP session
When pushing models, similar parameters are supported:
- `commit_message`: custom commit message
- `private`: create a private repo if missing
- `create_pr`: create a PR instead of pushing to `main`
- `branch`: push to a branch instead of the `main` branch
- `allow_patterns`/`ignore_patterns`: filter which files to upload
- `token`
- ... | 1,114 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | - `allow_patterns`/`ignore_patterns`: filter which files to upload
- `token`
- ...
All of these parameters can be added to the implementations we saw above and passed to the `huggingface_hub` methods.
However, if a parameter changes or a new feature is added, you will need to update your package. Supporting those
parameters also means more documentation to maintain on your side. To see how to mitigate these limitations, let's jump
to our next section **class inheritance**. | 1,115 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | As we saw above, there are two main methods to include in your library to integrate it with the Hub: upload files
(`push_to_hub`) and download files (`from_pretrained`). You can implement those methods by yourself but it comes with
caveats. To tackle this, `huggingface_hub` provides a tool that uses class inheritance. Let's see how it works!
In a lot of cases, a library already implements its model using a Python class. The class contains the properties of | 1,116 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | In a lot of cases, a library already implements its model using a Python class. The class contains the properties of
the model and methods to load, run, train, and evaluate it. Our approach is to extend this class to include upload and
download features using mixins. A [Mixin](https://stackoverflow.com/a/547714) is a class that is meant to extend an
existing class with a set of specific features using multiple inheritance. `huggingface_hub` provides its own mixin, | 1,117 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | existing class with a set of specific features using multiple inheritance. `huggingface_hub` provides its own mixin,
the [`ModelHubMixin`]. The key here is to understand its behavior and how to customize it.
The [`ModelHubMixin`] class implements 3 *public* methods (`push_to_hub`, `save_pretrained` and `from_pretrained`). Those
are the methods that your users will call to load/save models with your library. [`ModelHubMixin`] also defines 2 | 1,118 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | are the methods that your users will call to load/save models with your library. [`ModelHubMixin`] also defines 2
*private* methods (`_save_pretrained` and `_from_pretrained`). Those are the ones you must implement. So to integrate
your library, you should:
1. Make your Model class inherit from [`ModelHubMixin`].
2. Implement the private methods:
- [`~ModelHubMixin._save_pretrained`]: method taking as input a path to a directory and saving the model to it. | 1,119 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | - [`~ModelHubMixin._save_pretrained`]: method taking as input a path to a directory and saving the model to it.
You must write all the logic to dump your model in this method: model card, model weights, configuration files,
training logs, and figures. Any relevant information for this model must be handled by this method.
[Model Cards](https://huggingface.co/docs/hub/model-cards) are particularly important to describe your model. Check
out [our implementation guide](./model-cards) for more details. | 1,120 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | out [our implementation guide](./model-cards) for more details.
- [`~ModelHubMixin._from_pretrained`]: **class method** taking as input a `model_id` and returning an instantiated
model. The method must download the relevant files and load them.
3. You are done! | 1,121 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | 3. You are done!
The advantage of using [`ModelHubMixin`] is that once you take care of the serialization/loading of the files, you are ready to go. You don't need to worry about stuff like repo creation, commits, PRs, or revisions. The [`ModelHubMixin`] also ensures public methods are documented and type annotated, and you'll be able to view your model's download count on the Hub. All of this is handled by the [`ModelHubMixin`] and available to your users. | 1,122 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | A good example of what we saw above is [`PyTorchModelHubMixin`], our integration for the PyTorch framework. This is a ready-to-use integration. | 1,123 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | Here is how any user can load/save a PyTorch model from/to the Hub:
```python
>>> import torch
>>> import torch.nn as nn
>>> from huggingface_hub import PyTorchModelHubMixin | 1,124 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | # Define your Pytorch model exactly the same way you are used to
>>> class MyModel(
... nn.Module,
... PyTorchModelHubMixin, # multiple inheritance
... library_name="keras-nlp",
... tags=["keras"],
... repo_url="https://github.com/keras-team/keras-nlp",
... docs_url="https://keras.io/keras_nlp/",
... # ^ optional metadata to generate model card
... ): | 1,125 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | ... docs_url="https://keras.io/keras_nlp/",
... # ^ optional metadata to generate model card
... ):
... def __init__(self, hidden_size: int = 512, vocab_size: int = 30000, output_size: int = 4):
... super().__init__()
... self.param = nn.Parameter(torch.rand(hidden_size, vocab_size))
... self.linear = nn.Linear(output_size, vocab_size) | 1,126 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | ... def forward(self, x):
... return self.linear(x + self.param)
# 1. Create model
>>> model = MyModel(hidden_size=128)
# Config is automatically created based on input + default values
>>> model.param.shape[0]
128
# 2. (optional) Save model to local directory
>>> model.save_pretrained("path/to/my-awesome-model")
# 3. Push model weights to the Hub
>>> model.push_to_hub("my-awesome-model") | 1,127 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | # 3. Push model weights to the Hub
>>> model.push_to_hub("my-awesome-model")
# 4. Initialize model from the Hub => config has been preserved
>>> model = MyModel.from_pretrained("username/my-awesome-model")
>>> model.param.shape[0]
128
# Model card has been correctly populated
>>> from huggingface_hub import ModelCard
>>> card = ModelCard.load("username/my-awesome-model")
>>> card.data.tags
["keras", "pytorch_model_hub_mixin", "model_hub_mixin"]
>>> card.data.library_name
"keras-nlp"
``` | 1,128 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | The implementation is actually very straightforward, and the full implementation can be found [here](https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/hub_mixin.py).
1. First, inherit your class from `ModelHubMixin`:
```python
from huggingface_hub import ModelHubMixin
class PyTorchModelHubMixin(ModelHubMixin):
(...)
```
2. Implement the `_save_pretrained` method:
```py
from huggingface_hub import ModelHubMixin
class PyTorchModelHubMixin(ModelHubMixin):
(...) | 1,129 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | class PyTorchModelHubMixin(ModelHubMixin):
(...)
def _save_pretrained(self, save_directory: Path) -> None:
"""Save weights from a Pytorch model to a local directory."""
save_model_as_safetensor(self.module, str(save_directory / SAFETENSORS_SINGLE_FILE))
```
3. Implement the `_from_pretrained` method:
```python
class PyTorchModelHubMixin(ModelHubMixin):
(...) | 1,130 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | @classmethod # Must be a classmethod!
def _from_pretrained(
cls,
*,
model_id: str,
revision: str,
cache_dir: str,
force_download: bool,
proxies: Optional[Dict],
resume_download: bool,
local_files_only: bool,
token: Union[str, bool, None],
map_location: str = "cpu", # additional argument
strict: bool = False, # additional argument
**model_kwargs,
):
"""Load Pytorch pretrained weights and return the loaded model."""
model = cls(**model_kwargs)
if os.path.isdir(model_id): | 1,131 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | ):
"""Load Pytorch pretrained weights and return the loaded model."""
model = cls(**model_kwargs)
if os.path.isdir(model_id):
print("Loading weights from local directory")
model_file = os.path.join(model_id, SAFETENSORS_SINGLE_FILE)
return cls._load_as_safetensor(model, model_file, map_location, strict) | 1,132 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | model_file = hf_hub_download(
repo_id=model_id,
filename=SAFETENSORS_SINGLE_FILE,
revision=revision,
cache_dir=cache_dir,
force_download=force_download,
proxies=proxies,
resume_download=resume_download,
token=token,
local_files_only=local_files_only,
)
return cls._load_as_safetensor(model, model_file, map_location, strict)
```
And that's it! Your library now enables users to upload and download files to and from the Hub. | 1,133 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | In the section above, we quickly discussed how the [`ModelHubMixin`] works. In this section, we will see some of its more advanced features to improve your library integration with the Hugging Face Hub. | 1,134 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | [`ModelHubMixin`] generates the model card for you. Model cards are files that accompany the models and provide important information about them. Under the hood, model cards are simple Markdown files with additional metadata. Model cards are essential for discoverability, reproducibility, and sharing! Check out the [Model Cards guide](https://huggingface.co/docs/hub/model-cards) for more details. | 1,135 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | Generating model cards semi-automatically is a good way to ensure that all models pushed with your library will share common metadata: `library_name`, `tags`, `license`, `pipeline_tag`, etc. This makes all models backed by your library easily searchable on the Hub and provides some resource links for users landing on the Hub. You can define the metadata directly when inheriting from [`ModelHubMixin`]:
```py
class UniDepthV1(
nn.Module,
PyTorchModelHubMixin,
library_name="unidepth", | 1,136 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | ```py
class UniDepthV1(
nn.Module,
PyTorchModelHubMixin,
library_name="unidepth",
repo_url="https://github.com/lpiccinelli-eth/UniDepth",
docs_url=...,
pipeline_tag="depth-estimation",
license="cc-by-nc-4.0",
tags=["monocular-metric-depth-estimation", "arxiv:1234.56789"]
):
...
``` | 1,137 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | license="cc-by-nc-4.0",
tags=["monocular-metric-depth-estimation", "arxiv:1234.56789"]
):
...
```
By default, a generic model card will be generated with the info you've provided (example: [pyp1/VoiceCraft_giga830M](https://huggingface.co/pyp1/VoiceCraft_giga830M)). But you can define your own model card template as well! | 1,138 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | In this example, all models pushed with the `VoiceCraft` class will automatically include a citation section and license details. For more details on how to define a model card template, please check the [Model Cards guide](./model-cards).
```py
MODEL_CARD_TEMPLATE = """
---
# For reference on model card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1
# Doc / guide: https://huggingface.co/docs/hub/model-cards
{{ card_data }}
--- | 1,139 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | This is a VoiceCraft model. For more details, please check out the official Github repo: https://github.com/jasonppy/VoiceCraft. This model is shared under a Attribution-NonCommercial-ShareAlike 4.0 International license.
## Citation
@article{peng2024voicecraft,
author = {Peng, Puyuan and Huang, Po-Yao and Li, Daniel and Mohamed, Abdelrahman and Harwath, David},
title = {VoiceCraft: Zero-Shot Speech Editing and Text-to-Speech in the Wild},
journal = {arXiv},
year = {2024},
}
""" | 1,140 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | class VoiceCraft(
nn.Module,
PyTorchModelHubMixin,
library_name="voicecraft",
model_card_template=MODEL_CARD_TEMPLATE,
...
):
...
```
Finally, if you want to extend the model card generation process with dynamic values, you can override the [`~ModelHubMixin.generate_model_card`] method:
```py
from huggingface_hub import ModelCard, PyTorchModelHubMixin
class UniDepthV1(nn.Module, PyTorchModelHubMixin, ...):
(...) | 1,141 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | class UniDepthV1(nn.Module, PyTorchModelHubMixin, ...):
(...)
def generate_model_card(self, *args, **kwargs) -> ModelCard:
card = super().generate_model_card(*args, **kwargs)
card.data.metrics = ... # add metrics to the metadata
card.text += ... # append section to the modelcard
return card
``` | 1,142 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | [`ModelHubMixin`] handles the model configuration for you. It automatically checks the input values when you instantiate the model and serializes them in a `config.json` file. This provides 2 benefits:
1. Users will be able to reload the model with the exact same parameters as you.
2. Having a `config.json` file automatically enables analytics on the Hub (i.e. the "downloads" count).
But how does it work in practice? Several rules make the process as smooth as possible from a user perspective: | 1,143 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | But how does it work in practice? Several rules make the process as smooth as possible from a user perspective:
- if your `__init__` method expects a `config` input, it will be automatically saved in the repo as `config.json`.
- if the `config` input parameter is annotated with a dataclass type (e.g. `config: Optional[MyConfigClass] = None`), then the `config` value will be correctly deserialized for you. | 1,144 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | - all values passed at initialization will also be stored in the config file. This means you don't necessarily have to expect a `config` input to benefit from it.
Example:
```py
class MyModel(ModelHubMixin):
def __init__(value: str, size: int = 3):
self.value = value
self.size = size | 1,145 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | (...) # implement _save_pretrained / _from_pretrained
model = MyModel(value="my_value")
model.save_pretrained(...) | 1,146 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | # config.json contains passed and default values
{"value": "my_value", "size": 3}
``` | 1,147 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | But what if a value cannot be serialized as JSON? By default, the value will be ignored when saving the config file. However, in some cases your library already expects a custom object as input that cannot be serialized, and you don't want to update your internal logic to update its type. No worries! You can pass custom encoders/decoders for any type when inheriting from [`ModelHubMixin`]. This is a bit more work but ensures your internal logic is untouched when integrating your library with the Hub. | 1,148 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | Here is a concrete example where a class expects a `argparse.Namespace` config as input:
```py
class VoiceCraft(nn.Module):
def __init__(self, args):
self.pattern = self.args.pattern
self.hidden_size = self.args.hidden_size
...
```
One solution can be to update the `__init__` signature to `def __init__(self, pattern: str, hidden_size: int)` and update all snippets that instantiate your class. This is a perfectly valid way to fix it but it might break downstream applications using your library. | 1,149 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | Another solution is to provide a simple encoder/decoder to convert `argparse.Namespace` to a dictionary.
```py
from argparse import Namespace | 1,150 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | class VoiceCraft(
nn.Module,
PyTorchModelHubMixin, # inherit from mixin
coders={
Namespace : (
lambda x: vars(x), # Encoder: how to convert a `Namespace` to a valid jsonable value?
lambda data: Namespace(**data), # Decoder: how to reconstruct a `Namespace` from a dictionary?
)
}
):
def __init__(self, args: Namespace): # annotate `args`
self.pattern = self.args.pattern
self.hidden_size = self.args.hidden_size
...
``` | 1,151 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | self.pattern = self.args.pattern
self.hidden_size = self.args.hidden_size
...
```
In the snippet above, both the internal logic and the `__init__` signature of the class did not change. This means all existing code snippets for your library will continue to work. To achieve this, we had to:
1. Inherit from the mixin (`PytorchModelHubMixin` in this case). | 1,152 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | 1. Inherit from the mixin (`PytorchModelHubMixin` in this case).
2. Pass a `coders` parameter in the inheritance. This is a dictionary where keys are custom types you want to process. Values are a tuple `(encoder, decoder)`.
- The encoder expects an object of the specified type as input and returns a jsonable value. This will be used when saving a model with `save_pretrained`. | 1,153 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | - The decoder expects raw data (typically a dictionary) as input and reconstructs the initial object. This will be used when loading the model with `from_pretrained`.
3. Add a type annotation to the `__init__` signature. This is important to let the mixin know which type is expected by the class and, therefore, which decoder to use. | 1,154 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | For the sake of simplicity, the encoder/decoder functions in the example above are not robust. For a concrete implementation, you would most likely have to handle corner cases properly. | 1,155 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | Let's quickly sum up the two approaches we saw with their advantages and drawbacks. The table below is only indicative.
Your framework might have some specificities that you need to address. This guide is only here to give guidelines and
ideas on how to handle integration. In any case, feel free to contact us if you have any questions!
<!-- Generated using https://www.tablesgenerator.com/markdown_tables -->
| Integration | Using helpers | Using [`ModelHubMixin`] |
|:---:|:---:|:---:| | 1,156 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | | Integration | Using helpers | Using [`ModelHubMixin`] |
|:---:|:---:|:---:|
| User experience | `model = load_from_hub(...)`<br>`push_to_hub(model, ...)` | `model = MyModel.from_pretrained(...)`<br>`model.push_to_hub(...)` |
| Flexibility | Very flexible.<br>You fully control the implementation. | Less flexible.<br>Your framework must have a model class. | | 1,157 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | | Maintenance | More maintenance to add support for configuration, and new features. Might also require fixing issues reported by users. | Less maintenance as most of the interactions with the Hub are implemented in `huggingface_hub`. |
| Documentation / Type annotation | To be written manually. | Partially handled by `huggingface_hub`. |
| Download counter | To be handled manually. | Enabled by default if class has a `config` attribute. | | 1,158 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/integrations.md | .md | | Download counter | To be handled manually. | Enabled by default if class has a `config` attribute. |
| Model card | To be handled manually | Generated by default with library_name, tags, etc. | | 1,159 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/hf_file_system.md | .md | <!--⚠️ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
--> | 1,160 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/hf_file_system.md | .md | In addition to the [`HfApi`], the `huggingface_hub` library provides [`HfFileSystem`], a pythonic [fsspec-compatible](https://filesystem-spec.readthedocs.io/en/latest/) file interface to the Hugging Face Hub. The [`HfFileSystem`] builds on top of the [`HfApi`] and offers typical filesystem style operations like `cp`, `mv`, `ls`, `du`, `glob`, `get_file`, and `put_file`.
<Tip warning={true}>
[`HfFileSystem`] provides fsspec compatibility, which is useful for libraries that require it (e.g., reading | 1,161 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/hf_file_system.md | .md | [`HfFileSystem`] provides fsspec compatibility, which is useful for libraries that require it (e.g., reading
Hugging Face datasets directly with `pandas`). However, it introduces additional overhead due to this compatibility
layer. For better performance and reliability, it's recommended to use [`HfApi`] methods when possible.
</Tip> | 1,162 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/hf_file_system.md | .md | ```python
>>> from huggingface_hub import HfFileSystem
>>> fs = HfFileSystem()
>>> # List all files in a directory
>>> fs.ls("datasets/my-username/my-dataset-repo/data", detail=False)
['datasets/my-username/my-dataset-repo/data/train.csv', 'datasets/my-username/my-dataset-repo/data/test.csv']
>>> # List all ".csv" files in a repo
>>> fs.glob("datasets/my-username/my-dataset-repo/**/*.csv")
['datasets/my-username/my-dataset-repo/data/train.csv', 'datasets/my-username/my-dataset-repo/data/test.csv'] | 1,163 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/hf_file_system.md | .md | >>> # Read a remote file
>>> with fs.open("datasets/my-username/my-dataset-repo/data/train.csv", "r") as f:
... train_data = f.readlines()
>>> # Read the content of a remote file as a string
>>> train_data = fs.read_text("datasets/my-username/my-dataset-repo/data/train.csv", revision="dev") | 1,164 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/hf_file_system.md | .md | >>> # Write a remote file
>>> with fs.open("datasets/my-username/my-dataset-repo/data/validation.csv", "w") as f:
... f.write("text,label")
... f.write("Fantastic movie!,good")
```
The optional `revision` argument can be passed to run an operation from a specific commit such as a branch, tag name, or a commit hash. | 1,165 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/hf_file_system.md | .md | Unlike Python's built-in `open`, `fsspec`'s `open` defaults to binary mode, `"rb"`. This means you must explicitly set mode as `"r"` for reading and `"w"` for writing in text mode. Appending to a file (modes `"a"` and `"ab"`) is not supported yet. | 1,166 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/hf_file_system.md | .md | The [`HfFileSystem`] can be used with any library that integrates `fsspec`, provided the URL follows the scheme:
```
hf://[<repo_type_prefix>]<repo_id>[@<revision>]/<path/in/repo>
```
<div class="flex justify-center">
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/huggingface_hub/hf_urls.png"/>
</div>
The `repo_type_prefix` is `datasets/` for datasets, `spaces/` for spaces, and models don't need a prefix in the URL. | 1,167 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/hf_file_system.md | .md | </div>
The `repo_type_prefix` is `datasets/` for datasets, `spaces/` for spaces, and models don't need a prefix in the URL.
Some interesting integrations where [`HfFileSystem`] simplifies interacting with the Hub are listed below:
* Reading/writing a [Pandas](https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#reading-writing-remote-files) DataFrame from/to a Hub repository:
```python
>>> import pandas as pd | 1,168 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/hf_file_system.md | .md | >>> # Read a remote CSV file into a dataframe
>>> df = pd.read_csv("hf://datasets/my-username/my-dataset-repo/train.csv") | 1,169 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/hf_file_system.md | .md | >>> # Write a dataframe to a remote CSV file
>>> df.to_csv("hf://datasets/my-username/my-dataset-repo/test.csv")
```
The same workflow can also be used for [Dask](https://docs.dask.org/en/stable/how-to/connect-to-remote-data.html) and [Polars](https://pola-rs.github.io/polars/py-polars/html/reference/io.html) DataFrames.
* Querying (remote) Hub files with [DuckDB](https://duckdb.org/docs/guides/python/filesystems):
```python
>>> from huggingface_hub import HfFileSystem
>>> import duckdb | 1,170 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/hf_file_system.md | .md | >>> fs = HfFileSystem()
>>> duckdb.register_filesystem(fs)
>>> # Query a remote file and get the result back as a dataframe
>>> fs_query_file = "hf://datasets/my-username/my-dataset-repo/data_dir/data.parquet"
>>> df = duckdb.query(f"SELECT * FROM '{fs_query_file}' LIMIT 10").df()
```
* Using the Hub as an array store with [Zarr](https://zarr.readthedocs.io/en/stable/tutorial.html#io-with-fsspec):
```python
>>> import numpy as np
>>> import zarr | 1,171 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/hf_file_system.md | .md | >>> embeddings = np.random.randn(50000, 1000).astype("float32")
>>> # Write an array to a repo
>>> with zarr.open_group("hf://my-username/my-model-repo/array-store", mode="w") as root:
... foo = root.create_group("embeddings")
... foobar = foo.zeros('experiment_0', shape=(50000, 1000), chunks=(10000, 1000), dtype='f4')
... foobar[:] = embeddings | 1,172 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/hf_file_system.md | .md | >>> # Read an array from a repo
>>> with zarr.open_group("hf://my-username/my-model-repo/array-store", mode="r") as root:
... first_row = root["embeddings/experiment_0"][0]
``` | 1,173 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/hf_file_system.md | .md | In many cases, you must be logged in with a Hugging Face account to interact with the Hub. Refer to the [Authentication](../quick-start#authentication) section of the documentation to learn more about authentication methods on the Hub.
It is also possible to log in programmatically by passing your `token` as an argument to [`HfFileSystem`]:
```python
>>> from huggingface_hub import HfFileSystem
>>> fs = HfFileSystem(token=token)
``` | 1,174 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/hf_file_system.md | .md | ```python
>>> from huggingface_hub import HfFileSystem
>>> fs = HfFileSystem(token=token)
```
If you log in this way, be careful not to accidentally leak the token when sharing your source code! | 1,175 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | <!--⚠️ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
--> | 1,176 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | Webhooks are a foundation for MLOps-related features. They allow you to listen for new changes on specific repos or to all repos belonging to particular users/organizations you're interested in following. This guide will first explain how to manage webhooks programmatically. Then we'll see how to leverage `huggingface_hub` to create a server listening to webhooks and deploy it to a Space. | 1,177 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | This guide assumes you are familiar with the concept of webhooks on the Huggingface Hub. To learn more about webhooks themselves, you should read this [guide](https://huggingface.co/docs/hub/webhooks) first. | 1,178 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | `huggingface_hub` allows you to manage your webhooks programmatically. You can list your existing webhooks, create new ones, and update, enable, disable or delete them. This section guides you through the procedures using the Hugging Face Hub's API functions. | 1,179 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | To create a new webhook, use [`create_webhook`] and specify the URL where payloads should be sent, what events should be watched, and optionally set a domain and a secret for security.
```python
from huggingface_hub import create_webhook
# Example: Creating a webhook
webhook = create_webhook(
url="https://webhook.site/your-custom-url",
watched=[{"type": "user", "name": "your-username"}, {"type": "org", "name": "your-org-name"}],
domains=["repo", "discussion"],
secret="your-secret"
)
``` | 1,180 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | To see all the webhooks you have configured, you can list them with [`list_webhooks`]. This is useful to review their IDs, URLs, and statuses.
```python
from huggingface_hub import list_webhooks
# Example: Listing all webhooks
webhooks = list_webhooks()
for webhook in webhooks:
print(webhook)
``` | 1,181 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | If you need to change the configuration of an existing webhook, such as the URL or the events it watches, you can update it using [`update_webhook`].
```python
from huggingface_hub import update_webhook
# Example: Updating a webhook
updated_webhook = update_webhook(
webhook_id="your-webhook-id",
url="https://new.webhook.site/url",
watched=[{"type": "user", "name": "new-username"}],
domains=["repo"]
)
``` | 1,182 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | You might want to temporarily disable a webhook without deleting it. This can be done using [`disable_webhook`], and the webhook can be re-enabled later with [`enable_webhook`].
```python
from huggingface_hub import enable_webhook, disable_webhook
# Example: Enabling a webhook
enabled_webhook = enable_webhook("your-webhook-id")
print("Enabled:", enabled_webhook)
# Example: Disabling a webhook
disabled_webhook = disable_webhook("your-webhook-id")
print("Disabled:", disabled_webhook)
``` | 1,183 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | When a webhook is no longer needed, it can be permanently deleted using [`delete_webhook`].
```python
from huggingface_hub import delete_webhook
# Example: Deleting a webhook
delete_webhook("your-webhook-id")
``` | 1,184 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | The base class that we will use in this guides section is [`WebhooksServer`]. It is a class for easily configuring a server that
can receive webhooks from the Huggingface Hub. The server is based on a [Gradio](https://gradio.app/) app. It has a UI
to display instructions for you or your users and an API to listen to webhooks.
<Tip>
To see a running example of a webhook server, check out the [Spaces CI Bot](https://huggingface.co/spaces/spaces-ci-bot/webhook) | 1,185 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | one. It is a Space that launches ephemeral environments when a PR is opened on a Space.
</Tip>
<Tip warning={true}>
This is an [experimental feature](../package_reference/environment_variables#hfhubdisableexperimentalwarning). This
means that we are still working on improving the API. Breaking changes might be introduced in the future without prior
notice. Make sure to pin the version of `huggingface_hub` in your requirements.
</Tip> | 1,186 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | Implementing a webhook endpoint is as simple as decorating a function. Let's see a first example to explain the main
concepts:
```python
# app.py
from huggingface_hub import webhook_endpoint, WebhookPayload | 1,187 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | @webhook_endpoint
async def trigger_training(payload: WebhookPayload) -> None:
if payload.repo.type == "dataset" and payload.event.action == "update":
# Trigger a training job if a dataset is updated
...
```
Save this snippet in a file called `'app.py'` and run it with `'python app.py'`. You should see a message like this:
```text
Webhook secret is not defined. This means your webhook endpoints will be open to everyone. | 1,188 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | ```text
Webhook secret is not defined. This means your webhook endpoints will be open to everyone.
To add a secret, set `WEBHOOK_SECRET` as environment variable or pass it at initialization:
`app = WebhooksServer(webhook_secret='my_secret', ...)`
For more details about webhook secrets, please refer to https://huggingface.co/docs/hub/webhooks#webhook-secret.
Running on local URL: http://127.0.0.1:7860
Running on public URL: https://1fadb0f52d8bf825fc.gradio.live | 1,189 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | This share link expires in 72 hours. For free permanent hosting and GPU upgrades (NEW!), check out Spaces: https://huggingface.co/spaces | 1,190 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | Webhooks are correctly setup and ready to use:
- POST https://1fadb0f52d8bf825fc.gradio.live/webhooks/trigger_training
Go to https://huggingface.co/settings/webhooks to setup your webhooks.
```
Good job! You just launched a webhook server! Let's break down what happened exactly:
1. By decorating a function with [`webhook_endpoint`], a [`WebhooksServer`] object has been created in the background. | 1,191 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | 1. By decorating a function with [`webhook_endpoint`], a [`WebhooksServer`] object has been created in the background.
As you can see, this server is a Gradio app running on http://127.0.0.1:7860. If you open this URL in your browser, you
will see a landing page with instructions about the registered webhooks.
2. A Gradio app is a FastAPI server under the hood. A new POST route `/webhooks/trigger_training` has been added to it. | 1,192 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | 2. A Gradio app is a FastAPI server under the hood. A new POST route `/webhooks/trigger_training` has been added to it.
This is the route that will listen to webhooks and run the `trigger_training` function when triggered. FastAPI will
automatically parse the payload and pass it to the function as a [`WebhookPayload`] object. This is a `pydantic` object
that contains all the information about the event that triggered the webhook. | 1,193 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | that contains all the information about the event that triggered the webhook.
3. The Gradio app also opened a tunnel to receive requests from the internet. This is the interesting part: you can
configure a Webhook on https://huggingface.co/settings/webhooks pointing to your local machine. This is useful for
debugging your webhook server and quickly iterating before deploying it to a Space.
4. Finally, the logs also tell you that your server is currently not secured by a secret. This is not problematic for | 1,194 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | 4. Finally, the logs also tell you that your server is currently not secured by a secret. This is not problematic for
local debugging but is to keep in mind for later.
<Tip warning={true}>
By default, the server is started at the end of your script. If you are running it in a notebook, you can start the
server manually by calling `decorated_function.run()`. Since a unique server is used, you only have to start the server
once even if you have multiple endpoints.
</Tip> | 1,195 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | Now that you have a webhook server running, you want to configure a Webhook to start receiving messages.
Go to https://huggingface.co/settings/webhooks, click on "Add a new webhook" and configure your Webhook. Set the target
repositories you want to watch and the Webhook URL, here `https://1fadb0f52d8bf825fc.gradio.live/webhooks/trigger_training`.
<div class="flex justify-center">
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hub/configure_webhook.png"/>
</div> | 1,196 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hub/configure_webhook.png"/>
</div>
And that's it! You can now trigger that webhook by updating the target repository (e.g. push a commit). Check the
Activity tab of your Webhook to see the events that have been triggered. Now that you have a working setup, you can
test it and quickly iterate. If you modify your code and restart the server, your public URL might change. Make sure | 1,197 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | test it and quickly iterate. If you modify your code and restart the server, your public URL might change. Make sure
to update the webhook configuration on the Hub if needed. | 1,198 |
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/docs/source/en/guides/webhooks.md | .md | Now that you have a working webhook server, the goal is to deploy it to a Space. Go to https://huggingface.co/new-space
to create a Space. Give it a name, select the Gradio SDK and click on "Create Space". Upload your code to the Space
in a file called `app.py`. Your Space will start automatically! For more details about Spaces, please refer to this
[guide](https://huggingface.co/docs/hub/spaces-overview). | 1,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.