Skip to content

Commit

Permalink
๐ŸŒ [i18n-KO] Translated `knowledge_distillation_for_image_classificatiโ€ฆ
Browse files Browse the repository at this point in the history
โ€ฆon.md to Korean" (huggingface#32334)

* docs: ko: tasks/knowledge_distillation_for_image_classification.md

* feat: nmt draft

* fix: manual edits

* Apply suggestions from code review

Co-authored-by: Chulhwa (Evan) Han <[email protected]>

* Apply suggestions from code review

Co-authored-by: Chulhwa (Evan) Han <[email protected]>

* Apply suggestions from code review

Co-authored-by: Ahnjj_DEV <[email protected]>

* Apply suggestions from code review

Co-authored-by: Ahnjj_DEV <[email protected]>

* Apply suggestions from code review

Co-authored-by: Ahnjj_DEV <[email protected]>

* Apply suggestions from code review

Co-authored-by: Chulhwa (Evan) Han <[email protected]>

* Apply suggestions from code review

Co-authored-by: Chulhwa (Evan) Han <[email protected]>

* Apply suggestions from code review

Co-authored-by: Chulhwa (Evan) Han <[email protected]>

* Apply suggestions from code review

* Apply suggestions from code review

* Apply suggestions from code review

* Apply suggestions from code review

---------

Co-authored-by: Chulhwa (Evan) Han <[email protected]>
Co-authored-by: Ahnjj_DEV <[email protected]>
  • Loading branch information
3 people authored and itazap committed Sep 20, 2024
1 parent 21b722f commit 05efc73
Show file tree
Hide file tree
Showing 2 changed files with 195 additions and 2 deletions.
4 changes: 2 additions & 2 deletions docs/source/ko/_toctree.yml
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@
title: ์ด๋ฏธ์ง€ ํŠน์ง• ์ถ”์ถœ
- local: tasks/mask_generation
title: ๋งˆ์Šคํฌ ์ƒ์„ฑ
- local: in_translation
title: (๋ฒˆ์—ญ์ค‘) Knowledge Distillation for Computer Vision
- local: tasks/knowledge_distillation_for_image_classification
title: ์ปดํ“จํ„ฐ ๋น„์ „(์ด๋ฏธ์ง€ ๋ถ„๋ฅ˜)๋ฅผ ์œ„ํ•œ ์ง€์‹ ์ฆ๋ฅ˜(knowledge distillation)
title: ์ปดํ“จํ„ฐ ๋น„์ „
- isExpanded: false
sections:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
โš ๏ธ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
-->
# ์ปดํ“จํ„ฐ ๋น„์ „์„ ์œ„ํ•œ ์ง€์‹ ์ฆ๋ฅ˜[[Knowledge-Distillation-for-Computer-Vision]]

[[open-in-colab]]

์ง€์‹ ์ฆ๋ฅ˜(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) ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ณด์—ฌ์ค๋‹ˆ๋‹ค.

์ฆ๋ฅ˜์™€ ๊ณผ์ • ํ‰๊ฐ€๋ฅผ ์œ„ํ•ด ํ•„์š”ํ•œ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์„ค์น˜ํ•ด ๋ด…์‹œ๋‹ค.


```bash
pip install transformers datasets accelerate tensorboard evaluate --upgrade
```

์ด ์˜ˆ์ œ์—์„œ๋Š” `merve/beans-vit-224` ๋ชจ๋ธ์„ ๊ต์‚ฌ ๋ชจ๋ธ๋กœ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ๋ชจ๋ธ์€ beans ๋ฐ์ดํ„ฐ์…‹์—์„œ ํŒŒ์ธ ํŠœ๋‹๋œ `google/vit-base-patch16-224-in21k` ๊ธฐ๋ฐ˜์˜ ์ด๋ฏธ์ง€ ๋ถ„๋ฅ˜ ๋ชจ๋ธ์ž…๋‹ˆ๋‹ค. ์ด ๋ชจ๋ธ์„ ๋ฌด์ž‘์œ„๋กœ ์ดˆ๊ธฐํ™”๋œ MobileNetV2๋กœ ์ฆ๋ฅ˜ํ•ด๋ณผ ๊ฒƒ์ž…๋‹ˆ๋‹ค.

์ด์ œ ๋ฐ์ดํ„ฐ์…‹์„ ๋กœ๋“œํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

```python
from datasets import load_dataset

