From 2036740b83b8fd8d11a0ee2cd2710c085d5be651 Mon Sep 17 00:00:00 2001 From: Jinuk <45095330+JinukHong@users.noreply.github.com> Date: Thu, 18 Jul 2024 21:48:25 +0900 Subject: [PATCH 01/15] docs: ko: tasks/knowledge_distillation_for_image_classification.md --- docs/source/ko/_toctree.yml | 38 +++- ...e_distillation_for_image_classification.md | 186 ++++++++++++++++++ 2 files changed, 216 insertions(+), 8 deletions(-) create mode 100644 docs/source/ko/tasks/knowledge_distillation_for_image_classification.md diff --git a/docs/source/ko/_toctree.yml b/docs/source/ko/_toctree.yml index 6b4a3001f2d8..5001a1e09b61 100644 --- a/docs/source/ko/_toctree.yml +++ b/docs/source/ko/_toctree.yml @@ -27,6 +27,8 @@ title: 에이전트 - local: llm_tutorial title: 대규모 언어 모델로 생성하기 + - local: in_translation + title: (번역중)Chatting with Transformers title: 튜토리얼 - sections: - isExpanded: false @@ -77,8 +79,8 @@ title: (번역중) Image Feature Extraction - local: in_translation title: (번역중) Mask Generation - - local: in_translation - title: (번역중) Knowledge Distillation for Computer Vision + - local: tasks/knowledge_distillation_for_image_classification + title: 컴퓨터 비전(이미지 분류)를 위한 지식 증류(knowledge distillation) title: 컴퓨터 비전 - isExpanded: false sections: @@ -131,21 +133,41 @@ title: (번역중) Notebooks with examples - local: community title: 커뮤니티 리소스 - - local: custom_tools - title: 사용자 정의 도구와 프롬프트 - local: troubleshooting title: 문제 해결 - local: in_translation - title: (번역중) Contribute new quantization method + title: (번역중) Interoperability with GGUF files title: (번역중) 개발자 가이드 +- sections: + - local: in_translation + title: (번역중) Getting started + - local: in_translation + title: (번역중) bitsandbytes + - local: in_translation + title: (번역중) GPTQ + - local: in_translation + title: (번역중) AWQ + - local: in_translation + title: (번역중) AQLM + - local: in_translation + title: (번역중) Quanto + - local: in_translation + title: (번역중) EETQ + - local: in_translation + title: (번역중) HQQ + - local: in_translation + title: (번역중) Optimum + - local: in_translation + title: (번역중) Contribute new quantization method + title: (번역중) 경량화 메소드 - sections: - local: performance title: 성능 및 확장성 - local: in_translation - title: (번역중) Quantization + title: (번역중) LLM inference optimization - sections: - local: in_translation - title: (번역중) Training on one GPU + title: (번역중) Methods and tools for efficient training on a single GPU - local: perf_train_gpu_many title: 다중 GPU에서 훈련 진행하기 - local: in_translation @@ -191,7 +213,7 @@ title: 테스트 - local: pr_checks title: Pull Request에 대한 검사 - title: (번역중) 기여하기 + title: 기여하기 - sections: - local: philosophy title: 이념과 목표 diff --git a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md new file mode 100644 index 000000000000..f856e35b1740 --- /dev/null +++ b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md @@ -0,0 +1,186 @@ + +# Knowledge Distillation for Computer Vision + +[[open-in-colab]] + +Knowledge distillation is a technique used to transfer knowledge from a larger, more complex model (teacher) to a smaller, simpler model (student). To distill knowledge from one model to another, we take a pre-trained teacher model trained on a certain task (image classification for this case) and randomly initialize a student model to be trained on image classification. Next, we train the student model to minimize the difference between it's outputs and the teacher's outputs, thus making it mimic the behavior. It was first introduced in [Distilling the Knowledge in a Neural Network by Hinton et al](https://arxiv.org/abs/1503.02531). In this guide, we will do task-specific knowledge distillation. We will use the [beans dataset](https://huggingface.co/datasets/beans) for this. + +This guide demonstrates how you can distill a [fine-tuned ViT model](https://huggingface.co/merve/vit-mobilenet-beans-224) (teacher model) to a [MobileNet](https://huggingface.co/google/mobilenet_v2_1.4_224) (student model) using the [Trainer API](https://huggingface.co/docs/transformers/en/main_classes/trainer#trainer) of 🤗 Transformers. + +Let's install the libraries needed for distillation and evaluating the process. + +```bash +pip install transformers datasets accelerate tensorboard evaluate --upgrade +``` + +In this example, we are using the `merve/beans-vit-224` model as teacher model. It's an image classification model, based on `google/vit-base-patch16-224-in21k` fine-tuned on beans dataset. We will distill this model to a randomly initialized MobileNetV2. + +We will now load the dataset. + +```python +from datasets import load_dataset + +dataset = load_dataset("beans") +``` + +We can use an image processor from either of the models, as in this case they return the same output with same resolution. We will use the `map()` method of `dataset` to apply the preprocessing to every split of the dataset. + +```python +from transformers import AutoImageProcessor +teacher_processor = AutoImageProcessor.from_pretrained("merve/beans-vit-224") + +def process(examples): + processed_inputs = teacher_processor(examples["image"]) + return processed_inputs + +processed_datasets = dataset.map(process, batched=True) +``` + +Essentially, we want the student model (a randomly initialized MobileNet) to mimic the teacher model (fine-tuned vision transformer). To achieve this, we first get the logits output from the teacher and the student. Then, we divide each of them by the parameter `temperature` which controls the importance of each soft target. A parameter called `lambda` weighs the importance of the distillation loss. In this example, we will use `temperature=5` and `lambda=0.5`. We will use the Kullback-Leibler Divergence loss to compute the divergence between the student and teacher. Given two data P and Q, KL Divergence explains how much extra information we need to represent P using Q. If two are identical, their KL divergence is zero, as there's no other information needed to explain P from Q. Thus, in the context of knowledge distillation, KL divergence is useful. + + +```python +from transformers import TrainingArguments, Trainer +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class ImageDistilTrainer(Trainer): + def __init__(self, teacher_model=None, student_model=None, temperature=None, lambda_param=None, *args, **kwargs): + super().__init__(model=student_model, *args, **kwargs) + self.teacher = teacher_model + self.student = student_model + self.loss_function = nn.KLDivLoss(reduction="batchmean") + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + self.teacher.to(device) + self.teacher.eval() + self.temperature = temperature + self.lambda_param = lambda_param + + def compute_loss(self, student, inputs, return_outputs=False): + student_output = self.student(**inputs) + + with torch.no_grad(): + teacher_output = self.teacher(**inputs) + + # Compute soft targets for teacher and student + soft_teacher = F.softmax(teacher_output.logits / self.temperature, dim=-1) + soft_student = F.log_softmax(student_output.logits / self.temperature, dim=-1) + + # Compute the loss + distillation_loss = self.loss_function(soft_student, soft_teacher) * (self.temperature ** 2) + + # Compute the true label loss + student_target_loss = student_output.loss + + # Calculate final loss + loss = (1. - self.lambda_param) * student_target_loss + self.lambda_param * distillation_loss + return (loss, student_output) if return_outputs else loss +``` + +We will now login to Hugging Face Hub so we can push our model to the Hugging Face Hub through the `Trainer`. + +```python +from huggingface_hub import notebook_login + +notebook_login() +``` + +Let's set the `TrainingArguments`, the teacher model and the student model. + +```python +from transformers import AutoModelForImageClassification, MobileNetV2Config, MobileNetV2ForImageClassification + +training_args = TrainingArguments( + output_dir="my-awesome-model", + num_train_epochs=30, + fp16=True, + logging_dir=f"{repo_name}/logs", + logging_strategy="epoch", + eval_strategy="epoch", + save_strategy="epoch", + load_best_model_at_end=True, + metric_for_best_model="accuracy", + report_to="tensorboard", + push_to_hub=True, + hub_strategy="every_save", + hub_model_id=repo_name, + ) + +num_labels = len(processed_datasets["train"].features["labels"].names) + +# initialize models +teacher_model = AutoModelForImageClassification.from_pretrained( + "merve/beans-vit-224", + num_labels=num_labels, + ignore_mismatched_sizes=True +) + +# training MobileNetV2 from scratch +student_config = MobileNetV2Config() +student_config.num_labels = num_labels +student_model = MobileNetV2ForImageClassification(student_config) +``` + +We can use `compute_metrics` function to evaluate our model on the test set. This function will be used during the training process to compute the `accuracy` & `f1` of our model. + +```python +import evaluate +import numpy as np + +accuracy = evaluate.load("accuracy") + +def compute_metrics(eval_pred): + predictions, labels = eval_pred + acc = accuracy.compute(references=labels, predictions=np.argmax(predictions, axis=1)) + return {"accuracy": acc["accuracy"]} +``` + +Let's initialize the `Trainer` with the training arguments we defined. We will also initialize our data collator. + +```python +from transformers import DefaultDataCollator + +data_collator = DefaultDataCollator() +trainer = ImageDistilTrainer( + student_model=student_model, + teacher_model=teacher_model, + training_args=training_args, + train_dataset=processed_datasets["train"], + eval_dataset=processed_datasets["validation"], + data_collator=data_collator, + tokenizer=teacher_processor, + compute_metrics=compute_metrics, + temperature=5, + lambda_param=0.5 +) +``` + +We can now train our model. + +```python +trainer.train() +``` + +We can evaluate the model on the test set. + +```python +trainer.evaluate(processed_datasets["test"]) +``` + +On test set, our model reaches 72 percent accuracy. To have a sanity check over efficiency of distillation, we also trained MobileNet on the beans dataset from scratch with the same hyperparameters and observed 63 percent accuracy on the test set. We invite the readers to try different pre-trained teacher models, student architectures, distillation parameters and report their findings. The training logs and checkpoints for distilled model can be found in [this repository](https://huggingface.co/merve/vit-mobilenet-beans-224), and MobileNetV2 trained from scratch can be found in this [repository](https://huggingface.co/merve/resnet-mobilenet-beans-5). From dccbfb6990f9df410e0d1d43cf878344fe9fe37a Mon Sep 17 00:00:00 2001 From: JinukHong <45095330+JinukHong@users.noreply.github.com> Date: Thu, 25 Jul 2024 17:13:40 +0900 Subject: [PATCH 02/15] feat: nmt draft --- ...e_distillation_for_image_classification.md | 36 +++++++++++-------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md index f856e35b1740..88154037f740 100644 --- a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md +++ b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md @@ -13,23 +13,24 @@ specific language governing permissions and limitations under the License. rendered properly in your Markdown viewer. --> -# Knowledge Distillation for Computer Vision +# 컴퓨터 비전을 위한 지식 증류[[Knowledge-Distillation-for-Computer-Vision]] [[open-in-colab]] -Knowledge distillation is a technique used to transfer knowledge from a larger, more complex model (teacher) to a smaller, simpler model (student). To distill knowledge from one model to another, we take a pre-trained teacher model trained on a certain task (image classification for this case) and randomly initialize a student model to be trained on image classification. Next, we train the student model to minimize the difference between it's outputs and the teacher's outputs, thus making it mimic the behavior. It was first introduced in [Distilling the Knowledge in a Neural Network by Hinton et al](https://arxiv.org/abs/1503.02531). In this guide, we will do task-specific knowledge distillation. We will use the [beans dataset](https://huggingface.co/datasets/beans) for this. +지식 증류(Knowledge distillation)는 더 크고 복잡한 모델(교사)에서 더 작고 간단한 모델(학생)로 지식을 전달하는 기술입니다. 지식을 한 모델에서 다른 모델로 증류하기 위해서는, 특정 작업(이 경우 이미지 분류)에 대해 학습된 사전 훈련된 교사 모델을 사용하고, 이미지 분류 작업을 학습할 학생 모델을 무작위로 초기화합니다. 다음으로, 학생 모델이 교사 모델의 출력을 모방하도록 하기 위해 학생 모델의 출력과 교사 모델의 출력 간의 차이를 최소화하도록 훈련합니다. 이 방법은 Hinton 등이 발표한 논문 [Neural Network에서 지식 증류](https://arxiv.org/abs/1503.02531)에서 처음 소개되었습니다. 이 가이드에서는 특정 작업에 맞춘 지식 증류를 수행할 것입니다. 우리는 [beans dataset](https://huggingface.co/datasets/beans)을 사용할 것입니다. -This guide demonstrates how you can distill a [fine-tuned ViT model](https://huggingface.co/merve/vit-mobilenet-beans-224) (teacher model) to a [MobileNet](https://huggingface.co/google/mobilenet_v2_1.4_224) (student model) using the [Trainer API](https://huggingface.co/docs/transformers/en/main_classes/trainer#trainer) of 🤗 Transformers. +이 가이드는 [미세 조정된 ViT 모델](https://huggingface.co/merve/vit-mobilenet-beans-224) (교사 모델)을 [MobileNet](https://huggingface.co/google/mobilenet_v2_1.4_224) (학생 모델)으로 증류하는 방법을 🤗 Transformers의 [Trainer API](https://huggingface.co/docs/transformers/en/main_classes/trainer#trainer) 를 사용하여 보여줍니다. + +증류 및 평가 과정을 위해 필요한 라이브러리를 설치해 봅시다. -Let's install the libraries needed for distillation and evaluating the process. ```bash pip install transformers datasets accelerate tensorboard evaluate --upgrade ``` -In this example, we are using the `merve/beans-vit-224` model as teacher model. It's an image classification model, based on `google/vit-base-patch16-224-in21k` fine-tuned on beans dataset. We will distill this model to a randomly initialized MobileNetV2. +이 예제에서는 `merve/beans-vit-224` 모델을 교사 모델로 사용하고 있습니다. 이 모델은 `google/vit-base-patch16-224-in21k`를 기반으로 하여 beans 데이터셋에 대해 미세 조정된 이미지 분류 모델입니다. 우리는 이 모델을 무작위로 초기화된 MobileNetV2로 증류할 것입니다. -We will now load the dataset. +이제 데이터셋을 로드하겠습니다. ```python from datasets import load_dataset @@ -37,7 +38,8 @@ from datasets import load_dataset dataset = load_dataset("beans") ``` -We can use an image processor from either of the models, as in this case they return the same output with same resolution. We will use the `map()` method of `dataset` to apply the preprocessing to every split of the dataset. +이 경우 두 모델의 이미지 프로세서를 사용할 수 있습니다. 이들은 동일한 해상도로 동일한 출력을 반환하기 때문입니다. 우리는 `dataset`의 `map()` 메서드를 사용하여 데이터셋의 모든 분할에 전처리를 적용할 것입니다. + ```python from transformers import AutoImageProcessor @@ -50,7 +52,7 @@ def process(examples): processed_datasets = dataset.map(process, batched=True) ``` -Essentially, we want the student model (a randomly initialized MobileNet) to mimic the teacher model (fine-tuned vision transformer). To achieve this, we first get the logits output from the teacher and the student. Then, we divide each of them by the parameter `temperature` which controls the importance of each soft target. A parameter called `lambda` weighs the importance of the distillation loss. In this example, we will use `temperature=5` and `lambda=0.5`. We will use the Kullback-Leibler Divergence loss to compute the divergence between the student and teacher. Given two data P and Q, KL Divergence explains how much extra information we need to represent P using Q. If two are identical, their KL divergence is zero, as there's no other information needed to explain P from Q. Thus, in the context of knowledge distillation, KL divergence is useful. +본질적으로, 우리는 학생 모델(무작위로 초기화된 MobileNet)이 교사 모델(미세 조정된 비전 트랜스포머)을 모방하도록 만들고자 합니다. 이를 위해 먼저 교사와 학생 모델의 로짓 출력을 얻습니다. 그런 다음 각 출력을 매개변수 `temperature`로 나누는데, 이는 각 소프트 타겟의 중요성을 조절합니다. `lambda`라는 매개변수는 증류 손실의 중요성을 가중합니다. 이 예제에서는 `temperature=5`와 `lambda=0.5`를 사용할 것입니다. 우리는 학생과 교사 간의 발산을 계산하기 위해 Kullback-Leibler Divergence 손실을 사용할 것입니다. 두 데이터 P와 Q가 주어졌을 때, KL Divergence는 Q를 사용하여 P를 표현하는 데 필요한 추가 정보를 설명합니다. 두 데이터가 동일하다면, KL Divergence는 0이며, Q로 P를 설명하는 데 추가 정보가 필요하지 않음을 의미합니다. 따라서 지식 증류의 맥락에서 KL Divergence는 유용합니다. ```python @@ -93,7 +95,8 @@ class ImageDistilTrainer(Trainer): return (loss, student_output) if return_outputs else loss ``` -We will now login to Hugging Face Hub so we can push our model to the Hugging Face Hub through the `Trainer`. +이제 Hugging Face Hub에 로그인하여 `Trainer`를 통해 Hugging Face Hub에 모델을 푸시할 수 있도록 하겠습니다. + ```python from huggingface_hub import notebook_login @@ -101,7 +104,8 @@ from huggingface_hub import notebook_login notebook_login() ``` -Let's set the `TrainingArguments`, the teacher model and the student model. +이제 `TrainingArguments`, 교사 모델과 학생 모델을 설정해봅시다. + ```python from transformers import AutoModelForImageClassification, MobileNetV2Config, MobileNetV2ForImageClassification @@ -137,7 +141,8 @@ student_config.num_labels = num_labels student_model = MobileNetV2ForImageClassification(student_config) ``` -We can use `compute_metrics` function to evaluate our model on the test set. This function will be used during the training process to compute the `accuracy` & `f1` of our model. +`compute_metrics` 함수를 사용하여 테스트 세트에서 모델을 평가할 수 있습니다. 이 함수는 훈련 과정에서 모델의 `accuracy`와 `f1`을 계산하는 데 사용됩니다. + ```python import evaluate @@ -151,7 +156,7 @@ def compute_metrics(eval_pred): return {"accuracy": acc["accuracy"]} ``` -Let's initialize the `Trainer` with the training arguments we defined. We will also initialize our data collator. +정의한 훈련 인수로 `Trainer`를 초기화해봅시다. 또한 데이터 콜레이터(data collator)를 초기화하겠습니다. ```python from transformers import DefaultDataCollator @@ -171,16 +176,17 @@ trainer = ImageDistilTrainer( ) ``` -We can now train our model. +이제 모델을 훈련할 수 있습니다. ```python trainer.train() ``` -We can evaluate the model on the test set. +모델을 테스트 세트에서 평가할 수 있습니다. ```python trainer.evaluate(processed_datasets["test"]) ``` -On test set, our model reaches 72 percent accuracy. To have a sanity check over efficiency of distillation, we also trained MobileNet on the beans dataset from scratch with the same hyperparameters and observed 63 percent accuracy on the test set. We invite the readers to try different pre-trained teacher models, student architectures, distillation parameters and report their findings. The training logs and checkpoints for distilled model can be found in [this repository](https://huggingface.co/merve/vit-mobilenet-beans-224), and MobileNetV2 trained from scratch can be found in this [repository](https://huggingface.co/merve/resnet-mobilenet-beans-5). + +테스트 세트에서 우리 모델은 72%의 정확도에 도달했습니다. 증류의 효율성을 검증하기 위해 동일한 하이퍼파라미터로 beans 데이터셋에서 MobileNet을 처음부터 훈련했을 때 테스트 세트에서 63%의 정확도를 관찰했습니다. 독자들이 다양한 사전 훈련된 교사 모델, 학생 구조, 증류 매개변수를 시도하고 그 결과를 보고하도록 권장합니다. 증류된 모델의 훈련 로그와 체크포인트는 [이 저장소](https://huggingface.co/merve/vit-mobilenet-beans-224)에서 찾을 수 있으며, 처음부터 훈련된 MobileNetV2는 이 [저장소](https://huggingface.co/merve/resnet-mobilenet-beans-5)에서 찾을 수 있습니다. From c52dbe3dd49536d5da2357e268a4b2fbb1374ad4 Mon Sep 17 00:00:00 2001 From: JinukHong <45095330+JinukHong@users.noreply.github.com> Date: Wed, 31 Jul 2024 00:50:21 +0900 Subject: [PATCH 03/15] fix: manual edits --- .../knowledge_distillation_for_image_classification.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md index 88154037f740..5ba18674a099 100644 --- a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md +++ b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md @@ -17,18 +17,18 @@ rendered properly in your Markdown viewer. [[open-in-colab]] -지식 증류(Knowledge distillation)는 더 크고 복잡한 모델(교사)에서 더 작고 간단한 모델(학생)로 지식을 전달하는 기술입니다. 지식을 한 모델에서 다른 모델로 증류하기 위해서는, 특정 작업(이 경우 이미지 분류)에 대해 학습된 사전 훈련된 교사 모델을 사용하고, 이미지 분류 작업을 학습할 학생 모델을 무작위로 초기화합니다. 다음으로, 학생 모델이 교사 모델의 출력을 모방하도록 하기 위해 학생 모델의 출력과 교사 모델의 출력 간의 차이를 최소화하도록 훈련합니다. 이 방법은 Hinton 등이 발표한 논문 [Neural Network에서 지식 증류](https://arxiv.org/abs/1503.02531)에서 처음 소개되었습니다. 이 가이드에서는 특정 작업에 맞춘 지식 증류를 수행할 것입니다. 우리는 [beans dataset](https://huggingface.co/datasets/beans)을 사용할 것입니다. +지식 증류(Knowledge distillation)는 더 크고 복잡한 모델(교사)에서 더 작고 간단한 모델(학생)로 지식을 전달하는 기술입니다. 지식을 한 모델에서 다른 모델로 증류하기 위해서는, 특정 작업(이 경우 이미지 분류)에 대해 학습된 사전 훈련된 교사 모델을 사용하고, 이미지 분류 작업을 학습할 학생 모델을 무작위로 초기화합니다. 다음으로, 학생 모델이 교사 모델의 출력을 모방하도록 하기 위해 학생 모델의 출력과 교사 모델의 출력 간의 차이를 최소화하도록 훈련합니다. 이 방법은 Hinton 등이 발표한 논문 [Neural Network에서 지식 증류](https://arxiv.org/abs/1503.02531)에서 처음 소개되었습니다. 이 가이드에서는 특정 작업에 맞춘 지식 증류를 수행할 것입니다. 이번에는 [beans dataset](https://huggingface.co/datasets/beans)을 사용할 것입니다. 이 가이드는 [미세 조정된 ViT 모델](https://huggingface.co/merve/vit-mobilenet-beans-224) (교사 모델)을 [MobileNet](https://huggingface.co/google/mobilenet_v2_1.4_224) (학생 모델)으로 증류하는 방법을 🤗 Transformers의 [Trainer API](https://huggingface.co/docs/transformers/en/main_classes/trainer#trainer) 를 사용하여 보여줍니다. -증류 및 평가 과정을 위해 필요한 라이브러리를 설치해 봅시다. +증류와 과정 평가를 위해 필요한 라이브러리를 설치해 봅시다. ```bash pip install transformers datasets accelerate tensorboard evaluate --upgrade ``` -이 예제에서는 `merve/beans-vit-224` 모델을 교사 모델로 사용하고 있습니다. 이 모델은 `google/vit-base-patch16-224-in21k`를 기반으로 하여 beans 데이터셋에 대해 미세 조정된 이미지 분류 모델입니다. 우리는 이 모델을 무작위로 초기화된 MobileNetV2로 증류할 것입니다. +이 예제에서는 `merve/beans-vit-224` 모델을 교사 모델로 사용하고 있습니다. 이 모델은 `google/vit-base-patch16-224-in21k`를 기반으로 하여 beans 데이터셋에 대해 파인 튜닝된 이미지 분류 모델입니다. 우리는 이 모델을 무작위로 초기화된 MobileNetV2로 증류해볼 것입니다. 이제 데이터셋을 로드하겠습니다. @@ -38,7 +38,7 @@ from datasets import load_dataset dataset = load_dataset("beans") ``` -이 경우 두 모델의 이미지 프로세서를 사용할 수 있습니다. 이들은 동일한 해상도로 동일한 출력을 반환하기 때문입니다. 우리는 `dataset`의 `map()` 메서드를 사용하여 데이터셋의 모든 분할에 전처리를 적용할 것입니다. +이 경우 두 모델의 이미지 프로세서가 동일한 해상도로 동일한 출력을 반환하기 때문에, 두가지를 모두 사용할 수 있습니다. 우리는 `dataset`의 `map()` 메서드를 사용하여 데이터셋의 모든 분할마다 전처리를 적용할 것입니다. ```python @@ -52,7 +52,7 @@ def process(examples): processed_datasets = dataset.map(process, batched=True) ``` -본질적으로, 우리는 학생 모델(무작위로 초기화된 MobileNet)이 교사 모델(미세 조정된 비전 트랜스포머)을 모방하도록 만들고자 합니다. 이를 위해 먼저 교사와 학생 모델의 로짓 출력을 얻습니다. 그런 다음 각 출력을 매개변수 `temperature`로 나누는데, 이는 각 소프트 타겟의 중요성을 조절합니다. `lambda`라는 매개변수는 증류 손실의 중요성을 가중합니다. 이 예제에서는 `temperature=5`와 `lambda=0.5`를 사용할 것입니다. 우리는 학생과 교사 간의 발산을 계산하기 위해 Kullback-Leibler Divergence 손실을 사용할 것입니다. 두 데이터 P와 Q가 주어졌을 때, KL Divergence는 Q를 사용하여 P를 표현하는 데 필요한 추가 정보를 설명합니다. 두 데이터가 동일하다면, KL Divergence는 0이며, Q로 P를 설명하는 데 추가 정보가 필요하지 않음을 의미합니다. 따라서 지식 증류의 맥락에서 KL Divergence는 유용합니다. +본질적으로, 우리는 학생 모델(무작위로 초기화된 MobileNet)이 교사 모델(파인 튜닝된 비전 트랜스포머)을 모방하도록 만들고자 합니다. 이를 달성하기 위해 먼저 교사와 학생 모델의 로짓 출력값을 구합니다. 그런 다음 각 출력을 매개변수 `temperature`로 나누는데, 이는 각 소프트 타겟의 중요성을 조절합니다. `lambda`라는 매개변수는 증류 손실의 중요성에 가중치를 줍니다. 이 예제에서는 `temperature=5`와 `lambda=0.5`를 사용할 것입니다. 우리는 학생과 교사 간의 발산을 계산하기 위해 Kullback-Leibler Divergence 손실을 사용할 것입니다. 두 데이터 P와 Q가 주어졌을 때, KL Divergence는 Q를 사용하여 P를 표현하는 데 얼만큼의 추가 정보가 필요한지를 설명합니다. 두 데이터가 동일하다면, KL Divergence는 0이며, Q로 P를 설명하는 데 추가 정보가 필요하지 않음을 의미합니다. 따라서 지식 증류의 맥락에서 KL Divergence는 유용합니다. ```python From a769bb5526f2638a668dbf165f9789e351138f68 Mon Sep 17 00:00:00 2001 From: Jinuk <45095330+JinukHong@users.noreply.github.com> Date: Wed, 7 Aug 2024 12:59:15 +0900 Subject: [PATCH 04/15] Apply suggestions from code review Co-authored-by: Chulhwa (Evan) Han --- .../ko/tasks/knowledge_distillation_for_image_classification.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md index 5ba18674a099..76be3f4fc253 100644 --- a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md +++ b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md @@ -17,7 +17,7 @@ rendered properly in your Markdown viewer. [[open-in-colab]] -지식 증류(Knowledge distillation)는 더 크고 복잡한 모델(교사)에서 더 작고 간단한 모델(학생)로 지식을 전달하는 기술입니다. 지식을 한 모델에서 다른 모델로 증류하기 위해서는, 특정 작업(이 경우 이미지 분류)에 대해 학습된 사전 훈련된 교사 모델을 사용하고, 이미지 분류 작업을 학습할 학생 모델을 무작위로 초기화합니다. 다음으로, 학생 모델이 교사 모델의 출력을 모방하도록 하기 위해 학생 모델의 출력과 교사 모델의 출력 간의 차이를 최소화하도록 훈련합니다. 이 방법은 Hinton 등이 발표한 논문 [Neural Network에서 지식 증류](https://arxiv.org/abs/1503.02531)에서 처음 소개되었습니다. 이 가이드에서는 특정 작업에 맞춘 지식 증류를 수행할 것입니다. 이번에는 [beans dataset](https://huggingface.co/datasets/beans)을 사용할 것입니다. +지식 증류(Knowledge distillation)는 더 크고 복잡한 모델(교사)에서 더 작고 간단한 모델(학생)로 지식을 전달하는 기술입니다. 한 모델에서 다른 모델로 지식을 증류하기 위해, 특정 작업(이 경우 이미지 분류)에 대해 학습된 사전 훈련된 교사 모델을 사용하고, 랜덤으로 초기화된 학생 모델을 이미지 분류 작업에 대해 학습합니다. 그다음, 학생 모델이 교사 모델의 출력을 모방하여 두 모델의 출력 차이를 최소화하도록 훈련합니다. 이 기법은 Hinton 등 연구진의 [Distilling the Knowledge in a Neural Network](https://arxiv.org/abs/1503.02531)에서 처음 소개되었습니다. 이 가이드에서는 특정 작업에 맞춘 지식 증류를 수행할 것입니다. 이번에는 [beans dataset](https://huggingface.co/datasets/beans)을 사용할 것입니다. 이 가이드는 [미세 조정된 ViT 모델](https://huggingface.co/merve/vit-mobilenet-beans-224) (교사 모델)을 [MobileNet](https://huggingface.co/google/mobilenet_v2_1.4_224) (학생 모델)으로 증류하는 방법을 🤗 Transformers의 [Trainer API](https://huggingface.co/docs/transformers/en/main_classes/trainer#trainer) 를 사용하여 보여줍니다. From 44a63a5fde957e5df71fc04557829b98b5d896bb Mon Sep 17 00:00:00 2001 From: Jinuk <45095330+JinukHong@users.noreply.github.com> Date: Wed, 7 Aug 2024 12:59:26 +0900 Subject: [PATCH 05/15] Apply suggestions from code review Co-authored-by: Chulhwa (Evan) Han --- .../ko/tasks/knowledge_distillation_for_image_classification.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md index 76be3f4fc253..f4f9e8249b0e 100644 --- a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md +++ b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md @@ -28,7 +28,7 @@ rendered properly in your Markdown viewer. pip install transformers datasets accelerate tensorboard evaluate --upgrade ``` -이 예제에서는 `merve/beans-vit-224` 모델을 교사 모델로 사용하고 있습니다. 이 모델은 `google/vit-base-patch16-224-in21k`를 기반으로 하여 beans 데이터셋에 대해 파인 튜닝된 이미지 분류 모델입니다. 우리는 이 모델을 무작위로 초기화된 MobileNetV2로 증류해볼 것입니다. +이 예제에서는 `merve/beans-vit-224` 모델을 교사 모델로 사용하고 있습니다. 이 모델은 beans 데이터셋에서 파인 튜닝된 `google/vit-base-patch16-224-in21k` 기반의 이미지 분류 모델입니다. 이 모델을 무작위로 초기화된 MobileNetV2로 증류해볼 것입니다. 이제 데이터셋을 로드하겠습니다. From 63c78d151d8d4e6e303f1cbb6fd56715bc9d58f1 Mon Sep 17 00:00:00 2001 From: Jinuk <45095330+JinukHong@users.noreply.github.com> Date: Wed, 7 Aug 2024 12:59:38 +0900 Subject: [PATCH 06/15] Apply suggestions from code review Co-authored-by: Ahnjj_DEV --- .../ko/tasks/knowledge_distillation_for_image_classification.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md index f4f9e8249b0e..6a2c5d8a9757 100644 --- a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md +++ b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md @@ -38,7 +38,7 @@ from datasets import load_dataset dataset = load_dataset("beans") ``` -이 경우 두 모델의 이미지 프로세서가 동일한 해상도로 동일한 출력을 반환하기 때문에, 두가지를 모두 사용할 수 있습니다. 우리는 `dataset`의 `map()` 메서드를 사용하여 데이터셋의 모든 분할마다 전처리를 적용할 것입니다. +이 경우 두 모델의 이미지 프로세서가 동일한 해상도로 동일한 출력을 반환하기 때문에, 두가지를 모두 사용할 수 있습니다. 데이터셋의 모든 분할마다 전처리를 적용하기 위해 `dataset`의 `map()` 메소드를 사용할 것 입니다. ```python From 9f2b283792dfd845f39ad01f685ce7ddef0d0531 Mon Sep 17 00:00:00 2001 From: Jinuk <45095330+JinukHong@users.noreply.github.com> Date: Wed, 7 Aug 2024 13:00:30 +0900 Subject: [PATCH 07/15] Apply suggestions from code review Co-authored-by: Ahnjj_DEV --- .../ko/tasks/knowledge_distillation_for_image_classification.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md index 6a2c5d8a9757..87ddf4ba8b5f 100644 --- a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md +++ b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md @@ -52,7 +52,7 @@ def process(examples): processed_datasets = dataset.map(process, batched=True) ``` -본질적으로, 우리는 학생 모델(무작위로 초기화된 MobileNet)이 교사 모델(파인 튜닝된 비전 트랜스포머)을 모방하도록 만들고자 합니다. 이를 달성하기 위해 먼저 교사와 학생 모델의 로짓 출력값을 구합니다. 그런 다음 각 출력을 매개변수 `temperature`로 나누는데, 이는 각 소프트 타겟의 중요성을 조절합니다. `lambda`라는 매개변수는 증류 손실의 중요성에 가중치를 줍니다. 이 예제에서는 `temperature=5`와 `lambda=0.5`를 사용할 것입니다. 우리는 학생과 교사 간의 발산을 계산하기 위해 Kullback-Leibler Divergence 손실을 사용할 것입니다. 두 데이터 P와 Q가 주어졌을 때, KL Divergence는 Q를 사용하여 P를 표현하는 데 얼만큼의 추가 정보가 필요한지를 설명합니다. 두 데이터가 동일하다면, KL Divergence는 0이며, Q로 P를 설명하는 데 추가 정보가 필요하지 않음을 의미합니다. 따라서 지식 증류의 맥락에서 KL Divergence는 유용합니다. +학생 모델(무작위로 초기화된 MobileNet)이 교사 모델(파인 튜닝된 비전 트랜스포머)을 모방하도록 할 것 입니다. 이를 위해 먼저 교사와 학생 모델의 로짓 출력값을 구합니다. 그런 다음 각 출력값을 매개변수 `temperature` 값으로 나누는데, 이 매개변수는 각 소프트 타겟의 중요도를 조절하는 역할을 합니다. 매개변수 `lambda` 는 증류 손실의 중요도에 가중치를 줍니다. 이 예제에서는 `temperature=5`와 `lambda=0.5`를 사용할 것입니다. 학생과 교사 간의 발산을 계산하기 위해 Kullback-Leibler Divergence 손실을 사용합니다. 두 데이터 P와 Q가 주어졌을 때, KL Divergence는 Q를 사용하여 P를 표현하는 데 얼만큼의 추가 정보가 필요한지를 말해줍니다. 두 데이터가 동일하다면, KL Divergence는 0이며, Q로 P를 설명하는 데 추가 정보가 필요하지 않음을 의미합니다. 따라서 지식 증류의 맥락에서 KL Divergence는 유용합니다. ```python From 2b1fe0e1fc681ae4b2d7a1c85b9b65f54a4d57b9 Mon Sep 17 00:00:00 2001 From: Jinuk <45095330+JinukHong@users.noreply.github.com> Date: Wed, 7 Aug 2024 13:00:39 +0900 Subject: [PATCH 08/15] Apply suggestions from code review Co-authored-by: Ahnjj_DEV --- .../ko/tasks/knowledge_distillation_for_image_classification.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md index 87ddf4ba8b5f..ac7036ea1ecf 100644 --- a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md +++ b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md @@ -189,4 +189,4 @@ trainer.evaluate(processed_datasets["test"]) ``` -테스트 세트에서 우리 모델은 72%의 정확도에 도달했습니다. 증류의 효율성을 검증하기 위해 동일한 하이퍼파라미터로 beans 데이터셋에서 MobileNet을 처음부터 훈련했을 때 테스트 세트에서 63%의 정확도를 관찰했습니다. 독자들이 다양한 사전 훈련된 교사 모델, 학생 구조, 증류 매개변수를 시도하고 그 결과를 보고하도록 권장합니다. 증류된 모델의 훈련 로그와 체크포인트는 [이 저장소](https://huggingface.co/merve/vit-mobilenet-beans-224)에서 찾을 수 있으며, 처음부터 훈련된 MobileNetV2는 이 [저장소](https://huggingface.co/merve/resnet-mobilenet-beans-5)에서 찾을 수 있습니다. +테스트 세트에서 모델의 정확도는 72%에 도달했습니다. 증류의 효율성을 검증하기 위해 동일한 하이퍼파라미터로 beans 데이터셋에서 MobileNet을 처음부터 훈련하였고, 테스트 세트에서의 정확도는 63% 였습니다. 다양한 사전 훈련된 교사 모델, 학생 구조, 증류 매개변수를 시도해보시고 결과를 보고하기를 권장합니다. 증류된 모델의 훈련 로그와 체크포인트는 [이 저장소](https://huggingface.co/merve/vit-mobilenet-beans-224)에서 찾을 수 있으며, 처음부터 훈련된 MobileNetV2는 이 [저장소](https://huggingface.co/merve/resnet-mobilenet-beans-5)에서 찾을 수 있습니다. From 596cffe07a9a688f339e7bf258c4ab49822fa6a4 Mon Sep 17 00:00:00 2001 From: Jinuk <45095330+JinukHong@users.noreply.github.com> Date: Wed, 7 Aug 2024 13:00:47 +0900 Subject: [PATCH 09/15] Apply suggestions from code review Co-authored-by: Chulhwa (Evan) Han --- .../ko/tasks/knowledge_distillation_for_image_classification.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md index ac7036ea1ecf..bfac9163e8af 100644 --- a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md +++ b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md @@ -135,7 +135,7 @@ teacher_model = AutoModelForImageClassification.from_pretrained( ignore_mismatched_sizes=True ) -# training MobileNetV2 from scratch +# MobileNetV2 밑바닥부터 학습 student_config = MobileNetV2Config() student_config.num_labels = num_labels student_model = MobileNetV2ForImageClassification(student_config) From 9ae78730fd0d2a181a3133db1d956641b401e1ee Mon Sep 17 00:00:00 2001 From: Jinuk <45095330+JinukHong@users.noreply.github.com> Date: Wed, 7 Aug 2024 13:00:53 +0900 Subject: [PATCH 10/15] Apply suggestions from code review Co-authored-by: Chulhwa (Evan) Han --- .../ko/tasks/knowledge_distillation_for_image_classification.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md index bfac9163e8af..3b01288362aa 100644 --- a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md +++ b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md @@ -128,7 +128,7 @@ training_args = TrainingArguments( num_labels = len(processed_datasets["train"].features["labels"].names) -# initialize models +# 모델 초기화 teacher_model = AutoModelForImageClassification.from_pretrained( "merve/beans-vit-224", num_labels=num_labels, From f85a0d7524b255b6326832c055c43aece444c72a Mon Sep 17 00:00:00 2001 From: Jinuk <45095330+JinukHong@users.noreply.github.com> Date: Wed, 7 Aug 2024 13:01:01 +0900 Subject: [PATCH 11/15] Apply suggestions from code review Co-authored-by: Chulhwa (Evan) Han --- .../ko/tasks/knowledge_distillation_for_image_classification.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md index 3b01288362aa..2edffec58ed5 100644 --- a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md +++ b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md @@ -104,7 +104,7 @@ from huggingface_hub import notebook_login notebook_login() ``` -이제 `TrainingArguments`, 교사 모델과 학생 모델을 설정해봅시다. +이제 `TrainingArguments`, 교사 모델과 학생 모델을 설정하겠습니다. ```python From e8c352fd60fc10408266d33be30831b1caa508dc Mon Sep 17 00:00:00 2001 From: Jinuk <45095330+JinukHong@users.noreply.github.com> Date: Thu, 22 Aug 2024 11:36:20 +0200 Subject: [PATCH 12/15] Apply suggestions from code review --- .../tasks/knowledge_distillation_for_image_classification.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md index 2edffec58ed5..cec81e286e58 100644 --- a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md +++ b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md @@ -80,7 +80,8 @@ class ImageDistilTrainer(Trainer): with torch.no_grad(): teacher_output = self.teacher(**inputs) - # Compute soft targets for teacher and student + # 교사와 학생의 소프트 타겟(soft targets) 계산 + soft_teacher = F.softmax(teacher_output.logits / self.temperature, dim=-1) soft_student = F.log_softmax(student_output.logits / self.temperature, dim=-1) From 609398e0a0cbbda05c8c56d8a55b2a5eb4cb5c88 Mon Sep 17 00:00:00 2001 From: Jinuk <45095330+JinukHong@users.noreply.github.com> Date: Thu, 22 Aug 2024 11:36:31 +0200 Subject: [PATCH 13/15] Apply suggestions from code review --- .../ko/tasks/knowledge_distillation_for_image_classification.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md index cec81e286e58..172425f1a5b2 100644 --- a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md +++ b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md @@ -85,7 +85,7 @@ class ImageDistilTrainer(Trainer): soft_teacher = F.softmax(teacher_output.logits / self.temperature, dim=-1) soft_student = F.log_softmax(student_output.logits / self.temperature, dim=-1) - # Compute the loss + # 손실(loss) 계산 distillation_loss = self.loss_function(soft_student, soft_teacher) * (self.temperature ** 2) # Compute the true label loss From 28bb6b1b0af80e725e349a24b7a1d6d1be9a2309 Mon Sep 17 00:00:00 2001 From: Jinuk <45095330+JinukHong@users.noreply.github.com> Date: Thu, 22 Aug 2024 11:36:39 +0200 Subject: [PATCH 14/15] Apply suggestions from code review --- .../ko/tasks/knowledge_distillation_for_image_classification.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md index 172425f1a5b2..5033a564ca1c 100644 --- a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md +++ b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md @@ -88,7 +88,7 @@ class ImageDistilTrainer(Trainer): # 손실(loss) 계산 distillation_loss = self.loss_function(soft_student, soft_teacher) * (self.temperature ** 2) - # Compute the true label loss + # 실제 레이블 손실 계산 student_target_loss = student_output.loss # Calculate final loss From ca46b689edfacad0c2c410be27f3f22fae205929 Mon Sep 17 00:00:00 2001 From: Jinuk <45095330+JinukHong@users.noreply.github.com> Date: Thu, 22 Aug 2024 11:36:48 +0200 Subject: [PATCH 15/15] Apply suggestions from code review --- .../ko/tasks/knowledge_distillation_for_image_classification.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md index 5033a564ca1c..37c0cc25083e 100644 --- a/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md +++ b/docs/source/ko/tasks/knowledge_distillation_for_image_classification.md @@ -91,7 +91,7 @@ class ImageDistilTrainer(Trainer): # 실제 레이블 손실 계산 student_target_loss = student_output.loss - # Calculate final loss + # 최종 손실 계산 loss = (1. - self.lambda_param) * student_target_loss + self.lambda_param * distillation_loss return (loss, student_output) if return_outputs else loss ```