From b5293cfcca39cce19959ce95bf2b914757d2d0fd Mon Sep 17 00:00:00 2001 From: "Chulhwa (Evan) Han" Date: Thu, 11 Apr 2024 12:49:39 +0000 Subject: [PATCH 01/13] docs: ko: guides/integrations.md --- docs/source/ko/_toctree.yml | 4 +- docs/source/ko/guides/integrations.md | 297 ++++++++++++++++++++++++++ 2 files changed, 299 insertions(+), 2 deletions(-) create mode 100644 docs/source/ko/guides/integrations.md diff --git a/docs/source/ko/_toctree.yml b/docs/source/ko/_toctree.yml index a9e81fb126..f5a15a7f47 100644 --- a/docs/source/ko/_toctree.yml +++ b/docs/source/ko/_toctree.yml @@ -32,8 +32,8 @@ title: 모델 카드 - local: in_translation title: (번역 중) Manage your Space - - local: in_translation - title: (번역 중) Integrate a library + - local: guides/integrations + title: 라이브러리 통합 - local: in_translation title: (번역 중) Webhooks server - title: "(번역 중) 개념 가이드" diff --git a/docs/source/ko/guides/integrations.md b/docs/source/ko/guides/integrations.md new file mode 100644 index 0000000000..d3f6c26658 --- /dev/null +++ b/docs/source/ko/guides/integrations.md @@ -0,0 +1,297 @@ + + +# Integrate any ML framework with the Hub + +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. **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()`. +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. +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 +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 +[in our docs](https://huggingface.co/docs/hub/models-libraries). + +## A flexible approach: helpers + +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`] +and [`from_pretrained_fastai`]). + +Implementation can differ between libraries, but the workflow is often similar. + +### from_pretrained + +This is how a `from_pretrained` method usually look 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) +``` + +### push_to_hub + +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) + + # 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 + # ... + + # 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. + +### Limitations + +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`/`resume_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` +- ... + +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**. + +## A more complex approach: class inheritance + +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 +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, +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 +*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. + 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. + - [`~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! + +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. All of this is handled by the mixin and is available to your users. The Mixin also ensures that public methods are well documented and type annotated. + +As a bonus, [`ModelHubMixin`] handles the model configuration for you. If your `__init__` method expects a `config` input, it will be automatically saved in the repo when calling `save_pretrained` and reloaded correctly by `load_pretrained`. Moreover, if the `config` input parameter is annotated with dataclass type (e.g. `config: Optional[MyConfigClass] = None`), then the `config` value will be correctly deserialized for you. Finally, all jsonable values passed at initialization will be also stored in the config file. This means you don't necessarily have to expect a `config` input to benefit from it. The big advantage of having a `config.json` file in your model repository is that it automatically enables the analytics on the Hub (e.g. the "downloads" count). + +Finally, [`ModelHubMixin`] handles generating a model card for you. When inheriting from [`ModelHubMixin`], you can define metadata such as `library_name`, `tags`, `repo_url` and `docs_url`. Those fields will be reused to populate the modelcard of any model that use your class. This is very practical to make all models using your library easily searchable on the Hub and to provide some resource links for users landing on the Hub. If you want to extend the modelcard template, you can override the [`~ModelHubMixin.generate_model_card`] method. + +### A concrete example: PyTorch + +A good example of what we saw above is [`PyTorchModelHubMixin`], our integration for the PyTorch framework. This is a ready-to-use integration. + +#### How to use it? + +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 + + +# 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 +... ): +... 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) + +... 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") + +# 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" +``` + +#### Implementation + +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): + (...) + + 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): + (...) + + @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): + 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) + + 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. + +## Quick comparison + +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! + + +| Integration | Using helpers | Using [`ModelHubMixin`] | +|:---:|:---:|:---:| +| User experience | `model = load_from_hub(...)`
`push_to_hub(model, ...)` | `model = MyModel.from_pretrained(...)`
`model.push_to_hub(...)` | +| Flexibility | Very flexible.
You fully control the implementation. | Less flexible.
Your framework must have a model class. | +| 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. | +| Model card | To be handled manually | Generated by default with library_name, tags, etc. | From 36a9c9dbe66e14ad82e82855b8f4ee3f97708a89 Mon Sep 17 00:00:00 2001 From: "Chulhwa (Evan) Han" Date: Fri, 19 Apr 2024 06:31:36 +0000 Subject: [PATCH 02/13] feat: nmt draft --- docs/source/ko/guides/integrations.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/source/ko/guides/integrations.md b/docs/source/ko/guides/integrations.md index d3f6c26658..08b4ac4cfb 100644 --- a/docs/source/ko/guides/integrations.md +++ b/docs/source/ko/guides/integrations.md @@ -2,7 +2,7 @@ rendered properly in your Markdown viewer. --> -# Integrate any ML framework with the Hub +# Integrate any ML framework with the Hub[[integrate-any-ml-framework-with-the-hub]] 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 @@ -27,7 +27,7 @@ If you are interested in Inference and Widgets, you can follow [this guide](http 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). -## A flexible approach: helpers +## A flexible approach: helpers[[a-flexible-approach-helpers]] 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 @@ -37,7 +37,7 @@ and [`from_pretrained_fastai`]). Implementation can differ between libraries, but the workflow is often similar. -### from_pretrained +### from_pretrained[[frompretrained]] This is how a `from_pretrained` method usually look like: @@ -55,7 +55,7 @@ def from_pretrained(model_id: str) -> MyModelClass: return load_model(cached_model) ``` -### push_to_hub +### push_to_hub[[pushtohub]] 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. @@ -90,7 +90,7 @@ def push_to_hub(model: MyModelClass, repo_name: str) -> None: 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. -### Limitations +### Limitations[[limitations]] 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 @@ -115,7 +115,7 @@ However, if a parameter changes or a new feature is added, you will need to upda 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**. -## A more complex approach: class inheritance +## A more complex approach: class inheritance[[a-more-complex-approach-class-inheritance]] 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 @@ -149,11 +149,11 @@ As a bonus, [`ModelHubMixin`] handles the model configuration for you. If your ` Finally, [`ModelHubMixin`] handles generating a model card for you. When inheriting from [`ModelHubMixin`], you can define metadata such as `library_name`, `tags`, `repo_url` and `docs_url`. Those fields will be reused to populate the modelcard of any model that use your class. This is very practical to make all models using your library easily searchable on the Hub and to provide some resource links for users landing on the Hub. If you want to extend the modelcard template, you can override the [`~ModelHubMixin.generate_model_card`] method. -### A concrete example: PyTorch +### A concrete example: PyTorch[[a-concrete-example-pytorch]] A good example of what we saw above is [`PyTorchModelHubMixin`], our integration for the PyTorch framework. This is a ready-to-use integration. -#### How to use it? +#### How to use it?[[how-to-use-it]] Here is how any user can load/save a PyTorch model from/to the Hub: @@ -208,7 +208,7 @@ Here is how any user can load/save a PyTorch model from/to the Hub: "keras-nlp" ``` -#### Implementation +#### Implementation[[implementation]] 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). @@ -280,7 +280,7 @@ class PyTorchModelHubMixin(ModelHubMixin): And that's it! Your library now enables users to upload and download files to and from the Hub. -## Quick comparison +## Quick comparison[[quick-comparison]] 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 From 4986a406736c85c83354e95ffa752240a4f69e38 Mon Sep 17 00:00:00 2001 From: "Chulhwa (Evan) Han" Date: Sun, 28 Apr 2024 08:19:57 +0000 Subject: [PATCH 03/13] feat: nmt draft --- docs/source/ko/guides/integrations.md | 201 +++++++++++--------------- 1 file changed, 83 insertions(+), 118 deletions(-) diff --git a/docs/source/ko/guides/integrations.md b/docs/source/ko/guides/integrations.md index 08b4ac4cfb..e6f28c56be 100644 --- a/docs/source/ko/guides/integrations.md +++ b/docs/source/ko/guides/integrations.md @@ -2,48 +2,33 @@ rendered properly in your Markdown viewer. --> -# Integrate any ML framework with the Hub[[integrate-any-ml-framework-with-the-hub]] +# 머신 러닝(Machine Learning) 프레임워크 Hub와 통합[[integrate-any-ml-framework-with-the-hub]] +Hugging Face Hub는 커뮤니티와 모델을 공유하는 것을 쉽게 만들어줍니다. 이는 오픈소스 생태계의 [수십 가지 라이브러리](https://glorious-goldfish-v557q9qvxv7366v9.github.dev/)를 지원합니다. 우리는 항상 협업적인 머신 러닝을 전진시키기 위해 이 지원을 확대하기 위해 노력하고 있습니다. `huggingface_hub` 라이브러리는 어떤 Python 스크립트든지 쉽게 파일을 업로드하고 로드할 수 있도록 하는 데 중요한 역할을 합니다. -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. +라이브러리를 Hub와 통합하는 주요 네 가지 방법이 있습니다: -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()`. -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. -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. +1. **Hub로 업로드하기**: 모델을 Hub에 업로드하는 메서드를 구현합니다. 이에는 모델 가중치뿐만 아니라 [모델 카드](https://huggingface.co/docs/huggingface_hub/how-to-model-cards) 및 모델 실행에 필요한 다른 관련 정보나 데이터(예: 훈련 로그)가 포함됩니다. 이 방법은 일반적으로 `push_to_hub()`라고 합니다. +2. **Hub에서 다운로드하기**: Hub에서 모델을 로드하는 메서드를 구현합니다. 이 메서드는 모델 구성/가중치를 다운로드하고 모델을 로드해야 합니다. 이 방법은 일반적으로 `from_pretrained` 또는 `load_from_hub()`라고 합니다. +3. **추론 API**: 라이브러리에서 지원하는 모델에 대해 무료로 추론을 실행하기 위해 서버를 사용합니다. +4. **위젯**: Hub의 모델 랜딩 페이지에 위젯을 표시합니다. 이를 통해 사용자들은 브라우저에서 빠르게 모델을 시도할 수 있습니다. -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 -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 -[in our docs](https://huggingface.co/docs/hub/models-libraries). +추론 및 위젯에 관심이 있는 경우 [이 가이드](https://huggingface.co/docs/hub/models-adding-libraries#set-up-the-inference-api)를 따를 수 있습니다. 양쪽 모두에서 라이브러리를 Hub와 통합하고 [문서](https://huggingface.co/docs/hub/models-libraries)에 목록으로 나열되고자 하는 경우에는 언제든지 저희에게 연락하실 수 있습니다. -## A flexible approach: helpers[[a-flexible-approach-helpers]] +## 유연한 접근 방식: 도우미(helper)[[a-flexible-approach-helpers]] -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`] -and [`from_pretrained_fastai`]). +라이브러리를 Hub에 통합하는 첫 번째 접근 방법은 실제로 `push_to_hub` 및 `from_pretrained` 메서드를 직접 구현하는 것입니다. 이를 통해 업로드/다운로드할 파일 및 입력을 처리하는 방법에 대한 완전한 유연성을 제공받을 수 있습니다. 이를 위해 [파일 업로드](./upload) 및 [파일 다운로드](./download) 가이드를 참조하여 자세히 알아볼 수 있습니다. 예를 들어 FastAI 통합이 구현된 방법을 보면 됩니다 ([`push_to_hub_fastai`] 및 [`from_pretrained_fastai`]를 참조). -Implementation can differ between libraries, but the workflow is often similar. +라이브러리마다 구현 방식은 다를 수 있지만, 워크플로우는 일반적으로 비슷합니다. ### from_pretrained[[frompretrained]] -This is how a `from_pretrained` method usually look like: +일반적으로 `from_pretrained` 메서드는 다음과 같은 형태를 가집니다: ```python def from_pretrained(model_id: str) -> MyModelClass: - # Download model from Hub + # Hub로부터 모델을 다운로드 cached_model = hf_hub_download( repo_id=repo_id, filename="model.pkl", @@ -51,111 +36,93 @@ def from_pretrained(model_id: str) -> MyModelClass: library_version=get_fastai_version(), ) - # Load model + # 모델 가져오기 return load_model(cached_model) ``` ### push_to_hub[[pushtohub]] -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. +`push_to_hub` 메서드는 종종 레포지토리 생성, 모델 카드 생성 및 가중치 저장을 처리하기 위해 조금 더 복잡한 접근 방식이 필요합니다. 일반적으로 모든 이러한 파일을 임시 폴더에 저장한 다음 업로드하고 나중에 삭제하는 방식이 흔히 사용됩니다. ```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 + # 해당 리포지토리가 아직 없다면 리포지토리를 생성하고 관련된 리포지토리 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 + # model card 생성 card = generate_model_card(model) (tmpdir / "README.md").write_text(card) - # Save logs - # Save figures - # Save evaluation metrics + # 로그 저장 + # 설정 저장 + # 평가 지표를 저장 # ... - # Push to hub + # 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. - -### Limitations[[limitations]] - -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`/`resume_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 + +물론 이는 단순한 예시에 불과합니다. 더 복잡한 조작(원격 파일 삭제, 가중치를 실시간으로 업로드, 로컬로 가중치를 유지 등)에 관심이 있다면 [파일 업로드](./upload) 가이드를 참조해 주세요. + +### 제한[[limitations]] + +유연성을 가지고 있지만, 이 방식은 유지보수 측면에서 일부 단점을 가지고 있습니다. Hugging Face 사용자들은 `huggingface_hub`와 함께 작업할 때 추가 기능에 익숙합니다. 예를 들어, Hub에서 파일을 로드할 때 다음과 같은 매개변수를 제공하는 것이 일반적입니다: + +- `token`: 개인 저장소에서 다운로드하기 위한 토큰 +- `revision`: 특정 브랜치에서 다운로드하기 위한 리비전 +- `cache_dir`: 특정 디렉터리에 파일을 캐시하기 위한 디렉터리 +- `force_download`/`resume_download`/`local_files_only`: 캐시를 재사용할 것인지 여부를 결정하는 매개변수 +- `proxies`: HTTP 세션 구성 +모델을 푸시할 때는 유사한 매개변수가 지원됩니다: + +- `commit_message`: 사용자 정의 커밋 메시지 +- `private`: 개인 저장소를 만들어야 할 경우 +- `create_pr`: `main`에 푸시하는 대신 PR을 만드는 경우 +- `branch`: `main` 브랜치 대신 브랜치에 푸시하는 경우 +- `allow_patterns/ignore_patterns`: 업로드할 파일을 필터링하는 매개변수 - `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**. +이러한 매개변수는 위에서 본 구현에 추가하여 `huggingface_hub` 메서드로 전달할 수 있습니다. 그러나 매개변수가 변경되거나 새로운 기능이 추가되는 경우에는 패키지를 업데이트해야 합니다. 이러한 매개변수를 지원하는 것은 귀하측의 유지 관리할 문서가 더 많아진다는 것을 의미합니다. 이러한 제한 사항을 어떻게 완화할 수 있는지 보려면 다음 섹션인 **클래스 상속**으로 이동해 보겠습니다. + +## 더욱 복잡한 접근법: 클래스 상속[[a-more-complex-approach-class-inheritance]] -## A more complex approach: class inheritance[[a-more-complex-approach-class-inheritance]] -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! +위에서 보았듯이 Hub와 통합하기 위해 라이브러리에 포함해야 할 주요 메서드는 파일을 업로드하는 (`push_to_hub`) 및 파일을 다운로드하는 (`from_pretrained`)입니다. 이러한 메서드를 직접 구현할 수 있지만, 이에는 몇 가지 주의할 점이 있습니다. 이를 해결하기 위해 `huggingface_hub`은 클래스 상속을 사용하는 도구를 제공합니다. 이 도구가 어떻게 작동하는지 살펴보겠습니다! -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, -the [`ModelHubMixin`]. The key here is to understand its behavior and how to customize it. +많은 경우에 라이브러리는 이미 Python 클래스를 사용하여 모델을 구현합니다. 이 클래스에는 모델의 속성 및 로드, 실행, 훈련 및 평가하는 메서드가 포함되어 있습니다. 저희의 접근 방식은 [믹스인]을(https://stackoverflow.com/a/547714) 사용하여 이 클래스를 확장하여 업로드 및 다운로드 기능을 포함하는 것입니다. 믹스인(Mixin)은 기존 클래스에 여러 상속을 통해 특정 기능을 확장하기 위해 설계된 클래스입니다. `huggingface_hub`은 자체 믹스인인 [`ModelHubMixin`]을 제공합니다. 이 중요한 점은 그 동작을 이해하고 사용자 정의하는 것입니다. -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 -*private* methods (`_save_pretrained` and `_from_pretrained`). Those are the ones you must implement. So to integrate -your library, you should: +[`ModelHubMixin`] 클래스는 세 개의 *공개* 메서드(`push_to_hub`, `save_pretrained`, `from_pretrained`)를 구현합니다. 이들은 사용자가 라이브러리를 사용하여 모델을 로드/저장할 때 호출하는 메서드입니다. 또한 [`ModelHubMixin`]은 두 개의 *비공개* 메서드(`_save_pretrained` 및 `_from_pretrained`)를 정의합니다. 이 메서드들을 구현해야 합니다. 라이브러리를 통합하려면: -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. - 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. - - [`~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. 모델 클래스를 [`ModelHubMixin`]에서 상속합니다. +2. 비공개 메서드를 구현합니다: + - [`~ModelHubMixin._save_pretrained`]: 디렉터리 경로를 입력으로 받아 모델을 해당 디렉터리에 저장하는 메서드입니다. 이 메서드에는 모델 카드, 모델 가중치, 구성 파일, 훈련 로그 및 그림 등 해당 모델에 대한 모든 관련 정보를 덤프하기 위한 로직을 작성해야 합니다. [모델 카드](https://huggingface.co/docs/hub/model-cards)는 모델을 설명하는 데 특히 중요합니다. 더 자세한 내용은 [구현 가이드](./model-cards)를 확인하세요. + - [`~ModelHubMixin._from_pretrained`]: `model_id`를 입력으로 받아 인스턴스화된 모델을 반환하는 **클래스 메서드**입니다. 이 메서드는 관련 파일을 다운로드하고 로드해야 합니다. +3. 작업을 완료했습니다! -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. All of this is handled by the mixin and is available to your users. The Mixin also ensures that public methods are well documented and type annotated. +[`ModelHubMixin`]의 장점은 파일의 직렬화/로드에만 신경을 쓰면 되기 때문에 즉시 사용할 수 있다는 것입니다. 레포지토리 생성, 커밋, PR 또는 리비전과 같은 사항에 대해 걱정할 필요가 없습니다. 이 모든 것은 믹스인에 의해 처리되며 사용자에게 제공됩니다. 믹스인은 또한 공개 메서드가 잘 문서화되고 타입이 주석이 달려있는지를 보장합니다. -As a bonus, [`ModelHubMixin`] handles the model configuration for you. If your `__init__` method expects a `config` input, it will be automatically saved in the repo when calling `save_pretrained` and reloaded correctly by `load_pretrained`. Moreover, if the `config` input parameter is annotated with dataclass type (e.g. `config: Optional[MyConfigClass] = None`), then the `config` value will be correctly deserialized for you. Finally, all jsonable values passed at initialization will be also stored in the config file. This means you don't necessarily have to expect a `config` input to benefit from it. The big advantage of having a `config.json` file in your model repository is that it automatically enables the analytics on the Hub (e.g. the "downloads" count). +보너스로, [`ModelHubMixin`]은 모델 구성을 자동으로 처리해 줍니다. 만약 당신의 `__init__` 메서드가 `config` 입력을 기대한다면, `save_pretrained`를 호출할 때 자동으로 레포에 저장되고 `load_pretrained`에 의해 올바르게 다시 로드될 것입니다. 더불어, `config` 입력 매개변수가 dataclass 타입으로 주석 처리되어 있다면 (예: `config: Optional[MyConfigClass] = None`), 그렇게 하면 `config` 값이 올바르게 역직렬화됩니다. 마지막으로, 초기화할 때 전달된 모든 jsonable 값은 구성 파일에 저장됩니다. 이는 `config` 입력을 기대하지 않더라도 이를 활용할 수 있다는 것을 의미합니다. 모델 리포지토리에 `config.json` 파일이 있으면 Hub에서 자동으로 분석을 활성화시킵니다 (예: "다운로드" 횟수). -Finally, [`ModelHubMixin`] handles generating a model card for you. When inheriting from [`ModelHubMixin`], you can define metadata such as `library_name`, `tags`, `repo_url` and `docs_url`. Those fields will be reused to populate the modelcard of any model that use your class. This is very practical to make all models using your library easily searchable on the Hub and to provide some resource links for users landing on the Hub. If you want to extend the modelcard template, you can override the [`~ModelHubMixin.generate_model_card`] method. +마지막으로, [`ModelHubMixin`]은 모델 카드 생성을 처리해줍니다. [`ModelHubMixin`]을 상속받을 때 `library_name`, `tags`, `repo_url`, `docs_url`과 같은 메타데이터를 정의할 수 있습니다. 이러한 필드는 당신의 클래스를 사용하는 모든 모델의 모델 카드를 채우는 데 재사용됩니다. 이는 Hub에서 당신의 라이브러리를 사용하는 모든 모델을 쉽게 검색할 수 있도록 만들고, Hub에 착륙하는 사용자에게 일부 리소스 링크를 제공하는 데 매우 유용합니다. 만약 모델 카드 템플릿을 확장하고 싶다면, [`~ModelHubMixin.generate_model_card`] 메서드를 재정의할 수 있습니다. -### A concrete example: PyTorch[[a-concrete-example-pytorch]] +### 자세한 예시: PyTorch[[a-concrete-example-pytorch]] -A good example of what we saw above is [`PyTorchModelHubMixin`], our integration for the PyTorch framework. This is a ready-to-use integration. +위에서 언급한 내용의 좋은 예시는 [`PyTorchModelHubMixin`]입니다. 이것은 PyTorch 프레임워크를 위한 저희의 통합입니다. 이것은 즉시 사용할 수 있는 통합입니다. -#### How to use it?[[how-to-use-it]] +#### 어떻게 사용할까요?[[how-to-use-it]] -Here is how any user can load/save a PyTorch model from/to the Hub: +다음은 사용자가 Hub에서 PyTorch 모델을 로드/저장하는 방법입니다: ```python >>> import torch @@ -163,15 +130,15 @@ Here is how any user can load/save a PyTorch model from/to the Hub: >>> from huggingface_hub import PyTorchModelHubMixin -# Define your Pytorch model exactly the same way you are used to +# PyTorch 모델을 여러분이 흔히 사용하는 방식과 완전히 동일하게 정의하세요. >>> class MyModel( ... nn.Module, -... PyTorchModelHubMixin, # multiple inheritance +... PyTorchModelHubMixin, # 다중 상송 ... 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 +... # ^ 모델 카드를 생성하는 데 선택적인 메타데이터입니다. ... ): ... def __init__(self, hidden_size: int = 512, vocab_size: int = 30000, output_size: int = 4): ... super().__init__() @@ -181,25 +148,25 @@ Here is how any user can load/save a PyTorch model from/to the Hub: ... def forward(self, x): ... return self.linear(x + self.param) -# 1. Create model +# 1. 모델 생성 >>> 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 +# 2. (선택사항) 모델을 로컬 디렉터리에 저장합니다. >>> model.save_pretrained("path/to/my-awesome-model") -# 3. Push model weights to the Hub +# 3. 모델 가중치를 Hub에 푸시합니다. >>> model.push_to_hub("my-awesome-model") -# 4. Initialize model from the Hub => config has been preserved +# 4. Hub로부터 모델을 초기화합니다. => 이때 설정은 보존됩니다. >>> 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 @@ -208,11 +175,11 @@ Here is how any user can load/save a PyTorch model from/to the Hub: "keras-nlp" ``` -#### Implementation[[implementation]] +#### 구현[[implementation]] -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). +실제 구현은 매우 간단합니다. 전체 구현은 [여기](https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/hub_mixin.py)에서 찾을 수 있습니다. -1. First, inherit your class from `ModelHubMixin`: +1. 클래스를 `ModelHubMixin`으로부터 상속하세요: ```python from huggingface_hub import ModelHubMixin @@ -221,7 +188,7 @@ class PyTorchModelHubMixin(ModelHubMixin): (...) ``` -2. Implement the `_save_pretrained` method: +2. `_save_pretrained` 메서드를 구현하세요: ```py from huggingface_hub import ModelHubMixin @@ -230,18 +197,18 @@ class PyTorchModelHubMixin(ModelHubMixin): (...) def _save_pretrained(self, save_directory: Path) -> None: - """Save weights from a Pytorch model to a local directory.""" + """PyTorch 모델의 가중치를 로컬 디렉터리에 저장합니다.""" save_model_as_safetensor(self.module, str(save_directory / SAFETENSORS_SINGLE_FILE)) ``` -3. Implement the `_from_pretrained` method: +3. `_from_pretrained` 메서드를 구현하세요: ```python class PyTorchModelHubMixin(ModelHubMixin): (...) - @classmethod # Must be a classmethod! + @classmethod # 반드시 클래스 메서드여야 합니다! def _from_pretrained( cls, *, @@ -253,11 +220,11 @@ class PyTorchModelHubMixin(ModelHubMixin): resume_download: bool, local_files_only: bool, token: Union[str, bool, None], - map_location: str = "cpu", # additional argument - strict: bool = False, # additional argument + map_location: str = "cpu", # 추가 인자 + strict: bool = False, # 추가 인자 **model_kwargs, ): - """Load Pytorch pretrained weights and return the loaded model.""" + """PyTorch의 사전 학습된 가중치를 로드하고 로드된 모델을 반환합니다.""" model = cls(**model_kwargs) if os.path.isdir(model_id): print("Loading weights from local directory") @@ -278,13 +245,11 @@ class PyTorchModelHubMixin(ModelHubMixin): 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. +그게 다입니다! 이제 라이브러리를 통해 사용자가 Hub로부터 파일을 업로드하고 다운로드할 수 있습니다. -## Quick comparison[[quick-comparison]] +## 빠른 비교[[quick-comparison]] -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! +두 가지 접근 방법에 대한 장단점을 간단히 정리해보겠습니다. 아래 표는 단순히 예시일 뿐입니다. 여러분의 프레임워크에는 고려해야 할 특정 사항이 있을 수 있습니다. 이 가이드는 통합을 다루는 아이디어와 지침을 제공하기 위한 것입니다. 언제든지 궁금한 점이 있으면 문의해 주세요! | Integration | Using helpers | Using [`ModelHubMixin`] | From f95b70337d2ad8cc99bdbaa3121069a21ac5ca21 Mon Sep 17 00:00:00 2001 From: "Chulhwa (Evan) Han" Date: Mon, 29 Apr 2024 00:33:45 +0000 Subject: [PATCH 04/13] fix: manual edits --- docs/source/ko/guides/integrations.md | 36 +++++++++++++-------------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/docs/source/ko/guides/integrations.md b/docs/source/ko/guides/integrations.md index e6f28c56be..cb9178316e 100644 --- a/docs/source/ko/guides/integrations.md +++ b/docs/source/ko/guides/integrations.md @@ -2,19 +2,19 @@ rendered properly in your Markdown viewer. --> -# 머신 러닝(Machine Learning) 프레임워크 Hub와 통합[[integrate-any-ml-framework-with-the-hub]] -Hugging Face Hub는 커뮤니티와 모델을 공유하는 것을 쉽게 만들어줍니다. 이는 오픈소스 생태계의 [수십 가지 라이브러리](https://glorious-goldfish-v557q9qvxv7366v9.github.dev/)를 지원합니다. 우리는 항상 협업적인 머신 러닝을 전진시키기 위해 이 지원을 확대하기 위해 노력하고 있습니다. `huggingface_hub` 라이브러리는 어떤 Python 스크립트든지 쉽게 파일을 업로드하고 로드할 수 있도록 하는 데 중요한 역할을 합니다. +# 어떤 머신 러닝 프레임워크든 Hub와 통합[[integrate-any-ml-framework-with-the-hub]] +Hugging Face Hub는 커뮤니티와 모델을 공유하는 것을 쉽게 만들어줍니다. 이는 오픈소스 생태계의 [수십 가지 라이브러리](https://glorious-goldfish-v557q9qvxv7366v9.github.dev/)를 지원합니다. 저희는 항상 협업적인 머신 러닝을 전진시키기 위해 이 지원을 확대하기 위해 노력하고 있습니다. `huggingface_hub` 라이브러리는 어떤 Python 스크립트든지 쉽게 파일을 업로드하고 로드할 수 있도록 하는 데 중요한 역할을 합니다. 라이브러리를 Hub와 통합하는 주요 네 가지 방법이 있습니다: -1. **Hub로 업로드하기**: 모델을 Hub에 업로드하는 메서드를 구현합니다. 이에는 모델 가중치뿐만 아니라 [모델 카드](https://huggingface.co/docs/huggingface_hub/how-to-model-cards) 및 모델 실행에 필요한 다른 관련 정보나 데이터(예: 훈련 로그)가 포함됩니다. 이 방법은 일반적으로 `push_to_hub()`라고 합니다. -2. **Hub에서 다운로드하기**: Hub에서 모델을 로드하는 메서드를 구현합니다. 이 메서드는 모델 구성/가중치를 다운로드하고 모델을 로드해야 합니다. 이 방법은 일반적으로 `from_pretrained` 또는 `load_from_hub()`라고 합니다. +1. **Hub에 업로드하기**: 모델을 Hub에 업로드하는 메서드를 구현합니다. 이에는 모델 가중치뿐만 아니라 [모델 카드](https://huggingface.co/docs/huggingface_hub/how-to-model-cards) 및 모델 실행에 필요한 다른 관련 정보나 데이터(예: 훈련 로그)가 포함됩니다. 이 방법은 일반적으로 `push_to_hub()`라고 합니다. +2. **Hub에서 다운로드하기**: Hub에서 모델을 가져오는 메서드를 구현합니다. 이 메서드는 모델 구성/가중치를 다운로드하고 모델을 가져와야 합니다. 이 방법은 일반적으로 `from_pretrained` 또는 `load_from_hub()`라고 합니다. 3. **추론 API**: 라이브러리에서 지원하는 모델에 대해 무료로 추론을 실행하기 위해 서버를 사용합니다. 4. **위젯**: Hub의 모델 랜딩 페이지에 위젯을 표시합니다. 이를 통해 사용자들은 브라우저에서 빠르게 모델을 시도할 수 있습니다. -이 가이드에서는 앞의 두 가지 주제에 중점을 둘 것입니다. 두 가지 주요 통합 방법을 소개하고 각각의 장단점을 설명할 것입니다. 이를 요약하여 두 가지 중 어떤 것을 선택할지에 대한 도움이 될 것입니다. 이는 단지 가이드라는 것을 명심하고 귀하의 요구에 맞게 적응시킬 수 있는 가이드라는 점을 유념하십시오. +이 가이드에서는 앞의 두 가지 주제에 중점을 둘 것입니다. 두 가지 주요 통합 방법을 소개하고 각각의 장단점을 설명할 것입니다. 이를 요약하여 두 가지 중 어떤 것을 선택할지에 대한 도움이 될 것입니다. 이는 단지 가이드라는 것을 명심하고 상황에 맞게 적응시킬 수 있는 가이드라는 점을 유념하십시오. -추론 및 위젯에 관심이 있는 경우 [이 가이드](https://huggingface.co/docs/hub/models-adding-libraries#set-up-the-inference-api)를 따를 수 있습니다. 양쪽 모두에서 라이브러리를 Hub와 통합하고 [문서](https://huggingface.co/docs/hub/models-libraries)에 목록으로 나열되고자 하는 경우에는 언제든지 저희에게 연락하실 수 있습니다. +추론 및 위젯에 관심이 있는 경우 [이 가이드](https://huggingface.co/docs/hub/models-adding-libraries#set-up-the-inference-api)를 참조할 수 있습니다. 양쪽 모두에서 라이브러리를 Hub와 통합하고 [문서](https://huggingface.co/docs/hub/models-libraries)에 목록에 게시하고자 하는 경우에는 언제든지 저희에게 연락하실 수 있습니다. ## 유연한 접근 방식: 도우미(helper)[[a-flexible-approach-helpers]] @@ -78,51 +78,51 @@ def push_to_hub(model: MyModelClass, repo_name: str) -> None: 유연성을 가지고 있지만, 이 방식은 유지보수 측면에서 일부 단점을 가지고 있습니다. Hugging Face 사용자들은 `huggingface_hub`와 함께 작업할 때 추가 기능에 익숙합니다. 예를 들어, Hub에서 파일을 로드할 때 다음과 같은 매개변수를 제공하는 것이 일반적입니다: -- `token`: 개인 저장소에서 다운로드하기 위한 토큰 +- `token`: 개인 리포지토리에서 다운로드하기 위한 토큰 - `revision`: 특정 브랜치에서 다운로드하기 위한 리비전 - `cache_dir`: 특정 디렉터리에 파일을 캐시하기 위한 디렉터리 - `force_download`/`resume_download`/`local_files_only`: 캐시를 재사용할 것인지 여부를 결정하는 매개변수 - `proxies`: HTTP 세션 구성 -모델을 푸시할 때는 유사한 매개변수가 지원됩니다: +모델을 푸시할 때는 유사한 매개변수가 지원됩니다: - `commit_message`: 사용자 정의 커밋 메시지 -- `private`: 개인 저장소를 만들어야 할 경우 +- `private`: 개인 리포지토리를 만들어야 할 경우 - `create_pr`: `main`에 푸시하는 대신 PR을 만드는 경우 - `branch`: `main` 브랜치 대신 브랜치에 푸시하는 경우 - `allow_patterns/ignore_patterns`: 업로드할 파일을 필터링하는 매개변수 - `token` - ... -이러한 매개변수는 위에서 본 구현에 추가하여 `huggingface_hub` 메서드로 전달할 수 있습니다. 그러나 매개변수가 변경되거나 새로운 기능이 추가되는 경우에는 패키지를 업데이트해야 합니다. 이러한 매개변수를 지원하는 것은 귀하측의 유지 관리할 문서가 더 많아진다는 것을 의미합니다. 이러한 제한 사항을 어떻게 완화할 수 있는지 보려면 다음 섹션인 **클래스 상속**으로 이동해 보겠습니다. +이러한 매개변수는 위에서 본 구현에 추가하여 `huggingface_hub` 메서드로 전달할 수 있습니다. 그러나 매개변수가 변경되거나 새로운 기능이 추가되는 경우에는 패키지를 업데이트해야 합니다. 이러한 매개변수를 지원하는 것은 유지 관리할 문서가 더 많아진다는 것을 의미합니다. 이러한 제한 사항을 어떻게 완화할 수 있는지 보려면 다음 섹션인 **클래스 상속**으로 이동해 보겠습니다. ## 더욱 복잡한 접근법: 클래스 상속[[a-more-complex-approach-class-inheritance]] 위에서 보았듯이 Hub와 통합하기 위해 라이브러리에 포함해야 할 주요 메서드는 파일을 업로드하는 (`push_to_hub`) 및 파일을 다운로드하는 (`from_pretrained`)입니다. 이러한 메서드를 직접 구현할 수 있지만, 이에는 몇 가지 주의할 점이 있습니다. 이를 해결하기 위해 `huggingface_hub`은 클래스 상속을 사용하는 도구를 제공합니다. 이 도구가 어떻게 작동하는지 살펴보겠습니다! -많은 경우에 라이브러리는 이미 Python 클래스를 사용하여 모델을 구현합니다. 이 클래스에는 모델의 속성 및 로드, 실행, 훈련 및 평가하는 메서드가 포함되어 있습니다. 저희의 접근 방식은 [믹스인]을(https://stackoverflow.com/a/547714) 사용하여 이 클래스를 확장하여 업로드 및 다운로드 기능을 포함하는 것입니다. 믹스인(Mixin)은 기존 클래스에 여러 상속을 통해 특정 기능을 확장하기 위해 설계된 클래스입니다. `huggingface_hub`은 자체 믹스인인 [`ModelHubMixin`]을 제공합니다. 이 중요한 점은 그 동작을 이해하고 사용자 정의하는 것입니다. +많은 경우에 라이브러리는 이미 Python 클래스를 사용하여 모델을 구현합니다. 이 클래스에는 모델의 속성 및 로드, 실행, 훈련 및 평가하는 메서드가 포함되어 있습니다. 접근 방식은 [믹스인](https://stackoverflow.com/a/547714)을 사용하여 이 클래스를 확장하여 업로드 및 다운로드 기능을 포함하는 것입니다. 믹스인(Mixin)은 기존 클래스에 여러 상속을 통해 특정 기능을 확장하기 위해 설계된 클래스입니다. `huggingface_hub`은 자체 믹스인인 [`ModelHubMixin`]을 제공합니다. 이 중요한 점은 그 동작을 이해하고 사용자 정의하는 것입니다. -[`ModelHubMixin`] 클래스는 세 개의 *공개* 메서드(`push_to_hub`, `save_pretrained`, `from_pretrained`)를 구현합니다. 이들은 사용자가 라이브러리를 사용하여 모델을 로드/저장할 때 호출하는 메서드입니다. 또한 [`ModelHubMixin`]은 두 개의 *비공개* 메서드(`_save_pretrained` 및 `_from_pretrained`)를 정의합니다. 이 메서드들을 구현해야 합니다. 라이브러리를 통합하려면: +[`ModelHubMixin`] 클래스는 세 개의 *공개* 메서드(`push_to_hub`, `save_pretrained`, `from_pretrained`)를 구현합니다. 이 메서드들은 사용자가 라이브러리를 사용하여 모델을 로드/저장할 때 호출하는 메서드입니다. 또한 [`ModelHubMixin`]은 두 개의 *비공개* 메서드(`_save_pretrained` 및 `_from_pretrained`)를 정의합니다. 이 메서드들을 구현해야 합니다. 라이브러리를 통합하려면: 1. 모델 클래스를 [`ModelHubMixin`]에서 상속합니다. 2. 비공개 메서드를 구현합니다: - [`~ModelHubMixin._save_pretrained`]: 디렉터리 경로를 입력으로 받아 모델을 해당 디렉터리에 저장하는 메서드입니다. 이 메서드에는 모델 카드, 모델 가중치, 구성 파일, 훈련 로그 및 그림 등 해당 모델에 대한 모든 관련 정보를 덤프하기 위한 로직을 작성해야 합니다. [모델 카드](https://huggingface.co/docs/hub/model-cards)는 모델을 설명하는 데 특히 중요합니다. 더 자세한 내용은 [구현 가이드](./model-cards)를 확인하세요. - [`~ModelHubMixin._from_pretrained`]: `model_id`를 입력으로 받아 인스턴스화된 모델을 반환하는 **클래스 메서드**입니다. 이 메서드는 관련 파일을 다운로드하고 로드해야 합니다. -3. 작업을 완료했습니다! +3. 완료했습니다! [`ModelHubMixin`]의 장점은 파일의 직렬화/로드에만 신경을 쓰면 되기 때문에 즉시 사용할 수 있다는 것입니다. 레포지토리 생성, 커밋, PR 또는 리비전과 같은 사항에 대해 걱정할 필요가 없습니다. 이 모든 것은 믹스인에 의해 처리되며 사용자에게 제공됩니다. 믹스인은 또한 공개 메서드가 잘 문서화되고 타입이 주석이 달려있는지를 보장합니다. 보너스로, [`ModelHubMixin`]은 모델 구성을 자동으로 처리해 줍니다. 만약 당신의 `__init__` 메서드가 `config` 입력을 기대한다면, `save_pretrained`를 호출할 때 자동으로 레포에 저장되고 `load_pretrained`에 의해 올바르게 다시 로드될 것입니다. 더불어, `config` 입력 매개변수가 dataclass 타입으로 주석 처리되어 있다면 (예: `config: Optional[MyConfigClass] = None`), 그렇게 하면 `config` 값이 올바르게 역직렬화됩니다. 마지막으로, 초기화할 때 전달된 모든 jsonable 값은 구성 파일에 저장됩니다. 이는 `config` 입력을 기대하지 않더라도 이를 활용할 수 있다는 것을 의미합니다. 모델 리포지토리에 `config.json` 파일이 있으면 Hub에서 자동으로 분석을 활성화시킵니다 (예: "다운로드" 횟수). -마지막으로, [`ModelHubMixin`]은 모델 카드 생성을 처리해줍니다. [`ModelHubMixin`]을 상속받을 때 `library_name`, `tags`, `repo_url`, `docs_url`과 같은 메타데이터를 정의할 수 있습니다. 이러한 필드는 당신의 클래스를 사용하는 모든 모델의 모델 카드를 채우는 데 재사용됩니다. 이는 Hub에서 당신의 라이브러리를 사용하는 모든 모델을 쉽게 검색할 수 있도록 만들고, Hub에 착륙하는 사용자에게 일부 리소스 링크를 제공하는 데 매우 유용합니다. 만약 모델 카드 템플릿을 확장하고 싶다면, [`~ModelHubMixin.generate_model_card`] 메서드를 재정의할 수 있습니다. +마지막으로, [`ModelHubMixin`]은 모델 카드 생성을 처리해줍니다. [`ModelHubMixin`]을 상속받을 때 `library_name`, `tags`, `repo_url`, `docs_url`과 같은 메타데이터를 정의할 수 있습니다. 이러한 필드는 클래스를 사용하는 모든 모델의 모델 카드를 채우는 데 재사용됩니다. 이는 Hub에서 라이브러리를 사용하는 모든 모델을 쉽게 검색할 수 있도록 만들고, Hub에 착륙하는 사용자에게 일부 리소스 링크를 제공하는 데 매우 유용합니다. 만약 모델 카드 템플릿을 확장하고 싶다면, [`~ModelHubMixin.generate_model_card`] 메서드를 재정의할 수 있습니다. ### 자세한 예시: PyTorch[[a-concrete-example-pytorch]] 위에서 언급한 내용의 좋은 예시는 [`PyTorchModelHubMixin`]입니다. 이것은 PyTorch 프레임워크를 위한 저희의 통합입니다. 이것은 즉시 사용할 수 있는 통합입니다. -#### 어떻게 사용할까요?[[how-to-use-it]] +#### 어떻게 사용하나요?[[how-to-use-it]] -다음은 사용자가 Hub에서 PyTorch 모델을 로드/저장하는 방법입니다: +다음은 Hub에서 PyTorch 모델을 로드/저장하는 방법입니다: ```python >>> import torch @@ -133,7 +133,7 @@ def push_to_hub(model: MyModelClass, repo_name: str) -> None: # PyTorch 모델을 여러분이 흔히 사용하는 방식과 완전히 동일하게 정의하세요. >>> class MyModel( ... nn.Module, -... PyTorchModelHubMixin, # 다중 상송 +... PyTorchModelHubMixin, # 다중 상속 ... library_name="keras-nlp", ... tags=["keras"], ... repo_url="https://github.com/keras-team/keras-nlp", @@ -245,7 +245,7 @@ class PyTorchModelHubMixin(ModelHubMixin): return cls._load_as_safetensor(model, model_file, map_location, strict) ``` -그게 다입니다! 이제 라이브러리를 통해 사용자가 Hub로부터 파일을 업로드하고 다운로드할 수 있습니다. +이게 전부입니다! 이제 라이브러리를 통해 Hub로부터 파일을 업로드하고 다운로드할 수 있습니다. ## 빠른 비교[[quick-comparison]] From 12279fecc9ee0e3027790e338d4ab23d9dbfd71d Mon Sep 17 00:00:00 2001 From: "Chulhwa (Evan) Han" Date: Mon, 29 Apr 2024 09:54:25 +0900 Subject: [PATCH 05/13] Apply suggestions from code review --- docs/source/ko/guides/integrations.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/source/ko/guides/integrations.md b/docs/source/ko/guides/integrations.md index cb9178316e..c02d039887 100644 --- a/docs/source/ko/guides/integrations.md +++ b/docs/source/ko/guides/integrations.md @@ -2,8 +2,8 @@ rendered properly in your Markdown viewer. --> -# 어떤 머신 러닝 프레임워크든 Hub와 통합[[integrate-any-ml-framework-with-the-hub]] -Hugging Face Hub는 커뮤니티와 모델을 공유하는 것을 쉽게 만들어줍니다. 이는 오픈소스 생태계의 [수십 가지 라이브러리](https://glorious-goldfish-v557q9qvxv7366v9.github.dev/)를 지원합니다. 저희는 항상 협업적인 머신 러닝을 전진시키기 위해 이 지원을 확대하기 위해 노력하고 있습니다. `huggingface_hub` 라이브러리는 어떤 Python 스크립트든지 쉽게 파일을 업로드하고 로드할 수 있도록 하는 데 중요한 역할을 합니다. +# Hub와 어떤 머신 러닝 프레임워크든 통합[[integrate-any-ml-framework-with-the-hub]] +Hugging Face Hub는 커뮤니티와 모델을 공유하는 것을 쉽게 만들어줍니다. 이는 오픈소스 생태계의 [수십 가지 라이브러리](https://huggingface.co/docs/hub/models-libraries)를 지원합니다. 저희는 항상 협업적인 머신 러닝을 전진시키기 위해 이 지원을 확대하기 위해 노력하고 있습니다. `huggingface_hub` 라이브러리는 어떤 Python 스크립트든지 쉽게 파일을 업로드하고 로드할 수 있도록 하는 데 중요한 역할을 합니다. 라이브러리를 Hub와 통합하는 주요 네 가지 방법이 있습니다: @@ -42,7 +42,7 @@ def from_pretrained(model_id: str) -> MyModelClass: ### push_to_hub[[pushtohub]] -`push_to_hub` 메서드는 종종 레포지토리 생성, 모델 카드 생성 및 가중치 저장을 처리하기 위해 조금 더 복잡한 접근 방식이 필요합니다. 일반적으로 모든 이러한 파일을 임시 폴더에 저장한 다음 업로드하고 나중에 삭제하는 방식이 흔히 사용됩니다. +`push_to_hub` 메서드는 종종 리포지토리 생성, 모델 카드 생성 및 가중치 저장을 처리하기 위해 조금 더 복잡한 접근 방식이 필요합니다. 일반적으로 모든 이러한 파일을 임시 폴더에 저장한 다음 업로드하고 나중에 삭제하는 방식이 흔히 사용됩니다. ```python def push_to_hub(model: MyModelClass, repo_name: str) -> None: @@ -110,9 +110,9 @@ def push_to_hub(model: MyModelClass, repo_name: str) -> None: - [`~ModelHubMixin._from_pretrained`]: `model_id`를 입력으로 받아 인스턴스화된 모델을 반환하는 **클래스 메서드**입니다. 이 메서드는 관련 파일을 다운로드하고 로드해야 합니다. 3. 완료했습니다! -[`ModelHubMixin`]의 장점은 파일의 직렬화/로드에만 신경을 쓰면 되기 때문에 즉시 사용할 수 있다는 것입니다. 레포지토리 생성, 커밋, PR 또는 리비전과 같은 사항에 대해 걱정할 필요가 없습니다. 이 모든 것은 믹스인에 의해 처리되며 사용자에게 제공됩니다. 믹스인은 또한 공개 메서드가 잘 문서화되고 타입이 주석이 달려있는지를 보장합니다. +[`ModelHubMixin`]의 장점은 파일의 직렬화/로드에만 신경을 쓰면 되기 때문에 즉시 사용할 수 있다는 것입니다. 리포지토리 생성, 커밋, PR 또는 리비전과 같은 사항에 대해 걱정할 필요가 없습니다. 이 모든 것은 믹스인에 의해 처리되며 사용자에게 제공됩니다. 믹스인은 또한 공개 메서드가 잘 문서화되고 타입이 주석이 달려있는지를 보장합니다. -보너스로, [`ModelHubMixin`]은 모델 구성을 자동으로 처리해 줍니다. 만약 당신의 `__init__` 메서드가 `config` 입력을 기대한다면, `save_pretrained`를 호출할 때 자동으로 레포에 저장되고 `load_pretrained`에 의해 올바르게 다시 로드될 것입니다. 더불어, `config` 입력 매개변수가 dataclass 타입으로 주석 처리되어 있다면 (예: `config: Optional[MyConfigClass] = None`), 그렇게 하면 `config` 값이 올바르게 역직렬화됩니다. 마지막으로, 초기화할 때 전달된 모든 jsonable 값은 구성 파일에 저장됩니다. 이는 `config` 입력을 기대하지 않더라도 이를 활용할 수 있다는 것을 의미합니다. 모델 리포지토리에 `config.json` 파일이 있으면 Hub에서 자동으로 분석을 활성화시킵니다 (예: "다운로드" 횟수). +보너스로, [`ModelHubMixin`]은 모델 구성을 자동으로 처리해 줍니다. 만약 당신의 `__init__` 메서드가 `config` 입력을 기대한다면, `save_pretrained`를 호출할 때 자동으로 리포지토리에 저장되고 `load_pretrained`에 의해 올바르게 다시 로드될 것입니다. 더불어, `config` 입력 매개변수가 dataclass 타입으로 주석 처리되어 있다면 (예: `config: Optional[MyConfigClass] = None`), 그렇게 하면 `config` 값이 올바르게 역직렬화됩니다. 마지막으로, 초기화할 때 전달된 모든 jsonable 값은 구성 파일에 저장됩니다. 이는 `config` 입력을 기대하지 않더라도 이를 활용할 수 있다는 것을 의미합니다. 모델 리포지토리에 `config.json` 파일이 있으면 Hub에서 자동으로 분석을 활성화시킵니다 (예: "다운로드" 횟수). 마지막으로, [`ModelHubMixin`]은 모델 카드 생성을 처리해줍니다. [`ModelHubMixin`]을 상속받을 때 `library_name`, `tags`, `repo_url`, `docs_url`과 같은 메타데이터를 정의할 수 있습니다. 이러한 필드는 클래스를 사용하는 모든 모델의 모델 카드를 채우는 데 재사용됩니다. 이는 Hub에서 라이브러리를 사용하는 모든 모델을 쉽게 검색할 수 있도록 만들고, Hub에 착륙하는 사용자에게 일부 리소스 링크를 제공하는 데 매우 유용합니다. 만약 모델 카드 템플릿을 확장하고 싶다면, [`~ModelHubMixin.generate_model_card`] 메서드를 재정의할 수 있습니다. From 3851802d90f74876767e8d1d800411ff18a93308 Mon Sep 17 00:00:00 2001 From: "Chulhwa (Evan) Han" Date: Mon, 29 Apr 2024 01:13:20 +0000 Subject: [PATCH 06/13] fix: manual edits --- docs/source/ko/guides/integrations.md | 183 +++++++++++++++++++++++--- 1 file changed, 165 insertions(+), 18 deletions(-) diff --git a/docs/source/ko/guides/integrations.md b/docs/source/ko/guides/integrations.md index cb9178316e..fcaa4c61e7 100644 --- a/docs/source/ko/guides/integrations.md +++ b/docs/source/ko/guides/integrations.md @@ -7,8 +7,8 @@ Hugging Face Hub는 커뮤니티와 모델을 공유하는 것을 쉽게 만들 라이브러리를 Hub와 통합하는 주요 네 가지 방법이 있습니다: -1. **Hub에 업로드하기**: 모델을 Hub에 업로드하는 메서드를 구현합니다. 이에는 모델 가중치뿐만 아니라 [모델 카드](https://huggingface.co/docs/huggingface_hub/how-to-model-cards) 및 모델 실행에 필요한 다른 관련 정보나 데이터(예: 훈련 로그)가 포함됩니다. 이 방법은 일반적으로 `push_to_hub()`라고 합니다. -2. **Hub에서 다운로드하기**: Hub에서 모델을 가져오는 메서드를 구현합니다. 이 메서드는 모델 구성/가중치를 다운로드하고 모델을 가져와야 합니다. 이 방법은 일반적으로 `from_pretrained` 또는 `load_from_hub()`라고 합니다. +1. **Hub에 업로드하기**: 모델을 Hub에 업로드하는 메소드를 구현합니다. 이에는 모델 가중치뿐만 아니라 [모델 카드](https://huggingface.co/docs/huggingface_hub/how-to-model-cards) 및 모델 실행에 필요한 다른 관련 정보나 데이터(예: 훈련 로그)가 포함됩니다. 이 방법은 일반적으로 `push_to_hub()`라고 합니다. +2. **Hub에서 다운로드하기**: Hub에서 모델을 가져오는 메소드를 구현합니다. 이 메소드는 모델 구성/가중치를 다운로드하고 모델을 가져와야 합니다. 이 방법은 일반적으로 `from_pretrained` 또는 `load_from_hub()`라고 합니다. 3. **추론 API**: 라이브러리에서 지원하는 모델에 대해 무료로 추론을 실행하기 위해 서버를 사용합니다. 4. **위젯**: Hub의 모델 랜딩 페이지에 위젯을 표시합니다. 이를 통해 사용자들은 브라우저에서 빠르게 모델을 시도할 수 있습니다. @@ -18,13 +18,13 @@ Hugging Face Hub는 커뮤니티와 모델을 공유하는 것을 쉽게 만들 ## 유연한 접근 방식: 도우미(helper)[[a-flexible-approach-helpers]] -라이브러리를 Hub에 통합하는 첫 번째 접근 방법은 실제로 `push_to_hub` 및 `from_pretrained` 메서드를 직접 구현하는 것입니다. 이를 통해 업로드/다운로드할 파일 및 입력을 처리하는 방법에 대한 완전한 유연성을 제공받을 수 있습니다. 이를 위해 [파일 업로드](./upload) 및 [파일 다운로드](./download) 가이드를 참조하여 자세히 알아볼 수 있습니다. 예를 들어 FastAI 통합이 구현된 방법을 보면 됩니다 ([`push_to_hub_fastai`] 및 [`from_pretrained_fastai`]를 참조). +라이브러리를 Hub에 통합하는 첫 번째 접근 방법은 실제로 `push_to_hub` 및 `from_pretrained` 메소드를 직접 구현하는 것입니다. 이를 통해 업로드/다운로드할 파일 및 입력을 처리하는 방법에 대한 완전한 유연성을 제공받을 수 있습니다. 이를 위해 [파일 업로드](./upload) 및 [파일 다운로드](./download) 가이드를 참조하여 자세히 알아볼 수 있습니다. 예를 들어 FastAI 통합이 구현된 방법을 보면 됩니다 ([`push_to_hub_fastai`] 및 [`from_pretrained_fastai`]를 참조). 라이브러리마다 구현 방식은 다를 수 있지만, 워크플로우는 일반적으로 비슷합니다. ### from_pretrained[[frompretrained]] -일반적으로 `from_pretrained` 메서드는 다음과 같은 형태를 가집니다: +일반적으로 `from_pretrained` 메소드는 다음과 같은 형태를 가집니다: ```python def from_pretrained(model_id: str) -> MyModelClass: @@ -42,7 +42,7 @@ def from_pretrained(model_id: str) -> MyModelClass: ### push_to_hub[[pushtohub]] -`push_to_hub` 메서드는 종종 레포지토리 생성, 모델 카드 생성 및 가중치 저장을 처리하기 위해 조금 더 복잡한 접근 방식이 필요합니다. 일반적으로 모든 이러한 파일을 임시 폴더에 저장한 다음 업로드하고 나중에 삭제하는 방식이 흔히 사용됩니다. +`push_to_hub` 메소드는 종종 레포지토리 생성, 모델 카드 생성 및 가중치 저장을 처리하기 위해 조금 더 복잡한 접근 방식이 필요합니다. 일반적으로 모든 이러한 파일을 임시 폴더에 저장한 다음 업로드하고 나중에 삭제하는 방식이 흔히 사용됩니다. ```python def push_to_hub(model: MyModelClass, repo_name: str) -> None: @@ -93,28 +93,28 @@ def push_to_hub(model: MyModelClass, repo_name: str) -> None: - `token` - ... -이러한 매개변수는 위에서 본 구현에 추가하여 `huggingface_hub` 메서드로 전달할 수 있습니다. 그러나 매개변수가 변경되거나 새로운 기능이 추가되는 경우에는 패키지를 업데이트해야 합니다. 이러한 매개변수를 지원하는 것은 유지 관리할 문서가 더 많아진다는 것을 의미합니다. 이러한 제한 사항을 어떻게 완화할 수 있는지 보려면 다음 섹션인 **클래스 상속**으로 이동해 보겠습니다. +이러한 매개변수는 위에서 본 구현에 추가하여 `huggingface_hub` 메소드로 전달할 수 있습니다. 그러나 매개변수가 변경되거나 새로운 기능이 추가되는 경우에는 패키지를 업데이트해야 합니다. 이러한 매개변수를 지원하는 것은 유지 관리할 문서가 더 많아진다는 것을 의미합니다. 이러한 제한 사항을 어떻게 완화할 수 있는지 보려면 다음 섹션인 **클래스 상속**으로 이동해 보겠습니다. ## 더욱 복잡한 접근법: 클래스 상속[[a-more-complex-approach-class-inheritance]] -위에서 보았듯이 Hub와 통합하기 위해 라이브러리에 포함해야 할 주요 메서드는 파일을 업로드하는 (`push_to_hub`) 및 파일을 다운로드하는 (`from_pretrained`)입니다. 이러한 메서드를 직접 구현할 수 있지만, 이에는 몇 가지 주의할 점이 있습니다. 이를 해결하기 위해 `huggingface_hub`은 클래스 상속을 사용하는 도구를 제공합니다. 이 도구가 어떻게 작동하는지 살펴보겠습니다! +위에서 보았듯이 Hub와 통합하기 위해 라이브러리에 포함해야 할 주요 메소드는 파일을 업로드하는 (`push_to_hub`) 및 파일을 다운로드하는 (`from_pretrained`)입니다. 이러한 메소드를 직접 구현할 수 있지만, 이에는 몇 가지 주의할 점이 있습니다. 이를 해결하기 위해 `huggingface_hub`은 클래스 상속을 사용하는 도구를 제공합니다. 이 도구가 어떻게 작동하는지 살펴보겠습니다! -많은 경우에 라이브러리는 이미 Python 클래스를 사용하여 모델을 구현합니다. 이 클래스에는 모델의 속성 및 로드, 실행, 훈련 및 평가하는 메서드가 포함되어 있습니다. 접근 방식은 [믹스인](https://stackoverflow.com/a/547714)을 사용하여 이 클래스를 확장하여 업로드 및 다운로드 기능을 포함하는 것입니다. 믹스인(Mixin)은 기존 클래스에 여러 상속을 통해 특정 기능을 확장하기 위해 설계된 클래스입니다. `huggingface_hub`은 자체 믹스인인 [`ModelHubMixin`]을 제공합니다. 이 중요한 점은 그 동작을 이해하고 사용자 정의하는 것입니다. +많은 경우에 라이브러리는 이미 Python 클래스를 사용하여 모델을 구현합니다. 이 클래스에는 모델의 속성 및 로드, 실행, 훈련 및 평가하는 메소드가 포함되어 있습니다. 접근 방식은 [믹스인](https://stackoverflow.com/a/547714)을 사용하여 이 클래스를 확장하여 업로드 및 다운로드 기능을 포함하는 것입니다. 믹스인(Mixin)은 기존 클래스에 여러 상속을 통해 특정 기능을 확장하기 위해 설계된 클래스입니다. `huggingface_hub`은 자체 믹스인인 [`ModelHubMixin`]을 제공합니다. 이 중요한 점은 그 동작을 이해하고 사용자 정의하는 것입니다. -[`ModelHubMixin`] 클래스는 세 개의 *공개* 메서드(`push_to_hub`, `save_pretrained`, `from_pretrained`)를 구현합니다. 이 메서드들은 사용자가 라이브러리를 사용하여 모델을 로드/저장할 때 호출하는 메서드입니다. 또한 [`ModelHubMixin`]은 두 개의 *비공개* 메서드(`_save_pretrained` 및 `_from_pretrained`)를 정의합니다. 이 메서드들을 구현해야 합니다. 라이브러리를 통합하려면: +[`ModelHubMixin`] 클래스는 세 개의 *공개* 메소드(`push_to_hub`, `save_pretrained`, `from_pretrained`)를 구현합니다. 이 메소드들은 사용자가 라이브러리를 사용하여 모델을 로드/저장할 때 호출하는 메소드입니다. 또한 [`ModelHubMixin`]은 두 개의 *비공개* 메소드(`_save_pretrained` 및 `_from_pretrained`)를 정의합니다. 이 메소드들을 구현해야 합니다. 라이브러리를 통합하려면: 1. 모델 클래스를 [`ModelHubMixin`]에서 상속합니다. -2. 비공개 메서드를 구현합니다: - - [`~ModelHubMixin._save_pretrained`]: 디렉터리 경로를 입력으로 받아 모델을 해당 디렉터리에 저장하는 메서드입니다. 이 메서드에는 모델 카드, 모델 가중치, 구성 파일, 훈련 로그 및 그림 등 해당 모델에 대한 모든 관련 정보를 덤프하기 위한 로직을 작성해야 합니다. [모델 카드](https://huggingface.co/docs/hub/model-cards)는 모델을 설명하는 데 특히 중요합니다. 더 자세한 내용은 [구현 가이드](./model-cards)를 확인하세요. - - [`~ModelHubMixin._from_pretrained`]: `model_id`를 입력으로 받아 인스턴스화된 모델을 반환하는 **클래스 메서드**입니다. 이 메서드는 관련 파일을 다운로드하고 로드해야 합니다. +2. 비공개 메소드를 구현합니다: + - [`~ModelHubMixin._save_pretrained`]: 디렉터리 경로를 입력으로 받아 모델을 해당 디렉터리에 저장하는 메소드입니다. 이 메소드에는 모델 카드, 모델 가중치, 구성 파일, 훈련 로그 및 그림 등 해당 모델에 대한 모든 관련 정보를 덤프하기 위한 로직을 작성해야 합니다. [모델 카드](https://huggingface.co/docs/hub/model-cards)는 모델을 설명하는 데 특히 중요합니다. 더 자세한 내용은 [구현 가이드](./model-cards)를 확인하세요. + - [`~ModelHubMixin._from_pretrained`]: `model_id`를 입력으로 받아 인스턴스화된 모델을 반환하는 **클래스 메소드**입니다. 이 메소드는 관련 파일을 다운로드하고 로드해야 합니다. 3. 완료했습니다! -[`ModelHubMixin`]의 장점은 파일의 직렬화/로드에만 신경을 쓰면 되기 때문에 즉시 사용할 수 있다는 것입니다. 레포지토리 생성, 커밋, PR 또는 리비전과 같은 사항에 대해 걱정할 필요가 없습니다. 이 모든 것은 믹스인에 의해 처리되며 사용자에게 제공됩니다. 믹스인은 또한 공개 메서드가 잘 문서화되고 타입이 주석이 달려있는지를 보장합니다. +[`ModelHubMixin`]의 장점은 파일의 직렬화/로드에만 신경을 쓰면 되기 때문에 즉시 사용할 수 있다는 것입니다. 레포지토리 생성, 커밋, PR 또는 리비전과 같은 사항에 대해 걱정할 필요가 없습니다. 이 모든 것은 믹스인에 의해 처리되며 사용자에게 제공됩니다. 믹스인은 또한 공개 메소드가 잘 문서화되고 타입이 주석이 달려있는지를 보장합니다. -보너스로, [`ModelHubMixin`]은 모델 구성을 자동으로 처리해 줍니다. 만약 당신의 `__init__` 메서드가 `config` 입력을 기대한다면, `save_pretrained`를 호출할 때 자동으로 레포에 저장되고 `load_pretrained`에 의해 올바르게 다시 로드될 것입니다. 더불어, `config` 입력 매개변수가 dataclass 타입으로 주석 처리되어 있다면 (예: `config: Optional[MyConfigClass] = None`), 그렇게 하면 `config` 값이 올바르게 역직렬화됩니다. 마지막으로, 초기화할 때 전달된 모든 jsonable 값은 구성 파일에 저장됩니다. 이는 `config` 입력을 기대하지 않더라도 이를 활용할 수 있다는 것을 의미합니다. 모델 리포지토리에 `config.json` 파일이 있으면 Hub에서 자동으로 분석을 활성화시킵니다 (예: "다운로드" 횟수). +보너스로, [`ModelHubMixin`]은 모델 구성을 자동으로 처리해 줍니다. 만약 당신의 `__init__` 메소드가 `config` 입력을 기대한다면, `save_pretrained`를 호출할 때 자동으로 레포에 저장되고 `load_pretrained`에 의해 올바르게 다시 로드될 것입니다. 더불어, `config` 입력 매개변수가 dataclass 타입으로 주석 처리되어 있다면 (예: `config: Optional[MyConfigClass] = None`), 그렇게 하면 `config` 값이 올바르게 역직렬화됩니다. 마지막으로, 초기화할 때 전달된 모든 jsonable 값은 구성 파일에 저장됩니다. 이는 `config` 입력을 기대하지 않더라도 이를 활용할 수 있다는 것을 의미합니다. 모델 리포지토리에 `config.json` 파일이 있으면 Hub에서 자동으로 분석을 활성화시킵니다 (예: "다운로드" 횟수). -마지막으로, [`ModelHubMixin`]은 모델 카드 생성을 처리해줍니다. [`ModelHubMixin`]을 상속받을 때 `library_name`, `tags`, `repo_url`, `docs_url`과 같은 메타데이터를 정의할 수 있습니다. 이러한 필드는 클래스를 사용하는 모든 모델의 모델 카드를 채우는 데 재사용됩니다. 이는 Hub에서 라이브러리를 사용하는 모든 모델을 쉽게 검색할 수 있도록 만들고, Hub에 착륙하는 사용자에게 일부 리소스 링크를 제공하는 데 매우 유용합니다. 만약 모델 카드 템플릿을 확장하고 싶다면, [`~ModelHubMixin.generate_model_card`] 메서드를 재정의할 수 있습니다. +마지막으로, [`ModelHubMixin`]은 모델 카드 생성을 처리해줍니다. [`ModelHubMixin`]을 상속받을 때 `library_name`, `tags`, `repo_url`, `docs_url`과 같은 메타데이터를 정의할 수 있습니다. 이러한 필드는 클래스를 사용하는 모든 모델의 모델 카드를 채우는 데 재사용됩니다. 이는 Hub에서 라이브러리를 사용하는 모든 모델을 쉽게 검색할 수 있도록 만들고, Hub에 착륙하는 사용자에게 일부 리소스 링크를 제공하는 데 매우 유용합니다. 만약 모델 카드 템플릿을 확장하고 싶다면, [`~ModelHubMixin.generate_model_card`] 메소드를 재정의할 수 있습니다. ### 자세한 예시: PyTorch[[a-concrete-example-pytorch]] @@ -188,7 +188,7 @@ class PyTorchModelHubMixin(ModelHubMixin): (...) ``` -2. `_save_pretrained` 메서드를 구현하세요: +2. `_save_pretrained` 메소드를 구현하세요: ```py from huggingface_hub import ModelHubMixin @@ -202,13 +202,13 @@ class PyTorchModelHubMixin(ModelHubMixin): ``` -3. `_from_pretrained` 메서드를 구현하세요: +3. `_from_pretrained` 메소드를 구현하세요: ```python class PyTorchModelHubMixin(ModelHubMixin): (...) - @classmethod # 반드시 클래스 메서드여야 합니다! + @classmethod # 반드시 클래스 메소드여야 합니다! def _from_pretrained( cls, *, @@ -247,6 +247,153 @@ class PyTorchModelHubMixin(ModelHubMixin): 이게 전부입니다! 이제 라이브러리를 통해 Hub로부터 파일을 업로드하고 다운로드할 수 있습니다. +### Advanced usage + +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. + +#### Model card + +[`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. + +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", + 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"] +): + ... +``` + +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! + +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 }} +--- + +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}, +} +""" + +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, ...): + (...) + + 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 +``` + +#### 구성[[config]] + +[ModelHubMixin]은 모델 구성을 처리합니다. 모델을 인스턴스화할 때 입력 값들을 자동으로 확인하고 이를 `config.json` 파일에 직렬화합니다. 이렇게 함으로써 두 가지 이점이 제공됩니다: + +1. 사용자는 정확히 동일한 매개변수로 모델을 다시 로드할 수 있습니다. +2. `config.json` 파일이 자동으로 생성되면 Hub에서 분석이 가능해집니다(즉, "다운로드" 횟수가 기록됩니다). + +하지만 이것이 실제로 어떻게 작동하는 걸까요? 사용자 관점에서 프로세스가 가능한 매끄럽도록 하기 위해 여러 규칙이 존재합니다: +- 만약 `__init__` 메소드가 `config` 입력을 기대한다면, 이는 자동으로 `config.json`으로 저장됩니다. +- 만약 `config` 입력 매개변수에 데이터 클래스 유형(예: `config: Optional[MyConfigClass] = None`)의 어노테이션이 있다면, config 값은 올바르게 역직렬화됩니다. +- 초기화할 때 전달된 모든 값들도 구성 파일에 저장됩니다. 이는 `config` 입력을 기대하지 않더라도 이점을 얻을 수 있다는 것을 의미합니다. + +예시: + +```py +class MyModel(ModelHubMixin): + def __init__(value: str, size: int = 3): + self.value = value + self.size = size + + (...) # _save_pretrained / _from_pretrained 구현 + +model = MyModel(value="my_value") +model.save_pretrained(...) + +# config.json 파일에는 전달된 값과 기본 값이 모두 포함됩니다. +{"value": "my_value", "size": 3} +``` + +그러나 값이 JSON으로 직렬화될 수 없는 경우는 어떻게 될까요? 기본적으로 구성 파일을 저장할 때 해당 값은 무시됩니다. 그러나 경우에 따라 라이브러리가 이미 직렬화할 수 없는 사용자 정의 객체를 예상하고 있고 해당 유형을 업데이트하고 싶지 않은 경우가 있습니다. 걱정 마세요! [`ModelHubMixin`]을 상속할 때 어떤 유형에 대한 사용자 지정 인코더/디코더를 전달할 수 있습니다. 이는 조금 더 많은 작업이 필요하지만 내부 로직을 변경하지 않고도 라이브러리를 Hub에 통합할 수 있도록 보장합니다. + +여기서 `argparse.Namespace` 구성을 입력으로 받는 클래스의 구체적인 예가 있습니다: + +```py +class VoiceCraft(nn.Module): + def __init__(self, args): + self.pattern = self.args.pattern + self.hidden_size = self.args.hidden_size + ... +``` + +한 가지 해결책은 `__init__` 시그니처를 `def __init__(self, pattern: str, hidden_size: int)`로 업데이트하고 클래스를 인스턴스화하는 모든 스니펫을 업데이트하는 것입니다. 이 방법은 완벽히 유효한 방법이지만, 여러분의 라이브러리를 사용하는 하위 응용 프로그램을 망가뜨릴 수 있습니다. + +다른 해결책은 `argparse.Namespace`를 사전으로 변환하는 간단한 인코더/디코더를 제공하는 것입니다. + +```py +from argparse import Namespace + +class VoiceCraft( + nn.Module, + PytorchModelHubMixin, # 믹스인을 상속합니다. + coders: { + Namespace = ( + lambda x: vars(x), # Encoder: `Namespace`를 유효한 JSON 형태로 변환하는 방법은 무엇인가요? + lambda data: Namespace(**data), # Decoder: 딕셔너리에서 Namespace를 재구성하는 방법은 무엇인가요? + ) + } +): + def __init__(self, args: Namespace): # `args`에 주석을 답니다. + self.pattern = self.args.pattern + self.hidden_size = self.args.hidden_size + ... +``` + +위의 코드 스니펫에서는 클래스의 내부 로직과 `__init__` 시그니처가 변경되지 않았습니다. 이는 기존의 모든 코드 스니펫이 여전히 작동한다는 것을 의미합니다. 이를 달성하기 위해 우리는 다음을 수행했습니다: +1. 믹스인(`PytorchModelHubMixin` 이 경우)으로부터 상속합니다. +2. 상속 시 `coders` 매개변수를 전달합니다. 이는 키가 처리하려는 사용자 지정 유형이고, 값은 튜플 `(인코더, 디코더)`입니다. + - 인코더는 지정된 유형의 객체를 입력으로 받아서 jsonable 값으로 반환합니다. 이는 `save_pretrained`로 모델을 저장할 때 사용됩니다. + - 디코더는 원시 데이터(일반적으로 딕셔너리 타입)를 입력으로 받아서 초기 객체를 재구성합니다. 이는 `from_pretrained`로 모델을 로드할 때 사용됩니다. + - `__init__` 시그니처에 유형 주석을 추가합니다. 이는 믹스인에게 클래스가 기대하는 유형과, 따라서 어떤 디코더를 사용해야 하는지를 알려주는 데 중요합니다. + +간단함을 위해 위의 예제에서 인코더/디코더 함수는 견고하지 않습니다. 구체적인 구현을 위해서는 대부분의 경우 코너 케이스를 적절하게 처리해야 할 것입니다. + ## 빠른 비교[[quick-comparison]] 두 가지 접근 방법에 대한 장단점을 간단히 정리해보겠습니다. 아래 표는 단순히 예시일 뿐입니다. 여러분의 프레임워크에는 고려해야 할 특정 사항이 있을 수 있습니다. 이 가이드는 통합을 다루는 아이디어와 지침을 제공하기 위한 것입니다. 언제든지 궁금한 점이 있으면 문의해 주세요! From 4f0a0421ad43b6473f01c7f213cbcdbf12d0379f Mon Sep 17 00:00:00 2001 From: "Chulhwa (Evan) Han" Date: Mon, 29 Apr 2024 02:08:04 +0000 Subject: [PATCH 07/13] fix: manual edits --- docs/source/ko/guides/integrations.md | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/docs/source/ko/guides/integrations.md b/docs/source/ko/guides/integrations.md index a10055d0ba..2ca05be1f2 100644 --- a/docs/source/ko/guides/integrations.md +++ b/docs/source/ko/guides/integrations.md @@ -247,15 +247,15 @@ class PyTorchModelHubMixin(ModelHubMixin): 이게 전부입니다! 이제 라이브러리를 통해 Hub로부터 파일을 업로드하고 다운로드할 수 있습니다. -### Advanced usage +### 고급 사용법[[advanced-usage]] -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. +위의 섹션에서는 [`ModelHubMixin`]이 어떻게 작동하는지 간단히 살펴보았습니다. 이번 섹션에서는 Hugging Face Hub와 라이브러리 통합을 개선하기 위한 더 고급 기능 중 일부를 살펴보겠습니다. -#### Model card +#### 모델 카드[[model-card]] -[`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. +[`ModelHubMixin`]은 모델 카드를 자동으로 생성합니다. 모델 카드는 모델과 함께 제공되는 중요한 정보를 제공하는 파일입니다. 모델 카드는 추가 메타데이터가 포함된 간단한 Markdown 파일입니다. 모델 카드는 발견 가능성, 재현성 및 공유를 위해 중요합니다! 더 자세한 내용은 [모델 카드 가이드](https://huggingface.co/docs/hub/model-cards)를 확인하세요. -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`]: +모델 카드를 준자동적으로 생성하는 것은 모든 라이브러리로 푸시된 모델이 `library_name`, `tags`, `license`, `pipeline_tag` 등과 같은 일반적인 메타데이터를 공유하도록 하는 좋은 방법입니다. 이를 통해 모든 모델이 Hub에서 쉽게 검색 가능하게 되고, Hub에 접속한 사용자에게 일부 리소스 링크를 제공합니다. [`ModelHubMixin`]을 상속할 때 메타데이터를 직접 정의할 수 있습니다: ```py class UniDepthV1( @@ -271,9 +271,9 @@ class UniDepthV1( ... ``` -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! +기본적으로는 제공된 정보로 일반적인 모델 카드가 생성됩니다(예: [pyp1/VoiceCraft_giga830M](https://huggingface.co/pyp1/VoiceCraft_giga830M)). 그러나 사용자 정의 모델 카드 템플릿을 정의할 수도 있습니다! -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). +이 예에서는 `VoiceCraft` 클래스로 푸시된 모든 모델에 자동으로 인용 부분과 라이선스 세부 정보가 포함됩니다. 모델 카드 템플릿을 정의하는 방법에 대한 자세한 내용은 [모델 카드 가이드](./model-cards)를 참조하세요. ```py MODEL_CARD_TEMPLATE = """ @@ -305,8 +305,7 @@ class VoiceCraft( ... ``` - -Finally, if you want to extend the model card generation process with dynamic values, you can override the [`~ModelHubMixin.generate_model_card`] method: +마지막으로, 모델 카드 생성 프로세스를 동적 값으로 확장하려면 [`~ModelHubMixin.generate_model_card`] 메소드를 재정의할 수 있습니다: ```py from huggingface_hub import ModelCard, PyTorchModelHubMixin @@ -316,14 +315,14 @@ 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 + card.data.metrics = ... # 메타데이터에 메트릭 추가 + card.text += ... # 모델 카드에 섹션 추가 return card ``` #### 구성[[config]] -[ModelHubMixin]은 모델 구성을 처리합니다. 모델을 인스턴스화할 때 입력 값들을 자동으로 확인하고 이를 `config.json` 파일에 직렬화합니다. 이렇게 함으로써 두 가지 이점이 제공됩니다: +[`ModelHubMixin`]은 모델 구성을 처리합니다. 모델을 인스턴스화할 때 입력 값들을 자동으로 확인하고 이를 `config.json` 파일에 직렬화합니다. 이렇게 함으로써 두 가지 이점이 제공됩니다: 1. 사용자는 정확히 동일한 매개변수로 모델을 다시 로드할 수 있습니다. 2. `config.json` 파일이 자동으로 생성되면 Hub에서 분석이 가능해집니다(즉, "다운로드" 횟수가 기록됩니다). From bd8623dba1840a916d8fbed12499e4b568c49a7e Mon Sep 17 00:00:00 2001 From: "Chulhwa (Evan) Han" Date: Mon, 29 Apr 2024 02:08:18 +0000 Subject: [PATCH 08/13] fix: manual edits --- docs/source/ko/guides/integrations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/ko/guides/integrations.md b/docs/source/ko/guides/integrations.md index 2ca05be1f2..b444db49d9 100644 --- a/docs/source/ko/guides/integrations.md +++ b/docs/source/ko/guides/integrations.md @@ -350,7 +350,7 @@ model.save_pretrained(...) ``` 그러나 값이 JSON으로 직렬화될 수 없는 경우는 어떻게 될까요? 기본적으로 구성 파일을 저장할 때 해당 값은 무시됩니다. 그러나 경우에 따라 라이브러리가 이미 직렬화할 수 없는 사용자 정의 객체를 예상하고 있고 해당 유형을 업데이트하고 싶지 않은 경우가 있습니다. 걱정 마세요! [`ModelHubMixin`]을 상속할 때 어떤 유형에 대한 사용자 지정 인코더/디코더를 전달할 수 있습니다. 이는 조금 더 많은 작업이 필요하지만 내부 로직을 변경하지 않고도 라이브러리를 Hub에 통합할 수 있도록 보장합니다. -ㄹ + 여기서 `argparse.Namespace` 구성을 입력으로 받는 클래스의 구체적인 예가 있습니다: ```py From 7e803ad39aace46d93a9b0f68c3b0be28d863f94 Mon Sep 17 00:00:00 2001 From: "Chulhwa (Evan) Han" Date: Tue, 21 May 2024 23:20:44 +0900 Subject: [PATCH 09/13] Apply suggestions from code review Co-authored-by: usr/bin/ksh <95210697+usr-bin-ksh@users.noreply.github.com> Co-authored-by: SeongWooChoi <46990061+nuatmochoi@users.noreply.github.com> --- docs/source/ko/guides/integrations.md | 30 +++++++++++++-------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/docs/source/ko/guides/integrations.md b/docs/source/ko/guides/integrations.md index b444db49d9..7317a5bd8f 100644 --- a/docs/source/ko/guides/integrations.md +++ b/docs/source/ko/guides/integrations.md @@ -3,16 +3,16 @@ rendered properly in your Markdown viewer. --> # Hub와 어떤 머신 러닝 프레임워크든 통합[[integrate-any-ml-framework-with-the-hub]] -Hugging Face Hub는 커뮤니티와 모델을 공유하는 것을 쉽게 만들어줍니다. 이는 오픈소스 생태계의 [수십 가지 라이브러리](https://huggingface.co/docs/hub/models-libraries)를 지원합니다. 저희는 항상 협업적인 머신 러닝을 전진시키기 위해 이 지원을 확대하기 위해 노력하고 있습니다. `huggingface_hub` 라이브러리는 어떤 Python 스크립트든지 쉽게 파일을 업로드하고 로드할 수 있도록 하는 데 중요한 역할을 합니다. +Hugging Face Hub는 커뮤니티와 모델을 공유하는 것을 쉽게 만들어줍니다. 이는 오픈소스 생태계의 [수십 가지 라이브러리](https://huggingface.co/docs/hub/models-libraries)를 지원합니다. 저희는 항상 협업적인 머신 러닝을 전진시키기 위해 이 라이브러리를 확대하고자 노력하고 있습니다. `huggingface_hub` 라이브러리는 어떤 Python 스크립트든지 쉽게 파일을 업로드하고 가져올 수 있는 중요한 역할을 합니다. 라이브러리를 Hub와 통합하는 주요 네 가지 방법이 있습니다: -1. **Hub에 업로드하기**: 모델을 Hub에 업로드하는 메소드를 구현합니다. 이에는 모델 가중치뿐만 아니라 [모델 카드](https://huggingface.co/docs/huggingface_hub/how-to-model-cards) 및 모델 실행에 필요한 다른 관련 정보나 데이터(예: 훈련 로그)가 포함됩니다. 이 방법은 일반적으로 `push_to_hub()`라고 합니다. -2. **Hub에서 다운로드하기**: Hub에서 모델을 가져오는 메소드를 구현합니다. 이 메소드는 모델 구성/가중치를 다운로드하고 모델을 가져와야 합니다. 이 방법은 일반적으로 `from_pretrained` 또는 `load_from_hub()`라고 합니다. +1. **Hub에 업로드하기**: 모델을 Hub에 업로드하는 메소드를 구현합니다. 이에는 모델 가중치뿐만 아니라 [모델 카드](https://huggingface.co/docs/huggingface_hub/how-to-model-cards) 및 모델 실행에 필요한 다른 관련 정보나 데이터(예: 훈련 로그)가 포함됩니다. 이 메소드는 일반적으로 `push_to_hub()`라고 합니다. +2. **Hub에서 다운로드하기**: Hub에서 모델을 가져오는 메소드를 구현합니다. 이 메소드는 모델 구성/가중치를 다운로드하고 모델을 가져와야 합니다. 이 메소드는 일반적으로 `from_pretrained` 또는 `load_from_hub()`라고 합니다. 3. **추론 API**: 라이브러리에서 지원하는 모델에 대해 무료로 추론을 실행하기 위해 서버를 사용합니다. 4. **위젯**: Hub의 모델 랜딩 페이지에 위젯을 표시합니다. 이를 통해 사용자들은 브라우저에서 빠르게 모델을 시도할 수 있습니다. -이 가이드에서는 앞의 두 가지 주제에 중점을 둘 것입니다. 두 가지 주요 통합 방법을 소개하고 각각의 장단점을 설명할 것입니다. 이를 요약하여 두 가지 중 어떤 것을 선택할지에 대한 도움이 될 것입니다. 이는 단지 가이드라는 것을 명심하고 상황에 맞게 적응시킬 수 있는 가이드라는 점을 유념하십시오. +이 가이드에서는 앞의 두 가지 주제에 중점을 둘 것입니다. 우리는 라이브러리를 통합하는 데 사용할 수 있는 두 가지 주요 방법을 소개하고 각각의 장단점을 설명할 것입니다. 두 가지 중 어떤 것을 선택할지에 대한 도움이 되도록 끝 부분에 내용이 요약되어 있습니다. 이는 단지 가이드라는 것을 명심하고 상황에 맞게 적응시킬 수 있는 가이드라는 점을 유념하십시오. 추론 및 위젯에 관심이 있는 경우 [이 가이드](https://huggingface.co/docs/hub/models-adding-libraries#set-up-the-inference-api)를 참조할 수 있습니다. 양쪽 모두에서 라이브러리를 Hub와 통합하고 [문서](https://huggingface.co/docs/hub/models-libraries)에 목록에 게시하고자 하는 경우에는 언제든지 저희에게 연락하실 수 있습니다. @@ -76,7 +76,7 @@ def push_to_hub(model: MyModelClass, repo_name: str) -> None: ### 제한[[limitations]] -유연성을 가지고 있지만, 이 방식은 유지보수 측면에서 일부 단점을 가지고 있습니다. Hugging Face 사용자들은 `huggingface_hub`와 함께 작업할 때 추가 기능에 익숙합니다. 예를 들어, Hub에서 파일을 로드할 때 다음과 같은 매개변수를 제공하는 것이 일반적입니다: +이러한 방식은 유연성을 가지고 있지만, 유지보수 측면에서 일부 단점을 가지고 있습니다. Hugging Face 사용자들은 `huggingface_hub`와 함께 작업할 때 추가 기능에 익숙합니다. 예를 들어, Hub에서 파일을 로드할 때 다음과 같은 매개변수를 제공하는 것이 일반적입니다: - `token`: 개인 리포지토리에서 다운로드하기 위한 토큰 - `revision`: 특정 브랜치에서 다운로드하기 위한 리비전 @@ -93,24 +93,24 @@ def push_to_hub(model: MyModelClass, repo_name: str) -> None: - `token` - ... -이러한 매개변수는 위에서 본 구현에 추가하여 `huggingface_hub` 메소드로 전달할 수 있습니다. 그러나 매개변수가 변경되거나 새로운 기능이 추가되는 경우에는 패키지를 업데이트해야 합니다. 이러한 매개변수를 지원하는 것은 유지 관리할 문서가 더 많아진다는 것을 의미합니다. 이러한 제한 사항을 어떻게 완화할 수 있는지 보려면 다음 섹션인 **클래스 상속**으로 이동해 보겠습니다. +이러한 매개변수는 위에서 본 구현에 추가하여 `huggingface_hub` 메소드로 전달할 수 있습니다. 그러나 매개변수가 변경되거나 새로운 기능이 추가되는 경우에는 패키지를 업데이트해야 합니다. 이러한 매개변수를 지원하는 것은 유지 관리할 문서가 더 많아진다는 것을 의미합니다. 이러한 제한 사항을 완화할 수 있는 방법을 보려면 다음 섹션인 **클래스 상속**으로 이동해 보겠습니다. ## 더욱 복잡한 접근법: 클래스 상속[[a-more-complex-approach-class-inheritance]] -위에서 보았듯이 Hub와 통합하기 위해 라이브러리에 포함해야 할 주요 메소드는 파일을 업로드하는 (`push_to_hub`) 및 파일을 다운로드하는 (`from_pretrained`)입니다. 이러한 메소드를 직접 구현할 수 있지만, 이에는 몇 가지 주의할 점이 있습니다. 이를 해결하기 위해 `huggingface_hub`은 클래스 상속을 사용하는 도구를 제공합니다. 이 도구가 어떻게 작동하는지 살펴보겠습니다! +위에서 보았듯이 Hub와 통합하기 위해 라이브러리에 포함해야 할 주요 메소드는 파일을 업로드 (`push_to_hub`) 와 파일 다운로드 (`from_pretrained`)입니다. 이러한 메소드를 직접 구현할 수 있지만, 이에는 몇 가지 주의할 점이 있습니다. 이를 해결하기 위해 `huggingface_hub`은 클래스 상속을 사용하는 도구를 제공합니다. 이 도구가 어떻게 작동하는지 살펴보겠습니다! -많은 경우에 라이브러리는 이미 Python 클래스를 사용하여 모델을 구현합니다. 이 클래스에는 모델의 속성 및 로드, 실행, 훈련 및 평가하는 메소드가 포함되어 있습니다. 접근 방식은 [믹스인](https://stackoverflow.com/a/547714)을 사용하여 이 클래스를 확장하여 업로드 및 다운로드 기능을 포함하는 것입니다. 믹스인(Mixin)은 기존 클래스에 여러 상속을 통해 특정 기능을 확장하기 위해 설계된 클래스입니다. `huggingface_hub`은 자체 믹스인인 [`ModelHubMixin`]을 제공합니다. 이 중요한 점은 그 동작을 이해하고 사용자 정의하는 것입니다. +많은 경우에 라이브러리는 이미 Python 클래스를 사용하여 모델을 구현합니다. 이 클래스에는 모델의 속성 및 로드, 실행, 훈련 및 평가하는 메소드가 포함되어 있습니다. 접근 방식은 믹스인을 사용하여 이 클래스를 확장하여 업로드 및 다운로드 기능을 포함하는 것입니다. [믹스인(Mixin)](https://stackoverflow.com/a/547714)은 기존 클래스에 여러 상속을 통해 특정 기능을 확장하기 위해 설계된 클래스입니다. `huggingface_hub`은 자체 믹스인인 [`ModelHubMixin`]을 제공합니다. 여기서 핵심은 동작과 이를 사용자 정의하는 방법을 이해하는 것입니다. -[`ModelHubMixin`] 클래스는 세 개의 *공개* 메소드(`push_to_hub`, `save_pretrained`, `from_pretrained`)를 구현합니다. 이 메소드들은 사용자가 라이브러리를 사용하여 모델을 로드/저장할 때 호출하는 메소드입니다. 또한 [`ModelHubMixin`]은 두 개의 *비공개* 메소드(`_save_pretrained` 및 `_from_pretrained`)를 정의합니다. 이 메소드들을 구현해야 합니다. 라이브러리를 통합하려면: +[`ModelHubMixin`] 클래스는 세 개의 *공개* 메소드(`push_to_hub`, `save_pretrained`, `from_pretrained`)를 구현합니다. 이 메소드들은 사용자가 라이브러리를 사용하여 모델을 로드/저장할 때 호출하는 메소드입니다. 또한 [`ModelHubMixin`]은 두 개의 *비공개* 메소드(`_save_pretrained` 및 `_from_pretrained`)를 정의합니다. 라이브러리를 통합하려면 이 메소드들을 구현해야 합니다. : 1. 모델 클래스를 [`ModelHubMixin`]에서 상속합니다. 2. 비공개 메소드를 구현합니다: - - [`~ModelHubMixin._save_pretrained`]: 디렉터리 경로를 입력으로 받아 모델을 해당 디렉터리에 저장하는 메소드입니다. 이 메소드에는 모델 카드, 모델 가중치, 구성 파일, 훈련 로그 및 그림 등 해당 모델에 대한 모든 관련 정보를 덤프하기 위한 로직을 작성해야 합니다. [모델 카드](https://huggingface.co/docs/hub/model-cards)는 모델을 설명하는 데 특히 중요합니다. 더 자세한 내용은 [구현 가이드](./model-cards)를 확인하세요. - - [`~ModelHubMixin._from_pretrained`]: `model_id`를 입력으로 받아 인스턴스화된 모델을 반환하는 **클래스 메소드**입니다. 이 메소드는 관련 파일을 다운로드하고 로드해야 합니다. + - [`~ModelHubMixin._save_pretrained`]: 디렉터리 경로를 입력으로 받아 모델을 해당 디렉터리에 저장하는 메소드입니다. 이 메소드에는 모델 카드, 모델 가중치, 구성 파일, 훈련 로그 및 그림 등 해당 모델에 대한 모든 관련 정보를 저장하기 위한 로직을 작성해야 합니다. [모델 카드](https://huggingface.co/docs/hub/model-cards)는 모델을 설명하는 데 특히 중요합니다. 더 자세한 내용은 [구현 가이드](./model-cards)를 확인하세요. + - [`~ModelHubMixin._from_pretrained`]: `model_id`를 입력으로 받아 인스턴스화된 모델을 반환하는 **클래스 메소드**입니다. 이 메소드는 관련 파일을 다운로드하고 가져와야 합니다. 3. 완료했습니다! -[`ModelHubMixin`]의 장점은 파일의 직렬화/로드에만 신경을 쓰면 되기 때문에 즉시 사용할 수 있다는 것입니다. 리포지토리 생성, 커밋, PR 또는 리비전과 같은 사항에 대해 걱정할 필요가 없습니다. 이 모든 것은 믹스인에 의해 처리되며 사용자에게 제공됩니다. 믹스인은 또한 공개 메소드가 잘 문서화되고 타입이 주석이 달려있는지를 보장합니다. +[`ModelHubMixin`]의 장점은 파일의 직렬화/로드에만 신경을 쓰면 되기 때문에 즉시 사용할 수 있다는 것입니다. 리포지토리 생성, 커밋, PR 또는 리비전과 같은 사항에 대해 걱정할 필요가 없습니다. [`ModelHubMixin`]은 또한 공개 메소드가 문서화되고 타입에 주석이 달려있는지를 확인하며, 허브에서 모델의 다운로드 수를 볼 수 있도록 합니다. 이 모든 것은 [`ModelHubMixin`]에 의해 처리되며 사용자에게 제공됩니다. 보너스로, [`ModelHubMixin`]은 모델 구성을 자동으로 처리해 줍니다. 만약 당신의 `__init__` 메소드가 `config` 입력을 기대한다면, `save_pretrained`를 호출할 때 자동으로 리포지토리에 저장되고 `load_pretrained`에 의해 올바르게 다시 로드될 것입니다. 더불어, `config` 입력 매개변수가 dataclass 타입으로 주석 처리되어 있다면 (예: `config: Optional[MyConfigClass] = None`), 그렇게 하면 `config` 값이 올바르게 역직렬화됩니다. 마지막으로, 초기화할 때 전달된 모든 jsonable 값은 구성 파일에 저장됩니다. 이는 `config` 입력을 기대하지 않더라도 이를 활용할 수 있다는 것을 의미합니다. 모델 리포지토리에 `config.json` 파일이 있으면 Hub에서 자동으로 분석을 활성화시킵니다 (예: "다운로드" 횟수). @@ -224,7 +224,7 @@ class PyTorchModelHubMixin(ModelHubMixin): strict: bool = False, # 추가 인자 **model_kwargs, ): - """PyTorch의 사전 학습된 가중치를 로드하고 로드된 모델을 반환합니다.""" + """PyTorch의 사전 학습된 가중치와 모델을 반환합니다.""" model = cls(**model_kwargs) if os.path.isdir(model_id): print("Loading weights from local directory") @@ -255,7 +255,7 @@ class PyTorchModelHubMixin(ModelHubMixin): [`ModelHubMixin`]은 모델 카드를 자동으로 생성합니다. 모델 카드는 모델과 함께 제공되는 중요한 정보를 제공하는 파일입니다. 모델 카드는 추가 메타데이터가 포함된 간단한 Markdown 파일입니다. 모델 카드는 발견 가능성, 재현성 및 공유를 위해 중요합니다! 더 자세한 내용은 [모델 카드 가이드](https://huggingface.co/docs/hub/model-cards)를 확인하세요. -모델 카드를 준자동적으로 생성하는 것은 모든 라이브러리로 푸시된 모델이 `library_name`, `tags`, `license`, `pipeline_tag` 등과 같은 일반적인 메타데이터를 공유하도록 하는 좋은 방법입니다. 이를 통해 모든 모델이 Hub에서 쉽게 검색 가능하게 되고, Hub에 접속한 사용자에게 일부 리소스 링크를 제공합니다. [`ModelHubMixin`]을 상속할 때 메타데이터를 직접 정의할 수 있습니다: +모델 카드를 반자동으로 생성하는 것은 라이브러리로 푸시된 모든 모델이 `library_name`, `tags`, `license`, `pipeline_tag` 등과 같은 공통 메타데이터를 공유하도록 하는 좋은 방법입니다. 이를 통해 모든 모델이 Hub에서 쉽게 검색 가능하게 되고, Hub에 접속한 사용자에게 일부 리소스 링크를 제공합니다. [`ModelHubMixin`]을 상속할 때 메타데이터를 직접 정의할 수 있습니다: ```py class UniDepthV1( @@ -324,7 +324,7 @@ class UniDepthV1(nn.Module, PyTorchModelHubMixin, ...): [`ModelHubMixin`]은 모델 구성을 처리합니다. 모델을 인스턴스화할 때 입력 값들을 자동으로 확인하고 이를 `config.json` 파일에 직렬화합니다. 이렇게 함으로써 두 가지 이점이 제공됩니다: -1. 사용자는 정확히 동일한 매개변수로 모델을 다시 로드할 수 있습니다. +1. 사용자는 정확히 동일한 매개변수로 모델을 다시 가져올 수 있습니다. 2. `config.json` 파일이 자동으로 생성되면 Hub에서 분석이 가능해집니다(즉, "다운로드" 횟수가 기록됩니다). 하지만 이것이 실제로 어떻게 작동하는 걸까요? 사용자 관점에서 프로세스가 가능한 매끄럽도록 하기 위해 여러 규칙이 존재합니다: From c94299ece6e06c689e9790771417b5867ce0a02f Mon Sep 17 00:00:00 2001 From: "Chulhwa (Evan) Han" Date: Tue, 21 May 2024 23:24:27 +0900 Subject: [PATCH 10/13] Apply suggestions from code review --- docs/source/ko/guides/integrations.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs/source/ko/guides/integrations.md b/docs/source/ko/guides/integrations.md index 7317a5bd8f..5cea7cfd6c 100644 --- a/docs/source/ko/guides/integrations.md +++ b/docs/source/ko/guides/integrations.md @@ -112,9 +112,7 @@ def push_to_hub(model: MyModelClass, repo_name: str) -> None: [`ModelHubMixin`]의 장점은 파일의 직렬화/로드에만 신경을 쓰면 되기 때문에 즉시 사용할 수 있다는 것입니다. 리포지토리 생성, 커밋, PR 또는 리비전과 같은 사항에 대해 걱정할 필요가 없습니다. [`ModelHubMixin`]은 또한 공개 메소드가 문서화되고 타입에 주석이 달려있는지를 확인하며, 허브에서 모델의 다운로드 수를 볼 수 있도록 합니다. 이 모든 것은 [`ModelHubMixin`]에 의해 처리되며 사용자에게 제공됩니다. -보너스로, [`ModelHubMixin`]은 모델 구성을 자동으로 처리해 줍니다. 만약 당신의 `__init__` 메소드가 `config` 입력을 기대한다면, `save_pretrained`를 호출할 때 자동으로 리포지토리에 저장되고 `load_pretrained`에 의해 올바르게 다시 로드될 것입니다. 더불어, `config` 입력 매개변수가 dataclass 타입으로 주석 처리되어 있다면 (예: `config: Optional[MyConfigClass] = None`), 그렇게 하면 `config` 값이 올바르게 역직렬화됩니다. 마지막으로, 초기화할 때 전달된 모든 jsonable 값은 구성 파일에 저장됩니다. 이는 `config` 입력을 기대하지 않더라도 이를 활용할 수 있다는 것을 의미합니다. 모델 리포지토리에 `config.json` 파일이 있으면 Hub에서 자동으로 분석을 활성화시킵니다 (예: "다운로드" 횟수). -마지막으로, [`ModelHubMixin`]은 모델 카드 생성을 처리해줍니다. [`ModelHubMixin`]을 상속받을 때 `library_name`, `tags`, `repo_url`, `docs_url`과 같은 메타데이터를 정의할 수 있습니다. 이러한 필드는 클래스를 사용하는 모든 모델의 모델 카드를 채우는 데 재사용됩니다. 이는 Hub에서 라이브러리를 사용하는 모든 모델을 쉽게 검색할 수 있도록 만들고, Hub에 착륙하는 사용자에게 일부 리소스 링크를 제공하는 데 매우 유용합니다. 만약 모델 카드 템플릿을 확장하고 싶다면, [`~ModelHubMixin.generate_model_card`] 메소드를 재정의할 수 있습니다. ### 자세한 예시: PyTorch[[a-concrete-example-pytorch]] From de6401b04c7b9e4efe76c7b0f91411b02ca8d982 Mon Sep 17 00:00:00 2001 From: "Chulhwa (Evan) Han" Date: Wed, 22 May 2024 21:13:03 +0900 Subject: [PATCH 11/13] Apply suggestions from code review --- docs/source/ko/guides/integrations.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/source/ko/guides/integrations.md b/docs/source/ko/guides/integrations.md index 5cea7cfd6c..2e97f22526 100644 --- a/docs/source/ko/guides/integrations.md +++ b/docs/source/ko/guides/integrations.md @@ -14,7 +14,7 @@ Hugging Face Hub는 커뮤니티와 모델을 공유하는 것을 쉽게 만들 이 가이드에서는 앞의 두 가지 주제에 중점을 둘 것입니다. 우리는 라이브러리를 통합하는 데 사용할 수 있는 두 가지 주요 방법을 소개하고 각각의 장단점을 설명할 것입니다. 두 가지 중 어떤 것을 선택할지에 대한 도움이 되도록 끝 부분에 내용이 요약되어 있습니다. 이는 단지 가이드라는 것을 명심하고 상황에 맞게 적응시킬 수 있는 가이드라는 점을 유념하십시오. -추론 및 위젯에 관심이 있는 경우 [이 가이드](https://huggingface.co/docs/hub/models-adding-libraries#set-up-the-inference-api)를 참조할 수 있습니다. 양쪽 모두에서 라이브러리를 Hub와 통합하고 [문서](https://huggingface.co/docs/hub/models-libraries)에 목록에 게시하고자 하는 경우에는 언제든지 저희에게 연락하실 수 있습니다. +추론 및 위젯에 관심이 있는 경우 [이 가이드](https://huggingface.co/docs/hub/models-adding-libraries#set-up-the-inference-api)를 참조할 수 있습니다. 양쪽 모두에서 라이브러리를 Hub와 통합하고 [문서](https://huggingface.co/docs/hub/models-libraries)에 목록에 게시하고자 하는 경우에는 언제든지 연락하실 수 있습니다. ## 유연한 접근 방식: 도우미(helper)[[a-flexible-approach-helpers]] @@ -112,8 +112,6 @@ def push_to_hub(model: MyModelClass, repo_name: str) -> None: [`ModelHubMixin`]의 장점은 파일의 직렬화/로드에만 신경을 쓰면 되기 때문에 즉시 사용할 수 있다는 것입니다. 리포지토리 생성, 커밋, PR 또는 리비전과 같은 사항에 대해 걱정할 필요가 없습니다. [`ModelHubMixin`]은 또한 공개 메소드가 문서화되고 타입에 주석이 달려있는지를 확인하며, 허브에서 모델의 다운로드 수를 볼 수 있도록 합니다. 이 모든 것은 [`ModelHubMixin`]에 의해 처리되며 사용자에게 제공됩니다. - - ### 자세한 예시: PyTorch[[a-concrete-example-pytorch]] 위에서 언급한 내용의 좋은 예시는 [`PyTorchModelHubMixin`]입니다. 이것은 PyTorch 프레임워크를 위한 저희의 통합입니다. 이것은 즉시 사용할 수 있는 통합입니다. @@ -393,7 +391,7 @@ class VoiceCraft( ## 빠른 비교[[quick-comparison]] -두 가지 접근 방법에 대한 장단점을 간단히 정리해보겠습니다. 아래 표는 단순히 예시일 뿐입니다. 여러분의 프레임워크에는 고려해야 할 특정 사항이 있을 수 있습니다. 이 가이드는 통합을 다루는 아이디어와 지침을 제공하기 위한 것입니다. 언제든지 궁금한 점이 있으면 문의해 주세요! +두 가지 접근 방법에 대한 장단점을 간단히 정리해보겠습니다. 아래 표는 단순히 예시일 뿐입니다. 각자 다른 프레임워크에는 고려해야 할 특정 사항이 있을 수 있습니다. 이 가이드는 통합을 다루는 아이디어와 지침을 제공하기 위한 것입니다. 언제든지 궁금한 점이 있으면 문의해 주세요! | Integration | Using helpers | Using [`ModelHubMixin`] | From c972a7df26d80304d3affe68f4393eac80824787 Mon Sep 17 00:00:00 2001 From: "Chulhwa (Evan) Han" Date: Mon, 27 May 2024 13:56:19 +0900 Subject: [PATCH 12/13] Apply suggestions from code review Co-authored-by: Jihun Lim <31366038+heuristicwave@users.noreply.github.com> Co-authored-by: SeongWooChoi <46990061+nuatmochoi@users.noreply.github.com> --- docs/source/ko/guides/integrations.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/source/ko/guides/integrations.md b/docs/source/ko/guides/integrations.md index 2e97f22526..c5252c7228 100644 --- a/docs/source/ko/guides/integrations.md +++ b/docs/source/ko/guides/integrations.md @@ -3,13 +3,13 @@ rendered properly in your Markdown viewer. --> # Hub와 어떤 머신 러닝 프레임워크든 통합[[integrate-any-ml-framework-with-the-hub]] -Hugging Face Hub는 커뮤니티와 모델을 공유하는 것을 쉽게 만들어줍니다. 이는 오픈소스 생태계의 [수십 가지 라이브러리](https://huggingface.co/docs/hub/models-libraries)를 지원합니다. 저희는 항상 협업적인 머신 러닝을 전진시키기 위해 이 라이브러리를 확대하고자 노력하고 있습니다. `huggingface_hub` 라이브러리는 어떤 Python 스크립트든지 쉽게 파일을 업로드하고 가져올 수 있는 중요한 역할을 합니다. +Hugging Face Hub는 커뮤니티와 모델을 공유하는 것을 쉽게 만들어줍니다. 이는 오픈소스 생태계의 [수십 가지 라이브러리](https://huggingface.co/docs/hub/models-libraries)를 지원합니다. 저희는 항상 협업적인 머신 러닝을 발전시키기 위해 이 라이브러리를 확대하고자 노력하고 있습니다. `huggingface_hub` 라이브러리는 어떤 Python 스크립트든지 쉽게 파일을 업로드하고 가져올 수 있는 중요한 역할을 합니다. 라이브러리를 Hub와 통합하는 주요 네 가지 방법이 있습니다: 1. **Hub에 업로드하기**: 모델을 Hub에 업로드하는 메소드를 구현합니다. 이에는 모델 가중치뿐만 아니라 [모델 카드](https://huggingface.co/docs/huggingface_hub/how-to-model-cards) 및 모델 실행에 필요한 다른 관련 정보나 데이터(예: 훈련 로그)가 포함됩니다. 이 메소드는 일반적으로 `push_to_hub()`라고 합니다. 2. **Hub에서 다운로드하기**: Hub에서 모델을 가져오는 메소드를 구현합니다. 이 메소드는 모델 구성/가중치를 다운로드하고 모델을 가져와야 합니다. 이 메소드는 일반적으로 `from_pretrained` 또는 `load_from_hub()`라고 합니다. -3. **추론 API**: 라이브러리에서 지원하는 모델에 대해 무료로 추론을 실행하기 위해 서버를 사용합니다. +3. **추론 API**: 라이브러리에서 지원하는 모델에 대해 무료로 추론을 실행할 수 있도록 당사 서버를 사용합니다. 4. **위젯**: Hub의 모델 랜딩 페이지에 위젯을 표시합니다. 이를 통해 사용자들은 브라우저에서 빠르게 모델을 시도할 수 있습니다. 이 가이드에서는 앞의 두 가지 주제에 중점을 둘 것입니다. 우리는 라이브러리를 통합하는 데 사용할 수 있는 두 가지 주요 방법을 소개하고 각각의 장단점을 설명할 것입니다. 두 가지 중 어떤 것을 선택할지에 대한 도움이 되도록 끝 부분에 내용이 요약되어 있습니다. 이는 단지 가이드라는 것을 명심하고 상황에 맞게 적응시킬 수 있는 가이드라는 점을 유념하십시오. @@ -394,11 +394,11 @@ class VoiceCraft( 두 가지 접근 방법에 대한 장단점을 간단히 정리해보겠습니다. 아래 표는 단순히 예시일 뿐입니다. 각자 다른 프레임워크에는 고려해야 할 특정 사항이 있을 수 있습니다. 이 가이드는 통합을 다루는 아이디어와 지침을 제공하기 위한 것입니다. 언제든지 궁금한 점이 있으면 문의해 주세요! -| Integration | Using helpers | Using [`ModelHubMixin`] | +| 통합 | helpers 사용 시 | [`ModelHubMixin`] 사용 시 | |:---:|:---:|:---:| -| User experience | `model = load_from_hub(...)`
`push_to_hub(model, ...)` | `model = MyModel.from_pretrained(...)`
`model.push_to_hub(...)` | -| Flexibility | Very flexible.
You fully control the implementation. | Less flexible.
Your framework must have a model class. | -| 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. | -| Model card | To be handled manually | Generated by default with library_name, tags, etc. | +| 사용자 경험 | `model = load_from_hub(...)`
`push_to_hub(model, ...)` | `model = MyModel.from_pretrained(...)`
`model.push_to_hub(...)` | +| 유연성 | 매우 유연합니다.
구현을 완전히 제어합니다. | 유연성이 떨어집니다.
프레임워크에는 모델 클래스가 있어야 합니다. | +| 유지 관리 | 구성 및 새로운 기능에 대한 지원을 추가하기 위한 유지 관리가 더 필요합니다. 사용자가 보고한 문제를 해결해야할 수도 있습니다. | Hub와의 대부분의 상호 작용이 `huggingface_hub`에서 구현되므로 유지 관리가 줄어듭니다. | +| 문서화 / 타입 주석 | 수동으로 작성해야 합니다. | `huggingface_hub`에서 부분적으로 처리됩니다. | +| 다운로드 횟수 표시기 | 수동으로 처리해야 합니다. | 클래스에 `config` 속성이 있다면 기본적으로 활성화됩니다. | +| 모델 카드 | 수동으로 처리해야 합니다. | library_name, tags 등을 활용하여 기본적으로 생성됩니다. | From 12fc5111b04038bd0a6f67499b2bc4f07cfdf423 Mon Sep 17 00:00:00 2001 From: "Chulhwa (Evan) Han" Date: Sat, 1 Jun 2024 21:59:33 +0900 Subject: [PATCH 13/13] Apply suggestions from code review Co-authored-by: Jihun Lim <31366038+heuristicwave@users.noreply.github.com> --- docs/source/ko/guides/integrations.md | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/docs/source/ko/guides/integrations.md b/docs/source/ko/guides/integrations.md index c5252c7228..729b3179b7 100644 --- a/docs/source/ko/guides/integrations.md +++ b/docs/source/ko/guides/integrations.md @@ -5,7 +5,7 @@ rendered properly in your Markdown viewer. # Hub와 어떤 머신 러닝 프레임워크든 통합[[integrate-any-ml-framework-with-the-hub]] Hugging Face Hub는 커뮤니티와 모델을 공유하는 것을 쉽게 만들어줍니다. 이는 오픈소스 생태계의 [수십 가지 라이브러리](https://huggingface.co/docs/hub/models-libraries)를 지원합니다. 저희는 항상 협업적인 머신 러닝을 발전시키기 위해 이 라이브러리를 확대하고자 노력하고 있습니다. `huggingface_hub` 라이브러리는 어떤 Python 스크립트든지 쉽게 파일을 업로드하고 가져올 수 있는 중요한 역할을 합니다. -라이브러리를 Hub와 통합하는 주요 네 가지 방법이 있습니다: +라이브러리를 Hub와 통합하는 네 가지 주요 방법이 있습니다: 1. **Hub에 업로드하기**: 모델을 Hub에 업로드하는 메소드를 구현합니다. 이에는 모델 가중치뿐만 아니라 [모델 카드](https://huggingface.co/docs/huggingface_hub/how-to-model-cards) 및 모델 실행에 필요한 다른 관련 정보나 데이터(예: 훈련 로그)가 포함됩니다. 이 메소드는 일반적으로 `push_to_hub()`라고 합니다. 2. **Hub에서 다운로드하기**: Hub에서 모델을 가져오는 메소드를 구현합니다. 이 메소드는 모델 구성/가중치를 다운로드하고 모델을 가져와야 합니다. 이 메소드는 일반적으로 `from_pretrained` 또는 `load_from_hub()`라고 합니다. @@ -74,7 +74,7 @@ def push_to_hub(model: MyModelClass, repo_name: str) -> None: 물론 이는 단순한 예시에 불과합니다. 더 복잡한 조작(원격 파일 삭제, 가중치를 실시간으로 업로드, 로컬로 가중치를 유지 등)에 관심이 있다면 [파일 업로드](./upload) 가이드를 참조해 주세요. -### 제한[[limitations]] +### 제한 사항[[limitations]] 이러한 방식은 유연성을 가지고 있지만, 유지보수 측면에서 일부 단점을 가지고 있습니다. Hugging Face 사용자들은 `huggingface_hub`와 함께 작업할 때 추가 기능에 익숙합니다. 예를 들어, Hub에서 파일을 로드할 때 다음과 같은 매개변수를 제공하는 것이 일반적입니다: @@ -97,7 +97,6 @@ def push_to_hub(model: MyModelClass, repo_name: str) -> None: ## 더욱 복잡한 접근법: 클래스 상속[[a-more-complex-approach-class-inheritance]] - 위에서 보았듯이 Hub와 통합하기 위해 라이브러리에 포함해야 할 주요 메소드는 파일을 업로드 (`push_to_hub`) 와 파일 다운로드 (`from_pretrained`)입니다. 이러한 메소드를 직접 구현할 수 있지만, 이에는 몇 가지 주의할 점이 있습니다. 이를 해결하기 위해 `huggingface_hub`은 클래스 상속을 사용하는 도구를 제공합니다. 이 도구가 어떻게 작동하는지 살펴보겠습니다! 많은 경우에 라이브러리는 이미 Python 클래스를 사용하여 모델을 구현합니다. 이 클래스에는 모델의 속성 및 로드, 실행, 훈련 및 평가하는 메소드가 포함되어 있습니다. 접근 방식은 믹스인을 사용하여 이 클래스를 확장하여 업로드 및 다운로드 기능을 포함하는 것입니다. [믹스인(Mixin)](https://stackoverflow.com/a/547714)은 기존 클래스에 여러 상속을 통해 특정 기능을 확장하기 위해 설계된 클래스입니다. `huggingface_hub`은 자체 믹스인인 [`ModelHubMixin`]을 제공합니다. 여기서 핵심은 동작과 이를 사용자 정의하는 방법을 이해하는 것입니다. @@ -110,11 +109,11 @@ def push_to_hub(model: MyModelClass, repo_name: str) -> None: - [`~ModelHubMixin._from_pretrained`]: `model_id`를 입력으로 받아 인스턴스화된 모델을 반환하는 **클래스 메소드**입니다. 이 메소드는 관련 파일을 다운로드하고 가져와야 합니다. 3. 완료했습니다! -[`ModelHubMixin`]의 장점은 파일의 직렬화/로드에만 신경을 쓰면 되기 때문에 즉시 사용할 수 있다는 것입니다. 리포지토리 생성, 커밋, PR 또는 리비전과 같은 사항에 대해 걱정할 필요가 없습니다. [`ModelHubMixin`]은 또한 공개 메소드가 문서화되고 타입에 주석이 달려있는지를 확인하며, 허브에서 모델의 다운로드 수를 볼 수 있도록 합니다. 이 모든 것은 [`ModelHubMixin`]에 의해 처리되며 사용자에게 제공됩니다. +[`ModelHubMixin`]의 장점은 파일의 직렬화/로드에만 신경을 쓰면 되기 때문에 즉시 사용할 수 있다는 것입니다. 리포지토리 생성, 커밋, PR 또는 리비전과 같은 사항에 대해 걱정할 필요가 없습니다. [`ModelHubMixin`]은 또한 공개 메소드가 문서화되고 타입에 주석이 달려있는지를 확인하며, Hub 모델의 다운로드 수를 볼 수 있도록 합니다. 이 모든 것은 [`ModelHubMixin`]에 의해 처리되며 사용자에게 제공됩니다. ### 자세한 예시: PyTorch[[a-concrete-example-pytorch]] -위에서 언급한 내용의 좋은 예시는 [`PyTorchModelHubMixin`]입니다. 이것은 PyTorch 프레임워크를 위한 저희의 통합입니다. 이것은 즉시 사용할 수 있는 통합입니다. +위에서 언급한 내용의 좋은 예시는 Pytorch 프레임워크를 통합한 [`PyTorchModelHubMixin`]입니다. 바로 사용 가능할 수 있는 메소드입니다. #### 어떻게 사용하나요?[[how-to-use-it]] @@ -345,7 +344,7 @@ model.save_pretrained(...) {"value": "my_value", "size": 3} ``` -그러나 값이 JSON으로 직렬화될 수 없는 경우는 어떻게 될까요? 기본적으로 구성 파일을 저장할 때 해당 값은 무시됩니다. 그러나 경우에 따라 라이브러리가 이미 직렬화할 수 없는 사용자 정의 객체를 예상하고 있고 해당 유형을 업데이트하고 싶지 않은 경우가 있습니다. 걱정 마세요! [`ModelHubMixin`]을 상속할 때 어떤 유형에 대한 사용자 지정 인코더/디코더를 전달할 수 있습니다. 이는 조금 더 많은 작업이 필요하지만 내부 로직을 변경하지 않고도 라이브러리를 Hub에 통합할 수 있도록 보장합니다. +그러나 값이 JSON으로 직렬화될 수 없는 경우, 기본적으로 구성 파일을 저장할 때 해당 값은 무시됩니다. 그러나 경우에 따라 라이브러리가 이미 직렬화할 수 없는 사용자 정의 객체를 예상하고 있고 해당 유형을 업데이트하고 싶지 않은 경우가 있습니다. 그렇다면 [`ModelHubMixin`]을 상속할 때 어떤 유형에 대한 사용자 지정 인코더/디코더를 전달할 수 있습니다. 이는 조금 더 많은 작업이 필요하지만 내부 로직을 변경하지 않고도 라이브러리를 Hub에 통합할 수 있도록 보장합니다. 여기서 `argparse.Namespace` 구성을 입력으로 받는 클래스의 구체적인 예가 있습니다: @@ -357,7 +356,7 @@ class VoiceCraft(nn.Module): ... ``` -한 가지 해결책은 `__init__` 시그니처를 `def __init__(self, pattern: str, hidden_size: int)`로 업데이트하고 클래스를 인스턴스화하는 모든 스니펫을 업데이트하는 것입니다. 이 방법은 완벽히 유효한 방법이지만, 여러분의 라이브러리를 사용하는 하위 응용 프로그램을 망가뜨릴 수 있습니다. +한 가지 해결책은 `__init__` 시그니처를 `def __init__(self, pattern: str, hidden_size: int)`로 업데이트하고 클래스를 인스턴스화하는 모든 스니펫을 업데이트하는 것입니다. 이 방법은 유효한 방법이지만, 라이브러리를 사용하는 하위 응용 프로그램을 망가뜨릴 수 있습니다. 다른 해결책은 `argparse.Namespace`를 사전으로 변환하는 간단한 인코더/디코더를 제공하는 것입니다. @@ -380,14 +379,14 @@ class VoiceCraft( ... ``` -위의 코드 스니펫에서는 클래스의 내부 로직과 `__init__` 시그니처가 변경되지 않았습니다. 이는 기존의 모든 코드 스니펫이 여전히 작동한다는 것을 의미합니다. 이를 달성하기 위해 우리는 다음을 수행했습니다: -1. 믹스인(`PytorchModelHubMixin` 이 경우)으로부터 상속합니다. +위의 코드 스니펫에서는 클래스의 내부 로직과 `__init__` 시그니처가 변경되지 않았습니다. 이는 기존의 모든 코드 스니펫이 여전히 작동한다는 것을 의미합니다. 이를 달성하기 위해 다음 과정을 수행하면 됩니다: +1. 믹스인(`PytorchModelHubMixin`)으로부터 상속합니다. 2. 상속 시 `coders` 매개변수를 전달합니다. 이는 키가 처리하려는 사용자 지정 유형이고, 값은 튜플 `(인코더, 디코더)`입니다. - 인코더는 지정된 유형의 객체를 입력으로 받아서 jsonable 값으로 반환합니다. 이는 `save_pretrained`로 모델을 저장할 때 사용됩니다. - 디코더는 원시 데이터(일반적으로 딕셔너리 타입)를 입력으로 받아서 초기 객체를 재구성합니다. 이는 `from_pretrained`로 모델을 로드할 때 사용됩니다. - `__init__` 시그니처에 유형 주석을 추가합니다. 이는 믹스인에게 클래스가 기대하는 유형과, 따라서 어떤 디코더를 사용해야 하는지를 알려주는 데 중요합니다. -간단함을 위해 위의 예제에서 인코더/디코더 함수는 견고하지 않습니다. 구체적인 구현을 위해서는 대부분의 경우 코너 케이스를 적절하게 처리해야 할 것입니다. +위의 예제는 간단한 예시이기 때문에 인코더/디코더 함수는 견고하지 않습니다. 구체적인 구현을 위해서는 코너 케이스를 적절하게 처리해야 할 것입니다. ## 빠른 비교[[quick-comparison]]