dataset = load_dataset("beans")
```

์ด ๊ฒฝ์šฐ ๋‘ ๋ชจ๋ธ์˜ ์ด๋ฏธ์ง€ ํ”„๋กœ์„ธ์„œ๊ฐ€ ๋™์ผํ•œ ํ•ด์ƒ๋„๋กœ ๋™์ผํ•œ ์ถœ๋ ฅ์„ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ๋•Œ๋ฌธ์—, ๋‘๊ฐ€์ง€๋ฅผ ๋ชจ๋‘ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋ฐ์ดํ„ฐ์…‹์˜ ๋ชจ๋“  ๋ถ„ํ• ๋งˆ๋‹ค ์ „์ฒ˜๋ฆฌ๋ฅผ ์ ์šฉํ•˜๊ธฐ ์œ„ํ•ด `dataset`์˜ `map()` ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•  ๊ฒƒ ์ž…๋‹ˆ๋‹ค.


```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)
```

ํ•™์ƒ ๋ชจ๋ธ(๋ฌด์ž‘์œ„๋กœ ์ดˆ๊ธฐํ™”๋œ 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 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)

# ๊ต์‚ฌ์™€ ํ•™์ƒ์˜ ์†Œํ”„ํŠธ ํƒ€๊ฒŸ(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)

# ์†์‹ค(loss) ๊ณ„์‚ฐ
distillation_loss = self.loss_function(soft_student, soft_teacher) * (self.temperature ** 2)

# ์‹ค์ œ ๋ ˆ์ด๋ธ” ์†์‹ค ๊ณ„์‚ฐ
student_target_loss = student_output.loss

# ์ตœ์ข… ์†์‹ค ๊ณ„์‚ฐ
loss = (1. - self.lambda_param) * student_target_loss + self.lambda_param * distillation_loss
return (loss, student_output) if return_outputs else loss
```

์ด์ œ Hugging Face Hub์— ๋กœ๊ทธ์ธํ•˜์—ฌ `Trainer`๋ฅผ ํ†ตํ•ด Hugging Face Hub์— ๋ชจ๋ธ์„ ํ‘ธ์‹œํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.


```python
from huggingface_hub import notebook_login

notebook_login()
```

์ด์ œ `TrainingArguments`, ๊ต์‚ฌ ๋ชจ๋ธ๊ณผ ํ•™์ƒ ๋ชจ๋ธ์„ ์„ค์ •ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.


```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)

# ๋ชจ๋ธ ์ดˆ๊ธฐํ™”
teacher_model = AutoModelForImageClassification.from_pretrained(
"merve/beans-vit-224",
num_labels=num_labels,
ignore_mismatched_sizes=True
)

# MobileNetV2 ๋ฐ‘๋ฐ”๋‹ฅ๋ถ€ํ„ฐ ํ•™์Šต
student_config = MobileNetV2Config()
student_config.num_labels = num_labels
student_model = MobileNetV2ForImageClassification(student_config)
```

`compute_metrics` ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ…Œ์ŠคํŠธ ์„ธํŠธ์—์„œ ๋ชจ๋ธ์„ ํ‰๊ฐ€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ํ•จ์ˆ˜๋Š” ํ›ˆ๋ จ ๊ณผ์ •์—์„œ ๋ชจ๋ธ์˜ `accuracy`์™€ `f1`์„ ๊ณ„์‚ฐํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.


```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"]}
```

์ •์˜ํ•œ ํ›ˆ๋ จ ์ธ์ˆ˜๋กœ `Trainer`๋ฅผ ์ดˆ๊ธฐํ™”ํ•ด๋ด…์‹œ๋‹ค. ๋˜ํ•œ ๋ฐ์ดํ„ฐ ์ฝœ๋ ˆ์ดํ„ฐ(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
)
```

์ด์ œ ๋ชจ๋ธ์„ ํ›ˆ๋ จํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

```python
trainer.train()
```

๋ชจ๋ธ์„ ํ…Œ์ŠคํŠธ ์„ธํŠธ์—์„œ ํ‰๊ฐ€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

```python
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)์—์„œ ์ฐพ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

0 comments on commit 05efc73

Please sign in to comment.