AdithyaSK HF Staff commited on
Commit
db0e72f
·
verified ·
1 Parent(s): 3c30401

Stage Harbor release files 39501-40000

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/multiple_choice.md +369 -0
  2. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/object_detection.md +583 -0
  3. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/prompting.md +384 -0
  4. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/question_answering.md +422 -0
  5. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/semantic_segmentation.md +587 -0
  6. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/sequence_classification.md +389 -0
  7. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/summarization.md +413 -0
  8. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/token_classification.md +555 -0
  9. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/translation.md +407 -0
  10. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/video_classification.md +492 -0
  11. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/visual_question_answering.md +375 -0
  12. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/zero_shot_image_classification.md +144 -0
  13. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/zero_shot_object_detection.md +307 -0
  14. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/testing.md +1271 -0
  15. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tflite.md +62 -0
  16. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tiny_agents.md +44 -0
  17. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tokenizer_summary.md +253 -0
  18. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/torchscript.md +189 -0
  19. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/trainer.md +534 -0
  20. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/training.md +428 -0
  21. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/troubleshooting.md +198 -0
  22. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ms/_toctree.yml +680 -0
  23. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ms/index.md +464 -0
  24. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/_config.py +14 -0
  25. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/_toctree.yml +38 -0
  26. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/accelerate.md +145 -0
  27. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/converting_tensorflow_models.md +152 -0
  28. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/create_a_model.md +359 -0
  29. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/custom_models.md +358 -0
  30. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/fast_tokenizers.md +66 -0
  31. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/index.md +296 -0
  32. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/installation.md +262 -0
  33. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/multilingual.md +195 -0
  34. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/pipeline_tutorial.md +157 -0
  35. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/quicktour.md +399 -0
  36. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/run_scripts.md +354 -0
  37. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/serialization.md +502 -0
  38. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/tasks/sequence_classification.md +216 -0
  39. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/tasks/token_classification.md +272 -0
  40. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/training.md +416 -0
  41. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/te/_toctree.yml +6 -0
  42. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/te/index.md +298 -0
  43. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/te/quicktour.md +557 -0
  44. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/tr/_toctree.yml +4 -0
  45. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/tr/index.md +295 -0
  46. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/zh/_toctree.yml +164 -0
  47. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/zh/accelerate.md +132 -0
  48. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/zh/add_new_pipeline.md +238 -0
  49. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/zh/attention.md +37 -0
  50. tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/zh/autoclass_tutorial.md +149 -0
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/multiple_choice.md ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # 객관식 문제[[multiple-choice]]
18
+
19
+ [[open-in-colab]]
20
+
21
+ 객관식 과제는 문맥과 함께 여러 개의 후보 답변이 제공되고 모델이 정답을 선택하도록 학습된다는 점을 제외하면 질의응답과 유사합니다.
22
+
23
+ 진행하는 방법은 아래와 같습니다:
24
+
25
+ 1. [SWAG](https://huggingface.co/datasets/swag) 데이터 세트의 'regular' 구성으로 [BERT](https://huggingface.co/google-bert/bert-base-uncased)를 미세 조정하여 여러 옵션과 일부 컨텍스트가 주어졌을 때 가장 적합한 답을 선택합니다.
26
+ 2. 추론에 미세 조정된 모델을 사용합니다.
27
+
28
+ 시작하기 전에 필요한 라이브러리가 모두 설치되어 있는지 확인하세요:
29
+
30
+ ```bash
31
+ pip install transformers datasets evaluate
32
+ ```
33
+
34
+ 모델을 업로드하고 커뮤니티와 공유할 수 있도록 허깅페이스 계정에 로그인하는 것이 좋습니다. 메시지가 표시되면 토큰을 입력하여 로그인합니다:
35
+
36
+ ```py
37
+ >>> from huggingface_hub import notebook_login
38
+
39
+ >>> notebook_login()
40
+ ```
41
+
42
+ ## SWAG 데이터 세트 가져오기[[load-swag-dataset]]
43
+
44
+ 먼저 🤗 Datasets 라이브러리에서 SWAG 데이터셋의 '일반' 구성을 가져옵니다:
45
+
46
+ ```py
47
+ >>> from datasets import load_dataset
48
+
49
+ >>> swag = load_dataset("swag", "regular")
50
+ ```
51
+
52
+ 이제 데이터를 살펴봅니다:
53
+
54
+ ```py
55
+ >>> swag["train"][0]
56
+ {'ending0': 'passes by walking down the street playing their instruments.',
57
+ 'ending1': 'has heard approaching them.',
58
+ 'ending2': "arrives and they're outside dancing and asleep.",
59
+ 'ending3': 'turns the lead singer watches the performance.',
60
+ 'fold-ind': '3416',
61
+ 'gold-source': 'gold',
62
+ 'label': 0,
63
+ 'sent1': 'Members of the procession walk down the street holding small horn brass instruments.',
64
+ 'sent2': 'A drum line',
65
+ 'startphrase': 'Members of the procession walk down the street holding small horn brass instruments. A drum line',
66
+ 'video-id': 'anetv_jkn6uvmqwh4'}
67
+ ```
68
+
69
+ 여기에는 많은 필드가 있는 것처럼 보이지만 실제로는 매우 간단합니다:
70
+
71
+ - `sent1` 및 `sent2`: 이 필드는 문장이 어떻게 시작되는지 보여주며, 이 두 필드를 합치면 `시작 구절(startphrase)` 필드가 됩니다.
72
+ - `종료 구절(ending)`: 문장이 어떻게 끝날 수 있는지에 대한 가능한 종료 구절를 제시하지만 그 중 하나만 정답입니다.
73
+ - `레이블(label)`: 올바른 문장 종료 구절을 식별합니다.
74
+
75
+ ## 전처리[[preprocess]]
76
+
77
+ 다음 단계는 문장의 시작과 네 가지 가능한 구절을 처리하기 위해 BERT 토크나이저를 불러옵니다:
78
+
79
+ ```py
80
+ >>> from transformers import AutoTokenizer
81
+
82
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
83
+ ```
84
+
85
+ 생성하려는 전처리 함수는 다음과 같아야 합니다:
86
+
87
+ 1. `sent1` 필드를 네 개 복사한 다음 각각을 `sent2`와 결합하여 문장이 시작되는 방식을 재현합니다.
88
+ 2. `sent2`를 네 가지 가능한 문장 구절 각각과 결합합니다.
89
+ 3. 이 두 목록을 토큰화할 수 있도록 평탄화(flatten)하고, 각 예제에 해당하는 `input_ids`, `attention_mask` 및 `labels` 필드를 갖도록 다차원화(unflatten) 합니다.
90
+
91
+ ```py
92
+ >>> ending_names = ["ending0", "ending1", "ending2", "ending3"]
93
+
94
+
95
+ >>> def preprocess_function(examples):
96
+ ... first_sentences = [[context] * 4 for context in examples["sent1"]]
97
+ ... question_headers = examples["sent2"]
98
+ ... second_sentences = [
99
+ ... [f"{header} {examples[end][i]}" for end in ending_names] for i, header in enumerate(question_headers)
100
+ ... ]
101
+
102
+ ... first_sentences = sum(first_sentences, [])
103
+ ... second_sentences = sum(second_sentences, [])
104
+
105
+ ... tokenized_examples = tokenizer(first_sentences, second_sentences, truncation=True)
106
+ ... return {k: [v[i : i + 4] for i in range(0, len(v), 4)] for k, v in tokenized_examples.items()}
107
+ ```
108
+
109
+ 전체 데이터 집합에 전처리 기능을 적용하려면 🤗 Datasets [`~datasets.Dataset.map`] 메소드를 사용합니다. `batched=True`를 설정하여 데이터 집합의 여러 요소를 한 번에 처리하면 `map` 함수의 속도를 높일 수 있습니다:
110
+
111
+ ```py
112
+ tokenized_swag = swag.map(preprocess_function, batched=True)
113
+ ```
114
+
115
+ [`DataCollatorForMultipleChoice`]는 모든 모델 입력을 평탄화하고 패딩을 적용하며 그 결과를 결과를 다차원화합니다:
116
+ ```py
117
+ >>> from transformers import DataCollatorForMultipleChoice
118
+ >>> collator = DataCollatorForMultipleChoice(tokenizer=tokenizer)
119
+ ```
120
+
121
+ ## 평가 하기[[evaluate]]
122
+
123
+ 훈련 중에 메트릭을 포함하면 모델의 성능을 평가하는 데 도움이 되는 경우가 많습니다. 🤗[Evaluate](https://huggingface.co/docs/evaluate/index) 라이브러리를 사용하여 평가 방법을 빠르게 가져올 수 있습니다. 이 작업에서는 [accuracy](https://huggingface.co/spaces/evaluate-metric/accuracy) 지표를 가져옵니다(🤗 Evaluate [둘러보기](https://huggingface.co/docs/evaluate/a_quick_tour)를 참조하여 지표를 가져오고 계산하는 방법에 대해 자세히 알아보세요):
124
+
125
+ ```py
126
+ >>> import evaluate
127
+
128
+ >>> accuracy = evaluate.load("accuracy")
129
+ ```
130
+
131
+ 그리고 예측과 레이블을 [`~evaluate.EvaluationModule.compute`]에 전달하여 정확도를 계산하는 함수를 만듭니다:
132
+
133
+ ```py
134
+ >>> import numpy as np
135
+
136
+
137
+ >>> def compute_metrics(eval_pred):
138
+ ... predictions, labels = eval_pred
139
+ ... predictions = np.argmax(predictions, axis=1)
140
+ ... return accuracy.compute(predictions=predictions, references=labels)
141
+ ```
142
+
143
+ 이제 `compute_metrics` 함수를 사용할 준비가 되었으며, 훈련을 설정할 때 이 함수로 돌아가게 됩니다.
144
+
145
+ ## 훈련 하기[[train]]
146
+
147
+ <frameworkcontent>
148
+ <pt>
149
+ <Tip>
150
+
151
+ [`Trainer`]로 모델을 미세 조정하는 데 익숙하지 않다면 기본 튜토리얼 [여기](../training#train-with-pytorch-trainer)를 살펴보세요!
152
+
153
+ </Tip>
154
+
155
+ 이제 모델 훈련을 시작할 준비가 되었습니다! [`AutoModelForMultipleChoice`]로 BERT를 로드합니다:
156
+
157
+ ```py
158
+ >>> from transformers import AutoModelForMultipleChoice, TrainingArguments, Trainer
159
+
160
+ >>> model = AutoModelForMultipleChoice.from_pretrained("google-bert/bert-base-uncased")
161
+ ```
162
+
163
+ 이제 세 단계만 남았습니다:
164
+
165
+ 1. 훈련 하이퍼파라미터를 [`TrainingArguments`]에 정의합니다. 유일한 필수 매개변수는 모델을 저장할 위치를 지정하는 `output_dir`입니다. `push_to_hub=True`를 설정하여 이 모델을 허브에 푸시합니다(모델을 업로드하려면 허깅 페이스에 로그인해야 합니다). 각 에폭이 끝날 때마다 [`Trainer`]가 정확도를 평가하고 훈련 체크포인트를 저장합니다.
166
+ 2. 모델, 데이터 세트, 토크나이저, 데이터 콜레이터, `compute_metrics` 함수와 함께 훈련 인자를 [`Trainer`]에 전달합니다.
167
+ 3. [`~Trainer.train`]을 사용하여 모델을 미세 조정합니다.
168
+
169
+ ```py
170
+ >>> training_args = TrainingArguments(
171
+ ... output_dir="my_awesome_swag_model",
172
+ ... eval_strategy="epoch",
173
+ ... save_strategy="epoch",
174
+ ... load_best_model_at_end=True,
175
+ ... learning_rate=5e-5,
176
+ ... per_device_train_batch_size=16,
177
+ ... per_device_eval_batch_size=16,
178
+ ... num_train_epochs=3,
179
+ ... weight_decay=0.01,
180
+ ... push_to_hub=True,
181
+ ... )
182
+
183
+ >>> trainer = Trainer(
184
+ ... model=model,
185
+ ... args=training_args,
186
+ ... train_dataset=tokenized_swag["train"],
187
+ ... eval_dataset=tokenized_swag["validation"],
188
+ ... processing_class=tokenizer,
189
+ ... data_collator=collator,
190
+ ... compute_metrics=compute_metrics,
191
+ ... )
192
+
193
+ >>> trainer.train()
194
+ ```
195
+
196
+ 훈련이 완료되면 모든 사람이 모델을 사용할 수 있도록 [`~transformers.Trainer.push_to_hub`] 메소드를 사용하여 모델을 허브에 공유하세요:
197
+
198
+ ```py
199
+ >>> trainer.push_to_hub()
200
+ ```
201
+ </pt>
202
+ <tf>
203
+ <Tip>
204
+
205
+ Keras로 모델을 미세 조정하는 데 익숙하지 않다면 기본 튜토리얼 [여기](../training#train-a-tensorflow-model-with-keras)를 살펴보시기 바랍니다!
206
+
207
+ </Tip>
208
+ TensorFlow에서 모델을 미세 조정하려면 최적화 함수, 학습률 스케쥴 및 몇 가지 학습 하이퍼파라미터를 설정하는 것부터 시작하세요:
209
+
210
+ ```py
211
+ >>> from transformers import create_optimizer
212
+
213
+ >>> batch_size = 16
214
+ >>> num_train_epochs = 2
215
+ >>> total_train_steps = (len(tokenized_swag["train"]) // batch_size) * num_train_epochs
216
+ >>> optimizer, schedule = create_optimizer(init_lr=5e-5, num_warmup_steps=0, num_train_steps=total_train_steps)
217
+ ```
218
+
219
+ 그리고 [`TFAutoModelForMultipleChoice`]로 BERT를 가져올 수 있습니다:
220
+
221
+ ```py
222
+ >>> from transformers import TFAutoModelForMultipleChoice
223
+
224
+ >>> model = TFAutoModelForMultipleChoice.from_pretrained("google-bert/bert-base-uncased")
225
+ ```
226
+
227
+ [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]을 사용하여 데이터 세트를 `tf.data.Dataset` 형식으로 변환합니다:
228
+
229
+ ```py
230
+ >>> data_collator = DataCollatorForMultipleChoice(tokenizer=tokenizer)
231
+ >>> tf_train_set = model.prepare_tf_dataset(
232
+ ... tokenized_swag["train"],
233
+ ... shuffle=True,
234
+ ... batch_size=batch_size,
235
+ ... collate_fn=data_collator,
236
+ ... )
237
+
238
+ >>> tf_validation_set = model.prepare_tf_dataset(
239
+ ... tokenized_swag["validation"],
240
+ ... shuffle=False,
241
+ ... batch_size=batch_size,
242
+ ... collate_fn=data_collator,
243
+ ... )
244
+ ```
245
+
246
+ [`compile`](https://keras.io/api/models/model_training_apis/#compile-method)을 사용하여 훈련 모델을 구성합니다:
247
+
248
+ ```py
249
+ >>> model.compile(optimizer=optimizer)
250
+ ```
251
+
252
+ 훈련을 시작하기 전에 설정해야 할 마지막 두 가지는 예측의 정확도를 계산하고 모델을 허브로 푸시하는 방법을 제공하는 것입니다. 이 두 가지 작업은 모두 [Keras 콜백](../main_classes/keras_callbacks)을 사용하여 수행할 수 있습니다.
253
+
254
+ `compute_metrics`함수를 [`~transformers.KerasMetricCallback`]에 전달하세요:
255
+
256
+ ```py
257
+ >>> from transformers.keras_callbacks import KerasMetricCallback
258
+
259
+ >>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set)
260
+ ```
261
+
262
+ 모델과 토크나이저를 업로드할 위치를 [`~transformers.PushToHubCallback`]에서 지정하세요:
263
+
264
+ ```py
265
+ >>> from transformers.keras_callbacks import PushToHubCallback
266
+
267
+ >>> push_to_hub_callback = PushToHubCallback(
268
+ ... output_dir="my_awesome_model",
269
+ ... tokenizer=tokenizer,
270
+ ... )
271
+ ```
272
+
273
+ 그리고 콜백을 함께 묶습니다:
274
+
275
+ ```py
276
+ >>> callbacks = [metric_callback, push_to_hub_callback]
277
+ ```
278
+
279
+ 이제 모델 훈련을 시작합니다! 훈련 및 검증 데이터 세트, 에폭 수, 콜백을 사용하여 [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)을 호출하고 모델을 미세 조정합니다:
280
+
281
+ ```py
282
+ >>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=2, callbacks=callbacks)
283
+ ```
284
+
285
+ 훈련이 완료되면 모델이 자동으로 허브에 업로드되어 누구나 사용할 수 있습니다!
286
+ </tf>
287
+ </frameworkcontent>
288
+
289
+
290
+ <Tip>
291
+
292
+ 객관식 모델을 미세 조정하는 방법에 대한 보다 심층적인 예는 아래 문서를 참조하세요.
293
+ [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb)
294
+ 또는 [TensorFlow notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice-tf.ipynb).
295
+
296
+ </Tip>
297
+
298
+ ## 추론 하기[[inference]]
299
+
300
+ 이제 모델을 미세 조정했으니 추론에 사용할 수 있습니다!
301
+
302
+ 텍스트와 두 개의 후보 답안을 작성합니다:
303
+
304
+ ```py
305
+ >>> prompt = "France has a bread law, Le Décret Pain, with strict rules on what is allowed in a traditional baguette."
306
+ >>> candidate1 = "The law does not apply to croissants and brioche."
307
+ >>> candidate2 = "The law applies to baguettes."
308
+ ```
309
+
310
+ <frameworkcontent>
311
+ <pt>
312
+ 각 프롬프트와 후보 답변 쌍을 토큰화하여 PyTorch 텐서를 반환합니다. 또한 `labels`을 생성해야 합니다:
313
+
314
+ ```py
315
+ >>> from transformers import AutoTokenizer
316
+
317
+ >>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_swag_model")
318
+ >>> inputs = tokenizer([[prompt, candidate1], [prompt, candidate2]], return_tensors="pt", padding=True)
319
+ >>> labels = torch.tensor(0).unsqueeze(0)
320
+ ```
321
+
322
+ 입력과 레이블을 모델에 전달하고 `logits`을 반환합니다:
323
+
324
+ ```py
325
+ >>> from transformers import AutoModelForMultipleChoice
326
+
327
+ >>> model = AutoModelForMultipleChoice.from_pretrained("my_awesome_swag_model")
328
+ >>> outputs = model(**{k: v.unsqueeze(0) for k, v in inputs.items()}, labels=labels)
329
+ >>> logits = outputs.logits
330
+ ```
331
+
332
+ 가장 높은 확률을 가진 클래스를 가져옵니다:
333
+
334
+ ```py
335
+ >>> predicted_class = logits.argmax().item()
336
+ >>> predicted_class
337
+ '0'
338
+ ```
339
+ </pt>
340
+ <tf>
341
+ 각 프롬프트와 후보 답안 쌍을 토큰화하여 텐서플로 텐서를 반환합니다:
342
+
343
+ ```py
344
+ >>> from transformers import AutoTokenizer
345
+
346
+ >>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_swag_model")
347
+ >>> inputs = tokenizer([[prompt, candidate1], [prompt, candidate2]], return_tensors="tf", padding=True)
348
+ ```
349
+
350
+ 모델에 입력을 전달하고 `logits`를 반환합니다:
351
+
352
+ ```py
353
+ >>> from transformers import TFAutoModelForMultipleChoice
354
+
355
+ >>> model = TFAutoModelForMultipleChoice.from_pretrained("my_awesome_swag_model")
356
+ >>> inputs = {k: tf.expand_dims(v, 0) for k, v in inputs.items()}
357
+ >>> outputs = model(inputs)
358
+ >>> logits = outputs.logits
359
+ ```
360
+
361
+ 가장 높은 확률을 가진 클래스를 가져옵니다:
362
+
363
+ ```py
364
+ >>> predicted_class = int(tf.math.argmax(logits, axis=-1)[0])
365
+ >>> predicted_class
366
+ '0'
367
+ ```
368
+ </tf>
369
+ </frameworkcontent>
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/object_detection.md ADDED
@@ -0,0 +1,583 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # 객체 탐지 [[object-detection]]
18
+
19
+ [[open-in-colab]]
20
+
21
+ 객체 탐지는 이미지에서 인스턴스(예: 사람, 건물 또는 자동차)를 감지하는 컴퓨터 비전 작업입니다. 객체 탐지 모델은 이미지를 입력으로 받고 탐지된 바운딩 박스의 좌표와 관련된 레이블을 출력합니다.
22
+ 하나의 이미지에는 여러 객체가 있을 수 있으며 각각은 자체적인 바운딩 박스와 레이블을 가질 수 있습니다(예: 차와 건물이 있는 이미지).
23
+ 또한 각 객체는 이미지의 다른 부분에 존재할 수 있습니다(예: 이미지에 여러 대의 차가 있을 수 있음).
24
+ 이 작업은 보행자, 도로 표지판, 신호등과 같은 것들을 감지하는 자율 주행에 일반적으로 사용됩니다.
25
+ 다른 응용 분야로는 이미지 내 객체 수 계산 및 이미지 검색 등이 있습니다.
26
+
27
+ 이 가이드에서 다음을 배울 것입니다:
28
+
29
+ 1. 합성곱 백본(인풋 데이터의 특성을 추출하는 합성곱 네트워크)과 인코더-디코더 트랜스포머 모델을 결합한 [DETR](https://huggingface.co/docs/transformers/model_doc/detr) 모델을 [CPPE-5](https://huggingface.co/datasets/cppe-5) 데이터 세트에 대해 미세조정 하기
30
+ 2. 미세조정 한 모델을 추론에 사용하기.
31
+
32
+ <Tip>
33
+
34
+ 이 작업과 호환되는 모든 아키텍처와 체크포인트를 보려면 [작업 페이지](https://huggingface.co/tasks/object-detection)를 확인하는 것이 좋습니다.
35
+
36
+ </Tip>
37
+
38
+ 시작하기 전에 필요한 모든 라이브러리가 설치되어 있는지 확인하세요:
39
+ ```bash
40
+ pip install -q datasets transformers evaluate timm albumentations
41
+ ```
42
+
43
+ 허깅페이스 허브에서 데이터 세트를 가져오기 위한 🤗 Datasets과 모델을 학습하기 위한 🤗 Transformers, 데이터를 증강하기 위한 `albumentations`를 사용합니다.
44
+ DETR 모델의 합성곱 백본을 가져오기 위해서는 현재 `timm`이 필요합니다.
45
+
46
+ 커뮤니티에 모델을 업로드하고 공유할 수 있도록 Hugging Face 계정에 로그인하는 것을 권장합니다. 프롬프트가 나타나면 토큰을 입력하여 로그인하세요:
47
+
48
+ ```py
49
+ >>> from huggingface_hub import notebook_login
50
+
51
+ >>> notebook_login()
52
+ ```
53
+
54
+ ## CPPE-5 데이터 세트 가져오기 [[load-the-CPPE-5-dataset]]
55
+
56
+ [CPPE-5](https://huggingface.co/datasets/cppe-5) 데이터 세트는 COVID-19 대유행 상황에서 의료 전문인력 보호 장비(PPE)를 식별하는 어노테이션이 포함된 이미지를 담고 있습니다.
57
+
58
+ 데이터 세트를 가져오세요:
59
+
60
+ ```py
61
+ >>> from datasets import load_dataset
62
+
63
+ >>> cppe5 = load_dataset("cppe-5")
64
+ >>> cppe5
65
+ DatasetDict({
66
+ train: Dataset({
67
+ features: ['image_id', 'image', 'width', 'height', 'objects'],
68
+ num_rows: 1000
69
+ })
70
+ test: Dataset({
71
+ features: ['image_id', 'image', 'width', 'height', 'objects'],
72
+ num_rows: 29
73
+ })
74
+ })
75
+ ```
76
+
77
+ 이 데이터 세트는 학습 세트 이미지 1,000개와 테스트 세트 이미지 29개를 갖고 있습니다.
78
+
79
+ 데이터에 익숙해지기 위해, 예시가 어떻게 구성되어 있는지 살펴보세요.
80
+
81
+ ```py
82
+ >>> cppe5["train"][0]
83
+ {'image_id': 15,
84
+ 'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=943x663 at 0x7F9EC9E77C10>,
85
+ 'width': 943,
86
+ 'height': 663,
87
+ 'objects': {'id': [114, 115, 116, 117],
88
+ 'area': [3796, 1596, 152768, 81002],
89
+ 'bbox': [[302.0, 109.0, 73.0, 52.0],
90
+ [810.0, 100.0, 57.0, 28.0],
91
+ [160.0, 31.0, 248.0, 616.0],
92
+ [741.0, 68.0, 202.0, 401.0]],
93
+ 'category': [4, 4, 0, 0]}}
94
+ ```
95
+
96
+ 데이터 세트에 있는 예시는 다음의 영역을 가지고 있습니다:
97
+
98
+ - `image_id`: 예시 이미지 id
99
+ - `image`: 이미지를 포함하는 `PIL.Image.Image` 객체
100
+ - `width`: 이미지의 너비
101
+ - `height`: 이미지의 높이
102
+ - `objects`: 이미지 안의 객체들의 바운딩 박스 메타데이터를 포함하는 딕셔너리:
103
+ - `id`: 어노테이션 id
104
+ - `area`: 바운딩 박스의 면적
105
+ - `bbox`: 객체의 바운딩 박스 ([COCO 포맷](https://albumentations.ai/docs/getting_started/bounding_boxes_augmentation/#coco)으로)
106
+ - `category`: 객체의 카테고리, 가능한 값으로는 `Coverall (0)`, `Face_Shield (1)`, `Gloves (2)`, `Goggles (3)` 및 `Mask (4)` 가 포함됩니다.
107
+
108
+ `bbox` 필드가 DETR 모델이 요구하는 COCO 형식을 따른다는 것을 알 수 있습니다.
109
+ 그러나 `objects` 내부의 필드 그룹은 DETR이 요구하는 어노테이션 형식과 다릅니다. 따라서 이 데이터를 학습에 사용하기 전에 전처리를 적용해야 합니다.
110
+
111
+ 데이터를 더 잘 이해하기 위해서 데이터 세트에서 한 가지 예시를 시각화하세요.
112
+
113
+ ```py
114
+ >>> import numpy as np
115
+ >>> import os
116
+ >>> from PIL import Image, ImageDraw
117
+
118
+ >>> image = cppe5["train"][0]["image"]
119
+ >>> annotations = cppe5["train"][0]["objects"]
120
+ >>> draw = ImageDraw.Draw(image)
121
+
122
+ >>> categories = cppe5["train"].features["objects"].feature["category"].names
123
+
124
+ >>> id2label = {index: x for index, x in enumerate(categories, start=0)}
125
+ >>> label2id = {v: k for k, v in id2label.items()}
126
+
127
+ >>> for i in range(len(annotations["id"])):
128
+ ... box = annotations["bbox"][i - 1]
129
+ ... class_idx = annotations["category"][i - 1]
130
+ ... x, y, w, h = tuple(box)
131
+ ... draw.rectangle((x, y, x + w, y + h), outline="red", width=1)
132
+ ... draw.text((x, y), id2label[class_idx], fill="white")
133
+
134
+ >>> image
135
+ ```
136
+
137
+ <div class="flex justify-center">
138
+ <img src="https://i.imgur.com/TdaqPJO.png" alt="CPPE-5 Image Example"/>
139
+ </div>
140
+
141
+ 바운딩 박스와 연결된 레이블을 시각화하려면 데이터 세트의 메타 데이터, 특히 `category` 필드에서 레이블을 가져와야 합니다.
142
+ 또한 레이블 ID를 레이블 클래스에 매핑하는 `id2label`과 반대로 매핑하는 `label2id` 딕셔너리를 만들어야 합니다.
143
+ 모델을 설정할 때 이러한 매핑을 사용할 수 있습니다. 이러한 매핑은 허깅페이스 허브에서 모델을 공유했을 때 다른 사람들이 재사용할 수 있습니다.
144
+
145
+ 데이터를 더 잘 이해하기 위한 최종 단계로, 잠재적인 문제를 찾아보세요.
146
+ 객체 감지를 위한 데이터 세트에서 자주 발생하는 문제 중 하나는 바운딩 박스가 이미지의 가장자리를 넘어가는 것입니다.
147
+ 이러한 바운딩 박스를 "넘어가는 것(run away)"은 훈련 중에 오류를 발생시킬 수 있기에 이 단계에서 처리해야 합니다.
148
+ 이 데이터 세트에도 같은 문제가 있는 몇 가지 예가 있습니다. 이 가이드에서는 간단하게하기 위해 데이터에서 이러한 이미지를 제거합니다.
149
+
150
+ ```py
151
+ >>> remove_idx = [590, 821, 822, 875, 876, 878, 879]
152
+ >>> keep = [i for i in range(len(cppe5["train"])) if i not in remove_idx]
153
+ >>> cppe5["train"] = cppe5["train"].select(keep)
154
+ ```
155
+
156
+ ## 데이터 전처리하기 [[preprocess-the-data]]
157
+
158
+ 모델을 미세 조정 하려면, 미리 학습된 모델에서 사용한 전처리 방식과 정확하게 일치하도록 사용할 데이터를 전처리해야 합니다.
159
+ [`AutoImageProcessor`]는 이미지 데이터를 처리하여 DETR 모델이 학습에 사용할 수 있는 `pixel_values`, `pixel_mask`, 그리고 `labels`를 생성하는 작업을 담당합니다.
160
+ 이 이미지 프로세서에는 걱정하지 않아도 되는 몇 가지 속성이 있습니다:
161
+
162
+ - `image_mean = [0.485, 0.456, 0.406 ]`
163
+ - `image_std = [0.229, 0.224, 0.225]`
164
+
165
+
166
+ 이 값들은 모델 사전 훈련 중 이미지를 정규화하는 데 사용되는 평균과 표준 편차입니다.
167
+ 이 값들은 추론 또는 사전 훈련된 이미지 모델을 세밀하게 조정할 때 복제해야 하는 중요한 값입니다.
168
+
169
+ 사전 훈련된 모델과 동일한 체크포인트에서 이미지 프로세서를 인스턴스화합니다.
170
+
171
+ ```py
172
+ >>> from transformers import AutoImageProcessor
173
+
174
+ >>> checkpoint = "facebook/detr-resnet-50"
175
+ >>> image_processor = AutoImageProcessor.from_pretrained(checkpoint)
176
+ ```
177
+
178
+ `image_processor`에 이미지를 전달하기 전에, 데이터 세트에 두 가지 전처리를 적용해야 합니다:
179
+
180
+ - 이미지 증강
181
+ - DETR 모델의 요구에 맞게 어노테이션을 다시 포맷팅
182
+
183
+ 첫째로, 모델이 학습 데이터에 과적합 되지 않도록 데이터 증강 라이브러리 중 아무거나 사용하여 변환을 적용할 수 있습니다. 여기에서는 [Albumentations](https://albumentations.ai/docs/) 라이브러리를 사용합니다...
184
+ 이 라이브러리는 변환을 이미지에 적용하고 바운딩 박스를 적절하게 업데이트하도록 보장합니다.
185
+ 🤗 Datasets 라이브러리 문서에는 [객체 탐지를 위해 이미지를 보강하는 방법에 대한 자세한 가이드](https://huggingface.co/docs/datasets/object_detection)가 있으며,
186
+ 이 예제와 정확히 동일한 데이터 세트를 사용합니다. 여기서는 각 이미지를 (480, 480) 크기로 조정하고, 좌우로 뒤집고, 밝기를 높이는 동일한 접근법을 적용합니다:
187
+
188
+
189
+ ```py
190
+ >>> import albumentations
191
+ >>> import numpy as np
192
+ >>> import torch
193
+
194
+ >>> transform = albumentations.Compose(
195
+ ... [
196
+ ... albumentations.Resize(480, 480),
197
+ ... albumentations.HorizontalFlip(p=1.0),
198
+ ... albumentations.RandomBrightnessContrast(p=1.0),
199
+ ... ],
200
+ ... bbox_params=albumentations.BboxParams(format="coco", label_fields=["category"]),
201
+ ... )
202
+ ```
203
+
204
+ 이미지 프로세서는 어노테이션이 다음과 같은 형식일 것으로 예상합니다: `{'image_id': int, 'annotations': list[Dict]}`, 여기서 각 딕셔너리는 COCO 객체 어노테이션입니다. 단일 예제에 대해 어노테이션의 형식을 다시 지정하는 함수를 추가해 보겠습니다:
205
+
206
+ ```py
207
+ >>> def formatted_anns(image_id, category, area, bbox):
208
+ ... annotations = []
209
+ ... for i in range(0, len(category)):
210
+ ... new_ann = {
211
+ ... "image_id": image_id,
212
+ ... "category_id": category[i],
213
+ ... "isCrowd": 0,
214
+ ... "area": area[i],
215
+ ... "bbox": list(bbox[i]),
216
+ ... }
217
+ ... annotations.append(new_ann)
218
+
219
+ ... return annotations
220
+ ```
221
+
222
+ 이제 이미지와 어노테이션 전처리 변환을 결합하여 예제 배치에 사용할 수 있습니다:
223
+
224
+ ```py
225
+ >>> # transforming a batch
226
+ >>> def transform_aug_ann(examples):
227
+ ... image_ids = examples["image_id"]
228
+ ... images, bboxes, area, categories = [], [], [], []
229
+ ... for image, objects in zip(examples["image"], examples["objects"]):
230
+ ... image = np.array(image.convert("RGB"))[:, :, ::-1]
231
+ ... out = transform(image=image, bboxes=objects["bbox"], category=objects["category"])
232
+
233
+ ... area.append(objects["area"])
234
+ ... images.append(out["image"])
235
+ ... bboxes.append(out["bboxes"])
236
+ ... categories.append(out["category"])
237
+
238
+ ... targets = [
239
+ ... {"image_id": id_, "annotations": formatted_anns(id_, cat_, ar_, box_)}
240
+ ... for id_, cat_, ar_, box_ in zip(image_ids, categories, area, bboxes)
241
+ ... ]
242
+
243
+ ... return image_processor(images=images, annotations=targets, return_tensors="pt")
244
+ ```
245
+
246
+ 이전 단계에서 만든 전처리 함수를 🤗 Datasets의 [`~datasets.Dataset.with_transform`] 메소드를 사용하여 데이터 세트 전체에 적용합니다.
247
+ 이 메소드는 데이터 세트의 요소를 가져올 때마다 전처리 함수를 적용합니다.
248
+
249
+ 이 시점에서는 전처리 후 데이터 세트에서 예시 하나를 가져와서 변환 후 모양이 어떻게 되는지 확인해 볼 수 있습니다.
250
+ 이때, `pixel_values` 텐서, `pixel_mask` 텐서, 그리고 `labels`로 구성된 텐서가 있어야 합니다.
251
+
252
+ ```py
253
+ >>> cppe5["train"] = cppe5["train"].with_transform(transform_aug_ann)
254
+ >>> cppe5["train"][15]
255
+ {'pixel_values': tensor([[[ 0.9132, 0.9132, 0.9132, ..., -1.9809, -1.9809, -1.9809],
256
+ [ 0.9132, 0.9132, 0.9132, ..., -1.9809, -1.9809, -1.9809],
257
+ [ 0.9132, 0.9132, 0.9132, ..., -1.9638, -1.9638, -1.9638],
258
+ ...,
259
+ [-1.5699, -1.5699, -1.5699, ..., -1.9980, -1.9980, -1.9980],
260
+ [-1.5528, -1.5528, -1.5528, ..., -1.9980, -1.9809, -1.9809],
261
+ [-1.5528, -1.5528, -1.5528, ..., -1.9980, -1.9809, -1.9809]],
262
+
263
+ [[ 1.3081, 1.3081, 1.3081, ..., -1.8431, -1.8431, -1.8431],
264
+ [ 1.3081, 1.3081, 1.3081, ..., -1.8431, -1.8431, -1.8431],
265
+ [ 1.3081, 1.3081, 1.3081, ..., -1.8256, -1.8256, -1.8256],
266
+ ...,
267
+ [-1.3179, -1.3179, -1.3179, ..., -1.8606, -1.8606, -1.8606],
268
+ [-1.3004, -1.3004, -1.3004, ..., -1.8606, -1.8431, -1.8431],
269
+ [-1.3004, -1.3004, -1.3004, ..., -1.8606, -1.8431, -1.8431]],
270
+
271
+ [[ 1.4200, 1.4200, 1.4200, ..., -1.6476, -1.6476, -1.6476],
272
+ [ 1.4200, 1.4200, 1.4200, ..., -1.6476, -1.6476, -1.6476],
273
+ [ 1.4200, 1.4200, 1.4200, ..., -1.6302, -1.6302, -1.6302],
274
+ ...,
275
+ [-1.0201, -1.0201, -1.0201, ..., -1.5604, -1.5604, -1.5604],
276
+ [-1.0027, -1.0027, -1.0027, ..., -1.5604, -1.5430, -1.5430],
277
+ [-1.0027, -1.0027, -1.0027, ..., -1.5604, -1.5430, -1.5430]]]),
278
+ 'pixel_mask': tensor([[1, 1, 1, ..., 1, 1, 1],
279
+ [1, 1, 1, ..., 1, 1, 1],
280
+ [1, 1, 1, ..., 1, 1, 1],
281
+ ...,
282
+ [1, 1, 1, ..., 1, 1, 1],
283
+ [1, 1, 1, ..., 1, 1, 1],
284
+ [1, 1, 1, ..., 1, 1, 1]]),
285
+ 'labels': {'size': tensor([800, 800]), 'image_id': tensor([756]), 'class_labels': tensor([4]), 'boxes': tensor([[0.7340, 0.6986, 0.3414, 0.5944]]), 'area': tensor([519544.4375]), 'iscrowd': tensor([0]), 'orig_size': tensor([480, 480])}}
286
+ ```
287
+
288
+ 각각의 이미지를 성공적으로 증강하고 이미지의 어노테이션을 준비했습니다.
289
+ 그러나 전처리는 아직 끝나지 않았습니다. 마지막 단계로, 이미지를 배치로 만들 사용자 정의 `collate_fn`을 생성합니다.
290
+ 해당 배치에서 가장 큰 이미지에 이미지(현재 `pixel_values` 인)를 패드하고, 실제 픽셀(1)과 패딩(0)을 나타내기 위해 그에 해당하는 새로운 `pixel_mask`를 생성해야 합니다.
291
+
292
+ ```py
293
+ >>> def collate_fn(batch):
294
+ ... pixel_values = [item["pixel_values"] for item in batch]
295
+ ... encoding = image_processor.pad(pixel_values, return_tensors="pt")
296
+ ... labels = [item["labels"] for item in batch]
297
+ ... batch = {}
298
+ ... batch["pixel_values"] = encoding["pixel_values"]
299
+ ... batch["pixel_mask"] = encoding["pixel_mask"]
300
+ ... batch["labels"] = labels
301
+ ... return batch
302
+ ```
303
+
304
+ ## DETR 모델 학습시키기 [[training-the-DETR-model]]
305
+
306
+ 이전 섹션에서 대부분의 작업을 수행하여 이제 모델을 학습할 준비가 되었습니다!
307
+ 이 데이터 세트의 이미지는 리사이즈 후에도 여전히 용량이 크기 때문에, 이 모델을 미세 조정 하려면 적어도 하나의 GPU가 필요합니다.
308
+
309
+ 학습은 다음의 단계를 수행합니다:
310
+
311
+ 1. [`AutoModelForObjectDetection`]을 사용하여 전처리와 동일한 체크포인트를 사용하여 모델을 가져옵니다.
312
+ 2. [`TrainingArguments`]에서 학습 하이퍼파라미터를 정의합니다.
313
+ 3. 모델, 데이터 세트, 이미지 프로세서 및 데이터 콜레이터와 함께 [`Trainer`]에 훈련 인수를 전달합니다.
314
+ 4. [`~Trainer.train`]를 호출하여 모델을 미세 조정 합니다.
315
+
316
+ 전처리에 사용한 체크포인트와 동일한 체크포인트에서 모델을 가져올 때, 데이터 세트의 메타데이터에서 만든 `label2id`와 `id2label` 매핑을 전달해야 합니다.
317
+ 또한, `ignore_mismatched_sizes=True`를 지정하여 기존 분류 헤드(모델에서 분류에 사용되는 마지막 레이어)를 새 분류 헤드로 대체합니다.
318
+
319
+ ```py
320
+ >>> from transformers import AutoModelForObjectDetection
321
+
322
+ >>> model = AutoModelForObjectDetection.from_pretrained(
323
+ ... checkpoint,
324
+ ... id2label=id2label,
325
+ ... label2id=label2id,
326
+ ... ignore_mismatched_sizes=True,
327
+ ... )
328
+ ```
329
+
330
+ [`TrainingArguments`]에서 `output_dir`을 사용하여 모델을 저장할 위치를 지정한 다음, 필요에 따라 하이퍼파라미터를 구성하세요.
331
+ 사용하지 않는 열을 제거하지 않도록 주의해야 합니다. 만약 `remove_unused_columns`가 `True`일 경우 이미지 열이 삭제됩니다.
332
+ 이미지 열이 없는 경우 `pixel_values`를 생성할 수 없기 때문에 `remove_unused_columns`를 `False`로 설정해야 합니다.
333
+ 모델을 Hub에 업로드하여 공유하려면 `push_to_hub`를 `True`로 설정하십시오(허깅페이스에 로그인하여 모델을 업로드해야 합니다).
334
+
335
+
336
+ ```py
337
+ >>> from transformers import TrainingArguments
338
+
339
+ >>> training_args = TrainingArguments(
340
+ ... output_dir="detr-resnet-50_finetuned_cppe5",
341
+ ... per_device_train_batch_size=8,
342
+ ... num_train_epochs=10,
343
+ ... fp16=True,
344
+ ... save_steps=200,
345
+ ... logging_steps=50,
346
+ ... learning_rate=1e-5,
347
+ ... weight_decay=1e-4,
348
+ ... save_total_limit=2,
349
+ ... remove_unused_columns=False,
350
+ ... push_to_hub=True,
351
+ ... )
352
+ ```
353
+
354
+ 마지막으로 `model`, `training_args`, `collate_fn`, `image_processor`와 데이터 세트(`cppe5`)를 모두 가져온 후, [`~transformers.Trainer.train`]를 호출합니다.
355
+
356
+ ```py
357
+ >>> from transformers import Trainer
358
+
359
+ >>> trainer = Trainer(
360
+ ... model=model,
361
+ ... args=training_args,
362
+ ... data_collator=collate_fn,
363
+ ... train_dataset=cppe5["train"],
364
+ ... processing_class=image_processor,
365
+ ... )
366
+
367
+ >>> trainer.train()
368
+ ```
369
+
370
+ `training_args`에서 `push_to_hub`를 `True`로 설정한 경우, 학습 체크포인트는 허깅페이스 허브에 업로드됩니다.
371
+ 학습 완료 후, [`~transformers.Trainer.push_to_hub`] 메소드를 호출하여 최종 모델을 허깅페이스 허브에 업로드합니다.
372
+
373
+ ```py
374
+ >>> trainer.push_to_hub()
375
+ ```
376
+
377
+ ## 평가하기 [[evaluate]]
378
+
379
+ 객체 탐지 모델은 일반적으로 일련의 <a href="https://cocodataset.org/#detection-eval">COCO-스타일 지표</a>로 평가됩니다.
380
+ 기존에 구현된 평가 지표 중 하나를 사용할 수도 있지만, 여기에서는 허깅페이스 허브에 푸시한 최종 모델을 평가하는 데 `torchvision`에서 제공하는 평가 지표를 사용합니다.
381
+
382
+ `torchvision` 평가자(evaluator)를 사용하려면 실측값인 COCO 데이터 세트를 준비해야 합니다.
383
+ COCO 데이터 세트를 빌드하는 API는 데이터를 특정 형식으로 저장해야 하므로, 먼저 이미지와 어노테이션을 디스크에 저장해야 합니다.
384
+ 학습을 위해 데이터를 준비할 때와 마찬가지로, cppe5["test"]에서의 어노테이션은 포맷을 맞춰야 합니다. 그러나 이미지는 그대로 유지해야 합니다.
385
+
386
+ 평가 단계는 약간의 작업이 필요하지만, 크게 세 가지 주요 단계로 나눌 수 있습니다.
387
+ 먼저, `cppe5["test"]` 세트를 준비합니다: 어노테이션을 포맷에 맞게 만들고 데이터를 디스크에 저장합니다.
388
+
389
+ ```py
390
+ >>> import json
391
+
392
+
393
+ >>> # format annotations the same as for training, no need for data augmentation
394
+ >>> def val_formatted_anns(image_id, objects):
395
+ ... annotations = []
396
+ ... for i in range(0, len(objects["id"])):
397
+ ... new_ann = {
398
+ ... "id": objects["id"][i],
399
+ ... "category_id": objects["category"][i],
400
+ ... "iscrowd": 0,
401
+ ... "image_id": image_id,
402
+ ... "area": objects["area"][i],
403
+ ... "bbox": objects["bbox"][i],
404
+ ... }
405
+ ... annotations.append(new_ann)
406
+
407
+ ... return annotations
408
+
409
+
410
+ >>> # Save images and annotations into the files torchvision.datasets.CocoDetection expects
411
+ >>> def save_cppe5_annotation_file_images(cppe5):
412
+ ... output_json = {}
413
+ ... path_output_cppe5 = f"{os.getcwd()}/cppe5/"
414
+
415
+ ... if not os.path.exists(path_output_cppe5):
416
+ ... os.makedirs(path_output_cppe5)
417
+
418
+ ... path_anno = os.path.join(path_output_cppe5, "cppe5_ann.json")
419
+ ... categories_json = [{"supercategory": "none", "id": id, "name": id2label[id]} for id in id2label]
420
+ ... output_json["images"] = []
421
+ ... output_json["annotations"] = []
422
+ ... for example in cppe5:
423
+ ... ann = val_formatted_anns(example["image_id"], example["objects"])
424
+ ... output_json["images"].append(
425
+ ... {
426
+ ... "id": example["image_id"],
427
+ ... "width": example["image"].width,
428
+ ... "height": example["image"].height,
429
+ ... "file_name": f"{example['image_id']}.png",
430
+ ... }
431
+ ... )
432
+ ... output_json["annotations"].extend(ann)
433
+ ... output_json["categories"] = categories_json
434
+
435
+ ... with open(path_anno, "w") as file:
436
+ ... json.dump(output_json, file, ensure_ascii=False, indent=4)
437
+
438
+ ... for im, img_id in zip(cppe5["image"], cppe5["image_id"]):
439
+ ... path_img = os.path.join(path_output_cppe5, f"{img_id}.png")
440
+ ... im.save(path_img)
441
+
442
+ ... return path_output_cppe5, path_anno
443
+ ```
444
+
445
+ 다음으로, `cocoevaluator`와 함께 사용할 수 있는 `CocoDetection` 클래스의 인스턴스를 준비합니다.
446
+
447
+ ```py
448
+ >>> import torchvision
449
+
450
+
451
+ >>> class CocoDetection(torchvision.datasets.CocoDetection):
452
+ ... def __init__(self, img_folder, image_processor, ann_file):
453
+ ... super().__init__(img_folder, ann_file)
454
+ ... self.image_processor = image_processor
455
+
456
+ ... def __getitem__(self, idx):
457
+ ... # read in PIL image and target in COCO format
458
+ ... img, target = super(CocoDetection, self).__getitem__(idx)
459
+
460
+ ... # preprocess image and target: converting target to DETR format,
461
+ ... # resizing + normalization of both image and target)
462
+ ... image_id = self.ids[idx]
463
+ ... target = {"image_id": image_id, "annotations": target}
464
+ ... encoding = self.image_processor(images=img, annotations=target, return_tensors="pt")
465
+ ... pixel_values = encoding["pixel_values"].squeeze() # remove batch dimension
466
+ ... target = encoding["labels"][0] # remove batch dimension
467
+
468
+ ... return {"pixel_values": pixel_values, "labels": target}
469
+
470
+
471
+ >>> im_processor = AutoImageProcessor.from_pretrained("devonho/detr-resnet-50_finetuned_cppe5")
472
+
473
+ >>> path_output_cppe5, path_anno = save_cppe5_annotation_file_images(cppe5["test"])
474
+ >>> test_ds_coco_format = CocoDetection(path_output_cppe5, im_processor, path_anno)
475
+ ```
476
+
477
+ 마지막으로, 평가 지표를 가져와서 평가를 실행합니다.
478
+
479
+ ```py
480
+ >>> import evaluate
481
+ >>> from tqdm import tqdm
482
+
483
+ >>> model = AutoModelForObjectDetection.from_pretrained("devonho/detr-resnet-50_finetuned_cppe5")
484
+ >>> module = evaluate.load("ybelkada/cocoevaluate", coco=test_ds_coco_format.coco)
485
+ >>> val_dataloader = torch.utils.data.DataLoader(
486
+ ... test_ds_coco_format, batch_size=8, shuffle=False, num_workers=4, collate_fn=collate_fn
487
+ ... )
488
+
489
+ >>> with torch.no_grad():
490
+ ... for idx, batch in enumerate(tqdm(val_dataloader)):
491
+ ... pixel_values = batch["pixel_values"]
492
+ ... pixel_mask = batch["pixel_mask"]
493
+
494
+ ... labels = [
495
+ ... {k: v for k, v in t.items()} for t in batch["labels"]
496
+ ... ] # these are in DETR format, resized + normalized
497
+
498
+ ... # forward pass
499
+ ... outputs = model(pixel_values=pixel_values, pixel_mask=pixel_mask)
500
+
501
+ ... orig_target_sizes = torch.stack([target["orig_size"] for target in labels], dim=0)
502
+ ... results = im_processor.post_process(outputs, orig_target_sizes) # convert outputs of model to Pascal VOC format (xmin, ymin, xmax, ymax)
503
+
504
+ ... module.add(prediction=results, reference=labels)
505
+ ... del batch
506
+
507
+ >>> results = module.compute()
508
+ >>> print(results)
509
+ Accumulating evaluation results...
510
+ DONE (t=0.08s).
511
+ IoU metric: bbox
512
+ Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.352
513
+ Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.681
514
+ Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.292
515
+ Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.168
516
+ Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.208
517
+ Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.429
518
+ Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.274
519
+ Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.484
520
+ Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.501
521
+ Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.191
522
+ Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.323
523
+ Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.590
524
+ ```
525
+
526
+ 이러한 결과는 [`~transformers.TrainingArguments`]의 하이퍼파라미터를 조정하여 더욱 개선될 수 있습니다. 한번 시도해 보세요!
527
+
528
+ ## 추론하기 [[inference]]
529
+
530
+ DETR 모델을 미세 조정 및 평가하고, 허깅페이스 허브에 업로드 했으므로 추론에 사용할 수 있습니다.
531
+
532
+ 미세 조정된 모델을 추론에 사용하는 가장 간단한 방법은 [`pipeline`]에서 모델을 사용하는 것입니다.
533
+ 모델과 함께 객체 탐지를 위한 파이프라인을 인스턴스화하고, 이미지를 전달하세요:
534
+
535
+ ```py
536
+ >>> from transformers import pipeline
537
+ >>> import requests
538
+
539
+ >>> url = "https://i.imgur.com/2lnWoly.jpg"
540
+ >>> image = Image.open(requests.get(url, stream=True).raw)
541
+
542
+ >>> obj_detector = pipeline("object-detection", model="devonho/detr-resnet-50_finetuned_cppe5")
543
+ >>> obj_detector(image)
544
+ ```
545
+
546
+ 만약 원한다면 수동으로 `pipeline`의 결과를 재현할 수 있습니다:
547
+
548
+ ```py
549
+ >>> image_processor = AutoImageProcessor.from_pretrained("devonho/detr-resnet-50_finetuned_cppe5")
550
+ >>> model = AutoModelForObjectDetection.from_pretrained("devonho/detr-resnet-50_finetuned_cppe5")
551
+
552
+ >>> with torch.no_grad():
553
+ ... inputs = image_processor(images=image, return_tensors="pt")
554
+ ... outputs = model(**inputs)
555
+ ... target_sizes = torch.tensor([image.size[::-1]])
556
+ ... results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[0]
557
+
558
+ >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
559
+ ... box = [round(i, 2) for i in box.tolist()]
560
+ ... print(
561
+ ... f"Detected {model.config.id2label[label.item()]} with confidence "
562
+ ... f"{round(score.item(), 3)} at location {box}"
563
+ ... )
564
+ Detected Coverall with confidence 0.566 at location [1215.32, 147.38, 4401.81, 3227.08]
565
+ Detected Mask with confidence 0.584 at location [2449.06, 823.19, 3256.43, 1413.9]
566
+ ```
567
+
568
+ 결과를 시각화하겠습니다:
569
+ ```py
570
+ >>> draw = ImageDraw.Draw(image)
571
+
572
+ >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
573
+ ... box = [round(i, 2) for i in box.tolist()]
574
+ ... x, y, x2, y2 = tuple(box)
575
+ ... draw.rectangle((x, y, x2, y2), outline="red", width=1)
576
+ ... draw.text((x, y), model.config.id2label[label.item()], fill="white")
577
+
578
+ >>> image
579
+ ```
580
+
581
+ <div class="flex justify-center">
582
+ <img src="https://i.imgur.com/4QZnf9A.png" alt="Object detection result on a new image"/>
583
+ </div>
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/prompting.md ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2023 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+
18
+ # 대규모 언어 모델(LLM) 프롬프팅 가이드 [[llm-prompting-guide]]
19
+
20
+ [[open-in-colab]]
21
+
22
+ Falcon, LLaMA 등의 대규모 언어 모델은 사전 훈련된 트랜스포머 모델로, 초기에는 주어진 입력 텍스트에 대해 다음 토큰을 예측하도록 훈련됩니다. 이들은 보통 수십억 개의 매개변수를 가지고 있으며, 장기간에 걸쳐 수조 개의 토큰으로 훈련됩니다. 그 결과, 이 모델들은 매우 강력하고 다재다능해져서, 자연어 프롬프트로 모델에 지시하여 다양한 자연어 처리 작업을 즉시 수행할 수 있습니다.
23
+
24
+ 최적의 출력을 보장하기 위해 이러한 프롬프트를 설계하는 것을 흔히 "프롬프트 엔지니어링"이라고 합니다. 프롬프트 엔지니어링은 상당한 실험이 필요한 반복적인 과정입니다. 자연어는 프로그래밍 언어보다 훨씬 유연하고 표현력이 풍부하지만, 동시에 모호성을 초래할 수 있습니다. 또한, 자연어 프롬프트는 변화에 매우 민감합니다. 프롬프트의 사소한 수정만으로도 완전히 다른 출력이 나올 수 있습니다.
25
+
26
+ 모든 경우에 적용할 수 있는 정확한 프롬프트 생성 공식은 없지만, 연구자들은 더 일관되게 최적의 결과를 얻는 데 도움이 되는 여러 가지 모범 사례를 개발했습니다.
27
+
28
+ 이 가이드에서는 더 나은 대규모 언어 모델 프롬프트를 작성하고 다양한 자연어 처리 작업을 해결하는 데 도움이 되는 프롬프트 엔지니어링 모범 사례를 다룹니다:
29
+
30
+ - [프롬프팅의 기초](#basics-of-prompting)
31
+ - [대규모 언어 모델 프롬프팅의 모범 사례](#best-practices-of-llm-prompting)
32
+ - [고급 프롬프팅 기법: 퓨샷(Few-shot) 프롬프팅과 생각의 사슬(Chain-of-thought, CoT) 기법](#advanced-prompting-techniques)
33
+ - [프롬프팅 대신 미세 조정을 해야 하는 경우](#prompting-vs-fine-tuning)
34
+
35
+ <Tip>
36
+
37
+ 프롬프트 엔지니어링은 대규모 언어 모델 출력 최적화 과정의 일부일 뿐입니다. 또 다른 중요한 구성 요소는 최적의 텍스트 생성 전략을 선택하는 것입니다. 학습 가능한 매개변수를 수정하지 않고도 대규모 언어 모델이 텍스트를 생성하리 때 각각의 후속 토큰을 선택하는 방식을 사용자가 직접 정의할 수 있습니다. 텍스트 생성 매개변수를 조정함으로써 생성된 텍스트의 반복을 줄이고 더 일관되고 사람이 말하는 것 같은 텍스트를 만들 수 있습니다. 텍스트 생성 전략과 매개변수는 이 가이드의 범위를 벗어나지만, 다음 가이드에서 이러한 주제에 대해 자세히 알아볼 수 있습니다:
38
+
39
+ * [대규모 언어 모델을 이용한 생성](../llm_tutorial)
40
+ * [텍스트 생성 전략](../generation_strategies)
41
+
42
+ </Tip>
43
+
44
+ ## 프롬프팅의 기초 [[basics-of-prompting]]
45
+
46
+ ### 모델의 유형 [[types-of-models]]
47
+
48
+ 현대의 대부분의 대규모 언어 모델은 디코더만을 이용한 트랜스포머입니다. 예를 들어 [LLaMA](../model_doc/llama),
49
+ [Llama2](../model_doc/llama2), [Falcon](../model_doc/falcon), [GPT2](../model_doc/gpt2) 등이 있습니다. 그러나 [Flan-T5](../model_doc/flan-t5)와 [BART](../model_doc/bart)와 같은 인코더-디코더 기반의 트랜스포머 대규모 언어 모델을 접할 수도 있습니다.
50
+
51
+ 인코더-디코더 기반의 모델은 일반적으로 출력이 입력에 **크게** 의존하는 생성 작업에 사용됩니다. 예를 들어, 번역과 요약 작업에 사용됩니다. 디코더 전용 모델은 다른 모든 유형의 생성 작업에 사용됩니다.
52
+
53
+ 파이프라인을 사용하여 대규모 언어 모델으로 텍스트를 생성할 때, 어떤 유형의 대규모 언어 모델을 사용하고 있는지 아는 것이 중요합니다. 왜냐하면 이들은 서로 다른 파이프라인을 사용하기 때문입니다.
54
+
55
+ 디코더 전용 모델로 추론을 실행하려면 `text-generation` 파이프라인을 사용하세요:
56
+
57
+ ```python
58
+ >>> from transformers import pipeline
59
+ >>> import torch
60
+
61
+ >>> torch.manual_seed(0) # doctest: +IGNORE_RESULT
62
+
63
+ >>> generator = pipeline('text-generation', model = 'openai-community/gpt2')
64
+ >>> prompt = "Hello, I'm a language model"
65
+
66
+ >>> generator(prompt, max_length = 30)
67
+ [{'generated_text': "Hello, I'm a language model programmer so you can use some of my stuff. But you also need some sort of a C program to run."}]
68
+ ```
69
+
70
+ 인코더-디코더로 추론을 실행하려면 `text2text-generation` 파이프라인을 사용하세요:
71
+
72
+ ```python
73
+ >>> text2text_generator = pipeline("text2text-generation", model = 'google/flan-t5-base')
74
+ >>> prompt = "Translate from English to French: I'm very happy to see you"
75
+
76
+ >>> text2text_generator(prompt)
77
+ [{'generated_text': 'Je suis très heureuse de vous rencontrer.'}]
78
+ ```
79
+
80
+ ### 기본 모델 vs 지시/채팅 모델 [[base-vs-instructchat-models]]
81
+
82
+ 🤗 Hub에서 최근 사용 가능한 대부분의 대규모 언어 모델 체크포인트는 기본 버전과 지시(또는 채팅) 두 가지 버전이 제공됩니다. 예를 들어, [`tiiuae/falcon-7b`](https://huggingface.co/tiiuae/falcon-7b)와 [`tiiuae/falcon-7b-instruct`](https://huggingface.co/tiiuae/falcon-7b-instruct)가 있습니다.
83
+
84
+ 기본 모델은 초기 프롬프트가 주어졌을 때 텍스트를 완성하는 데 탁월하지만, 지시를 따라야 하거나 대화형 사용이 필요한 자연어 처리작업에는 이상적이지 않습니다. 이때 지시(채팅) 버전이 필요합니다. 이러한 체크포인트는 사전 훈련된 기본 버전을 지시사항과 대화 데이터로 추가 미세 조정한 결과입니다. 이 추가적인 미세 조정으로 인해 많은 자연어 처리 작업에 더 적합한 선택이 됩니다.
85
+
86
+ [`tiiuae/falcon-7b-instruct`](https://huggingface.co/tiiuae/falcon-7b-instruct)를 사용하여 일반적인 자연어 처리 작업을 해결하는 데 사용할 수 있는 몇 가지 간단한 프롬프트를 살펴보겠습니다.
87
+
88
+ ### 자연어 처리 작업 [[nlp-tasks]]
89
+
90
+ 먼저, 환경을 설정해 보겠습니다:
91
+
92
+ ```bash
93
+ pip install -q transformers accelerate
94
+ ```
95
+
96
+ 다음으로, 적절한 파이프라인("text-generation")을 사용하여 모델을 로드하겠습니다:
97
+
98
+ ```python
99
+ >>> from transformers import pipeline, AutoTokenizer
100
+ >>> import torch
101
+
102
+ >>> torch.manual_seed(0) # doctest: +IGNORE_RESULT
103
+ >>> model = "tiiuae/falcon-7b-instruct"
104
+
105
+ >>> tokenizer = AutoTokenizer.from_pretrained(model)
106
+ >>> pipe = pipeline(
107
+ ... "text-generation",
108
+ ... model=model,
109
+ ... tokenizer=tokenizer,
110
+ ... torch_dtype=torch.bfloat16,
111
+ ... device_map="auto",
112
+ ... )
113
+ ```
114
+
115
+ <Tip>
116
+
117
+ Falcon 모델은 bfloat16 데이터 타입을 사용하여 훈련되었으므로, 같은 타입을 사용하는 것을 권장합니다. 이를 위해서는 최신 버전의 CUDA가 필요하며, 최신 그래픽 카드에서 가장 잘 작동합니다.
118
+
119
+ </Tip>
120
+
121
+ 이제 파이프라인을 통해 모델을 로드했으니, 프롬프트를 사용하여 자연어 처리 작업을 해결하는 방법을 살펴보겠습니다.
122
+
123
+ #### 텍스트 분류 [[text-classification]]
124
+
125
+ 텍스트 분류의 가장 일반적인 형태 중 하나는 감정 분석입니다. 이는 텍스트 시퀀스에 "긍정적", "부정적" 또는 "중립적"과 같은 레이블을 할당합니다. 주어진 텍스트(영화 리뷰)를 분류하도록 모델에 지시하는 프롬프트를 작성해 보겠습니다. 먼저 지시사항을 제공한 다음, 분류할 텍스트를 지정하겠습니다. 여기서 주목할 점은 단순히 거기서 끝내지 않고, 응답의 시작 부분인 `"Sentiment: "`을 추가한다는 것입니다:
126
+
127
+ ```python
128
+ >>> torch.manual_seed(0)
129
+ >>> prompt = """Classify the text into neutral, negative or positive.
130
+ ... Text: This movie is definitely one of my favorite movies of its kind. The interaction between respectable and morally strong characters is an ode to chivalry and the honor code amongst thieves and policemen.
131
+ ... Sentiment:
132
+ ... """
133
+
134
+ >>> sequences = pipe(
135
+ ... prompt,
136
+ ... max_new_tokens=10,
137
+ ... )
138
+
139
+ >>> for seq in sequences:
140
+ ... print(f"Result: {seq['generated_text']}")
141
+ Result: Classify the text into neutral, negative or positive.
142
+ Text: This movie is definitely one of my favorite movies of its kind. The interaction between respectable and morally strong characters is an ode to chivalry and the honor code amongst thieves and policemen.
143
+ Sentiment:
144
+ Positive
145
+ ```
146
+
147
+ 결과적으로, 우리가 지시사항에서 제공한 목록에서 선택된 분류 레이블이 정확하게 포함되어 생성된 것을 확인할 수 있습니다!
148
+ <Tip>
149
+
150
+ 프롬프트 외에도 `max_new_tokens` 매개변수를 전달하는 것을 볼 수 있습니다. 이 매개변수는 모델이 생성할 토큰의 수를 제어하며, [텍스트 생성 전략](../generation_strategies) 가이드에서 배울 수 있는 여러 텍스트 생성 매개변수 중 하나입니다.
151
+
152
+ </Tip>
153
+
154
+ #### 개체명 인식 [[named-entity-recognition]]
155
+
156
+ 개체명 인식(Named Entity Recognition, NER)은 텍스트에서 인물, 장소, 조직과 같은 명명된 개체를 찾는 작업입니다. 프롬프트의 지시사항을 수정하여 대규모 언�� 모델이 이 작업을 수행하도록 해보겠습니다. 여기서는 `return_full_text = False`로 설정하여 출력에 프롬프트가 포함되지 않도록 하겠습니다:
157
+
158
+ ```python
159
+ >>> torch.manual_seed(1) # doctest: +IGNORE_RESULT
160
+ >>> prompt = """Return a list of named entities in the text.
161
+ ... Text: The Golden State Warriors are an American professional basketball team based in San Francisco.
162
+ ... Named entities:
163
+ ... """
164
+
165
+ >>> sequences = pipe(
166
+ ... prompt,
167
+ ... max_new_tokens=15,
168
+ ... return_full_text = False,
169
+ ... )
170
+
171
+ >>> for seq in sequences:
172
+ ... print(f"{seq['generated_text']}")
173
+ - Golden State Warriors
174
+ - San Francisco
175
+ ```
176
+
177
+ 보시다시피, 모델이 주어진 텍스트에서 두 개의 명명된 개체를 정확하게 식별했습니다.
178
+
179
+ #### 번역 [[translation]]
180
+
181
+ 대규모 언어 모델이 수행할 수 있는 또 다른 작업은 번역입니다. 이 작업을 위해 인코더-디코더 모델을 사용할 수 있지만, 여기서는 예시의 단순성을 위해 꽤 좋은 성능을 보이는 Falcon-7b-instruct를 계속 사용하겠습니다. 다시 한 번, 모델에게 영어에서 이탈리아어로 텍스트를 번역하도록 지시하는 기본적인 프롬프트를 작성하는 방법은 다음과 같습니다:
182
+
183
+ ```python
184
+ >>> torch.manual_seed(2) # doctest: +IGNORE_RESULT
185
+ >>> prompt = """Translate the English text to Italian.
186
+ ... Text: Sometimes, I've believed as many as six impossible things before breakfast.
187
+ ... Translation:
188
+ ... """
189
+
190
+ >>> sequences = pipe(
191
+ ... prompt,
192
+ ... max_new_tokens=20,
193
+ ... do_sample=True,
194
+ ... top_k=10,
195
+ ... return_full_text = False,
196
+ ... )
197
+
198
+ >>> for seq in sequences:
199
+ ... print(f"{seq['generated_text']}")
200
+ A volte, ho creduto a sei impossibili cose prima di colazione.
201
+ ```
202
+
203
+ 여기서는 모델이 출력을 생성할 때 조금 더 유연해질 수 있도록 `do_sample=True`와 `top_k=10`을 추가했습니다.
204
+
205
+ #### 텍스트 요약 [[text-summarization]]
206
+
207
+ 번역과 마찬가지로, 텍스트 요약은 출력이 입력에 크게 의존하는 또 다른 생성 작업이며, 인코더-디코더 기반 모델이 더 나은 선택일 수 있습니다. 그러나 디코더 기반의 모델도 이 작업에 사용될 수 있습니다. 이전에는 프롬프트의 맨 처음에 지시사항을 배치했습니다. 하지만 프롬프트의 맨 끝도 지시사항을 넣을 적절한 위치가 될 수 있습니다. 일반적으로 지시사항을 양 극단 중 하나에 배치하는 것이 더 좋습니다.
208
+
209
+ ```python
210
+ >>> torch.manual_seed(3) # doctest: +IGNORE_RESULT
211
+ >>> prompt = """Permaculture is a design process mimicking the diversity, functionality and resilience of natural ecosystems. The principles and practices are drawn from traditional ecological knowledge of indigenous cultures combined with modern scientific understanding and technological innovations. Permaculture design provides a framework helping individuals and communities develop innovative, creative and effective strategies for meeting basic needs while preparing for and mitigating the projected impacts of climate change.
212
+ ... Write a summary of the above text.
213
+ ... Summary:
214
+ ... """
215
+
216
+ >>> sequences = pipe(
217
+ ... prompt,
218
+ ... max_new_tokens=30,
219
+ ... do_sample=True,
220
+ ... top_k=10,
221
+ ... return_full_text = False,
222
+ ... )
223
+
224
+ >>> for seq in sequences:
225
+ ... print(f"{seq['generated_text']}")
226
+ Permaculture is an ecological design mimicking natural ecosystems to meet basic needs and prepare for climate change. It is based on traditional knowledge and scientific understanding.
227
+ ```
228
+
229
+ #### 질의 응답 [[question-answering]]
230
+
231
+ 질의 응답 작업을 위해 프롬프트를 다음과 같은 논리적 구성요소로 구조화할 수 있습니다. 지시사항, 맥락, 질문, 그리고 모델이 답변 생성을 시작하도록 유도하는 선도 단어나 구문(`"Answer:"`) 을 사용할 수 있습니다:
232
+
233
+ ```python
234
+ >>> torch.manual_seed(4) # doctest: +IGNORE_RESULT
235
+ >>> prompt = """Answer the question using the context below.
236
+ ... Context: Gazpacho is a cold soup and drink made of raw, blended vegetables. Most gazpacho includes stale bread, tomato, cucumbers, onion, bell peppers, garlic, olive oil, wine vinegar, water, and salt. Northern recipes often include cumin and/or pimentón (smoked sweet paprika). Traditionally, gazpacho was made by pounding the vegetables in a mortar with a pestle; this more laborious method is still sometimes used as it helps keep the gazpacho cool and avoids the foam and silky consistency of smoothie versions made in blenders or food processors.
237
+ ... Question: What modern tool is used to make gazpacho?
238
+ ... Answer:
239
+ ... """
240
+
241
+ >>> sequences = pipe(
242
+ ... prompt,
243
+ ... max_new_tokens=10,
244
+ ... do_sample=True,
245
+ ... top_k=10,
246
+ ... return_full_text = False,
247
+ ... )
248
+
249
+ >>> for seq in sequences:
250
+ ... print(f"Result: {seq['generated_text']}")
251
+ Result: Modern tools often used to make gazpacho include
252
+ ```
253
+
254
+ #### 추론 [[reasoning]]
255
+
256
+ 추론은 대규모 언어 모델(LLM)에게 가장 어려운 작업 중 하나이며, 좋은 결과를 얻기 위해서는 종종 [생각의 사슬(Chain-of-thought, CoT)](#chain-of-thought)과 같은 고급 프롬프팅 기법을 적용해야 합니다. 간단한 산술 작업에 대해 기본적인 프롬프트로 모델이 추론할 수 있는지 시도해 보겠습니다:
257
+
258
+ ```python
259
+ >>> torch.manual_seed(5) # doctest: +IGNORE_RESULT
260
+ >>> prompt = """There are 5 groups of students in the class. Each group has 4 students. How many students are there in the class?"""
261
+
262
+ >>> sequences = pipe(
263
+ ... prompt,
264
+ ... max_new_tokens=30,
265
+ ... do_sample=True,
266
+ ... top_k=10,
267
+ ... return_full_text = False,
268
+ ... )
269
+
270
+ >>> for seq in sequences:
271
+ ... print(f"Result: {seq['generated_text']}")
272
+ Result:
273
+ There are a total of 5 groups, so there are 5 x 4=20 students in the class.
274
+ ```
275
+
276
+ 정확한 답변이 생성되었습니다! 복잡성을 조금 높여보고 기본적인 프롬프트로도 여전히 해결할 수 있는지 확인해 보겠습니다:
277
+
278
+ ```python
279
+ >>> torch.manual_seed(6)
280
+ >>> prompt = """I baked 15 muffins. I ate 2 muffins and gave 5 muffins to a neighbor. My partner then bought 6 more muffins and ate 2. How many muffins do we now have?"""
281
+
282
+ >>> sequences = pipe(
283
+ ... prompt,
284
+ ... max_new_tokens=10,
285
+ ... do_sample=True,
286
+ ... top_k=10,
287
+ ... return_full_text = False,
288
+ ... )
289
+
290
+ >>> for seq in sequences:
291
+ ... print(f"Result: {seq['generated_text']}")
292
+ Result:
293
+ The total number of muffins now is 21
294
+ ```
295
+
296
+ 정답은 12여야 하는데 21이라는 잘못된 답변이 나왔습니다. 이 경우, 프롬프트가 너무 기본적이거나 모델의 크기가 작아서 생긴 문제일 수 있습니다. 우리는 Falcon의 가장 작은 버전을 선택했습니다. 추론은 큰 모델에게도 어려운 작업이지만, 더 큰 모델들이 더 나은 성능을 보일 가능성이 높습니다.
297
+
298
+ ## 대규모 언어 모델 프롬프트 작성의 모범 사례 [[best-practices-of-llm-prompting]]
299
+
300
+ 이 섹션에서는 프롬프트 결과를 향상시킬 수 있는 모범 사례 목록을 작성했습니다:
301
+
302
+ * 작업할 모델을 선택할 때 최신 및 가장 강력한 모델이 더 나은 성능을 발휘할 가능성이 높습니다.
303
+ * 간단하고 짧은 프롬프트로 시작하여 점진적으로 개선해 나가세요.
304
+ * 프롬프트의 시작 부분이나 맨 끝에 지시사항을 배치하세요. 대규모 컨텍스트를 다룰 때, 모델들은 어텐션 복잡도가 2차적으로 증가하는 것을 방지하기 위해 다양한 최적화를 적용합니다. 이렇게 함으로써 모델이 프롬프트의 중간보다 시작이나 끝 부분에 더 주의를 기울일 수 있습니다.
305
+ * 지시사항을 적용할 텍스트와 명확하게 분리해보세요. (이에 대해서는 다음 섹션에서 더 자세히 다룹니다.)
306
+ * 작업과 원하는 결과에 대해 구체적이고 풍부한 설명을 제공하세요. 형식, 길이, 스타일, 언어 등을 명확하게 작성해야 합니다.
307
+ * 모호한 설명과 지시사항을 피하세요.
308
+ * "하지 말라"는 지시보다는 "무엇을 해야 하는지"를 말하는 지시를 사용하는 것이 좋습니다.
309
+ * 첫 번째 단어를 쓰거나 첫 번째 문장을 시작하여 출력을 올바른 방향으로 "유도"하세요.
310
+ * [퓨샷(Few-shot) 프롬프팅](#few-shot-prompting) 및 [생각의 사슬(Chain-of-thought, CoT)](#chain-of-thought) 같은 고급 기술을 사용해보세요.
311
+ * 프롬프트의 견고성을 평가하기 위해 다른 모델로도 테스트하세요.
312
+ * 프롬프트의 버전을 관리하고 성능을 추적하세요.
313
+
314
+ ## 고급 프롬프트 기법 [[advanced-prompting-techniques]]
315
+
316
+ ### 퓨샷(Few-shot) 프롬프팅 [[few-shot-prompting]]
317
+
318
+ 위 섹션의 기본 프롬프트들은 "제로샷(Zero-shot)" 프롬프트의 예시입니다. 이는 모델에 지시사항과 맥락은 주어졌지만, 해결책이 포함된 예시는 제공되지 않았다는 의미입니다. 지시 데이터셋으로 미세 조정된 대규모 언어 모델은 일반적으로 이러한 "제로샷" 작업에서 좋은 성능을 보입니다. 하지만 여러분의 작업이 더 복잡하거나 미묘한 차이가 있을 수 있고, 아마도 지시사항만으로는 모델이 포착하지 못하는 출력에 대한 요구사항이 있을 수 있습니다. 이런 경우에는 퓨샷(Few-shot) 프롬프팅이라는 기법을 시도해 볼 수 있습니다.
319
+
320
+ 퓨샷 프롬프팅에서는 프롬프트에 예시를 제공하여 모델에 더 많은 맥락을 주고 성능을 향상시킵니다. 이 예시들은 모델이 예시의 패턴을 따라 출력을 생성하도록 조건화합니다.
321
+
322
+ 다음은 예시입니다:
323
+
324
+ ```python
325
+ >>> torch.manual_seed(0) # doctest: +IGNORE_RESULT
326
+ >>> prompt = """Text: The first human went into space and orbited the Earth on April 12, 1961.
327
+ ... Date: 04/12/1961
328
+ ... Text: The first-ever televised presidential debate in the United States took place on September 28, 1960, between presidential candidates John F. Kennedy and Richard Nixon.
329
+ ... Date:"""
330
+
331
+ >>> sequences = pipe(
332
+ ... prompt,
333
+ ... max_new_tokens=8,
334
+ ... do_sample=True,
335
+ ... top_k=10,
336
+ ... )
337
+
338
+ >>> for seq in sequences:
339
+ ... print(f"Result: {seq['generated_text']}")
340
+ Result: Text: The first human went into space and orbited the Earth on April 12, 1961.
341
+ Date: 04/12/1961
342
+ Text: The first-ever televised presidential debate in the United States took place on September 28, 1960, between presidential candidates John F. Kennedy and Richard Nixon.
343
+ Date: 09/28/1960
344
+ ```
345
+
346
+ 위의 코드 스니펫에서는 모델에 원하는 출력을 보여주기 위해 단일 예시를 사용했으므로, 이를 "원샷(One-shot)" 프롬프팅이라고 부를 수 있습니다. 그러나 작업의 복잡성에 따라 하나 이상의 예시를 사용해야 할 수도 있습니다.
347
+
348
+ 퓨샷 프롬프팅 기법의 한계:
349
+ - 대규모 언어 모델이 예시의 패턴을 파악할 수 있지만, 이 기법은 복잡한 추론 작업에는 잘 작동하지 않습니다.
350
+ - 퓨샷 프롬프팅을 적용하면 프롬프트의 길이가 길어집니다. 토큰 수가 많은 프롬프트는 계산량과 지연 시간을 증가시킬 수 있으며 프롬프트 길이에도 제한이 있습니다.
351
+ - 때로는 여러 예시가 주어질 때, 모델은 의도하지 않은 패턴을 학습할 수 있습니다. 예를 들어, 세 번째 영화 리뷰가 항상 부정적이라고 학습할 수 있습니다.
352
+
353
+ ### 생각의 사슬(Chain-of-thought, CoT) [[chain-of-thought]]
354
+
355
+ 생각의 사슬(Chain-of-thought, CoT) 프롬프팅은 모델이 중간 추론 단계를 생성하도록 유도하는 기법으로, 복잡한 추론 작업의 결과를 개선합니다.
356
+
357
+ 모델이 추론 단계를 생성하도록 유도하는 두 가지 방법이 있습니다:
358
+ - 질문에 대한 상세한 답변을 예시로 제시하는 퓨샷 프롬프팅을 통해 모델에게 문제를 어떻게 해결해 나가는지 보여줍니다.
359
+ - "단계별로 생각해 봅시다" 또는 "깊게 숨을 쉬고 문제를 단계별로 해결해 봅시다"와 같은 문구를 추가하여 모델에게 추론하도록 지시합니다.
360
+
361
+ [reasoning section](#reasoning)의 머핀 예시에 생각의 사슬(Chain-of-thought, CoT) 기법을 적용하고 [HuggingChat](https://huggingface.co/chat/)에서 사용할 수 있는 (`tiiuae/falcon-180B-chat`)과 같은 더 큰 모델을 사용하면, 추론 결과가 크게 개선됩니다:
362
+
363
+ ```text
364
+ 단계별로 살펴봅시다:
365
+ 1. 처음에 15개의 머핀이 있습니다.
366
+ 2. 2개의 머핀을 먹으면 13개의 머핀이 남습니다.
367
+ 3. 이웃에게 5개의 머핀을 주면 8개의 머핀이 남습니다.
368
+ 4. 파트너가 6개의 머핀을 더 사오면 총 머핀 수는 14개가 됩니다.
369
+ 5. 파트너가 2개의 머핀을 먹으면 12개의 머핀이 남습니다.
370
+ 따라서, 현재 12개의 머핀이 있습니다.
371
+ ```
372
+
373
+ ## 프롬프팅 vs 미세 조정 [[prompting-vs-fine-tuning]]
374
+
375
+ 프롬프트를 최적화하여 훌륭한 결과를 얻을 수 있지만, 여전히 모델을 미세 조정하는 것이 더 좋을지 고민할 수 있습니다. 다음은 더 작은 모델을 미세 조정하는 것이 선호되는 시나리오입니다:
376
+
377
+ - 도메인이 대규모 언어 모델이 사전 훈련된 것과 크게 다르고 광범위한 프롬프트 최적화로도 충분한 결과를 얻지 못한 경우.
378
+ - 저자원 언어에서 모델이 잘 작동해야 하는 경우.
379
+ - 엄격한 규제 하에 있는 민감한 데이터로 모델을 훈련해야 하는 경우.
380
+ - 비용, 개인정보 보호, 인프라 또는 기타 제한으로 인해 작은 모델을 사용해야 하는 경우.
381
+
382
+ 위의 모든 예시에서, 모델을 미세 조정하기 위해 충분히 큰 도메인별 데이터셋을 이미 가지고 있거나 합리적인 비용으로 쉽게 얻을 수 있는지 확인해야 합니다. 또한 모델을 미세 조정할 충분한 시간과 자원이 필요합니다.
383
+
384
+ 만약 위의 예시들이 여러분의 경우에 해당하지 않는다면, 프롬프트를 최적화하는 것이 더 유익할 수 있습니다.
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/question_answering.md ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # 질의 응답(Question Answering)[[question-answering]]
18
+
19
+ [[open-in-colab]]
20
+
21
+ <Youtube id="ajPx5LwJD-I"/>
22
+
23
+ 질의 응답 태스크는 주어진 질문에 대한 답변을 제공합니다. Alexa, Siri 또는 Google과 같은 가상 비서에게 날씨가 어떤지 물어본 적이 있다면 질의 응답 모델을 사용해본 적이 있을 것입니다. 질의 응답 태스크에는 일반적으로 두 가지 유형이 있습니다.
24
+
25
+ - 추출적(Extractive) 질의 응답: 주어진 문맥에서 답변을 추출합니다.
26
+ - 생성적(Abstractive) 질의 응답: 문맥에서 질문에 올바르게 답하는 답변을 생성합니다.
27
+
28
+ 이 가이드는 다음과 같은 방법들을 보여줍니다.
29
+
30
+ 1. 추출적 질의 응답을 하기 위해 [SQuAD](https://huggingface.co/datasets/squad) 데이터 세트에서 [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased) 미세 조정하기
31
+ 2. 추론에 미세 조정된 모델 사용하기
32
+
33
+ <Tip>
34
+
35
+ 이 작업과 호환되는 모든 아키텍처와 체크포인트를 보려면 [작업 페이지](https://huggingface.co/tasks/question-answering)를 확인하는 것이 좋습니다.
36
+
37
+ </Tip>
38
+
39
+ 시작하기 전에, 필요한 라이브러리가 모두 설치되어 있는지 확인하세요:
40
+
41
+ ```bash
42
+ pip install transformers datasets evaluate
43
+ ```
44
+
45
+ 여러분의 모델을 업로드하고 커뮤니티에 공유할 수 있도록 Hugging Face 계정에 로그인하는 것이 좋습니다. 메시지가 표시되면 토큰을 입력해서 로그인합니다:
46
+
47
+ ```py
48
+ >>> from huggingface_hub import notebook_login
49
+
50
+ >>> notebook_login()
51
+ ```
52
+
53
+ ## SQuAD 데이터 세트 가져오기[[load-squad-dataset]]
54
+
55
+ 먼저 🤗 Datasets 라이브러리에서 SQuAD 데이터 세트의 일부를 가져옵니다. 이렇게 하면 전체 데이터 세트로 훈련하며 더 많은 시간을 할애하기 전에 모든 것이 잘 작동하는지 실험하고 확인할 수 있습니다.
56
+
57
+ ```py
58
+ >>> from datasets import load_dataset
59
+
60
+ >>> squad = load_dataset("squad", split="train[:5000]")
61
+ ```
62
+
63
+ 데이터 세트의 분할된 `train`을 [`~datasets.Dataset.train_test_split`] 메소드를 사용해 훈련 데이터 세트와 테스트 데이터 세트로 나누어줍니다:
64
+
65
+ ```py
66
+ >>> squad = squad.train_test_split(test_size=0.2)
67
+ ```
68
+
69
+ 그리고나서 예시로 데이터를 하나 살펴봅니다:
70
+
71
+ ```py
72
+ >>> squad["train"][0]
73
+ {'answers': {'answer_start': [515], 'text': ['Saint Bernadette Soubirous']},
74
+ 'context': 'Architecturally, the school has a Catholic character. Atop the Main Building\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend "Venite Ad Me Omnes". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.',
75
+ 'id': '5733be284776f41900661182',
76
+ 'question': 'To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?',
77
+ 'title': 'University_of_Notre_Dame'
78
+ }
79
+ ```
80
+
81
+ 이 중에서 몇 가지 중요한 항목이 있습니다:
82
+
83
+ - `answers`: 답안 토큰의 시작 위치와 답안 텍스트
84
+ - `context`: 모델이 답을 추출하는데 필요한 배경 지식
85
+ - `question`: 모델이 답해야 하는 질문
86
+
87
+ ## 전처리[[preprocess]]
88
+
89
+ <Youtube id="qgaM0weJHpA"/>
90
+
91
+ 다음 단계에서는 `question` 및 `context` 항목을 처리하기 위해 DistilBERT 토크나이저를 가져옵니다:
92
+
93
+ ```py
94
+ >>> from transformers import AutoTokenizer
95
+
96
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
97
+ ```
98
+
99
+ 질의 응답 태스크와 관련해서 특히 유의해야할 몇 가지 전처리 단계가 있습니다:
100
+
101
+ 1. 데이터 세트의 일부 예제에는 모델의 최대 입력 길이를 초과하는 매우 긴 `context`가 있을 수 있습니다. 긴 시퀀스를 다루기 위해서는, `truncation="only_second"`로 설정해 `context`만 잘���내면 됩니다.
102
+ 2. 그 다음, `return_offset_mapping=True`로 설정해 답변의 시작과 종료 위치를 원래의 `context`에 매핑합니다.
103
+ 3. 매핑을 완료하면, 이제 답변에서 시작 토큰과 종료 토큰을 찾을 수 있습니다. 오프셋의 어느 부분이 `question`과 `context`에 해당하는지 찾을 수 있도록 [`~tokenizers.Encoding.sequence_ids`] 메소드를 사용하세요.
104
+
105
+ 다음은 `answer`의 시작 토큰과 종료 토큰을 잘라내서 `context`에 매핑하는 함수를 만드는 방법입니다:
106
+
107
+ ```py
108
+ >>> def preprocess_function(examples):
109
+ ... questions = [q.strip() for q in examples["question"]]
110
+ ... inputs = tokenizer(
111
+ ... questions,
112
+ ... examples["context"],
113
+ ... max_length=384,
114
+ ... truncation="only_second",
115
+ ... return_offsets_mapping=True,
116
+ ... padding="max_length",
117
+ ... )
118
+
119
+ ... offset_mapping = inputs.pop("offset_mapping")
120
+ ... answers = examples["answers"]
121
+ ... start_positions = []
122
+ ... end_positions = []
123
+
124
+ ... for i, offset in enumerate(offset_mapping):
125
+ ... answer = answers[i]
126
+ ... start_char = answer["answer_start"][0]
127
+ ... end_char = answer["answer_start"][0] + len(answer["text"][0])
128
+ ... sequence_ids = inputs.sequence_ids(i)
129
+
130
+ ... # Find the start and end of the context
131
+ ... idx = 0
132
+ ... while sequence_ids[idx] != 1:
133
+ ... idx += 1
134
+ ... context_start = idx
135
+ ... while sequence_ids[idx] == 1:
136
+ ... idx += 1
137
+ ... context_end = idx - 1
138
+
139
+ ... # If the answer is not fully inside the context, label it (0, 0)
140
+ ... if offset[context_start][0] > end_char or offset[context_end][1] < start_char:
141
+ ... start_positions.append(0)
142
+ ... end_positions.append(0)
143
+ ... else:
144
+ ... # Otherwise it's the start and end token positions
145
+ ... idx = context_start
146
+ ... while idx <= context_end and offset[idx][0] <= start_char:
147
+ ... idx += 1
148
+ ... start_positions.append(idx - 1)
149
+
150
+ ... idx = context_end
151
+ ... while idx >= context_start and offset[idx][1] >= end_char:
152
+ ... idx -= 1
153
+ ... end_positions.append(idx + 1)
154
+
155
+ ... inputs["start_positions"] = start_positions
156
+ ... inputs["end_positions"] = end_positions
157
+ ... return inputs
158
+ ```
159
+
160
+ 모든 데이터 세트에 전처리를 적용하려면, 🤗 Datasets [`~datasets.Dataset.map`] 함수를 사용하세요. `batched=True`로 설정해 데이터 세트의 여러 요소들을 한 번에 처리하면 `map` 함수의 속도를 빠르게 할 수 있습니다. 필요하지 않은 열은 모두 제거합니다:
161
+
162
+ ```py
163
+ >>> tokenized_squad = squad.map(preprocess_function, batched=True, remove_columns=squad["train"].column_names)
164
+ ```
165
+
166
+ 이제 [`DefaultDataCollator`]를 이용해 예시 배치를 생성합니다. 🤗 Transformers의 다른 데이터 콜레이터(data collator)와 달리, [`DefaultDataCollator`]는 패딩과 같은 추가 전처리를 적용하지 않습니다:
167
+
168
+ <frameworkcontent>
169
+ <pt>
170
+ ```py
171
+ >>> from transformers import DefaultDataCollator
172
+
173
+ >>> data_collator = DefaultDataCollator()
174
+ ```
175
+ </pt>
176
+ <tf>
177
+ ```py
178
+ >>> from transformers import DefaultDataCollator
179
+
180
+ >>> data_collator = DefaultDataCollator(return_tensors="tf")
181
+ ```
182
+ </tf>
183
+ </frameworkcontent>
184
+
185
+ ## 훈련[[train]]
186
+
187
+ <frameworkcontent>
188
+ <pt>
189
+ <Tip>
190
+
191
+ [`Trainer`]를 이용해 모델을 미세 조정하는 것에 익숙하지 않다면, [여기](../training#train-with-pytorch-trainer)에서 기초 튜토리얼을 살펴보세요!
192
+
193
+ </Tip>
194
+
195
+ 이제 모델 훈련을 시작할 준비가 되었습니다! [`AutoModelForQuestionAnswering`]으로 DistilBERT를 가져옵니다:
196
+
197
+ ```py
198
+ >>> from transformers import AutoModelForQuestionAnswering, TrainingArguments, Trainer
199
+
200
+ >>> model = AutoModelForQuestionAnswering.from_pretrained("distilbert/distilbert-base-uncased")
201
+ ```
202
+
203
+ 이제 세 단계만 남았습니다:
204
+
205
+ 1. [`TrainingArguments`]에서 훈련 하이퍼파라미터를 정합니다. 꼭 필요한 매개변수는 모델을 저장할 위치를 지정하는 `output_dir` 입니다. `push_to_hub=True`로 설정해서 이 모델을 Hub로 푸시합니다 (모델을 업로드하려면 Hugging Face에 로그인해야 합니다).
206
+ 2. 모델, 데이터 세트, 토크나이저, 데이터 콜레이터와 함께 [`Trainer`]에 훈련 인수들을 전달합니다.
207
+ 3. [`~Trainer.train`]을 호출해서 모델을 미세 조정합니다.
208
+
209
+ ```py
210
+ >>> training_args = TrainingArguments(
211
+ ... output_dir="my_awesome_qa_model",
212
+ ... eval_strategy="epoch",
213
+ ... learning_rate=2e-5,
214
+ ... per_device_train_batch_size=16,
215
+ ... per_device_eval_batch_size=16,
216
+ ... num_train_epochs=3,
217
+ ... weight_decay=0.01,
218
+ ... push_to_hub=True,
219
+ ... )
220
+
221
+ >>> trainer = Trainer(
222
+ ... model=model,
223
+ ... args=training_args,
224
+ ... train_dataset=tokenized_squad["train"],
225
+ ... eval_dataset=tokenized_squad["test"],
226
+ ... processing_class=tokenizer,
227
+ ... data_collator=data_collator,
228
+ ... )
229
+
230
+ >>> trainer.train()
231
+ ```
232
+
233
+ 훈련이 완료되면, [`~transformers.Trainer.push_to_hub`] 매소드를 사용해 모델을 Hub에 공유해서 모든 사람들이 사용할 수 있게 공유해주세요:
234
+
235
+ ```py
236
+ >>> trainer.push_to_hub()
237
+ ```
238
+ </pt>
239
+ <tf>
240
+ <Tip>
241
+
242
+ Keras로 모델을 미세 조정하는 것에 익숙하지 않다면, [여기](../training#train-a-tensorflow-model-with-keras)에서 기초 튜토리얼을 살펴보세요!
243
+
244
+ </Tip>
245
+ TensorFlow를 이용한 모델을 미세 조정하려면 옵티마이저 함수, 학습률 스케쥴 및 몇 가지 훈련 하이퍼파라미터를 설정하는 것부터 시작해야합니다:
246
+
247
+ ```py
248
+ >>> from transformers import create_optimizer
249
+
250
+ >>> batch_size = 16
251
+ >>> num_epochs = 2
252
+ >>> total_train_steps = (len(tokenized_squad["train"]) // batch_size) * num_epochs
253
+ >>> optimizer, schedule = create_optimizer(
254
+ ... init_lr=2e-5,
255
+ ... num_warmup_steps=0,
256
+ ... num_train_steps=total_train_steps,
257
+ ... )
258
+ ```
259
+
260
+ 그 다음 [`TFAutoModelForQuestionAnswering`]으로 DistilBERT를 가져옵니다:
261
+
262
+ ```py
263
+ >>> from transformers import TFAutoModelForQuestionAnswering
264
+
265
+ >>> model = TFAutoModelForQuestionAnswering("distilbert/distilbert-base-uncased")
266
+ ```
267
+
268
+ [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]을 사용해서 데이터 세트를 `tf.data.Dataset` 형식으로 변환합니다:
269
+
270
+ ```py
271
+ >>> tf_train_set = model.prepare_tf_dataset(
272
+ ... tokenized_squad["train"],
273
+ ... shuffle=True,
274
+ ... batch_size=16,
275
+ ... collate_fn=data_collator,
276
+ ... )
277
+
278
+ >>> tf_validation_set = model.prepare_tf_dataset(
279
+ ... tokenized_squad["test"],
280
+ ... shuffle=False,
281
+ ... batch_size=16,
282
+ ... collate_fn=data_collator,
283
+ ... )
284
+ ```
285
+
286
+ [`compile`](https://keras.io/api/models/model_training_apis/#compile-method)로 훈련할 모델을 설정합니다:
287
+
288
+ ```py
289
+ >>> import tensorflow as tf
290
+
291
+ >>> model.compile(optimizer=optimizer)
292
+ ```
293
+
294
+ 마지막으로 모델을 Hub로 푸시할 방법을 설정합니다. [`~transformers.PushToHubCallback`]에서 모델과 토크나이저를 푸시할 경로를 설정합니다:
295
+
296
+ ```py
297
+ >>> from transformers.keras_callbacks import PushToHubCallback
298
+
299
+ >>> callback = PushToHubCallback(
300
+ ... output_dir="my_awesome_qa_model",
301
+ ... tokenizer=tokenizer,
302
+ ... )
303
+ ```
304
+
305
+ 드디어 모델 훈련을 시작할 준비가 되었습니다! 훈련 데이터 세트와 평가 데이터 세트, 에폭 수, 콜백을 설정한 후 [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)을 이용해 모델을 미세 조정합니다:
306
+
307
+ ```py
308
+ >>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3, callbacks=[callback])
309
+ ```
310
+ 훈련이 완료되면 모델이 자동으로 Hub에 업로드되어 누구나 사용할 수 있습니다!
311
+ </tf>
312
+ </frameworkcontent>
313
+
314
+ <Tip>
315
+
316
+ 질의 응답을 위해 모델을 미세 조정하는 방법에 대한 더 자세한 예시는 [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering.ipynb) 또는 [TensorFlow notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering-tf.ipynb)을 참조하세요.
317
+
318
+ </Tip>
319
+
320
+ ## 평가[[evaluate]]
321
+
322
+ 질의 응답을 평가하려면 상당한 양의 후처리가 필요합니다. 시간이 너무 많이 걸리지 않도록 이 가이드에서는 평가 단계를 생략합니다. [`Trainer`]는 훈련 과정에서 평가 손실(evaluation loss)을 계속 계산하기 때문에 모델의 성능을 대략적으로 알 수 있습니다.
323
+
324
+ 시간에 여유가 있고 질의 응답 모델을 평가하는 방법에 관심이 있다면 🤗 Hugging Face Course의 [Question answering](https://huggingface.co/course/chapter7/7?fw=pt#postprocessing) 챕터를 살펴보세요!
325
+
326
+ ## 추론[[inference]]
327
+
328
+ 이제 모델을 미세 조정했으니 추론에 사용할 수 있습니다!
329
+
330
+ 질문과 모델이 예측하기 원하는 문맥(context)를 생각해보세요:
331
+
332
+ ```py
333
+ >>> question = "How many programming languages does BLOOM support?"
334
+ >>> context = "BLOOM has 176 billion parameters and can generate text in 46 languages natural languages and 13 programming languages."
335
+ ```
336
+
337
+ 추론을 위해 미세 조정한 모델을 테스트하는 가장 쉬운 방법은 [`pipeline`]을 사용하는 것 입니다. 모델을 사용해 질의 응답을 하기 위해서 `pipeline`을 인스턴스화하고 텍스트를 입력합니다:
338
+
339
+ ```py
340
+ >>> from transformers import pipeline
341
+
342
+ >>> question_answerer = pipeline("question-answering", model="my_awesome_qa_model")
343
+ >>> question_answerer(question=question, context=context)
344
+ {'score': 0.2058267742395401,
345
+ 'start': 10,
346
+ 'end': 95,
347
+ 'answer': '176 billion parameters and can generate text in 46 languages natural languages and 13'}
348
+ ```
349
+
350
+ 원한다면 `pipeline`의 결과를 직접 복제할 수도 있습니다:
351
+
352
+ <frameworkcontent>
353
+ <pt>
354
+ 텍스트를 토큰화해서 PyTorch 텐서를 반환��니다:
355
+
356
+ ```py
357
+ >>> from transformers import AutoTokenizer
358
+
359
+ >>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_qa_model")
360
+ >>> inputs = tokenizer(question, context, return_tensors="pt")
361
+ ```
362
+
363
+ 모델에 입력을 전달하고 `logits`을 반환합니다:
364
+
365
+ ```py
366
+ >>> from transformers import AutoModelForQuestionAnswering
367
+
368
+ >>> model = AutoModelForQuestionAnswering.from_pretrained("my_awesome_qa_model")
369
+ >>> with torch.no_grad():
370
+ ... outputs = model(**inputs)
371
+ ```
372
+
373
+ 모델의 출력에서 시작 및 종료 위치가 어딘지 가장 높은 확률을 얻습니다:
374
+
375
+ ```py
376
+ >>> answer_start_index = outputs.start_logits.argmax()
377
+ >>> answer_end_index = outputs.end_logits.argmax()
378
+ ```
379
+
380
+ 예측된 토큰을 해독해서 답을 얻습니다:
381
+
382
+ ```py
383
+ >>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
384
+ >>> tokenizer.decode(predict_answer_tokens)
385
+ '176 billion parameters and can generate text in 46 languages natural languages and 13'
386
+ ```
387
+ </pt>
388
+ <tf>
389
+ 텍스트를 토큰화해서 TensorFlow 텐서를 반환합니다:
390
+
391
+ ```py
392
+ >>> from transformers import AutoTokenizer
393
+
394
+ >>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_qa_model")
395
+ >>> inputs = tokenizer(question, text, return_tensors="tf")
396
+ ```
397
+
398
+ 모델에 입력을 전달하고 `logits`을 반환합니다:
399
+
400
+ ```py
401
+ >>> from transformers import TFAutoModelForQuestionAnswering
402
+
403
+ >>> model = TFAutoModelForQuestionAnswering.from_pretrained("my_awesome_qa_model")
404
+ >>> outputs = model(**inputs)
405
+ ```
406
+
407
+ 모델의 출력에서 시작 및 종료 위치가 어딘지 가장 높은 확률을 얻습니다:
408
+
409
+ ```py
410
+ >>> answer_start_index = int(tf.math.argmax(outputs.start_logits, axis=-1)[0])
411
+ >>> answer_end_index = int(tf.math.argmax(outputs.end_logits, axis=-1)[0])
412
+ ```
413
+
414
+ 예측된 토큰을 해독해서 답을 얻습니다:
415
+
416
+ ```py
417
+ >>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
418
+ >>> tokenizer.decode(predict_answer_tokens)
419
+ '176 billion parameters and can generate text in 46 languages natural languages and 13'
420
+ ```
421
+ </tf>
422
+ </frameworkcontent>
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/semantic_segmentation.md ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # 의미적 분할(Semantic segmentation)[[semantic-segmentation]]
18
+
19
+ [[open-in-colab]]
20
+
21
+ <Youtube id="dKE8SIt9C-w"/>
22
+
23
+ 의미적 분할(semantic segmentation)은 이미지의 각 픽셀에 레이블 또는 클래스를 할당합니다. 분할(segmentation)에는 여러 종류가 있으며, 의미적 분할의 경우 동일한 물체의 고유 인스턴스를 구분하지 않습니다. 두 물체 모두 동일한 레이블이 지정됩니다(예시로, "car-1" 과 "car-2" 대신 "car"로 지정합니다).
24
+ 실생활에서 흔히 볼 수 있는 의미적 분할의 적용 사례로는 보행자와 중요한 교통 정보를 식별하는 자율 주행 자동차 학습, 의료 이미지의 세포와 이상 징후 식별, 그리고 위성 이미지의 환경 변화 모니터링등이 있습니다.
25
+
26
+ 이번 가이드에서 배울 내용은 다음과 같습니다:
27
+
28
+ 1. [SceneParse150](https://huggingface.co/datasets/scene_parse_150) 데이터 세트를 이용해 [SegFormer](https://huggingface.co/docs/transformers/main/en/model_doc/segformer#segformer) 미세 조정하기.
29
+ 2. 미세 조정된 모델을 추론에 사용하기.
30
+
31
+ <Tip>
32
+
33
+ 이 작업과 호환되는 모든 아키텍처와 체크포인트를 보려면 [작업 페이지](https://huggingface.co/tasks/image-segmentation)를 확인하는 것이 좋습니다.
34
+
35
+ </Tip>
36
+
37
+ 시작하기 전에 필요한 모든 라이브러리가 설치되었는지 확인하세요:
38
+
39
+ ```bash
40
+ pip install -q datasets transformers evaluate
41
+ ```
42
+ 커뮤니티에 모델을 업로드하고 공유할 수 있도록 Hugging Face 계정에 로그인하는 것을 권장합니다. 프롬프트가 나타나면 토큰을 입력하여 로그인하세요:
43
+
44
+ ```py
45
+ >>> from huggingface_hub import notebook_login
46
+
47
+ >>> notebook_login()
48
+ ```
49
+
50
+ ## SceneParse150 데이터 세트 불러오기[[load-sceneparse150-dataset]]
51
+
52
+ 🤗 Datasets 라이브러리에서 SceneParse150 데이터 세트의 더 작은 부분 집합을 가져오는 것으로 시작합니다. 이렇게 하면 데이터 세트 전체에 대한 훈련에 많은 시간을 할애하기 전에 실험을 통해 모든 것이 제대로 작동하는지 확인할 수 있습니다.
53
+
54
+ ```py
55
+ >>> from datasets import load_dataset
56
+
57
+ >>> ds = load_dataset("scene_parse_150", split="train[:50]")
58
+ ```
59
+
60
+ 데이터 세트의 `train`을 [`~datasets.Dataset.train_test_split`] 메소드를 사용하여 훈련 및 테스트 세트로 분할하세요:
61
+
62
+ ```py
63
+ >>> ds = ds.train_test_split(test_size=0.2)
64
+ >>> train_ds = ds["train"]
65
+ >>> test_ds = ds["test"]
66
+ ```
67
+
68
+ 그리고 예시를 살펴보세요:
69
+
70
+ ```py
71
+ >>> train_ds[0]
72
+ {'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=512x683 at 0x7F9B0C201F90>,
73
+ 'annotation': <PIL.PngImagePlugin.PngImageFile image mode=L size=512x683 at 0x7F9B0C201DD0>,
74
+ 'scene_category': 368}
75
+ ```
76
+
77
+ - `image`: 장면의 PIL 이미지입니다.
78
+ - `annotation`: 분할 지도(segmentation map)의 PIL 이미지입니다. 모델의 타겟이기도 합니다.
79
+ - `scene_category`: "주방" 또는 "사무실"과 같이 이미지 장면을 설명하는 카테고리 ID입니다. 이 가이드에서는 둘 다 PIL 이미지인 `image`와 `annotation`만을 사용합니다.
80
+
81
+ 나중에 모델을 설정할 때 유용하게 사용할 수 있도록 레이블 ID를 레이블 클래스에 매핑하는 사전도 만들고 싶을 것입니다. Hub에서 매핑을 다운로드하고 `id2label` 및 `label2id` 사전을 만드세요:
82
+
83
+ ```py
84
+ >>> import json
85
+ >>> from pathlib import Path
86
+ >>> from huggingface_hub import hf_hub_download
87
+
88
+ >>> repo_id = "huggingface/label-files"
89
+ >>> filename = "ade20k-id2label.json"
90
+ >>> id2label = json.loads(Path(hf_hub_download(repo_id, filename, repo_type="dataset")).read_text())
91
+ >>> id2label = {int(k): v for k, v in id2label.items()}
92
+ >>> label2id = {v: k for k, v in id2label.items()}
93
+ >>> num_labels = len(id2label)
94
+ ```
95
+
96
+ ## 전처리하기[[preprocess]
97
+
98
+ 다음 단계는 모델에 사용할 이미지와 주석을 준비하기 위해 SegFormer 이미지 프로세서를 불러오는 것입니다. 우리가 사용하는 데이터 세트와 같은 일부 데이터 세트는 배경 클래스로 제로 인덱스를 사용합니다. 하지만 배경 클래스는 150개의 클래스에 실제로는 포함되지 않기 때문에 `do_reduce_labels=True` 를 설정해 모든 레이블에서 배경 클래스를 제거해야 합니다. 제로 인덱스는 `255`로 대체되므로 SegFormer의 손실 함수에서 무시됩니다:
99
+
100
+ ```py
101
+ >>> from transformers import AutoImageProcessor
102
+
103
+ >>> checkpoint = "nvidia/mit-b0"
104
+ >>> image_processor = AutoImageProcessor.from_pretrained(checkpoint, do_reduce_labels=True)
105
+ ```
106
+
107
+ <frameworkcontent>
108
+ <pt>
109
+
110
+ 이미지 데이터 세트에 데이터 증강을 적용하여 과적합에 대해 모델을 보다 강건하게 만드는 것이 일반적입니다. 이 가이드에서는 [torchvision](https://pytorch.org/vision/stable/index.html)의 [`ColorJitter`](https://pytorch.org/vision/stable/generated/torchvision.transforms.ColorJitter.html)를 사용하여 이미지의 색상 속성을 임의로 변경합니다. 하지만, 자신이 원하는 이미지 라이브러리를 사용할 수도 있습니다.
111
+
112
+ ```py
113
+ >>> from torchvision.transforms import ColorJitter
114
+
115
+ >>> jitter = ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1)
116
+ ```
117
+
118
+ 이제 모델에 사용할 이미지와 주석을 준비하기 위해 두 개의 전처리 함수를 만듭니다. 이 함수들은 이미지를 `pixel_values`로, 주석을 `labels`로 변환합니다. 훈련 세트의 경우 이미지 프로세서에 이미지를 제공하기 전에 `jitter`를 적용합니다. 테스트 세트의 경우 이미지 프로세서는 `images`를 자르고 정규화하며, 테스트 중에는 데이터 증강이 적용되지 않으므로 `labels`만 자릅니다.
119
+
120
+ ```py
121
+ >>> def train_transforms(example_batch):
122
+ ... images = [jitter(x) for x in example_batch["image"]]
123
+ ... labels = [x for x in example_batch["annotation"]]
124
+ ... inputs = image_processor(images, labels)
125
+ ... return inputs
126
+
127
+
128
+ >>> def val_transforms(example_batch):
129
+ ... images = [x for x in example_batch["image"]]
130
+ ... labels = [x for x in example_batch["annotation"]]
131
+ ... inputs = image_processor(images, labels)
132
+ ... return inputs
133
+ ```
134
+
135
+ 모든 데이터 세트에 `jitter`를 적용하려면, 🤗 Datasets [`~datasets.Dataset.set_transform`] 함수를 사용하세요. 즉시 변환이 적용되기 때문에 더 빠르고 디스크 공간을 덜 차지합니다:
136
+
137
+ ```py
138
+ >>> train_ds.set_transform(train_transforms)
139
+ >>> test_ds.set_transform(val_transforms)
140
+ ```
141
+
142
+ </pt>
143
+ </frameworkcontent>
144
+
145
+ <frameworkcontent>
146
+ <tf>
147
+
148
+ 이미지 데이터 세트에 데이터 증강을 적용하여 과적합에 대해 모델을 보다 강건하게 만드는 것이 일반적입니다. 이 가이드에서는 [`tf.image`](https://www.tensorflow.org/api_docs/python/tf/image)를 사용하여 이미지의 색상 속성을 임의로 변경합니다. 하지만, 자신이 원하는 이미지 라이브러리를 사용할 수도 있습니다.
149
+
150
+ 별개의 두 변환 함수를 정의합니다:
151
+ - 이미지 증강을 포함하는 학습 데이터 변환
152
+ - 🤗 Transformers의 컴퓨터 비전 모델은 채널 우선 레이아웃을 기대하기 때문에, 이미지만 바꾸는 검증 데이터 변환
153
+
154
+ ```py
155
+ >>> import tensorflow as tf
156
+
157
+
158
+ >>> def aug_transforms(image):
159
+ ... image = tf.keras.utils.img_to_array(image)
160
+ ... image = tf.image.random_brightness(image, 0.25)
161
+ ... image = tf.image.random_contrast(image, 0.5, 2.0)
162
+ ... image = tf.image.random_saturation(image, 0.75, 1.25)
163
+ ... image = tf.image.random_hue(image, 0.1)
164
+ ... image = tf.transpose(image, (2, 0, 1))
165
+ ... return image
166
+
167
+
168
+ >>> def transforms(image):
169
+ ... image = tf.keras.utils.img_to_array(image)
170
+ ... image = tf.transpose(image, (2, 0, 1))
171
+ ... return image
172
+ ```
173
+
174
+ 그런 다음 모델을 위해 두 개의 전처리 함수를 만들어 이미지 및 주석 배치를 준비합니다. 이 함수들은 이미지 변환을 적용하고 이전에 로드한 `image_processor`를 사용하여 이미지를 `pixel_values`로, 주석을 `label`로 변환합니다. `ImageProcessor` 는 이미지의 크기 조정과 정규화도 처리합니다.
175
+
176
+ ```py
177
+ >>> def train_transforms(example_batch):
178
+ ... images = [aug_transforms(x.convert("RGB")) for x in example_batch["image"]]
179
+ ... labels = [x for x in example_batch["annotation"]]
180
+ ... inputs = image_processor(images, labels)
181
+ ... return inputs
182
+
183
+
184
+ >>> def val_transforms(example_batch):
185
+ ... images = [transforms(x.convert("RGB")) for x in example_batch["image"]]
186
+ ... labels = [x for x in example_batch["annotation"]]
187
+ ... inputs = image_processor(images, labels)
188
+ ... return inputs
189
+ ```
190
+
191
+ 전체 데이터 집합에 전처리 변환을 적용하려면 🤗 Datasets [`~datasets.Dataset.set_transform`] 함수를 사용하세요.
192
+ 즉시 변환이 적용되기 때문에 더 빠르고 디스크 공간을 덜 차지합니다:
193
+
194
+ ```py
195
+ >>> train_ds.set_transform(train_transforms)
196
+ >>> test_ds.set_transform(val_transforms)
197
+ ```
198
+ </tf>
199
+ </frameworkcontent>
200
+
201
+ ## 평가하기[[evaluate]]
202
+
203
+ 훈련 중에 메트릭을 포함하면 모델의 성능을 평가하는 데 도움이 되는 경��가 많습니다. 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) 라이브러리를 사용하여 평가 방법을 빠르게 로드할 수 있습니다. 이 태스크에서는 [mean Intersection over Union](https://huggingface.co/spaces/evaluate-metric/accuracy) (IoU) 메트릭을 로드하세요 (메트릭을 로드하고 계산하는 방법에 대해 자세히 알아보려면 🤗 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour)를 살펴보세요).
204
+
205
+ ```py
206
+ >>> import evaluate
207
+
208
+ >>> metric = evaluate.load("mean_iou")
209
+ ```
210
+
211
+ 그런 다음 메트릭을 [`~evaluate.EvaluationModule.compute`]하는 함수를 만듭니다. 예측을 먼저 로짓으로 변환한 다음, 레이블의 크기에 맞게 모양을 다시 지정해야 [`~evaluate.EvaluationModule.compute`]를 호출할 수 있습니다:
212
+
213
+ <frameworkcontent>
214
+ <pt>
215
+
216
+ ```py
217
+ >>> import numpy as np
218
+ >>> import torch
219
+ >>> from torch import nn
220
+
221
+ >>> def compute_metrics(eval_pred):
222
+ ... with torch.no_grad():
223
+ ... logits, labels = eval_pred
224
+ ... logits_tensor = torch.from_numpy(logits)
225
+ ... logits_tensor = nn.functional.interpolate(
226
+ ... logits_tensor,
227
+ ... size=labels.shape[-2:],
228
+ ... mode="bilinear",
229
+ ... align_corners=False,
230
+ ... ).argmax(dim=1)
231
+
232
+ ... pred_labels = logits_tensor.detach().cpu().numpy()
233
+ ... metrics = metric.compute(
234
+ ... predictions=pred_labels,
235
+ ... references=labels,
236
+ ... num_labels=num_labels,
237
+ ... ignore_index=255,
238
+ ... reduce_labels=False,
239
+ ... )
240
+ ... for key, value in metrics.items():
241
+ ... if isinstance(value, np.ndarray):
242
+ ... metrics[key] = value.tolist()
243
+ ... return metrics
244
+ ```
245
+
246
+ </pt>
247
+ </frameworkcontent>
248
+
249
+
250
+ <frameworkcontent>
251
+ <tf>
252
+
253
+ ```py
254
+ >>> def compute_metrics(eval_pred):
255
+ ... logits, labels = eval_pred
256
+ ... logits = tf.transpose(logits, perm=[0, 2, 3, 1])
257
+ ... logits_resized = tf.image.resize(
258
+ ... logits,
259
+ ... size=tf.shape(labels)[1:],
260
+ ... method="bilinear",
261
+ ... )
262
+
263
+ ... pred_labels = tf.argmax(logits_resized, axis=-1)
264
+ ... metrics = metric.compute(
265
+ ... predictions=pred_labels,
266
+ ... references=labels,
267
+ ... num_labels=num_labels,
268
+ ... ignore_index=-1,
269
+ ... reduce_labels=image_processor.do_reduce_labels,
270
+ ... )
271
+
272
+ ... per_category_accuracy = metrics.pop("per_category_accuracy").tolist()
273
+ ... per_category_iou = metrics.pop("per_category_iou").tolist()
274
+
275
+ ... metrics.update({f"accuracy_{id2label[i]}": v for i, v in enumerate(per_category_accuracy)})
276
+ ... metrics.update({f"iou_{id2label[i]}": v for i, v in enumerate(per_category_iou)})
277
+ ... return {"val_" + k: v for k, v in metrics.items()}
278
+ ```
279
+
280
+ </tf>
281
+ </frameworkcontent>
282
+
283
+ 이제 `compute_metrics` 함수를 사용할 준비가 되었습니다. 트레이닝을 설정할 때 이 함수로 돌아가게 됩니다.
284
+
285
+ ## 학습하기[[train]]
286
+ <frameworkcontent>
287
+ <pt>
288
+ <Tip>
289
+
290
+ 만약 [`Trainer`]를 사용해 모델을 미세 조정하는 것에 익숙하지 않다면, [여기](../training#finetune-with-trainer)에서 기본 튜토리얼을 살펴보세요!
291
+
292
+ </Tip>
293
+
294
+ 이제 모델 학습을 시작할 준비가 되었습니다! [`AutoModelForSemanticSegmentation`]로 SegFormer를 불러오고, 모델에 레이블 ID와 레이블 클래스 간의 매핑을 전달합니다:
295
+
296
+ ```py
297
+ >>> from transformers import AutoModelForSemanticSegmentation, TrainingArguments, Trainer
298
+
299
+ >>> model = AutoModelForSemanticSegmentation.from_pretrained(checkpoint, id2label=id2label, label2id=label2id)
300
+ ```
301
+
302
+ 이제 세 단계만 남았습니다:
303
+
304
+ 1. 학습 하이퍼파라미터를 [`TrainingArguments`]에 정의합니다. `image` 열이 삭제되기 때문에 사용하지 않는 열을 제거하지 않는 것이 중요합니다. `image` 열이 없으면 `pixel_values`을 생성할 수 없습니다. 이런 경우를 방지하려면 `remove_unused_columns=False`로 설정하세요! 유일하게 필요한 다른 매개변수는 모델을 저장할 위치를 지정하는 `output_dir`입니다. `push_to_hub=True`를 설정하여 이 모델을 Hub에 푸시합니다(모델을 업로드하려면 Hugging Face에 로그인해야 합니다). 각 에포크가 끝날 때마다 [`Trainer`]가 IoU 메트릭을 평가하고 학습 체크포인트를 저장합니다.
305
+ 2. 모델, 데이터 세트, 토크나이저, 데이터 콜레이터, `compute_metrics` 함수와 함께 학습 인자를 [`Trainer`]에 전달하세요.
306
+ 3. 모델을 미세 조정하기 위해 [`~Trainer.train`]를 호출하세요.
307
+
308
+ ```py
309
+ >>> training_args = TrainingArguments(
310
+ ... output_dir="segformer-b0-scene-parse-150",
311
+ ... learning_rate=6e-5,
312
+ ... num_train_epochs=50,
313
+ ... per_device_train_batch_size=2,
314
+ ... per_device_eval_batch_size=2,
315
+ ... save_total_limit=3,
316
+ ... eval_strategy="steps",
317
+ ... save_strategy="steps",
318
+ ... save_steps=20,
319
+ ... eval_steps=20,
320
+ ... logging_steps=1,
321
+ ... eval_accumulation_steps=5,
322
+ ... remove_unused_columns=False,
323
+ ... push_to_hub=True,
324
+ ... )
325
+
326
+ >>> trainer = Trainer(
327
+ ... model=model,
328
+ ... args=training_args,
329
+ ... train_dataset=train_ds,
330
+ ... eval_dataset=test_ds,
331
+ ... compute_metrics=compute_metrics,
332
+ ... )
333
+
334
+ >>> trainer.train()
335
+ ```
336
+ 학습이 완료되면, 누구나 모델을 사용할 수 있도록 [`~transformers.Trainer.push_to_hub`] 메서드를 사용해 Hub에 모델을 공유하세요:
337
+
338
+ ```py
339
+ >>> trainer.push_to_hub()
340
+ ```
341
+ </pt>
342
+ </frameworkcontent>
343
+
344
+ <frameworkcontent>
345
+ <tf>
346
+ <Tip>
347
+
348
+ Keras로 모델을 미세 조정하는 데 익숙하지 않은 경우, 먼저 [기본 튜토리얼](../training#train-a-tensorflow-model-with-keras)을 확인해보세요!
349
+
350
+ </Tip>
351
+
352
+ TensorFlow에서 모델을 미세 조정하려면 다음 단계를 따르세요:
353
+ 1. 학습 하이퍼파라미터를 정의하고 옵티마이저와 학습률 스케쥴러를 설정하세요.
354
+ 2. 사전 학습된 모델을 인스턴스화하세요.
355
+ 3. 🤗 Dataset을 `tf.data.Dataset`로 변환하세요.
356
+ 4. 모델을 컴파일하세요.
357
+ 5. 콜백을 추가하여 메트릭을 계산하고 🤗 Hub에 모델을 업로드하세요.
358
+ 6. `fit()` 메서드를 사용하여 훈련을 실행하세요.
359
+
360
+ 하이퍼파라미터, 옵티마이저, 학습률 스케쥴러를 정의하는 것으로 시작하세요:
361
+
362
+ ```py
363
+ >>> from transformers import create_optimizer
364
+
365
+ >>> batch_size = 2
366
+ >>> num_epochs = 50
367
+ >>> num_train_steps = len(train_ds) * num_epochs
368
+ >>> learning_rate = 6e-5
369
+ >>> weight_decay_rate = 0.01
370
+
371
+ >>> optimizer, lr_schedule = create_optimizer(
372
+ ... init_lr=learning_rate,
373
+ ... num_train_steps=num_train_steps,
374
+ ... weight_decay_rate=weight_decay_rate,
375
+ ... num_warmup_steps=0,
376
+ ... )
377
+ ```
378
+
379
+ 그런 다음 레이블 매핑과 함께 [`TFAutoModelForSemanticSegmentation`]을 사용하여 SegFormer를 불러오고 옵티마이저로 컴파일합니다. 트랜스포머 모델은 모두 디폴트로 태스크 관련 손실 함수가 있으므로 원치 않으면 지정할 필요가 없습니다:
380
+
381
+ ```py
382
+ >>> from transformers import TFAutoModelForSemanticSegmentation
383
+
384
+ >>> model = TFAutoModelForSemanticSegmentation.from_pretrained(
385
+ ... checkpoint,
386
+ ... id2label=id2label,
387
+ ... label2id=label2id,
388
+ ... )
389
+ >>> model.compile(optimizer=optimizer) # 손실 함수 인자가 없습니다!
390
+ ```
391
+
392
+ [`~datasets.Dataset.to_tf_dataset`] 와 [`DefaultDataCollator`]를 사용해 데이터 세트를 `tf.data.Dataset` 포맷으로 변환하세요:
393
+
394
+ ```py
395
+ >>> from transformers import DefaultDataCollator
396
+
397
+ >>> data_collator = DefaultDataCollator(return_tensors="tf")
398
+
399
+ >>> tf_train_dataset = train_ds.to_tf_dataset(
400
+ ... columns=["pixel_values", "label"],
401
+ ... shuffle=True,
402
+ ... batch_size=batch_size,
403
+ ... collate_fn=data_collator,
404
+ ... )
405
+
406
+ >>> tf_eval_dataset = test_ds.to_tf_dataset(
407
+ ... columns=["pixel_values", "label"],
408
+ ... shuffle=True,
409
+ ... batch_size=batch_size,
410
+ ... collate_fn=data_collator,
411
+ ... )
412
+ ```
413
+
414
+ 예측으로 정확도를 계산하고 모델을 🤗 Hub로 푸시하려면 [Keras callbacks](../main_classes/keras_callbacks)를 사용하세요. `compute_metrics` 함수를 [`KerasMetricCallback`]에 전달하고, 모델 업로드를 위해 [`PushToHubCallback`]를 사용하세요:
415
+
416
+ ```py
417
+ >>> from transformers.keras_callbacks import KerasMetricCallback, PushToHubCallback
418
+
419
+ >>> metric_callback = KerasMetricCallback(
420
+ ... metric_fn=compute_metrics, eval_dataset=tf_eval_dataset, batch_size=batch_size, label_cols=["labels"]
421
+ ... )
422
+
423
+ >>> push_to_hub_callback = PushToHubCallback(output_dir="scene_segmentation", tokenizer=image_processor)
424
+
425
+ >>> callbacks = [metric_callback, push_to_hub_callback]
426
+ ```
427
+
428
+ 이제 모델을 훈련할 준비가 되었습니다! 훈련 및 검증 데이터 세트, 에포크 수와 함께 `fit()`을 호출하고, 콜백을 사용하여 모델을 미세 조정합니다:
429
+
430
+ ```py
431
+ >>> model.fit(
432
+ ... tf_train_dataset,
433
+ ... validation_data=tf_eval_dataset,
434
+ ... callbacks=callbacks,
435
+ ... epochs=num_epochs,
436
+ ... )
437
+ ```
438
+
439
+ 축하합니다! 모델을 미세 조정하고 🤗 Hub에 공유했습니다. 이제 추론에 사용할 수 있습니다!
440
+
441
+ </tf>
442
+ </frameworkcontent>
443
+
444
+
445
+ ## 추론하기[[inference]]
446
+
447
+ 이제 모델을 미세 조정했으니 추론에 사용할 수 있습니다!
448
+
449
+ 추론할 이미지를 로드하세요:
450
+
451
+ ```py
452
+ >>> image = ds[0]["image"]
453
+ >>> image
454
+ ```
455
+
456
+ <div class="flex justify-center">
457
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/semantic-seg-image.png" alt="Image of bedroom"/>
458
+ </div>
459
+
460
+ <frameworkcontent>
461
+ <pt>
462
+
463
+ 추론을 위해 미세 조정한 모델을 시험해 보는 가장 간단한 방법은 [`pipeline`]에서 사용하는 것입니다. 모델을 사용하여 이미지 분할을 위한 `pipeline`을 인스턴스화하고 이미지를 전달합니다:
464
+
465
+ ```py
466
+ >>> from transformers import pipeline
467
+
468
+ >>> segmenter = pipeline("image-segmentation", model="my_awesome_seg_model")
469
+ >>> segmenter(image)
470
+ [{'score': None,
471
+ 'label': 'wall',
472
+ 'mask': <PIL.Image.Image image mode=L size=640x427 at 0x7FD5B2062690>},
473
+ {'score': None,
474
+ 'label': 'sky',
475
+ 'mask': <PIL.Image.Image image mode=L size=640x427 at 0x7FD5B2062A50>},
476
+ {'score': None,
477
+ 'label': 'floor',
478
+ 'mask': <PIL.Image.Image image mode=L size=640x427 at 0x7FD5B2062B50>},
479
+ {'score': None,
480
+ 'label': 'ceiling',
481
+ 'mask': <PIL.Image.Image image mode=L size=640x427 at 0x7FD5B2062A10>},
482
+ {'score': None,
483
+ 'label': 'bed ',
484
+ 'mask': <PIL.Image.Image image mode=L size=640x427 at 0x7FD5B2062E90>},
485
+ {'score': None,
486
+ 'label': 'windowpane',
487
+ 'mask': <PIL.Image.Image image mode=L size=640x427 at 0x7FD5B2062390>},
488
+ {'score': None,
489
+ 'label': 'cabinet',
490
+ 'mask': <PIL.Image.Image image mode=L size=640x427 at 0x7FD5B2062550>},
491
+ {'score': None,
492
+ 'label': 'chair',
493
+ 'mask': <PIL.Image.Image image mode=L size=640x427 at 0x7FD5B2062D90>},
494
+ {'score': None,
495
+ 'label': 'armchair',
496
+ 'mask': <PIL.Image.Image image mode=L size=640x427 at 0x7FD5B2062E10>}]
497
+ ```
498
+ 원하는 경우 `pipeline`의 결과를 수동으로 복제할 수도 있습니다. 이미지 프로세서로 이미지를 처리하고 `pixel_values`을 GPU에 배치합니다:
499
+
500
+ ```py
501
+ >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # 가능하다면 GPU를 사용하고, 그렇지 않다면 CPU를 사용하세요
502
+ >>> encoding = image_processor(image, return_tensors="pt")
503
+ >>> pixel_values = encoding.pixel_values.to(device)
504
+ ```
505
+
506
+ 모델에 입력을 전달하고 `logits`를 반환합니다:
507
+
508
+ ```py
509
+ >>> outputs = model(pixel_values=pixel_values)
510
+ >>> logits = outputs.logits.cpu()
511
+ ```
512
+ 그런 다음 로짓의 크기를 원본 이미지 크기로 다시 조정합니다:
513
+
514
+ ```py
515
+ >>> upsampled_logits = nn.functional.interpolate(
516
+ ... logits,
517
+ ... size=image.size[::-1],
518
+ ... mode="bilinear",
519
+ ... align_corners=False,
520
+ ... )
521
+
522
+ >>> pred_seg = upsampled_logits.argmax(dim=1)[0]
523
+ ```
524
+
525
+ </pt>
526
+ </frameworkcontent>
527
+
528
+ <frameworkcontent>
529
+ <tf>
530
+ 이미지 프로세서를 로드하여 이미지를 전처리하고 입력을 TensorFlow 텐서로 반환합니다:
531
+
532
+ ```py
533
+ >>> from transformers import AutoImageProcessor
534
+
535
+ >>> image_processor = AutoImageProcessor.from_pretrained("MariaK/scene_segmentation")
536
+ >>> inputs = image_processor(image, return_tensors="tf")
537
+ ```
538
+
539
+ 모델에 입력을 전달하고 `logits`를 반환합니다:
540
+
541
+ ```py
542
+ >>> from transformers import TFAutoModelForSemanticSegmentation
543
+
544
+ >>> model = TFAutoModelForSemanticSegmentation.from_pretrained("MariaK/scene_segmentation")
545
+ >>> logits = model(**inputs).logits
546
+ ```
547
+
548
+ 그런 다음 로그를 원본 이미지 크기로 재조정하고 클래스 차원에 argmax를 적용합니다:
549
+
550
+ ```py
551
+ >>> logits = tf.transpose(logits, [0, 2, 3, 1])
552
+
553
+ >>> upsampled_logits = tf.image.resize(
554
+ ... logits,
555
+ ... # `image.size`가 너비와 높이를 반환하기 때문에 `image`의 모양을 반전시킵니다
556
+ ... image.size[::-1],
557
+ ... )
558
+
559
+ >>> pred_seg = tf.math.argmax(upsampled_logits, axis=-1)[0]
560
+ ```
561
+
562
+ </tf>
563
+ </frameworkcontent>
564
+
565
+ 결과를 시각화하려면 [dataset color palette](https://github.com/tensorflow/models/blob/3f1ca33afe3c1631b733ea7e40c294273b9e406d/research/deeplab/utils/get_dataset_colormap.py#L51)를 각 클래스를 RGB 값에 매핑하는 `ade_palette()`로 로드합니다. 그런 다음 이미지와 예측된 분할 지도(segmentation map)을 결합하여 구성할 수 있습니다:
566
+
567
+ ```py
568
+ >>> import matplotlib.pyplot as plt
569
+ >>> import numpy as np
570
+
571
+ >>> color_seg = np.zeros((pred_seg.shape[0], pred_seg.shape[1], 3), dtype=np.uint8)
572
+ >>> palette = np.array(ade_palette())
573
+ >>> for label, color in enumerate(palette):
574
+ ... color_seg[pred_seg == label, :] = color
575
+ >>> color_seg = color_seg[..., ::-1] # BGR로 변환
576
+
577
+ >>> img = np.array(image) * 0.5 + color_seg * 0.5 # 분할 지도으로 이미지 구성
578
+ >>> img = img.astype(np.uint8)
579
+
580
+ >>> plt.figure(figsize=(15, 10))
581
+ >>> plt.imshow(img)
582
+ >>> plt.show()
583
+ ```
584
+
585
+ <div class="flex justify-center">
586
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/semantic-seg-preds.png" alt="Image of bedroom overlaid with segmentation map"/>
587
+ </div>
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/sequence_classification.md ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # 텍스트 분류[[text-classification]]
18
+
19
+ [[open-in-colab]]
20
+
21
+ <Youtube id="leNG9fN9FQU"/>
22
+
23
+ 텍스트 분류는 자연어 처리의 일종으로, 텍스트에 레이블 또는 클래스를 지정하는 작업입니다. 많은 대기업이 다양한 실용적인 응용 분야에서 텍스트 분류를 운영하고 있습니다. 가장 인기 있는 텍스트 분류 형태 중 하나는 감성 분석으로, 텍스트 시퀀스에 🙂 긍정, 🙁 부정 또는 😐 중립과 같은 레이블을 지정합니다.
24
+
25
+ 이 가이드에서 학습할 내용은:
26
+
27
+ 1. [IMDb](https://huggingface.co/datasets/imdb) 데이터셋에서 [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased)를 파인 튜닝하여 영화 리뷰가 긍정적인지 부정적인지 판단합니다.
28
+ 2. 추론을 위해 파인 튜닝 모델을 사용합니다.
29
+
30
+ <Tip>
31
+
32
+ 이 작업과 호환되는 모든 아키텍처와 체크포인트를 보려면 [작업 페이지](https://huggingface.co/tasks/text-classification)를 확인하는 것이 좋습니다.
33
+
34
+ </Tip>
35
+
36
+ 시작하기 전에, 필요한 모든 라이브러리가 설치되어 있는지 확인하세요:
37
+
38
+ ```bash
39
+ pip install transformers datasets evaluate
40
+ ```
41
+
42
+ Hugging Face 계정에 로그인하여 모델을 업로드하고 커뮤니티에 공유하는 것을 권장합니다. 메시지가 표시되면, 토큰을 입력하여 로그인하세요:
43
+
44
+ ```py
45
+ >>> from huggingface_hub import notebook_login
46
+
47
+ >>> notebook_login()
48
+ ```
49
+
50
+ ## IMDb 데이터셋 가져오기[[load-imdb-dataset]]
51
+
52
+ 먼저 🤗 Datasets 라이브러리에서 IMDb 데이터셋을 가져옵니다:
53
+
54
+ ```py
55
+ >>> from datasets import load_dataset
56
+
57
+ >>> imdb = load_dataset("imdb")
58
+ ```
59
+
60
+ 그런 다음 예시를 살펴봅시다:
61
+
62
+ ```py
63
+ >>> imdb["test"][0]
64
+ {
65
+ "label": 0,
66
+ "text": "I love sci-fi and am willing to put up with a lot. Sci-fi movies/TV are usually underfunded, under-appreciated and misunderstood. I tried to like this, I really did, but it is to good TV sci-fi as Babylon 5 is to Star Trek (the original). Silly prosthetics, cheap cardboard sets, stilted dialogues, CG that doesn't match the background, and painfully one-dimensional characters cannot be overcome with a 'sci-fi' setting. (I'm sure there are those of you out there who think Babylon 5 is good sci-fi TV. It's not. It's clichéd and uninspiring.) While US viewers might like emotion and character development, sci-fi is a genre that does not take itself seriously (cf. Star Trek). It may treat important issues, yet not as a serious philosophy. It's really difficult to care about the characters here as they are not simply foolish, just missing a spark of life. Their actions and reactions are wooden and predictable, often painful to watch. The makers of Earth KNOW it's rubbish as they have to always say \"Gene Roddenberry's Earth...\" otherwise people would not continue watching. Roddenberry's ashes must be turning in their orbit as this dull, cheap, poorly edited (watching it without advert breaks really brings this home) trudging Trabant of a show lumbers into space. Spoiler. So, kill off a main character. And then bring him back as another actor. Jeeez! Dallas all over again.",
67
+ }
68
+ ```
69
+
70
+ 이 데이터셋에는 두 가지 필드가 있습니다:
71
+
72
+ - `text`: 영화 리뷰 텍스트
73
+ - `label`: `0`은 부정적인 리뷰, `1`은 긍정적인 리뷰를 나타냅니다.
74
+
75
+ ## 전처리[[preprocess]]
76
+
77
+ 다음 단계는 DistilBERT 토크나이저를 가져와서 `text` 필드를 전처리하는 것입니다:
78
+
79
+ ```py
80
+ >>> from transformers import AutoTokenizer
81
+
82
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
83
+ ```
84
+
85
+ `text`를 토큰화하고 시퀀스가 DistilBERT의 최대 입력 길이보다 길지 않도록 자르기 위한 전처리 함수를 생성하세요:
86
+
87
+ ```py
88
+ >>> def preprocess_function(examples):
89
+ ... return tokenizer(examples["text"], truncation=True)
90
+ ```
91
+
92
+ 전체 데이터셋에 전처리 함수를 적용하려면, 🤗 Datasets [`~datasets.Dataset.map`] 함수를 사용하세요. 데이터셋의 여러 요소를 한 번에 처리하기 위해 `batched=True`로 설정함으로써 데이터셋 `map`를 더 빠르게 처리할 수 있습니다:
93
+
94
+ ```py
95
+ tokenized_imdb = imdb.map(preprocess_function, batched=True)
96
+ ```
97
+
98
+ 이제 [`DataCollatorWithPadding`]를 사용하여 예제 배치를 만들어봅시다. 데이터셋 전체를 최대 길이로 패딩하는 대신, *동적 패딩*을 사용하여 배치에서 가장 긴 길이에 맞게 문장을 패딩하는 것이 효율적입니다.
99
+
100
+ <frameworkcontent>
101
+ <pt>
102
+ ```py
103
+ >>> from transformers import DataCollatorWithPadding
104
+
105
+ >>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
106
+ ```
107
+ </pt>
108
+ <tf>
109
+ ```py
110
+ >>> from transformers import DataCollatorWithPadding
111
+
112
+ >>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer, return_tensors="tf")
113
+ ```
114
+ </tf>
115
+ </frameworkcontent>
116
+
117
+ ## 평가하기[[evaluate]]
118
+
119
+ 훈련 중 모델의 성능을 평가하기 위해 메트릭을 포함하는 것이 유용합니다. 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) 라이브러리를 사용하여 빠르게 평가 방법을 로드할 수 있습니다. 이 작업에서는 [accuracy](https://huggingface.co/spaces/evaluate-metric/accuracy) 메트릭을 가져옵니다. (메트릭을 가져오고 계산하는 방법에 대해서는 🤗 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour)를 참조하세요):
120
+
121
+ ```py
122
+ >>> import evaluate
123
+
124
+ >>> accuracy = evaluate.load("accuracy")
125
+ ```
126
+
127
+ 그런 다음 `compute_metrics` 함수를 만들어서 예측과 레이블을 계산하여 정확도를 계산하도록 [`~evaluate.EvaluationModule.compute`]를 호출합니다:
128
+
129
+ ```py
130
+ >>> import numpy as np
131
+
132
+
133
+ >>> def compute_metrics(eval_pred):
134
+ ... predictions, labels = eval_pred
135
+ ... predictions = np.argmax(predictions, axis=1)
136
+ ... return accuracy.compute(predictions=predictions, references=labels)
137
+ ```
138
+
139
+ 이제 `compute_metrics` 함수는 준비되었고, 훈련 과정을 설정할 때 다시 살펴볼 예정입니다.
140
+
141
+ ## 훈련[[train]]
142
+
143
+ 모델을 훈련하기 전에, `id2label`와 `label2id`를 사용하여 예상되는 id와 레이블의 맵을 생성하세요:
144
+
145
+ ```py
146
+ >>> id2label = {0: "NEGATIVE", 1: "POSITIVE"}
147
+ >>> label2id = {"NEGATIVE": 0, "POSITIVE": 1}
148
+ ```
149
+
150
+ <frameworkcontent>
151
+ <pt>
152
+ <Tip>
153
+
154
+ [`Trainer`]를 사용하여 모델을 파인 튜닝하는 방법에 익숙하지 않은 경우, [여기](../training#train-with-pytorch-trainer)의 기본 튜토리얼을 확인하세요!
155
+
156
+ </Tip>
157
+
158
+ 이제 모델을 훈련시킬 준비가 되었습니다! [`AutoModelForSequenceClassification`]로 DistilBERT를 가쳐오고 예상되는 레이블 수와 레이블 매핑을 지정하세요:
159
+
160
+ ```py
161
+ >>> from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer
162
+
163
+ >>> model = AutoModelForSequenceClassification.from_pretrained(
164
+ ... "distilbert/distilbert-base-uncased", num_labels=2, id2label=id2label, label2id=label2id
165
+ ... )
166
+ ```
167
+
168
+ 이제 세 단계만 거치면 끝입니다:
169
+
170
+ 1. [`TrainingArguments`]에서 하이퍼파라미터를 정의하세요. `output_dir`는 모델을 저장할 위치를 지정하는 유일한 파라미터입니다. 이 모델을 Hub에 업로드하기 위해 `push_to_hub=True`를 설정합니다. (모델을 업로드하기 위해 Hugging Face에 로그인해야합니다.) 각 에폭이 끝날 때마다, [`Trainer`]는 정확도를 평가하고 훈련 체크포인트를 저장합니다.
171
+ 2. [`Trainer`]에 훈련 인수와 모델, 데이터셋, 토크나이저, 데이터 수집기 및 `compute_metrics` 함수를 전달하세요.
172
+ 3. [`~Trainer.train`]를 호출하여 모델은 파인 튜닝하세요.
173
+
174
+ ```py
175
+ >>> training_args = TrainingArguments(
176
+ ... output_dir="my_awesome_model",
177
+ ... learning_rate=2e-5,
178
+ ... per_device_train_batch_size=16,
179
+ ... per_device_eval_batch_size=16,
180
+ ... num_train_epochs=2,
181
+ ... weight_decay=0.01,
182
+ ... eval_strategy="epoch",
183
+ ... save_strategy="epoch",
184
+ ... load_best_model_at_end=True,
185
+ ... push_to_hub=True,
186
+ ... )
187
+
188
+ >>> trainer = Trainer(
189
+ ... model=model,
190
+ ... args=training_args,
191
+ ... train_dataset=tokenized_imdb["train"],
192
+ ... eval_dataset=tokenized_imdb["test"],
193
+ ... processing_class=tokenizer,
194
+ ... data_collator=data_collator,
195
+ ... compute_metrics=compute_metrics,
196
+ ... )
197
+
198
+ >>> trainer.train()
199
+ ```
200
+
201
+ <Tip>
202
+
203
+ [`Trainer`]는 `tokenizer`를 전달하면 기본적으로 동적 매핑을 적용합니다. 이 경우, 명시적으로 데이터 수집기를 지정할 필요가 없습니다.
204
+
205
+ </Tip>
206
+
207
+ 훈련이 완료되면, [`~transformers.Trainer.push_to_hub`] 메소드를 사용하여 모델을 Hub에 공유할 수 있습니다.
208
+
209
+ ```py
210
+ >>> trainer.push_to_hub()
211
+ ```
212
+ </pt>
213
+ <tf>
214
+ <Tip>
215
+
216
+ Keras를 사용하여 모델을 파인 튜닝하는 방법에 익숙하지 않은 경우, [여기](../training#train-a-tensorflow-model-with-keras)의 기본 튜토리얼을 확인하세요!
217
+
218
+ </Tip>
219
+ TensorFlow에서 모델을 파인 튜닝하려면, 먼저 옵티마이저 함수와 학습률 스케쥴, 그리고 일부 훈련 하이퍼파라미터를 설정해야 합니다:
220
+
221
+ ```py
222
+ >>> from transformers import create_optimizer
223
+ >>> import tensorflow as tf
224
+
225
+ >>> batch_size = 16
226
+ >>> num_epochs = 5
227
+ >>> batches_per_epoch = len(tokenized_imdb["train"]) // batch_size
228
+ >>> total_train_steps = int(batches_per_epoch * num_epochs)
229
+ >>> optimizer, schedule = create_optimizer(init_lr=2e-5, num_warmup_steps=0, num_train_steps=total_train_steps)
230
+ ```
231
+
232
+ 그런 다음 [`TFAutoModelForSequenceClassification`]을 사용하여 DistilBERT를 로드하고, 예상되는 레이블 수와 레이블 매핑을 로드할 수 있습니다:
233
+
234
+ ```py
235
+ >>> from transformers import TFAutoModelForSequenceClassification
236
+
237
+ >>> model = TFAutoModelForSequenceClassification.from_pretrained(
238
+ ... "distilbert/distilbert-base-uncased", num_labels=2, id2label=id2label, label2id=label2id
239
+ ... )
240
+ ```
241
+
242
+ [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]을 사용하여 데이터셋을 `tf.data.Dataset` 형식으로 변환합니다:
243
+
244
+ ```py
245
+ >>> tf_train_set = model.prepare_tf_dataset(
246
+ ... tokenized_imdb["train"],
247
+ ... shuffle=True,
248
+ ... batch_size=16,
249
+ ... collate_fn=data_collator,
250
+ ... )
251
+
252
+ >>> tf_validation_set = model.prepare_tf_dataset(
253
+ ... tokenized_imdb["test"],
254
+ ... shuffle=False,
255
+ ... batch_size=16,
256
+ ... collate_fn=data_collator,
257
+ ... )
258
+ ```
259
+
260
+ [`compile`](https://keras.io/api/models/model_training_apis/#compile-method)를 사용하여 훈련할 모델을 구성합니다:
261
+
262
+ ```py
263
+ >>> import tensorflow as tf
264
+
265
+ >>> model.compile(optimizer=optimizer)
266
+ ```
267
+
268
+ 훈련을 시작하기 전에 설정해야할 마지막 두 가지는 예측에서 정확도를 계산하고, 모델을 Hub에 업로드할 방법을 제공하는 것입니다. 모두 [Keras callbacks](../main_classes/keras_callbacks)를 사용하여 수행됩니다.
269
+
270
+ [`~transformers.KerasMetricCallback`]에 `compute_metrics`를 전달하여 정확도를 높입니다.
271
+
272
+ ```py
273
+ >>> from transformers.keras_callbacks import KerasMetricCallback
274
+
275
+ >>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set)
276
+ ```
277
+
278
+ [`~transformers.PushToHubCallback`]에서 모델과 토크나이저를 업로드할 위치를 지정합니다:
279
+
280
+ ```py
281
+ >>> from transformers.keras_callbacks import PushToHubCallback
282
+
283
+ >>> push_to_hub_callback = PushToHubCallback(
284
+ ... output_dir="my_awesome_model",
285
+ ... tokenizer=tokenizer,
286
+ ... )
287
+ ```
288
+
289
+ 그런 다음 콜백을 함께 묶습니다:
290
+
291
+ ```py
292
+ >>> callbacks = [metric_callback, push_to_hub_callback]
293
+ ```
294
+
295
+ 드디어, 모델 훈련을 시작할 준비가 되었습니다! [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)에 훈련 데이터셋, 검증 데이터셋, 에폭의 수 및 콜백을 전달하여 파인 튜닝합니다:
296
+
297
+ ```py
298
+ >>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3, callbacks=callbacks)
299
+ ```
300
+
301
+ 훈련이 완료되면, 모델이 자동으로 Hub에 업로드되어 모든 사람이 사용할 수 있습니다!
302
+ </tf>
303
+ </frameworkcontent>
304
+
305
+ <Tip>
306
+
307
+ 텍스트 분류를 위한 모델을 파인 튜닝하는 자세한 예제는 다음 [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb) 또는 [TensorFlow notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb)를 참조하세요.
308
+
309
+ </Tip>
310
+
311
+ ## 추론[[inference]]
312
+
313
+ 좋아요, 이제 모델을 파인 튜닝했으니 추론에 사용할 수 있습니다!
314
+
315
+ 추론을 수행하고자 하는 텍스트를 가져와봅시다:
316
+
317
+ ```py
318
+ >>> text = "This was a masterpiece. Not completely faithful to the books, but enthralling from beginning to end. Might be my favorite of the three."
319
+ ```
320
+
321
+ 파인 튜닝된 모델로 추론을 시도하는 가장 간단한 방법은 [`pipeline`]를 사용하는 것입니다. 모델로 감정 분석을 위한 `pipeline`을 인스턴스화하고, 텍스트를 전달해보세요:
322
+
323
+ ```py
324
+ >>> from transformers import pipeline
325
+
326
+ >>> classifier = pipeline("sentiment-analysis", model="stevhliu/my_awesome_model")
327
+ >>> classifier(text)
328
+ [{'label': 'POSITIVE', 'score': 0.9994940757751465}]
329
+ ```
330
+
331
+ 원한다면, `pipeline`의 결과를 수동으로 복제할 수도 있습니다.
332
+
333
+ <frameworkcontent>
334
+ <pt>
335
+ 텍스트를 토큰화하고 PyTorch 텐서를 반환합니다.
336
+
337
+ ```py
338
+ >>> from transformers import AutoTokenizer
339
+
340
+ >>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_model")
341
+ >>> inputs = tokenizer(text, return_tensors="pt")
342
+ ```
343
+
344
+ 입력을 모델에 전달하고 `logits`을 반환합니다:
345
+
346
+ ```py
347
+ >>> from transformers import AutoModelForSequenceClassification
348
+
349
+ >>> model = AutoModelForSequenceClassification.from_pretrained("stevhliu/my_awesome_model")
350
+ >>> with torch.no_grad():
351
+ ... logits = model(**inputs).logits
352
+ ```
353
+
354
+ 가장 높은 확률을 가진 클래스를 모델의 `id2label` 매핑을 사용하여 텍스트 레이블로 변환합니다:
355
+
356
+ ```py
357
+ >>> predicted_class_id = logits.argmax().item()
358
+ >>> model.config.id2label[predicted_class_id]
359
+ 'POSITIVE'
360
+ ```
361
+ </pt>
362
+ <tf>
363
+ 텍스트를 토큰화하고 TensorFlow 텐서를 반환합니��:
364
+
365
+ ```py
366
+ >>> from transformers import AutoTokenizer
367
+
368
+ >>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_model")
369
+ >>> inputs = tokenizer(text, return_tensors="tf")
370
+ ```
371
+
372
+ 입력값을 모델에 전달하고 `logits`을 반환합니다:
373
+
374
+ ```py
375
+ >>> from transformers import TFAutoModelForSequenceClassification
376
+
377
+ >>> model = TFAutoModelForSequenceClassification.from_pretrained("stevhliu/my_awesome_model")
378
+ >>> logits = model(**inputs).logits
379
+ ```
380
+
381
+ 가장 높은 확률을 가진 클래스를 모델의 `id2label` 매핑을 사용하여 텍스트 레이블로 변환합니다:
382
+
383
+ ```py
384
+ >>> predicted_class_id = int(tf.math.argmax(logits, axis=-1)[0])
385
+ >>> model.config.id2label[predicted_class_id]
386
+ 'POSITIVE'
387
+ ```
388
+ </tf>
389
+ </frameworkcontent>
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/summarization.md ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # 요약[[summarization]]
18
+
19
+ [[open-in-colab]]
20
+
21
+ <Youtube id="yHnr5Dk2zCI"/>
22
+
23
+ 요약은 문서나 기사에서 중요한 정보를 모두 포함하되 짧게 만드는 일입니다.
24
+ 번역과 마찬가지로, 시퀀스-투-시퀀스 문제로 구성할 수 있는 대표적인 작업 중 하나입니다.
25
+ 요약에는 아래와 같이 유형이 있습니다:
26
+
27
+ - 추출(Extractive) 요약: 문서에서 가장 관련성 높은 정보를 추출합니다.
28
+ - 생성(Abstractive) 요약: 가장 관련성 높은 정보를 포착해내는 새로운 텍스트를 생성합니다.
29
+
30
+ 이 가이드에서 소개할 내용은 아래와 같습니다:
31
+
32
+ 1. 생성 요약을 위한 [BillSum](https://huggingface.co/datasets/billsum) 데이터셋 중 캘리포니아 주 법안 하위 집합으로 [T5](https://huggingface.co/google-t5/t5-small)를 파인튜닝합니다.
33
+ 2. 파인튜닝된 모델을 사용하여 추론합니다.
34
+
35
+ <Tip>
36
+
37
+ 이 작업과 호환되는 모든 아키텍처와 체크포인트를 보려면 [작업 페이지](https://huggingface.co/tasks/summarization)를 확인하는 것이 좋습니다.
38
+
39
+ </Tip>
40
+
41
+ 시작하기 전에 필요한 라이브러리가 모두 설치되어 있는지 확인하세요:
42
+
43
+ ```bash
44
+ pip install transformers datasets evaluate rouge_score
45
+ ```
46
+
47
+ Hugging Face 계정에 로그인하면 모델을 업로드하고 커뮤니티에 공유할 수 있습니다.
48
+ 토큰을 입력하여 로그인하세요.
49
+
50
+ ```py
51
+ >>> from huggingface_hub import notebook_login
52
+
53
+ >>> notebook_login()
54
+ ```
55
+
56
+ ## BillSum 데이터셋 가져오기[[load-billsum-dataset]]
57
+
58
+ 🤗 Datasets 라이브러리에서 BillSum 데이터셋의 작은 버전인 캘리포니아 주 법안 하위 집합을 가져오세요:
59
+
60
+ ```py
61
+ >>> from datasets import load_dataset
62
+
63
+ >>> billsum = load_dataset("billsum", split="ca_test")
64
+ ```
65
+
66
+ [`~datasets.Dataset.train_test_split`] 메소드로 데이터셋을 학습용와 테스트용으로 나누세요:
67
+
68
+ ```py
69
+ >>> billsum = billsum.train_test_split(test_size=0.2)
70
+ ```
71
+
72
+ 그런 다음 예시를 하나 살펴보세요:
73
+
74
+ ```py
75
+ >>> billsum["train"][0]
76
+ {'summary': 'Existing law authorizes state agencies to enter into contracts for the acquisition of goods or services upon approval by the Department of General Services. Existing law sets forth various requirements and prohibitions for those contracts, including, but not limited to, a prohibition on entering into contracts for the acquisition of goods or services of $100,000 or more with a contractor that discriminates between spouses and domestic partners or same-sex and different-sex couples in the provision of benefits. Existing law provides that a contract entered into in violation of those requirements and prohibitions is void and authorizes the state or any person acting on behalf of the state to bring a civil action seeking a determination that a contract is in violation and therefore void. Under existing law, a willful violation of those requirements and prohibitions is a misdemeanor.\nThis bill would also prohibit a state agency from entering into contracts for the acquisition of goods or services of $100,000 or more with a contractor that discriminates between employees on the basis of gender identity in the provision of benefits, as specified. By expanding the scope of a crime, this bill would impose a state-mandated local program.\nThe California Constitution requires the state to reimburse local agencies and school districts for certain costs mandated by the state. Statutory provisions establish procedures for making that reimbursement.\nThis bill would provide that no reimbursement is required by this act for a specified reason.',
77
+ 'text': 'The people of the State of California do enact as follows:\n\n\nSECTION 1.\nSection 10295.35 is added to the Public Contract Code, to read:\n10295.35.\n(a) (1) Notwithstanding any other law, a state agency shall not enter into any contract for the acquisition of goods or services in the amount of one hundred thousand dollars ($100,000) or more with a contractor that, in the provision of benefits, discriminates between employees on the basis of an employee’s or dependent’s actual or perceived gender identity, including, but not limited to, the employee’s or dependent’s identification as transgender.\n(2) For purposes of this section, “contract” includes contracts with a cumulative amount of one hundred thousand dollars ($100,000) or more per contractor in each fiscal year.\n(3) For purposes of this section, an employee health plan is discriminatory if the plan is not consistent with Section 1365.5 of the Health and Safety Code and Section 10140 of the Insurance Code.\n(4) The requirements of this section shall apply only to those portions of a contractor’s operations that occur under any of the following conditions:\n(A) Within the state.\n(B) On real property outside the state if the property is owned by the state or if the state has a right to occupy the property, and if the contractor’s presence at that location is connected to a contract with the state.\n(C) Elsewhere in the United States where work related to a state contract is being performed.\n(b) Contractors shall treat as confidential, to the maximum extent allowed by law or by the requirement of the contractor’s insurance provider, any request by an employee or applicant for employment benefits or any documentation of eligibility for benefits submitted by an employee or applicant for employment.\n(c) After taking all reasonable measures to find a contractor that complies with this section, as determined by the state agency, the requirements of this section may be waived under any of the following circumstances:\n(1) There is only one prospective contractor willing to enter into a specific contract with the state agency.\n(2) The contract is necessary to respond to an emergency, as determined by the state agency, that endangers the public health, welfare, or safety, or the contract is necessary for the provision of essential services, and no entity that complies with the requirements of this section capable of responding to the emergency is immediately available.\n(3) The requirements of this section violate, or are inconsistent with, the terms or conditions of a grant, subvention, or agreement, if the agency has made a good faith attempt to change the terms or conditions of any grant, subvention, or agreement to authorize application of this section.\n(4) The contractor is providing wholesale or bulk water, power, or natural gas, the conveyance or transmission of the same, or ancillary services, as required for ensuring reliable services in accordance with good utility practice, if the purchase of the same cannot practically be accomplished through the standard competitive bidding procedures and the contractor is not providing direct retail services to end users.\n(d) (1) A contractor shall not be deemed to discriminate in the provision of benefits if the contractor, in providing the benefits, pays the actual costs incurred in obtaining the benefit.\n(2) If a contractor is unable to provide a certain benefit, despite taking reasonable measures to do so, the contractor shall not be deemed to discriminate in the provision of benefits.\n(e) (1) Every contract subject to this chapter shall contain a statement by which the contractor certifies that the contractor is in compliance with this section.\n(2) The department or other contracting agency shall enforce this section pursuant to its existing enforcement powers.\n(3) (A) If a contractor falsely certifies that it is in compliance with this section, the contract with that contractor shall be subject to Article 9 (commencing with Section 10420), unless, within a time period specified by the department or other contracting agency, the contractor provides to the department or agency proof that it has complied, or is in the process of complying, with this section.\n(B) The application of the remedies or penalties contained in Article 9 (commencing with Section 10420) to a contract subject to this chapter shall not preclude the application of any existing remedies otherwise available to the department or other contracting agency under its existing enforcement powers.\n(f) Nothing in this section is intended to regulate the contracting practices of any local jurisdiction.\n(g) This section shall be construed so as not to conflict with applicable federal laws, rules, or regulations. In the event that a court or agency of competent jurisdiction holds that federal law, rule, or regulation invalidates any clause, sentence, paragraph, or section of this code or the application thereof to any person or circumstances, it is the intent of the state that the court or agency sever that clause, sentence, paragraph, or section so that the remainder of this section shall remain in effect.\nSEC. 2.\nSection 10295.35 of the Public Contract Code shall not be construed to create any new enforcement authority or responsibility in the Department of General Services or any other contracting agency.\nSEC. 3.\nNo reimbursement is required by this act pursuant to Section 6 of Article XIII\u2009B of the California Constitution because the only costs that may be incurred by a local agency or school district will be incurred because this act creates a new crime or infraction, eliminates a crime or infraction, or changes the penalty for a crime or infraction, within the meaning of Section 17556 of the Government Code, or changes the definition of a crime within the meaning of Section 6 of Article XIII\u2009B of the California Constitution.',
78
+ 'title': 'An act to add Section 10295.35 to the Public Contract Code, relating to public contracts.'}
79
+ ```
80
+
81
+ 여기서 다음 두 개의 필드를 사용하게 됩니다:
82
+
83
+ - `text`: 모델의 입력이 될 법안 텍스트입니다.
84
+ - `summary`: `text`의 간략한 버전으로 모델의 타겟이 됩니다.
85
+
86
+ ## 전처리[[preprocess]]
87
+
88
+ 다음으로 `text`와 `summary`를 처리하기 위한 T5 토크나이저를 가져옵니다:
89
+
90
+ ```py
91
+ >>> from transformers import AutoTokenizer
92
+
93
+ >>> checkpoint = "google-t5/t5-small"
94
+ >>> tokenizer = AutoTokenizer.from_pretrained(checkpoint)
95
+ ```
96
+
97
+ 생성하려는 전처리 함수는 아래 조건을 만족해야 합니다:
98
+
99
+ 1. 입력 앞에 프롬프트를 붙여 T5가 요약 작업임을 인식할 수 있도록 합니다. 여러 NLP 작업을 수행할 수 있는 일부 모델은 특정 작업에 대한 프롬프트가 필요합니다.
100
+ 2. 레이블을 토큰화할 때 `text_target` 인수를 사용합니다.
101
+ 3. `max_length` 매개변수로 설정된 최대 길이를 넘지 않도록 긴 시퀀스를 잘라냅니다.
102
+
103
+ ```py
104
+ >>> prefix = "summarize: "
105
+
106
+
107
+ >>> def preprocess_function(examples):
108
+ ... inputs = [prefix + doc for doc in examples["text"]]
109
+ ... model_inputs = tokenizer(inputs, max_length=1024, truncation=True)
110
+
111
+ ... labels = tokenizer(text_target=examples["summary"], max_length=128, truncation=True)
112
+
113
+ ... model_inputs["labels"] = labels["input_ids"]
114
+ ... return model_inputs
115
+ ```
116
+
117
+ 전체 데이터셋에 전처리 함수를 적용하려면 🤗 Datasets의 [`~datasets.Dataset.map`] 메소드를 사용하세요.
118
+ `batched=True`로 설정하여 데이터셋의 여러 요소를 한 번에 처리하면 `map` 함수의 속도를 높일 수 있습니다.
119
+
120
+ ```py
121
+ >>> tokenized_billsum = billsum.map(preprocess_function, batched=True)
122
+ ```
123
+
124
+ 이제 [`DataCollatorForSeq2Seq`]를 사용하여 예제 배치를 만드세요.
125
+ 전체 데이터셋을 최대 길이로 패딩하는 것보다 배치마다 가장 긴 문장 길이에 맞춰 *동적 패딩*하는 것이 더 효율적입니다.
126
+
127
+ <frameworkcontent>
128
+ <pt>
129
+ ```py
130
+ >>> from transformers import DataCollatorForSeq2Seq
131
+
132
+ >>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint)
133
+ ```
134
+ </pt>
135
+ <tf>
136
+ ```py
137
+ >>> from transformers import DataCollatorForSeq2Seq
138
+
139
+ >>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint, return_tensors="tf")
140
+ ```
141
+ </tf>
142
+ </frameworkcontent>
143
+
144
+ ## 평가[[evaluate]]
145
+
146
+ 학습 중에 평가 지표를 포함하면 모델의 성능을 평가하는 데 도움이 되는 경우가 많습니다.
147
+ 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) 라이브러리를 사용하면 평가 방법을 빠르게 불러올 수 있습니다.
148
+ 이 작업에서는 [ROUGE](https://huggingface.co/spaces/evaluate-metric/rouge) 평가 지표를 가져옵니다.
149
+ (평가 지표를 불러오고 계산하는 방법은 🤗 Evaluate [둘러보기](https://huggingface.co/docs/evaluate/a_quick_tour)를 참조하세요.)
150
+
151
+ ```py
152
+ >>> import evaluate
153
+
154
+ >>> rouge = evaluate.load("rouge")
155
+ ```
156
+
157
+ 그런 다음 예측값과 레이블을 [`~evaluate.EvaluationModule.compute`]에 전달하여 ROUGE 지표를 계산하는 함수를 만듭니다:
158
+
159
+ ```py
160
+ >>> import numpy as np
161
+
162
+
163
+ >>> def compute_metrics(eval_pred):
164
+ ... predictions, labels = eval_pred
165
+ ... decoded_preds = tokenizer.batch_decode(predictions, skip_special_tokens=True)
166
+ ... labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
167
+ ... decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
168
+
169
+ ... result = rouge.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True)
170
+
171
+ ... prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in predictions]
172
+ ... result["gen_len"] = np.mean(prediction_lens)
173
+
174
+ ... return {k: round(v, 4) for k, v in result.items()}
175
+ ```
176
+
177
+ 이제 `compute_metrics` 함수를 사용할 준비가 되었으며, 학습을 설정할 때 이 함수로 되돌아올 것입니다.
178
+
179
+ ## 학습[[train]]
180
+
181
+ <frameworkcontent>
182
+ <pt>
183
+ <Tip>
184
+
185
+ 모델을 [`Trainer`]로 파인튜닝 하는 것이 익숙하지 않다면, [여기](../training#train-with-pytorch-trainer)에서 기본 튜토리얼을 확인해보세요!
186
+
187
+ </Tip>
188
+
189
+ 이제 모델 학습을 시작할 준비가 되었습니다! [`AutoModelForSeq2SeqLM`]로 T5를 가져오세요:
190
+
191
+ ```py
192
+ >>> from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer
193
+
194
+ >>> model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint)
195
+ ```
196
+
197
+ 이제 세 단계만 남았습니다:
198
+
199
+ 1. [`Seq2SeqTrainingArguments`]에서 학습 하이퍼파라미터를 정의하세요.
200
+ 유일한 필수 매개변수는 모델을 저장할 위치를 지정하는 `output_dir`입니다.
201
+ `push_to_hub=True`를 설정하�� 이 모델을 Hub에 푸시할 수 있습니다(모델을 업로드하려면 Hugging Face에 로그인해야 합니다.)
202
+ [`Trainer`]는 각 에폭이 끝날 때마다 ROUGE 지표를 평가하고 학습 체크포인트를 저장합니다.
203
+ 2. 모델, 데이터셋, 토크나이저, 데이터 콜레이터 및 `compute_metrics` 함수와 함께 학습 인수를 [`Seq2SeqTrainer`]에 전달하세요.
204
+ 3. [`~Trainer.train`]을 호출하여 모델을 파인튜닝하세요.
205
+
206
+ ```py
207
+ >>> training_args = Seq2SeqTrainingArguments(
208
+ ... output_dir="my_awesome_billsum_model",
209
+ ... eval_strategy="epoch",
210
+ ... learning_rate=2e-5,
211
+ ... per_device_train_batch_size=16,
212
+ ... per_device_eval_batch_size=16,
213
+ ... weight_decay=0.01,
214
+ ... save_total_limit=3,
215
+ ... num_train_epochs=4,
216
+ ... predict_with_generate=True,
217
+ ... fp16=True,
218
+ ... push_to_hub=True,
219
+ ... )
220
+
221
+ >>> trainer = Seq2SeqTrainer(
222
+ ... model=model,
223
+ ... args=training_args,
224
+ ... train_dataset=tokenized_billsum["train"],
225
+ ... eval_dataset=tokenized_billsum["test"],
226
+ ... processing_class=tokenizer,
227
+ ... data_collator=data_collator,
228
+ ... compute_metrics=compute_metrics,
229
+ ... )
230
+
231
+ >>> trainer.train()
232
+ ```
233
+
234
+ 학습이 완료되면, 누구나 모델을 사용할 수 있도록 [`~transformers.Trainer.push_to_hub`] 메소드로 Hub에 공유합니다:
235
+
236
+ ```py
237
+ >>> trainer.push_to_hub()
238
+ ```
239
+ </pt>
240
+ <tf>
241
+ <Tip>
242
+
243
+ Keras로 모델 파인튜닝을 하는 것이 익숙하지 않다면, [여기](../training#train-a-tensorflow-model-with-keras)에서 기본적인 튜토리얼을 확인하세요!
244
+
245
+ </Tip>
246
+ TensorFlow에서 모델을 파인튜닝하려면, 먼저 옵티마이저, 학습률 스케줄 그리고 몇 가지 학습 하이퍼파라미터를 설정하세요:
247
+
248
+ ```py
249
+ >>> from transformers import create_optimizer, AdamWeightDecay
250
+
251
+ >>> optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01)
252
+ ```
253
+
254
+ 그런 다음 [`TFAutoModelForSeq2SeqLM`]을 사용하여 T5를 가져오세요:
255
+
256
+ ```py
257
+ >>> from transformers import TFAutoModelForSeq2SeqLM
258
+
259
+ >>> model = TFAutoModelForSeq2SeqLM.from_pretrained(checkpoint)
260
+ ```
261
+
262
+ [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]을 사용하여 데이터셋을 `tf.data.Dataset` 형식으로 변환하세요:
263
+
264
+ ```py
265
+ >>> tf_train_set = model.prepare_tf_dataset(
266
+ ... tokenized_billsum["train"],
267
+ ... shuffle=True,
268
+ ... batch_size=16,
269
+ ... collate_fn=data_collator,
270
+ ... )
271
+
272
+ >>> tf_test_set = model.prepare_tf_dataset(
273
+ ... tokenized_billsum["test"],
274
+ ... shuffle=False,
275
+ ... batch_size=16,
276
+ ... collate_fn=data_collator,
277
+ ... )
278
+ ```
279
+
280
+ [`compile`](https://keras.io/api/models/model_training_apis/#compile-method)을 사용하여 모델을 학습할 수 있도록 구성하세요:
281
+
282
+ ```py
283
+ >>> import tensorflow as tf
284
+
285
+ >>> model.compile(optimizer=optimizer)
286
+ ```
287
+
288
+ 학습을 시작하기 전에 설정해야 할 마지막 두 가지는 예측에서 ROUGE 점수를 계산하고 모델을 Hub에 푸시하는 방법을 제공하는 것입니다.
289
+ 두 작업 모두 [Keras callbacks](../main_classes/keras_callbacks)으로 수행할 수 있습니다.
290
+
291
+ [`~transformers.KerasMetricCallback`]에 `compute_metrics` 함수를 전달하세요:
292
+
293
+ ```py
294
+ >>> from transformers.keras_callbacks import KerasMetricCallback
295
+
296
+ >>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set)
297
+ ```
298
+
299
+ [`~transformers.PushToHubCallback`]에서 모델과 토크나이저를 푸시할 위치를 지정하세요:
300
+
301
+ ```py
302
+ >>> from transformers.keras_callbacks import PushToHubCallback
303
+
304
+ >>> push_to_hub_callback = PushToHubCallback(
305
+ ... output_dir="my_awesome_billsum_model",
306
+ ... tokenizer=tokenizer,
307
+ ... )
308
+ ```
309
+
310
+ 그런 다음 콜백을 번들로 묶어줍니다:
311
+
312
+ ```py
313
+ >>> callbacks = [metric_callback, push_to_hub_callback]
314
+ ```
315
+
316
+ 드디어 모델 학습을 시작할 준비가 되었습니다!
317
+ 학습 및 검증 데이터셋, 에폭 수 및 콜백과 함께 [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)을 호출하여 모델을 파인튜닝하세요.
318
+
319
+ ```py
320
+ >>> model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=callbacks)
321
+ ```
322
+
323
+ 학습이 완료되면 모델이 자동으로 Hub에 업로드되어 누구나 사용할 수 있게 됩니다!
324
+ </tf>
325
+ </frameworkcontent>
326
+
327
+ <Tip>
328
+
329
+ 요약을 위해 모델을 파인튜닝하는 방법에 대한 더 자세한 예제를 보려면 [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization.ipynb)
330
+ 또는 [TensorFlow notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization-tf.ipynb)을 참고하세요.
331
+
332
+ </Tip>
333
+
334
+ ## 추론[[inference]]
335
+
336
+ 좋아요, 이제 모델을 파인튜닝했으니 추론에 사용할 수 있습니다!
337
+
338
+ 요약할 텍스트를 작성해보세요. T5의 경우 작업에 따라 입력 앞에 접두사를 붙여야 합니다. 요약의 경우, 아래와 같은 접두사를 입력 앞에 붙여야 ���니다:
339
+
340
+ ```py
341
+ >>> text = "summarize: The Inflation Reduction Act lowers prescription drug costs, health care costs, and energy costs. It's the most aggressive action on tackling the climate crisis in American history, which will lift up American workers and create good-paying, union jobs across the country. It'll lower the deficit and ask the ultra-wealthy and corporations to pay their fair share. And no one making under $400,000 per year will pay a penny more in taxes."
342
+ ```
343
+
344
+ 추론을 위해 파인튜닝한 모델을 시험해 보는 가장 간단한 방법은 [`pipeline`]에서 사용하는 것입니다.
345
+ 모델을 사용하여 요약을 수행할 [`pipeline`]을 인스턴스화하고 텍스트를 전달하세요:
346
+
347
+ ```py
348
+ >>> from transformers import pipeline
349
+
350
+ >>> summarizer = pipeline("summarization", model="stevhliu/my_awesome_billsum_model")
351
+ >>> summarizer(text)
352
+ [{"summary_text": "The Inflation Reduction Act lowers prescription drug costs, health care costs, and energy costs. It's the most aggressive action on tackling the climate crisis in American history, which will lift up American workers and create good-paying, union jobs across the country."}]
353
+ ```
354
+
355
+ 원한다면 수동으로 다음과 같은 작업을 수행하여 [`pipeline`]의 결과와 동일한 결과를 얻을 수 있습니다:
356
+
357
+
358
+ <frameworkcontent>
359
+ <pt>
360
+ 텍스트를 토크나이즈하고 `input_ids`를 PyTorch 텐서로 반환합니다:
361
+
362
+ ```py
363
+ >>> from transformers import AutoTokenizer
364
+
365
+ >>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_billsum_model")
366
+ >>> inputs = tokenizer(text, return_tensors="pt").input_ids
367
+ ```
368
+
369
+ 요약문을 생성하려면 [`~generation.GenerationMixin.generate`] 메소드를 사용하세요.
370
+ 텍스트 생성에 대한 다양한 전략과 생성을 제어하기 위한 매개변수에 대한 자세한 내용은 [텍스트 생성](../main_classes/text_generation) API를 참조하세요.
371
+
372
+ ```py
373
+ >>> from transformers import AutoModelForSeq2SeqLM
374
+
375
+ >>> model = AutoModelForSeq2SeqLM.from_pretrained("stevhliu/my_awesome_billsum_model")
376
+ >>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=False)
377
+ ```
378
+
379
+ 생성된 토큰 ID를 텍스트로 디코딩합니다:
380
+
381
+ ```py
382
+ >>> tokenizer.decode(outputs[0], skip_special_tokens=True)
383
+ 'the inflation reduction act lowers prescription drug costs, health care costs, and energy costs. it's the most aggressive action on tackling the climate crisis in american history. it will ask the ultra-wealthy and corporations to pay their fair share.'
384
+ ```
385
+ </pt>
386
+ <tf>
387
+ 텍스트를 토크나이즈하고 `input_ids`를 TensorFlow 텐서로 반환합니다:
388
+
389
+ ```py
390
+ >>> from transformers import AutoTokenizer
391
+
392
+ >>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_billsum_model")
393
+ >>> inputs = tokenizer(text, return_tensors="tf").input_ids
394
+ ```
395
+
396
+ 요약문을 생성하려면 [`~transformers.generation_tf_utils.TFGenerationMixin.generate`] 메소드를 사용하세요.
397
+ 텍스트 생성에 대한 다양한 전략과 생성을 제어하기 위한 매개변수에 대한 자세한 내용은 [텍스트 생성](../main_classes/text_generation) API를 참조하세요.
398
+
399
+ ```py
400
+ >>> from transformers import TFAutoModelForSeq2SeqLM
401
+
402
+ >>> model = TFAutoModelForSeq2SeqLM.from_pretrained("stevhliu/my_awesome_billsum_model")
403
+ >>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=False)
404
+ ```
405
+
406
+ 생성된 토큰 ID를 텍스트로 디코딩합니다:
407
+
408
+ ```py
409
+ >>> tokenizer.decode(outputs[0], skip_special_tokens=True)
410
+ 'the inflation reduction act lowers prescription drug costs, health care costs, and energy costs. it's the most aggressive action on tackling the climate crisis in american history. it will ask the ultra-wealthy and corporations to pay their fair share.'
411
+ ```
412
+ </tf>
413
+ </frameworkcontent>
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/token_classification.md ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # 토큰 분류[[token-classification]]
18
+
19
+ [[open-in-colab]]
20
+
21
+ <Youtube id="wVHdVlPScxA"/>
22
+
23
+ 토큰 분류는 문장의 개별 토큰에 레이블을 할당합니다. 가장 일반적인 토큰 분류 작업 중 하나는 개체명 인식(Named Entity Recognition, NER)입니다. 개체명 인식은 문장에서 사람, 위치 또는 조직과 같은 각 개체의 레이블을 찾으려고 시도합니다.
24
+
25
+ 이 가이드에서 학습할 내용은:
26
+
27
+ 1. [WNUT 17](https://huggingface.co/datasets/wnut_17) 데이터 세트에서 [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased)를 파인 튜닝하여 새로운 개체를 탐지합니다.
28
+ 2. 추론을 위해 파인 튜닝 모델을 사용합니다.
29
+
30
+ <Tip>
31
+
32
+ 이 작업과 호환되는 모든 아키텍처와 체크포인트를 보려면 [작업 페이지](https://huggingface.co/tasks/token-classification)를 확인하는 것이 좋습니다.
33
+
34
+ </Tip>
35
+
36
+ 시작하기 전에, 필요한 모든 라이브러리가 설치되어 있는지 확인하세요:
37
+
38
+ ```bash
39
+ pip install transformers datasets evaluate seqeval
40
+ ```
41
+
42
+ Hugging Face 계정에 로그인하여 모델을 업로드하고 커뮤니티에 공유하는 것을 권장합니다. 메시지가 표시되면, 토큰을 입력하여 로그인하세요:
43
+
44
+ ```py
45
+ >>> from huggingface_hub import notebook_login
46
+
47
+ >>> notebook_login()
48
+ ```
49
+
50
+ ## WNUT 17 데이터 세트 가져오기[[load-wnut-17-dataset]]
51
+
52
+ 먼저 🤗 Datasets 라이브러리에서 WNUT 17 데이터 세트를 가져옵니다:
53
+
54
+ ```py
55
+ >>> from datasets import load_dataset
56
+
57
+ >>> wnut = load_dataset("wnut_17")
58
+ ```
59
+
60
+ 다음 예제를 살펴보세요:
61
+
62
+ ```py
63
+ >>> wnut["train"][0]
64
+ {'id': '0',
65
+ 'ner_tags': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0],
66
+ 'tokens': ['@paulwalk', 'It', "'s", 'the', 'view', 'from', 'where', 'I', "'m", 'living', 'for', 'two', 'weeks', '.', 'Empire', 'State', 'Building', '=', 'ESB', '.', 'Pretty', 'bad', 'storm', 'here', 'last', 'evening', '.']
67
+ }
68
+ ```
69
+
70
+ `ner_tags`의 각 숫자는 개체를 나타냅니다. 숫자를 레이블 이름으로 변환하여 개체가 무엇인지 확인합니다:
71
+
72
+ ```py
73
+ >>> label_list = wnut["train"].features[f"ner_tags"].feature.names
74
+ >>> label_list
75
+ [
76
+ "O",
77
+ "B-corporation",
78
+ "I-corporation",
79
+ "B-creative-work",
80
+ "I-creative-work",
81
+ "B-group",
82
+ "I-group",
83
+ "B-location",
84
+ "I-location",
85
+ "B-person",
86
+ "I-person",
87
+ "B-product",
88
+ "I-product",
89
+ ]
90
+ ```
91
+
92
+ 각 `ner_tag`의 앞에 붙은 문자는 개체의 토큰 위치를 나타냅니다:
93
+
94
+ - `B-`는 개체의 시작을 나타냅니다.
95
+ - `I-`는 토큰이 동일한 개체 내부에 포함되어 있음을 나타냅니다(예를 들어 `State` 토큰은 `Empire State Building`와 같은 개체의 일부입니다).
96
+ - `0`는 토큰이 어떤 개체에도 해당하지 않음을 나타냅니다.
97
+
98
+ ## 전처리[[preprocess]]
99
+
100
+ <Youtube id="iY2AZYdZAr0"/>
101
+
102
+ 다음으로 `tokens` 필드를 전처리하기 위해 DistilBERT 토크나이저를 가져옵니다:
103
+
104
+ ```py
105
+ >>> from transformers import AutoTokenizer
106
+
107
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
108
+ ```
109
+
110
+ 위의 예제 `tokens` 필드를 보면 입력이 이미 토큰화된 것처럼 보입니다. 그러나 실제로 입력은 아직 토큰화되지 않았으므로 단어를 하위 단어로 토큰화하기 위해 `is_split_into_words=True`를 설정해야 합니다. 예제로 확인합니다:
111
+
112
+ ```py
113
+ >>> example = wnut["train"][0]
114
+ >>> tokenized_input = tokenizer(example["tokens"], is_split_into_words=True)
115
+ >>> tokens = tokenizer.convert_ids_to_tokens(tokenized_input["input_ids"])
116
+ >>> tokens
117
+ ['[CLS]', '@', 'paul', '##walk', 'it', "'", 's', 'the', 'view', 'from', 'where', 'i', "'", 'm', 'living', 'for', 'two', 'weeks', '.', 'empire', 'state', 'building', '=', 'es', '##b', '.', 'pretty', 'bad', 'storm', 'here', 'last', 'evening', '.', '[SEP]']
118
+ ```
119
+
120
+ 그러나 이로 인해 `[CLS]`과 `[SEP]`라는 특수 토큰이 추가되고, 하위 단어 토큰화로 인해 입력과 레이블 간에 불일치가 발생합니다. 하나의 레이블에 해당하는 단일 단어는 이제 두 개의 하위 단어로 분할될 수 있습니다. 토큰과 레이블을 다음�� 같이 재정렬해야 합니다:
121
+
122
+ 1. [`word_ids`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.BatchEncoding.word_ids) 메소드로 모든 토큰을 해당 단어에 매핑합니다.
123
+ 2. 특수 토큰 `[CLS]`와 `[SEP]`에 `-100` 레이블을 할당하여, PyTorch 손실 함수가 해당 토큰을 무시하도록 합니다.
124
+ 3. 주어진 단어의 첫 번째 토큰에만 레이블을 지정합니다. 같은 단어의 다른 하위 토큰에 `-100`을 할당합니다.
125
+
126
+ 다음은 토큰과 레이블을 재정렬하고 DistilBERT의 최대 입력 길이보다 길지 않도록 시퀀스를 잘라내는 함수를 만드는 방법입니다:
127
+
128
+ ```py
129
+ >>> def tokenize_and_align_labels(examples):
130
+ ... tokenized_inputs = tokenizer(examples["tokens"], truncation=True, is_split_into_words=True)
131
+
132
+ ... labels = []
133
+ ... for i, label in enumerate(examples[f"ner_tags"]):
134
+ ... word_ids = tokenized_inputs.word_ids(batch_index=i) # Map tokens to their respective word.
135
+ ... previous_word_idx = None
136
+ ... label_ids = []
137
+ ... for word_idx in word_ids: # Set the special tokens to -100.
138
+ ... if word_idx is None:
139
+ ... label_ids.append(-100)
140
+ ... elif word_idx != previous_word_idx: # Only label the first token of a given word.
141
+ ... label_ids.append(label[word_idx])
142
+ ... else:
143
+ ... label_ids.append(-100)
144
+ ... previous_word_idx = word_idx
145
+ ... labels.append(label_ids)
146
+
147
+ ... tokenized_inputs["labels"] = labels
148
+ ... return tokenized_inputs
149
+ ```
150
+
151
+ 전체 데이터 세트에 전처리 함수를 적용하려면, 🤗 Datasets [`~datasets.Dataset.map`] 함수를 사용하세요. `batched=True`로 설정하여 데이터 세트의 여러 요소를 한 번에 처리하면 `map` 함수의 속도를 높일 수 있습니다:
152
+ ```py
153
+ >>> tokenized_wnut = wnut.map(tokenize_and_align_labels, batched=True)
154
+ ```
155
+
156
+ 이제 [`DataCollatorWithPadding`]를 사용하여 예제 배치를 만들어봅시다. 데이터 세트 전체를 최대 길이로 패딩하는 대신, *동적 패딩*을 사용하여 배치에서 가장 긴 길이에 맞게 문장을 패딩하는 것이 효율적입니다.
157
+
158
+ <frameworkcontent>
159
+ <pt>
160
+ ```py
161
+ >>> from transformers import DataCollatorForTokenClassification
162
+
163
+ >>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)
164
+ ```
165
+ </pt>
166
+ <tf>
167
+ ```py
168
+ >>> from transformers import DataCollatorForTokenClassification
169
+
170
+ >>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer, return_tensors="tf")
171
+ ```
172
+ </tf>
173
+ </frameworkcontent>
174
+
175
+ ## 평가[[evaluation]]
176
+
177
+ 훈련 중 모델의 성능을 평가하기 위해 평가 지표를 포함하는 것이 유용합니다. 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) 라이브러리를 사용하여 빠르게 평가 방법을 가져올 수 있습니다. 이 작업에서는 [seqeval](https://huggingface.co/spaces/evaluate-metric/seqeval) 평가 지표를 가져옵니다. (평가 지표를 가져오고 계산하는 방법에 대해서는 🤗 Evaluate [빠른 둘러보기](https://huggingface.co/docs/evaluate/a_quick_tour)를 참조하세요). Seqeval은 실제로 정밀도, 재현률, F1 및 정확도와 같은 여러 점수를 산출합니다.
178
+
179
+ ```py
180
+ >>> import evaluate
181
+
182
+ >>> seqeval = evaluate.load("seqeval")
183
+ ```
184
+
185
+ 먼저 NER 레이블을 가져온 다음, [`~evaluate.EvaluationModule.compute`]에 실제 예측과 실제 레이블을 전달하여 점수를 계산하는 함수를 만듭니다:
186
+
187
+ ```py
188
+ >>> import numpy as np
189
+
190
+ >>> labels = [label_list[i] for i in example[f"ner_tags"]]
191
+
192
+
193
+ >>> def compute_metrics(p):
194
+ ... predictions, labels = p
195
+ ... predictions = np.argmax(predictions, axis=2)
196
+
197
+ ... true_predictions = [
198
+ ... [label_list[p] for (p, l) in zip(prediction, label) if l != -100]
199
+ ... for prediction, label in zip(predictions, labels)
200
+ ... ]
201
+ ... true_labels = [
202
+ ... [label_list[l] for (p, l) in zip(prediction, label) if l != -100]
203
+ ... for prediction, label in zip(predictions, labels)
204
+ ... ]
205
+
206
+ ... results = seqeval.compute(predictions=true_predictions, references=true_labels)
207
+ ... return {
208
+ ... "precision": results["overall_precision"],
209
+ ... "recall": results["overall_recall"],
210
+ ... "f1": results["overall_f1"],
211
+ ... "accuracy": results["overall_accuracy"],
212
+ ... }
213
+ ```
214
+
215
+ 이제 `compute_metrics` 함수를 사용할 준비가 되었으며, 훈련을 설정하면 이 함수로 되돌아올 것입니다.
216
+
217
+ ## 훈련[[train]]
218
+
219
+ 모델을 훈련하기 전에, `id2label`와 `label2id`를 사용하여 예상되는 id와 레이블의 맵을 생성하세요:
220
+
221
+ ```py
222
+ >>> id2label = {
223
+ ... 0: "O",
224
+ ... 1: "B-corporation",
225
+ ... 2: "I-corporation",
226
+ ... 3: "B-creative-work",
227
+ ... 4: "I-creative-work",
228
+ ... 5: "B-group",
229
+ ... 6: "I-group",
230
+ ... 7: "B-location",
231
+ ... 8: "I-location",
232
+ ... 9: "B-person",
233
+ ... 10: "I-person",
234
+ ... 11: "B-product",
235
+ ... 12: "I-product",
236
+ ... }
237
+ >>> label2id = {
238
+ ... "O": 0,
239
+ ... "B-corporation": 1,
240
+ ... "I-corporation": 2,
241
+ ... "B-creative-work": 3,
242
+ ... "I-creative-work": 4,
243
+ ... "B-group": 5,
244
+ ... "I-group": 6,
245
+ ... "B-location": 7,
246
+ ... "I-location": 8,
247
+ ... "B-person": 9,
248
+ ... "I-person": 10,
249
+ ... "B-product": 11,
250
+ ... "I-product": 12,
251
+ ... }
252
+ ```
253
+
254
+ <frameworkcontent>
255
+ <pt>
256
+ <Tip>
257
+
258
+ [`Trainer`]를 사용하여 모델을 파인 튜닝하는 방법에 익숙하지 않은 경우, [여기](../training#train-with-pytorch-trainer)에서 기본 튜토리얼을 확인하세요!
259
+
260
+ </Tip>
261
+
262
+ 이제 모델을 훈련시킬 준비가 되었습니다! [`AutoModelForSequenceClassification`]로 DistilBERT를 가져오고 예상되는 레이블 수와 레이블 매핑을 지정하세요:
263
+
264
+ ```py
265
+ >>> from transformers import AutoModelForTokenClassification, TrainingArguments, Trainer
266
+
267
+ >>> model = AutoModelForTokenClassification.from_pretrained(
268
+ ... "distilbert/distilbert-base-uncased", num_labels=13, id2label=id2label, label2id=label2id
269
+ ... )
270
+ ```
271
+
272
+ 이제 세 단계만 거치면 끝입니다:
273
+
274
+ 1. [`TrainingArguments`]에서 하이퍼파라미터를 정의하세요. `output_dir`는 모델을 저장할 위치를 지정하는 유일한 매개변수입니다. 이 모델을 허브에 업로드하기 위해 `push_to_hub=True`를 설정합니다(모델을 업로드하기 위해 Hugging Face에 로그인해야합니다.) 각 에폭이 끝날 때마다, [`Trainer`]는 seqeval 점수를 평가하고 훈련 체크포인트를 저장합니다.
275
+ 2. [`Trainer`]에 훈련 인수와 모델, 데이터 세트, 토크나이저, 데이터 콜레이터 및 `compute_metrics` 함수를 전달하세요.
276
+ 3. [`~Trainer.train`]를 호출하여 모델을 파인 튜닝하세요.
277
+
278
+ ```py
279
+ >>> training_args = TrainingArguments(
280
+ ... output_dir="my_awesome_wnut_model",
281
+ ... learning_rate=2e-5,
282
+ ... per_device_train_batch_size=16,
283
+ ... per_device_eval_batch_size=16,
284
+ ... num_train_epochs=2,
285
+ ... weight_decay=0.01,
286
+ ... eval_strategy="epoch",
287
+ ... save_strategy="epoch",
288
+ ... load_best_model_at_end=True,
289
+ ... push_to_hub=True,
290
+ ... )
291
+
292
+ >>> trainer = Trainer(
293
+ ... model=model,
294
+ ... args=training_args,
295
+ ... train_dataset=tokenized_wnut["train"],
296
+ ... eval_dataset=tokenized_wnut["test"],
297
+ ... processing_class=tokenizer,
298
+ ... data_collator=data_collator,
299
+ ... compute_metrics=compute_metrics,
300
+ ... )
301
+
302
+ >>> trainer.train()
303
+ ```
304
+
305
+ 훈련이 완료되면, [`~transformers.Trainer.push_to_hub`] 메소드를 사용하여 모델을 허브에 공유할 수 있습니다.
306
+
307
+ ```py
308
+ >>> trainer.push_to_hub()
309
+ ```
310
+ </pt>
311
+ <tf>
312
+ <Tip>
313
+
314
+ Keras를 사용하여 모델을 파인 튜닝하는 방법에 익숙하지 않은 경우, [여기](../training#train-a-tensorflow-model-with-keras)의 기본 튜토리얼을 확인하세요!
315
+
316
+ </Tip>
317
+ TensorFlow에서 모델을 파인 튜닝하려면, 먼저 옵티마이저 함수와 학습률 스케쥴, 그리고 일부 훈련 하이퍼파라미터를 설정해야 합니다:
318
+
319
+ ```py
320
+ >>> from transformers import create_optimizer
321
+
322
+ >>> batch_size = 16
323
+ >>> num_train_epochs = 3
324
+ >>> num_train_steps = (len(tokenized_wnut["train"]) // batch_size) * num_train_epochs
325
+ >>> optimizer, lr_schedule = create_optimizer(
326
+ ... init_lr=2e-5,
327
+ ... num_train_steps=num_train_steps,
328
+ ... weight_decay_rate=0.01,
329
+ ... num_warmup_steps=0,
330
+ ... )
331
+ ```
332
+
333
+ 그런 다음 [`TFAutoModelForSequenceClassification`]을 사용하여 DistilBERT를 가져오고, 예상되는 레이블 수와 레이블 매핑을 지정합니다:
334
+
335
+ ```py
336
+ >>> from transformers import TFAutoModelForTokenClassification
337
+
338
+ >>> model = TFAutoModelForTokenClassification.from_pretrained(
339
+ ... "distilbert/distilbert-base-uncased", num_labels=13, id2label=id2label, label2id=label2id
340
+ ... )
341
+ ```
342
+
343
+ [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]을 사용하여 데이터 세트를 `tf.data.Dataset` 형식으로 변환합니다:
344
+
345
+ ```py
346
+ >>> tf_train_set = model.prepare_tf_dataset(
347
+ ... tokenized_wnut["train"],
348
+ ... shuffle=True,
349
+ ... batch_size=16,
350
+ ... collate_fn=data_collator,
351
+ ... )
352
+
353
+ >>> tf_validation_set = model.prepare_tf_dataset(
354
+ ... tokenized_wnut["validation"],
355
+ ... shuffle=False,
356
+ ... batch_size=16,
357
+ ... collate_fn=data_collator,
358
+ ... )
359
+ ```
360
+
361
+ [`compile`](https://keras.io/api/models/model_training_apis/#compile-method)를 사용하여 훈련할 모델을 구성합니다:
362
+
363
+ ```py
364
+ >>> import tensorflow as tf
365
+
366
+ >>> model.compile(optimizer=optimizer)
367
+ ```
368
+
369
+ 훈련을 시작하기 전에 설정해야할 마지막 두 가지는 예측에서 seqeval 점수를 계산하고, 모델을 허브에 업로드할 방법을 제공하는 것입니다. 모두 [Keras callbacks](../main_classes/keras_callbacks)를 사용하여 수행됩니다.
370
+
371
+ [`~transformers.KerasMetricCallback`]에 `compute_metrics` 함수를 전달하세요:
372
+
373
+ ```py
374
+ >>> from transformers.keras_callbacks import KerasMetricCallback
375
+
376
+ >>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set)
377
+ ```
378
+
379
+ [`~transformers.PushToHubCallback`]에서 모델과 토크나이저를 업로드할 위치를 지정합니다:
380
+
381
+ ```py
382
+ >>> from transformers.keras_callbacks import PushToHubCallback
383
+
384
+ >>> push_to_hub_callback = PushToHubCallback(
385
+ ... output_dir="my_awesome_wnut_model",
386
+ ... tokenizer=tokenizer,
387
+ ... )
388
+ ```
389
+
390
+ 그런 다음 콜백을 함께 묶습니다:
391
+
392
+ ```py
393
+ >>> callbacks = [metric_callback, push_to_hub_callback]
394
+ ```
395
+
396
+ 드디어, 모델 훈련을 시작할 준비가 되었습니다! [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)에 훈련 데이터 세트, 검증 데이터 세트, 에폭의 수 및 콜백을 전달하여 파인 튜닝합니다:
397
+
398
+ ```py
399
+ >>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3, callbacks=callbacks)
400
+ ```
401
+
402
+ 훈련이 완료되면, 모델이 자동으로 허브에 업로드되어 누구나 사용할 수 있습니다!
403
+ </tf>
404
+ </frameworkcontent>
405
+
406
+ <Tip>
407
+
408
+ 토큰 분류를 위한 모델을 파인 튜닝하는 자세한 예제는 다음
409
+ [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb)
410
+ 또는 [TensorFlow notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb)를 참조하세요.
411
+
412
+ </Tip>
413
+
414
+ ## 추론[[inference]]
415
+
416
+ 좋아요, 이제 모델을 파인 튜닝했으니 추론에 사용할 수 있습니다!
417
+
418
+ 추론을 수행하고자 하는 텍스트를 가져와봅시다:
419
+
420
+ ```py
421
+ >>> text = "The Golden State Warriors are an American professional basketball team based in San Francisco."
422
+ ```
423
+
424
+ 파인 튜닝된 모델로 추론을 시도하는 가장 간단한 방법은 [`pipeline`]를 사용하는 것입니다. 모델로 NER의 `pipeline`을 인스턴스화하고, 텍스트를 전달해보세요:
425
+
426
+ ```py
427
+ >>> from transformers import pipeline
428
+
429
+ >>> classifier = pipeline("ner", model="stevhliu/my_awesome_wnut_model")
430
+ >>> classifier(text)
431
+ [{'entity': 'B-location',
432
+ 'score': 0.42658573,
433
+ 'index': 2,
434
+ 'word': 'golden',
435
+ 'start': 4,
436
+ 'end': 10},
437
+ {'entity': 'I-location',
438
+ 'score': 0.35856336,
439
+ 'index': 3,
440
+ 'word': 'state',
441
+ 'start': 11,
442
+ 'end': 16},
443
+ {'entity': 'B-group',
444
+ 'score': 0.3064001,
445
+ 'index': 4,
446
+ 'word': 'warriors',
447
+ 'start': 17,
448
+ 'end': 25},
449
+ {'entity': 'B-location',
450
+ 'score': 0.65523505,
451
+ 'index': 13,
452
+ 'word': 'san',
453
+ 'start': 80,
454
+ 'end': 83},
455
+ {'entity': 'B-location',
456
+ 'score': 0.4668663,
457
+ 'index': 14,
458
+ 'word': 'francisco',
459
+ 'start': 84,
460
+ 'end': 93}]
461
+ ```
462
+
463
+ 원한다면, `pipeline`의 결과를 수동으로 복제할 수도 있습니다:
464
+
465
+ <frameworkcontent>
466
+ <pt>
467
+ 텍스트를 토큰화하고 PyTorch 텐서를 반환합니다:
468
+
469
+ ```py
470
+ >>> from transformers import AutoTokenizer
471
+
472
+ >>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_wnut_model")
473
+ >>> inputs = tokenizer(text, return_tensors="pt")
474
+ ```
475
+
476
+ 입력을 모델에 전달하고 `logits`을 반환합니다:
477
+
478
+ ```py
479
+ >>> from transformers import AutoModelForTokenClassification
480
+
481
+ >>> model = AutoModelForTokenClassification.from_pretrained("stevhliu/my_awesome_wnut_model")
482
+ >>> with torch.no_grad():
483
+ ... logits = model(**inputs).logits
484
+ ```
485
+
486
+ 가장 높은 확률을 가진 클래스를 모델의 `id2label` 매핑을 사용하여 텍스트 레이블로 변환합니다:
487
+
488
+ ```py
489
+ >>> predictions = torch.argmax(logits, dim=2)
490
+ >>> predicted_token_class = [model.config.id2label[t.item()] for t in predictions[0]]
491
+ >>> predicted_token_class
492
+ ['O',
493
+ 'O',
494
+ 'B-location',
495
+ 'I-location',
496
+ 'B-group',
497
+ 'O',
498
+ 'O',
499
+ 'O',
500
+ 'O',
501
+ 'O',
502
+ 'O',
503
+ 'O',
504
+ 'O',
505
+ 'B-location',
506
+ 'B-location',
507
+ 'O',
508
+ 'O']
509
+ ```
510
+ </pt>
511
+ <tf>
512
+ 텍스트를 토큰화하고 TensorFlow 텐서를 반환합니다:
513
+
514
+ ```py
515
+ >>> from transformers import AutoTokenizer
516
+
517
+ >>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_wnut_model")
518
+ >>> inputs = tokenizer(text, return_tensors="tf")
519
+ ```
520
+
521
+ 입력값을 모델에 전달하고 `logits`을 반환합니다:
522
+
523
+ ```py
524
+ >>> from transformers import TFAutoModelForTokenClassification
525
+
526
+ >>> model = TFAutoModelForTokenClassification.from_pretrained("stevhliu/my_awesome_wnut_model")
527
+ >>> logits = model(**inputs).logits
528
+ ```
529
+
530
+ 가장 높은 확률을 가진 클래스를 모델의 `id2label` 매핑을 사용하여 텍스트 레이블로 변환합니다:
531
+
532
+ ```py
533
+ >>> predicted_token_class_ids = tf.math.argmax(logits, axis=-1)
534
+ >>> predicted_token_class = [model.config.id2label[t] for t in predicted_token_class_ids[0].numpy().tolist()]
535
+ >>> predicted_token_class
536
+ ['O',
537
+ 'O',
538
+ 'B-location',
539
+ 'I-location',
540
+ 'B-group',
541
+ 'O',
542
+ 'O',
543
+ 'O',
544
+ 'O',
545
+ 'O',
546
+ 'O',
547
+ 'O',
548
+ 'O',
549
+ 'B-location',
550
+ 'B-location',
551
+ 'O',
552
+ 'O']
553
+ ```
554
+ </tf>
555
+ </frameworkcontent>
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/translation.md ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # 번역[[translation]]
18
+
19
+ [[open-in-colab]]
20
+
21
+ <Youtube id="1JvfrvZgi6c"/>
22
+
23
+ 번역은 한 언어로 된 시퀀스를 다른 언어로 변환합니다. 번역이나 요약은 입력을 받아 일련의 출력을 반환하는 강력한 프레임워크인 시퀀스-투-시퀀스 문제로 구성할 수 있는 대표적인 태스크입니다. 번역 시스템은 일반적으로 다른 언어로 된 텍스트 간의 번역에 사용되지만, 음성 간의 통역이나 텍스트-음성 또는 음성-텍스트와 같은 조합에도 사용될 수 있습니다.
24
+
25
+ 이 가이드에서 학습할 내용은:
26
+
27
+ 1. 영어 텍스트를 프랑스어로 번역하기 위해 [T5](https://huggingface.co/google-t5/t5-small) 모델을 OPUS Books 데이터세트의 영어-프랑스어 하위 집합으로 파인튜닝하는 방법과
28
+ 2. 파인튜닝된 모델을 추론에 사용하는 방법입니다.
29
+
30
+ <Tip>
31
+
32
+ 이 작업과 호환되는 모든 아키텍처와 체크포인트를 보려면 [작업 페이지](https://huggingface.co/tasks/translation)를 확인하는 것이 좋습니다.
33
+
34
+ </Tip>
35
+
36
+ 시작하기 전에 필요한 라이브러리가 모두 설치되어 있는지 확인하세요:
37
+
38
+ ```bash
39
+ pip install transformers datasets evaluate sacrebleu
40
+ ```
41
+
42
+ 모델을 업로드하고 커뮤니티와 공유할 수 있도록 Hugging Face 계정에 로그인하는 것이 좋습니다. 새로운 창이 표시되면 토큰을 입력하여 로그인하세요.
43
+
44
+ ```py
45
+ >>> from huggingface_hub import notebook_login
46
+
47
+ >>> notebook_login()
48
+ ```
49
+
50
+ ## OPUS Books 데이터세트 가져오기[[load-opus-books-dataset]]
51
+
52
+ 먼저 🤗 Datasets 라이브러리에서 [OPUS Books](https://huggingface.co/datasets/opus_books) 데이터세트의 영어-프랑스어 하위 집합을 가져오세요.
53
+
54
+ ```py
55
+ >>> from datasets import load_dataset
56
+
57
+ >>> books = load_dataset("opus_books", "en-fr")
58
+ ```
59
+
60
+ 데이터세트를 [`~datasets.Dataset.train_test_split`] 메서드를 사용하여 훈련 및 테스트 데이터로 분할하세요.
61
+
62
+ ```py
63
+ >>> books = books["train"].train_test_split(test_size=0.2)
64
+ ```
65
+
66
+ 훈련 데이터에서 예시를 살펴볼까요?
67
+
68
+ ```py
69
+ >>> books["train"][0]
70
+ {'id': '90560',
71
+ 'translation': {'en': 'But this lofty plateau measured only a few fathoms, and soon we reentered Our Element.',
72
+ 'fr': 'Mais ce plateau élevé ne mesurait que quelques toises, et bientôt nous fûmes rentrés dans notre élément.'}}
73
+ ```
74
+
75
+ 반환된 딕셔너리의 `translation` 키가 텍스트의 영어, 프랑스어 버전을 포함하고 있는 것을 볼 수 있습니다.
76
+
77
+ ## 전처리[[preprocess]]
78
+
79
+ <Youtube id="XAR8jnZZuUs"/>
80
+
81
+ 다음 단계로 영어-프랑스어 쌍을 처리하기 위해 T5 토크나이저를 가져오세요.
82
+
83
+ ```py
84
+ >>> from transformers import AutoTokenizer
85
+
86
+ >>> checkpoint = "google-t5/t5-small"
87
+ >>> tokenizer = AutoTokenizer.from_pretrained(checkpoint)
88
+ ```
89
+
90
+ 만들 전처리 함수는 아래 요구사항을 충족해야 합니다:
91
+
92
+ 1. T5가 번역 태스크임을 인지할 수 있도록 입력 앞에 프롬프트를 추가하세요. 여러 NLP 태스크를 할 수 있는 모델 중 일부는 이렇게 태스크 프롬프트를 미리 줘야합니다.
93
+ 2. 원어(영어)과 번역어(프랑스어)를 별도로 토큰화하세요. 영어 어휘로 사전 학습된 토크나이저로 프랑스어 텍스트를 토큰화할 수는 없기 때문입니다.
94
+ 3. `max_length` 매개변수로 설정한 최대 길이보다 길지 않도록 시퀀스를 truncate하세요.
95
+
96
+ ```py
97
+ >>> source_lang = "en"
98
+ >>> target_lang = "fr"
99
+ >>> prefix = "translate English to French: "
100
+
101
+
102
+ >>> def preprocess_function(examples):
103
+ ... inputs = [prefix + example[source_lang] for example in examples["translation"]]
104
+ ... targets = [example[target_lang] for example in examples["translation"]]
105
+ ... model_inputs = tokenizer(inputs, text_target=targets, max_length=128, truncation=True)
106
+ ... return model_inputs
107
+ ```
108
+
109
+ 전체 데이터세트에 전처리 함수를 적용하려면 🤗 Datasets의 [`~datasets.Dataset.map`] 메서드를 사용하세요. `map` 함수의 속도를 높이려면 `batched=True`를 설정하여 데이터세트의 여러 요소를 한 번에 처리하는 방법이 있습니다.
110
+
111
+ ```py
112
+ >>> tokenized_books = books.map(preprocess_function, batched=True)
113
+ ```
114
+
115
+ 이제 [`DataCollatorForSeq2Seq`]를 사용하여 예제 배치를 생성합니다. 데이터세트의 최대 길이로 전부를 padding하는 대신, 데이터 정렬 중 각 배치의 최대 길이로 문장을 *동적으로 padding*하는 것이 더 효율적입니다.
116
+
117
+ <frameworkcontent>
118
+ <pt>
119
+ ```py
120
+ >>> from transformers import DataCollatorForSeq2Seq
121
+
122
+ >>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint)
123
+ ```
124
+ </pt>
125
+ <tf>
126
+
127
+ ```py
128
+ >>> from transformers import DataCollatorForSeq2Seq
129
+
130
+ >>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint, return_tensors="tf")
131
+ ```
132
+ </tf>
133
+ </frameworkcontent>
134
+
135
+ ## 평가[[evalulate]]
136
+
137
+ 훈련 중에 메트릭을 포함하면 모델의 성능을 평가하는 데 도움이 됩니다. 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) 라이브러리로 평가 방법(evaluation method)을 빠르게 가져올 수 있습니다. 현재 태스크에 적합한 SacreBLEU 메트릭을 가져오세요. (메트릭을 가져오고 계산하는 방법에 대해 자세히 알아보려면 🤗 Evaluate [둘러보기](https://huggingface.co/docs/evaluate/a_quick_tour)를 참조하세요):
138
+
139
+ ```py
140
+ >>> import evaluate
141
+
142
+ >>> metric = evaluate.load("sacrebleu")
143
+ ```
144
+
145
+ 그런 다음 [`~evaluate.EvaluationModule.compute`]에 예측값과 레이블을 전달하여 SacreBLEU 점수를 계산하는 함수를 생성하세요:
146
+
147
+ ```py
148
+ >>> import numpy as np
149
+
150
+
151
+ >>> def postprocess_text(preds, labels):
152
+ ... preds = [pred.strip() for pred in preds]
153
+ ... labels = [[label.strip()] for label in labels]
154
+
155
+ ... return preds, labels
156
+
157
+
158
+ >>> def compute_metrics(eval_preds):
159
+ ... preds, labels = eval_preds
160
+ ... if isinstance(preds, tuple):
161
+ ... preds = preds[0]
162
+ ... decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)
163
+
164
+ ... labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
165
+ ... decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
166
+
167
+ ... decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels)
168
+
169
+ ... result = metric.compute(predictions=decoded_preds, references=decoded_labels)
170
+ ... result = {"bleu": result["score"]}
171
+
172
+ ... prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in preds]
173
+ ... result["gen_len"] = np.mean(prediction_lens)
174
+ ... result = {k: round(v, 4) for k, v in result.items()}
175
+ ... return result
176
+ ```
177
+
178
+ 이제 `compute_metrics` 함수는 준비되었고, 훈련 과정을 설정할 때 다시 살펴볼 예정입니다.
179
+
180
+ ## 훈련[[train]]
181
+
182
+ <frameworkcontent>
183
+ <pt>
184
+ <Tip>
185
+
186
+ [`Trainer`]로 모델을 파인튜닝하는 방법에 익숙하지 않다면 [여기](../training#train-with-pytorch-trainer)에서 기본 튜토리얼을 살펴보시기 바랍니다!
187
+
188
+ </Tip>
189
+
190
+ 모델을 훈련시킬 준비가 되었군요! [`AutoModelForSeq2SeqLM`]으로 T5를 로드하세요:
191
+
192
+ ```py
193
+ >>> from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer
194
+
195
+ >>> model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint)
196
+ ```
197
+
198
+ 이제 세 단계만 거치면 끝입니다:
199
+
200
+ 1. [`Seq2SeqTrainingArguments`]에서 훈련 하이퍼파라미터를 정의하세요. 유일한 필수 매개변수는 모델을 저장할 위치인 `output_dir`입니다. 모델을 Hub에 푸시하기 위해 `push_to_hub=True`로 설정하세요. (모델을 업로드하려면 Hugging Face에 로그인해야 합니다.) [`Trainer`]는 에폭이 끝날때마다 SacreBLEU 메트릭을 평가하고 훈련 체크포인트를 저장합니다.
201
+ 2. [`Seq2SeqTrainer`]에 훈련 인수를 전달하세요. 모델, 데이터 세트, 토크나이저, data collator 및 `compute_metrics` 함수도 덩달아 전달해야 합니다.
202
+ 3. [`~Trainer.train`]을 호출하여 모델을 파인튜닝하세요.
203
+
204
+ ```py
205
+ >>> training_args = Seq2SeqTrainingArguments(
206
+ ... output_dir="my_awesome_opus_books_model",
207
+ ... eval_strategy="epoch",
208
+ ... learning_rate=2e-5,
209
+ ... per_device_train_batch_size=16,
210
+ ... per_device_eval_batch_size=16,
211
+ ... weight_decay=0.01,
212
+ ... save_total_limit=3,
213
+ ... num_train_epochs=2,
214
+ ... predict_with_generate=True,
215
+ ... fp16=True,
216
+ ... push_to_hub=True,
217
+ ... )
218
+
219
+ >>> trainer = Seq2SeqTrainer(
220
+ ... model=model,
221
+ ... args=training_args,
222
+ ... train_dataset=tokenized_books["train"],
223
+ ... eval_dataset=tokenized_books["test"],
224
+ ... processing_class=tokenizer,
225
+ ... data_collator=data_collator,
226
+ ... compute_metrics=compute_metrics,
227
+ ... )
228
+
229
+ >>> trainer.train()
230
+ ```
231
+
232
+ 학습이 완료되면 [`~transformers.Trainer.push_to_hub`] 메서드로 모델을 Hub에 공유하세요. 이러면 누구나 모델을 사용할 수 있게 됩니다:
233
+
234
+ ```py
235
+ >>> trainer.push_to_hub()
236
+ ```
237
+ </pt>
238
+ <tf>
239
+ <Tip>
240
+
241
+ Keras로 모델을 파인튜닝하는 방법이 익숙하지 않다면, [여기](../training#train-a-tensorflow-model-with-keras)에서 기본 튜토리얼을 살펴보시�� 바랍니다!
242
+
243
+ </Tip>
244
+ TensorFlow에서 모델을 파인튜닝하려면 우선 optimizer 함수, 학습률 스케줄 등의 훈련 하이퍼파라미터를 설정하세요:
245
+
246
+ ```py
247
+ >>> from transformers import AdamWeightDecay
248
+
249
+ >>> optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01)
250
+ ```
251
+
252
+ 이제 [`TFAutoModelForSeq2SeqLM`]로 T5를 가져오세요:
253
+
254
+ ```py
255
+ >>> from transformers import TFAutoModelForSeq2SeqLM
256
+
257
+ >>> model = TFAutoModelForSeq2SeqLM.from_pretrained(checkpoint)
258
+ ```
259
+
260
+ [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]로 데이터 세트를 `tf.data.Dataset` 형식으로 변환하세요:
261
+
262
+ ```py
263
+ >>> tf_train_set = model.prepare_tf_dataset(
264
+ ... tokenized_books["train"],
265
+ ... shuffle=True,
266
+ ... batch_size=16,
267
+ ... collate_fn=data_collator,
268
+ ... )
269
+
270
+ >>> tf_test_set = model.prepare_tf_dataset(
271
+ ... tokenized_books["test"],
272
+ ... shuffle=False,
273
+ ... batch_size=16,
274
+ ... collate_fn=data_collator,
275
+ ... )
276
+ ```
277
+
278
+ 훈련하기 위해 [`compile`](https://keras.io/api/models/model_training_apis/#compile-method) 메서드로 모델을 구성하세요:
279
+
280
+ ```py
281
+ >>> import tensorflow as tf
282
+
283
+ >>> model.compile(optimizer=optimizer)
284
+ ```
285
+
286
+ 훈련을 시작하기 전에 예측값으로부터 SacreBLEU 메트릭을 계산하는 방법과 모델을 Hub에 업로드하는 방법 두 가지를 미리 설정해둬야 합니다. 둘 다 [Keras callbacks](../main_classes/keras_callbacks)로 구현하세요.
287
+
288
+ [`~transformers.KerasMetricCallback`]에 `compute_metrics` 함수를 전달하세요.
289
+
290
+ ```py
291
+ >>> from transformers.keras_callbacks import KerasMetricCallback
292
+
293
+ >>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set)
294
+ ```
295
+
296
+ 모델과 토크나이저를 업로드할 위치를 [`~transformers.PushToHubCallback`]에서 지정하세요:
297
+
298
+ ```py
299
+ >>> from transformers.keras_callbacks import PushToHubCallback
300
+
301
+ >>> push_to_hub_callback = PushToHubCallback(
302
+ ... output_dir="my_awesome_opus_books_model",
303
+ ... tokenizer=tokenizer,
304
+ ... )
305
+ ```
306
+
307
+ 이제 콜백들을 한데로 묶어주세요:
308
+
309
+ ```py
310
+ >>> callbacks = [metric_callback, push_to_hub_callback]
311
+ ```
312
+
313
+ 드디어 모델을 훈련시킬 모든 준비를 마쳤군요! 이제 훈련 및 검증 데이터 세트에 [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) 메서드를 에폭 수와 만들어둔 콜백과 함께 호출하여 모델을 파인튜닝하세요:
314
+
315
+ ```py
316
+ >>> model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=callbacks)
317
+ ```
318
+
319
+ 학습이 완료되면 모델이 자동으로 Hub에 업로드되고, 누구나 사용할 수 있게 됩니다!
320
+ </tf>
321
+ </frameworkcontent>
322
+
323
+ <Tip>
324
+
325
+ 번역을 위해 모델을 파인튜닝하는 방법에 대한 보다 자세한 예제는 해당 [PyTorch 노트북](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation.ipynb) 또는 [TensorFlow 노트북](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation-tf.ipynb)을 참조하세요.
326
+
327
+ </Tip>
328
+
329
+ ## 추론[[inference]]
330
+
331
+ 좋아요, 이제 모델을 파인튜닝했으니 추론에 사용할 수 있습니다!
332
+
333
+ 다른 언어로 번역하고 싶은 텍스트를 써보세요. T5의 경우 원하는 태스크를 입력의 접두사로 추가해야 합니다. 예를 들어 영어에서 프랑스어로 번역하는 경우, 아래와 같은 접두사가 추가됩니다:
334
+
335
+ ```py
336
+ >>> text = "translate English to French: Legumes share resources with nitrogen-fixing bacteria."
337
+ ```
338
+
339
+ 파인튜닝된 모델로 추론하기에 제일 간단한 방법은 [`pipeline`]을 사용하는 것입니다. 해당 모델로 번역 `pipeline`을 만든 뒤, 텍스트를 전달하세요:
340
+
341
+ ```py
342
+ >>> from transformers import pipeline
343
+
344
+ # Change `xx` to the language of the input and `yy` to the language of the desired output.
345
+ # Examples: "en" for English, "fr" for French, "de" for German, "es" for Spanish, "zh" for Chinese, etc; translation_en_to_fr translates English to French
346
+ # You can view all the lists of languages here - https://huggingface.co/languages
347
+ >>> translator = pipeline("translation_xx_to_yy", model="my_awesome_opus_books_model")
348
+ >>> translator(text)
349
+ [{'translation_text': 'Legumes partagent des ressources avec des bactéries azotantes.'}]
350
+ ```
351
+
352
+ 원한다면 `pipeline`의 결과를 직접 복제할 수도 있습니다:
353
+
354
+ <frameworkcontent>
355
+ <pt>
356
+ 텍스트를 토큰화하고 `input_ids`를 PyTorch 텐서로 반환하세요:
357
+
358
+ ```py
359
+ >>> from transformers import AutoTokenizer
360
+
361
+ >>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_opus_books_model")
362
+ >>> inputs = tokenizer(text, return_tensors="pt").input_ids
363
+ ```
364
+
365
+ [`~generation.GenerationMixin.generate`] 메서드로 번역을 생성하세요. 다양한 텍스트 생성 전략 및 생성을 제어하기 위한 매개변수에 대한 자세한 내용은 [Text Generation](../main_classes/text_generation) API를 살펴보시기 바랍니다.
366
+
367
+ ```py
368
+ >>> from transformers import AutoModelForSeq2SeqLM
369
+
370
+ >>> model = AutoModelForSeq2SeqLM.from_pretrained("my_awesome_opus_books_model")
371
+ >>> outputs = model.generate(inputs, max_new_tokens=40, do_sample=True, top_k=30, top_p=0.95)
372
+ ```
373
+
374
+ 생성된 토큰 ID들을 다시 텍스트로 디코딩하세요:
375
+
376
+ ```py
377
+ >>> tokenizer.decode(outputs[0], skip_special_tokens=True)
378
+ 'Les lignées partagent des ressources avec des bactéries enfixant l'azote.'
379
+ ```
380
+ </pt>
381
+ <tf>
382
+ 텍스트를 토큰화하고 `input_ids`를 TensorFlow 텐서로 반환하세요:
383
+
384
+ ```py
385
+ >>> from transformers import AutoTokenizer
386
+
387
+ >>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_opus_books_model")
388
+ >>> inputs = tokenizer(text, return_tensors="tf").input_ids
389
+ ```
390
+
391
+ [`~transformers.generation_tf_utils.TFGenerationMixin.generate`] 메서드로 번역을 생성하세요. 다양한 텍스트 생성 전략 및 생성을 제어하기 위한 매개변수에 대한 자세한 내용은 [Text Generation](../main_classes/text_generation) API를 살펴보시기 바랍니다.
392
+
393
+ ```py
394
+ >>> from transformers import TFAutoModelForSeq2SeqLM
395
+
396
+ >>> model = TFAutoModelForSeq2SeqLM.from_pretrained("my_awesome_opus_books_model")
397
+ >>> outputs = model.generate(inputs, max_new_tokens=40, do_sample=True, top_k=30, top_p=0.95)
398
+ ```
399
+
400
+ 생성된 토큰 ID들을 다시 텍스트로 디코딩하세요:
401
+
402
+ ```py
403
+ >>> tokenizer.decode(outputs[0], skip_special_tokens=True)
404
+ 'Les lugumes partagent les ressources avec des bactéries fixatrices d'azote.'
405
+ ```
406
+ </tf>
407
+ </frameworkcontent>
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/video_classification.md ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2023 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # 영상 분류 [[video-classification]]
18
+
19
+ [[open-in-colab]]
20
+
21
+
22
+ 영상 분류는 영상 전체에 레이블 또는 클래스를 지정하는 작업입니다. 각 영상에는 하나의 클래스가 있을 것으로 예상됩니다. 영상 분류 모델은 영상을 입력으로 받아 어느 클래스에 속하는지에 대한 예측을 반환합니다. 이러한 모델은 영상이 어떤 내용인지 분류하는 데 사용될 수 있습니다. 영상 분류의 실제 응용 예는 피트니스 앱에서 유용한 동작 / 운동 인식 서비스가 있습니다. 이는 또한 시각 장애인이 이동할 때 보조하는데 사용될 수 있습니다
23
+
24
+ 이 가이드에서는 다음을 수행하는 방법을 보여줍니다:
25
+
26
+ 1. [UCF101](https://www.crcv.ucf.edu/data/UCF101.php) 데이터 세트의 하위 집합을 통해 [VideoMAE](https://huggingface.co/docs/transformers/main/en/model_doc/videomae) 모델을 미세 조정하기.
27
+ 2. 미세 조정한 모델을 추론에 사용하기.
28
+
29
+ <Tip>
30
+
31
+ 이 작업과 호환되는 모든 아키텍처와 체크포인트를 보려면 [작업 페이지](https://huggingface.co/tasks/video-classification)를 확인하는 것이 좋습니다.
32
+
33
+ </Tip>
34
+
35
+
36
+ 시작하기 전에 필요한 모든 라이브러리가 설치되었는지 확인하세요:
37
+ ```bash
38
+ pip install -q pytorchvideo transformers evaluate
39
+ ```
40
+
41
+ 영상을 처리하고 준비하기 위해 [PyTorchVideo](https://pytorchvideo.org/)(이하 `pytorchvideo`)를 사용합니다.
42
+
43
+ 커뮤니티에 모델을 업로드하고 공유할 수 있도록 Hugging Face 계정에 로그인하는 것을 권장합니다. 프롬프트가 나타나면 토큰을 입력하여 로그인하세요:
44
+
45
+ ```py
46
+ >>> from huggingface_hub import notebook_login
47
+
48
+ >>> notebook_login()
49
+ ```
50
+
51
+ ## UCF101 데이터셋 불러오기 [[load-ufc101-dataset]]
52
+
53
+ [UCF-101](https://www.crcv.ucf.edu/data/UCF101.php) 데이터 세트의 하위 집합(subset)을 불러오는 것으로 시작할 수 있습니다. 전체 데이터 세트를 학습하는데 더 많은 시간을 할애하기 전에 데이터의 하위 집합을 불러와 모든 것이 잘 작동하는지 실험하고 확인할 수 있습니다.
54
+
55
+ ```py
56
+ >>> from huggingface_hub import hf_hub_download
57
+
58
+ >>> hf_dataset_identifier = "sayakpaul/ucf101-subset"
59
+ >>> filename = "UCF101_subset.tar.gz"
60
+ >>> file_path = hf_hub_download(repo_id=hf_dataset_identifier, filename=filename, repo_type="dataset")
61
+ ```
62
+
63
+ 데이터 세트의 하위 집합이 다운로드 되면, 압축된 파일의 압축을 해제해야 합니다:
64
+ ```py
65
+ >>> import tarfile
66
+
67
+ >>> with tarfile.open(file_path) as t:
68
+ ... t.extractall(".")
69
+ ```
70
+
71
+ 전체 데이터 세트는 다음과 같이 구성되어 있습니다.
72
+
73
+ ```bash
74
+ UCF101_subset/
75
+ train/
76
+ BandMarching/
77
+ video_1.mp4
78
+ video_2.mp4
79
+ ...
80
+ Archery
81
+ video_1.mp4
82
+ video_2.mp4
83
+ ...
84
+ ...
85
+ val/
86
+ BandMarching/
87
+ video_1.mp4
88
+ video_2.mp4
89
+ ...
90
+ Archery
91
+ video_1.mp4
92
+ video_2.mp4
93
+ ...
94
+ ...
95
+ test/
96
+ BandMarching/
97
+ video_1.mp4
98
+ video_2.mp4
99
+ ...
100
+ Archery
101
+ video_1.mp4
102
+ video_2.mp4
103
+ ...
104
+ ...
105
+ ```
106
+
107
+
108
+ 정렬된 영상의 경로는 다음과 같습니다:
109
+
110
+ ```bash
111
+ ...
112
+ 'UCF101_subset/train/ApplyEyeMakeup/v_ApplyEyeMakeup_g07_c04.avi',
113
+ 'UCF101_subset/train/ApplyEyeMakeup/v_ApplyEyeMakeup_g07_c06.avi',
114
+ 'UCF101_subset/train/ApplyEyeMakeup/v_ApplyEyeMakeup_g08_c01.avi',
115
+ 'UCF101_subset/train/ApplyEyeMakeup/v_ApplyEyeMakeup_g09_c02.avi',
116
+ 'UCF101_subset/train/ApplyEyeMakeup/v_ApplyEyeMakeup_g09_c06.avi'
117
+ ...
118
+ ```
119
+
120
+ 동일한 그룹/장면에 속하는 영상 클립은 파일 경로에서 `g`로 표시되어 있습니다. 예를 들면, `v_ApplyEyeMakeup_g07_c04.avi`와 `v_ApplyEyeMakeup_g07_c06.avi` 이 있습니다. 이 둘은 같은 그룹입니다.
121
+
122
+ 검증 및 평가 데이터 분할을 할 때, [데이터 누출(data leakage)](https://www.kaggle.com/code/alexisbcook/data-leakage)을 방지하기 위해 동일한 그룹 / 장면의 영상 클립을 사용하지 않아야 합니다. 이 튜토리얼에서 사��하는 하위 집합은 이러한 정보를 고려하고 있습니다.
123
+
124
+ 그 다음으로, 데이터 세트에 존재하는 라벨을 추출합니다. 또한, 모델을 초기화할 때 도움이 될 딕셔너리(dictionary data type)를 생성합니다.
125
+
126
+ * `label2id`: 클래스 이름을 정수에 매핑합니다.
127
+ * `id2label`: 정수를 클래스 이름에 매핑합니다.
128
+
129
+ ```py
130
+ >>> class_labels = sorted({str(path).split("/")[2] for path in all_video_file_paths})
131
+ >>> label2id = {label: i for i, label in enumerate(class_labels)}
132
+ >>> id2label = {i: label for label, i in label2id.items()}
133
+
134
+ >>> print(f"Unique classes: {list(label2id.keys())}.")
135
+
136
+ # Unique classes: ['ApplyEyeMakeup', 'ApplyLipstick', 'Archery', 'BabyCrawling', 'BalanceBeam', 'BandMarching', 'BaseballPitch', 'Basketball', 'BasketballDunk', 'BenchPress'].
137
+ ```
138
+
139
+ 이 데이터 세트에는 총 10개의 고유한 클래스가 있습니다. 각 클래스마다 30개의 영상이 훈련 세트에 있습니다
140
+
141
+ ## 미세 조정하기 위해 모델 가져오기 [[load-a-model-to-fine-tune]]
142
+
143
+ 사전 훈련된 체크포인트와 체크포인트에 연관된 이미지 프로세서를 사용하여 영상 분류 모델을 인스턴스화합니다. 모델의 인코더에는 미리 학습된 매개변수가 제공되며, 분류 헤드(데이터를 분류하는 마지막 레이어)는 무작위로 초기화됩니다. 데이터 세트의 전처리 파이프라인을 작성할 때는 이미지 프로세서가 유용합니다.
144
+
145
+ ```py
146
+ >>> from transformers import VideoMAEImageProcessor, VideoMAEForVideoClassification
147
+
148
+ >>> model_ckpt = "MCG-NJU/videomae-base"
149
+ >>> image_processor = VideoMAEImageProcessor.from_pretrained(model_ckpt)
150
+ >>> model = VideoMAEForVideoClassification.from_pretrained(
151
+ ... model_ckpt,
152
+ ... label2id=label2id,
153
+ ... id2label=id2label,
154
+ ... ignore_mismatched_sizes=True, # provide this in case you're planning to fine-tune an already fine-tuned checkpoint
155
+ ... )
156
+ ```
157
+
158
+ 모델을 가져오는 동안, 다음과 같은 경고를 마주칠 수 있습니다:
159
+
160
+ ```bash
161
+ Some weights of the model checkpoint at MCG-NJU/videomae-base were not used when initializing VideoMAEForVideoClassification: [..., 'decoder.decoder_layers.1.attention.output.dense.bias', 'decoder.decoder_layers.2.attention.attention.key.weight']
162
+ - This IS expected if you are initializing VideoMAEForVideoClassification from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).
163
+ - This IS NOT expected if you are initializing VideoMAEForVideoClassification from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).
164
+ Some weights of VideoMAEForVideoClassification were not initialized from the model checkpoint at MCG-NJU/videomae-base and are newly initialized: ['classifier.bias', 'classifier.weight']
165
+ You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
166
+ ```
167
+
168
+
169
+ 위 경고는 우리가 일부 가중치(예: `classifier` 층의 가중치와 편향)를 버리고 새로운 `classifier` 층의 가중치와 편향을 무작위로 초기화하고 있다는 것을 알려줍니다. 이 경우에는 미리 학습된 가중치가 없는 새로운 헤드를 추가하고 있으므로, 라이브러리가 모델을 추론에 사용하기 전에 미세 조정하라고 경고를 보내는 것은 당연합니다. 그리고 이제 우리는 이 모델을 미세 조정할 예정입니다.
170
+
171
+ **참고** 이 [체크포인트](https://huggingface.co/MCG-NJU/videomae-base-finetuned-kinetics)는 도메인이 많이 중첩된 유사한 다운스트림 작업에 대해 미세 조정하여 얻은 체크포인트이므로 이 작업에서 더 나은 성능을 보일 수 있습니다. `MCG-NJU/videomae-base-finetuned-kinetics` 데이터 세트를 미세 조정하여 얻은 [체크포인트](https://huggingface.co/sayakpaul/videomae-base-finetuned-kinetics-finetuned-ucf101-subset)도 있습니다.
172
+
173
+ ## 훈련을 위한 데이터 세트 준비하기[[prepare-the-datasets-for-training]]
174
+
175
+ 영상 전처리를 위해 [PyTorchVideo 라이브러리](https://pytorchvideo.org/)를 활용할 것입니다. 필요한 종속성을 가져오는 것으로 시작하세요.
176
+
177
+ ```py
178
+ >>> import pytorchvideo.data
179
+
180
+ >>> from pytorchvideo.transforms import (
181
+ ... ApplyTransformToKey,
182
+ ... Normalize,
183
+ ... RandomShortSideScale,
184
+ ... RemoveKey,
185
+ ... ShortSideScale,
186
+ ... UniformTemporalSubsample,
187
+ ... )
188
+
189
+ >>> from torchvision.transforms import (
190
+ ... Compose,
191
+ ... Lambda,
192
+ ... RandomCrop,
193
+ ... RandomHorizontalFlip,
194
+ ... Resize,
195
+ ... )
196
+ ```
197
+
198
+ 학습 데이터 세트 변환에는 '균일한 시간 샘플링(uniform temporal subsampling)', '픽셀 정규화(pixel normalization)', '랜덤 잘라내기(random cropping)' 및 '랜덤 수평 뒤집기(random horizontal flipping)'의 조합을 사��합니다. 검증 및 평가 데이터 세트 변환에는 '랜덤 잘라내기'와 '랜덤 뒤집기'를 제외한 동일한 변환 체인을 유지합니다. 이러한 변환에 대해 자세히 알아보려면 [PyTorchVideo 공식 문서](https://pytorchvideo.org)를 확인하세요.
199
+
200
+ 사전 훈련된 모델과 관련된 이미지 프로세서를 사용하여 다음 정보를 얻을 수 있습니다:
201
+
202
+ * 영상 프레임 픽셀을 정규화하는 데 사용되는 이미지 평균과 표준 편차
203
+ * 영상 프레임이 조정될 공간 해상도
204
+
205
+
206
+ 먼저, 몇 가지 상수를 정의합니다.
207
+
208
+ ```py
209
+ >>> mean = image_processor.image_mean
210
+ >>> std = image_processor.image_std
211
+ >>> if "shortest_edge" in image_processor.size:
212
+ ... height = width = image_processor.size["shortest_edge"]
213
+ >>> else:
214
+ ... height = image_processor.size["height"]
215
+ ... width = image_processor.size["width"]
216
+ >>> resize_to = (height, width)
217
+
218
+ >>> num_frames_to_sample = model.config.num_frames
219
+ >>> sample_rate = 4
220
+ >>> fps = 30
221
+ >>> clip_duration = num_frames_to_sample * sample_rate / fps
222
+ ```
223
+
224
+ 이제 데이터 세트에 특화된 전처리(transform)과 데이터 세트 자체를 정의합니다. 먼저 훈련 데이터 세트로 시작합니다:
225
+
226
+ ```py
227
+ >>> train_transform = Compose(
228
+ ... [
229
+ ... ApplyTransformToKey(
230
+ ... key="video",
231
+ ... transform=Compose(
232
+ ... [
233
+ ... UniformTemporalSubsample(num_frames_to_sample),
234
+ ... Lambda(lambda x: x / 255.0),
235
+ ... Normalize(mean, std),
236
+ ... RandomShortSideScale(min_size=256, max_size=320),
237
+ ... RandomCrop(resize_to),
238
+ ... RandomHorizontalFlip(p=0.5),
239
+ ... ]
240
+ ... ),
241
+ ... ),
242
+ ... ]
243
+ ... )
244
+
245
+ >>> train_dataset = pytorchvideo.data.Ucf101(
246
+ ... data_path=os.path.join(dataset_root_path, "train"),
247
+ ... clip_sampler=pytorchvideo.data.make_clip_sampler("random", clip_duration),
248
+ ... decode_audio=False,
249
+ ... transform=train_transform,
250
+ ... )
251
+ ```
252
+
253
+ 같은 방식의 작업 흐름을 검증과 평가 세트에도 적용할 수 있습니다.
254
+
255
+ ```py
256
+ >>> val_transform = Compose(
257
+ ... [
258
+ ... ApplyTransformToKey(
259
+ ... key="video",
260
+ ... transform=Compose(
261
+ ... [
262
+ ... UniformTemporalSubsample(num_frames_to_sample),
263
+ ... Lambda(lambda x: x / 255.0),
264
+ ... Normalize(mean, std),
265
+ ... Resize(resize_to),
266
+ ... ]
267
+ ... ),
268
+ ... ),
269
+ ... ]
270
+ ... )
271
+
272
+ >>> val_dataset = pytorchvideo.data.Ucf101(
273
+ ... data_path=os.path.join(dataset_root_path, "val"),
274
+ ... clip_sampler=pytorchvideo.data.make_clip_sampler("uniform", clip_duration),
275
+ ... decode_audio=False,
276
+ ... transform=val_transform,
277
+ ... )
278
+
279
+ >>> test_dataset = pytorchvideo.data.Ucf101(
280
+ ... data_path=os.path.join(dataset_root_path, "test"),
281
+ ... clip_sampler=pytorchvideo.data.make_clip_sampler("uniform", clip_duration),
282
+ ... decode_audio=False,
283
+ ... transform=val_transform,
284
+ ... )
285
+ ```
286
+
287
+
288
+ **참고**: 위의 데이터 세트의 파이프라인은 [공식 파이토치 예제](https://pytorchvideo.org/docs/tutorial_classification#dataset)에서 가져온 것입니다. 우리는 UCF-101 데이터셋에 맞게 [`pytorchvideo.data.Ucf101()`](https://pytorchvideo.readthedocs.io/en/latest/api/data/data.html#pytorchvideo.data.Ucf101) 함수를 사용하고 있습니다. 내부적으로 이 함수는 [`pytorchvideo.data.labeled_video_dataset.LabeledVideoDataset`](https://pytorchvideo.readthedocs.io/en/latest/api/data/data.html#pytorchvideo.data.LabeledVideoDataset) 객체를 반환합니다. `LabeledVideoDataset` 클래스는 PyTorchVideo 데이터셋에서 모든 영상 관련 작업의 기본 클래스입니다. 따라서 PyTorchVideo에서 미리 제공하지 않는 사용자 지정 데이터 세트를 사용하려면, 이 클래스를 적절하게 확장하면 됩니다. 더 자세한 사항이 알고 싶다면 `data` API [문서](https://pytorchvideo.readthedocs.io/en/latest/api/data/data.html) 를 참고하세요. 또한 위의 예시와 유사한 구조를 갖는 데이터 세트를 사용하고 있다면, `pytorchvideo.data.Ucf101()` 함수를 사용하는 데 문제가 없을 것입니다.
289
+
290
+ 데이터 세트에 영상의 개수를 알기 위해 `num_videos` 인수에 접근할 수 있습니다.
291
+
292
+ ```py
293
+ >>> print(train_dataset.num_videos, val_dataset.num_videos, test_dataset.num_videos)
294
+ # (300, 30, 75)
295
+ ```
296
+
297
+ ## 더 나은 디버깅을 위해 전처리 영상 시각화하기[[visualize-the-preprocessed-video-for-better-debugging]]
298
+
299
+ ```py
300
+ >>> import imageio
301
+ >>> import numpy as np
302
+ >>> from IPython.display import Image
303
+
304
+ >>> def unnormalize_img(img):
305
+ ... """Un-normalizes the image pixels."""
306
+ ... img = (img * std) + mean
307
+ ... img = (img * 255).astype("uint8")
308
+ ... return img.clip(0, 255)
309
+
310
+ >>> def create_gif(video_tensor, filename="sample.gif"):
311
+ ... """Prepares a GIF from a video tensor.
312
+ ...
313
+ ... The video tensor is expected to have the following shape:
314
+ ... (num_frames, num_channels, height, width).
315
+ ... """
316
+ ... frames = []
317
+ ... for video_frame in video_tensor:
318
+ ... frame_unnormalized = unnormalize_img(video_frame.permute(1, 2, 0).numpy())
319
+ ... frames.append(frame_unnormalized)
320
+ ... kargs = {"duration": 0.25}
321
+ ... imageio.mimsave(filename, frames, "GIF", **kargs)
322
+ ... return filename
323
+
324
+ >>> def display_gif(video_tensor, gif_name="sample.gif"):
325
+ ... """Prepares and displays a GIF from a video tensor."""
326
+ ... video_tensor = video_tensor.permute(1, 0, 2, 3)
327
+ ... gif_filename = create_gif(video_tensor, gif_name)
328
+ ... return Image(filename=gif_filename)
329
+
330
+ >>> sample_video = next(iter(train_dataset))
331
+ >>> video_tensor = sample_video["video"]
332
+ >>> display_gif(video_tensor)
333
+ ```
334
+
335
+ <div class="flex justify-center">
336
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/sample_gif.gif" alt="Person playing basketball"/>
337
+ </div>
338
+
339
+ ## 모델 훈련하기[[train-the-model]]
340
+
341
+ 🤗 Transformers의 [`Trainer`](https://huggingface.co/docs/transformers/main_classes/trainer)를 사용하여 모델을 훈련시켜보세요. `Trainer`를 인스턴스화하려면 훈련 설정과 평가 지표를 정의해야 합니다. 가장 중요한 것은 [`TrainingArguments`](https://huggingface.co/transformers/main_classes/trainer.html#transformers.TrainingArguments)입니다. 이 클래스는 훈련을 구성하는 모든 속성을 포함하며, 훈련 중 체크포인트를 저장할 출력 폴더 이름을 필요로 합니다. 또한 🤗 Hub의 모델 저장소의 모든 정보를 동기화하는 데 도움이 됩니다.
342
+
343
+ 대부분의 훈련 인수는 따로 설명할 필요는 없습니다. 하지만 여기에서 중요한 인수는 `remove_unused_columns=False` 입니다. 이 인자는 모델의 호출 함수에서 사용되지 않는 모든 속성 열(columns)을 삭제합니다. 기본값은 일반적으로 True입니다. 이는 사용되지 않는 기능 열을 삭제하는 것이 이상적이며, 입력을 모델의 호출 함수로 풀기(unpack)가 쉬워지기 때문입니다. 하지만 이 경우에는 `pixel_values`(모델의 입력으로 필수적인 키)를 생성하기 위해 사용되지 않는 기능('video'가 특히 그렇습니다)이 필요합니다. 따라서 remove_unused_columns을 False로 설정해야 합니다.
344
+
345
+ ```py
346
+ >>> from transformers import TrainingArguments, Trainer
347
+
348
+ >>> model_name = model_ckpt.split("/")[-1]
349
+ >>> new_model_name = f"{model_name}-finetuned-ucf101-subset"
350
+ >>> num_epochs = 4
351
+
352
+ >>> args = TrainingArguments(
353
+ ... new_model_name,
354
+ ... remove_unused_columns=False,
355
+ ... eval_strategy="epoch",
356
+ ... save_strategy="epoch",
357
+ ... learning_rate=5e-5,
358
+ ... per_device_train_batch_size=batch_size,
359
+ ... per_device_eval_batch_size=batch_size,
360
+ ... warmup_ratio=0.1,
361
+ ... logging_steps=10,
362
+ ... load_best_model_at_end=True,
363
+ ... metric_for_best_model="accuracy",
364
+ ... push_to_hub=True,
365
+ ... max_steps=(train_dataset.num_videos // batch_size) * num_epochs,
366
+ ... )
367
+ ```
368
+
369
+ `pytorchvideo.data.Ucf101()` 함수로 반환되는 데이터 세트는 `__len__` 메소드가 이식되어 있지 않습니다. 따라서, `TrainingArguments`를 인스턴스화할 때 `max_steps`를 정의해야 합니다.
370
+
371
+ 다음으로, 평가지표를 불러오고, 예측값에서 평가지표를 계산할 함수를 정의합니다. 필요한 전처리 작업은 예측된 로짓(logits)에 argmax 값을 취하는 것뿐입니다:
372
+
373
+ ```py
374
+ import evaluate
375
+
376
+ metric = evaluate.load("accuracy")
377
+
378
+
379
+ def compute_metrics(eval_pred):
380
+ predictions = np.argmax(eval_pred.predictions, axis=1)
381
+ return metric.compute(predictions=predictions, references=eval_pred.label_ids)
382
+ ```
383
+
384
+ **평가에 대한 참고사항**:
385
+
386
+ [VideoMAE 논문](https://huggingface.co/papers/2203.12602)에서 저자는 다음과 같은 평가 전략을 사용합니다. 테스트 영상에서 여러 클립을 선택하고 그 클립에 다양한 크롭을 적용하여 집계 점수를 보고합니다. 그러나 이번 튜토리얼에서는 간단함과 간결함을 위해 해당 전략을 고려하지 않습니다.
387
+
388
+ 또한, 예제를 묶어서 배치를 형성하는 `collate_fn`을 정의해야합니다. 각 배치는 `pixel_values`와 `labels`라는 2개의 키로 구성됩니다.
389
+
390
+ ```py
391
+ >>> def collate_fn(examples):
392
+ ... # permute to (num_frames, num_channels, height, width)
393
+ ... pixel_values = torch.stack(
394
+ ... [example["video"].permute(1, 0, 2, 3) for example in examples]
395
+ ... )
396
+ ... labels = torch.tensor([example["label"] for example in examples])
397
+ ... return {"pixel_values": pixel_values, "labels": labels}
398
+ ```
399
+
400
+ 그런 다음 이 모든 것을 데이터 세트와 함께 `Trainer`에 전달하기만 하면 됩니다:
401
+
402
+ ```py
403
+ >>> trainer = Trainer(
404
+ ... model,
405
+ ... args,
406
+ ... train_dataset=train_dataset,
407
+ ... eval_dataset=val_dataset,
408
+ ... processing_class=image_processor,
409
+ ... compute_metrics=compute_metrics,
410
+ ... data_collator=collate_fn,
411
+ ... )
412
+ ```
413
+
414
+ 데이터를 이미 처리했는데도 불구하고 `image_processor`를 토크나이저 인수로 넣은 이유는 JSON으로 저장되는 이미지 프로세서 구성 파일이 Hub의 저장소에 업로드되도록 하기 위함입니다.
415
+
416
+ `train` 메소드를 호출하여 모델을 미세 조정하세요:
417
+
418
+ ```py
419
+ >>> train_results = trainer.train()
420
+ ```
421
+
422
+ 학습이 완료되면, 모델을 [`~transformers.Trainer.push_to_hub`] 메소드를 사용하여 허브에 공유하여 누구나 모델을 사용할 수 있도록 합니다:
423
+ ```py
424
+ >>> trainer.push_to_hub()
425
+ ```
426
+
427
+ ## 추론하기[[inference]]
428
+
429
+ 좋습니다. 이제 미세 조정된 모델을 추론하는 데 사용할 수 있습니다.
430
+
431
+ 추론에 사용할 영상을 불러오세요:
432
+ ```py
433
+ >>> sample_test_video = next(iter(test_dataset))
434
+ ```
435
+
436
+ <div class="flex justify-center">
437
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/sample_gif_two.gif" alt="Teams playing basketball"/>
438
+ </div>
439
+
440
+ 미세 조정된 모델을 추론에 사용하는 가장 간단한 방법은 [`pipeline`](https://huggingface.co/docs/transformers/main/en/main_classes/pipelines#transformers.VideoClassificationPipeline)에서 모델을 사용하는 것입니다. 모델로 영상 분류를 하기 위해 `pipeline`을 인스턴스화하고 영상을 전달하세요:
441
+
442
+ ```py
443
+ >>> from transformers import pipeline
444
+
445
+ >>> video_cls = pipeline(model="my_awesome_video_cls_model")
446
+ >>> video_cls("https://huggingface.co/datasets/sayakpaul/ucf101-subset/resolve/main/v_BasketballDunk_g14_c06.avi")
447
+ [{'score': 0.9272987842559814, 'label': 'BasketballDunk'},
448
+ {'score': 0.017777055501937866, 'label': 'BabyCrawling'},
449
+ {'score': 0.01663011871278286, 'label': 'BalanceBeam'},
450
+ {'score': 0.009560945443809032, 'label': 'BandMarching'},
451
+ {'score': 0.0068979403004050255, 'label': 'BaseballPitch'}]
452
+ ```
453
+
454
+ 만약 원한다면 수동으로 `pipeline`의 결과를 재현할 수 있습니다:
455
+
456
+
457
+ ```py
458
+ >>> def run_inference(model, video):
459
+ ... # (num_frames, num_channels, height, width)
460
+ ... perumuted_sample_test_video = video.permute(1, 0, 2, 3)
461
+ ... inputs = {
462
+ ... "pixel_values": perumuted_sample_test_video.unsqueeze(0),
463
+ ... "labels": torch.tensor(
464
+ ... [sample_test_video["label"]]
465
+ ... ), # this can be skipped if you don't have labels available.
466
+ ... }
467
+
468
+ ... device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
469
+ ... inputs = {k: v.to(device) for k, v in inputs.items()}
470
+ ... model = model.to(device)
471
+
472
+ ... # forward pass
473
+ ... with torch.no_grad():
474
+ ... outputs = model(**inputs)
475
+ ... logits = outputs.logits
476
+
477
+ ... return logits
478
+ ```
479
+
480
+ 모델에 입력값을 넣고 `logits`을 반환받으세요:
481
+
482
+ ```py
483
+ >>> logits = run_inference(trained_model, sample_test_video["video"])
484
+ ```
485
+
486
+ `logits`을 디코딩하면, 우리는 다음 결과를 얻을 수 있습니다:
487
+
488
+ ```py
489
+ >>> predicted_class_idx = logits.argmax(-1).item()
490
+ >>> print("Predicted class:", model.config.id2label[predicted_class_idx])
491
+ # Predicted class: BasketballDunk
492
+ ```
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/visual_question_answering.md ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2023 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # 시각적 질의응답 (Visual Question Answering)
18
+
19
+ [[open-in-colab]]
20
+
21
+ 시각적 질의응답(VQA)은 이미지를 기반으로 개방형 질문에 대응하는 작업입니다. 이 작업을 지원하는 모델의 입력은 대부분 이미지와 질문의 조합이며, 출력은 자연어로 된 답변입니다.
22
+
23
+ VQA의 주요 사용 사례는 다음과 같습니다:
24
+ * 시각 장애인을 위한 접근성 애플리케이션을 구축할 수 있습니다.
25
+ * 교육: 강의나 교과서에 나온 시각 자료에 대한 질문에 답할 수 있습니다. 또한 체험형 전시와 유적 등에서도 VQA를 활용할 수 있습니다.
26
+ * 고객 서비스 및 전자상거래: VQA는 사용자가 제품에 대해 질문할 수 있게 함으로써 사용자 경험을 향상시킬 수 있습니다.
27
+ * 이미지 검색: VQA 모델을 사용하여 원하는 특성을 가진 이미지를 검색할 수 있습니다. 예를 들어 사용자는 "강아지가 있어?"라고 물어봐서 주어진 이미지 묶음에서 강아지가 있는 모든 이미지를 받아볼 수 있습니다.
28
+
29
+ 이 가이드에서 학습할 내용은 다음과 같습니다:
30
+
31
+ - VQA 모델 중 하나인 [ViLT](../../en/model_doc/vilt)를 [`Graphcore/vqa` 데이터셋](https://huggingface.co/datasets/Graphcore/vqa) 에서 미세조정하는 방법
32
+ - 미세조정된 ViLT 모델로 추론하는 방법
33
+ - BLIP-2 같은 생성 모델로 제로샷 VQA 추론을 실행하는 방법
34
+
35
+ ## ViLT 미세 조정 [[finetuning-vilt]]
36
+
37
+ ViLT는 Vision Transformer (ViT) 내에 텍스트 임베딩을 포함하여 비전/자연어 사전훈련(VLP; Vision-and-Language Pretraining)을 위한 기본 디자인을 제공합니다.
38
+ ViLT 모델은 비전 트랜스포머(ViT)에 텍스트 임베딩을 넣어 비전/언어 사전훈련(VLP; Vision-and-Language Pre-training)을 위한 기본적인 디자인을 갖췄습니다. 이 모델은 여러 다운스트림 작업에 사용할 수 있습니다. VQA 태스크에서는 (`[CLS]` 토큰의 최종 은닉 상태 위에 선형 레이어인) 분류 헤더가 있으며 무작위로 초기화됩니다.
39
+ 따라서 여기에서 시각적 질의응답은 **분류 문제**로 취급됩니다.
40
+
41
+ 최근의 BLIP, BLIP-2, InstructBLIP와 같은 모델들은 VQA를 생성형 작업으로 간주합니다. 가이드의 후반부에서는 이런 모델들을 사용하여 제로샷 VQA 추론을 하는 방법에 대해 설명하겠습니다.
42
+
43
+ 시작하기 전 필요한 모든 라이브러리를 설치했는지 확인하세요.
44
+
45
+ ```bash
46
+ pip install -q transformers datasets
47
+ ```
48
+
49
+ 커뮤니티에 모델을 공유하는 것을 권장 드립니다. Hugging Face 계정에 로그인하여 🤗 Hub에 업로드할 수 있습니다.
50
+ 메시지가 나타나면 로그인할 토큰을 입력하세요:
51
+
52
+ ```py
53
+ >>> from huggingface_hub import notebook_login
54
+
55
+ >>> notebook_login()
56
+ ```
57
+
58
+ 모델 체크포인트를 전역 변수로 선언하세요.
59
+
60
+ ```py
61
+ >>> model_checkpoint = "dandelin/vilt-b32-mlm"
62
+ ```
63
+
64
+ ## 데이터 가져오기 [[load-the-data]]
65
+
66
+ 이 가이드에서는 `Graphcore/vqa` 데이터세트의 작은 샘플을 사용합니다. 전체 데이터세트는 [🤗 Hub](https://huggingface.co/datasets/Graphcore/vqa) 에서 확인할 수 있습니다.
67
+
68
+ [`Graphcore/vqa` 데이터세트](https://huggingface.co/datasets/Graphcore/vqa) 의 대안으로 공식 [VQA 데이터세트 페이지](https://visualqa.org/download.html) 에서 동일한 데이터를 수동으로 다운로드할 수 있습니다. 직접 공수한 데이터로 튜토리얼을 따르고 싶다면 [이미지 데이터세트 만들기](https://huggingface.co/docs/datasets/image_dataset#loading-script) 라는
69
+ 🤗 Datasets 문서를 참조하세요.
70
+
71
+ 검증 데이터의 첫 200개 항목을 불러와 데이터세트의 특성을 확인해 보겠습니다:
72
+
73
+ ```python
74
+ >>> from datasets import load_dataset
75
+
76
+ >>> dataset = load_dataset("Graphcore/vqa", split="validation[:200]")
77
+ >>> dataset
78
+ Dataset({
79
+ features: ['question', 'question_type', 'question_id', 'image_id', 'answer_type', 'label'],
80
+ num_rows: 200
81
+ })
82
+ ```
83
+
84
+ 예제를 하나 뽑아 데이터세트의 특성을 이해해 보겠습니다.
85
+
86
+ ```py
87
+ >>> dataset[0]
88
+ {'question': 'Where is he looking?',
89
+ 'question_type': 'none of the above',
90
+ 'question_id': 262148000,
91
+ 'image_id': '/root/.cache/huggingface/datasets/downloads/extracted/ca733e0e000fb2d7a09fbcc94dbfe7b5a30750681d0e965f8e0a23b1c2f98c75/val2014/COCO_val2014_000000262148.jpg',
92
+ 'answer_type': 'other',
93
+ 'label': {'ids': ['at table', 'down', 'skateboard', 'table'],
94
+ 'weights': [0.30000001192092896,
95
+ 1.0,
96
+ 0.30000001192092896,
97
+ 0.30000001192092896]}}
98
+ ```
99
+
100
+ 데이터세트에는 다음과 같은 특성이 포함되어 있습니다:
101
+ * `question`: 이미지에 대한 질문
102
+ * `image_id`: 질문과 관련된 이미지의 경로
103
+ * `label`: 데이터의 레이블 (annotations)
104
+
105
+ 나머지 특성들은 필요하지 않기 때문에 삭제해도 됩니다:
106
+
107
+ ```py
108
+ >>> dataset = dataset.remove_columns(['question_type', 'question_id', 'answer_type'])
109
+ ```
110
+
111
+ 보시다시피 `label` 특성은 같은 질문마다 답변이 여러 개 있을 수 있습니다. 모두 다른 데이터 라벨러들로부터 수집되었기 때문인데요. 질문의 답변은 주관적일 수 있습니다. 이 경우 질문은 "그는 어디를 보고 있나요?" 였지만, 어떤 사람들은 "아래"로 레이블을 달았고, 다른 사람들은 "테이블" 또는 "스케이트보드" 등으로 주석을 달았습니다.
112
+
113
+ 아래의 이미지를 보고 어떤 답변을 선택할 것인지 생각해 보세요:
114
+
115
+ ```python
116
+ >>> from PIL import Image
117
+
118
+ >>> image = Image.open(dataset[0]['image_id'])
119
+ >>> image
120
+ ```
121
+
122
+ <div class="flex justify-center">
123
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/vqa-example.png" alt="VQA Image Example"/>
124
+ </div>
125
+
126
+ 질문과 답변의 모호성으로 인해 이러한 데이터세트는 여러 개의 답변이 가능하므로 다중 레이블 분류 문제로 처리됩니다. 게다가, 원핫(one-hot) 인코딩 벡터를 생성하기보다는 레이블에서 특정 답변이 나타나는 횟수를 기반으로 소프트 인코딩을 생성합니다.
127
+
128
+ 위의 예시에서 "아래"라는 답변이 다른 답변보다 훨씬 더 자주 선택되었기 때문에 데이터세트에서 `weight`라고 불리는 점수로 1.0을 가지며, 나머지 답변들은 1.0 미만의 점수를 가집니다.
129
+
130
+ 적절한 분류 헤더로 모델을 나중에 인스턴스화하기 위해 레이블을 정수로 매핑한 딕셔너리 하나, 반대로 정수를 레이블로 매핑한 딕셔너리 하나 총 2개의 딕셔너리를 생성하세요:
131
+
132
+ ```py
133
+ >>> import itertools
134
+
135
+ >>> labels = [item['ids'] for item in dataset['label']]
136
+ >>> flattened_labels = list(itertools.chain(*labels))
137
+ >>> unique_labels = list(set(flattened_labels))
138
+
139
+ >>> label2id = {label: idx for idx, label in enumerate(unique_labels)}
140
+ >>> id2label = {idx: label for label, idx in label2id.items()}
141
+ ```
142
+
143
+ 이제 매핑이 완료되었으므로 문자열 답변을 해당 id로 교체하고, 데이터세트의 더 편리한 후처리를 위해 편평화 할 수 있습니다.
144
+
145
+ ```python
146
+ >>> def replace_ids(inputs):
147
+ ... inputs["label"]["ids"] = [label2id[x] for x in inputs["label"]["ids"]]
148
+ ... return inputs
149
+
150
+
151
+ >>> dataset = dataset.map(replace_ids)
152
+ >>> flat_dataset = dataset.flatten()
153
+ >>> flat_dataset.features
154
+ {'question': Value(dtype='string', id=None),
155
+ 'image_id': Value(dtype='string', id=None),
156
+ 'label.ids': Sequence(feature=Value(dtype='int64', id=None), length=-1, id=None),
157
+ 'label.weights': Sequence(feature=Value(dtype='float64', id=None), length=-1, id=None)}
158
+ ```
159
+
160
+ ## 데이터 전처리 [[preprocessing-data]]
161
+
162
+ 다음 단계는 모델을 위해 이미지와 텍스트 데이터를 준비하기 위해 ViLT 프로세서를 가져오는 것입니다.
163
+ [`ViltProcessor`]는 BERT 토크나이저와 ViLT 이미지 프로세서를 편리하게 하나의 프로세서로 묶습니다:
164
+
165
+ ```py
166
+ >>> from transformers import ViltProcessor
167
+
168
+ >>> processor = ViltProcessor.from_pretrained(model_checkpoint)
169
+ ```
170
+
171
+ 데이터를 전처리하려면 이미지와 질문을 [`ViltProcessor`]로 인코딩해야 합니다. 프로세서는 [`BertTokenizerFast`]로 텍스트를 토크나이즈하고 텍스트 데이터를 위해 `input_ids`, `attention_mask` 및 `token_type_ids`를 생성합니다.
172
+ 이미지는 [`ViltImageProcessor`]로 이미지를 크기 조정하고 정규화하며, `pixel_values`와 `pixel_mask`를 생성합니다.
173
+
174
+ 이런 전처리 단계는 모두 내부에서 이루어지므로, `processor`를 호출하기만 하면 됩니다. 하지만 아직 타겟 레이블이 완성되지 않았습니다. 타겟의 표현에서 각 요소는 가능한 답변(레이블)에 해당합니다. 정확한 답변의 요소는 해당 점수(weight)를 유지시키고 나머지 요소는 0으로 설정해야 합니다.
175
+
176
+ 아래 함수가 위에서 설명한대로 이미지와 질문에 `processor`를 적용하고 레이블을 형식에 맞춥니다:
177
+
178
+ ```py
179
+ >>> import torch
180
+
181
+ >>> def preprocess_data(examples):
182
+ ... image_paths = examples['image_id']
183
+ ... images = [Image.open(image_path) for image_path in image_paths]
184
+ ... texts = examples['question']
185
+
186
+ ... encoding = processor(images, texts, padding="max_length", truncation=True, return_tensors="pt")
187
+
188
+ ... for k, v in encoding.items():
189
+ ... encoding[k] = v.squeeze()
190
+
191
+ ... targets = []
192
+
193
+ ... for labels, scores in zip(examples['label.ids'], examples['label.weights']):
194
+ ... target = torch.zeros(len(id2label))
195
+
196
+ ... for label, score in zip(labels, scores):
197
+ ... target[label] = score
198
+
199
+ ... targets.append(target)
200
+
201
+ ... encoding["labels"] = targets
202
+
203
+ ... return encoding
204
+ ```
205
+
206
+ 전체 데이터세트에 전처리 함수를 적용하려면 🤗 Datasets의 [`~datasets.map`] 함수를 사용하십시오. `batched=True`를 설정하여 데이터세트의 여러 요소를 한 번에 처리함으로써 `map`을 더 빠르게 할 수 있습니다. 이 시점에서 필요하지 않은 열은 제거하세요.
207
+
208
+ ```py
209
+ >>> processed_dataset = flat_dataset.map(preprocess_data, batched=True, remove_columns=['question','question_type', 'question_id', 'image_id', 'answer_type', 'label.ids', 'label.weights'])
210
+ >>> processed_dataset
211
+ Dataset({
212
+ features: ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values', 'pixel_mask', 'labels'],
213
+ num_rows: 200
214
+ })
215
+ ```
216
+
217
+ 마지막 단계로, [`DefaultDataCollator`]를 사용하여 예제로 쓸 배치를 생성하세요:
218
+
219
+ ```py
220
+ >>> from transformers import DefaultDataCollator
221
+
222
+ >>> data_collator = DefaultDataCollator()
223
+ ```
224
+
225
+ ## 모델 훈련 [[train-the-model]]
226
+
227
+ 이제 모델을 훈련하기 위해 준비되었습니다! [`ViltForQuestionAnswering`]으로 ViLT를 가져올 차례입니다. 레이블의 수와 레이블 매핑을 지정하세요:
228
+
229
+ ```py
230
+ >>> from transformers import ViltForQuestionAnswering
231
+
232
+ >>> model = ViltForQuestionAnswering.from_pretrained(model_checkpoint, num_labels=len(id2label), id2label=id2label, label2id=label2id)
233
+ ```
234
+
235
+ 이 시점에서는 다음 세 단계만 남았습니다:
236
+
237
+ 1. [`TrainingArguments`]에서 훈련 하이퍼파라미터를 정의하세요:
238
+
239
+ ```py
240
+ >>> from transformers import TrainingArguments
241
+
242
+ >>> repo_id = "MariaK/vilt_finetuned_200"
243
+
244
+ >>> training_args = TrainingArguments(
245
+ ... output_dir=repo_id,
246
+ ... per_device_train_batch_size=4,
247
+ ... num_train_epochs=20,
248
+ ... save_steps=200,
249
+ ... logging_steps=50,
250
+ ... learning_rate=5e-5,
251
+ ... save_total_limit=2,
252
+ ... remove_unused_columns=False,
253
+ ... push_to_hub=True,
254
+ ... )
255
+ ```
256
+
257
+ 2. 모델, 데이터세트, 프로세서, 데이터 콜레이터와 함께 훈련 인수를 [`Trainer`]에 전달하세요:
258
+
259
+ ```py
260
+ >>> from transformers import Trainer
261
+
262
+ >>> trainer = Trainer(
263
+ ... model=model,
264
+ ... args=training_args,
265
+ ... data_collator=data_collator,
266
+ ... train_dataset=processed_dataset,
267
+ ... processing_class=processor,
268
+ ... )
269
+ ```
270
+
271
+ 3. [`~Trainer.train`]을 호출하여 모델을 미세 조정하세요:
272
+
273
+ ```py
274
+ >>> trainer.train()
275
+ ```
276
+
277
+ 훈련이 완료되면, [`~Trainer.push_to_hub`] 메소드를 사용하여 🤗 Hub에 모델을 공유하세요:
278
+
279
+ ```py
280
+ >>> trainer.push_to_hub()
281
+ ```
282
+
283
+ ## 추론 [[inference]]
284
+
285
+ ViLT 모델을 미세 조정하고 🤗 Hub에 업로드했다면 추론에 사용할 수 있습니다. 미세 조정된 모델을 추론에 사용해보는 가장 간단한 방법은 [`Pipeline`]에서 사용하는 것입니다.
286
+
287
+ ```py
288
+ >>> from transformers import pipeline
289
+
290
+ >>> pipe = pipeline("visual-question-answering", model="MariaK/vilt_finetuned_200")
291
+ ```
292
+
293
+ 이 가이드의 모델은 200개의 예제에서만 훈련되었으므로 그다지 많은 것을 기대할 수는 없습니다. 데이터세트의 첫 번째 예제를 사용하여 추론 결과를 설명해보겠습니다:
294
+
295
+ ```py
296
+ >>> example = dataset[0]
297
+ >>> image = Image.open(example['image_id'])
298
+ >>> question = example['question']
299
+ >>> print(question)
300
+ >>> pipe(image, question, top_k=1)
301
+ "Where is he looking?"
302
+ [{'score': 0.5498199462890625, 'answer': 'down'}]
303
+ ```
304
+
305
+ 비록 확신은 별로 없지만, 모델은 실제로 무언가를 배웠습니다. 더 많은 예제와 더 긴 훈련 기간이 주어진다면 분명 더 나은 결과를 얻을 수 있을 것입니다!
306
+
307
+ 원한다면 파이프라인의 결과를 수동으로 복제할 수도 있습니다:
308
+ 1. 이미지와 질문을 가져와서 프로세서를 사용하여 모델에 준비합니다.
309
+ 2. 전처리된 결과를 모델에 전달합니다.
310
+ 3. 로짓에서 가장 가능성 있는 답변의 id를 가져와서 `id2label`에서 실제 답변을 찾습니다.
311
+
312
+ ```py
313
+ >>> processor = ViltProcessor.from_pretrained("MariaK/vilt_finetuned_200")
314
+
315
+ >>> image = Image.open(example['image_id'])
316
+ >>> question = example['question']
317
+
318
+ >>> # prepare inputs
319
+ >>> inputs = processor(image, question, return_tensors="pt")
320
+
321
+ >>> model = ViltForQuestionAnswering.from_pretrained("MariaK/vilt_finetuned_200")
322
+
323
+ >>> # forward pass
324
+ >>> with torch.no_grad():
325
+ ... outputs = model(**inputs)
326
+
327
+ >>> logits = outputs.logits
328
+ >>> idx = logits.argmax(-1).item()
329
+ >>> print("Predicted answer:", model.config.id2label[idx])
330
+ Predicted answer: down
331
+ ```
332
+
333
+ ## 제로샷 VQA [[zeroshot-vqa]]
334
+
335
+ 이전 모델은 VQA를 분류 문제로 처리했습니다. BLIP, BLIP-2 및 InstructBLIP와 같은 최근의 모델은 VQA를 생성 작업으로 접근합니다. [BLIP-2](../../en/model_doc/blip-2)를 예로 들어 보겠습니다. 이 모델은 사전훈련된 비전 인코더와 LLM의 모든 조합을 사용할 수 있는 새로운 비전-자연어 사전 학습 패러다임을 도입했습니다. ([BLIP-2 블로그 포스트](https://huggingface.co/blog/blip-2)를 통해 더 자세히 알아볼 수 있어요)
336
+ 이를 통해 시각적 질의응답을 포함한 여러 비전-자연어 작업에서 SOTA를 달성할 수 있었습니다.
337
+
338
+ 이 모델을 어떻게 VQA에 사용할 수 있는지 설명해 보겠습니다. 먼저 모델을 가져와 보겠습니다. 여기서 GPU가 사용 가능한 경우 모델을 명시적으로 GPU로 전송할 것입니다. 이전에는 훈련할 때 쓰지 않은 이유는 [`Trainer`]가 이 부분을 자동으로 처리하기 때문입니다:
339
+
340
+ ```py
341
+ >>> from transformers import AutoProcessor, Blip2ForConditionalGeneration
342
+ >>> import torch
343
+
344
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip2-opt-2.7b")
345
+ >>> model = Blip2ForConditionalGeneration.from_pretrained("Salesforce/blip2-opt-2.7b", torch_dtype=torch.float16)
346
+ >>> device = "cuda" if torch.cuda.is_available() else "cpu"
347
+ >>> model.to(device)
348
+ ```
349
+
350
+ 모델은 이미지와 텍스트를 입력으로 받으므로, VQA 데이터세트의 첫 번째 예제에서와 동일한 이미지/질문 쌍을 사용해 보겠습니다:
351
+
352
+ ```py
353
+ >>> example = dataset[0]
354
+ >>> image = Image.open(example['image_id'])
355
+ >>> question = example['question']
356
+ ```
357
+
358
+ BLIP-2를 시각적 질의응답 작업에 사용하려면 텍스트 프롬프트가 `Question: {} Answer:` 형식을 따라야 합니다.
359
+
360
+ ```py
361
+ >>> prompt = f"Question: {question} Answer:"
362
+ ```
363
+
364
+ 이제 모델의 프로세서로 이미지/프롬프트를 전처리하고, 처리된 입력을 모델을 통해 전달하고, 출력을 디코드해야 합니다:
365
+
366
+ ```py
367
+ >>> inputs = processor(image, text=prompt, return_tensors="pt").to(device, torch.float16)
368
+
369
+ >>> generated_ids = model.generate(**inputs, max_new_tokens=10)
370
+ >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
371
+ >>> print(generated_text)
372
+ "He is looking at the crowd"
373
+ ```
374
+
375
+ 보시다시피 모델은 군중을 인식하고, 얼굴의 방향(아래쪽을 보고 있음)을 인식했지만, 군중이 스케이터 뒤에 있다는 사실을 놓쳤습니다. 그러나 사람이 직접 라벨링한 데이터셋을 얻을 수 없는 경우에, 이 접근법은 빠르게 유용한 결과를 생성할 수 있습니다.
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/zero_shot_image_classification.md ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2023 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # 제로샷(zero-shot) 이미지 분류[[zeroshot-image-classification]]
18
+
19
+ [[open-in-colab]]
20
+
21
+ 제로샷(zero-shot) 이미지 분류는 특정 카테고리의 예시가 포함된 데이터를 학습되지 않은 모델을 사용해 이미지 분류를 수행하는 작업입니다.
22
+
23
+ 일반적으로 이미지 분류를 위해서는 레이블이 달린 특정 이미지 데이터로 모델 학습이 필요하며, 이 모델은 특정 이미지의 특징을 레이블에 "매핑"하는 방법을 학습합니다.
24
+ 새로운 레이블이 있는 분류 작업에 이러한 모델을 사용해야 하는 경우에는, 모델을 "재보정"하기 위해 미세 조정이 필요합니다.
25
+
26
+ 이와 대조적으로, 제로샷 또는 개방형 어휘(open vocabulary) 이미지 분류 모델은 일반적으로 대규모 이미지 데이터와 해당 설명에 대해 학습된 멀티모달(multimodal) 모델입니다.
27
+ 이러한 모델은 제로샷 이미지 분류를 포함한 많은 다운스트림 작업에 사용할 수 있는 정렬된(aligned) 비전 언어 표현을 학습합니다.
28
+
29
+ 이는 이미지 분류에 대한 보다 유연한 접근 방식으로, 추가 학습 데이터 없이 새로운 레이블이나 학습하지 못한 카테고리에 대해 모델을 일반화할 수 있습니다.
30
+ 또한, 사용자가 대상 개체에 대한 자유 형식의 텍스트 설명으로 이미지를 검색할 수 있습니다.
31
+
32
+ 이번 가이드에서 배울 내용은 다음과 같습니다:
33
+
34
+ * 제로샷 이미지 분류 파이프라인 만들기
35
+ * 직접 제로샷 이미지 분류 모델 추론 실행하기
36
+
37
+ 시작하기 전에 필요한 라이브러리가 모두 설치되어 있는지 확인하세요:
38
+
39
+ ```bash
40
+ pip install -q transformers
41
+ ```
42
+
43
+ ## 제로샷(zero-shot) 이미지 분류 파이프라인[[zeroshot-image-classification-pipeline]]
44
+
45
+ [`pipeline`]을 활용하면 가장 간단하게 제로샷 이미지 분류를 지원하는 모델로 추론해볼 수 있습니다.
46
+ [Hugging Face Hub에 업로드된 체크포인트](https://huggingface.co/models?pipeline_tag=zero-shot-image-classification&sort=downloads)에서 파이프라인을 인스턴스화합니다.
47
+
48
+ ```python
49
+ >>> from transformers import pipeline
50
+
51
+ >>> checkpoint = "openai/clip-vit-large-patch14"
52
+ >>> detector = pipeline(model=checkpoint, task="zero-shot-image-classification")
53
+ ```
54
+
55
+ 다음으로, 분류하고 싶은 이미지를 선택하세요.
56
+
57
+ ```py
58
+ >>> from PIL import Image
59
+ >>> import requests
60
+
61
+ >>> url = "https://unsplash.com/photos/g8oS8-82DxI/download?ixid=MnwxMjA3fDB8MXx0b3BpY3x8SnBnNktpZGwtSGt8fHx8fDJ8fDE2NzgxMDYwODc&force=true&w=640"
62
+ >>> image = Image.open(requests.get(url, stream=True).raw)
63
+
64
+ >>> image
65
+ ```
66
+
67
+ <div class="flex justify-center">
68
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/owl.jpg" alt="Photo of an owl"/>
69
+ </div>
70
+
71
+ 이미지와 해당 이미지의 후보 레이블인 `candidate_labels`를 파이프라인으로 전달합니다.
72
+ 여기서는 이미지를 직접 전달하지만, 컴퓨터에 저장된 이미지의 경로나 url로 전달할 수도 있습니다.
73
+ `candidate_labels`는 이 예시처럼 간단한 단어일 수도 있고 좀 더 설명적인 단어일 수도 있습니다.
74
+
75
+ ```py
76
+ >>> predictions = classifier(image, candidate_labels=["fox", "bear", "seagull", "owl"])
77
+ >>> predictions
78
+ [{'score': 0.9996670484542847, 'label': 'owl'},
79
+ {'score': 0.000199399160919711, 'label': 'seagull'},
80
+ {'score': 7.392891711788252e-05, 'label': 'fox'},
81
+ {'score': 5.96074532950297e-05, 'label': 'bear'}]
82
+ ```
83
+
84
+ ## 직접 제로샷(zero-shot) 이미지 분류하기[[zeroshot-image-classification-by-hand]]
85
+
86
+ 이제 제로샷 이미지 분류 파이프라인 사용 방법을 살펴보았으니, 실행하는 방법을 살펴보겠습니다.
87
+
88
+ [Hugging Face Hub에 업로드된 체크포인트](https://huggingface.co/models?pipeline_tag=zero-shot-image-classification&sort=downloads)에서 모델과 프로세서를 가져오는 것으로 시작합니다.
89
+ 여기서는 이전과 동일한 체크포인트를 사용하겠습니다:
90
+
91
+ ```py
92
+ >>> from transformers import AutoProcessor, AutoModelForZeroShotImageClassification
93
+
94
+ >>> model = AutoModelForZeroShotImageClassification.from_pretrained(checkpoint)
95
+ >>> processor = AutoProcessor.from_pretrained(checkpoint)
96
+ ```
97
+
98
+ 다른 이미지를 사용해 보겠습니다.
99
+
100
+ ```py
101
+ >>> from PIL import Image
102
+ >>> import requests
103
+
104
+ >>> url = "https://unsplash.com/photos/xBRQfR2bqNI/download?ixid=MnwxMjA3fDB8MXxhbGx8fHx8fHx8fHwxNjc4Mzg4ODEx&force=true&w=640"
105
+ >>> image = Image.open(requests.get(url, stream=True).raw)
106
+
107
+ >>> image
108
+ ```
109
+
110
+ <div class="flex justify-center">
111
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg" alt="Photo of a car"/>
112
+ </div>
113
+
114
+ 프로세서를 사용해 모델의 입력을 준비합니다.
115
+ 프로세서는 모델의 입력으로 사용하기 위해 이미지 크기를 변환하고 정규화하는 이미지 프로세서와 텍스트 입력을 처리하는 토크나이저로 구성됩니다.
116
+
117
+ ```py
118
+ >>> candidate_labels = ["tree", "car", "bike", "cat"]
119
+ >>> inputs = processor(images=image, text=candidate_labels, return_tensors="pt", padding=True)
120
+ ```
121
+
122
+ 모델에 입력을 전달하고, 결과를 후처리합니다:
123
+
124
+ ```py
125
+ >>> import torch
126
+
127
+ >>> with torch.no_grad():
128
+ ... outputs = model(**inputs)
129
+
130
+ >>> logits = outputs.logits_per_image[0]
131
+ >>> probs = logits.softmax(dim=-1).numpy()
132
+ >>> scores = probs.tolist()
133
+
134
+ >>> result = [
135
+ ... {"score": score, "label": candidate_label}
136
+ ... for score, candidate_label in sorted(zip(probs, candidate_labels), key=lambda x: -x[0])
137
+ ... ]
138
+
139
+ >>> result
140
+ [{'score': 0.998572, 'label': 'car'},
141
+ {'score': 0.0010570387, 'label': 'bike'},
142
+ {'score': 0.0003393686, 'label': 'tree'},
143
+ {'score': 3.1572064e-05, 'label': 'cat'}]
144
+ ```
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tasks/zero_shot_object_detection.md ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2023 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # 제로샷(zero-shot) 객체 탐지[[zeroshot-object-detection]]
18
+
19
+ [[open-in-colab]]
20
+
21
+ 일반적으로 [객체 탐지](object_detection)에 사용되는 모델을 학습하기 위해서는 레이블이 지정된 이미지 데이터 세트가 필요합니다.
22
+ 그리고 학습 데이터에 존재하는 클래스(레이블)만 탐지할 수 있다는 한계점이 있습니다.
23
+
24
+ 다른 방식을 사용하는 [OWL-ViT](../model_doc/owlvit) 모델로 제로샷 객체 탐지가 가능합니다.
25
+ OWL-ViT는 개방형 어휘(open-vocabulary) 객체 탐지기입니다.
26
+ 즉, 레이블이 지정된 데이터 세트에 미세 조정하지 않고 자유 텍스트 쿼리를 기반으로 이미지에서 객체를 탐지할 수 있습니다.
27
+
28
+ OWL-ViT 모델은 멀티 모달 표현을 활용해 개방형 어휘 탐지(open-vocabulary detection)를 수행합니다.
29
+ [CLIP](../model_doc/clip) 모델에 경량화(lightweight)된 객체 분류와 지역화(localization) 헤드를 결합합니다.
30
+ 개방형 어휘 탐지는 CLIP의 텍스트 인코더로 free-text 쿼리를 임베딩하고, 객체 분류와 지역화 헤드의 입력으로 사용합니다.
31
+ 이미지와 해당 텍스트 설명을 연결하면 ViT가 이미지 패치(image patches)를 입력으로 처리합니다.
32
+ OWL-ViT 모델의 저자들은 CLIP 모델을 처음부터 학습(scratch learning)한 후에, bipartite matching loss를 사용하여 표준 객체 인식 데이터셋으로 OWL-ViT 모델을 미세 조정했습니다.
33
+
34
+ 이 접근 방식을 사용하면 모델은 레이블이 지정된 데이터 세트에 대한 사전 학습 없이도 텍스트 설명을 기반으로 객체를 탐지할 수 있습니다.
35
+
36
+ 이번 가이드에서는 OWL-ViT 모델의 사용법을 다룰 것입니다:
37
+ - 텍스트 프롬프트 기반 객체 탐지
38
+ - 일괄 객체 탐지
39
+ - 이미지 가이드 객체 탐지
40
+
41
+ 시작하기 전에 필요한 라이브러리가 모두 설치되어 있는지 확인하세요:
42
+ ```bash
43
+ pip install -q transformers
44
+ ```
45
+
46
+ ## 제로샷(zero-shot) 객체 탐지 파이프라인[[zeroshot-object-detection-pipeline]]
47
+
48
+ [`pipeline`]을 활용하면 가장 간단하게 OWL-ViT 모델을 추론해볼 수 있습니다.
49
+ [Hugging Face Hub에 업로드된 체크포인트](https://huggingface.co/models?pipeline_tag=zero-shot-image-classification&sort=downloads)에서 제로샷(zero-shot) 객체 탐지용 파이프라인을 인스턴스화합니다:
50
+
51
+ ```python
52
+ >>> from transformers import pipeline
53
+
54
+ >>> checkpoint = "google/owlvit-base-patch32"
55
+ >>> detector = pipeline(model=checkpoint, task="zero-shot-object-detection")
56
+ ```
57
+
58
+ 다음으로, 객체를 탐지하고 싶은 이미지를 선택하세요.
59
+ 여기서는 [NASA](https://www.nasa.gov/multimedia/imagegallery/index.html) Great Images 데이터 세트의 일부인 우주비행사 에일린 콜린스(Eileen Collins) 사진을 사용하겠습니다.
60
+
61
+ ```py
62
+ >>> import skimage
63
+ >>> import numpy as np
64
+ >>> from PIL import Image
65
+
66
+ >>> image = skimage.data.astronaut()
67
+ >>> image = Image.fromarray(np.uint8(image)).convert("RGB")
68
+
69
+ >>> image
70
+ ```
71
+
72
+ <div class="flex justify-center">
73
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_1.png" alt="Astronaut Eileen Collins"/>
74
+ </div>
75
+
76
+ 이미지와 해당 이미지의 후보 레이블을 파이프라인으로 전달합니다.
77
+ 여기서는 이미지를 직접 전달하지만, 컴퓨터에 저장된 이미지의 경로나 url로 전달할 수도 있습니다.
78
+ candidate_labels는 이 예시처럼 간단한 단어일 수도 있고 좀 더 설명적인 단어일 수도 있습니다.
79
+ 또한, 이미지를 검색(query)하려는 모든 항목에 대한 텍스트 설명도 전달합니다.
80
+
81
+ ```py
82
+ >>> predictions = detector(
83
+ ... image,
84
+ ... candidate_labels=["human face", "rocket", "nasa badge", "star-spangled banner"],
85
+ ... )
86
+ >>> predictions
87
+ [{'score': 0.3571370542049408,
88
+ 'label': 'human face',
89
+ 'box': {'xmin': 180, 'ymin': 71, 'xmax': 271, 'ymax': 178}},
90
+ {'score': 0.28099656105041504,
91
+ 'label': 'nasa badge',
92
+ 'box': {'xmin': 129, 'ymin': 348, 'xmax': 206, 'ymax': 427}},
93
+ {'score': 0.2110239565372467,
94
+ 'label': 'rocket',
95
+ 'box': {'xmin': 350, 'ymin': -1, 'xmax': 468, 'ymax': 288}},
96
+ {'score': 0.13790413737297058,
97
+ 'label': 'star-spangled banner',
98
+ 'box': {'xmin': 1, 'ymin': 1, 'xmax': 105, 'ymax': 509}},
99
+ {'score': 0.11950037628412247,
100
+ 'label': 'nasa badge',
101
+ 'box': {'xmin': 277, 'ymin': 338, 'xmax': 327, 'ymax': 380}},
102
+ {'score': 0.10649408400058746,
103
+ 'label': 'rocket',
104
+ 'box': {'xmin': 358, 'ymin': 64, 'xmax': 424, 'ymax': 280}}]
105
+ ```
106
+
107
+ 이제 예측값을 시각화해봅시다:
108
+
109
+ ```py
110
+ >>> from PIL import ImageDraw
111
+
112
+ >>> draw = ImageDraw.Draw(image)
113
+
114
+ >>> for prediction in predictions:
115
+ ... box = prediction["box"]
116
+ ... label = prediction["label"]
117
+ ... score = prediction["score"]
118
+
119
+ ... xmin, ymin, xmax, ymax = box.values()
120
+ ... draw.rectangle((xmin, ymin, xmax, ymax), outline="red", width=1)
121
+ ... draw.text((xmin, ymin), f"{label}: {round(score,2)}", fill="white")
122
+
123
+ >>> image
124
+ ```
125
+
126
+ <div class="flex justify-center">
127
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_2.png" alt="Visualized predictions on NASA image"/>
128
+ </div>
129
+
130
+ ## 텍스트 프롬프트 기반 객체 탐지[[textprompted-zeroshot-object-detection-by-hand]]
131
+
132
+ 제로샷 객체 탐지 파이프라인 사용법에 대해 살펴보았으니, 이제 동일한 결과를 복제해보겠습니다.
133
+
134
+ [Hugging Face Hub에 업로드된 체크포인트](https://huggingface.co/models?other=owlvit)에서 관련 모델과 프로세서를 가져오는 것으로 시작합니다.
135
+ 여기서는 이전과 동일한 체크포인트를 사용하겠습니다:
136
+
137
+ ```py
138
+ >>> from transformers import AutoProcessor, AutoModelForZeroShotObjectDetection
139
+
140
+ >>> model = AutoModelForZeroShotObjectDetection.from_pretrained(checkpoint)
141
+ >>> processor = AutoProcessor.from_pretrained(checkpoint)
142
+ ```
143
+
144
+ 다른 이미지를 사용해 보겠습니다:
145
+
146
+ ```py
147
+ >>> import requests
148
+
149
+ >>> url = "https://unsplash.com/photos/oj0zeY2Ltk4/download?ixid=MnwxMjA3fDB8MXxzZWFyY2h8MTR8fHBpY25pY3xlbnwwfHx8fDE2Nzc0OTE1NDk&force=true&w=640"
150
+ >>> im = Image.open(requests.get(url, stream=True).raw)
151
+ >>> im
152
+ ```
153
+
154
+ <div class="flex justify-center">
155
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_3.png" alt="Beach photo"/>
156
+ </div>
157
+
158
+ 프로세서를 사용해 모델의 입력을 준비합니다.
159
+ 프로세서는 모델의 입력으로 사용하기 위해 이미지 크기를 변환하고 정규화하는 이미지 프로세서와 텍스트 입력을 처리하는 [`CLIPTokenizer`]로 구성됩니다.
160
+
161
+ ```py
162
+ >>> text_queries = ["hat", "book", "sunglasses", "camera"]
163
+ >>> inputs = processor(text=text_queries, images=im, return_tensors="pt")
164
+ ```
165
+
166
+ 모델에 입력을 전달하고 결과를 후처리 및 시각화합니다.
167
+ 이미지 프로세서가 모델에 이미지를 입력하기 전에 이미지 크기를 조정했기 때문에, [`~OwlViTImageProcessor.post_process_object_detection`] 메소드를 사용해
168
+ 예측값의 바운딩 박스(bounding box)가 원본 이미지의 좌표와 상대적으로 동일한지 확인해야 합니다.
169
+
170
+ ```py
171
+ >>> import torch
172
+
173
+ >>> with torch.no_grad():
174
+ ... outputs = model(**inputs)
175
+ ... target_sizes = torch.tensor([im.size[::-1]])
176
+ ... results = processor.post_process_object_detection(outputs, threshold=0.1, target_sizes=target_sizes)[0]
177
+
178
+ >>> draw = ImageDraw.Draw(im)
179
+
180
+ >>> scores = results["scores"].tolist()
181
+ >>> labels = results["labels"].tolist()
182
+ >>> boxes = results["boxes"].tolist()
183
+
184
+ >>> for box, score, label in zip(boxes, scores, labels):
185
+ ... xmin, ymin, xmax, ymax = box
186
+ ... draw.rectangle((xmin, ymin, xmax, ymax), outline="red", width=1)
187
+ ... draw.text((xmin, ymin), f"{text_queries[label]}: {round(score,2)}", fill="white")
188
+
189
+ >>> im
190
+ ```
191
+
192
+ <div class="flex justify-center">
193
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_4.png" alt="Beach photo with detected objects"/>
194
+ </div>
195
+
196
+ ## 일괄 처리[[batch-processing]]
197
+
198
+ 여러 이미지와 텍스트 쿼리를 전달하여 여러 이미지에서 서로 다른(또는 동일한) 객체를 검색할 수 있습니다.
199
+ 일괄 처리를 위해서 텍스트 쿼리는 이중 리스트로, 이미지는 PIL 이미지, PyTorch 텐서, 또는 NumPy 배열로 이루어진 리스트로 프로세서에 전달해야 합니다.
200
+
201
+ ```py
202
+ >>> images = [image, im]
203
+ >>> text_queries = [
204
+ ... ["human face", "rocket", "nasa badge", "star-spangled banner"],
205
+ ... ["hat", "book", "sunglasses", "camera"],
206
+ ... ]
207
+ >>> inputs = processor(text=text_queries, images=images, return_tensors="pt")
208
+ ```
209
+
210
+ 이전에는 후처리를 위해 단일 이미지의 크기를 텐서로 전달했지만, 튜플을 전달할 수 있고, 여러 이미지를 처리하는 경우에는 튜플로 이루어진 리스트를 전달할 수도 있습니다.
211
+ 아래 두 예제에 대한 예측을 생성하고, 두 번째 이미지(`image_idx = 1`)를 시각화해 보겠습니다.
212
+
213
+ ```py
214
+ >>> with torch.no_grad():
215
+ ... outputs = model(**inputs)
216
+ ... target_sizes = [x.size[::-1] for x in images]
217
+ ... results = processor.post_process_object_detection(outputs, threshold=0.1, target_sizes=target_sizes)
218
+
219
+ >>> image_idx = 1
220
+ >>> draw = ImageDraw.Draw(images[image_idx])
221
+
222
+ >>> scores = results[image_idx]["scores"].tolist()
223
+ >>> labels = results[image_idx]["labels"].tolist()
224
+ >>> boxes = results[image_idx]["boxes"].tolist()
225
+
226
+ >>> for box, score, label in zip(boxes, scores, labels):
227
+ ... xmin, ymin, xmax, ymax = box
228
+ ... draw.rectangle((xmin, ymin, xmax, ymax), outline="red", width=1)
229
+ ... draw.text((xmin, ymin), f"{text_queries[image_idx][label]}: {round(score,2)}", fill="white")
230
+
231
+ >>> images[image_idx]
232
+ ```
233
+
234
+ <div class="flex justify-center">
235
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_4.png" alt="Beach photo with detected objects"/>
236
+ </div>
237
+
238
+ ## 이미지 가이드 객체 탐지[[imageguided-object-detection]]
239
+
240
+ 텍스트 쿼리를 이용한 제로샷 객체 탐지 외에도 OWL-ViT 모델은 이미지 가이드 객체 탐지 기능을 제공합니다.
241
+ 이미지를 쿼리로 사용해 대상 이미지에서 유사한 객체를 찾을 수 있다는 의미입니다.
242
+ 텍스트 쿼리와 달리 하나의 예제 이미지에서만 가능합니다.
243
+
244
+ 소파에 고양이 두 마리가 있는 이미지를 대상 이미지(target image)로, 고양이 한 마리가 있는 이미지를 쿼리로 사용해보겠습니다:
245
+
246
+ ```py
247
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
248
+ >>> image_target = Image.open(requests.get(url, stream=True).raw)
249
+
250
+ >>> query_url = "http://images.cocodataset.org/val2017/000000524280.jpg"
251
+ >>> query_image = Image.open(requests.get(query_url, stream=True).raw)
252
+ ```
253
+
254
+ 다음 이미지를 살펴보겠습니다:
255
+
256
+ ```py
257
+ >>> import matplotlib.pyplot as plt
258
+
259
+ >>> fig, ax = plt.subplots(1, 2)
260
+ >>> ax[0].imshow(image_target)
261
+ >>> ax[1].imshow(query_image)
262
+ ```
263
+
264
+ <div class="flex justify-center">
265
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_5.png" alt="Cats"/>
266
+ </div>
267
+
268
+ 전처리 단계에서 텍스트 쿼리 대신에 `query_images`를 사용합니다:
269
+
270
+ ```py
271
+ >>> inputs = processor(images=image_target, query_images=query_image, return_tensors="pt")
272
+ ```
273
+
274
+ 예측의 경우, 모델에 입력을 전달하는 대신 [`~OwlViTForObjectDetection.image_guided_detection`]에 전달합니다.
275
+ 레이블이 없다는 점을 제외하면 이전과 동일합니다.
276
+ 이전과 동일하게 이미지를 시각화합니다.
277
+
278
+ ```py
279
+ >>> with torch.no_grad():
280
+ ... outputs = model.image_guided_detection(**inputs)
281
+ ... target_sizes = torch.tensor([image_target.size[::-1]])
282
+ ... results = processor.post_process_image_guided_detection(outputs=outputs, target_sizes=target_sizes)[0]
283
+
284
+ >>> draw = ImageDraw.Draw(image_target)
285
+
286
+ >>> scores = results["scores"].tolist()
287
+ >>> boxes = results["boxes"].tolist()
288
+
289
+ >>> for box, score, label in zip(boxes, scores, labels):
290
+ ... xmin, ymin, xmax, ymax = box
291
+ ... draw.rectangle((xmin, ymin, xmax, ymax), outline="white", width=4)
292
+
293
+ >>> image_target
294
+ ```
295
+
296
+ <div class="flex justify-center">
297
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_6.png" alt="Cats with bounding boxes"/>
298
+ </div>
299
+
300
+ OWL-ViT 모델을 추론하고 싶다면 아래 데모를 확인하세요:
301
+
302
+ <iframe
303
+ src="https://adirik-owl-vit.hf.space"
304
+ frameborder="0"
305
+ width="850"
306
+ height="450"
307
+ ></iframe>
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/testing.md ADDED
@@ -0,0 +1,1271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2020 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # 테스트[[testing]]
18
+
19
+
20
+ 먼저 🤗 Transformers 모델이 어떻게 테스트되는지 살펴보고, 새로운 테스트를 작성 및 기존 테스트를 개선하는 방법을 알아봅시다.
21
+
22
+ 이 저장소에는 2개의 테스트 스위트가 있습니다:
23
+
24
+ 1. `tests` - 일반 API에 대한 테스트
25
+ 2. `examples` - API의 일부가 아닌 다양한 응용 프로그램에 대한 테스트
26
+
27
+ ## Transformers 테스트 방법[[how-transformers-are-tested]]
28
+
29
+ 1. PR이 제출되면 9개의 CircleCi 작업으로 테스트가 진행됩니다. 해당 PR에 대해 새로운 커밋이 생성될 때마다 테스트는 다시 진행됩니다. 이 작업들은
30
+ 이 [config 파일](https://github.com/huggingface/transformers/tree/main/.circleci/config.yml)에 정의되어 있으므로 필요하다면
31
+ 사용자의 로컬 환경에서 동일하게 재현해 볼 수 있습니다.
32
+
33
+ 이 CI 작업은 `@slow` 테스트를 실행하지 않습니다.
34
+
35
+ 2. [github actions](https://github.com/huggingface/transformers/actions)에 의해 실행되는 작업은 3개입니다:
36
+
37
+ - [torch hub integration](https://github.com/huggingface/transformers/tree/main/.github/workflows/github-torch-hub.yml):
38
+ torch hub integration이 작동하는지 확인합니다.
39
+
40
+ - [self-hosted (push)](https://github.com/huggingface/transformers/tree/main/.github/workflows/self-push.yml): `main` 브랜치에서 커밋이 업데이트된 경우에만 GPU를 이용한 빠른 테스트를 실행합니다.
41
+ 이는 `src`, `tests`, `.github` 폴더 중 하나에 코드가 업데이트된 경우에만 실행됩니다.
42
+ (model card, notebook, 기타 등등을 추가한 경우 실행되지 않도록 하기 위해서입니다)
43
+
44
+ - [self-hosted runner](https://github.com/huggingface/transformers/tree/main/.github/workflows/self-scheduled.yml): `tests` 및 `examples`에서
45
+ GPU를 이용한 일반 테스트, 느린 테스트를 실행합니다.
46
+
47
+
48
+ ```bash
49
+ RUN_SLOW=1 pytest tests/
50
+ RUN_SLOW=1 pytest examples/
51
+ ```
52
+
53
+ 결과는 [여기](https://github.com/huggingface/transformers/actions)에서 확인할 수 있습니다.
54
+
55
+
56
+ ## 테스트 실행[[running-tests]]
57
+
58
+
59
+
60
+
61
+
62
+ ### 실행할 테스트 선택[[choosing-which-tests-to-run]]
63
+
64
+ 이 문서는 테스트를 실행하는 다양한 방법에 대해 자세히 설명합니다.
65
+ 모든 내용을 읽은 후에도, 더 자세한 내용이 필요하다면 [여기](https://docs.pytest.org/en/latest/usage.html)에서 확인할 수 있습니다.
66
+
67
+ 다음은 가장 유용한 테스트 실행 방법 몇 가지입니다.
68
+
69
+ 모두 실행:
70
+
71
+ ```console
72
+ pytest
73
+ ```
74
+
75
+ 또는:
76
+
77
+ ```bash
78
+ make test
79
+ ```
80
+
81
+ 후자는 다음과 같이 정의됩니다:
82
+
83
+ ```bash
84
+ python -m pytest -n auto --dist=loadfile -s -v ./tests/
85
+ ```
86
+
87
+ 위의 명령어는 pytest에게 아래의 내용을 전달합니다:
88
+
89
+ - 사용 가능한 CPU 코어 수만큼 테스트 프로세스를 실행합니다. (RAM이 충분하지 않다면, 테스트 프로세스 수가 너무 많을 수 있습니다!)
90
+ - 동일한 파일의 모든 테스트는 동일한 테스트 프로세스에서 실행되어야 합니다.
91
+ - 출력을 캡처하지 않습니다.
92
+ - 자세한 모드로 실행합니다.
93
+
94
+
95
+
96
+ ### 모든 테스트 목록 가져오기[[getting-the-list-of-all-tests]]
97
+
98
+ 테스트 스위트의 모든 테스트:
99
+
100
+ ```bash
101
+ pytest --collect-only -q
102
+ ```
103
+
104
+ 지정된 테스트 파일의 모든 테스트:
105
+
106
+ ```bash
107
+ pytest tests/test_optimization.py --collect-only -q
108
+ ```
109
+
110
+ ### 특정 테스트 모듈 실행[[run-a-specific-test-module]]
111
+
112
+ 개별 테스트 모듈 실행하기:
113
+
114
+ ```bash
115
+ pytest tests/utils/test_logging.py
116
+ ```
117
+
118
+ ### 특정 테스트 실행[[run-specific-tests]]
119
+
120
+ 대부분의 테스트 내부에서는 unittest가 사용됩니다. 따라서 특정 하위 테스트를 실행하려면 해당 테스트를 포함하는 unittest 클래스의 이름을 알아야 합니다.
121
+ 예를 들어 다음과 같을 수 있습니다:
122
+
123
+ ```bash
124
+ pytest tests/test_optimization.py::OptimizationTest::test_adam_w
125
+ ```
126
+
127
+ 위의 명령어의 의미는 다음과 같습니다:
128
+
129
+ - `tests/test_optimization.py` - 테스트가 있는 파일
130
+ - `OptimizationTest` - 클래스의 이름
131
+ - `test_adam_w` - 특정 테스트 함수의 이름
132
+
133
+ 파일에 ���러 클래스가 포함된 경우, 특정 클래스의 테스트만 실행할 수도 있습니다. 예를 들어 다음과 같습니다:
134
+
135
+ ```bash
136
+ pytest tests/test_optimization.py::OptimizationTest
137
+ ```
138
+
139
+ 이 명령어는 해당 클래스 내부의 모든 테스트를 실행합니다.
140
+
141
+ 앞에서 언급한 것처럼 `OptimizationTest` 클래스에 포함된 테스트를 확인할 수 있습니다.
142
+
143
+ ```bash
144
+ pytest tests/test_optimization.py::OptimizationTest --collect-only -q
145
+ ```
146
+
147
+ 키워드 표현식을 사용하여 테스트를 실행할 수도 있습니다.
148
+
149
+ `adam`이라는 이름을 포함하는 테스트만 실행하려면 다음과 같습니다:
150
+
151
+ ```bash
152
+ pytest -k adam tests/test_optimization.py
153
+ ```
154
+
155
+ 논리 연산자 `and`와 `or`를 사용하여 모든 키워드가 일치해야 하는지 또는 어느 하나가 일치해야 하는지를 나타낼 수 있습니다.
156
+ `not`은 부정할 때 사용할 수 있습니다.
157
+
158
+ `adam`이라는 이름을 포함하지 않는 모든 테스트를 실행하려면 다음과 같습니다:
159
+
160
+ ```bash
161
+ pytest -k "not adam" tests/test_optimization.py
162
+ ```
163
+
164
+ 두 가지 패턴을 하나로 결합할 수도 있습니다:
165
+
166
+ ```bash
167
+ pytest -k "ada and not adam" tests/test_optimization.py
168
+ ```
169
+
170
+ 예를 들어 `test_adafactor`와 `test_adam_w`를 모두 실행하려면 다음을 사용할 수 있습니다:
171
+
172
+ ```bash
173
+ pytest -k "test_adam_w or test_adam_w" tests/test_optimization.py
174
+ ```
175
+
176
+ 여기서 `or`를 사용하는 것에 유의하세요. 두 키워드 중 하나가 일치하도록 하기 위한 목적으로 사용하기 때문입니다.
177
+
178
+ 두 패턴이 모두 포함되어야 하는 테스트만 실행하려면, `and`를 사용해야 합니다:
179
+
180
+ ```bash
181
+ pytest -k "test and ada" tests/test_optimization.py
182
+ ```
183
+
184
+ ### `accelerate` 테스트 실행[[run-`accelerate`-tests]]
185
+
186
+ 모델에서 `accelerate` 테스트를 실행해야 할 때가 있습니다. 이를 위해서는 명령어에 `-m accelerate_tests`를 추가하면 됩니다.
187
+ 예를 들어, `OPT`에서 이러한 테스트를 실행하려면 다음과 같습니다:
188
+ ```bash
189
+ RUN_SLOW=1 pytest -m accelerate_tests tests/models/opt/test_modeling_opt.py
190
+ ```
191
+
192
+ ### 문서 테스트 실행[[run-documentation-tests]]
193
+
194
+ 예시 문서가 올바른지 테스트하려면 `doctests`가 통과하는지 확인해야 합니다.
195
+ 예를 들어, [`WhisperModel.forward`'s docstring](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L1017-L1035)를 사용해 봅시다:
196
+
197
+ ```python
198
+ r"""
199
+ Returns:
200
+
201
+ Example:
202
+ ```python
203
+ >>> import torch
204
+ >>> from transformers import WhisperModel, WhisperFeatureExtractor
205
+ >>> from datasets import load_dataset
206
+
207
+ >>> model = WhisperModel.from_pretrained("openai/whisper-base")
208
+ >>> feature_extractor = WhisperFeatureExtractor.from_pretrained("openai/whisper-base")
209
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
210
+ >>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
211
+ >>> input_features = inputs.input_features
212
+ >>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
213
+ >>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state
214
+ >>> list(last_hidden_state.shape)
215
+ [1, 2, 512]
216
+ ```"""
217
+
218
+ ```
219
+
220
+ 원하는 파일의 모든 docstring 예제를 자동으로 테스트하려면 다음 명령을 실행하면 됩니다:
221
+ ```bash
222
+ pytest --doctest-modules <path_to_file_or_dir>
223
+ ```
224
+ 파일의 확장자가 markdown인 경우 `--doctest-glob="*.md"` 인수를 추가해야 합니다.
225
+
226
+ ### 수정된 테스트만 실행[[run-only-modified-tests]]
227
+
228
+ 수정된 파일 또는 현재 브랜치 (Git 기준)와 관련된 테스트를 실행하려면 [pytest-picked](https://github.com/anapaulagomes/pytest-picked)을 사용할 수 있습니다.
229
+ 이는 변경한 내용이 테스트에 영향을 주지 않았는지 빠르게 확인할 수 있는 좋은 방법입니다.
230
+
231
+ ```bash
232
+ pip install pytest-picked
233
+ ```
234
+
235
+ ```bash
236
+ pytest --picked
237
+ ```
238
+
239
+ 수정되었지만, 아직 커밋되지 않은 모든 파일 및 폴더에서 테스트가 실행됩니다.
240
+
241
+ ### 소스 수정 시 실패한 테스트 자동 재실행[[automatically-rerun-failed-tests-on-source-modification]]
242
+
243
+ [pytest-xdist](https://github.com/pytest-dev/pytest-xdist)는 모든 실패한 테스트를 감지하고,
244
+ 파일을 수정한 후에 파일을 계속 재실행하여 테스트가 성공할 때까지 기다리는 매우 유용한 기능을 제공합니다.
245
+ 따라서 수정한 내용을 확인한 후 pytest를 다시 시작할 필요가 없습니다.
246
+ 모든 테스트가 통과될 때까지 이 과정을 반복한 후 다시 전체 실행이 이루어집니다.
247
+
248
+ ```bash
249
+ pip install pytest-xdist
250
+ ```
251
+
252
+ 재귀적 모드의 사용: `pytest -f` 또는 `pytest --looponfail`
253
+
254
+ 파일의 변경 사항은 `looponfailroots` 루트 디렉터리와 해당 내용을 (재귀적으로) 확인하여 감지됩니다.
255
+ 이 값의 기본값이 작동하지 않는 경우,
256
+ `setup.cfg`의 설정 옵션을 변경하여 프로젝트에서 변경할 수 있습니다:
257
+
258
+ ```ini
259
+ [tool:pytest]
260
+ looponfailroots = transformers tests
261
+ ```
262
+
263
+ 또는 `pytest.ini`/`tox.ini`` 파일:
264
+
265
+ ```ini
266
+ [pytest]
267
+ looponfailroots = transformers tests
268
+ ```
269
+
270
+ 이렇게 하면 ini-file의 디렉터리를 기준으로 상대적으로 지정된 각 디렉터리에서 파일 변경 사항만 찾게 됩니다.
271
+
272
+
273
+ 이 기능을 대체할 수 있는 구현 방법인 [pytest-watch](https://github.com/joeyespo/pytest-watch)도 있습니다.
274
+
275
+
276
+ ### 특정 테스트 모듈 건너뛰기[[skip-a-test-module]]
277
+
278
+ 모든 테스트 모듈을 실행하되 특정 모듈을 제외하려면, 실행할 테스트 목록을 명시적으로 지정할 수 있습니다.
279
+ 예를 들어, `test_modeling_*.py` 테스트를 제외한 모든 테스트를 실행하려면 다음을 사용할 수 있습니다:
280
+
281
+ ```bash
282
+ pytest *ls -1 tests/*py | grep -v test_modeling*
283
+ ```
284
+
285
+ ### 상태 초기화[[clearing state]]
286
+
287
+ CI 빌드 및 (속도에 대한) 격리가 중요한 경우, 캐시를 지워야 합니다:
288
+
289
+ ```bash
290
+ pytest --cache-clear tests
291
+ ```
292
+
293
+ ### 테스트를 병렬로 실행[[running-tests-in-parallel]]
294
+
295
+ 이전에 언급한 것처럼 `make test`는 테스트를 병렬로 실행하기 위해
296
+ `pytest-xdist` 플러그인(`-n X` 인수, 예를 들어 `-n 2`를 사용하여 2개의 병렬 작업 실행)을 통해 실행됩니다.
297
+
298
+ `pytest-xdist`의 `--dist=` 옵션을 사용하여 테스트를 어떻게 그룹화할지 제어할 수 있습니다.
299
+ `--dist=loadfile`은 하나의 파일에 있는 테스트를 동일한 프로세스로 그룹화합니다.
300
+
301
+ 실행된 테스트의 순서가 다르고 예측할 수 없기 때문에, `pytest-xdist`로 테스트 스위트를 실행하면 실패가 발생할 수 있습니다 (검출되지 않은 결합된 테스트가 있는 경우).
302
+ 이 경우 [pytest-replay](https://github.com/ESSS/pytest-replay)를 사용하면 동일한 순서로 테스트를 다시 실행해서
303
+ 실패하는 시퀀스를 최소화하는 데에 도움이 됩니다.
304
+
305
+ ### 테스트 순서와 반복[[test-order-and-repetition]]
306
+
307
+ 잠재적인 종속성 및 상태 관련 버그(tear down)를 감지하기 위해
308
+ 테스트를 여러 번, 연속으로, 무작위로 또는 세트로 반복하는 것이 좋습니다.
309
+ 그리고 직접적인 여러 번의 반복은 DL의 무작위성에 의해 발견되는 일부 문제를 감지하는 데에도 유용합니다.
310
+
311
+
312
+ #### 테스트를 반복[[repeat-tests]]
313
+
314
+ - [pytest-flakefinder](https://github.com/dropbox/pytest-flakefinder):
315
+
316
+ ```bash
317
+ pip install pytest-flakefinder
318
+ ```
319
+
320
+ 모든 테스트를 여러 번 실행합니다(기본값은 50번):
321
+
322
+ ```bash
323
+ pytest --flake-finder --flake-runs=5 tests/test_failing_test.py
324
+ ```
325
+
326
+ <Tip>
327
+
328
+ 이 플러그인은 `pytest-xdist`의 `-n` 플래그와 함께 작동하지 않습니다.
329
+
330
+ </Tip>
331
+
332
+ <Tip>
333
+
334
+ `pytest-repeat`라는 또 다른 플러그인도 있지만 `unittest`와 함께 작동하지 않습니다.
335
+
336
+ </Tip>
337
+
338
+ #### 테스트를 임의의 순서로 실행[[run-tests-in-a-random-order]]
339
+
340
+ ```bash
341
+ pip install pytest-random-order
342
+ ```
343
+
344
+ 중요: `pytest-random-order`가 설치되면 테스트가 자동으로 임의의 순서로 섞입니다.
345
+ 구성 변경이나 커맨드 라인 옵션이 필요하지 않습니다.
346
+
347
+ 앞서 설명한 것처럼 이를 통해 한 테스트의 상태가 다른 테스트의 상태에 영향을 미치는 결합된 테스트를 감지할 수 있습니다.
348
+ `pytest-random-order`가 설치되면 해당 세션에서 사용된 랜덤 시드가 출력되며 예를 들어 다음과 같습니다:
349
+
350
+ ```bash
351
+ pytest tests
352
+ [...]
353
+ Using --random-order-bucket=module
354
+ Using --random-order-seed=573663
355
+ ```
356
+
357
+ 따라서 특정 시퀀스가 실패하는 경우에는 정확한 시드를 추가하여 재현할 수 있습니다. 예를 들어 다음과 같습니다:
358
+
359
+ ```bash
360
+ pytest --random-order-seed=573663
361
+ [...]
362
+ Using --random-order-bucket=module
363
+ Using --random-order-seed=573663
364
+ ```
365
+
366
+ 정확히 동일한 테스트 목록(또는 목록이 없음)을 사용하는 경우에만 정확한 순서를 재현합니다.
367
+ 목록을 수동으로 좁히기 시작하면 더 이상 시드에 의존할 수 없고 실패했던 정확한 순서로 수동으로 목록을 나열해야합니다. 그리고 `--random-order-bucket=none`을 사용하여 pytest에게 순서를 임의로 설정하지 않도록 알려야 합니다.
368
+ 예를 들어 다음과 같습니다:
369
+
370
+ ```bash
371
+ pytest --random-order-bucket=none tests/test_a.py tests/test_c.py tests/test_b.py
372
+ ```
373
+
374
+ 모든 테스트에 대해 섞기를 비활성화하려면 다음과 같습니다:
375
+
376
+ ```bash
377
+ pytest --random-order-bucket=none
378
+ ```
379
+
380
+ 기본적으로 `--random-order-bucket=module`이 내재되어 있으므로, 모듈 수준에서 파일을 섞습니다.
381
+ 또한 `class`, `package`, `global` 및 `none` 수준에서도 섞을 수 있습니다.
382
+ 자세한 내용은 해당 [문서](https://github.com/jbasko/pytest-random-order)를 참조하세요.
383
+
384
+ 또 다른 무작위화의 대안은 [`pytest-randomly`](https://github.com/pytest-dev/pytest-randomly)입니다.
385
+ 이 모듈은 매우 유사한 기능/인터페이스를 가지고 있지만, `pytest-random-order`에 있는 버킷 모드를 사용할 수는 없습니다.
386
+ 설치 후에는 자동으로 적용되는 문제도 동일하게 가집니다.
387
+
388
+ ### 외관과 느낌을 변경[[look-and-feel-variations]
389
+
390
+ #### pytest-sugar 사용[[pytest-sugar]]
391
+
392
+ [pytest-sugar](https://github.com/Frozenball/pytest-sugar)는 테스트가 보여지는 형태를 개선하고,
393
+ 진행 상황 바를 추가하며, 실패한 테스트와 검증을 즉시 표시하는 플러그인입니다. 설치하면 자동으로 활성화됩니다.
394
+
395
+ ```bash
396
+ pip install pytest-sugar
397
+ ```
398
+
399
+ pytest-sugar 없이 테스트를 실행하려면 다음과 같습니다:
400
+
401
+ ```bash
402
+ pytest -p no:sugar
403
+ ```
404
+
405
+ 또는 제거하세요.
406
+
407
+
408
+
409
+ #### 각 하위 테스트 이름과 진행 상황 보고[[report-each-sub-test-name-and-its-progress]]
410
+
411
+ `pytest`를 통해 단일 또는 그룹의 테스트를 실행하는 경우(`pip install pytest-pspec` 이후):
412
+
413
+ ```bash
414
+ pytest --pspec tests/test_optimization.py
415
+ ```
416
+
417
+ #### 실패한 테스트 즉시 표시[[instantly-shows-failed-tests]]
418
+
419
+ [pytest-instafail](https://github.com/pytest-dev/pytest-instafail)은 테스트 세션의 끝까지 기다리지 않고
420
+ 실패 및 오류를 즉시 표시합니다.
421
+
422
+ ```bash
423
+ pip install pytest-instafail
424
+ ```
425
+
426
+ ```bash
427
+ pytest --instafail
428
+ ```
429
+
430
+ ### GPU 사용 여부[[to-GPU-or-not-to-GPU]]
431
+
432
+ GPU가 활성화된 환경에서, CPU 전용 모드로 테스트하려면 `CUDA_VISIBLE_DEVICES=""`를 추가합니다:
433
+
434
+ ```bash
435
+ CUDA_VISIBLE_DEVICES="" pytest tests/utils/test_logging.py
436
+ ```
437
+
438
+ 또는 다중 GPU가 있는 경우 `pytest`에서 사용할 GPU를 지정할 수도 있습니다.
439
+ 예를 들어, GPU `0` 및 `1`이 있는 경우 다음을 실행할 수 있습니다:
440
+
441
+ ```bash
442
+ CUDA_VISIBLE_DEVICES="1" pytest tests/utils/test_logging.py
443
+ ```
444
+
445
+ 이렇게 하면 다른 GPU에서 다른 작업을 실행하려는 경우 유용합니다.
446
+
447
+ 일부 테스트는 반드시 CPU 전용으로 실행해야 하며, 일부는 CPU 또는 GPU 또는 TPU에서 실행해야 하고, 일부는 여러 GPU에서 실행해야 합니다.
448
+ 다음 스킵 데코레이터는 테스트의 요구 사항을 CPU/GPU/TPU별로 설정하는 데 사용됩니다:
449
+
450
+ - `require_torch` - 이 테스트는 torch에서만 실행됩니다.
451
+ - `require_torch_gpu` - `require_torch`에 추가로 적어도 1개의 GPU가 필요합니다.
452
+ - `require_torch_multi_gpu` - `require_torch`에 추가로 적어도 2개의 GPU가 필요합니다.
453
+ - `require_torch_non_multi_gpu` - `require_torch`에 추가로 0개 또는 1개의 GPU가 필요합니다.
454
+ - `require_torch_up_to_2_gpus` - `require_torch`에 추가로 0개, 1개 또는 2개의 GPU가 필요합니다.
455
+ - `require_torch_xla` - `require_torch`에 추가로 적어도 1개의 TPU가 필요합니다.
456
+
457
+ GPU 요구 사항을 표로 정리하면 아래와 같습니디ㅏ:
458
+
459
+
460
+ | n gpus | decorator |
461
+ |--------+--------------------------------|
462
+ | `>= 0` | `@require_torch` |
463
+ | `>= 1` | `@require_torch_gpu` |
464
+ | `>= 2` | `@require_torch_multi_gpu` |
465
+ | `< 2` | `@require_torch_non_multi_gpu` |
466
+ | `< 3` | `@require_torch_up_to_2_gpus` |
467
+
468
+
469
+ 예를 들어, 2개 이상의 GPU가 있고 pytorch가 설치되어 있을 때에만 실행되어야 하는 테스트는 다음과 같습니다:
470
+
471
+ ```python no-style
472
+ @require_torch_multi_gpu
473
+ def test_example_with_multi_gpu():
474
+ ```
475
+
476
+ 이러한 데코레이터는 중첩될 수 있습니다.
477
+ 예를 들어, 느린 테스트로 진행되고 pytorch에서 적어도 하나의 GPU가 필요한 경우 다음과 같이 설정할 수 있습니다:
478
+
479
+ ```python no-style
480
+ @require_torch_gpu
481
+ @slow
482
+ def test_example_slow_on_gpu():
483
+ ```
484
+
485
+ `@parametrized`와 같은 일부 데코레이터는 테스트 이름을 다시 작성하기 때문에 `@require_*` 스킵 데코레이터는 올바르게 작동하려면 항상 맨 마지막에 나열되어야 합니다.
486
+ 다음은 올바른 사용 예입니다:
487
+
488
+ ```python no-style
489
+ @parameterized.expand(...)
490
+ @require_torch_multi_gpu
491
+ def test_integration_foo():
492
+ ```
493
+
494
+ `@pytest.mark.parametrize`에는 이러한 순서 문제는 없으므로 처음 혹은 마지막에 위치시킬 수 있고 이러한 경우에도 잘 작동할 것입니다.
495
+ 하지만 unittest가 아닌 경우에만 작동합니다.
496
+
497
+ 테스트 내부에서 다음을 사용할 수 있습니다:
498
+
499
+ - 사용 가능한 GPU 수:
500
+
501
+ ```python
502
+ from transformers.testing_utils import get_gpu_count
503
+
504
+ n_gpu = get_gpu_count() #torch와 tf와 함께 작동
505
+ ```
506
+
507
+ ### 분산 훈련[[distributed-training]]
508
+
509
+ `pytest`는 분산 훈련을 직접적으로 다루지 못합니다.
510
+ 이를 시도하면 하위 프로세스가 올바른 작업을 수행하지 않고 `pytest`라고 생각하기에 테스트 스위트를 반복해서 실행하게 됩니��.
511
+ 그러나 일반 프로세스를 생성한 다음 여러 워커를 생성하고 IO 파이프를 관리하도록 하면 동작합니다.
512
+
513
+ 다음은 사용 가능한 테스트입니다:
514
+
515
+ - [test_trainer_distributed.py](https://github.com/huggingface/transformers/tree/main/tests/trainer/test_trainer_distributed.py)
516
+ - [test_deepspeed.py](https://github.com/huggingface/transformers/tree/main/tests/deepspeed/test_deepspeed.py)
517
+
518
+ 실행 지점으로 바로 이동하려면, 해당 테스트에서 `execute_subprocess_async` 호출을 검색하세요.
519
+
520
+ 이러한 테스트를 실행하려면 적어도 2개의 GPU가 필요합니다.
521
+
522
+ ```bash
523
+ CUDA_VISIBLE_DEVICES=0,1 RUN_SLOW=1 pytest -sv tests/test_trainer_distributed.py
524
+ ```
525
+
526
+ ### 출력 캡처[[output-capture]]
527
+
528
+ 테스트 실행 중 `stdout` 및 `stderr`로 전송된 모든 출력이 캡처됩니다.
529
+ 테스트나 설정 메소드가 실패하면 캡처된 출력은 일반적으로 실패 추적 정보와 함께 표시됩니다.
530
+
531
+ 출력 캡처를 비활성화하고 `stdout` 및 `stderr`를 정상적으로 받으려면 `-s` 또는 `--capture=no`를 사용하세요:
532
+
533
+ ```bash
534
+ pytest -s tests/utils/test_logging.py
535
+ ```
536
+
537
+ 테스트 결과를 JUnit 형식의 출력으로 보내려면 다음을 사용하세요:
538
+
539
+ ```bash
540
+ py.test tests --junitxml=result.xml
541
+ ```
542
+
543
+ ### 색상 조절[[color-control]]
544
+
545
+ 색상이 없게 하려면 다음과 같이 설정하세요(예를 들어 흰색 배경에 노란색 글씨는 가독성이 좋지 않습니다):
546
+
547
+ ```bash
548
+ pytest --color=no tests/utils/test_logging.py
549
+ ```
550
+
551
+ ### online pastebin service에 테스트 보고서 전송[[sending test report to online pastebin service]]
552
+
553
+ 각 테스트 실패에 대한 URL을 만듭니다:
554
+
555
+ ```bash
556
+ pytest --pastebin=failed tests/utils/test_logging.py
557
+ ```
558
+
559
+ 이렇게 하면 각 실패에 대한 URL을 제공하는 remote Paste service에 테스트 실행 정보를 제출합니다.
560
+ 일반적인 테스트를 선택할 수도 있고 혹은 특정 실패만 보내려면 `-x`와 같이 추가할 수도 있습니다.
561
+
562
+ 전체 테스트 세션 로그에 대한 URL을 생성합니다:
563
+
564
+ ```bash
565
+ pytest --pastebin=all tests/utils/test_logging.py
566
+ ```
567
+
568
+ ## 테스트 작성[[writing-tests]]
569
+
570
+ 🤗 transformers 테스트는 대부분 `unittest`를 기반으로 하지만,
571
+ `pytest`에서 실행되므로 대부분의 경우 두 시스템의 기능을 사용할 수 있습니다.
572
+
573
+ 지원되는 기능에 대해 [여기](https://docs.pytest.org/en/stable/unittest.html)에서 확인할 수 있지만,
574
+ 기억해야 할 중요한 점은 대부분의 `pytest` fixture가 작동하지 않는다는 것입니다.
575
+ 파라미터화도 작동하지 않지만, 우리는 비슷한 방식으로 작동하는 `parameterized` 모듈을 사용합니다.
576
+
577
+
578
+ ### 매개변수화[[parametrization]]
579
+
580
+ 동일한 테스트를 다른 인수로 여러 번 실행해야 하는 경우가 종종 있습니다.
581
+ 테스트 내에서 이 작업을 수행할 수 있지만, 그렇게 하면 하나의 인수 세트에 대해 테스트를 실행할 수 없습니다.
582
+
583
+ ```python
584
+ # test_this1.py
585
+ import unittest
586
+ from parameterized import parameterized
587
+
588
+
589
+ class TestMathUnitTest(unittest.TestCase):
590
+ @parameterized.expand(
591
+ [
592
+ ("negative", -1.5, -2.0),
593
+ ("integer", 1, 1.0),
594
+ ("large fraction", 1.6, 1),
595
+ ]
596
+ )
597
+ def test_floor(self, name, input, expected):
598
+ assert_equal(math.floor(input), expected)
599
+ ```
600
+
601
+ 이제 기본적으로 이 테스트는 `test_floor`의 마지막 3개 인수가
602
+ 매개변수 목록의 해당 인수에 할당되는 것으로 3번 실행될 것입니다.
603
+
604
+ 그리고 `negative` 및 `integer` 매개변수 집합만 실행하려면 다음과 같이 실행할 수 있습니다:
605
+
606
+ ```bash
607
+ pytest -k "negative and integer" tests/test_mytest.py
608
+ ```
609
+
610
+ 또는 `negative` 하위 테스트를 제외한 모든 서브 테스트를 다음과 같이 실행할 수 있습니다:
611
+
612
+ ```bash
613
+ pytest -k "not negative" tests/test_mytest.py
614
+ ```
615
+
616
+ 앞에서 언급한 `-k` 필터를 사용하는 것 외에도,
617
+ 각 서브 테스트의 정확한 이름을 확인한 후에 일부 혹은 전체 서브 테스트를 실행할 수 있습니다.
618
+
619
+ ```bash
620
+ pytest test_this1.py --collect-only -q
621
+ ```
622
+
623
+ 그리고 다음의 내용을 확인할 수 있을 것입니다:
624
+
625
+ ```bash
626
+ test_this1.py::TestMathUnitTest::test_floor_0_negative
627
+ test_this1.py::TestMathUnitTest::test_floor_1_integer
628
+ test_this1.py::TestMathUnitTest::test_floor_2_large_fraction
629
+ ```
630
+
631
+ 2개의 특정한 서브 테스트만 실행할 수도 있습니다:
632
+
633
+ ```bash
634
+ pytest test_this1.py::TestMathUnitTest::test_floor_0_negative test_this1.py::TestMathUnitTest::test_floor_1_integer
635
+ ```
636
+
637
+ `transformers`의 개발자 종속성에 이미 있는 [parameterized](https://pypi.org/project/parameterized/) 모듈은
638
+ `unittests`와 `pytest` 테스트 모두에서 작동합니다.
639
+
640
+ 그러나 테스트가 `unittest`가 아닌 경우 `pytest.mark.parametrize`를 사용할 수 있습니다(이미 있는 ���부 테스트에서 사용되는 경우도 있습니다.
641
+ 주로 `examples` 하위에 있습니다).
642
+
643
+ 다음은 `pytest`의 `parametrize` 마커를 사용한 동일한 예입니다:
644
+
645
+ ```python
646
+ # test_this2.py
647
+ import pytest
648
+
649
+
650
+ @pytest.mark.parametrize(
651
+ "name, input, expected",
652
+ [
653
+ ("negative", -1.5, -2.0),
654
+ ("integer", 1, 1.0),
655
+ ("large fraction", 1.6, 1),
656
+ ],
657
+ )
658
+ def test_floor(name, input, expected):
659
+ assert_equal(math.floor(input), expected)
660
+ ```
661
+
662
+ `parameterized`와 마찬가지로 `pytest.mark.parametrize`를 사용하면
663
+ `-k` 필터가 작동하지 않는 경우에도 실행할 서브 테스트를 정확하게 지정할 수 있습니다.
664
+ 단, 이 매개변수화 함수는 서브 테스트의 이름 집합을 약간 다르게 생성합니다. 다음과 같은 모습입니다:
665
+
666
+ ```bash
667
+ pytest test_this2.py --collect-only -q
668
+ ```
669
+
670
+ 그리고 다음의 내용을 확인할 수 있을 것입니다:
671
+
672
+ ```bash
673
+ test_this2.py::test_floor[integer-1-1.0]
674
+ test_this2.py::test_floor[negative--1.5--2.0]
675
+ test_this2.py::test_floor[large fraction-1.6-1]
676
+ ```
677
+
678
+ 특정한 테스트에 대해서만 실행할 수도 있습니다:
679
+
680
+ ```bash
681
+ pytest test_this2.py::test_floor[negative--1.5--2.0] test_this2.py::test_floor[integer-1-1.0]
682
+ ```
683
+
684
+ 이전의 예시와 같이 실행할 수 있습니다.
685
+
686
+
687
+
688
+ ### 파일 및 디렉터리[[files-and-directories]]
689
+
690
+ 테스트에서 종종 현재 테스트 파일과 관련된 상대적인 위치를 알아야 하는 경우가 있습니다.
691
+ 테스트가 여러 디렉터리에서 호출되거나 깊이가 다른 하위 디렉터리에 있을 수 있기 때문에 그 위치를 아는 것은 간단하지 않습니다.
692
+ `transformers.test_utils.TestCasePlus`라는 헬퍼 클래스는 모든 기본 경로를 처리하고 간단한 액세서를 제공하여 이 문제를 해결합니다:
693
+
694
+
695
+ - `pathlib` 객체(완전히 정해진 경로)
696
+
697
+ - `test_file_path` - 현재 테스트 파일 경로 (예: `__file__`)
698
+ - test_file_dir` - 현재 테스트 파일이 포함된 디렉터리
699
+ - tests_dir` - `tests` 테스트 스위트의 디렉터리
700
+ - examples_dir` - `examples` 테스트 스위트의 디렉터리
701
+ - repo_root_dir` - 저장소 디렉터리
702
+ - src_dir` - `src`의 디렉터리(예: `transformers` 하위 디렉터리가 있는 곳)
703
+
704
+ - 문자열로 변환된 경로---위와 동일하지만, `pathlib` 객체가 아닌 문자열로 경로를 반환합니다:
705
+
706
+ - `test_file_path_str`
707
+ - `test_file_dir_str`
708
+ - `tests_dir_str`
709
+ - `examples_dir_str`
710
+ - `repo_root_dir_str`
711
+ - `src_dir_str`
712
+
713
+ 위의 내용을 사용하려면 테스트가 'transformers.test_utils.TestCasePlus'의 서브클래스에 있는지 확인해야 합니다.
714
+ 예를 들어 다음과 같습니다:
715
+
716
+ ```python
717
+ from transformers.testing_utils import TestCasePlus
718
+
719
+
720
+ class PathExampleTest(TestCasePlus):
721
+ def test_something_involving_local_locations(self):
722
+ data_dir = self.tests_dir / "fixtures/tests_samples/wmt_en_ro"
723
+ ```
724
+
725
+ 만약 `pathlib`를 통해 경로를 조작할 필요가 없거나 경로를 문자열로만 필요로 하는 경우에는 `pathlib` 객체에 `str()`을 호출하거나 `_str`로 끝나는 접근자를 사용할 수 있습니다.
726
+ 예를 들어 다음과 같습니다:
727
+
728
+ ```python
729
+ from transformers.testing_utils import TestCasePlus
730
+
731
+
732
+ class PathExampleTest(TestCasePlus):
733
+ def test_something_involving_stringified_locations(self):
734
+ examples_dir = self.examples_dir_str
735
+ ```
736
+
737
+ ### 임시 파일 및 디렉터리[[temporary-files-and-directories]]
738
+
739
+ 고유한 임시 파일 및 디렉터리를 사용하는 것은 병렬 테스트 실행에 있어 필수적입니다.
740
+ 이렇게 함으로써 테스트들이 서로의 데이터를 덮어쓰지 않게 할 수 있습니다. 또한 우리는 생성된 테스트의 종료 단계에서 이러한 임시 파일 및 디렉터리를 제거하고 싶습니다.
741
+ 따라서 이러한 요구 사항을 충족시켜주는 `tempfile`과 같은 패키지를 사용하는 것이 중요합니다.
742
+
743
+ 그러나 테스트를 디버깅할 때는 임시 파일이나 디렉터리에 들어가는 내용을 확인할 수 있어야 하며,
744
+ 재실행되는 각 테스트마다 임시 파일이나 디렉터리의 경로에 대해 무작위 값이 아닌 정확한 값을 알고 싶을 것입니다.
745
+
746
+ `transformers.test_utils.TestCasePlus`라는 도우미 클래스는 이러한 목적에 가장 적합합니다.
747
+ 이 클래스는 `unittest.TestCase`의 하위 클래스이므로, 우리는 이것을 테스트 모듈에서 쉽게 상속할 수 있습니다.
748
+
749
+ 다음은 해당 클래스를 사용하는 예시입니다:
750
+
751
+ ```python
752
+ from transformers.testing_utils import TestCasePlus
753
+
754
+
755
+ class ExamplesTests(TestCasePlus):
756
+ def test_whatever(self):
757
+ tmp_dir = self.get_auto_remove_tmp_dir()
758
+ ```
759
+
760
+ 이 코드는 고유한 임시 디렉터리를 생성하고 `tmp_dir`을 해당 위치로 설정합니다.
761
+
762
+ - 고유한 임시 디렉터리를 생성합니다:
763
+
764
+ ```python
765
+ def test_whatever(self):
766
+ tmp_dir = self.get_auto_remove_tmp_dir()
767
+ ```
768
+
769
+ `tmp_dir`에는 생성된 임시 디렉터리의 경로가 포함됩니다.
770
+ 이는 테스트의 종료 단계에서 자동으로 제거됩니다.
771
+
772
+ - 선택한 경로로 임시 디렉터리 생성 후에 테스트 시작 전에 비어 있는 상태인지 확인하고, 테스트 후에는 비우지 마세요.
773
+
774
+ ```python
775
+ def test_whatever(self):
776
+ tmp_dir = self.get_auto_remove_tmp_dir("./xxx")
777
+ ```
778
+
779
+ 이것은 디버깅할 때 특정 디렉터리를 모니터링하고,
780
+ 그 디렉터리에 이전에 실행된 테스트가 데이터를 남기지 않도록 하는 데에 유용합니다.
781
+
782
+ - `before` 및 `after` 인수를 직접 오버라이딩하여 기본 동작을 변경할 수 있으며
783
+ 다음 중 하나의 동작으로 이어집니다:
784
+
785
+ - `before=True`: 테스트 시작 시 임시 디렉터리가 항상 지워집니다.
786
+ - `before=False`: 임시 디렉터리가 이미 존재하는 경우 기존 파일은 그대로 남습니다.
787
+ - `after=True`: 테스트 종료 시 임시 디렉터리가 항상 삭제됩니다.
788
+ - `after=False`: 테스트 종료 시 임시 디렉터리가 항상 그대로 유지됩니다.
789
+
790
+ <Tip>
791
+
792
+ `rm -r`에 해당하는 명령을 안전하게 실행하기 위해,
793
+ 명시적인 `tmp_dir`을 사용하는 경우 프로젝트 저장소 체크 아웃의 하위 디렉터리만 허용됩니다.
794
+ 따라서 실수로 `/tmp`가 아닌 중요한 파일 시스템의 일부가 삭제되지 않도록 항상 `./`로 시작하는 경로를 전달해야 합니다.
795
+
796
+ </Tip>
797
+
798
+ <Tip>
799
+
800
+ 각 테스트는 여러 개의 임시 디렉터리를 등록할 수 있으며,
801
+ 별도로 요청하지 않는 한 모두 자동으로 제거됩니다.
802
+
803
+ </Tip>
804
+
805
+ ### 임시 sys.path 오버라이드[[temporary-sys.path-override]]
806
+
807
+ `sys.path`를 다른 테스트로 임시로 오버라이드하기 위해 예를 들어 `ExtendSysPath` 컨텍스트 관리자를 사용할 수 있습니다.
808
+ 예를 들어 다음과 같습니다:
809
+
810
+
811
+ ```python
812
+ import os
813
+ from transformers.testing_utils import ExtendSysPath
814
+
815
+ bindir = os.path.abspath(os.path.dirname(__file__))
816
+ with ExtendSysPath(f"{bindir}/.."):
817
+ from test_trainer import TrainerIntegrationCommon # noqa
818
+ ```
819
+
820
+ ### 테스트 건너뛰기[[skipping-tests]]
821
+
822
+ 이것은 버그가 발견되어 새로운 테스트가 작성되었지만 아직 그 버그가 수정되지 않은 경우에 유용합니다.
823
+ 이 테스트를 주 저장소에 커밋하려면 `make test` 중에 건너뛰도록 해야 합니다.
824
+
825
+ 방법:
826
+
827
+ - **skip**은 테스트가 일부 조건이 충족될 경우에만 통과될 것으로 예상되고, 그렇지 않으면 pytest가 전체 테스트를 건너뛰어야 함을 의미합니다.
828
+ 일반적인 예로는 Windows가 아닌 플랫폼에서 Windows 전용 테스트를 건너뛰거나
829
+ 외부 리소스(예를 들어 데이터베이스)에 의존하는 테스트를 건너뛰는 것이 있습니다.
830
+
831
+ - **xfail**은 테스트가 특정한 이유로 인해 실패할 것으로 예상하는 것을 의미합니다.
832
+ 일반적인 예로는 아직 구현되지 않은 기능이나 아직 수정되지 않은 버그의 테스트가 있습니다.
833
+ `xfail`로 표시된 테스트가 예상대로 실패하지 않고 통과된 경우, 이것은 xpass이며 테스트 결과 요약에 기록됩니다.
834
+
835
+ 두 가지 중요한 차이점 중 하나는 `skip`은 테스트를 실행하지 않지만 `xfail`은 실행한다는 것입니다.
836
+ 따라서 오류가 있는 코드가 일부 테스트에 영향을 미칠 수 있는 경우 `xfail`을 사용하지 마세요.
837
+
838
+ #### 구현[[implementation]]
839
+
840
+ - 전체 테스트를 무조건 건너뛰려면 다음과 같이 할 수 있습니다:
841
+
842
+ ```python no-style
843
+ @unittest.skip(reason="this bug needs to be fixed")
844
+ def test_feature_x():
845
+ ```
846
+
847
+ 또는 pytest를 통해:
848
+
849
+ ```python no-style
850
+ @pytest.mark.skip(reason="this bug needs to be fixed")
851
+ ```
852
+
853
+ 또는 `xfail` 방식으로:
854
+
855
+ ```python no-style
856
+ @pytest.mark.xfail
857
+ def test_feature_x():
858
+ ```
859
+
860
+ - 테스트 내부에서 내부 확인에 따라 테스트를 건너뛰는 방법은 다음과 같습니다:
861
+
862
+ ```python
863
+ def test_feature_x():
864
+ if not has_something():
865
+ pytest.skip("unsupported configuration")
866
+ ```
867
+
868
+ 또는 모듈 전체:
869
+
870
+ ```python
871
+ import pytest
872
+
873
+ if not pytest.config.getoption("--custom-flag"):
874
+ pytest.skip("--custom-flag is missing, skipping tests", allow_module_level=True)
875
+ ```
876
+
877
+ 또는 `xfail` 방식으로:
878
+
879
+ ```python
880
+ def test_feature_x():
881
+ pytest.xfail("expected to fail until bug XYZ is fixed")
882
+ ```
883
+
884
+ - import가 missing된 모듈이 있을 때 그 모듈의 모든 테스트를 건너뛰는 방법:
885
+
886
+ ```python
887
+ docutils = pytest.importorskip("docutils", minversion="0.3")
888
+ ```
889
+
890
+ - 조건에 따라 테스트를 건너뛰는 방법:
891
+
892
+ ```python no-style
893
+ @pytest.mark.skipif(sys.version_info < (3,6), reason="requires python3.6 or higher")
894
+ def test_feature_x():
895
+ ```
896
+
897
+ 또는:
898
+
899
+ ```python no-style
900
+ @unittest.skipIf(torch_device == "cpu", "Can't do half precision")
901
+ def test_feature_x():
902
+ ```
903
+
904
+ 또는 모듈 전체를 건너뛰는 방법:
905
+
906
+ ```python no-style
907
+ @pytest.mark.skipif(sys.platform == 'win32', reason="does not run on windows")
908
+ class TestClass():
909
+ def test_feature_x(self):
910
+ ```
911
+
912
+ 보다 자세한 예제 및 방법은 [여기](https://docs.pytest.org/en/latest/skipping.html)에서 확인할 수 있습니다.
913
+
914
+ ### 느린 테스트[[slow-tests]]
915
+
916
+ 테스트 라이브러리는 지속적으로 확장되고 있으며, 일부 테스트는 실행하는 데 몇 분이 걸립니다.
917
+ 그리고 우리에게는 테스트 스위트가 CI를 통해 완료되기까지 한 시간을 기다릴 여유가 없습니다.
918
+ 따라서 필수 테스트를 위한 일부 예외를 제외하고 느린 테스트는 다음과 같이 표시해야 합니다.
919
+
920
+ ```python no-style
921
+ from transformers.testing_utils import slow
922
+ @slow
923
+ def test_integration_foo():
924
+ ```
925
+
926
+ `@slow`로 표시된 테스트를 실행하려면 `RUN_SLOW=1` 환경 변수를 설정하세요. 예를 들어 다음과 같습니다:
927
+
928
+ ```bash
929
+ RUN_SLOW=1 pytest tests
930
+ ```
931
+
932
+ `@parameterized`와 같은 몇 가지 데코레이터는 테스트 이름을 다시 작성합니다.
933
+ 그러므로 `@slow`와 나머지 건너뛰기 데코레이터 `@require_*`가 올바르게 작동되려면 마지막에 나열되어야 합니다. 다음은 올바른 사용 예입니다.
934
+
935
+ ```python no-style
936
+ @parameterized.expand(...)
937
+ @slow
938
+ def test_integration_foo():
939
+ ```
940
+
941
+ 이 문서의 초반부에 설명된 것처럼 느린 테스트는 PR의 CI 확인이 아닌 예약된 일정 기반으로 실행됩니다.
942
+ 따라서 PR 제출 중에 일부 문제를 놓친 채로 병합될 수 있습니다.
943
+ 이러한 문제들은 다음번의 예정된 CI 작업 중에 감지됩니다.
944
+ 하지만 PR을 제출하기 전에 자신의 컴퓨터에서 느린 테스트를 실행하는 것 또한 중요합니다.
945
+
946
+ 느린 테스트로 표시해야 하는지 여부를 결정하는 대략적인 결정 기준은 다음과 같습니다.
947
+
948
+ 만약 테스트가 라이브러리의 내부 구성 요소 중 하나에 집중되어 있다면(예: 모델링 파일, 토큰화 파일, 파이프라인),
949
+ 해당 테스트를 느린 테스트 스위트에서 실행해야 합니다.
950
+ 만약 라이브러리의 다른 측면(예: 문서 또는 예제)에 집중되어 있다면,
951
+ 해당 테스트를 느린 테스트 스위트에서 실행해야 합니다. 그리고 이 접근 방식을 보완하기 위해 예외를 만들어야 합니다.
952
+
953
+ - 무거운 가중치 세트나 50MB보다 큰 데이터셋을 다운로드해야 하는 모든 테스트(예: 모델 통합 테스트, 토크나이저 통합 테스트, 파이프라인 통합 테스트)를
954
+ 느린 테스트로 설정해야 합니다.
955
+ 새로운 모델을 추가하는 경우 통합 테스트용으로 무작위 가중치로 작은 버전을 만들어 허브에 업로드해야 합니다.
956
+ 이 내용은 아래 단락에서 설명됩니다.
957
+ - 특별히 빠르게 실행되도록 최적화되지 않은 학습을 수행해야 하는 테스트는 느린 테스트로 설정해야 합니다.
958
+ - 느리지 않아야 할 테스트 중 일부가 극도로 느린 경우
959
+ 예외를 도입하고 이를 `@slow`로 설정할 수 있습니다.
960
+ 대용량 파일을 디스크에 저장하고 불러오는 자동 모델링 테스트는 `@slow`으로 표시된 테스트의 좋은 예입니다.
961
+ - CI에서 1초 이내에 테스트가 완료되는 경우(다운로드 포함)에는 느린 테스트가 아니어야 합니다.
962
+
963
+ 느린 테스트가 아닌 경우에는 다양한 내부를 완전히 커버하면서 빠르게 유지되어야 합니다.
964
+ 예를 들어, 무작위 가중치를 사용하여 특별히 생성된 작은 모델로 테스트하면 상당한 커버리지를 얻을 수 있습니다.
965
+ 이러한 모델은 최소한의 레이어 수(예: 2), 어휘 크기(예: 1000) 등의 요소만 가집니다. 그런 다음 `@slow` 테스트는 대형 느린 모델을 사용하여 정성적인 테스트를 수행할 수 있습니다.
966
+ 이러한 작은 모델을 사용하는 방법을 확인하려면 다음과 같이 *tiny* 모델을 찾아보세요.
967
+
968
+ ```bash
969
+ grep tiny tests examples
970
+ ```
971
+
972
+ 다음은 작은 모델[stas/tiny-wmt19-en-de](https://huggingface.co/stas/tiny-wmt19-en-de)을 만든
973
+ [script](https://github.com/huggingface/transformers/tree/main/scripts/fsmt/fsmt-make-tiny-model.py) 예시입니다.
974
+ 특정 모델의 아키텍처에 맞게 쉽게 조정할 수 있습니다.
975
+
976
+ 예를 들어 대용량 모델을 다운로드하는 경우 런타임을 잘못 측정하기 쉽지만,
977
+ 로컬에서 테스트하면 다운로드한 파일이 캐시되어 다운로드 시간이 측정되지 않습니다.
978
+ 대신 CI 로그의 실행 속도 보고서를 확인하세요(`pytest --durations=0 tests`의 출력).
979
+
980
+ 이 보고서는 느린 이상값으로 표시되지 않거나 빠르게 다시 작성해야 하는 느린 이상값을 찾는 데도 유용합니다.
981
+ CI에서 테스트 스위트가 느려지기 시작하면 이 보고서의 맨 위 목록에 가장 느린 테스트가 표시됩니다.
982
+
983
+
984
+
985
+ ### stdout/stderr 출력 테스트[[testing-the-stdout/stderr-output]]
986
+
987
+ `stdout` 및/또는 `stderr`로 쓰는 함수를 테스트하려면 `pytest`의 [capsys 시스템](https://docs.pytest.org/en/latest/capture.html)을 사용하여 해당 스트림에 액세스할 수 있습니다.
988
+ 다음과 같이 수행할 수 있습니다.
989
+
990
+ ```python
991
+ import sys
992
+
993
+
994
+ def print_to_stdout(s):
995
+ print(s)
996
+
997
+
998
+ def print_to_stderr(s):
999
+ sys.stderr.write(s)
1000
+
1001
+
1002
+ def test_result_and_stdout(capsys):
1003
+ msg = "Hello"
1004
+ print_to_stdout(msg)
1005
+ print_to_stderr(msg)
1006
+ out, err = capsys.readouterr() # 캡처된 출력 스트림 사용
1007
+ # 선택 사항: 캡처된 스트림 재생성
1008
+ sys.stdout.write(out)
1009
+ sys.stderr.write(err)
1010
+ # 테스트:
1011
+ assert msg in out
1012
+ assert msg in err
1013
+ ```
1014
+
1015
+ 그리고, 물론 대부분의 경우에는 `stderr`는 예외의 일부로 제공됩니다.
1016
+ 그러므로 해당 경우에는 try/except를 사용해야 합니다.
1017
+
1018
+ ```python
1019
+ def raise_exception(msg):
1020
+ raise ValueError(msg)
1021
+
1022
+
1023
+ def test_something_exception():
1024
+ msg = "Not a good value"
1025
+ error = ""
1026
+ try:
1027
+ raise_exception(msg)
1028
+ except Exception as e:
1029
+ error = str(e)
1030
+ assert msg in error, f"{msg} is in the exception:\n{error}"
1031
+ ```
1032
+
1033
+ `stdout`를 캡처하는 또 다른 방법은 `contextlib.redirect_stdout`를 사용하는 것입니다.
1034
+
1035
+ ```python
1036
+ from io import StringIO
1037
+ from contextlib import redirect_stdout
1038
+
1039
+
1040
+ def print_to_stdout(s):
1041
+ print(s)
1042
+
1043
+
1044
+ def test_result_and_stdout():
1045
+ msg = "Hello"
1046
+ buffer = StringIO()
1047
+ with redirect_stdout(buffer):
1048
+ print_to_stdout(msg)
1049
+ out = buffer.getvalue()
1050
+ # 선택 사항: 캡처된 스트림 재생성
1051
+ sys.stdout.write(out)
1052
+ # 테스트:
1053
+ assert msg in out
1054
+ ```
1055
+
1056
+ `stdout` 캡처에 관련된 중요한 문제 중 하나는 보통 `print`에서 이전에 인쇄된 내용을 재설정하는 `\r` 문자가 포함될 수 있다는 것입니다.
1057
+ `pytest`에서는 문제가 없지만 `pytest -s`에서는 이러한 문자가 버퍼에 포함되므로
1058
+ `-s`가 있거나 없는 상태에서 태스트를 수행할 수 있으려면 캡처된 출력에 대해 추가적인 정리가 필요합니다.
1059
+ 이 경우에는 `re.sub(r'~.*\r', '', buf, 0, re.M)`을 사용할 수 있습니다.
1060
+
1061
+ 하지만 도우미 컨텍스트 관리자 래퍼를 사용하면
1062
+ 출력에 `\r`이 포함되어 있는지의 여부에 관계없이 모든 것을 자동으로 처리하므로 편리합니다.
1063
+
1064
+ ```python
1065
+ from transformers.testing_utils import CaptureStdout
1066
+
1067
+ with CaptureStdout() as cs:
1068
+ function_that_writes_to_stdout()
1069
+ print(cs.out)
1070
+ ```
1071
+
1072
+ 다음은 전체 테스트 예제입니다.
1073
+
1074
+ ```python
1075
+ from transformers.testing_utils import CaptureStdout
1076
+
1077
+ msg = "Secret message\r"
1078
+ final = "Hello World"
1079
+ with CaptureStdout() as cs:
1080
+ print(msg + final)
1081
+ assert cs.out == final + "\n", f"captured: {cs.out}, expecting {final}"
1082
+ ```
1083
+
1084
+ `stderr`를 캡처하고 싶다면, 대신 `CaptureStderr` 클래스를 사용하세요.
1085
+
1086
+ ```python
1087
+ from transformers.testing_utils import CaptureStderr
1088
+
1089
+ with CaptureStderr() as cs:
1090
+ function_that_writes_to_stderr()
1091
+ print(cs.err)
1092
+ ```
1093
+
1094
+ 두 스트림을 동시에 캡처해야 한다면, 부모 `CaptureStd` 클래스를 사용하세요.
1095
+
1096
+ ```python
1097
+ from transformers.testing_utils import CaptureStd
1098
+
1099
+ with CaptureStd() as cs:
1100
+ function_that_writes_to_stdout_and_stderr()
1101
+ print(cs.err, cs.out)
1102
+ ```
1103
+
1104
+ 또한, 테스트의 디버깅을 지원하기 위해
1105
+ 이러한 컨텍스트 관리자는 기본적으로 컨텍스트에서 종료할 때 캡처된 스트림을 자동으로 다시 실행합니다.
1106
+
1107
+
1108
+ ### 로거 스트림 캡처[[capturing-logger-stream]]
1109
+
1110
+ 로거 출력을 검증해야 하는 경우 `CaptureLogger`를 사용할 수 있습니다.
1111
+
1112
+ ```python
1113
+ from transformers import logging
1114
+ from transformers.testing_utils import CaptureLogger
1115
+
1116
+ msg = "Testing 1, 2, 3"
1117
+ logging.set_verbosity_info()
1118
+ logger = logging.get_logger("transformers.models.bart.tokenization_bart")
1119
+ with CaptureLogger(logger) as cl:
1120
+ logger.info(msg)
1121
+ assert cl.out, msg + "\n"
1122
+ ```
1123
+
1124
+ ### 환경 변수를 이용하여 테스트[[testing-with-environment-variables]]
1125
+
1126
+ 특정 테스트의 환경 변수 영향을 검증하려면
1127
+ `transformers.testing_utils.mockenv`라는 도우미 데코레이터를 사용할 수 있습니다.
1128
+
1129
+ ```python
1130
+ from transformers.testing_utils import mockenv
1131
+
1132
+
1133
+ class HfArgumentParserTest(unittest.TestCase):
1134
+ @mockenv(TRANSFORMERS_VERBOSITY="error")
1135
+ def test_env_override(self):
1136
+ env_level_str = os.getenv("TRANSFORMERS_VERBOSITY", None)
1137
+ ```
1138
+
1139
+ 일부 경우에는 외부 프로그램을 호출해야할 수도 있는데, 이 때에는 여러 개의 로컬 경로를 포함하는 `os.environ`에서 `PYTHONPATH`의 설정이 필요합니다.
1140
+ 헬퍼 클래스 `transformers.test_utils.TestCasePlus`가 도움이 됩니다:
1141
+
1142
+ ```python
1143
+ from transformers.testing_utils import TestCasePlus
1144
+
1145
+
1146
+ class EnvExampleTest(TestCasePlus):
1147
+ def test_external_prog(self):
1148
+ env = self.get_env()
1149
+ # 이제 `env`를 사용하여 외부 프로그램 호출
1150
+ ```
1151
+
1152
+ 테스트 파일이 `tests` 테스트 스위트 또는 `examples`에 있는지에 따라
1153
+ `env[PYTHONPATH]`가 두 디렉터리 중 하나를 포함하도록 설정되며,
1154
+ 현재 저장소에 대해 테스트가 수행되도록 `src` 디렉터리도 포함됩니다.
1155
+ 테스트 호출 이전에 설정된 경우에는 `env[PYTHONPATH]`를 그대로 사용합니다.
1156
+
1157
+ 이 헬퍼 메소드는 `os.environ` 객체의 사본을 생성하므로 원본은 그대로 유지됩니다.
1158
+
1159
+
1160
+ ### 재현 가능한 결과 얻기[[getting-reproducible-results]]
1161
+
1162
+ 일부 상황에서 테스트에서 임의성을 제거하여 동일하게 재현 가능한 결과를 얻고 싶을 수 있습니다.
1163
+ 이를 위해서는 다음과 같이 시드를 고정해야 합니다.
1164
+
1165
+ ```python
1166
+ seed = 42
1167
+
1168
+ # 파이썬 RNG
1169
+ import random
1170
+
1171
+ random.seed(seed)
1172
+
1173
+ # 파이토치 RNG
1174
+ import torch
1175
+
1176
+ torch.manual_seed(seed)
1177
+ torch.backends.cudnn.deterministic = True
1178
+ if torch.cuda.is_available():
1179
+ torch.cuda.manual_seed_all(seed)
1180
+
1181
+ # 넘파이 RNG
1182
+ import numpy as np
1183
+
1184
+ np.random.seed(seed)
1185
+
1186
+ # 텐서플로 RNG
1187
+ tf.random.set_seed(seed)
1188
+ ```
1189
+
1190
+ ### 테스트 디버깅[[debugging tests]]
1191
+
1192
+ 경고가 있는 곳에서 디버거를 시작하려면 다음을 수행하세요.
1193
+
1194
+ ```bash
1195
+ pytest tests/utils/test_logging.py -W error::UserWarning --pdb
1196
+ ```
1197
+
1198
+ ## Github Actions 워크플로우 작업 처리[[working-with-github-actions-workflows]]
1199
+
1200
+ 셀프 푸시 워크플로우 CI 작업을 트리거하려면, 다음을 수행해야 합니다.
1201
+
1202
+ 1. `transformers` 원본에서 새 브랜치를 만듭니다(포크가 아닙니다!).
1203
+ 2. 브랜치 이름은 `ci_` 또는 `ci-`로 시작해야 합니다(`main`도 트리거하지만 `main`에서는 PR을 할 수 없습니다).
1204
+ 또한 특정 경로에 대해서만 트리거되므로 이 문서가 작성된 후에 변경된 내용은
1205
+ [여기](https://github.com/huggingface/transformers/blob/main/.github/workflows/self-push.yml)의 *push:*에서 확인할 수 있습니다.
1206
+ 3. 이 브랜치에서 PR을 생성합니다
1207
+ 4. 그런 다음 [여기](https://github.com/huggingface/transformers/actions/workflows/self-push.yml)에서 작업이 나타나는지 확인할 수 있습니다.
1208
+ 백로그가 있는 경우, 바로 실행되지 않을 수도 있습니다.
1209
+
1210
+
1211
+
1212
+
1213
+ ## 실험적인 CI 기능 테스트[[testing-Experimental-CI-Features]]
1214
+
1215
+ CI 기능을 테스트하는 것은 일반 CI 작동에 방해가 될 수 있기 때문에 잠재적으로 문제가 발생할 수 있습니다.
1216
+ 따라서 새로운 CI 기능을 추가하는 경우 다음과 같이 수행해야 합니다.
1217
+
1218
+ 1. 테스트해야 할 내용을 테스트하는 새로운 전용 작업을 생성합니다.
1219
+ 2. 새로운 작업은 항상 성공해야만 녹색 ✓를 받을 수 있습니다(아래에 자세한 내용이 있습니다).
1220
+ 3. 다양한 PR 유형에 대한 확인을 위해
1221
+ (사용자 포크 브랜치, 포크되지 않은 브랜치, github.com UI 직접 파일 편집에서 생성된 브랜치, 강제 푸시 등 PR의 유형은 아주 다양합니다.)
1222
+ 며칠 동안 실험 작업의 로그를 모니터링하면서 실행해봅니다.
1223
+ (의도적으로 항상 녹색을 표시하므로 작업 전체가 녹색은 아니라는 점에 유의합니다.)
1224
+ 4. 모든 것이 안정적인지 확인한 후, 새로운 변경 사항을 기존 작업에 병합합니다.
1225
+
1226
+ 이렇게 하면 CI 기능 자체에 대한 실험이 일반 작업 흐름에 방해가 되지 않습니다.
1227
+
1228
+ 그러나 새로운 CI 기능이 개발 중인 동안, 항상 성공하도록 할 수 있는 방법은 무엇일까요?
1229
+
1230
+ TravisCI와 같은 일부 CI는 `ignore-step-failure`를 지원하며 전체 작업을 성공한 것으로 보고하지만,
1231
+ 현재 우리가 사용하는 CircleCI와 Github Actions는 이를 지원하지 않습니다.
1232
+
1233
+ 따라서 다음과 같은 해결책을 사용할 수 있습니다.
1234
+
1235
+ 1. bash 스크립트에서 가능한 많은 오류를 억제하기 위해 실행 명령의 시작 부분에 `set +euo pipefail`을 추가합니다.
1236
+ 2. 마지막 명령은 반드시 성공해야 합니다. `echo "done"` 또는 `true`를 사용하면 됩니다.
1237
+
1238
+ 예시는 다음과 같습니다.
1239
+
1240
+ ```yaml
1241
+ - run:
1242
+ name: run CI experiment
1243
+ command: |
1244
+ set +euo pipefail
1245
+ echo "setting run-all-despite-any-errors-mode"
1246
+ this_command_will_fail
1247
+ echo "but bash continues to run"
1248
+ # emulate another failure
1249
+ false
1250
+ # but the last command must be a success
1251
+ echo "during experiment do not remove: reporting success to CI, even if there were failures"
1252
+ ```
1253
+
1254
+ 간단한 명령의 경우 다음과 같이 수행할 수도 있습니다.
1255
+
1256
+ ```bash
1257
+ cmd_that_may_fail || true
1258
+ ```
1259
+
1260
+ 결과에 만족한 후에는 물론, 실험적인 단계 또는 작업을 일반 작업의 나머지 부분과 통합하면서
1261
+ `set +euo pipefail` 또는 기타 추가한 요소를 제거하여
1262
+ 실험 작업이 일반 CI 작동에 방해되지 않도록 해야 합니다.
1263
+
1264
+ 이 전반적인 과정은 실험 단계가 PR의 전반적인 상태에 영향을 주지 않고 실패하도록
1265
+ `allow-failure`와 같은 기능을 설정할 수 있다면 훨씬 더 쉬웠을 것입니다.
1266
+ 그러나 앞에서 언급한 바와 같이 CircleCI와 Github Actions는 현재 이러한 기능들 지원하지 않습니다.
1267
+
1268
+ 이 기능의 지원을 위한 투표에 참여하고 CI 관련 스레드들에서 이러한 상황을 확인할 수도 있습니다.
1269
+
1270
+ - [Github Actions:](https://github.com/actions/toolkit/issues/399)
1271
+ - [CircleCI:](https://ideas.circleci.com/ideas/CCI-I-344)
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tflite.md ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2023 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # TFLite로 내보내기[[export-to-tflite]]
18
+
19
+ [TensorFlow Lite](https://www.tensorflow.org/lite/guide)는 자원이 제한된 휴대폰, 임베디드 시스템, 사물인터넷(IoT) 기기에서
20
+ 기계학습 모델을 배포하기 위한 경량 프레임워크입니다.
21
+ TFLite는 연산 능력, 메모리, 전력 소비가 제한된 기기에서 모델을 효율적으로 최적화하고 실행하기 위해
22
+ 설계되었습니다.
23
+ TensorFlow Lite 모델은 `.tflite` 파일 확장자로 식별되는 특수하고 효율적인 휴대용 포맷으로 표현됩니다.
24
+
25
+ 🤗 Optimum은 `exporters.tflite` 모듈로 🤗 Transformers 모델을 TFLite로 내보내는 기능을 제공합니다.
26
+ 지원되는 모델 아키텍처 목록은 [🤗 Optimum 문서](https://huggingface.co/docs/optimum/exporters/tflite/overview)를 참고하세요.
27
+
28
+ 모델을 TFLite로 내보내려면, 필요한 종속성을 설치하세요:
29
+
30
+ ```bash
31
+ pip install optimum[exporters-tf]
32
+ ```
33
+
34
+ 모든 사용 가능한 인수를 확인하려면, [🤗 Optimum 문서](https://huggingface.co/docs/optimum/main/en/exporters/tflite/usage_guides/export_a_model)를 참고하거나
35
+ 터미널에서 도움말을 살펴보세요:
36
+
37
+ ```bash
38
+ optimum-cli export tflite --help
39
+ ```
40
+
41
+ 예를 들어 🤗 Hub에서의 `google-bert/bert-base-uncased` 모델 체크포인트를 내보내려면, 다음 명령을 실행하세요:
42
+
43
+ ```bash
44
+ optimum-cli export tflite --model google-bert/bert-base-uncased --sequence_length 128 bert_tflite/
45
+ ```
46
+
47
+ 다음과 같이 진행 상황을 나타내는 로그와 결과물인 `model.tflite`가 저장된 위치를 보여주는 로그가 표시됩니다:
48
+
49
+ ```bash
50
+ Validating TFLite model...
51
+ -[✓] TFLite model output names match reference model (logits)
52
+ - Validating TFLite Model output "logits":
53
+ -[✓] (1, 128, 30522) matches (1, 128, 30522)
54
+ -[x] values not close enough, max diff: 5.817413330078125e-05 (atol: 1e-05)
55
+ The TensorFlow Lite export succeeded with the warning: The maximum absolute difference between the output of the reference model and the TFLite exported model is not within the set tolerance 1e-05:
56
+ - logits: max diff = 5.817413330078125e-05.
57
+ The exported model was saved at: bert_tflite
58
+ ```
59
+
60
+ 위 예제는 🤗 Hub에서의 체크포인트를 내보내는 방법을 보여줍니다.
61
+ 로컬 모델을 내보낸다면, 먼저 모델 가중치와 토크나이저 파일이 모두 같은 디렉터리( `local_path` )에 저장됐는지 확인하세요.
62
+ CLI를 사용할 때, 🤗 Hub에서의 체크포인트 이름 대신 `model` 인수에 `local_path`를 전달하면 됩니다.
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tiny_agents.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### `tiny-agents` CLI 및 MCP 도구[[tiny-agents-cli-and-mcp-tools]]
2
+
3
+ MCP 도구의 사용을 보여주기 위해 [`tiny-agents`](https://huggingface.co/blog/python-tiny-agents) CLI와 `transformers serve` 서버를 연동하는 방법을 살펴보겠습니다.
4
+
5
+ > [!TIP]
6
+ > 이 예시처럼 많은 Hugging Face Spaces를 MCP 서버로 활용할 수 있습니다. 호환 가능한 모든 Spaces는 [여기](https://huggingface.co/spaces?filter=mcp-server)에서 찾을 수 있습니다.
7
+
8
+ MCP 도구를 사용하려면 먼저 모델에 사용 가능한 도구를 알려야 합니다. 예를 들어, [이미지 생성 MCP 서버](https://evalstate-flux1-schnell.hf.space/)를 참조하는 `tiny-agents` 설정 파일을 살펴보겠습니다.
9
+
10
+ ```json
11
+ {
12
+ "model": "Menlo/Jan-nano",
13
+ "endpointUrl": "http://localhost:8000",
14
+ "servers": [
15
+ {
16
+ "type": "sse",
17
+ "url": "https://evalstate-flux1-schnell.hf.space/gradio_api/mcp/sse"
18
+ }
19
+ ]
20
+ }
21
+ ```
22
+
23
+ 그런 다음 아래 명령어로 `tiny-agents` 채팅 인터페이스를 실행할 수 있습니다.
24
+
25
+ ```bash
26
+ tiny-agents run path/to/your/config.json
27
+ ```
28
+
29
+ 백그라운드에서 `transformers serve`가 실행 중이라면, 이제 로컬 모델에서 MCP 도구를 사용할 수 있습니다. 다음은 `tiny-agents`와의 채팅 세션 예시입니다.
30
+
31
+ ```bash
32
+ Agent loaded with 1 tools:
33
+ • flux1_schnell_infer
34
+ » Generate an image of a cat on the moon
35
+ <Tool req_0_tool_call>flux1_schnell_infer {"prompt": "a cat on the moon", "seed": 42, "randomize_seed": true, "width": 1024, "height": 1024, "num_inference_steps": 4}
36
+
37
+ Tool req_0_tool_call
38
+ [Binary Content: Image image/webp, 57732 bytes]
39
+ The task is complete and the content accessible to the User
40
+ Image URL: https://evalstate-flux1-schnell.hf.space/gradio_api/file=/tmp/gradio/3dbddc0e53b5a865ed56a4e3dbdd30f3f61cf3b8aabf1b456f43e5241bd968b8/image.webp
41
+ 380576952
42
+
43
+ Flux 1 Schnell 이미지 생성기를 사용하여 달 위의 고양이 이미지를 생성했습니다. 이미지는 1024x1024 픽셀이며 4번의 추론 단계를 거쳐 생성되었습니다. 변경 사항이 필요하거나 추가 도움이 필요하시면 알려주세요!
44
+ ```
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/tokenizer_summary.md ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2020 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # 토크나이저 요약[[summary-of-the-tokenizers]]
18
+
19
+ [[open-in-colab]]
20
+
21
+ 이 페이지에서는 토큰화에 대해 자세히 살펴보겠습니다.
22
+
23
+ <Youtube id="VFp38yj8h3A"/>
24
+
25
+ [데이터 전처리하기 튜토리얼](preprocessing)에서 살펴본 것처럼, 텍스트를 토큰화하는 것은 텍스트를 단어 또는 서브워드로 분할하고 룩업 테이블을 통해 id로 변환하는 과정입니다.
26
+ 단어 또는 서브워드를 id로 변환하는 것은 간단하기 때문에 이번 문서에서는 텍스트를 단어 또는 서브워드로 쪼개는 것(즉, 텍스트를 토큰화하는 것)에 중점을 두겠습니다.
27
+ 구체적으로, 🤗 Transformers에서 사용되는 세 가지 주요 토큰화 유형인 [Byte-Pair Encoding (BPE)](#byte-pair-encoding), [WordPiece](#wordpiece), [SentencePiece](#sentencepiece)를 살펴보고 어떤 모델에서 어떤 토큰화 유형을 사용하는지 예시를 보여드리겠습니다.
28
+
29
+ 각 모델 페이지에 연결된 토크나이저의 문서를 보면 사전 훈련 모델에서 어떤 토크나이저를 사용했는지 알 수 있습니다.
30
+ 예를 들어, [`BertTokenizer`]를 보면 이 모델이 [WordPiece](#wordpiece)를 사용하는 것을 알 수 있습니다.
31
+
32
+ ## 개요[[introduction]]
33
+
34
+ 텍스트를 작은 묶음(chunk)으로 쪼개는 것은 보기보다 어려운 작업이며, 여러 가지 방법이 있습니다.
35
+ 예를 들어, `"Don't you love 🤗 Transformers? We sure do."` 라는 문장을 살펴보도록 하겠습니다.
36
+
37
+ <Youtube id="nhJxYji1aho"/>
38
+
39
+ 위 문장을 토큰화하는 간단한 방법은 공백을 기준으로 쪼개는 것입니다.
40
+ 토큰화된 결과는 다음과 같습니다:
41
+
42
+ ```
43
+ ["Don't", "you", "love", "🤗", "Transformers?", "We", "sure", "do."]
44
+ ```
45
+ 이는 첫 번째 결과로는 합리적이지만, `"Transformers?"`와 `"do."`토큰을 보면 각각 `"Transformer"`와 `"do"`에 구두점이 붙어있는 것을 확인할 수 있습니다.
46
+ 구두점을 고려해야 모델이 단어의 다른 표현과 그 뒤에 올 수 있는 모든 가능한 구두점을 학습할 필요가 없습니다. 그렇지 않으면 모델이 학습해야 하는 표현의 수가 폭발적으로 증가하게 됩니다.
47
+
48
+ 구두점을 고려한 토큰화 결과는 다음과 같습니다:
49
+
50
+ ```
51
+ ["Don", "'", "t", "you", "love", "🤗", "Transformers", "?", "We", "sure", "do", "."]
52
+ ```
53
+
54
+ 이전보다 나아졌습니다. 하지만, `"Don't"`의 토큰화 결과도 수정이 필요합니다.
55
+ `"Don't"`는 `"do not"`의 줄임말이기 때문에 `["Do", "n't"]`로 토큰화되는 것이 좋습니다.
56
+ 여기서부터 복잡해지기 시작합니다. 그리고 이 점이 각 모델마다 고유한 토큰화 유형이 존재하는 이유 중 하나입니다.
57
+ 텍스트를 토큰화하는 데 적용하는 규칙에 따라 동일한 텍스트에 대해 토큰화된 결과가 달라집니다.
58
+ 사전 훈련된 모델은 훈련 데이터를 토큰화하는 데 사용된 것과 동일한 규칙으로 토큰화된 입력을 제공해야만 제대로 작동합니다.
59
+
60
+ [spaCy](https://spacy.io/)와 [Moses](http://www.statmt.org/moses/?n=Development.GetStarted)는 유명한 규칙 기반 토크나이저입니다. 예제에 *spaCy*와 *Moses* 를 적용한 결과는 다음과 같습니다:
61
+
62
+ ```
63
+ ["Do", "n't", "you", "love", "🤗", "Transformers", "?", "We", "sure", "do", "."]
64
+ ```
65
+
66
+ 보시다시피 공백 및 구두점 토큰화와 규칙 기반 토큰화가 사용됩니다.
67
+ 공백 및 구두점, 규칙 기반 토큰화은 모두 단어 문장을 단어로 쪼개는 단어 토큰화에 해당합니다.
68
+ 이 토큰화 방법은 텍스트를 더 작은 묶음(chunk)로 분할하는 가장 직관적인 방법이지만, 대규모 텍스트 말뭉치에 대해서는 문제가 발생할 수 있습니다.
69
+ 이 경우 공백 및 구두점 토큰화는 일반적으로 매우 큰 어휘(사용된 모든 고유 단어와 토큰 집합)을 생성합니다.
70
+ *예를 들어*, [Transformer XL](model_doc/transformerxl)은 공백 및 구두점 토큰화를 사용해 어휘(vocabulary) 크기가 267,735입니다!
71
+
72
+ 어휘 크기가 크면 모델에 입력 및 출력 레이어로 엄청난 임베딩 행렬이 필요하므로 메모리와 시간 복잡성이 모두 증가합���다.
73
+ 일반적으로 트랜스포머 모델은 어휘 크기가 50,000개를 넘는 경우가 드물며, 특히 단일 언어에 대해서만 사전 훈련된 경우에는 더욱 그렇습니다.
74
+ 단순한 공백과 구두점 토큰화가 만족스럽지 않다면 단순히 문자를 토큰화하면 어떨까요?
75
+
76
+ <Youtube id="ssLq_EK2jLE"/>
77
+
78
+ 문자 토큰화는 아주 간단하고 메모리와 시간 복잡도를 크게 줄일 수 있지만, 모델이 의미 있는 입력 표현을 학습하기에는 훨씬 더 어렵습니다.
79
+
80
+ *예를 들어*, 문자 `"t"`에 대한 의미 있는 문맥 독립적 표현을 배우는 것 보다 단어 `"today"`에 대한 의미 있는 문맥 독립적 표현을 배우는 것이 훨씬 더 어렵습니다.
81
+ 문자 토큰화는 종종 성능 저하를 동반하기 때문에 두 가지 장점을 모두 얻기 위해 트랜스포머 모델은 **서브워드** 토큰화라고 하는 단어 수준과 문자 수준 토큰화의 하이브리드를 사용합니다.
82
+
83
+ ## 서브워드 토큰화[[subword-tokenization]]
84
+
85
+ <Youtube id="zHvTiHr506c"/>
86
+
87
+ 서브워드 토큰화 알고리즘은 자주 사용되는 단어는 더 작은 하위 단어로 쪼개고, 드문 단어는 의미 있는 하위 단어로 분해되어야 한다는 원칙에 따라 작동합니다.
88
+ 예를 들어 `"annoyingly"`는 드문 단어로 간주되어 `"annoying"`과 `"ly"`로 분해될 수 있습니다.
89
+ `"annoyingly"`가 `"annoying"`과 `"ly"`의 합성어인 반면, `"annoying"`과 `"ly"` 둘 다 독립적인 서브워드로 자주 등장합니다.
90
+ 이는 터키어와 같은 응집성 언어에서 특히 유용하며, 서브워드를 묶어 임의로 긴 복합 단어를 만들 수 있습니다.
91
+
92
+ 서브워드 토큰화를 사용하면 모델이 의미 있는 문맥 독립적 표현을 학습하면서 합리적인 어휘 크기를 가질 수 있습니다.
93
+ 또한, 서브워드 토큰화를 통해 모델은 이전에 본 적이 없는 단어를 알려진 서브워드로 분해하여 처리할 수 있습니다.
94
+
95
+ 예를 들어, [`~transformers.BertTokenizer`]는 `"I have a new GPU!"` 라는 문장을 아래와 같이 토큰화합니다:
96
+
97
+ ```py
98
+ >>> from transformers import BertTokenizer
99
+
100
+ >>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased")
101
+ >>> tokenizer.tokenize("I have a new GPU!")
102
+ ["i", "have", "a", "new", "gp", "##u", "!"]
103
+ ```
104
+
105
+ 대소문자가 없는 모델을 사용해 문장의 시작이 소문자로 표기되었습니다.
106
+ 단어 `["i", "have", "a", "new"]`는 토크나이저의 어휘에 속하지만, `"gpu"`는 속하지 않는 것을 확인할 수 있습니다.
107
+ 결과적으로 토크나이저는 `"gpu"`를 알려진 두 개의 서브워드로 쪼갭니다: `["gp" and "##u"]`.
108
+ `"##"`은 토큰의 나머지 부분이 공백 없이 이전 토큰에 연결되어야(attach) 함을 의미합니다(토큰화 디코딩 또는 역전을 위해).
109
+
110
+ 또 다른 예로, [`~transformers.XLNetTokenizer`]는 이전에 예시 문장을 다음과 같이 토큰화합니다:
111
+ ```py
112
+ >>> from transformers import XLNetTokenizer
113
+
114
+ >>> tokenizer = XLNetTokenizer.from_pretrained("xlnet/xlnet-base-cased")
115
+ >>> tokenizer.tokenize("Don't you love 🤗 Transformers? We sure do.")
116
+ ["▁Don", "'", "t", "▁you", "▁love", "▁", "🤗", "▁", "Transform", "ers", "?", "▁We", "▁sure", "▁do", "."]
117
+ ```
118
+
119
+ `"▁"`가 가지는 의미는 [SentencePiece](#sentencepiece)에서 다시 살펴보도록 하겠습니다.
120
+ 보다시피 `"Transformers"` 라는 드문 단어는 서브워드 `"Transform"`와 `"ers"`로 쪼개집니다.
121
+
122
+ 이제 다양한 하위 단어 토큰화 알고리즘이 어떻게 작동하는지 살펴보겠습니다.
123
+ 이러한 토큰화 알고리즘은 일반적으로 해당 모델이 학습되는 말뭉치에 대해 수행되는 어떤 형태의 학습에 의존한다는 점에 유의하세요.
124
+
125
+ <a id='byte-pair-encoding'></a>
126
+
127
+ ### 바이트 페어 인코딩 (Byte-Pair Encoding, BPE)[[bytepair-encoding-bpe]]
128
+
129
+ 바이트 페어 인코딩(BPE)은 [Neural Machine Translation of Rare Words with Subword Units (Sennrich et
130
+ al., 2015)](https://huggingface.co/papers/1508.07909) 에서 소개되었습니다.
131
+ BPE는 훈련 데이터를 단어로 분할하는 사전 토크나이저(pre-tokenizer)에 의존합니다.
132
+ 사전 토큰화(Pretokenization)에는 [GPT-2](model_doc/gpt2), [Roberta](model_doc/roberta)와 같은 간단한 공백 토큰화가 있습니다.
133
+ 복잡한 사전 토큰화에는 규칙 기반 토큰화가 해당하는데, 훈련 말뭉치에서 각 단어의 빈도를 계산하기 위해 사용합니다.
134
+ [XLM](model_doc/xlm), 대부분의 언어에서 Moses를 사용하는 [FlauBERT](model_doc/flaubert), Spacy와 ftfy를 사용하는 [GPT](model_doc/gpt)가 해당합니다.
135
+
136
+
137
+ 사전 토큰화 이후에, 고유 단어 집합가 생성되고 훈련 데이터에서 각 단어가 등장하는 빈도가 결정됩니다.
138
+ 다음으로, BPE는 고유 단어 집합에 나타나는 모든 기호로 구성된 기본 어휘를 생성하고 기본 어휘의 두 기호��서 새로운 기호를 형성하는 병합 규칙을 학습합니다.
139
+ 어휘가 원하는 어휘 크기에 도달할 때까지 위의 과정을 반복합니다.
140
+ 어휘 크기는 토크나이저를 훈련시키기 전에 정의해야 하는 하이퍼파라미터라는 점을 유의하세요.
141
+
142
+ 예를 들어, 사전 토큰화 후 빈도를 포함한 다음과 같은 어휘 집합이 결정되었다고 가정해 보겠습니다:
143
+
144
+ ```
145
+ ("hug", 10), ("pug", 5), ("pun", 12), ("bun", 4), ("hugs", 5)
146
+ ```
147
+
148
+ 결과적으로 기본 어휘는 `["b", "g", "h", "n", "p", "s", "u"]` 이고, 각 단어를 기본 어휘에 속하는 기호로 쪼개면 아래와 같습니다:
149
+
150
+ ```
151
+ ("h" "u" "g", 10), ("p" "u" "g", 5), ("p" "u" "n", 12), ("b" "u" "n", 4), ("h" "u" "g" "s", 5)
152
+ ```
153
+
154
+ 그런 다음 BPE는 가능한 각 기호 쌍의 빈도를 계산하여 가장 자주 발생하는 기호 쌍을 선택합니다.
155
+ 위의 예시에서 `"h"` 뒤에 오는 `"u"`는 _10 + 5 = 15_ 번 등장합니다. (`"hug"`에서 10번, `"hugs"`에서 5번 등장)
156
+
157
+ 하지만, 가장 등장 빈도가 높은 기호 쌍은 `"u"` 뒤에 오는 `"g"`입니다. _10 + 5 + 5 = 20_ 으로 총 20번 등장합니다.
158
+ 따라서 토크나이저가 병합하는 가장 첫 번째 쌍은 `"u"` 뒤에 오는 `"g"`입니다. `"ug"`가 어휘에 추가되어 어휘는 다음과 같습니다:
159
+
160
+ ```
161
+ ("h" "ug", 10), ("p" "ug", 5), ("p" "u" "n", 12), ("b" "u" "n", 4), ("h" "ug" "s", 5)
162
+ ```
163
+
164
+ BPE는 다음으로 가장 많이 등장하는 기호 쌍을 식별합니다.
165
+ `"u"` 뒤에 오는 `"n"`은 16번 등장해 `"un"` 으로 병합되어 어휘에 추가됩니다.
166
+ 그 다음으로 빈도수가 놓은 기호 쌍은 `"h"` 뒤에 오는 `"ug"`로 15번 등장합니다.
167
+ 다시 한 번 `"hug"`로 병합되어 어휘에 추가됩니다.
168
+
169
+ 현재 단계에서 어휘는 `["b", "g", "h", "n", "p", "s", "u", "ug", "un", "hug"]` 이고, 고유 단어 집합은 다음과 같습니다:
170
+
171
+ ```
172
+ ("hug", 10), ("p" "ug", 5), ("p" "un", 12), ("b" "un", 4), ("hug" "s", 5)
173
+ ```
174
+
175
+ 이 시점에서 바이트 페어 인코딩 훈련이 중단된다고 가정하면, 훈련된 병합 규칙은 새로운 단어에 적용됩니다(기본 어휘에 포함된 기호가 새로운 단어에 포함되지 않는 한).
176
+ 예를 들어, 단어 `"bug"`는 `["b", "ug"]`로 토큰화되지만, `"m"`이 기본 어휘에 없기 때문에 `"mug"`는 `["<unk>", "ug"]`로 토큰화될 것입니다.
177
+ 훈련 데이터에는 단일 문자가 최소한 한 번 등장하기 때문에 일반적으로 `"m"`과 같은 단일 문자는 `"<unk>"` 기호로 대체되지 않지만, 이모티콘과 같은 특별한 문자인 경우에는 대체될 수 있습니다.
178
+
179
+ 이전에 언급했듯이 어휘 크기(즉 기본 어휘 크기 + 병합 횟수)는 선택해야하는 하이퍼파라미터입니다.
180
+ 예를 들어 [GPT](model_doc/gpt)의 기본 어휘 크기는 478, 40,000번의 병합 이후에 훈련을 종료하기 때문에 어휘 크기가 40,478입니다.
181
+
182
+ #### 바이트 수준 BPE (Byte-level BPE)[[bytelevel-bpe]]
183
+
184
+ 가능한 모든 기본 문자를 포함하는 기본 어휘의 크기는 굉장히 커질 수 있습니다. (예: 모든 유니코드 문자를 기본 문자로 간주하는 경우)
185
+ 더 나은 기본 어휘를 갖도록 [GPT-2](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf)는 기본 어휘로 바이트(bytes)를 사용합니다.
186
+ 이 방식은 모든 기본 문자가 어휘에 포함되도록 하면서 기본 어휘의 크기를 256으로 제한합니다.
187
+ 구두점을 다루는 추가적인 규칙을 사용해 GPT2 토크나이저는 모든 텍스트를 <unk> 기호 없이 토큰화할 수 있습니다.
188
+ [GPT-2](model_doc/gpt)의 어휘 크기는 50,257로 256 바이트 크기의 기본 토큰, 특별한 end-of-text 토큰과 50,000번의 병합으로 학습한 기호로 구성됩니다.
189
+
190
+ <a id='wordpiece'></a>
191
+
192
+ ### 워드피스 (WordPiece)[[wordpiece]]
193
+
194
+ 워드피스는 [BERT](model_doc/bert), [DistilBERT](model_doc/distilbert), [Electra](model_doc/electra)에 사용된 서브워드 토큰화 알고리즘입니다.
195
+ 이 알고리즘은 [Japanese and Korean Voice Search (Schuster et al., 2012)](https://static.googleusercontent.com/media/research.google.com/ja//pubs/archive/37842.pdf)에서 소개되었고, BPE와 굉장히 유사합니다.
196
+ 워드피스는 훈련 데이터에 등장하는 모든 문자로 기본 어휘를 초기화한 후, 주어진 병합 규칙에 따라 점진적으로 학습합니다.
197
+ BPE와는 대조적으로 워드피스는 가장 빈도수가 높은 기호 쌍을 선택하지 않고, 어휘에 추가되었을 때 훈련 데이터의 우도가 최대화되는 쌍을 선택합니다.
198
+
199
+ 정확히 무슨 의미일까요?
200
+ 이전 예시를 참조하면, 훈련 데이터의 우도 값을 최대화하는 것은 모든 기호 쌍 중에서 첫 번째 기호와 두 번째 기호의 확률로 나눈 확률이 가장 큰 기호 쌍을 찾는 것과 동일합니다.
201
+ 예를 들어 `"ug"`의 확률이 `"u"`와 `"g"` ���각으로 쪼개졌을 때 보다 높아야 `"u"` 뒤에 오는 `"g"`는 병합될 것입니다.
202
+ 직관적으로 워드피스는 두 기호를 병합하여 _잃는_ 것을 평가하여 그만한 _가치_가 있는지 확인한다는 점에서 BPE와 약간 다릅니다.
203
+
204
+ <a id='unigram'></a>
205
+
206
+ ### 유니그램 (Unigram)[[unigram]]
207
+
208
+ 유니그램은 [Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates (Kudo, 2018)](https://huggingface.co/papers/1804.10959)에서 제안된 서브워드 토큰화 알고리즘입니다.
209
+ BPE나 워드피스와 달리 유니그램은 기본 어휘를 많은 수의 기호로 초기화한 후 각 기호를 점진적으로 줄여 더 작은 어휘를 얻습니다.
210
+ 예를 들어 기본 어휘는 모든 사전 토큰화된 단어와 가장 일반적인 하위 문자열에 해당할 수 있습니다.
211
+ 유니그램은 transformers 모델에서 직접적으로 사용되지는 않지만, [SentencePiece](#sentencepiece)와 함께 사용됩니다.
212
+
213
+ 각 훈련 단계에서 유니그램 알고리즘은 현재 어휘와 유니그램 언어 모델이 주어졌을 때 훈련 데이터에 대한 손실(흔히 로그 우도로 정의됨)을 정의합니다.
214
+ 그런 다음 어휘의 각 기호에 대해 알고리즘은 해당 기호를 어휘에서 제거할 경우 전체 손실이 얼마나 증가할지 계산합니다.
215
+ 이후에 유니그램은 손실 증가율이 가장 낮은 기호의 p(보통 10% 또는 20%) 퍼센트를 제거합니다. (제거되는 기호는 훈련 데이터에 대한 전체 손실에 가장 작은 영향을 미칩니다.)
216
+ 어휘가 원하는 크기에 도달할 때까지 이 과정을 반복합니다.
217
+ 유니그램 알고리즘은 항상 기본 문자를 포함해 어떤 단어라도 토큰화할 수 있습니다.
218
+ 유니그램이 병합 규칙에 기반하지 않기 떄문에 (BPE나 워드피스와는 대조적으로), 해당 알고리즘은 훈련 이후에 새로운 텍스트를 토큰화하는데 여러 가지 방법이 있습니다.
219
+
220
+ 예를 들어, 훈련된 유니그램 토큰화가 다음과 같은 어휘를 가진다면:
221
+
222
+ ```
223
+ ["b", "g", "h", "n", "p", "s", "u", "ug", "un", "hug"],
224
+ ```
225
+
226
+ `"hugs"`는 두 가지로 토큰화할 수 있습니다. `["hug", "s"]`와 `["h", "ug", "s"]` 또는 `["h", "u", "g", "s"]`.
227
+
228
+ 그렇다면 어떤 토큰화 방법을 선택해야 할까요?
229
+ 유니그램은 어휘를 저장하는 것 외에도 훈련 말뭉치에 각 토큰의 확률을 저장하여 훈련 후 가능한 각 토큰화의 확률을 계산할 수 있도록 합니다.
230
+ 이 알고리즘은 단순히 실제로 가장 가능성이 높은 토큰화를 선택하지만, 확률에 따라 가능한 토큰화를 샘플링할 수 있는 가능성도 제공합니다.
231
+ 이러한 확률은 토크나이저가 학습한 손실에 의해 정의됩니다.
232
+
233
+ 단어로 구성된 훈련 데이터를 \\(x_{1}, \dots, x_{N}\\)라 하고, 단어 \\(x_{i}\\)에 대한 가능한 모든 토큰화 결과를 \\(S(x_{i})\\)라 한다면, 전체 손실은 다음과 같이 정의됩니다:
234
+
235
+ $$\mathcal{L} = -\sum_{i=1}^{N} \log \left ( \sum_{x \in S(x_{i})} p(x) \right )$$
236
+
237
+
238
+
239
+ <a id='sentencepiece'></a>
240
+
241
+ ### 센텐스피스 (SentencePiece)[[sentencepiece]]
242
+
243
+ 지금까지 다룬 토큰화 알고리즘은 동일한 문제를 가집니다: 입력 텍스트는 공백을 사용하여 단어를 구분한다고 가정합니다.
244
+ 하지만, 모든 언어에서 단어를 구분하기 위해 공백을 사용하지 않습니다.
245
+ 한가지 가능한 해결방안은 특정 언어에 특화된 사전 토크나이저를 사용하는 것입니다. 예를 들어 [XLM](model_doc/xlm)은 특정 중국어, 일본어, 태국어 사전 토크나이저를 사용합니다.
246
+ 이 문제를 일반적인 방법으로 해결하기 위해, [SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing (Kudo et al., 2018)](https://huggingface.co/papers/1808.06226)는 입력을 스트림으로 처리해 공백를 하나의 문자로 사용합니다.
247
+ 이후에 BPE 또는 유니그램 알고리즘을 사용해 적절한 어휘를 구성합니다.
248
+
249
+ [`XLNetTokenizer`]는 센텐스피스를 사용하기 때문에, 위에서 다룬 예시에서 어휘에 `"▁"`가 포함되어있습니다.
250
+ 모든 토큰을 합친 후 `"▁"`을 공백으로 대체하면 되기 때문에 센텐스피스로 토큰화된 결과는 디코딩하기 수월합니다.
251
+
252
+ transformers에서 제공하는 센텐스피스 토크나이저를 사용하는 모든 모델은 유니그램과 함께 사용됩니다.
253
+ [ALBERT](model_doc/albert), [XLNet](model_doc/xlnet), [Marian](model_doc/marian), [T5](model_doc/t5) 모델이 센텐스피스 토크나이저를 사용합니다.
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/torchscript.md ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # TorchScript로 내보내기[[export-to-torchscript]]
18
+
19
+ <Tip>
20
+
21
+ TorchScript를 활용한 실험은 아직 초기 단계로, 가변적인 입력 크기 모델들을 통해 그 기능성을 계속 탐구하고 있습니다.
22
+ 이 기능은 저희가 관심을 두고 있는 분야 중 하나이며,
23
+ 앞으로 출시될 버전에서 더 많은 코드 예제, 더 유연한 구현, 그리고 Python 기반 코드와 컴파일된 TorchScript를 비교하는 벤치마크를 등을 통해 분석을 심화할 예정입니다.
24
+
25
+ </Tip>
26
+
27
+ [TorchScript 문서](https://pytorch.org/docs/stable/jit.html)에서는 이렇게 말합니다.
28
+
29
+ > TorchScript는 PyTorch 코드에서 직렬화 및 최적화 가능한 모델을 생성하는 방법입니다.
30
+
31
+ [JIT과 TRACE](https://pytorch.org/docs/stable/jit.html)는 개발자가 모델을 내보내서 효율 지향적인 C++ 프로그램과 같은 다른 프로그램에서 재사용할 수 있도록 하는 PyTorch 모듈입니다.
32
+
33
+ PyTorch 기반 Python 프로그램과 다른 환경에서 모델을 재사용할 수 있도록, 🤗 Transformers 모델을 TorchScript로 내보낼 수 있는 인터페이스를 제공합니다.
34
+ 이 문서에서는 TorchScript를 사용하여 모델을 내보내고 사용하는 방법을 설명합니다.
35
+
36
+ 모델을 내보내려면 두 가지가 필요합니다:
37
+
38
+ - `torchscript` 플래그로 모델 인스턴스화
39
+ - 더미 입력을 사용한 순전파(forward pass)
40
+
41
+ 이 필수 조건들은 아래에 자세히 설명된 것처럼 개발자들이 주의해야 할 여러 사항들을 의미합니다.
42
+
43
+ ## TorchScript 플래그와 묶인 가중치(tied weights)[[torchscript-flag-and-tied-weights]]
44
+
45
+ `torchscript` 플래그가 필요한 이유는 대부분의 🤗 Transformers 언어 모델에서 `Embedding` 레이어와 `Decoding` 레이어 간의 묶인 가중치(tied weights)가 존재하기 때문입니다.
46
+ TorchScript는 묶인 가중치를 가진 모델을 내보낼 수 없으므로, 미리 가중치를 풀고 복제해야 합니다.
47
+
48
+ `torchscript` 플래그로 인스턴스화된 모델은 `Embedding` 레이어와 `Decoding` 레이어가 분리되어 있으므로 이후에 훈련해서는 안 됩니다.
49
+ 훈련을 하게 되면 두 레이어 간 동기화가 해제되어 예상치 못한 결과가 발생할 수 있습니다.
50
+
51
+ 언어 모델 헤드를 갖지 않은 모델은 가중치가 묶여 있지 않아서 이 문제가 발생하지 않습니다.
52
+ 이러한 모델들은 `torchscript` 플래그 없이 안전하게 내보낼 수 있습니다.
53
+
54
+ ## 더미 입력과 표준 길이[[dummy-inputs-and-standard-lengths]]
55
+
56
+ 더미 입력(dummy inputs)은 모델의 순전파(forward pass)에 사용됩니다.
57
+ 입력 값이 레이어를 통해 전파되는 동안, PyTorch는 각 텐서에서 실행된 다른 연산을 추적합니다.
58
+ 이러한 기록된 연산은 모델의 *추적(trace)*을 생성하는 데 사용됩니다.
59
+
60
+ 추적은 입력의 차원을 기준으로 생성됩니다.
61
+ 따라서 더미 입력의 차원에 제한되어, 다른 시퀀스 길이나 배치 크기에서는 작동하지 않습니다.
62
+ 다른 크기로 시도할 경우 다음과 같은 오류가 발생합니다:
63
+
64
+ ```
65
+ `The expanded size of the tensor (3) must match the existing size (7) at non-singleton dimension 2`
66
+ ```
67
+ 추론 중 모델에 공급될 가장 큰 입력만큼 큰 더미 입력 크기로 모델을 추적하는 것이 좋습니다.
68
+ 패딩은 누락된 값을 채우는 데 도움이 될 수 있습니다.
69
+ 그러나 모델이 더 큰 입력 크기로 추적되기 때문에, 행렬의 차원이 커지고 계산량이 많아집니다.
70
+
71
+ 다양한 시퀀스 길이 모델을 내보낼 때는 각 입력에 대해 수행되는 총 연산 횟수에 주의하고 성능을 주의 깊게 확인하세요.
72
+
73
+ ## Python에서 TorchScript 사용하기[[using-torchscript-in-python]]
74
+
75
+ 이 섹션에서는 모델을 저장하고 가져오는 방법, 추적을 사용하여 추론하는 방법을 보여줍니다.
76
+
77
+ ### 모델 저장하기[[saving-a-model]]
78
+
79
+ `BertModel`을 TorchScript로 내보내려면 `BertConfig` 클래스에서 `BertModel`을 인스턴스화한 다음, `traced_bert.pt`라는 파일명으로 디스크에 저장하면 됩니다.
80
+
81
+ ```python
82
+ from transformers import BertModel, BertTokenizer, BertConfig
83
+ import torch
84
+
85
+ enc = BertTokenizer.from_pretrained("google-bert/bert-base-uncased")
86
+
87
+ # 입력 텍스트 토큰화하기
88
+ text = "[CLS] Who was Jim Henson ? [SEP] Jim Henson was a puppeteer [SEP]"
89
+ tokenized_text = enc.tokenize(text)
90
+
91
+ # 입력 토큰 중 하나를 마스킹하기
92
+ masked_index = 8
93
+ tokenized_text[masked_index] = "[MASK]"
94
+ indexed_tokens = enc.convert_tokens_to_ids(tokenized_text)
95
+ segments_ids = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]
96
+
97
+ # 더미 입력 만들기
98
+ tokens_tensor = torch.tensor([indexed_tokens])
99
+ segments_tensors = torch.tensor([segments_ids])
100
+ dummy_input = [tokens_tensor, segments_tensors]
101
+
102
+ # torchscript 플래그로 모델 초기화하기
103
+ # 이 모델은 LM 헤드가 없으므로 필요하지 않지만, 플래그를 True로 설정합니다.
104
+ config = BertConfig(
105
+ vocab_size_or_config_json_file=32000,
106
+ hidden_size=768,
107
+ num_hidden_layers=12,
108
+ num_attention_heads=12,
109
+ intermediate_size=3072,
110
+ torchscript=True,
111
+ )
112
+
113
+ # 모델을 인스턴트화하기
114
+ model = BertModel(config)
115
+
116
+ # 모델을 평가 모드로 두어야 합니다.
117
+ model.eval()
118
+
119
+ # 만약 *from_pretrained*를 사용하여 모델을 인스턴스화하는 경우, TorchScript 플래그를 쉽게 설정할 수 있습니다
120
+ model = BertModel.from_pretrained("google-bert/bert-base-uncased", torchscript=True)
121
+
122
+ # 추적 생성하기
123
+ traced_model = torch.jit.trace(model, [tokens_tensor, segments_tensors])
124
+ torch.jit.save(traced_model, "traced_bert.pt")
125
+ ```
126
+
127
+ ### 모델 가져오기[[loading-a-model]]
128
+
129
+ 이제 이전에 저장한 `BertModel`, 즉 `traced_bert.pt`를 디스크에서 가져오고, 이전에 초기화한 `dummy_input`에서 사용할 수 있습니다.
130
+
131
+ ```python
132
+ loaded_model = torch.jit.load("traced_bert.pt")
133
+ loaded_model.eval()
134
+
135
+ all_encoder_layers, pooled_output = loaded_model(*dummy_input)
136
+ ```
137
+
138
+ ### 추적된 모델을 사용하여 추론하기[[using-a-traced-model-for-inference]]
139
+
140
+ `__call__` 이중 언더스코어(dunder) 메소드를 사용하여 추론에 추적된 모델을 사용하세요:
141
+
142
+ ```python
143
+ traced_model(tokens_tensor, segments_tensors)
144
+ ```
145
+
146
+ ## Neuron SDK로 Hugging Face TorchScript 모델을 AWS에 배포하기[[deploy-hugging-face-torchscript-models-to-aws-with-the-neuron-sdk]]
147
+
148
+ AWS가 클라우드에서 저비용, 고성능 머신 러닝 추론을 위한 [Amazon EC2 Inf1](https://aws.amazon.com/ec2/instance-types/inf1/) 인스턴스 제품군을 출시했습니다.
149
+ Inf1 인스턴스는 딥러닝 추론 워크로드에 특화된 맞춤 하드웨어 가속기인 AWS Inferentia 칩으로 구동됩니다.
150
+ [AWS Neuron](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/#)은 Inferentia를 위한 SDK로, Inf1에 배포하기 위한 transformers 모델 추적 및 최적화를 지원합니다.
151
+ Neuron SDK는 다음과 같은 기능을 제공합니다:
152
+
153
+ 1. 코드 한 줄만 변경하면 클라우드 추론를 위해 TorchScript 모델을 추적하고 최적화할 수 있는 쉬운 API
154
+ 2. 즉시 사용 가능한 성능 최적화로 [비용 효율 향상](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/benchmark/>)
155
+ 3. [PyTorch](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/src/examples/pytorch/bert_tutorial/tutorial_pretrained_bert.html) 또는 [TensorFlow](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/src/examples/tensorflow/huggingface_bert/huggingface_bert.html)로 구축된 Hugging Face transformers 모델 지원
156
+
157
+ ### 시사점[[implications]]
158
+
159
+ [BERT (Bidirectional Encoder Representations from Transformers)](https://huggingface.co/docs/transformers/main/model_doc/bert) 아키텍처 또는 그 변형인 [distilBERT](https://huggingface.co/docs/transformers/main/model_doc/distilbert) 및 [roBERTa](https://huggingface.co/docs/transformers/main/model_doc/roberta)를 기반으로 한 Transformers 모델은 추출 기반 질의응답, 시퀀스 분류 및 토큰 분류와 같은 비생성 작업 시 Inf1에서 최상의 성능을 보입니다.
160
+ 그러나 텍스트 생성 작업도 [AWS Neuron MarianMT 튜토리얼](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/src/examples/pytorch/transformers-marianmt.html)을 따라 Inf1에서 실행되도록 조정할 수 있습니다.
161
+
162
+ Inferentia에서 바로 변환할 수 있는 모델에 대한 자세한 정보는 Neuron 문서의 [Model Architecture Fit](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/models/models-inferentia.html#models-inferentia) 섹션에서 확인할 수 있습니다.
163
+
164
+ ### 종속성[[dependencies]]
165
+
166
+ AWS Neuron을 사용하여 모델을 변환하려면 [Neuron SDK 환경](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/neuron-frameworks/pytorch-neuron/index.html#installation-guide)이 필요합니다.
167
+ 이는 [AWS Deep Learning AMI](https://docs.aws.amazon.com/dlami/latest/devguide/tutorial-inferentia-launching.html)에 미리 구성되어 있습니다.
168
+
169
+ ### AWS Neuron으로 모델 변환하기[[converting-a-model-for-aws-neuron]]
170
+
171
+ `BertModel`을 추적하려면, [Python에서 TorchScript 사용하기](torchscript#using-torchscript-in-python)에서와 동일한 코드를 사용해서 AWS NEURON용 모델을 변환합니다.
172
+ `torch.neuron` 프레임워크 익스텐션을 가져와 Python API를 통해 Neuron SDK의 구성 요소에 접근합니다:
173
+
174
+ ```python
175
+ from transformers import BertModel, BertTokenizer, BertConfig
176
+ import torch
177
+ import torch.neuron
178
+ ```
179
+
180
+ 다음 줄만 수정하면 됩니다:
181
+
182
+ ```diff
183
+ - torch.jit.trace(model, [tokens_tensor, segments_tensors])
184
+ + torch.neuron.trace(model, [token_tensor, segments_tensors])
185
+ ```
186
+
187
+ 이로써 Neuron SDK가 모델을 추적하고 Inf1 인스턴스에 최적화할 수 있게 됩니다.
188
+
189
+ AWS Neuron SDK의 기능, 도구, 예제 튜토리얼 및 최신 업데이트에 대해 자세히 알아보려면 [AWS NeuronSDK 문서](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/index.html)를 참조하세요.
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/trainer.md ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2023 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # Trainer [[trainer]]
18
+
19
+ [`Trainer`]는 Transformers 라이브러리에 구현된 PyTorch 모델을 반복하여 훈련 및 평가 과정입니다. 훈련에 필요한 요소(모델, 토크나이저, 데이터셋, 평가 함수, 훈련 하이퍼파라미터 등)만 제공하면 [`Trainer`]가 필요한 나머지 작업을 처리합니다. 이를 통해 직접 훈련 루프를 작성하지 않고도 빠르게 훈련을 시작할 수 있습니다. 또한 [`Trainer`]는 강력한 맞춤 설정과 다양한 훈련 옵션을 제공하여 사용자 맞춤 훈련이 가능합니다.
20
+
21
+ <Tip>
22
+
23
+ Transformers는 [`Trainer`] 클래스 외에도 번역이나 요약과 같은 시퀀스-투-시퀀스 작업을 위한 [`Seq2SeqTrainer`] 클래스도 제공합니다. 또한 [TRL](https://hf.co/docs/trl) 라이브러리에는 [`Trainer`] 클래스를 감싸고 Llama-2 및 Mistral과 같은 언어 모델을 자동 회귀 기법으로 훈련하는 데 최적화된 [`~trl.SFTTrainer`] 클래스 입니다. [`~trl.SFTTrainer`]는 시퀀스 패킹, LoRA, 양자화 및 DeepSpeed와 같은 기능을 지원하여 크기 상관없이 모델 효율적으로 확장할 수 있습니다.
24
+
25
+ <br>
26
+
27
+ 이들 다른 [`Trainer`] 유형 클래스에 대해 더 알고 싶다면 [API 참조](./main_classes/trainer)를 확인하여 언제 어떤 클래스가 적합할지 얼마든지 확인하세요. 일반적으로 [`Trainer`]는 가장 다재다능한 옵션으로, 다양한 작업에 적합합니다. [`Seq2SeqTrainer`]는 시퀀스-투-시퀀스 작업을 위해 설계되었고, [`~trl.SFTTrainer`]는 언어 모델 훈련을 위해 설계되었습니다.
28
+
29
+ </Tip>
30
+
31
+ 시작하기 전에, 분산 환경에서 PyTorch 훈련과 실행을 할 수 있게 [Accelerate](https://hf.co/docs/accelerate) 라이브러리가 설치되었는지 확인하세요.
32
+
33
+ ```bash
34
+ pip install accelerate
35
+
36
+ # 업그레이드
37
+ pip install accelerate --upgrade
38
+ ```
39
+
40
+ 이 가이드는 [`Trainer`] 클래스에 대한 개요를 제공합니다.
41
+
42
+ ## 기본 사용법 [[basic-usage]]
43
+
44
+ [`Trainer`]는 기본적인 훈련 루프에 필요한 모든 코드를 포함하고 있습니다.
45
+
46
+ 1. 손실을 계산하는 훈련 단계를 수행합니다.
47
+ 2. [`~accelerate.Accelerator.backward`] 메소드로 그레이디언트를 계산합니다.
48
+ 3. 그레이디언트를 기반으로 가중치를 업데이트합니다.
49
+ 4. 정해진 에폭 수에 도달할 때까지 이 과정을 반복합니다.
50
+
51
+ [`Trainer`] 클래스는 PyTorch와 훈련 과정에 익숙하지 않거나 막 시작한 경우에도 훈련이 가능하도록 필요한 모든 코드를 추상화하였습니다. 또한 매번 훈련 루프를 손수 작성하지 않아도 되며, 훈련에 필요한 모델과 데이터셋 같은 필수 구성 요소만 제공하면, [Trainer] 클래스가 나머지를 처리합니다.
52
+
53
+ 훈련 옵션이나 하이퍼파라미터를 지정하려면, [`TrainingArguments`] 클래스에서 확인 할 수 있습니다. 예를 들어, 모델을 저장할 디렉토리를 `output_dir`에 정의하고, 훈련 후에 Hub로 모델을 푸시하려면 `push_to_hub=True`로 설정합니다.
54
+
55
+ ```py
56
+ from transformers import TrainingArguments
57
+
58
+ training_args = TrainingArguments(
59
+ output_dir="your-model",
60
+ learning_rate=2e-5,
61
+ per_device_train_batch_size=16,
62
+ per_device_eval_batch_size=16,
63
+ num_train_epochs=2,
64
+ weight_decay=0.01,
65
+ eval_strategy="epoch",
66
+ save_strategy="epoch",
67
+ load_best_model_at_end=True,
68
+ push_to_hub=True,
69
+ )
70
+ ```
71
+
72
+ `training_args`를 [`Trainer`]에 모델, 데이터셋, 데이터셋 전처리 도구(데이터 유형에 따라 토크나이저, 특징 추출기 또는 이미지 프로세서일 수 있음), 데이터 수집기 및 훈련 중 확인할 지표를 계산할 함수를 함께 전달하세요.
73
+
74
+ 마지막으로, [`~Trainer.train`]를 호출하여 훈련을 시작하세요!
75
+
76
+ ```py
77
+ from transformers import Trainer
78
+
79
+ trainer = Trainer(
80
+ model=model,
81
+ args=training_args,
82
+ train_dataset=dataset["train"],
83
+ eval_dataset=dataset["test"],
84
+ tokenizer=tokenizer,
85
+ data_collator=data_collator,
86
+ compute_metrics=compute_metrics,
87
+ )
88
+
89
+ trainer.train()
90
+ ```
91
+
92
+ ### 체크포인트 [[checkpoints]]
93
+
94
+ [`Trainer`] 클래스는 [`TrainingArguments`]의 `output_dir` 매개변수에 지정된 디렉토리에 모델 체크포인트를 저장합니다. 체크포인트는 `checkpoint-000` 하위 폴더에 저장되며, 여기서 끝의 숫자는 훈련 단계에 해당합니다. 체크포인트를 저장하면 나중에 훈련을 재개할 때 유용합니다.
95
+
96
+ ```py
97
+ # 최신 체크포인트에서 재개
98
+ trainer.train(resume_from_checkpoint=True)
99
+
100
+ # 출력 디렉토리에 저장된 특정 체크포인트에서 재개
101
+ trainer.train(resume_from_checkpoint="your-model/checkpoint-1000")
102
+ ```
103
+
104
+ 체크포인트를 Hub에 푸시하려면 [`TrainingArguments`]에서 `push_to_hub=True`로 설정하여 커밋하고 푸시할 수 있습니다. 체크포인트 저장 방법을 결정하는 다른 옵션은 [`hub_strategy`](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.hub_strategy) 매개변수에서 설정합니다:
105
+
106
+ * `hub_strategy="checkpoint"`는 최신 체크포인트를 "last-checkpoint"라는 하위 폴더에 푸시하여 훈련을 재개할 수 있습니다.
107
+ * `hub_strategy="all_checkpoints"`는 모든 체크포인트를 `output_dir`에 정의된 디렉토리에 푸시합니다(모델 리포지토리에서 폴더당 하나의 체크포인트를 볼 수 있습니다).
108
+
109
+ 체크포인트에서 훈련을 재개할 때, [`Trainer`]는 체크포인트가 저장될 때와 동일한 Python, NumPy 및 PyTorch RNG 상태를 유지하려고 합니다. 하지만 PyTorch는 기본 설정으로 '일관된 결과를 보장하지 않음'으로 많이 되어있기 때문에, RNG 상태가 동일할 것이라고 보장할 수 없습니다. 따라서, 일관된 결과가 보장되도록 활성화 하려면, [랜덤성 제어](https://pytorch.org/docs/stable/notes/randomness#controlling-sources-of-randomness) 가이드를 참고하여 훈련을 완전히 일관된 결과를 보장 받도록 만들기 위해 활성화할 수 있는 항목을 확인하세요. 다만, 특정 설정을 결정적으로 만들면 훈련이 느려질 수 있습니다.
110
+
111
+ ## Trainer 맞춤 설정 [[customize-the-trainer]]
112
+
113
+ [`Trainer`] 클래스는 접근성과 용이성을 염두에 두고 설계되었지만, 더 다양한 기능을 원하는 사용자들을 위해 다양한 맞춤 설정 옵션을 제공합니다. [`Trainer`]의 많은 메소드는 서브클래스화 및 오버라이드하여 원하는 기능을 제공할 수 있으며, 이를 통해 전체 훈련 루프를 다시 작성할 필요 없이 원하는 기능을 추가할 수 있습니다. 이러한 메소드에는 다음이 포함됩니다:
114
+
115
+ * [`~Trainer.get_train_dataloader`]는 훈련 데이터로더를 생성합니다.
116
+ * [`~Trainer.get_eval_dataloader`]는 평가 데이터로더를 생성합니다.
117
+ * [`~Trainer.get_test_dataloader`]는 테스트 데이터로더를 생성합니다.
118
+ * [`~Trainer.log`]는 훈련을 모니터링하는 다양한 객체에 대한 정보를 로그로 남깁니다.
119
+ * [`~Trainer.create_optimizer_and_scheduler`]는 `__init__`에서 전달되지 않은 경우 옵티마이저와 학습률 스케줄러를 생성합니다. 이들은 각각 [`~Trainer.create_optimizer`] 및 [`~Trainer.create_scheduler`]로 별도로 맞춤 설정 할 수 있습니다.
120
+ * [`~Trainer.compute_loss`]는 훈련 입력 배치에 대한 손실을 계산합니다.
121
+ * [`~Trainer.training_step`]는 훈련 단계를 수행합니다.
122
+ * [`~Trainer.prediction_step`]는 예측 및 테스트 단계를 수행합니다.
123
+ * [`~Trainer.evaluate`]는 모델을 평가하고 평가 지표을 반환합니다.
124
+ * [`~Trainer.predict`]는 테스트 세트에 대한 예측(레이블이 있는 경우 지표 포함)을 수행합니다.
125
+
126
+ 예를 들어, [`~Trainer.compute_loss`] 메소드를 맞춤 설정하여 가중 손실을 사용하려는 경우:
127
+
128
+ ```py
129
+ from torch import nn
130
+ from transformers import Trainer
131
+
132
+ class CustomTrainer(Trainer):
133
+ def compute_loss(self,
134
+
135
+ model, inputs, return_outputs=False):
136
+ labels = inputs.pop("labels")
137
+ # 순방향 전파
138
+ outputs = model(**inputs)
139
+ logits = outputs.get("logits")
140
+ # 서로 다른 가중치로 3개의 레이블에 대한 사용자 정의 손실을 계산
141
+ loss_fct = nn.CrossEntropyLoss(weight=torch.tensor([1.0, 2.0, 3.0], device=model.device))
142
+ loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1))
143
+ return (loss, outputs) if return_outputs else loss
144
+ ```
145
+
146
+ ### 콜백 [[callbacks]]
147
+
148
+ [`Trainer`]를 맞춤 설정하는 또 다른 방법은 [콜백](callbacks)을 사용하는 것입니다. 콜백은 훈련 루프에서 *변화를 주지 않습니다*. 훈련 루프의 상태를 검사한 후 상태에 따라 일부 작업(조기 종료, 결과 로그 등)을 실행합니다. 즉, 콜백은 사용자 정의 손실 함수와 같은 것을 구현하는 데 사용할 수 없으며, 이를 위해서는 [`~Trainer.compute_loss`] 메소드를 서브클래스화하고 오버라이드해야 합니다.
149
+
150
+ 예를 들어, 훈련 루프에 10단계 후 조기 종료 콜백을 추가하려�� 다음과 같이 합니다.
151
+
152
+ ```py
153
+ from transformers import TrainerCallback
154
+
155
+ class EarlyStoppingCallback(TrainerCallback):
156
+ def __init__(self, num_steps=10):
157
+ self.num_steps = num_steps
158
+
159
+ def on_step_end(self, args, state, control, **kwargs):
160
+ if state.global_step >= self.num_steps:
161
+ return {"should_training_stop": True}
162
+ else:
163
+ return {}
164
+ ```
165
+
166
+ 그런 다음, 이를 [`Trainer`]의 `callback` 매개변수에 전달합니다.
167
+
168
+ ```py
169
+ from transformers import Trainer
170
+
171
+ trainer = Trainer(
172
+ model=model,
173
+ args=training_args,
174
+ train_dataset=dataset["train"],
175
+ eval_dataset=dataset["test"],
176
+ tokenizer=tokenizer,
177
+ data_collator=data_collator,
178
+ compute_metrics=compute_metrics,
179
+ callbacks=[EarlyStoppingCallback()],
180
+ )
181
+ ```
182
+
183
+ ## 로깅 [[logging]]
184
+
185
+ <Tip>
186
+
187
+ 로깅 API에 대한 자세한 내용은 [로깅](./main_classes/logging) API 레퍼런스를 확인하세요.
188
+
189
+ </Tip>
190
+
191
+ [`Trainer`]는 기본적으로 `logging.INFO`로 설정되어 있어 오류, 경고 및 기타 기본 정보를 보고합니다. 분산 환경에서는 [`Trainer`] 복제본이 `logging.WARNING`으로 설정되어 오류와 경고만 보고합니다. [`TrainingArguments`]의 [`log_level`](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.log_level) 및 [`log_level_replica`](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.log_level_replica) 매개변수로 로그 레벨을 변경할 수 있습니다.
192
+
193
+ 각 노드의 로그 레벨 설정을 구성하려면 [`log_on_each_node`](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments.log_on_each_node) 매개변수를 사용하여 각 노드에서 로그 레벨을 사용할지 아니면 주 노드에서만 사용할지 결정하세요.
194
+
195
+ <Tip>
196
+
197
+ [`Trainer`]는 [`Trainer.__init__`] 메소드에서 각 노드에 대해 로그 레벨을 별도로 설정하므로, 다른 Transformers 기능을 사용할 경우 [`Trainer`] 객체를 생성하기 전에 이를 미리 설정하는 것이 좋습니다.
198
+
199
+ </Tip>
200
+
201
+ 예를 들어, 메인 코드와 모듈을 각 노드에 따라 동일한 로그 레벨을 사용하도록 설정하려면 다음과 같이 합니다.
202
+
203
+ ```py
204
+ logger = logging.getLogger(__name__)
205
+
206
+ logging.basicConfig(
207
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
208
+ datefmt="%m/%d/%Y %H:%M:%S",
209
+ handlers=[logging.StreamHandler(sys.stdout)],
210
+ )
211
+
212
+ log_level = training_args.get_process_log_level()
213
+ logger.setLevel(log_level)
214
+ datasets.utils.logging.set_verbosity(log_level)
215
+ transformers.utils.logging.set_verbosity(log_level)
216
+
217
+ trainer = Trainer(...)
218
+ ```
219
+
220
+ 각 노드에서 기록될 내용을 구성하기 위해 `log_level`과 `log_level_replica`를 다양한 조합으로 사용해보세요.
221
+
222
+ <hfoptions id="logging">
223
+ <hfoption id="single node">
224
+
225
+ ```bash
226
+ my_app.py ... --log_level warning --log_level_replica error
227
+ ```
228
+
229
+ </hfoption>
230
+ <hfoption id="multi-node">
231
+
232
+ 멀티 노드 환경에서는 `log_on_each_node 0` 매개변수를 추가합니다.
233
+
234
+ ```bash
235
+ my_app.py ... --log_level warning --log_level_replica error --log_on_each_node 0
236
+
237
+ # 오류만 보고하도록 설정
238
+ my_app.py ... --log_level error --log_level_replica error --log_on_each_node 0
239
+ ```
240
+
241
+ </hfoption>
242
+ </hfoptions>
243
+
244
+ ## NEFTune [[neftune]]
245
+
246
+ [NEFTune](https://hf.co/papers/2310.05914)은 훈련 중 임베딩 벡터에 노이즈를 추가하여 성능을 향상시킬 수 있는 기술입니다. [`Trainer`]에서 이를 활성화하려면 [`TrainingArguments`]의 `neftune_noise_alpha` 매개변수를 설정하여 노이즈의 양을 조절합니다.
247
+
248
+ ```py
249
+ from transformers import TrainingArguments, Trainer
250
+
251
+ training_args = TrainingArguments(..., neftune_noise_alpha=0.1)
252
+ trainer = Trainer(..., args=training_args)
253
+ ```
254
+
255
+ NEFTune은 예상치 못한 동작을 피할 목적으로 처음 임베딩 레이어로 복원하기 위해 훈련 후 비활성화 됩니다.
256
+
257
+ ## GaLore [[galore]]
258
+
259
+ Gradient Low-Rank Projection (GaLore)은 전체 매개변수를 학습하면서도 LoRA와 같은 일반적인 저계수 적응 방법보다 더 메모리 효율적인 저계수 학습 전략입니다.
260
+
261
+ 먼저 GaLore 공식 리포지토리를 설치합니다:
262
+
263
+ ```bash
264
+ pip install galore-torch
265
+ ```
266
+
267
+ 그런 다음 `optim`에 `["galore_adamw", "galore_adafactor", "galore_adamw_8bit"]` 중 하나와 함께 `optim_target_modules`를 추가합니다. 이는 적용하려는 대상 모듈 이름에 해당하는 문자열, 정규 표현식 또는 전체 경로의 목록일 수 있습니다. 아래는 end-to-end 예제 스크립트입니다(필요한 경우 `pip install trl datasets`를 실행):
268
+
269
+ ```python
270
+ import datasets
271
+ from trl import SFTConfig, SFTTrainer
272
+
273
+ train_dataset = datasets.load_dataset('imdb', split='train')
274
+ args = SFTConfig(
275
+ output_dir="./test-galore",
276
+ max_steps=100,
277
+ optim="galore_adamw",
278
+ optim_target_modules=[r".*.attn.*", r".*.mlp.*"],
279
+ gradient_checkpointing=True,
280
+ )
281
+ trainer = SFTTrainer(
282
+ model="google/gemma-2b",
283
+ args=args,
284
+ train_dataset=train_dataset,
285
+ )
286
+ trainer.train()
287
+ ```
288
+
289
+ GaLore가 지원하는 추가 매개변수를 전달하려면 `optim_args`를 설정합니다. 예를 들어:
290
+
291
+ ```python
292
+ import datasets
293
+ from trl import SFTConfig, SFTTrainer
294
+
295
+ train_dataset = datasets.load_dataset('imdb', split='train')
296
+ args = SFTConfig(
297
+ output_dir="./test-galore",
298
+ max_steps=100,
299
+ optim="galore_adamw",
300
+ optim_target_modules=[r".*.attn.*", r".*.mlp.*"],
301
+ optim_args="rank=64, update_proj_gap=100, scale=0.10",
302
+ gradient_checkpointing=True,
303
+ )
304
+ trainer = SFTTrainer(
305
+ model="google/gemma-2b",
306
+ args=args,
307
+ train_dataset=train_dataset,
308
+ )
309
+ trainer.train()
310
+ ```
311
+
312
+ 해당 방법에 대한 자세한 내용은 [원본 리포지토리](https://github.com/jiaweizzhao/GaLore) 또는 [논문](https://huggingface.co/papers/2403.03507)을 참고하세요.
313
+
314
+ 현재 GaLore 레이어로 간주되는 Linear 레이어만 훈련 할수 있으며, 저계수 분해를 사용하여 훈련되고 나머지 레이어는 기존 방식으로 최적화됩니다.
315
+
316
+ 훈련 시작 전에 시간이 약간 걸릴 수 있습니다(NVIDIA A100에서 2B 모델의 경우 약 3분), 하지만 이후 훈련은 원활하게 진행됩니다.
317
+
318
+ 다음과 같이 옵티마이저 이름에 `layerwise`를 추가하여 레이어별 최적화를 수행할 수도 있습니다:
319
+
320
+ ```python
321
+ import datasets
322
+ from trl import SFTConfig, SFTTrainer
323
+
324
+ train_dataset = datasets.load_dataset('imdb', split='train')
325
+ args = SFTConfig(
326
+ output_dir="./test-galore",
327
+ max_steps=100,
328
+ optim="galore_adamw_layerwise",
329
+ optim_target_modules=[r".*.attn.*", r".*.mlp.*"],
330
+ gradient_checkpointing=True,
331
+ )
332
+ trainer = SFTTrainer(
333
+ model="google/gemma-2b",
334
+ args=args,
335
+ train_dataset=train_dataset,
336
+ )
337
+ trainer.train()
338
+ ```
339
+
340
+ 레이어별 최적화는 다소 실험적이며 DDP(분산 데이터 병렬)를 지원하지 않으므로, 단일 GPU에서만 훈련 스크립트를 실행할 수 있습니다. 자세한 내용은 [이 문서를](https://github.com/jiaweizzhao/GaLore?tab=readme-ov-file#train-7b-model-with-a-single-gpu-with-24gb-memory)을 참조하세요. gradient clipping, DeepSpeed 등 다른 기능은 기본적으로 지원되지 않을 수 있습니다. 이러한 문제가 발생하면 [GitHub에 이슈를 올려주세요](https://github.com/huggingface/transformers/issues).
341
+
342
+ ## LOMO 옵티마이저 [[lomo-optimizer]]
343
+
344
+ LOMO 옵티마이저는 [제한된 자원으로 대형 언어 모델의 전체 매개변수 미세 조정](https://hf.co/papers/2306.09782)과 [적응형 학습률을 통한 저메모리 최적화(AdaLomo)](https://hf.co/papers/2310.10195)에서 도입되었습니다.
345
+ 이들은 모두 효율적인 전체 매개변수 미세 조정 방법으로 구성되어 있습니다. 이러한 옵티마이저들은 메모리 사용량을 줄이기 위해 그레이디언트 계산과 매개변수 업데이트를 하나의 단계로 융합합니다. LOMO에서 지원되는 옵티마이저는 `"lomo"`와 `"adalomo"`입니다. 먼저 pypi에서 `pip install lomo-optim`를 통해 `lomo`를 설치하거나, GitHub 소스에서 `pip install git+https://github.com/OpenLMLab/LOMO.git`로 설치하세요.
346
+
347
+ <Tip>
348
+
349
+ 저자에 따르면, `grad_norm` 없이 `AdaLomo`를 사용하는 것이 더 나은 성능과 높은 처리량을 제공한다고 합니다.
350
+
351
+ </Tip>
352
+
353
+ 다음은 IMDB 데이터셋에서 [google/gemma-2b](https://huggingface.co/google/gemma-2b)를 최대 정밀도로 미세 조정하는 간단한 스크립트입니다:
354
+
355
+ ```python
356
+ import datasets
357
+ from trl import SFTConfig, SFTTrainer
358
+
359
+ train_dataset = datasets.load_dataset('imdb', split='train')
360
+ args = SFTConfig(
361
+ output_dir="./test-lomo",
362
+ max_steps=100,
363
+ optim="adalomo",
364
+ gradient_checkpointing=True,
365
+ )
366
+ trainer = SFTTrainer(
367
+ model="google/gemma-2b",
368
+ args=args,
369
+ train_dataset=train_dataset,
370
+ )
371
+ trainer.train()
372
+ ```
373
+
374
+ ## Accelerate와 Trainer [[accelerate-and-trainer]]
375
+
376
+ [`Trainer`] 클래스는 [Accelerate](https://hf.co/docs/accelerate)로 구동되며, 이는 [FullyShardedDataParallel (FSDP)](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/) 및 [DeepSpeed](https://www.deepspeed.ai/)와 같은 통합을 지원하는 분산 환경에서 PyTorch 모델을 쉽게 훈련할 수 있는 라이브러리입니다.
377
+
378
+ <Tip>
379
+
380
+ FSDP 샤딩 전략, CPU 오프로드 및 [`Trainer`]와 함께 사용할 수 있는 더 많은 기능을 알아보려면 [Fully Sharded Data Parallel](fsdp) 가이드를 확인하세요.
381
+
382
+ </Tip>
383
+
384
+ [`Trainer`]와 Accelerate를 사용하려면 [`accelerate.config`](https://huggingface.co/docs/accelerate/package_reference/cli#accelerate-config) 명령을 실행하여 훈련 환경을 설정하세요. 이 명령은 훈련 스크립트를 실행할 때 사용할 `config_file.yaml`을 생성합니다. 예를 들어, 다음 예시는 설정할 수 있는 일부 구성 예입니다.
385
+
386
+ <hfoptions id="config">
387
+ <hfoption id="DistributedDataParallel">
388
+
389
+ ```yml
390
+ compute_environment: LOCAL_MACHINE
391
+ distributed_type: MULTI_GPU
392
+ downcast_bf16: 'no'
393
+ gpu_ids: all
394
+ machine_rank: 0 # 노드에 따라 순위를 변경하세요
395
+ main_process_ip: 192.168.20.1
396
+ main_process_port: 9898
397
+ main_training_function: main
398
+ mixed_precision: fp16
399
+ num_machines: 2
400
+ num_processes: 8
401
+ rdzv_backend: static
402
+ same_network: true
403
+ tpu_env: []
404
+ tpu_use_cluster: false
405
+ tpu_use_sudo: false
406
+ use_cpu: false
407
+ ```
408
+
409
+ </hfoption>
410
+ <hfoption id="FSDP">
411
+
412
+ ```yml
413
+ compute_environment: LOCAL_MACHINE
414
+ distributed_type: FSDP
415
+ downcast_bf16: 'no'
416
+ fsdp_config:
417
+ fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
418
+ fsdp_backward_prefetch_policy: BACKWARD_PRE
419
+ fsdp_forward_prefetch: true
420
+ fsdp_offload_params: false
421
+ fsdp_sharding_strategy: 1
422
+ fsdp_state_dict_type: FULL_STATE_DICT
423
+ fsdp_sync_module_states: true
424
+ fsdp_transformer_layer_cls_to_wrap: BertLayer
425
+ fsdp_use_orig_params: true
426
+ machine_rank: 0
427
+ main_training_function: main
428
+ mixed_precision: bf16
429
+ num_machines: 1
430
+ num_processes: 2
431
+ rdzv_backend: static
432
+ same_network: true
433
+ tpu_env: []
434
+ tpu_use_cluster: false
435
+ tpu_use_sudo: false
436
+ use_cpu: false
437
+ ```
438
+
439
+ </hfoption>
440
+ <hfoption id="DeepSpeed">
441
+
442
+ ```yml
443
+ compute_environment: LOCAL_MACHINE
444
+ deepspeed_config:
445
+ deepspeed_config_file: /home/user/configs/ds_zero3_config.json
446
+ zero3_init_flag: true
447
+ distributed_type: DEEPSPEED
448
+ downcast_bf16: 'no'
449
+ machine_rank: 0
450
+ main_training_function: main
451
+ num_machines: 1
452
+ num_processes: 4
453
+ rdzv_backend: static
454
+ same_network: true
455
+ tpu_env: []
456
+ tpu_use_cluster: false
457
+ tpu_use_sudo: false
458
+ use_cpu: false
459
+ ```
460
+
461
+ </hfoption>
462
+ <hfoption id="DeepSpeed with Accelerate plugin">
463
+
464
+ ```yml
465
+ compute_environment: LOCAL_MACHINE
466
+ deepspeed_config:
467
+ gradient_accumulation_steps: 1
468
+ gradient_clipping: 0.7
469
+ offload_optimizer_device: cpu
470
+ offload_param_device: cpu
471
+ zero3_init_flag: true
472
+ zero_stage: 2
473
+ distributed_type: DEEPSPEED
474
+ downcast_bf16: 'no'
475
+ machine_rank: 0
476
+ main_training_function: main
477
+ mixed_precision: bf16
478
+ num_machines: 1
479
+ num_processes: 4
480
+ rdzv_backend: static
481
+ same_network: true
482
+ tpu_env: []
483
+ tpu_use_cluster: false
484
+ tpu_use_sudo: false
485
+ use_cpu: false
486
+ ```
487
+
488
+ </hfoption>
489
+
490
+ </hfoptions>
491
+
492
+ [`accelerate_launch`](https://huggingface.co/docs/accelerate/package_reference/cli#accelerate-launch) 명령은 Accelerate와 [`Trainer`]를 사용하여 분산 시스템에서 훈련 스크립트를 실행하는 권장 방법이며, `config_file.yaml`에 지정된 매개변수를 사용합니다. 이 파일은 Accelerate 캐시 폴더에 저장되며 `accelerate_launch`를 실행할 때 자동으로 로드됩니다.
493
+
494
+ 예를 들어, FSDP 구성을 사용하여 [run_glue.py](https://github.com/huggingface/transformers/blob/f4db565b695582891e43a5e042e5d318e28f20b8/examples/pytorch/text-classification/run_glue.py#L4) 훈련 스크립트를 실행하려면 다음과 같이 합니다:
495
+
496
+ ```bash
497
+ accelerate launch \
498
+ ./examples/pytorch/text-classification/run_glue.py \
499
+ --model_name_or_path google-bert/bert-base-cased \
500
+ --task_name $TASK_NAME \
501
+ --do_train \
502
+ --do_eval \
503
+ --max_seq_length 128 \
504
+ --per_device_train_batch_size 16 \
505
+ --learning_rate 5e-5 \
506
+ --num_train_epochs 3 \
507
+ --output_dir /tmp/$TASK_NAME/ \
508
+ --overwrite_output_dir
509
+ ```
510
+
511
+ `config_file.yaml` 파일의 매개변수를 직접 지정할 수도 있습니다:
512
+
513
+ ```bash
514
+ accelerate launch --num_processes=2 \
515
+ --use_fsdp \
516
+ --mixed_precision=bf16 \
517
+ --fsdp_auto_wrap_policy=TRANSFORMER_BASED_WRAP \
518
+ --fsdp_transformer_layer_cls_to_wrap="BertLayer" \
519
+ --fsdp_sharding_strategy=1 \
520
+ --fsdp_state_dict_type=FULL_STATE_DICT \
521
+ ./examples/pytorch/text-classification/run_glue.py \
522
+ --model_name_or_path google-bert/bert-base-cased \
523
+ --task_name $TASK_NAME \
524
+ --do_train \
525
+ --do_eval \
526
+ --max_seq_length 128 \
527
+ --per_device_train_batch_size 16 \
528
+ --learning_rate 5e-5 \
529
+ --num_train_epochs 3 \
530
+ --output_dir /tmp/$TASK_NAME/ \
531
+ --overwrite_output_dir
532
+ ```
533
+
534
+ `accelerate_launch`와 사용자 정의 구성에 대해 더 알아보려면 [Accelerate 스크립트 실행](https://huggingface.co/docs/accelerate/basic_tutorials/launch) 튜토리얼을 확인하세요.
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/training.md ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # 사전 학습된 모델 미세 튜닝하기[[finetune-a-pretrained-model]]
18
+
19
+ [[open-in-colab]]
20
+
21
+ 사전 학습된 모델을 사용하면 상당한 이점이 있습니다. 계산 비용과 탄소발자국을 줄이고, 처음부터 모델을 학습시킬 필요 없이 최신 모델을 사용할 수 있습니다. 🤗 Transformers는 다양한 작업을 위해 사전 학습된 수천 개의 모델에 액세스할 수 있습니다. 사전 학습된 모델을 사용하는 경우, 자신의 작업과 관련된 데이터셋을 사용해 학습합니다. 이것은 미세 튜닝이라고 하는 매우 강력한 훈련 기법입니다. 이 튜토리얼에서는 당신이 선택한 딥러닝 프레임워크로 사전 학습된 모델을 미세 튜닝합니다:
22
+
23
+ * 🤗 Transformers로 사전 학습된 모델 미세 튜닝하기 [`Trainer`].
24
+ * Keras를 사용하여 TensorFlow에서 사전 학습된 모델을 미세 튜닝하기.
25
+ * 기본 PyTorch에서 사전 학습된 모델을 미세 튜닝하기.
26
+
27
+ <a id='data-processing'></a>
28
+
29
+ ## 데이터셋 준비[[prepare-a-dataset]]
30
+
31
+ <Youtube id="_BZearw7f0w"/>
32
+
33
+ 사전 학습된 모델을 미세 튜닝하기 위해서 데이터셋을 다운로드하고 훈련할 수 있도록 준비하세요. 이전 튜토리얼에서 훈련을 위해 데이터를 처리하는 방법을 보여드렸는데, 지금이 배울 걸 되짚을 기회입니다!
34
+
35
+ 먼저 [Yelp 리뷰](https://huggingface.co/datasets/yelp_review_full) 데이터 세트를 로드합니다:
36
+
37
+ ```py
38
+ >>> from datasets import load_dataset
39
+
40
+ >>> dataset = load_dataset("yelp_review_full")
41
+ >>> dataset["train"][100]
42
+ {'label': 0,
43
+ 'text': 'My expectations for McDonalds are t rarely high. But for one to still fail so spectacularly...that takes something special!\\nThe cashier took my friends\'s order, then promptly ignored me. I had to force myself in front of a cashier who opened his register to wait on the person BEHIND me. I waited over five minutes for a gigantic order that included precisely one kid\'s meal. After watching two people who ordered after me be handed their food, I asked where mine was. The manager started yelling at the cashiers for \\"serving off their orders\\" when they didn\'t have their food. But neither cashier was anywhere near those controls, and the manager was the one serving food to customers and clearing the boards.\\nThe manager was rude when giving me my order. She didn\'t make sure that I had everything ON MY RECEIPT, and never even had the decency to apologize that I felt I was getting poor service.\\nI\'ve eaten at various McDonalds restaurants for over 30 years. I\'ve worked at more than one location. I expect bad days, bad moods, and the occasional mistake. But I have yet to have a decent experience at this store. It will remain a place I avoid unless someone in my party needs to avoid illness from low blood sugar. Perhaps I should go back to the racially biased service of Steak n Shake instead!'}
44
+ ```
45
+
46
+ 텍스트를 처리하고 서로 다른 길이의 시퀀스 패딩 및 잘라내기 전략을 포함하려면 토크나이저가 필요합니다. 데이터셋을 한 번에 처리하려면 🤗 Dataset [`map`](https://huggingface.co/docs/datasets/process#map) 메서드를 사용하여 전체 데이터셋에 전처리 함수를 적용하세요:
47
+
48
+ ```py
49
+ >>> from transformers import AutoTokenizer
50
+
51
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
52
+
53
+
54
+ >>> def tokenize_function(examples):
55
+ ... return tokenizer(examples["text"], padding="max_length", truncation=True)
56
+
57
+
58
+ >>> tokenized_datasets = dataset.map(tokenize_function, batched=True)
59
+ ```
60
+
61
+ 필요한 경우 미세 튜닝을 위해 데이터셋의 작은 부분 집합을 만들어 미세 튜닝 작업 시간을 줄일 수 있습니다:
62
+
63
+ ```py
64
+ >>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
65
+ >>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
66
+ ```
67
+
68
+ <a id='trainer'></a>
69
+
70
+ ## Train
71
+
72
+ 여기서부터는 사용하려는 프레임워크에 해당하는 섹션을 따라야 합니다. 오른쪽 사이드바의 링크를 사용하여 원하는 프레임워크로 이동할 수 있으며, 특정 프레임워크의 모든 콘텐츠를 숨기려면 해당 ���레임워크 블록의 오른쪽 상단에 있는 버튼을 사용하면 됩니다!
73
+
74
+ <frameworkcontent>
75
+ <pt>
76
+ <Youtube id="nvBXf7s7vTI"/>
77
+
78
+ ## 파이토치 Trainer로 훈련하기[[train-with-pytorch-trainer]]
79
+
80
+ 🤗 Transformers는 🤗 Transformers 모델 훈련에 최적화된 [`Trainer`] 클래스를 제공하여 훈련 루프를 직접 작성하지 않고도 쉽게 훈련을 시작할 수 있습니다. [`Trainer`] API는 로깅(logging), 경사 누적(gradient accumulation), 혼합 정밀도(mixed precision) 등 다양한 훈련 옵션과 기능을 지원합니다.
81
+
82
+ 먼저 모델을 가져오고 예상되는 레이블 수를 지정합니다. Yelp 리뷰 [데이터셋 카드](https://huggingface.co/datasets/yelp_review_full#data-fields)에서 5개의 레이블이 있음을 알 수 있습니다:
83
+
84
+ ```py
85
+ >>> from transformers import AutoModelForSequenceClassification
86
+
87
+ >>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased", num_labels=5)
88
+ ```
89
+
90
+ <Tip>
91
+
92
+ 사전 훈련된 가중치 중 일부가 사용되지 않고 일부 가중치가 무작위로 표시된다는 경고가 표시됩니다.
93
+ 걱정마세요. 이것은 올바른 동작입니다! 사전 학습된 BERT 모델의 헤드는 폐기되고 무작위로 초기화된 분류 헤드로 대체됩니다. 이제 사전 학습된 모델의 지식으로 시퀀스 분류 작업을 위한 새로운 모델 헤드를 미세 튜닝 합니다.
94
+
95
+ </Tip>
96
+
97
+ ### 하이퍼파라미터 훈련[[training-hyperparameters]]
98
+
99
+ 다음으로 정할 수 있는 모든 하이퍼파라미터와 다양한 훈련 옵션을 활성화하기 위한 플래그를 포함하는 [`TrainingArguments`] 클래스를 생성합니다.
100
+
101
+ 이 튜토리얼에서는 기본 훈련 [하이퍼파라미터](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments)로 시작하지만, 자유롭게 실험하여 여러분들에게 맞는 최적의 설정을 찾을 수 있습니다.
102
+
103
+ 훈련에서 체크포인트(checkpoints)를 저장할 위치를 지정합니다:
104
+
105
+ ```py
106
+ >>> from transformers import TrainingArguments
107
+
108
+ >>> training_args = TrainingArguments(output_dir="test_trainer")
109
+ ```
110
+
111
+ ### 평가 하기[[evaluate]]
112
+
113
+ [`Trainer`]는 훈련 중에 모델 성능을 자동으로 평가하지 않습니다. 평가 지표를 계산하고 보고할 함수를 [`Trainer`]에 전달해야 합니다.
114
+ [🤗 Evaluate](https://huggingface.co/docs/evaluate/index) 라이브러리는 [`evaluate.load`](https://huggingface.co/spaces/evaluate-metric/accuracy) 함수로 로드할 수 있는 간단한 [`accuracy`]함수를 제공합니다 (자세한 내용은 [둘러보기](https://huggingface.co/docs/evaluate/a_quick_tour)를 참조하세요):
115
+
116
+ ```py
117
+ >>> import numpy as np
118
+ >>> import evaluate
119
+
120
+ >>> metric = evaluate.load("accuracy")
121
+ ```
122
+
123
+ `metric`에서 [`~evaluate.compute`]를 호출하여 예측의 정확도를 계산합니다. 예측을 `compute`에 전달하기 전에 예측을 로짓으로 변환해야 합니다(모든 🤗 Transformers 모델은 로짓으로 반환한다는 점을 기억하세요):
124
+
125
+ ```py
126
+ >>> def compute_metrics(eval_pred):
127
+ ... logits, labels = eval_pred
128
+ ... predictions = np.argmax(logits, axis=-1)
129
+ ... return metric.compute(predictions=predictions, references=labels)
130
+ ```
131
+
132
+ 미세 튜닝 중에 평가 지표를 모니터링하려면 훈련 인수에 `eval_strategy` 파라미터를 지정하여 각 에폭이 끝날 때 평가 지표를 확인할 수 있습니다:
133
+
134
+ ```py
135
+ >>> from transformers import TrainingArguments, Trainer
136
+
137
+ >>> training_args = TrainingArguments(output_dir="test_trainer", eval_strategy="epoch")
138
+ ```
139
+
140
+ ### 훈련 하기[[trainer]]
141
+
142
+ 모델, 훈련 인수, 훈련 및 테스트 데이터셋, 평가 함수가 포함된 [`Trainer`] 객체를 만듭니다:
143
+
144
+ ```py
145
+ >>> trainer = Trainer(
146
+ ... model=model,
147
+ ... args=training_args,
148
+ ... train_dataset=small_train_dataset,
149
+ ... eval_dataset=small_eval_dataset,
150
+ ... compute_metrics=compute_metrics,
151
+ ... )
152
+ ```
153
+
154
+ 그리고 [`~transformers.Trainer.train`]을 호출하여 모델을 미세 튜닝합니다:
155
+
156
+ ```py
157
+ >>> trainer.train()
158
+ ```
159
+ </pt>
160
+ <tf>
161
+ <a id='keras'></a>
162
+
163
+ <Youtube id="rnTGBy2ax1c"/>
164
+
165
+ ## Keras로 텐서플로우 모델 훈련하기[[train-a-tensorflow-model-with-keras]]
166
+
167
+ Keras API를 사용하여 텐서플로우에서 🤗 Transformers 모델을 훈련할 수도 있습니다!
168
+
169
+ ### Keras용 데이터 로드[[loading-data-for-keras]]
170
+
171
+ Keras API로 🤗 Transformers 모델을 학습시키려면 데이터셋을 Keras가 이해할 수 있는 형식으로 변환해야 합니다.
172
+ 데이터 세트가 작은 경우, 전체를 NumPy 배열로 변환하여 Keras로 전달하면 됩니다.
173
+ 더 복잡한 작업을 수행하기 전에 먼저 이 작업을 시도해 보겠습니다.
174
+
175
+ 먼저 데이터 세트를 로드합니다. [GLUE 벤치마크](https://huggingface.co/datasets/glue)의 CoLA 데이터 세트를 사용하겠습니다.
176
+ 간단한 바이너리 텍스트 분류 작업이므로 지금�� 훈련 데이터 분할만 사용합니다.
177
+
178
+ ```py
179
+ from datasets import load_dataset
180
+
181
+ dataset = load_dataset("glue", "cola")
182
+ dataset = dataset["train"] # Just take the training split for now
183
+ ```
184
+
185
+ 다음으로 토크나이저를 로드하고 데이터를 NumPy 배열로 토큰화합니다. 레이블은 이미 0과 1로 된 리스트이기 때문에 토큰화하지 않고 바로 NumPy 배열로 변환할 수 있습니다!
186
+
187
+ ```py
188
+ from transformers import AutoTokenizer
189
+
190
+ tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
191
+ tokenized_data = tokenizer(dataset["sentence"], return_tensors="np", padding=True)
192
+ # Tokenizer returns a BatchEncoding, but we convert that to a dict for Keras
193
+ tokenized_data = dict(tokenized_data)
194
+
195
+ labels = np.array(dataset["label"]) # Label is already an array of 0 and 1
196
+ ```
197
+
198
+ 마지막으로 모델을 로드, [`compile`](https://keras.io/api/models/model_training_apis/#compile-method), [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)합니다:
199
+
200
+ ```py
201
+ from transformers import TFAutoModelForSequenceClassification
202
+ from tensorflow.keras.optimizers import Adam
203
+
204
+ # Load and compile our model
205
+ model = TFAutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased")
206
+ # Lower learning rates are often better for fine-tuning transformers
207
+ model.compile(optimizer=Adam(3e-5))
208
+
209
+ model.fit(tokenized_data, labels)
210
+ ```
211
+
212
+ <Tip>
213
+
214
+ 모델을 `compile()`할 때 손실 인수를 모델에 전달할 필요가 없습니다!
215
+ 이 인수를 비워두면 허깅 페이스 모델은 작업과 모델 아키텍처에 적합한 손실을 자동으로 선택합니다.
216
+ 원한다면 언제든지 직접 손실을 지정하여 이를 재정의할 수 있습니다!
217
+
218
+ </Tip>
219
+
220
+ 이 접근 방식은 소규모 데이터 집합에서는 잘 작동하지만, 대규모 데이터 집합에서는 문제가 될 수 있습니다. 왜 그럴까요?
221
+ 토큰화된 배열과 레이블을 메모리에 완전히 로드하고 NumPy는 "들쭉날쭉한" 배열을 처리하지 않기 때문에,
222
+ 모든 토큰화된 샘플을 전체 데이터셋에서 가장 긴 샘플의 길이만큼 패딩해야 합니다. 이렇게 하면 배열이 훨씬 더 커지고 이 패딩 토큰으로 인해 학습 속도도 느려집니다!
223
+
224
+ ### 데이터를 tf.data.Dataset으로 로드하기[[loading-data-as-a-tfdatadataset]]
225
+
226
+ 학습 속도가 느려지는 것을 피하려면 데이터를 `tf.data.Dataset`으로 로드할 수 있습니다. 원한다면 직접
227
+ `tf.data` 파이프라인을 직접 작성할 수도 있지만, 이 작업을 간편하게 수행하는 수 있는 두 가지 방법이 있습니다:
228
+
229
+ - [`~TFPreTrainedModel.prepare_tf_dataset`]: 대부분의 경우 이 방법을 권장합니다. 모델의 메서드이기 때문에 모델을 검사하여 모델 입력으로 사용할 수 있는 열을 자동으로 파악하고
230
+ 나머지는 버려서 더 단순하고 성능이 좋은 데이터 집합을 만들 수 있습니다.
231
+ - [`~datasets.Dataset.to_tf_dataset`]: 이 방법은 좀 더 낮은 수준이며, 포함할 '열'과 '레이블'을 정확히 지정하여
232
+ 데이터셋을 생성하는 방법을 정확히 제어하고 싶을 때 유용하며, 포함할 'columns'과 'label_cols'을 정확히 지정할 수 있습니다.
233
+
234
+ [`~TFPreTrainedModel.prepare_tf_dataset`]을 사용하려면 먼저 다음 코드 샘플과 같이 토크나이저 출력을 데이터 세트에 열로 추가해야 합니다:
235
+
236
+ ```py
237
+ def tokenize_dataset(data):
238
+ # Keys of the returned dictionary will be added to the dataset as columns
239
+ return tokenizer(data["text"])
240
+
241
+
242
+ dataset = dataset.map(tokenize_dataset)
243
+ ```
244
+
245
+ 허깅 페이스 데이터셋은 기본적으로 디스크에 저장되므로 메모리 사용량을 늘리지 않는다는 점을 기억하세요!
246
+ 열이 추가되면 데이터셋에서 배치를 스트리밍하고 각 배치에 패딩을 추가할 수 있으므로 전체 데이터셋에 패딩을 추가하는 것보다 패딩 토큰의 수를 크게 줄일 수 있습니다.
247
+
248
+
249
+ ```py
250
+ >>> tf_dataset = model.prepare_tf_dataset(dataset, batch_size=16, shuffle=True, tokenizer=tokenizer)
251
+ ```
252
+
253
+ 위의 코드 샘플에서는 배치가 로드될 때 올바르게 패딩할 수 있도록 `prepare_tf_dataset`에 토크나이저를 전달해야 합니다.
254
+ 데이터셋의 모든 샘플 길이가 같고 패딩이 필요하지 않은 경우 이 인수를 건너뛸 수 있습니다.
255
+ 샘플을 채우는 것보다 더 복잡한 작업(예: 마스킹된 언어의 토큰 손상 모델링)을 수행하기 위해 토큰을 손상시켜야 하는 경우,
256
+ `collate_fn` 인수를 사용하여 샘플 목록을 배치로 변환하고 원하는 전처리를 적용할 함수를 전달할 수 있습니다.
257
+ [예시](https://github.com/huggingface/transformers/tree/main/examples) 또는
258
+ [노트북](https://huggingface.co/docs/transformers/notebooks)을 참조하여 이 접근 방식이 실제로 작동하는 모습을 확인하세요.
259
+
260
+ `tf.data.Dataset`을 생성한 후에는 이전과 마찬���지로 모델을 컴파일하고 훈련(fit)할 수 있습니다:
261
+
262
+ ```py
263
+ model.compile(optimizer=Adam(3e-5))
264
+
265
+ model.fit(tf_dataset)
266
+ ```
267
+
268
+ </tf>
269
+ </frameworkcontent>
270
+
271
+ <a id='pytorch_native'></a>
272
+
273
+ ## 기본 파이토치로 훈련하기[[train-in-native-pytorch]]
274
+
275
+ <frameworkcontent>
276
+ <pt>
277
+ <Youtube id="Dh9CL8fyG80"/>
278
+
279
+ [`Trainer`]는 훈련 루프를 처리하며 한 줄의 코드로 모델을 미세 조정할 수 있습니다. 직접 훈련 루프를 작성하는 것을 선호하는 사용자의 경우, 기본 PyTorch에서 🤗 Transformers 모델을 미세 조정할 수도 있습니다.
280
+
281
+ 이 시점에서 노트북을 다시 시작하거나 다음 코드를 실행해 메모리를 확보해야 할 수 있습니다:
282
+
283
+ ```py
284
+ del model
285
+ del trainer
286
+ torch.cuda.empty_cache()
287
+ ```
288
+
289
+ 다음으로, '토큰화된 데이터셋'을 수동으로 후처리하여 훈련련에 사용할 수 있도록 준비합니다.
290
+
291
+ 1. 모델이 원시 텍스트를 입력으로 허용하지 않으므로 `text` 열을 제거합니다:
292
+
293
+ ```py
294
+ >>> tokenized_datasets = tokenized_datasets.remove_columns(["text"])
295
+ ```
296
+
297
+ 2. 모델에서 인수의 이름이 `labels`로 지정될 것으로 예상하므로 `label` 열의 이름을 `labels`로 변경합니다:
298
+
299
+ ```py
300
+ >>> tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
301
+ ```
302
+
303
+ 3. 데이터셋의 형식을 List 대신 PyTorch 텐서를 반환하도록 설정합니다:
304
+
305
+ ```py
306
+ >>> tokenized_datasets.set_format("torch")
307
+ ```
308
+
309
+ 그리고 앞서 표시된 대로 데이터셋의 더 작은 하위 집합을 생성하여 미세 조정 속도를 높입니다:
310
+
311
+ ```py
312
+ >>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
313
+ >>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
314
+ ```
315
+
316
+ ### DataLoader[[dataloader]]
317
+
318
+ 훈련 및 테스트 데이터셋에 대한 'DataLoader'를 생성하여 데이터 배치를 반복할 수 있습니다:
319
+
320
+ ```py
321
+ >>> from torch.utils.data import DataLoader
322
+
323
+ >>> train_dataloader = DataLoader(small_train_dataset, shuffle=True, batch_size=8)
324
+ >>> eval_dataloader = DataLoader(small_eval_dataset, batch_size=8)
325
+ ```
326
+
327
+ 예측을 위한 레이블 개수를 사용하여 모델을 로드합니다:
328
+
329
+ ```py
330
+ >>> from transformers import AutoModelForSequenceClassification
331
+
332
+ >>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased", num_labels=5)
333
+ ```
334
+
335
+ ### 옵티마이저 및 학습 속도 스케줄러[[optimizer-and-learning-rate-scheduler]]
336
+
337
+ 옵티마이저와 학습 속도 스케줄러를 생성하여 모델을 미세 조정합니다. 파이토치에서 제공하는 [`AdamW`](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html) 옵티마이저를 사용해 보겠습니다:
338
+
339
+ ```py
340
+ >>> from torch.optim import AdamW
341
+
342
+ >>> optimizer = AdamW(model.parameters(), lr=5e-5)
343
+ ```
344
+
345
+ [`Trainer`]에서 기본 학습 속도 스케줄러를 생성합니다:
346
+
347
+ ```py
348
+ >>> from transformers import get_scheduler
349
+
350
+ >>> num_epochs = 3
351
+ >>> num_training_steps = num_epochs * len(train_dataloader)
352
+ >>> lr_scheduler = get_scheduler(
353
+ ... name="linear", optimizer=optimizer, num_warmup_steps=0, num_training_steps=num_training_steps
354
+ ... )
355
+ ```
356
+
357
+ 마지막으로, GPU에 액세스할 수 있는 경우 'device'를 지정하여 GPU를 사용하도록 합니다. 그렇지 않으면 CPU에서 훈련하며 몇 분이 아닌 몇 시간이 걸릴 수 있습니다.
358
+
359
+ ```py
360
+ >>> import torch
361
+
362
+ >>> device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
363
+ >>> model.to(device)
364
+ ```
365
+
366
+ <Tip>
367
+
368
+ [Colaboratory](https://colab.research.google.com/) 또는 [SageMaker StudioLab](https://studiolab.sagemaker.aws/)과 같은 호스팅 노트북이 없는 경우 클라우드 GPU에 무료로 액세스할 수 있습니다.
369
+
370
+ </Tip>
371
+
372
+ 이제 훈련할 준비가 되었습니다! 🥳
373
+
374
+ ### 훈련 루프[[training-loop]]
375
+
376
+ 훈련 진행 상황을 추적하려면 [tqdm](https://tqdm.github.io/) 라이브러리를 사용하여 트레이닝 단계 수에 진행률 표시줄을 추가하세요:
377
+
378
+ ```py
379
+ >>> from tqdm.auto import tqdm
380
+
381
+ >>> progress_bar = tqdm(range(num_training_steps))
382
+
383
+ >>> model.train()
384
+ >>> for epoch in range(num_epochs):
385
+ ... for batch in train_dataloader:
386
+ ... batch = {k: v.to(device) for k, v in batch.items()}
387
+ ... outputs = model(**batch)
388
+ ... loss = outputs.loss
389
+ ... loss.backward()
390
+
391
+ ... optimizer.step()
392
+ ... lr_scheduler.step()
393
+ ... optimizer.zero_grad()
394
+ ... progress_bar.update(1)
395
+ ```
396
+
397
+ ### 평가 하기[[evaluate]]
398
+
399
+ [`Trainer`]에 평가 함수를 추가한 방법과 마찬가지로, 훈련 루프를 직접 작성할 때도 동일한 작업을 수행해야 합니다. 하지만 이번에는 각 에포크가 끝날 때마다 평가지표를 계산하여 보고하는 대신, [`~evaluate.add_batch`]를 사용하여 모든 배치를 누적하고 맨 마지막에 평가지표를 계산합니다.
400
+
401
+ ```py
402
+ >>> import evaluate
403
+
404
+ >>> metric = evaluate.load("accuracy")
405
+ >>> model.eval()
406
+ >>> for batch in eval_dataloader:
407
+ ... batch = {k: v.to(device) for k, v in batch.items()}
408
+ ... with torch.no_grad():
409
+ ... outputs = model(**batch)
410
+
411
+ ... logits = outputs.logits
412
+ ... predictions = torch.argmax(logits, dim=-1)
413
+ ... metric.add_batch(predictions=predictions, references=batch["labels"])
414
+
415
+ >>> metric.compute()
416
+ ```
417
+ </pt>
418
+ </frameworkcontent>
419
+
420
+ <a id='additional-resources'></a>
421
+
422
+ ## 추가 자료[[additional-resources]]
423
+
424
+ 더 많은 미세 튜닝 예제는 다음을 참조하세요:
425
+
426
+ - [🤗 Trnasformers 예제](https://github.com/huggingface/transformers/tree/main/examples)에는 PyTorch 및 텐서플로우에서 일반적인 NLP 작업을 훈련할 수 있는 스크립트가 포함되어 있습니다.
427
+
428
+ - [🤗 Transformers 노트북](notebooks)에는 PyTorch 및 텐서플로우에서 특정 작업을 위해 모델을 미세 튜닝하는 방법에 대한 다양한 노트북이 포함되어 있습니다.
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ko/troubleshooting.md ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2022 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+
16
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
17
+ rendered properly in your Markdown viewer.
18
+
19
+ -->
20
+
21
+ # 문제 해결[[troubleshoot]]
22
+
23
+ 때때로 오류가 발생할 수 있지만, 저희가 도와드리겠습니다! 이 가이드는 현재까지 확인된 가장 일반적인 문제 몇 가지와 그것들을 해결하는 방법에 대해 다룹니다. 그러나 이 가이드는 모든 🤗 Transformers 문제를 포괄적으로 다루고 있지 않습니다. 문제 해결에 더 많은 도움을 받으려면 다음을 시도해보세요:
24
+
25
+ <Youtube id="S2EEG3JIt2A"/>
26
+
27
+ 1. [포럼](https://discuss.huggingface.co/)에서 도움을 요청하세요. [Beginners](https://discuss.huggingface.co/c/beginners/5) 또는 [🤗 Transformers](https://discuss.huggingface.co/c/transformers/9)와 같은 특정 카테고리에 질문을 게시할 수 있습니다. 재현 가능한 코드와 함께 잘 서술된 포럼 게시물을 작성하여 여러분의 문제가 해결될 가능성을 극대화하세요!
28
+
29
+ <Youtube id="_PAli-V4wj0"/>
30
+
31
+ 2. 라이브러리와 관련된 버그이면 🤗 Transformers 저장소에서 [이슈](https://github.com/huggingface/transformers/issues/new/choose)를 생성하세요. 버그에 대해 설명하는 정보를 가능한 많이 포함하려고 노력하여, 무엇이 잘못 되었는지와 어떻게 수정할 수 있는지 더 잘 파악할 수 있도록 도와주세요.
32
+
33
+ 3. 이전 버전의 🤗 Transformers을 사용하는 경우 중요한 변경 사항이 버전 사이에 도입되었기 때문에 [마이그레이션](migration) 가이드를 확인하세요.
34
+
35
+ 문제 해결 및 도움 매뉴얼에 대한 자세한 내용은 Hugging Face 강좌의 [8장](https://huggingface.co/course/chapter8/1?fw=pt)을 참조하세요.
36
+
37
+
38
+ ## 방화벽 환경[[firewalled-environments]]
39
+
40
+ 클라우드 및 내부망(intranet) 설정의 일부 GPU 인스턴스는 외부 연결에 대한 방화벽으로 차단되어 연결 오류가 발생할 수 있습니다. 스크립트가 모델 가중치나 데이터를 다운로드하려고 할 때, 다운로드가 중단되고 다음 메시지와 함께 시간 초과됩니다:
41
+
42
+ ```
43
+ ValueError: Connection error, and we cannot find the requested files in the cached path.
44
+ Please try again or make sure your Internet connection is on.
45
+ ```
46
+
47
+ 이 경우에는 연결 오류를 피하기 위해 🤗 Transformers를 [오프라인 모드](installation#offline-mode)로 실행해야 합니다.
48
+
49
+ ## CUDA 메모리 부족(CUDA out of memory)[[cuda-out-of-memory]]
50
+
51
+ 수백만 개의 매개변수로 대규모 모델을 훈련하는 것은 적절한 하드웨어 없이 어려울 수 있습니다. GPU 메모리가 부족한 경우 발생할 수 있는 일반적인 오류는 다음과 같습니다:
52
+
53
+ ```
54
+ CUDA out of memory. Tried to allocate 256.00 MiB (GPU 0; 11.17 GiB total capacity; 9.70 GiB already allocated; 179.81 MiB free; 9.85 GiB reserved in total by PyTorch)
55
+ ```
56
+
57
+ 다음은 메모리 사용을 줄이기 위해 시도해 볼 수 있는 몇 가지 잠재적인 해결책입니다:
58
+
59
+ - [`TrainingArguments`]의 [`per_device_train_batch_size`](main_classes/trainer#transformers.TrainingArguments.per_device_train_batch_size) 값을 줄이세요.
60
+ - [`TrainingArguments`]의 [`gradient_accumulation_steps`](main_classes/trainer#transformers.TrainingArguments.gradient_accumulation_steps)은 전체 배치 크기를 효과적으로 늘리세요.
61
+
62
+ <Tip>
63
+
64
+ 메모리 절약 기술에 대한 자세한 내용은 성능 [가이드](performance)를 참조하세요.
65
+
66
+ </Tip>
67
+
68
+ ## 저장된 TensorFlow 모델을 가져올 수 없습니다(Unable to load a saved TensorFlow model)[[unable-to-load-a-saved-uensorFlow-model]]
69
+
70
+ TensorFlow의 [model.save](https://www.tensorflow.org/tutorials/keras/save_and_load#save_the_entire_model) 메소드는 아키텍처, 가중치, 훈련 구성 등 전체 모델을 단일 파일에 저장합니다. 그러나 모델 파일을 다시 가져올 때 🤗 Transformers는 모델 파일에 있는 모든 TensorFlow 관련 객체를 가져오지 않을 수 있기 때문에 오류가 발생할 수 있습니다. TensorFlow 모델 저장 및 가져오기 문제를 피하려면 다음을 권장합니다:
71
+
72
+ - 모델 가중치를 `h5` 파일 확장자로 [`model.save_weights`](https://www.tensorflow.org/tutorials/keras/save_and_load#save_the_entire_model)로 저장한 다음 [`~TFPreTrainedModel.from_pretrained`]로 모델을 다시 가져옵니다:
73
+
74
+ ```py
75
+ >>> from transformers import TFPreTrainedModel
76
+ >>> from tensorflow import keras
77
+
78
+ >>> model.save_weights("some_folder/tf_model.h5")
79
+ >>> model = TFPreTrainedModel.from_pretrained("some_folder")
80
+ ```
81
+
82
+ - 모델을 [`~TFPretrainedModel.save_pretrained`]로 저장하고 [`~TFPreTrainedModel.from_pretrained`]로 다시 가져옵니다:
83
+
84
+ ```py
85
+ >>> from transformers import TFPreTrainedModel
86
+
87
+ >>> model.save_pretrained("path_to/model")
88
+ >>> model = TFPreTrainedModel.from_pretrained("path_to/model")
89
+ ```
90
+
91
+ ## ImportError[[importerror]]
92
+
93
+ 특히 최신 모델인 경우 만날 수 있는 다른 일반적인 오류는 `ImportError`입니다:
94
+
95
+ ```
96
+ ImportError: cannot import name 'ImageGPTImageProcessor' from 'transformers' (unknown location)
97
+ ```
98
+
99
+ 이러한 오류 유형의 경우 최신 모델에 액세스할 수 있도록 최신 버전의 🤗 Transformers가 설치되어 있는지 확인하세요:
100
+
101
+ ```bash
102
+ pip install transformers --upgrade
103
+ ```
104
+
105
+ ## CUDA error: device-side assert triggered[[cuda-error-deviceside-assert-triggered]]
106
+
107
+ 때때로 장치 코드 오류에 대한 일반적인 CUDA 오류가 발생할 수 있습니다.
108
+
109
+ ```
110
+ RuntimeError: CUDA error: device-side assert triggered
111
+ ```
112
+
113
+ 더 자세한 오류 메시지를 얻으려면 우선 코드를 CPU에서 실행합니다. 다음 환경 변수를 코드의 시작 부분에 추가하여 CPU로 전환하세요:
114
+
115
+ ```py
116
+ >>> import os
117
+
118
+ >>> os.environ["CUDA_VISIBLE_DEVICES"] = ""
119
+ ```
120
+
121
+ 또 다른 옵션은 GPU에서 더 나은 역추적(traceback)을 얻는 것입니다. 다음 환경 변수를 코드의 시작 부분에 추가하여 역추적이 오류가 발생한 소스를 가리키도록 하세요:
122
+
123
+ ```py
124
+ >>> import os
125
+
126
+ >>> os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
127
+ ```
128
+
129
+ ## 패딩 토큰이 마스킹되지 않은 경우 잘못된 출력(Incorrect output when padding tokens aren't masked)[[incorrect-output-when-padding-tokens-arent-masked]]
130
+
131
+ 경우에 따라 `input_ids`에 패딩 토큰이 포함된 경우 `hidden_state` 출력이 올바르지 않을 수 있습니다. 데모를 위해 모델과 토크나이저를 가져오세요. 모델의 `pad_token_id`에 액세스하여 해당 값을 확인할 수 있습니다. 일부 모델의 경우 `pad_token_id`가 `None`일 수 있지만 언제든지 수동으로 설정할 수 있습니다.
132
+
133
+ ```py
134
+ >>> from transformers import AutoModelForSequenceClassification
135
+ >>> import torch
136
+
137
+ >>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-uncased")
138
+ >>> model.config.pad_token_id
139
+ 0
140
+ ```
141
+
142
+ 다음 예제는 패딩 토큰을 마스킹하지 않은 출력을 보여줍니다:
143
+
144
+ ```py
145
+ >>> input_ids = torch.tensor([[7592, 2057, 2097, 2393, 9611, 2115], [7592, 0, 0, 0, 0, 0]])
146
+ >>> output = model(input_ids)
147
+ >>> print(output.logits)
148
+ tensor([[ 0.0082, -0.2307],
149
+ [ 0.1317, -0.1683]], grad_fn=<AddmmBackward0>)
150
+ ```
151
+
152
+ 다음은 두 번째 시퀀스의 실제 출력입니다:
153
+
154
+ ```py
155
+ >>> input_ids = torch.tensor([[7592]])
156
+ >>> output = model(input_ids)
157
+ >>> print(output.logits)
158
+ tensor([[-0.1008, -0.4061]], grad_fn=<AddmmBackward0>)
159
+ ```
160
+
161
+ 대부분의 경우 모델에 `attention_mask`를 제공하여 패딩 토큰을 무시해야 이러한 조용한 오류를 방지할 수 있습니다. 이제 두 번째 시퀀스의 출력이 실제 출력과 일치합니다:
162
+
163
+ <Tip>
164
+
165
+ 일반적으로 토크나이저는 특정 토크나이저의 기본 값을 기준으로 사용자에 대한 'attention_mask'를 만듭니다.
166
+
167
+ </Tip>
168
+
169
+ ```py
170
+ >>> attention_mask = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0]])
171
+ >>> output = model(input_ids, attention_mask=attention_mask)
172
+ >>> print(output.logits)
173
+ tensor([[ 0.0082, -0.2307],
174
+ [-0.1008, -0.4061]], grad_fn=<AddmmBackward0>)
175
+ ```
176
+
177
+ 🤗 Transformers는 패딩 토큰이 제공된 경우 패딩 토큰을 마스킹하기 위한 `attention_mask`를 자동으로 생성하지 않습니다. 그 이유는 다음과 같습니다:
178
+
179
+ - 일부 모델에는 패딩 토큰이 없습니다.
180
+ - 일부 사용 사례의 경우 사용자가 모델이 패딩 토큰을 관리하기를 원합니다.
181
+
182
+ ## ValueError: 이 유형의 AutoModel에 대해 인식할 수 없는 XYZ 구성 클래스(ValueError: Unrecognized configuration class XYZ for this kind of AutoModel)[[valueerror-unrecognized-configuration-class-xyz-for-this-kind-of-automodel]]
183
+
184
+ 일반적으로, 사전 학습된 모델의 인스턴스를 가져오기 위해 [`AutoModel`] 클래스를 사용하는 것이 좋습니다.
185
+ 이 클래스는 구성에 따라 주어진 체크포인트에서 올바른 아키텍처를 자동으로 추론하고 가져올 수 있습니다.
186
+ 모델을 체크포인트에서 가져올 때 이 `ValueError`가 발생하면, 이는 Auto 클래스가 주어진 체크포인트의 구성에서
187
+ 가져오려는 모델 유형과 매핑을 찾을 수 없다는 것을 의미합니다. 가장 흔하게 발생하는 경우는
188
+ 체크포인트가 주어진 태스크를 지원하��� 않을 때입니다.
189
+ 예를 들어, 다음 예제에서 질의응답에 대한 GPT2가 없기 때문에 오류가 발생합니다:
190
+
191
+ ```py
192
+ >>> from transformers import AutoProcessor, AutoModelForQuestionAnswering
193
+
194
+ >>> processor = AutoProcessor.from_pretrained("openai-community/gpt2-medium")
195
+ >>> model = AutoModelForQuestionAnswering.from_pretrained("openai-community/gpt2-medium")
196
+ ValueError: Unrecognized configuration class <class 'transformers.models.gpt2.configuration_gpt2.GPT2Config'> for this kind of AutoModel: AutoModelForQuestionAnswering.
197
+ Model type should be one of AlbertConfig, BartConfig, BertConfig, BigBirdConfig, BigBirdPegasusConfig, BloomConfig, ...
198
+ ```
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ms/_toctree.yml ADDED
@@ -0,0 +1,680 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - sections:
2
+ - local: index
3
+ title: 🤗 Transformers
4
+ - local: quicktour
5
+ title: Lawatan cepat
6
+ - local: installation
7
+ title: Pemasangan
8
+ title: Mulakan
9
+ - sections:
10
+ - local: pipeline_tutorial
11
+ title: Jalankan inferens dengan saluran paip
12
+ - local: autoclass_tutorial
13
+ title: Tulis kod mudah alih dengan AutoClass
14
+ - local: preprocessing
15
+ title: Praproses data
16
+ - local: training
17
+ title: Perhalusi model yang telah dilatih
18
+ - local: run_scripts
19
+ title: Latih dengan skrip
20
+ - local: accelerate
21
+ title: Sediakan latihan yang diedarkan dengan 🤗 Accelerate
22
+ - local: model_sharing
23
+ title: Kongsi model anda
24
+ title: Tutorials
25
+ - sections:
26
+ - sections:
27
+ - local: tasks/sequence_classification
28
+ title: Klasifikasi teks
29
+ - local: tasks/token_classification
30
+ title: Klasifikasi token
31
+ - local: tasks/question_answering
32
+ title: Soalan menjawab
33
+ - local: tasks/language_modeling
34
+ title: Pemodelan bahasa sebab-akibat
35
+ - local: tasks/masked_language_modeling
36
+ title: Pemodelan bahasa Masked
37
+ - local: tasks/translation
38
+ title: Terjemahan
39
+ - local: tasks/summarization
40
+ title: Rumusan
41
+ - local: tasks/multiple_choice
42
+ title: Pilihan
43
+ title: Natural Language Processing
44
+ isExpanded: false
45
+ - sections:
46
+ - local: tasks/audio_classification
47
+ title: Klasifikasi audio
48
+ - local: tasks/asr
49
+ title: Pengecaman pertuturan automatik
50
+ title: Audio
51
+ isExpanded: false
52
+ - sections:
53
+ - local: tasks/image_classification
54
+ title: Klasifikasi imej
55
+ - local: tasks/semantic_segmentation
56
+ title: Segmentasi semantik
57
+ - local: tasks/video_classification
58
+ title: Klasifikasi video
59
+ - local: tasks/object_detection
60
+ title: Pengesanan objek
61
+ - local: tasks/zero_shot_object_detection
62
+ title: Pengesanan objek Zero-Shot
63
+ - local: tasks/zero_shot_image_classification
64
+ title: Klasifikasi imej tangkapan Zero-Shot
65
+ - local: tasks/monocular_depth_estimation
66
+ title: Anggaran kedalaman
67
+ title: Visi komputer
68
+ isExpanded: false
69
+ - sections:
70
+ - local: tasks/image_captioning
71
+ title: Kapsyen imej
72
+ - local: tasks/document_question_answering
73
+ title: Menjawab Soalan Dokumen
74
+ - local: tasks/text-to-speech
75
+ title: Teks kepada ucapan
76
+ title: Multimodal
77
+ isExpanded: false
78
+ title: Panduan Tugasan
79
+ - sections:
80
+ - local: fast_tokenizers
81
+ title: Gunakan tokenizer cepat dari 🤗 Tokenizers
82
+ - local: multilingual
83
+ title: Jalankan inferens dengan model berbilang bahasa
84
+ - local: generation_strategies
85
+ title: Sesuaikan strategi penjanaan teks
86
+ - local: create_a_model
87
+ title: Gunakan API khusus model
88
+ - local: custom_models
89
+ title: Kongsi model tersuai
90
+ - local: sagemaker
91
+ title: Jalankan latihan di Amazon SageMaker
92
+ - local: serialization
93
+ title: Eksport ke ONNX
94
+ - local: torchscript
95
+ title: Eksport ke TorchScript
96
+ - local: Buku nota dengan contoh
97
+ title: Notebooks with examples
98
+ - local: Sumber komuniti
99
+ title: Community resources
100
+ - local: Sumber komuniti
101
+ title: Custom Tools and Prompts
102
+ - local: Alat dan Gesaan Tersuai
103
+ title: Selesaikan masalah
104
+ title: Panduan Developer
105
+ - sections:
106
+ - local: performance
107
+ title: Gambaran keseluruhan
108
+ - local: perf_train_gpu_one
109
+ title: Latihan pada satu GPU
110
+ - local: perf_train_gpu_many
111
+ title: Latihan pada banyak GPU
112
+ - local: perf_train_cpu
113
+ title: Latihan mengenai CPU
114
+ - local: perf_train_cpu_many
115
+ title: Latihan pada banyak CPU
116
+ - local: perf_train_tpu
117
+ title: Latihan mengenai TPU
118
+ - local: perf_train_tpu_tf
119
+ title: Latihan tentang TPU dengan TensorFlow
120
+ - local: perf_train_special
121
+ title: Latihan mengenai Perkakasan Khusus
122
+ - local: perf_infer_cpu
123
+ title: Inferens pada CPU
124
+ - local: perf_infer_gpu_one
125
+ title: Inferens pada satu GPU
126
+ - local: perf_infer_gpu_many
127
+ title: Inferens pada banyak GPUs
128
+ - local: perf_infer_special
129
+ title: Inferens pada Perkakasan Khusus
130
+ - local: perf_hardware
131
+ title: Perkakasan tersuai untuk latihan
132
+ - local: big_models
133
+ title: Menghidupkan model besar
134
+ - local: debugging
135
+ title: Penyahpepijatan
136
+ - local: hpo_train
137
+ title: Carian Hiperparameter menggunakan API Pelatih
138
+ - local: tf_xla
139
+ title: Penyepaduan XLA untuk Model TensorFlow
140
+ title: Prestasi dan kebolehskalaan
141
+ - sections:
142
+ - local: contributing
143
+ title: Bagaimana untuk menyumbang kepada transformer?
144
+ - local: add_new_model
145
+ title: Bagaimana untuk menambah model pada 🤗 Transformers?
146
+ - local: add_new_pipeline
147
+ title: Bagaimana untuk menambah saluran paip ke 🤗 Transformers?
148
+ - local: testing
149
+ title: Ujian
150
+ - local: pr_checks
151
+ title: Menyemak Permintaan Tarik
152
+ title: Sumbangkan
153
+
154
+ - sections:
155
+ - local: philosophy
156
+ title: Falsafah
157
+ - local: glossary
158
+ title: Glosari
159
+ - local: task_summary
160
+ title: Apa 🤗 Transformers boleh buat
161
+ - local: tasks_explained
162
+ title: Bagaimana 🤗 Transformers menyelesaikan tugasan
163
+ - local: model_summary
164
+ title: Keluarga model Transformer
165
+ - local: tokenizer_summary
166
+ title: Ringkasan tokenizer
167
+ - local: attention
168
+ title: Mekanisme perhatian
169
+ - local: pad_truncation
170
+ title: Padding dan pemotongan
171
+ - local: bertology
172
+ title: BERTology
173
+ - local: perplexity
174
+ title: Kekeliruan model panjang tetap
175
+ - local: pipeline_webserver
176
+ title: Saluran paip untuk inferens pelayan web
177
+ title: Panduan konsep
178
+ - sections:
179
+ - sections:
180
+ - local: model_doc/auto
181
+ title: Kelas Auto
182
+ - local: main_classes/callback
183
+ title: Panggilan balik
184
+ - local: main_classes/configuration
185
+ title: Configuration
186
+ - local: main_classes/data_collator
187
+ title: Data Collator
188
+ - local: main_classes/keras_callbacks
189
+ title: Keras callbacks
190
+ - local: main_classes/logging
191
+ title: Logging
192
+ - local: main_classes/model
193
+ title: Models
194
+ - local: main_classes/text_generation
195
+ title: Text Generation
196
+ - local: main_classes/onnx
197
+ title: ONNX
198
+ - local: main_classes/optimizer_schedules
199
+ title: Optimization
200
+ - local: main_classes/output
201
+ title: Model outputs
202
+ - local: main_classes/pipelines
203
+ title: Pipelines
204
+ - local: main_classes/processors
205
+ title: Processors
206
+ - local: main_classes/quantization
207
+ title: Quantization
208
+ - local: main_classes/tokenizer
209
+ title: Tokenizer
210
+ - local: main_classes/trainer
211
+ title: Trainer
212
+ - local: main_classes/deepspeed
213
+ title: DeepSpeed Integration
214
+ - local: main_classes/feature_extractor
215
+ title: Feature Extractor
216
+ - local: main_classes/image_processor
217
+ title: Image Processor
218
+ title: Main Classes
219
+ - sections:
220
+ - isExpanded: false
221
+ sections:
222
+ - local: model_doc/albert
223
+ title: ALBERT
224
+ - local: model_doc/bart
225
+ title: BART
226
+ - local: model_doc/barthez
227
+ title: BARThez
228
+ - local: model_doc/bartpho
229
+ title: BARTpho
230
+ - local: model_doc/bert
231
+ title: BERT
232
+ - local: model_doc/bert-generation
233
+ title: BertGeneration
234
+ - local: model_doc/bert-japanese
235
+ title: BertJapanese
236
+ - local: model_doc/bertweet
237
+ title: Bertweet
238
+ - local: model_doc/big_bird
239
+ title: BigBird
240
+ - local: model_doc/bigbird_pegasus
241
+ title: BigBirdPegasus
242
+ - local: model_doc/biogpt
243
+ title: BioGpt
244
+ - local: model_doc/blenderbot
245
+ title: Blenderbot
246
+ - local: model_doc/blenderbot-small
247
+ title: Blenderbot Small
248
+ - local: model_doc/bloom
249
+ title: BLOOM
250
+ - local: model_doc/bort
251
+ title: BORT
252
+ - local: model_doc/byt5
253
+ title: ByT5
254
+ - local: model_doc/camembert
255
+ title: CamemBERT
256
+ - local: model_doc/canine
257
+ title: CANINE
258
+ - local: model_doc/codegen
259
+ title: CodeGen
260
+ - local: model_doc/convbert
261
+ title: ConvBERT
262
+ - local: model_doc/cpm
263
+ title: CPM
264
+ - local: model_doc/cpmant
265
+ title: CPMANT
266
+ - local: model_doc/ctrl
267
+ title: CTRL
268
+ - local: model_doc/deberta
269
+ title: DeBERTa
270
+ - local: model_doc/deberta-v2
271
+ title: DeBERTa-v2
272
+ - local: model_doc/dialogpt
273
+ title: DialoGPT
274
+ - local: model_doc/distilbert
275
+ title: DistilBERT
276
+ - local: model_doc/dpr
277
+ title: DPR
278
+ - local: model_doc/electra
279
+ title: ELECTRA
280
+ - local: model_doc/encoder-decoder
281
+ title: Encoder Decoder Models
282
+ - local: model_doc/ernie
283
+ title: ERNIE
284
+ - local: model_doc/ernie_m
285
+ title: ErnieM
286
+ - local: model_doc/esm
287
+ title: ESM
288
+ - local: model_doc/flan-t5
289
+ title: FLAN-T5
290
+ - local: model_doc/flan-ul2
291
+ title: FLAN-UL2
292
+ - local: model_doc/flaubert
293
+ title: FlauBERT
294
+ - local: model_doc/fnet
295
+ title: FNet
296
+ - local: model_doc/fsmt
297
+ title: FSMT
298
+ - local: model_doc/funnel
299
+ title: Funnel Transformer
300
+ - local: model_doc/openai-gpt
301
+ title: GPT
302
+ - local: model_doc/gpt_neo
303
+ title: GPT Neo
304
+ - local: model_doc/gpt_neox
305
+ title: GPT NeoX
306
+ - local: model_doc/gpt_neox_japanese
307
+ title: GPT NeoX Japanese
308
+ - local: model_doc/gptj
309
+ title: GPT-J
310
+ - local: model_doc/gpt2
311
+ title: GPT2
312
+ - local: model_doc/gpt_bigcode
313
+ title: GPTBigCode
314
+ - local: model_doc/gptsan-japanese
315
+ title: GPTSAN Japanese
316
+ - local: model_doc/gpt-sw3
317
+ title: GPTSw3
318
+ - local: model_doc/herbert
319
+ title: HerBERT
320
+ - local: model_doc/ibert
321
+ title: I-BERT
322
+ - local: model_doc/jukebox
323
+ title: Jukebox
324
+ - local: model_doc/led
325
+ title: LED
326
+ - local: model_doc/llama
327
+ title: LLaMA
328
+ - local: model_doc/longformer
329
+ title: Longformer
330
+ - local: model_doc/longt5
331
+ title: LongT5
332
+ - local: model_doc/luke
333
+ title: LUKE
334
+ - local: model_doc/m2m_100
335
+ title: M2M100
336
+ - local: model_doc/marian
337
+ title: MarianMT
338
+ - local: model_doc/markuplm
339
+ title: MarkupLM
340
+ - local: model_doc/mbart
341
+ title: MBart and MBart-50
342
+ - local: model_doc/mega
343
+ title: MEGA
344
+ - local: model_doc/megatron-bert
345
+ title: MegatronBERT
346
+ - local: model_doc/megatron_gpt2
347
+ title: MegatronGPT2
348
+ - local: model_doc/mluke
349
+ title: mLUKE
350
+ - local: model_doc/mobilebert
351
+ title: MobileBERT
352
+ - local: model_doc/mpnet
353
+ title: MPNet
354
+ - local: model_doc/mt5
355
+ title: MT5
356
+ - local: model_doc/mvp
357
+ title: MVP
358
+ - local: model_doc/nezha
359
+ title: NEZHA
360
+ - local: model_doc/nllb
361
+ title: NLLB
362
+ - local: model_doc/nllb-moe
363
+ title: NLLB-MoE
364
+ - local: model_doc/nystromformer
365
+ title: Nyströmformer
366
+ - local: model_doc/open-llama
367
+ title: Open-Llama
368
+ - local: model_doc/opt
369
+ title: OPT
370
+ - local: model_doc/pegasus
371
+ title: Pegasus
372
+ - local: model_doc/pegasus_x
373
+ title: PEGASUS-X
374
+ - local: model_doc/phobert
375
+ title: PhoBERT
376
+ - local: model_doc/plbart
377
+ title: PLBart
378
+ - local: model_doc/prophetnet
379
+ title: ProphetNet
380
+ - local: model_doc/qdqbert
381
+ title: QDQBert
382
+ - local: model_doc/rag
383
+ title: RAG
384
+ - local: model_doc/realm
385
+ title: REALM
386
+ - local: model_doc/reformer
387
+ title: Reformer
388
+ - local: model_doc/rembert
389
+ title: RemBERT
390
+ - local: model_doc/retribert
391
+ title: RetriBERT
392
+ - local: model_doc/roberta
393
+ title: RoBERTa
394
+ - local: model_doc/roberta-prelayernorm
395
+ title: RoBERTa-PreLayerNorm
396
+ - local: model_doc/roc_bert
397
+ title: RoCBert
398
+ - local: model_doc/roformer
399
+ title: RoFormer
400
+ - local: model_doc/rwkv
401
+ title: RWKV
402
+ - local: model_doc/splinter
403
+ title: Splinter
404
+ - local: model_doc/squeezebert
405
+ title: SqueezeBERT
406
+ - local: model_doc/switch_transformers
407
+ title: SwitchTransformers
408
+ - local: model_doc/t5
409
+ title: T5
410
+ - local: model_doc/t5v1.1
411
+ title: T5v1.1
412
+ - local: model_doc/tapex
413
+ title: TAPEX
414
+ - local: model_doc/transfo-xl
415
+ title: Transformer XL
416
+ - local: model_doc/ul2
417
+ title: UL2
418
+ - local: model_doc/xmod
419
+ title: X-MOD
420
+ - local: model_doc/xglm
421
+ title: XGLM
422
+ - local: model_doc/xlm
423
+ title: XLM
424
+ - local: model_doc/xlm-prophetnet
425
+ title: XLM-ProphetNet
426
+ - local: model_doc/xlm-roberta
427
+ title: XLM-RoBERTa
428
+ - local: model_doc/xlm-roberta-xl
429
+ title: XLM-RoBERTa-XL
430
+ - local: model_doc/xlm-v
431
+ title: XLM-V
432
+ - local: model_doc/xlnet
433
+ title: XLNet
434
+ - local: model_doc/yoso
435
+ title: YOSO
436
+ title: Text models
437
+ - isExpanded: false
438
+ sections:
439
+ - local: model_doc/beit
440
+ title: BEiT
441
+ - local: model_doc/bit
442
+ title: BiT
443
+ - local: model_doc/conditional_detr
444
+ title: Conditional DETR
445
+ - local: model_doc/convnext
446
+ title: ConvNeXT
447
+ - local: model_doc/convnextv2
448
+ title: ConvNeXTV2
449
+ - local: model_doc/cvt
450
+ title: CvT
451
+ - local: model_doc/deformable_detr
452
+ title: Deformable DETR
453
+ - local: model_doc/deit
454
+ title: DeiT
455
+ - local: model_doc/deta
456
+ title: DETA
457
+ - local: model_doc/detr
458
+ title: DETR
459
+ - local: model_doc/dinat
460
+ title: DiNAT
461
+ - local: model_doc/dit
462
+ title: DiT
463
+ - local: model_doc/dpt
464
+ title: DPT
465
+ - local: model_doc/efficientformer
466
+ title: EfficientFormer
467
+ - local: model_doc/efficientnet
468
+ title: EfficientNet
469
+ - local: model_doc/focalnet
470
+ title: FocalNet
471
+ - local: model_doc/glpn
472
+ title: GLPN
473
+ - local: model_doc/imagegpt
474
+ title: ImageGPT
475
+ - local: model_doc/levit
476
+ title: LeViT
477
+ - local: model_doc/mask2former
478
+ title: Mask2Former
479
+ - local: model_doc/maskformer
480
+ title: MaskFormer
481
+ - local: model_doc/mobilenet_v1
482
+ title: MobileNetV1
483
+ - local: model_doc/mobilenet_v2
484
+ title: MobileNetV2
485
+ - local: model_doc/mobilevit
486
+ title: MobileViT
487
+ - local: model_doc/nat
488
+ title: NAT
489
+ - local: model_doc/poolformer
490
+ title: PoolFormer
491
+ - local: model_doc/regnet
492
+ title: RegNet
493
+ - local: model_doc/resnet
494
+ title: ResNet
495
+ - local: model_doc/segformer
496
+ title: SegFormer
497
+ - local: model_doc/swiftformer
498
+ title: SwiftFormer
499
+ - local: model_doc/swin
500
+ title: Swin Transformer
501
+ - local: model_doc/swinv2
502
+ title: Swin Transformer V2
503
+ - local: model_doc/swin2sr
504
+ title: Swin2SR
505
+ - local: model_doc/table-transformer
506
+ title: Table Transformer
507
+ - local: model_doc/timesformer
508
+ title: TimeSformer
509
+ - local: model_doc/upernet
510
+ title: UperNet
511
+ - local: model_doc/van
512
+ title: VAN
513
+ - local: model_doc/videomae
514
+ title: VideoMAE
515
+ - local: model_doc/vit
516
+ title: Vision Transformer (ViT)
517
+ - local: model_doc/vit_hybrid
518
+ title: ViT Hybrid
519
+ - local: model_doc/vit_mae
520
+ title: ViTMAE
521
+ - local: model_doc/vit_msn
522
+ title: ViTMSN
523
+ - local: model_doc/yolos
524
+ title: YOLOS
525
+ title: Vision models
526
+ - isExpanded: false
527
+ sections:
528
+ - local: model_doc/audio-spectrogram-transformer
529
+ title: Audio Spectrogram Transformer
530
+ - local: model_doc/clap
531
+ title: CLAP
532
+ - local: model_doc/hubert
533
+ title: Hubert
534
+ - local: model_doc/mctct
535
+ title: MCTCT
536
+ - local: model_doc/sew
537
+ title: SEW
538
+ - local: model_doc/sew-d
539
+ title: SEW-D
540
+ - local: model_doc/speech_to_text
541
+ title: Speech2Text
542
+ - local: model_doc/speech_to_text_2
543
+ title: Speech2Text2
544
+ - local: model_doc/speecht5
545
+ title: SpeechT5
546
+ - local: model_doc/unispeech
547
+ title: UniSpeech
548
+ - local: model_doc/unispeech-sat
549
+ title: UniSpeech-SAT
550
+ - local: model_doc/wav2vec2
551
+ title: Wav2Vec2
552
+ - local: model_doc/wav2vec2-conformer
553
+ title: Wav2Vec2-Conformer
554
+ - local: model_doc/wav2vec2_phoneme
555
+ title: Wav2Vec2Phoneme
556
+ - local: model_doc/wavlm
557
+ title: WavLM
558
+ - local: model_doc/whisper
559
+ title: Whisper
560
+ - local: model_doc/xls_r
561
+ title: XLS-R
562
+ - local: model_doc/xlsr_wav2vec2
563
+ title: XLSR-Wav2Vec2
564
+ title: Audio models
565
+ - isExpanded: false
566
+ sections:
567
+ - local: model_doc/align
568
+ title: ALIGN
569
+ - local: model_doc/altclip
570
+ title: AltCLIP
571
+ - local: model_doc/blip
572
+ title: BLIP
573
+ - local: model_doc/blip-2
574
+ title: BLIP-2
575
+ - local: model_doc/bridgetower
576
+ title: BridgeTower
577
+ - local: model_doc/chinese_clip
578
+ title: Chinese-CLIP
579
+ - local: model_doc/clip
580
+ title: CLIP
581
+ - local: model_doc/clipseg
582
+ title: CLIPSeg
583
+ - local: model_doc/data2vec
584
+ title: Data2Vec
585
+ - local: model_doc/deplot
586
+ title: DePlot
587
+ - local: model_doc/donut
588
+ title: Donut
589
+ - local: model_doc/flava
590
+ title: FLAVA
591
+ - local: model_doc/git
592
+ title: GIT
593
+ - local: model_doc/groupvit
594
+ title: GroupViT
595
+ - local: model_doc/layoutlm
596
+ title: LayoutLM
597
+ - local: model_doc/layoutlmv2
598
+ title: LayoutLMV2
599
+ - local: model_doc/layoutlmv3
600
+ title: LayoutLMV3
601
+ - local: model_doc/layoutxlm
602
+ title: LayoutXLM
603
+ - local: model_doc/lilt
604
+ title: LiLT
605
+ - local: model_doc/lxmert
606
+ title: LXMERT
607
+ - local: model_doc/matcha
608
+ title: MatCha
609
+ - local: model_doc/mgp-str
610
+ title: MGP-STR
611
+ - local: model_doc/oneformer
612
+ title: OneFormer
613
+ - local: model_doc/owlvit
614
+ title: OWL-ViT
615
+ - local: model_doc/perceiver
616
+ title: Perceiver
617
+ - local: model_doc/pix2struct
618
+ title: Pix2Struct
619
+ - local: model_doc/sam
620
+ title: Segment Anything
621
+ - local: model_doc/speech-encoder-decoder
622
+ title: Speech Encoder Decoder Models
623
+ - local: model_doc/tapas
624
+ title: TAPAS
625
+ - local: model_doc/trocr
626
+ title: TrOCR
627
+ - local: model_doc/tvlt
628
+ title: TVLT
629
+ - local: model_doc/vilt
630
+ title: ViLT
631
+ - local: model_doc/vision-encoder-decoder
632
+ title: Vision Encoder Decoder Models
633
+ - local: model_doc/vision-text-dual-encoder
634
+ title: Vision Text Dual Encoder
635
+ - local: model_doc/visual_bert
636
+ title: VisualBERT
637
+ - local: model_doc/xclip
638
+ title: X-CLIP
639
+ title: Multimodal models
640
+ - isExpanded: false
641
+ sections:
642
+ - local: model_doc/decision_transformer
643
+ title: Decision Transformer
644
+ - local: model_doc/trajectory_transformer
645
+ title: Trajectory Transformer
646
+ title: Reinforcement learning models
647
+ - isExpanded: false
648
+ sections:
649
+ - local: model_doc/informer
650
+ title: Informer
651
+ - local: model_doc/time_series_transformer
652
+ title: Time Series Transformer
653
+ title: Time series models
654
+ - isExpanded: false
655
+ sections:
656
+ - local: model_doc/graphormer
657
+ title: Graphormer
658
+ title: Graph models
659
+ title: Models
660
+ - sections:
661
+ - local: internal/modeling_utils
662
+ title: Custom Layers and Utilities
663
+ - local: internal/pipelines_utils
664
+ title: Utilities for pipelines
665
+ - local: internal/tokenization_utils
666
+ title: Utilities for Tokenizers
667
+ - local: internal/trainer_utils
668
+ title: Utilities for Trainer
669
+ - local: internal/generation_utils
670
+ title: Utilities for Generation
671
+ - local: internal/image_processing_utils
672
+ title: Utilities for Image Processors
673
+ - local: internal/audio_utils
674
+ title: Utilities for Audio processing
675
+ - local: internal/file_utils
676
+ title: General Utilities
677
+ - local: internal/time_series_utils
678
+ title: Utilities for Time Series
679
+ title: Internal Helpers
680
+ title: API
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/ms/index.md ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2020 The HuggingFace Team. All rights reserved.
2
+
3
+ Dilesenkan di bawah Lesen Apache, Versi 2.0 ("Lesen"); anda tidak boleh menggunakan fail ini kecuali dengan mematuhi
4
+ Lesen. Anda boleh mendapatkan salinan Lesen di
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Melainkan diperlukan oleh undang-undang yang terpakai atau dipersetujui secara bertulis, perisian yang diedarkan di bawah Lesen diedarkan pada
9
+ ASAS ""SEBAGAIMANA ADANYA"", TANPA WARANTI ATAU SEBARANG JENIS SYARAT, sama ada nyata atau tersirat. Lihat Lesen untuk
10
+ bahasa tertentu yang mengawal kebenaran dan pengehadan di bawah Lesen.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # 🤗 Transformers
18
+
19
+ Pembelajaran Mesin terkini untuk [PyTorch](https://pytorch.org/), [TensorFlow](https://www.tensorflow.org/), dan [JAX](https://jax.readthedocs.io/en/latest/).
20
+
21
+ 🤗 Transformers menyediakan API dan alatan untuk memuat turun dan melatih model pra-latihan terkini dengan mudah. Menggunakan model terlatih boleh mengurangkan kos pengiraan anda, jejak karbon dan menjimatkan masa serta sumber yang diperlukan untuk melatih model dari awal. Model ini menyokong tugas biasa dalam modaliti yang berbeza, seperti:
22
+
23
+ 📝 **Natural Language Processing**: klasifikasi teks, pengecaman entiti bernama, menjawab soalan, pemodelan bahasa, ringkasan, terjemahan, pilihan berganda dan penjanaan teks.<br>
24
+ 🖼️ **Computer Vision**: pengelasan imej, pengesanan objek dan pembahagian.<br>
25
+ 🗣️ **Audio**: pengecaman pertuturan automatik dan klasifikasi audio.<br>
26
+ 🐙 **Multimodal**: jawapan soalan jadual, pengecaman aksara optik, pengekstrakan maklumat daripada dokumen yang diimbas, klasifikasi video dan jawapan soalan visual.
27
+
28
+ 🤗 Transformer menyokong kebolehoperasian rangka kerja antara PyTorch, TensorFlow, and JAX. Ini memberikan fleksibiliti untuk menggunakan rangka kerja yang berbeza pada setiap peringkat kehidupan model; latih model dalam tiga baris kod dalam satu rangka kerja, dan muatkannya untuk inferens dalam rangka kerja yang lain. Model juga boleh dieksport ke format seperti ONNX.
29
+
30
+ Sertai komuniti yang semakin berkembang di [Hub](https://huggingface.co/models), [forum](https://discuss.huggingface.co/), atau [Discord](https://discord.com/invite/JfAtkvEtRb) hari ini!
31
+
32
+ ## Jika anda sedang mencari sokongan tersuai daripada pasukan Hugging Face
33
+
34
+ <a target="_blank" href="https://huggingface.co/support">
35
+ <img alt="HuggingFace Expert Acceleration Program" src="https://cdn-media.huggingface.co/marketing/transformers/new-support-improved.png" style="width: 100%; max-width: 600px; border: 1px solid #eee; border-radius: 4px; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);">
36
+ </a>
37
+
38
+ ## Kandungan
39
+
40
+ Dokumentasi disusun kepada lima bahagian:
41
+
42
+ - **MULAKAN** menyediakan lawatan pantas ke perpustakaan dan arahan pemasangan untuk bangun dan berjalan.
43
+ - **TUTORIAL** ialah tempat yang bagus untuk bermula jika anda seorang pemula. Bahagian ini akan membantu anda memperoleh kemahiran asas yang anda perlukan untuk mula menggunakan perpustakaan.
44
+ - **PANDUAN CARA-CARA** menunjukkan kepada anda cara untuk mencapai matlamat tertentu, seperti memperhalusi model terlatih untuk pemodelan bahasa atau cara menulis dan berkongsi model tersuai.
45
+ - **PANDUAN KONSEP** menawarkan lebih banyak perbincangan dan penjelasan tentang konsep dan idea asas di sebalik model, tugasan dan falsafah reka bentuk 🤗 Transformers.
46
+ - **API** menerangkan semua kelas dan fungsi:
47
+
48
+ - **KELAS UTAMA** memperincikan kelas yang paling penting seperti konfigurasi, model, tokenizer dan saluran paip.
49
+ - **MODEL** memperincikan kelas dan fungsi yang berkaitan dengan setiap model yang dilaksanakan dalam perpustakaan.
50
+ - **PEMBANTU DALAMAN** memperincikan kelas utiliti dan fungsi yang digunakan secara dalaman.
51
+
52
+ ### Model yang disokong
53
+
54
+ <!--Senarai ini dikemas kini secara automatik daripada README dengan _make fix-copies_. Jangan kemas kini secara manual! -->
55
+
56
+ 1. **[ALBERT](model_doc/albert)** (from Google Research and the Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://huggingface.co/papers/1909.11942), by Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.
57
+ 1. **[ALIGN](model_doc/align)** (from Google Research) released with the paper [Scaling Up Visual and Vision-Language Representation Learning With Noisy Text Supervision](https://huggingface.co/papers/2102.05918) by Chao Jia, Yinfei Yang, Ye Xia, Yi-Ting Chen, Zarana Parekh, Hieu Pham, Quoc V. Le, Yunhsuan Sung, Zhen Li, Tom Duerig.
58
+ 1. **[AltCLIP](model_doc/altclip)** (from BAAI) released with the paper [AltCLIP: Altering the Language Encoder in CLIP for Extended Language Capabilities](https://huggingface.co/papers/2211.06679) by Chen, Zhongzhi and Liu, Guang and Zhang, Bo-Wen and Ye, Fulong and Yang, Qinghong and Wu, Ledell.
59
+ 1. **[Audio Spectrogram Transformer](model_doc/audio-spectrogram-transformer)** (from MIT) released with the paper [AST: Audio Spectrogram Transformer](https://huggingface.co/papers/2104.01778) by Yuan Gong, Yu-An Chung, James Glass.
60
+ 1. **[Autoformer](model_doc/autoformer)** (from Tsinghua University) released with the paper [Autoformer: Decomposition Transformers with Auto-Correlation for Long-Term Series Forecasting](https://huggingface.co/papers/2106.13008) by Haixu Wu, Jiehui Xu, Jianmin Wang, Mingsheng Long.
61
+ 1. **[BART](model_doc/bart)** (from Facebook) released with the paper [BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension](https://huggingface.co/papers/1910.13461) by Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer.
62
+ 1. **[BARThez](model_doc/barthez)** (from École polytechnique) released with the paper [BARThez: a Skilled Pretrained French Sequence-to-Sequence Model](https://huggingface.co/papers/2010.12321) by Moussa Kamal Eddine, Antoine J.-P. Tixier, Michalis Vazirgiannis.
63
+ 1. **[BARTpho](model_doc/bartpho)** (from VinAI Research) released with the paper [BARTpho: Pre-trained Sequence-to-Sequence Models for Vietnamese](https://huggingface.co/papers/2109.09701) by Nguyen Luong Tran, Duong Minh Le and Dat Quoc Nguyen.
64
+ 1. **[BEiT](model_doc/beit)** (from Microsoft) released with the paper [BEiT: BERT Pre-Training of Image Transformers](https://huggingface.co/papers/2106.08254) by Hangbo Bao, Li Dong, Furu Wei.
65
+ 1. **[BERT](model_doc/bert)** (from Google) released with the paper [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://huggingface.co/papers/1810.04805) by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova.
66
+ 1. **[BERT For Sequence Generation](model_doc/bert-generation)** (from Google) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://huggingface.co/papers/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
67
+ 1. **[BERTweet](model_doc/bertweet)** (from VinAI Research) released with the paper [BERTweet: A pre-trained language model for English Tweets](https://aclanthology.org/2020.emnlp-demos.2/) by Dat Quoc Nguyen, Thanh Vu and Anh Tuan Nguyen.
68
+ 1. **[BigBird-Pegasus](model_doc/bigbird_pegasus)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://huggingface.co/papers/2007.14062) by Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed.
69
+ 1. **[BigBird-RoBERTa](model_doc/big_bird)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://huggingface.co/papers/2007.14062) by Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed.
70
+ 1. **[BioGpt](model_doc/biogpt)** (from Microsoft Research AI4Science) released with the paper [BioGPT: generative pre-trained transformer for biomedical text generation and mining](https://academic.oup.com/bib/advance-article/doi/10.1093/bib/bbac409/6713511?guestAccessKey=a66d9b5d-4f83-4017-bb52-405815c907b9) by Renqian Luo, Liai Sun, Yingce Xia, Tao Qin, Sheng Zhang, Hoifung Poon and Tie-Yan Liu.
71
+ 1. **[BiT](model_doc/bit)** (from Google AI) released with the paper [Big Transfer (BiT): General Visual Representation Learning](https://huggingface.co/papers/1912.11370) by Alexander Kolesnikov, Lucas Beyer, Xiaohua Zhai, Joan Puigcerver, Jessica Yung, Sylvain Gelly, Neil Houlsby.
72
+ 1. **[Blenderbot](model_doc/blenderbot)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://huggingface.co/papers/2004.13637) by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston.
73
+ 1. **[BlenderbotSmall](model_doc/blenderbot-small)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://huggingface.co/papers/2004.13637) by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston.
74
+ 1. **[BLIP](model_doc/blip)** (from Salesforce) released with the paper [BLIP: Bootstrapping Language-Image Pre-training for Unified Vision-Language Understanding and Generation](https://huggingface.co/papers/2201.12086) by Junnan Li, Dongxu Li, Caiming Xiong, Steven Hoi.
75
+ 1. **[BLIP-2](model_doc/blip-2)** (from Salesforce) released with the paper [BLIP-2: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models](https://huggingface.co/papers/2301.12597) by Junnan Li, Dongxu Li, Silvio Savarese, Steven Hoi.
76
+ 1. **[BLOOM](model_doc/bloom)** (from BigScience workshop) released by the [BigScience Workshop](https://bigscience.huggingface.co/).
77
+ 1. **[BORT](model_doc/bort)** (from Alexa) released with the paper [Optimal Subarchitecture Extraction For BERT](https://huggingface.co/papers/2010.10499) by Adrian de Wynter and Daniel J. Perry.
78
+ 1. **[BridgeTower](model_doc/bridgetower)** (from Harbin Institute of Technology/Microsoft Research Asia/Intel Labs) released with the paper [BridgeTower: Building Bridges Between Encoders in Vision-Language Representation Learning](https://huggingface.co/papers/2206.08657) by Xiao Xu, Chenfei Wu, Shachar Rosenman, Vasudev Lal, Wanxiang Che, Nan Duan.
79
+ 1. **[Bros](model_doc/bros)** (from NAVER) released with the paper [BROS: A Pre-trained Language Model Focusing on Text and Layout for Better Key Information Extraction from Documents](https://huggingface.co/papers/2108.04539) by Teakgyu Hong, Donghyun Kim, Mingi Ji, Wonseok Hwang, Daehyun Nam, Sungrae Park.
80
+ 1. **[ByT5](model_doc/byt5)** (from Google Research) released with the paper [ByT5: Towards a token-free future with pre-trained byte-to-byte models](https://huggingface.co/papers/2105.13626) by Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, Colin Raffel.
81
+ 1. **[CamemBERT](model_doc/camembert)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://huggingface.co/papers/1911.03894) by Louis Martin*, Benjamin Muller*, Pedro Javier Ortiz Suárez*, Yoann Dupont, Laurent Romary, Éric Villemonte de la Clergerie, Djamé Seddah and Benoît Sagot.
82
+ 1. **[CANINE](model_doc/canine)** (from Google Research) released with the paper [CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation](https://huggingface.co/papers/2103.06874) by Jonathan H. Clark, Dan Garrette, Iulia Turc, John Wieting.
83
+ 1. **[Chinese-CLIP](model_doc/chinese_clip)** (from OFA-Sys) released with the paper [Chinese CLIP: Contrastive Vision-Language Pretraining in Chinese](https://huggingface.co/papers/2211.01335) by An Yang, Junshu Pan, Junyang Lin, Rui Men, Yichang Zhang, Jingren Zhou, Chang Zhou.
84
+ 1. **[CLAP](model_doc/clap)** (from LAION-AI) released with the paper [Large-scale Contrastive Language-Audio Pretraining with Feature Fusion and Keyword-to-Caption Augmentation](https://huggingface.co/papers/2211.06687) by Yusong Wu, Ke Chen, Tianyu Zhang, Yuchen Hui, Taylor Berg-Kirkpatrick, Shlomo Dubnov.
85
+ 1. **[CLIP](model_doc/clip)** (from OpenAI) released with the paper [Learning Transferable Visual Models From Natural Language Supervision](https://huggingface.co/papers/2103.00020) by Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, Gretchen Krueger, Ilya Sutskever.
86
+ 1. **[CLIPSeg](model_doc/clipseg)** (from University of Göttingen) released with the paper [Image Segmentation Using Text and Image Prompts](https://huggingface.co/papers/2112.10003) by Timo Lüddecke and Alexander Ecker.
87
+ 1. **[CodeGen](model_doc/codegen)** (from Salesforce) released with the paper [A Conversational Paradigm for Program Synthesis](https://huggingface.co/papers/2203.13474) by Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, Caiming Xiong.
88
+ 1. **[Conditional DETR](model_doc/conditional_detr)** (from Microsoft Research Asia) released with the paper [Conditional DETR for Fast Training Convergence](https://huggingface.co/papers/2108.06152) by Depu Meng, Xiaokang Chen, Zejia Fan, Gang Zeng, Houqiang Li, Yuhui Yuan, Lei Sun, Jingdong Wang.
89
+ 1. **[ConvBERT](model_doc/convbert)** (from YituTech) released with the paper [ConvBERT: Improving BERT with Span-based Dynamic Convolution](https://huggingface.co/papers/2008.02496) by Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng Yan.
90
+ 1. **[ConvNeXT](model_doc/convnext)** (from Facebook AI) released with the paper [A ConvNet for the 2020s](https://huggingface.co/papers/2201.03545) by Zhuang Liu, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, Saining Xie.
91
+ 1. **[ConvNeXTV2](model_doc/convnextv2)** (from Facebook AI) released with the paper [ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders](https://huggingface.co/papers/2301.00808) by Sanghyun Woo, Shoubhik Debnath, Ronghang Hu, Xinlei Chen, Zhuang Liu, In So Kweon, Saining Xie.
92
+ 1. **[CPM](model_doc/cpm)** (from Tsinghua University) released with the paper [CPM: A Large-scale Generative Chinese Pre-trained Language Model](https://huggingface.co/papers/2012.00413) by Zhengyan Zhang, Xu Han, Hao Zhou, Pei Ke, Yuxian Gu, Deming Ye, Yujia Qin, Yusheng Su, Haozhe Ji, Jian Guan, Fanchao Qi, Xiaozhi Wang, Yanan Zheng, Guoyang Zeng, Huanqi Cao, Shengqi Chen, Daixuan Li, Zhenbo Sun, Zhiyuan Liu, Minlie Huang, Wentao Han, Jie Tang, Juanzi Li, Xiaoyan Zhu, Maosong Sun.
93
+ 1. **[CPM-Ant](model_doc/cpmant)** (from OpenBMB) released by the [OpenBMB](https://www.openbmb.org/).
94
+ 1. **[CTRL](model_doc/ctrl)** (from Salesforce) released with the paper [CTRL: A Conditional Transformer Language Model for Controllable Generation](https://huggingface.co/papers/1909.05858) by Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong and Richard Socher.
95
+ 1. **[CvT](model_doc/cvt)** (from Microsoft) released with the paper [CvT: Introducing Convolutions to Vision Transformers](https://huggingface.co/papers/2103.15808) by Haiping Wu, Bin Xiao, Noel Codella, Mengchen Liu, Xiyang Dai, Lu Yuan, Lei Zhang.
96
+ 1. **[Data2Vec](model_doc/data2vec)** (from Facebook) released with the paper [Data2Vec: A General Framework for Self-supervised Learning in Speech, Vision and Language](https://huggingface.co/papers/2202.03555) by Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu, Michael Auli.
97
+ 1. **[DeBERTa](model_doc/deberta)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://huggingface.co/papers/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
98
+ 1. **[DeBERTa-v2](model_doc/deberta-v2)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://huggingface.co/papers/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
99
+ 1. **[Decision Transformer](model_doc/decision_transformer)** (from Berkeley/Facebook/Google) released with the paper [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://huggingface.co/papers/2106.01345) by Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch.
100
+ 1. **[Deformable DETR](model_doc/deformable_detr)** (from SenseTime Research) released with the paper [Deformable DETR: Deformable Transformers for End-to-End Object Detection](https://huggingface.co/papers/2010.04159) by Xizhou Zhu, Weijie Su, Lewei Lu, Bin Li, Xiaogang Wang, Jifeng Dai.
101
+ 1. **[DeiT](model_doc/deit)** (from Facebook) released with the paper [Training data-efficient image transformers & distillation through attention](https://huggingface.co/papers/2012.12877) by Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, Hervé Jégou.
102
+ 1. **[DePlot](model_doc/deplot)** (from Google AI) released with the paper [DePlot: One-shot visual language reasoning by plot-to-table translation](https://huggingface.co/papers/2212.10505) by Fangyu Liu, Julian Martin Eisenschlos, Francesco Piccinno, Syrine Krichene, Chenxi Pang, Kenton Lee, Mandar Joshi, Wenhu Chen, Nigel Collier, Yasemin Altun.
103
+ 1. **[DETA](model_doc/deta)** (from The University of Texas at Austin) released with the paper [NMS Strikes Back](https://huggingface.co/papers/2212.06137) by Jeffrey Ouyang-Zhang, Jang Hyun Cho, Xingyi Zhou, Philipp Krähenbühl.
104
+ 1. **[DETR](model_doc/detr)** (from Facebook) released with the paper [End-to-End Object Detection with Transformers](https://huggingface.co/papers/2005.12872) by Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko.
105
+ 1. **[DialoGPT](model_doc/dialogpt)** (from Microsoft Research) released with the paper [DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation](https://huggingface.co/papers/1911.00536) by Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dolan.
106
+ 1. **[DiNAT](model_doc/dinat)** (from SHI Labs) released with the paper [Dilated Neighborhood Attention Transformer](https://huggingface.co/papers/2209.15001) by Ali Hassani and Humphrey Shi.
107
+ 1. **[DistilBERT](model_doc/distilbert)** (from HuggingFace), released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://huggingface.co/papers/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same method has been applied to compress GPT2 into [DistilGPT2](https://github.com/huggingface/transformers-research-projects/tree/main/distillation), RoBERTa into [DistilRoBERTa](https://github.com/huggingface/transformers-research-projects/tree/main/distillation), Multilingual BERT into [DistilmBERT](https://github.com/huggingface/transformers-research-projects/tree/main/distillation) and a German version of DistilBERT.
108
+ 1. **[DiT](model_doc/dit)** (from Microsoft Research) released with the paper [DiT: Self-supervised Pre-training for Document Image Transformer](https://huggingface.co/papers/2203.02378) by Junlong Li, Yiheng Xu, Tengchao Lv, Lei Cui, Cha Zhang, Furu Wei.
109
+ 1. **[Donut](model_doc/donut)** (from NAVER), released together with the paper [OCR-free Document Understanding Transformer](https://huggingface.co/papers/2111.15664) by Geewook Kim, Teakgyu Hong, Moonbin Yim, Jeongyeon Nam, Jinyoung Park, Jinyeong Yim, Wonseok Hwang, Sangdoo Yun, Dongyoon Han, Seunghyun Park.
110
+ 1. **[DPR](model_doc/dpr)** (from Facebook) released with the paper [Dense Passage Retrieval for Open-Domain Question Answering](https://huggingface.co/papers/2004.04906) by Vladimir Karpukhin, Barlas Oğuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih.
111
+ 1. **[DPT](master/model_doc/dpt)** (from Intel Labs) released with the paper [Vision Transformers for Dense Prediction](https://huggingface.co/papers/2103.13413) by René Ranftl, Alexey Bochkovskiy, Vladlen Koltun.
112
+ 1. **[EfficientFormer](model_doc/efficientformer)** (from Snap Research) released with the paper [EfficientFormer: Vision Transformers at MobileNetSpeed](https://huggingface.co/papers/2206.01191) by Yanyu Li, Geng Yuan, Yang Wen, Ju Hu, Georgios Evangelidis, Sergey Tulyakov, Yanzhi Wang, Jian Ren.
113
+ 1. **[EfficientNet](model_doc/efficientnet)** (from Google Brain) released with the paper [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://huggingface.co/papers/1905.11946) by Mingxing Tan, Quoc V. Le.
114
+ 1. **[ELECTRA](model_doc/electra)** (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders as discriminators rather than generators](https://huggingface.co/papers/2003.10555) by Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning.
115
+ 1. **[EncoderDecoder](model_doc/encoder-decoder)** (from Google Research) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://huggingface.co/papers/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
116
+ 1. **[ERNIE](model_doc/ernie)** (from Baidu) released with the paper [ERNIE: Enhanced Representation through Knowledge Integration](https://huggingface.co/papers/1904.09223) by Yu Sun, Shuohuan Wang, Yukun Li, Shikun Feng, Xuyi Chen, Han Zhang, Xin Tian, Danxiang Zhu, Hao Tian, Hua Wu.
117
+ 1. **[ErnieM](model_doc/ernie_m)** (from Baidu) released with the paper [ERNIE-M: Enhanced Multilingual Representation by Aligning Cross-lingual Semantics with Monolingual Corpora](https://huggingface.co/papers/2012.15674) by Xuan Ouyang, Shuohuan Wang, Chao Pang, Yu Sun, Hao Tian, Hua Wu, Haifeng Wang.
118
+ 1. **[ESM](model_doc/esm)** (from Meta AI) are transformer protein language models. **ESM-1b** was released with the paper [Biological structure and function emerge from scaling unsupervised learning to 250 million protein sequences](https://www.pnas.org/content/118/15/e2016239118) by Alexander Rives, Joshua Meier, Tom Sercu, Siddharth Goyal, Zeming Lin, Jason Liu, Demi Guo, Myle Ott, C. Lawrence Zitnick, Jerry Ma, and Rob Fergus. **ESM-1v** was released with the paper [Language models enable zero-shot prediction of the effects of mutations on protein function](https://doi.org/10.1101/2021.07.09.450648) by Joshua Meier, Roshan Rao, Robert Verkuil, Jason Liu, Tom Sercu and Alexander Rives. **ESM-2 and ESMFold** were released with the paper [Language models of protein sequences at the scale of evolution enable accurate structure prediction](https://doi.org/10.1101/2022.07.20.500902) by Zeming Lin, Halil Akin, Roshan Rao, Brian Hie, Zhongkai Zhu, Wenting Lu, Allan dos Santos Costa, Maryam Fazel-Zarandi, Tom Sercu, Sal Candido, Alexander Rives.
119
+ 1. **[FLAN-T5](model_doc/flan-t5)** (from Google AI) released in the repository [google-research/t5x](https://github.com/google-research/t5x/blob/main/docs/models.md#flan-t5-checkpoints) by Hyung Won Chung, Le Hou, Shayne Longpre, Barret Zoph, Yi Tay, William Fedus, Eric Li, Xuezhi Wang, Mostafa Dehghani, Siddhartha Brahma, Albert Webson, Shixiang Shane Gu, Zhuyun Dai, Mirac Suzgun, Xinyun Chen, Aakanksha Chowdhery, Sharan Narang, Gaurav Mishra, Adams Yu, Vincent Zhao, Yanping Huang, Andrew Dai, Hongkun Yu, Slav Petrov, Ed H. Chi, Jeff Dean, Jacob Devlin, Adam Roberts, Denny Zhou, Quoc V. Le, and Jason Wei
120
+ 1. **[FLAN-UL2](model_doc/flan-ul2)** (from Google AI) released in the repository [google-research/t5x](https://github.com/google-research/t5x/blob/main/docs/models.md#flan-ul2-checkpoints) by Hyung Won Chung, Le Hou, Shayne Longpre, Barret Zoph, Yi Tay, William Fedus, Eric Li, Xuezhi Wang, Mostafa Dehghani, Siddhartha Brahma, Albert Webson, Shixiang Shane Gu, Zhuyun Dai, Mirac Suzgun, Xinyun Chen, Aakanksha Chowdhery, Sharan Narang, Gaurav Mishra, Adams Yu, Vincent Zhao, Yanping Huang, Andrew Dai, Hongkun Yu, Slav Petrov, Ed H. Chi, Jeff Dean, Jacob Devlin, Adam Roberts, Denny Zhou, Quoc V. Le, and Jason Wei
121
+ 1. **[FlauBERT](model_doc/flaubert)** (from CNRS) released with the paper [FlauBERT: Unsupervised Language Model Pre-training for French](https://huggingface.co/papers/1912.05372) by Hang Le, Loïc Vial, Jibril Frej, Vincent Segonne, Maximin Coavoux, Benjamin Lecouteux, Alexandre Allauzen, Benoît Crabbé, Laurent Besacier, Didier Schwab.
122
+ 1. **[FLAVA](model_doc/flava)** (from Facebook AI) released with the paper [FLAVA: A Foundational Language And Vision Alignment Model](https://huggingface.co/papers/2112.04482) by Amanpreet Singh, Ronghang Hu, Vedanuj Goswami, Guillaume Couairon, Wojciech Galuba, Marcus Rohrbach, and Douwe Kiela.
123
+ 1. **[FNet](model_doc/fnet)** (from Google Research) released with the paper [FNet: Mixing Tokens with Fourier Transforms](https://huggingface.co/papers/2105.03824) by James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon.
124
+ 1. **[FocalNet](model_doc/focalnet)** (from Microsoft Research) released with the paper [Focal Modulation Networks](https://huggingface.co/papers/2203.11926) by Jianwei Yang, Chunyuan Li, Xiyang Dai, Lu Yuan, Jianfeng Gao.
125
+ 1. **[Funnel Transformer](model_doc/funnel)** (from CMU/Google Brain) released with the paper [Funnel-Transformer: Filtering out Sequential Redundancy for Efficient Language Processing](https://huggingface.co/papers/2006.03236) by Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le.
126
+ 1. **[GIT](model_doc/git)** (from Microsoft Research) released with the paper [GIT: A Generative Image-to-text Transformer for Vision and Language](https://huggingface.co/papers/2205.14100) by Jianfeng Wang, Zhengyuan Yang, Xiaowei Hu, Linjie Li, Kevin Lin, Zhe Gan, Zicheng Liu, Ce Liu, Lijuan Wang.
127
+ 1. **[GLPN](model_doc/glpn)** (from KAIST) released with the paper [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://huggingface.co/papers/2201.07436) by Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim.
128
+ 1. **[GPT](model_doc/openai-gpt)** (from OpenAI) released with the paper [Improving Language Understanding by Generative Pre-Training](https://openai.com/research/language-unsupervised/) by Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever.
129
+ 1. **[GPT Neo](model_doc/gpt_neo)** (from EleutherAI) released in the repository [EleutherAI/gpt-neo](https://github.com/EleutherAI/gpt-neo) by Sid Black, Stella Biderman, Leo Gao, Phil Wang and Connor Leahy.
130
+ 1. **[GPT NeoX](model_doc/gpt_neox)** (from EleutherAI) released with the paper [GPT-NeoX-20B: An Open-Source Autoregressive Language Model](https://huggingface.co/papers/2204.06745) by Sid Black, Stella Biderman, Eric Hallahan, Quentin Anthony, Leo Gao, Laurence Golding, Horace He, Connor Leahy, Kyle McDonell, Jason Phang, Michael Pieler, USVSN Sai Prashanth, Shivanshu Purohit, Laria Reynolds, Jonathan Tow, Ben Wang, Samuel Weinbach
131
+ 1. **[GPT NeoX Japanese](model_doc/gpt_neox_japanese)** (from ABEJA) released by Shinya Otani, Takayoshi Makabe, Anuj Arora, and Kyo Hattori.
132
+ 1. **[GPT-2](model_doc/gpt2)** (from OpenAI) released with the paper [Language Models are Unsupervised Multitask Learners](https://openai.com/research/better-language-models/) by Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei and Ilya Sutskever.
133
+ 1. **[GPT-J](model_doc/gptj)** (from EleutherAI) released in the repository [kingoflolz/mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax/) by Ben Wang and Aran Komatsuzaki.
134
+ 1. **[GPT-Sw3](model_doc/gpt-sw3)** (from AI-Sweden) released with the paper [Lessons Learned from GPT-SW3: Building the First Large-Scale Generative Language Model for Swedish](http://www.lrec-conf.org/proceedings/lrec2022/pdf/2022.lrec-1.376.pdf) by Ariel Ekgren, Amaru Cuba Gyllensten, Evangelia Gogoulou, Alice Heiman, Severine Verlinden, Joey Öhman, Fredrik Carlsson, Magnus Sahlgren.
135
+ 1. **[GPTBigCode](model_doc/gpt_bigcode)** (from BigCode) released with the paper [SantaCoder: don't reach for the stars!](https://huggingface.co/papers/2301.03988) by Loubna Ben Allal, Raymond Li, Denis Kocetkov, Chenghao Mou, Christopher Akiki, Carlos Munoz Ferrandis, Niklas Muennighoff, Mayank Mishra, Alex Gu, Manan Dey, Logesh Kumar Umapathi, Carolyn Jane Anderson, Yangtian Zi, Joel Lamy Poirier, Hailey Schoelkopf, Sergey Troshin, Dmitry Abulkhanov, Manuel Romero, Michael Lappert, Francesco De Toni, Bernardo García del Río, Qian Liu, Shamik Bose, Urvashi Bhattacharyya, Terry Yue Zhuo, Ian Yu, Paulo Villegas, Marco Zocca, Sourab Mangrulkar, David Lansky, Huu Nguyen, Danish Contractor, Luis Villa, Jia Li, Dzmitry Bahdanau, Yacine Jernite, Sean Hughes, Daniel Fried, Arjun Guha, Harm de Vries, Leandro von Werra.
136
+ 1. **[GPTSAN-japanese](model_doc/gptsan-japanese)** released in the repository [tanreinama/GPTSAN](https://github.com/tanreinama/GPTSAN/blob/main/report/model.md) by Toshiyuki Sakamoto(tanreinama).
137
+ 1. **[Graphormer](model_doc/graphormer)** (from Microsoft) released with the paper [Do Transformers Really Perform Bad for Graph Representation?](https://huggingface.co/papers/2106.05234) by Chengxuan Ying, Tianle Cai, Shengjie Luo, Shuxin Zheng, Guolin Ke, Di He, Yanming Shen, Tie-Yan Liu.
138
+ 1. **[GroupViT](model_doc/groupvit)** (from UCSD, NVIDIA) released with the paper [GroupViT: Semantic Segmentation Emerges from Text Supervision](https://huggingface.co/papers/2202.11094) by Jiarui Xu, Shalini De Mello, Sifei Liu, Wonmin Byeon, Thomas Breuel, Jan Kautz, Xiaolong Wang.
139
+ 1. **[Hubert](model_doc/hubert)** (from Facebook) released with the paper [HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units](https://huggingface.co/papers/2106.07447) by Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed.
140
+ 1. **[I-BERT](model_doc/ibert)** (from Berkeley) released with the paper [I-BERT: Integer-only BERT Quantization](https://huggingface.co/papers/2101.01321) by Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney, Kurt Keutzer.
141
+ 1. **[ImageGPT](model_doc/imagegpt)** (from OpenAI) released with the paper [Generative Pretraining from Pixels](https://openai.com/blog/image-gpt/) by Mark Chen, Alec Radford, Rewon Child, Jeffrey Wu, Heewoo Jun, David Luan, Ilya Sutskever.
142
+ 1. **[Informer](model_doc/informer)** (from Beihang University, UC Berkeley, Rutgers University, SEDD Company) released with the paper [Informer: Beyond Efficient Transformer for Long Sequence Time-Series Forecasting](https://huggingface.co/papers/2012.07436) by Haoyi Zhou, Shanghang Zhang, Jieqi Peng, Shuai Zhang, Jianxin Li, Hui Xiong, and Wancai Zhang.
143
+ 1. **[Jukebox](model_doc/jukebox)** (from OpenAI) released with the paper [Jukebox: A Generative Model for Music](https://huggingface.co/papers/2005.00341) by Prafulla Dhariwal, Heewoo Jun, Christine Payne, Jong Wook Kim, Alec Radford, Ilya Sutskever.
144
+ 1. **[LayoutLM](model_doc/layoutlm)** (from Microsoft Research Asia) released with the paper [LayoutLM: Pre-training of Text and Layout for Document Image Understanding](https://huggingface.co/papers/1912.13318) by Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou.
145
+ 1. **[LayoutLMv2](model_doc/layoutlmv2)** (from Microsoft Research Asia) released with the paper [LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding](https://huggingface.co/papers/2012.14740) by Yang Xu, Yiheng Xu, Tengchao Lv, Lei Cui, Furu Wei, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Wanxiang Che, Min Zhang, Lidong Zhou.
146
+ 1. **[LayoutLMv3](model_doc/layoutlmv3)** (from Microsoft Research Asia) released with the paper [LayoutLMv3: Pre-training for Document AI with Unified Text and Image Masking](https://huggingface.co/papers/2204.08387) by Yupan Huang, Tengchao Lv, Lei Cui, Yutong Lu, Furu Wei.
147
+ 1. **[LayoutXLM](model_doc/layoutxlm)** (from Microsoft Research Asia) released with the paper [LayoutXLM: Multimodal Pre-training for Multilingual Visually-rich Document Understanding](https://huggingface.co/papers/2104.08836) by Yiheng Xu, Tengchao Lv, Lei Cui, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Furu Wei.
148
+ 1. **[LED](model_doc/led)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://huggingface.co/papers/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
149
+ 1. **[LeViT](model_doc/levit)** (from Meta AI) released with the paper [LeViT: A Vision Transformer in ConvNet's Clothing for Faster Inference](https://huggingface.co/papers/2104.01136) by Ben Graham, Alaaeldin El-Nouby, Hugo Touvron, Pierre Stock, Armand Joulin, Hervé Jégou, Matthijs Douze.
150
+ 1. **[LiLT](model_doc/lilt)** (from South China University of Technology) released with the paper [LiLT: A Simple yet Effective Language-Independent Layout Transformer for Structured Document Understanding](https://huggingface.co/papers/2202.13669) by Jiapeng Wang, Lianwen Jin, Kai Ding.
151
+ 1. **[LLaMA](model_doc/llama)** (from The FAIR team of Meta AI) released with the paper [LLaMA: Open and Efficient Foundation Language Models](https://huggingface.co/papers/2302.13971) by Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier Martinet, Marie-Anne Lachaux, Timothée Lacroix, Baptiste Rozière, Naman Goyal, Eric Hambro, Faisal Azhar, Aurelien Rodriguez, Armand Joulin, Edouard Grave, Guillaume Lample.
152
+ 1. **[Longformer](model_doc/longformer)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://huggingface.co/papers/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
153
+ 1. **[LongT5](model_doc/longt5)** (from Google AI) released with the paper [LongT5: Efficient Text-To-Text Transformer for Long Sequences](https://huggingface.co/papers/2112.07916) by Mandy Guo, Joshua Ainslie, David Uthus, Santiago Ontanon, Jianmo Ni, Yun-Hsuan Sung, Yinfei Yang.
154
+ 1. **[LUKE](model_doc/luke)** (from Studio Ousia) released with the paper [LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention](https://huggingface.co/papers/2010.01057) by Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda, Yuji Matsumoto.
155
+ 1. **[LXMERT](model_doc/lxmert)** (from UNC Chapel Hill) released with the paper [LXMERT: Learning Cross-Modality Encoder Representations from Transformers for Open-Domain Question Answering](https://huggingface.co/papers/1908.07490) by Hao Tan and Mohit Bansal.
156
+ 1. **[M-CTC-T](model_doc/mctct)** (from Facebook) released with the paper [Pseudo-Labeling For Massively Multilingual Speech Recognition](https://huggingface.co/papers/2111.00161) by Loren Lugosch, Tatiana Likhomanenko, Gabriel Synnaeve, and Ronan Collobert.
157
+ 1. **[M2M100](model_doc/m2m_100)** (from Facebook) released with the paper [Beyond English-Centric Multilingual Machine Translation](https://huggingface.co/papers/2010.11125) by Angela Fan, Shruti Bhosale, Holger Schwenk, Zhiyi Ma, Ahmed El-Kishky, Siddharth Goyal, Mandeep Baines, Onur Celebi, Guillaume Wenzek, Vishrav Chaudhary, Naman Goyal, Tom Birch, Vitaliy Liptchinsky, Sergey Edunov, Edouard Grave, Michael Auli, Armand Joulin.
158
+ 1. **[MarianMT](model_doc/marian)** Machine translation models trained using [OPUS](http://opus.nlpl.eu/) data by Jörg Tiedemann. The [Marian Framework](https://marian-nmt.github.io/) is being developed by the Microsoft Translator Team.
159
+ 1. **[MarkupLM](model_doc/markuplm)** (from Microsoft Research Asia) released with the paper [MarkupLM: Pre-training of Text and Markup Language for Visually-rich Document Understanding](https://huggingface.co/papers/2110.08518) by Junlong Li, Yiheng Xu, Lei Cui, Furu Wei.
160
+ 1. **[Mask2Former](model_doc/mask2former)** (from FAIR and UIUC) released with the paper [Masked-attention Mask Transformer for Universal Image Segmentation](https://huggingface.co/papers/2112.01527) by Bowen Cheng, Ishan Misra, Alexander G. Schwing, Alexander Kirillov, Rohit Girdhar.
161
+ 1. **[MaskFormer](model_doc/maskformer)** (from Meta and UIUC) released with the paper [Per-Pixel Classification is Not All You Need for Semantic Segmentation](https://huggingface.co/papers/2107.06278) by Bowen Cheng, Alexander G. Schwing, Alexander Kirillov.
162
+ 1. **[MatCha](model_doc/matcha)** (from Google AI) released with the paper [MatCha: Enhancing Visual Language Pretraining with Math Reasoning and Chart Derendering](https://huggingface.co/papers/2212.09662) by Fangyu Liu, Francesco Piccinno, Syrine Krichene, Chenxi Pang, Kenton Lee, Mandar Joshi, Yasemin Altun, Nigel Collier, Julian Martin Eisenschlos.
163
+ 1. **[mBART](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Denoising Pre-training for Neural Machine Translation](https://huggingface.co/papers/2001.08210) by Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer.
164
+ 1. **[mBART-50](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Translation with Extensible Multilingual Pretraining and Finetuning](https://huggingface.co/papers/2008.00401) by Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan.
165
+ 1. **[MEGA](model_doc/mega)** (from Meta/USC/CMU/SJTU) released with the paper [Mega: Moving Average Equipped Gated Attention](https://huggingface.co/papers/2209.10655) by Xuezhe Ma, Chunting Zhou, Xiang Kong, Junxian He, Liangke Gui, Graham Neubig, Jonathan May, and Luke Zettlemoyer.
166
+ 1. **[Megatron-BERT](model_doc/megatron-bert)** (from NVIDIA) released with the paper [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://huggingface.co/papers/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
167
+ 1. **[Megatron-GPT2](model_doc/megatron_gpt2)** (from NVIDIA) released with the paper [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://huggingface.co/papers/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
168
+ 1. **[MGP-STR](model_doc/mgp-str)** (from Alibaba Research) released with the paper [Multi-Granularity Prediction for Scene Text Recognition](https://huggingface.co/papers/2209.03592) by Peng Wang, Cheng Da, and Cong Yao.
169
+ 1. **[mLUKE](model_doc/mluke)** (from Studio Ousia) released with the paper [mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models](https://huggingface.co/papers/2110.08151) by Ryokan Ri, Ikuya Yamada, and Yoshimasa Tsuruoka.
170
+ 1. **[MobileBERT](model_doc/mobilebert)** (from CMU/Google Brain) released with the paper [MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited Devices](https://huggingface.co/papers/2004.02984) by Zhiqing Sun, Hongkun Yu, Xiaodan Song, Renjie Liu, Yiming Yang, and Denny Zhou.
171
+ 1. **[MobileNetV1](model_doc/mobilenet_v1)** (from Google Inc.) released with the paper [MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications](https://huggingface.co/papers/1704.04861) by Andrew G. Howard, Menglong Zhu, Bo Chen, Dmitry Kalenichenko, Weijun Wang, Tobias Weyand, Marco Andreetto, Hartwig Adam.
172
+ 1. **[MobileNetV2](model_doc/mobilenet_v2)** (from Google Inc.) released with the paper [MobileNetV2: Inverted Residuals and Linear Bottlenecks](https://huggingface.co/papers/1801.04381) by Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen.
173
+ 1. **[MobileViT](model_doc/mobilevit)** (from Apple) released with the paper [MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer](https://huggingface.co/papers/2110.02178) by Sachin Mehta and Mohammad Rastegari.
174
+ 1. **[MPNet](model_doc/mpnet)** (from Microsoft Research) released with the paper [MPNet: Masked and Permuted Pre-training for Language Understanding](https://huggingface.co/papers/2004.09297) by Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu.
175
+ 1. **[MT5](model_doc/mt5)** (from Google AI) released with the paper [mT5: A massively multilingual pre-trained text-to-text transformer](https://huggingface.co/papers/2010.11934) by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel.
176
+ 1. **[MVP](model_doc/mvp)** (from RUC AI Box) released with the paper [MVP: Multi-task Supervised Pre-training for Natural Language Generation](https://huggingface.co/papers/2206.12131) by Tianyi Tang, Junyi Li, Wayne Xin Zhao and Ji-Rong Wen.
177
+ 1. **[NAT](model_doc/nat)** (from SHI Labs) released with the paper [Neighborhood Attention Transformer](https://huggingface.co/papers/2204.07143) by Ali Hassani, Steven Walton, Jiachen Li, Shen Li, and Humphrey Shi.
178
+ 1. **[Nezha](model_doc/nezha)** (from Huawei Noah’s Ark Lab) released with the paper [NEZHA: Neural Contextualized Representation for Chinese Language Understanding](https://huggingface.co/papers/1909.00204) by Junqiu Wei, Xiaozhe Ren, Xiaoguang Li, Wenyong Huang, Yi Liao, Yasheng Wang, Jiashu Lin, Xin Jiang, Xiao Chen and Qun Liu.
179
+ 1. **[NLLB](model_doc/nllb)** (from Meta) released with the paper [No Language Left Behind: Scaling Human-Centered Machine Translation](https://huggingface.co/papers/2207.04672) by the NLLB team.
180
+ 1. **[NLLB-MOE](model_doc/nllb-moe)** (from Meta) released with the paper [No Language Left Behind: Scaling Human-Centered Machine Translation](https://huggingface.co/papers/2207.04672) by the NLLB team.
181
+ 1. **[Nyströmformer](model_doc/nystromformer)** (from the University of Wisconsin - Madison) released with the paper [Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention](https://huggingface.co/papers/2102.03902) by Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh.
182
+ 1. **[OneFormer](model_doc/oneformer)** (from SHI Labs) released with the paper [OneFormer: One Transformer to Rule Universal Image Segmentation](https://huggingface.co/papers/2211.06220) by Jitesh Jain, Jiachen Li, MangTik Chiu, Ali Hassani, Nikita Orlov, Humphrey Shi.
183
+ 1. **[OpenLlama](model_doc/open-llama)** (from [s-JoL](https://huggingface.co/s-JoL)) released on GitHub (now removed).
184
+ 1. **[OPT](master/model_doc/opt)** (from Meta AI) released with the paper [OPT: Open Pre-trained Transformer Language Models](https://huggingface.co/papers/2205.01068) by Susan Zhang, Stephen Roller, Naman Goyal, Mikel Artetxe, Moya Chen, Shuohui Chen et al.
185
+ 1. **[OWL-ViT](model_doc/owlvit)** (from Google AI) released with the paper [Simple Open-Vocabulary Object Detection with Vision Transformers](https://huggingface.co/papers/2205.06230) by Matthias Minderer, Alexey Gritsenko, Austin Stone, Maxim Neumann, Dirk Weissenborn, Alexey Dosovitskiy, Aravindh Mahendran, Anurag Arnab, Mostafa Dehghani, Zhuoran Shen, Xiao Wang, Xiaohua Zhai, Thomas Kipf, and Neil Houlsby.
186
+ 1. **[Pegasus](model_doc/pegasus)** (from Google) released with the paper [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://huggingface.co/papers/1912.08777) by Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu.
187
+ 1. **[PEGASUS-X](model_doc/pegasus_x)** (from Google) released with the paper [Investigating Efficiently Extending Transformers for Long Input Summarization](https://huggingface.co/papers/2208.04347) by Jason Phang, Yao Zhao, and Peter J. Liu.
188
+ 1. **[Perceiver IO](model_doc/perceiver)** (from Deepmind) released with the paper [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://huggingface.co/papers/2107.14795) by Andrew Jaegle, Sebastian Borgeaud, Jean-Baptiste Alayrac, Carl Doersch, Catalin Ionescu, David Ding, Skanda Koppula, Daniel Zoran, Andrew Brock, Evan Shelhamer, Olivier Hénaff, Matthew M. Botvinick, Andrew Zisserman, Oriol Vinyals, João Carreira.
189
+ 1. **[PhoBERT](model_doc/phobert)** (from VinAI Research) released with the paper [PhoBERT: Pre-trained language models for Vietnamese](https://www.aclweb.org/anthology/2020.findings-emnlp.92/) by Dat Quoc Nguyen and Anh Tuan Nguyen.
190
+ 1. **[Pix2Struct](model_doc/pix2struct)** (from Google) released with the paper [Pix2Struct: Screenshot Parsing as Pretraining for Visual Language Understanding](https://huggingface.co/papers/2210.03347) by Kenton Lee, Mandar Joshi, Iulia Turc, Hexiang Hu, Fangyu Liu, Julian Eisenschlos, Urvashi Khandelwal, Peter Shaw, Ming-Wei Chang, Kristina Toutanova.
191
+ 1. **[PLBart](model_doc/plbart)** (from UCLA NLP) released with the paper [Unified Pre-training for Program Understanding and Generation](https://huggingface.co/papers/2103.06333) by Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang.
192
+ 1. **[PoolFormer](model_doc/poolformer)** (from Sea AI Labs) released with the paper [MetaFormer is Actually What You Need for Vision](https://huggingface.co/papers/2111.11418) by Yu, Weihao and Luo, Mi and Zhou, Pan and Si, Chenyang and Zhou, Yichen and Wang, Xinchao and Feng, Jiashi and Yan, Shuicheng.
193
+ 1. **[ProphetNet](model_doc/prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://huggingface.co/papers/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
194
+ 1. **[QDQBert](model_doc/qdqbert)** (from NVIDIA) released with the paper [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://huggingface.co/papers/2004.09602) by Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev and Paulius Micikevicius.
195
+ 1. **[RAG](model_doc/rag)** (from Facebook) released with the paper [Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks](https://huggingface.co/papers/2005.11401) by Patrick Lewis, Ethan Perez, Aleksandara Piktus, Fabio Petroni, Vladimir Karpukhin, Naman Goyal, Heinrich Küttler, Mike Lewis, Wen-tau Yih, Tim Rocktäschel, Sebastian Riedel, Douwe Kiela.
196
+ 1. **[REALM](model_doc/realm.html)** (from Google Research) released with the paper [REALM: Retrieval-Augmented Language Model Pre-Training](https://huggingface.co/papers/2002.08909) by Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang.
197
+ 1. **[Reformer](model_doc/reformer)** (from Google Research) released with the paper [Reformer: The Efficient Transformer](https://huggingface.co/papers/2001.04451) by Nikita Kitaev, Łukasz Kaiser, Anselm Levskaya.
198
+ 1. **[RegNet](model_doc/regnet)** (from META Platforms) released with the paper [Designing Network Design Space](https://huggingface.co/papers/2003.13678) by Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr Dollár.
199
+ 1. **[RemBERT](model_doc/rembert)** (from Google Research) released with the paper [Rethinking embedding coupling in pre-trained language models](https://huggingface.co/papers/2010.12821) by Hyung Won Chung, Thibault Févry, Henry Tsai, M. Johnson, Sebastian Ruder.
200
+ 1. **[ResNet](model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://huggingface.co/papers/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun.
201
+ 1. **[RoBERTa](model_doc/roberta)** (from Facebook), released together with the paper [RoBERTa: A Robustly Optimized BERT Pretraining Approach](https://huggingface.co/papers/1907.11692) by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov.
202
+ 1. **[RoBERTa-PreLayerNorm](model_doc/roberta-prelayernorm)** (from Facebook) released with the paper [fairseq: A Fast, Extensible Toolkit for Sequence Modeling](https://huggingface.co/papers/1904.01038) by Myle Ott, Sergey Edunov, Alexei Baevski, Angela Fan, Sam Gross, Nathan Ng, David Grangier, Michael Auli.
203
+ 1. **[RoCBert](model_doc/roc_bert)** (from WeChatAI) released with the paper [RoCBert: Robust Chinese Bert with Multimodal Contrastive Pretraining](https://aclanthology.org/2022.acl-long.65.pdf) by HuiSu, WeiweiShi, XiaoyuShen, XiaoZhou, TuoJi, JiaruiFang, JieZhou.
204
+ 1. **[RoFormer](model_doc/roformer)** (from ZhuiyiTechnology), released together with the paper [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://huggingface.co/papers/2104.09864) by Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu.
205
+ 1. **[RWKV](model_doc/rwkv)** (from Bo Peng), released on [this repo](https://github.com/BlinkDL/RWKV-LM) by Bo Peng.
206
+ 1. **[SegFormer](model_doc/segformer)** (from NVIDIA) released with the paper [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://huggingface.co/papers/2105.15203) by Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo.
207
+ 1. **[Segment Anything](model_doc/sam)** (from Meta AI) released with the paper [Segment Anything](https://huggingface.co/papers/2304.02643v1.pdf) by Alexander Kirillov, Eric Mintun, Nikhila Ravi, Hanzi Mao, Chloe Rolland, Laura Gustafson, Tete Xiao, Spencer Whitehead, Alex Berg, Wan-Yen Lo, Piotr Dollar, Ross Girshick.
208
+ 1. **[SEW](model_doc/sew)** (from ASAPP) released with the paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://huggingface.co/papers/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
209
+ 1. **[SEW-D](model_doc/sew_d)** (from ASAPP) released with the paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://huggingface.co/papers/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
210
+ 1. **[SpeechT5](model_doc/speecht5)** (from Microsoft Research) released with the paper [SpeechT5: Unified-Modal Encoder-Decoder Pre-Training for Spoken Language Processing](https://huggingface.co/papers/2110.07205) by Junyi Ao, Rui Wang, Long Zhou, Chengyi Wang, Shuo Ren, Yu Wu, Shujie Liu, Tom Ko, Qing Li, Yu Zhang, Zhihua Wei, Yao Qian, Jinyu Li, Furu Wei.
211
+ 1. **[SpeechToTextTransformer](model_doc/speech_to_text)** (from Facebook), released together with the paper [fairseq S2T: Fast Speech-to-Text Modeling with fairseq](https://huggingface.co/papers/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino.
212
+ 1. **[SpeechToTextTransformer2](model_doc/speech_to_text_2)** (from Facebook), released together with the paper [Large-Scale Self- and Semi-Supervised Learning for Speech Translation](https://huggingface.co/papers/2104.06678) by Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau.
213
+ 1. **[Splinter](model_doc/splinter)** (from Tel Aviv University), released together with the paper [Few-Shot Question Answering by Pretraining Span Selection](https://huggingface.co/papers/2101.00438) by Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy.
214
+ 1. **[SqueezeBERT](model_doc/squeezebert)** (from Berkeley) released with the paper [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://huggingface.co/papers/2006.11316) by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer.
215
+ 1. **[SwiftFormer](model_doc/swiftformer)** (from MBZUAI) released with the paper [SwiftFormer: Efficient Additive Attention for Transformer-based Real-time Mobile Vision Applications](https://huggingface.co/papers/2303.15446) by Abdelrahman Shaker, Muhammad Maaz, Hanoona Rasheed, Salman Khan, Ming-Hsuan Yang, Fahad Shahbaz Khan.
216
+ 1. **[Swin Transformer](model_doc/swin)** (from Microsoft) released with the paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://huggingface.co/papers/2103.14030) by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo.
217
+ 1. **[Swin Transformer V2](model_doc/swinv2)** (from Microsoft) released with the paper [Swin Transformer V2: Scaling Up Capacity and Resolution](https://huggingface.co/papers/2111.09883) by Ze Liu, Han Hu, Yutong Lin, Zhuliang Yao, Zhenda Xie, Yixuan Wei, Jia Ning, Yue Cao, Zheng Zhang, Li Dong, Furu Wei, Baining Guo.
218
+ 1. **[Swin2SR](model_doc/swin2sr)** (from University of Würzburg) released with the paper [Swin2SR: SwinV2 Transformer for Compressed Image Super-Resolution and Restoration](https://huggingface.co/papers/2209.11345) by Marcos V. Conde, Ui-Jin Choi, Maxime Burchi, Radu Timofte.
219
+ 1. **[SwitchTransformers](model_doc/switch_transformers)** (from Google) released with the paper [Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity](https://huggingface.co/papers/2101.03961) by William Fedus, Barret Zoph, Noam Shazeer.
220
+ 1. **[T5](model_doc/t5)** (from Google AI) released with the paper [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://huggingface.co/papers/1910.10683) by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu.
221
+ 1. **[T5v1.1](model_doc/t5v1.1)** (from Google AI) released in the repository [google-research/text-to-text-transfer-transformer](https://github.com/google-research/text-to-text-transfer-transformer/blob/main/released_checkpoints.md#t511) by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu.
222
+ 1. **[Table Transformer](model_doc/table-transformer)** (from Microsoft Research) released with the paper [PubTables-1M: Towards Comprehensive Table Extraction From Unstructured Documents](https://huggingface.co/papers/2110.00061) by Brandon Smock, Rohith Pesala, Robin Abraham.
223
+ 1. **[TAPAS](model_doc/tapas)** (from Google AI) released with the paper [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://huggingface.co/papers/2004.02349) by Jonathan Herzig, Paweł Krzysztof Nowak, Thomas Müller, Francesco Piccinno and Julian Martin Eisenschlos.
224
+ 1. **[TAPEX](model_doc/tapex)** (from Microsoft Research) released with the paper [TAPEX: Table Pre-training via Learning a Neural SQL Executor](https://huggingface.co/papers/2107.07653) by Qian Liu, Bei Chen, Jiaqi Guo, Morteza Ziyadi, Zeqi Lin, Weizhu Chen, Jian-Guang Lou.
225
+ 1. **[Time Series Transformer](model_doc/time_series_transformer)** (from HuggingFace).
226
+ 1. **[TimeSformer](model_doc/timesformer)** (from Facebook) released with the paper [Is Space-Time Attention All You Need for Video Understanding?](https://huggingface.co/papers/2102.05095) by Gedas Bertasius, Heng Wang, Lorenzo Torresani.
227
+ 1. **[Trajectory Transformer](model_doc/trajectory_transformers)** (from the University of California at Berkeley) released with the paper [Offline Reinforcement Learning as One Big Sequence Modeling Problem](https://huggingface.co/papers/2106.02039) by Michael Janner, Qiyang Li, Sergey Levine
228
+ 1. **[Transformer-XL](model_doc/transfo-xl)** (from Google/CMU) released with the paper [Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context](https://huggingface.co/papers/1901.02860) by Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov.
229
+ 1. **[TrOCR](model_doc/trocr)** (from Microsoft), released together with the paper [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://huggingface.co/papers/2109.10282) by Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei.
230
+ 1. **[TVLT](model_doc/tvlt)** (from UNC Chapel Hill) released with the paper [TVLT: Textless Vision-Language Transformer](https://huggingface.co/papers/2209.14156) by Zineng Tang, Jaemin Cho, Yixin Nie, Mohit Bansal.
231
+ 1. **[TVP](model_doc/tvp)** (from Intel) released with the paper [Text-Visual Prompting for Efficient 2D Temporal Video Grounding](https://huggingface.co/papers/2303.04995) by Yimeng Zhang, Xin Chen, Jinghan Jia, Sijia Liu, Ke Ding.
232
+ 1. **[UL2](model_doc/ul2)** (from Google Research) released with the paper [Unifying Language Learning Paradigms](https://huggingface.co/papers/2205.05131v1) by Yi Tay, Mostafa Dehghani, Vinh Q. Tran, Xavier Garcia, Dara Bahri, Tal Schuster, Huaixiu Steven Zheng, Neil Houlsby, Donald Metzler
233
+ 1. **[UniSpeech](model_doc/unispeech)** (from Microsoft Research) released with the paper [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://huggingface.co/papers/2101.07597) by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang.
234
+ 1. **[UniSpeechSat](model_doc/unispeech-sat)** (from Microsoft Research) released with the paper [UNISPEECH-SAT: UNIVERSAL SPEECH REPRESENTATION LEARNING WITH SPEAKER AWARE PRE-TRAINING](https://huggingface.co/papers/2110.05752) by Sanyuan Chen, Yu Wu, Chengyi Wang, Zhengyang Chen, Zhuo Chen, Shujie Liu, Jian Wu, Yao Qian, Furu Wei, Jinyu Li, Xiangzhan Yu.
235
+ 1. **[UPerNet](model_doc/upernet)** (from Peking University) released with the paper [Unified Perceptual Parsing for Scene Understanding](https://huggingface.co/papers/1807.10221) by Tete Xiao, Yingcheng Liu, Bolei Zhou, Yuning Jiang, Jian Sun.
236
+ 1. **[VAN](model_doc/van)** (from Tsinghua University and Nankai University) released with the paper [Visual Attention Network](https://huggingface.co/papers/2202.09741) by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu.
237
+ 1. **[VideoMAE](model_doc/videomae)** (from Multimedia Computing Group, Nanjing University) released with the paper [VideoMAE: Masked Autoencoders are Data-Efficient Learners for Self-Supervised Video Pre-Training](https://huggingface.co/papers/2203.12602) by Zhan Tong, Yibing Song, Jue Wang, Limin Wang.
238
+ 1. **[ViLT](model_doc/vilt)** (from NAVER AI Lab/Kakao Enterprise/Kakao Brain) released with the paper [ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision](https://huggingface.co/papers/2102.03334) by Wonjae Kim, Bokyung Son, Ildoo Kim.
239
+ 1. **[Vision Transformer (ViT)](model_doc/vit)** (from Google AI) released with the paper [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://huggingface.co/papers/2010.11929) by Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby.
240
+ 1. **[VisualBERT](model_doc/visual_bert)** (from UCLA NLP) released with the paper [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://huggingface.co/papers/1908.03557) by Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang.
241
+ 1. **[ViT Hybrid](model_doc/vit_hybrid)** (from Google AI) released with the paper [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://huggingface.co/papers/2010.11929) by Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby.
242
+ 1. **[ViTMAE](model_doc/vit_mae)** (from Meta AI) released with the paper [Masked Autoencoders Are Scalable Vision Learners](https://huggingface.co/papers/2111.06377) by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr Dollár, Ross Girshick.
243
+ 1. **[ViTMSN](model_doc/vit_msn)** (from Meta AI) released with the paper [Masked Siamese Networks for Label-Efficient Learning](https://huggingface.co/papers/2204.07141) by Mahmoud Assran, Mathilde Caron, Ishan Misra, Piotr Bojanowski, Florian Bordes, Pascal Vincent, Armand Joulin, Michael Rabbat, Nicolas Ballas.
244
+ 1. **[Wav2Vec2](model_doc/wav2vec2)** (from Facebook AI) released with the paper [wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations](https://huggingface.co/papers/2006.11477) by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli.
245
+ 1. **[Wav2Vec2-Conformer](model_doc/wav2vec2-conformer)** (from Facebook AI) released with the paper [FAIRSEQ S2T: Fast Speech-to-Text Modeling with FAIRSEQ](https://huggingface.co/papers/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Sravya Popuri, Dmytro Okhonko, Juan Pino.
246
+ 1. **[Wav2Vec2Phoneme](model_doc/wav2vec2_phoneme)** (from Facebook AI) released with the paper [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://huggingface.co/papers/2109.11680) by Qiantong Xu, Alexei Baevski, Michael Auli.
247
+ 1. **[WavLM](model_doc/wavlm)** (from Microsoft Research) released with the paper [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://huggingface.co/papers/2110.13900) by Sanyuan Chen, Chengyi Wang, Zhengyang Chen, Yu Wu, Shujie Liu, Zhuo Chen, Jinyu Li, Naoyuki Kanda, Takuya Yoshioka, Xiong Xiao, Jian Wu, Long Zhou, Shuo Ren, Yanmin Qian, Yao Qian, Jian Wu, Michael Zeng, Furu Wei.
248
+ 1. **[Whisper](model_doc/whisper)** (from OpenAI) released with the paper [Robust Speech Recognition via Large-Scale Weak Supervision](https://cdn.openai.com/papers/whisper.pdf) by Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey, Ilya Sutskever.
249
+ 1. **[X-CLIP](model_doc/xclip)** (from Microsoft Research) released with the paper [Expanding Language-Image Pretrained Models for General Video Recognition](https://huggingface.co/papers/2208.02816) by Bolin Ni, Houwen Peng, Minghao Chen, Songyang Zhang, Gaofeng Meng, Jianlong Fu, Shiming Xiang, Haibin Ling.
250
+ 1. **[X-MOD](model_doc/xmod)** (from Meta AI) released with the paper [Lifting the Curse of Multilinguality by Pre-training Modular Transformers](http://dx.doi.org/10.18653/v1/2022.naacl-main.255) by Jonas Pfeiffer, Naman Goyal, Xi Lin, Xian Li, James Cross, Sebastian Riedel, Mikel Artetxe.
251
+ 1. **[XGLM](model_doc/xglm)** (From Facebook AI) released with the paper [Few-shot Learning with Multilingual Language Models](https://huggingface.co/papers/2112.10668) by Xi Victoria Lin, Todor Mihaylov, Mikel Artetxe, Tianlu Wang, Shuohui Chen, Daniel Simig, Myle Ott, Naman Goyal, Shruti Bhosale, Jingfei Du, Ramakanth Pasunuru, Sam Shleifer, Punit Singh Koura, Vishrav Chaudhary, Brian O'Horo, Jeff Wang, Luke Zettlemoyer, Zornitsa Kozareva, Mona Diab, Veselin Stoyanov, Xian Li.
252
+ 1. **[XLM](model_doc/xlm)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://huggingface.co/papers/1901.07291) by Guillaume Lample and Alexis Conneau.
253
+ 1. **[XLM-ProphetNet](model_doc/xlm-prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://huggingface.co/papers/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
254
+ 1. **[XLM-RoBERTa](model_doc/xlm-roberta)** (from Facebook AI), released together with the paper [Unsupervised Cross-lingual Representation Learning at Scale](https://huggingface.co/papers/1911.02116) by Alexis Conneau*, Kartikay Khandelwal*, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco Guzmán, Edouard Grave, Myle Ott, Luke Zettlemoyer and Veselin Stoyanov.
255
+ 1. **[XLM-RoBERTa-XL](model_doc/xlm-roberta-xl)** (from Facebook AI), released together with the paper [Larger-Scale Transformers for Multilingual Masked Language Modeling](https://huggingface.co/papers/2105.00572) by Naman Goyal, Jingfei Du, Myle Ott, Giri Anantharaman, Alexis Conneau.
256
+ 1. **[XLM-V](model_doc/xlm-v)** (from Meta AI) released with the paper [XLM-V: Overcoming the Vocabulary Bottleneck in Multilingual Masked Language Models](https://huggingface.co/papers/2301.10472) by Davis Liang, Hila Gonen, Yuning Mao, Rui Hou, Naman Goyal, Marjan Ghazvininejad, Luke Zettlemoyer, Madian Khabsa.
257
+ 1. **[XLNet](model_doc/xlnet)** (from Google/CMU) released with the paper [​XLNet: Generalized Autoregressive Pretraining for Language Understanding](https://huggingface.co/papers/1906.08237) by Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le.
258
+ 1. **[XLS-R](model_doc/xls_r)** (from Facebook AI) released with the paper [XLS-R: Self-supervised Cross-lingual Speech Representation Learning at Scale](https://huggingface.co/papers/2111.09296) by Arun Babu, Changhan Wang, Andros Tjandra, Kushal Lakhotia, Qiantong Xu, Naman Goyal, Kritika Singh, Patrick von Platen, Yatharth Saraf, Juan Pino, Alexei Baevski, Alexis Conneau, Michael Auli.
259
+ 1. **[XLSR-Wav2Vec2](model_doc/xlsr_wav2vec2)** (from Facebook AI) released with the paper [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://huggingface.co/papers/2006.13979) by Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli.
260
+ 1. **[YOLOS](model_doc/yolos)** (from Huazhong University of Science & Technology) released with the paper [You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection](https://huggingface.co/papers/2106.00666) by Yuxin Fang, Bencheng Liao, Xinggang Wang, Jiemin Fang, Jiyang Qi, Rui Wu, Jianwei Niu, Wenyu Liu.
261
+ 1. **[YOSO](model_doc/yoso)** (from the University of Wisconsin - Madison) released with the paper [You Only Sample (Almost) Once: Linear Cost Self-Attention Via Bernoulli Sampling](https://huggingface.co/papers/2111.09714) by Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh.
262
+
263
+
264
+ ### Rangka kerja yang disokong
265
+
266
+ Jadual di bawah mewakili sokongan semasa dalam perpustakaan untuk setiap model tersebut, sama ada model tersebut mempunyai Python
267
+ tokenizer (dipanggil ""lambat""). Tokenizer ""pantas"" yang disokong oleh perpustakaan Tokenizers 🤗, sama ada mereka mempunyai sokongan dalam Jax (melalui
268
+ Flax), PyTorch, dan/atau TensorFlow.
269
+
270
+ <!--Jadual ini dikemas kini secara automatik daripada modul auto dengan _make fix-copies_. Jangan kemas kini secara manual!-->
271
+
272
+ | Model | Tokenizer slow | Tokenizer fast | PyTorch support | TensorFlow support | Flax Support |
273
+ |:-----------------------------:|:--------------:|:--------------:|:---------------:|:------------------:|:------------:|
274
+ | ALBERT | ✅ | ✅ | ✅ | ✅ | ✅ |
275
+ | ALIGN | ❌ | ❌ | ✅ | ❌ | ❌ |
276
+ | AltCLIP | ❌ | ❌ | ✅ | ❌ | ❌ |
277
+ | Audio Spectrogram Transformer | ❌ | ❌ | ✅ | ❌ | ❌ |
278
+ | Autoformer | ❌ | ❌ | ✅ | ❌ | ❌ |
279
+ | BART | ✅ | ✅ | ✅ | ✅ | ✅ |
280
+ | BEiT | ❌ | ❌ | ✅ | ❌ | ✅ |
281
+ | BERT | ✅ | ✅ | ✅ | ✅ | ✅ |
282
+ | Bert Generation | ✅ | ❌ | ✅ | ❌ | ❌ |
283
+ | BigBird | ✅ | ✅ | ✅ | ❌ | ✅ |
284
+ | BigBird-Pegasus | ❌ | ❌ | ✅ | ❌ | ❌ |
285
+ | BioGpt | ✅ | ❌ | ✅ | ❌ | ❌ |
286
+ | BiT | ❌ | ❌ | ✅ | ❌ | ❌ |
287
+ | Blenderbot | ✅ | ✅ | ✅ | ✅ | ✅ |
288
+ | BlenderbotSmall | ✅ | ✅ | ✅ | ✅ | ✅ |
289
+ | BLIP | ❌ | ❌ | ✅ | ✅ | ❌ |
290
+ | BLIP-2 | ❌ | ❌ | ✅ | ❌ | ❌ |
291
+ | BLOOM | ❌ | ✅ | ✅ | ❌ | ❌ |
292
+ | BridgeTower | ❌ | ❌ | ✅ | ❌ | ❌ |
293
+ | Bros | ✅ | ✅ | ✅ | ❌ | ❌ |
294
+ | CamemBERT | ✅ | ✅ | ✅ | ✅ | ❌ |
295
+ | CANINE | ✅ | ❌ | ✅ | ❌ | ❌ |
296
+ | Chinese-CLIP | ❌ | ❌ | ✅ | ❌ | ❌ |
297
+ | CLAP | ❌ | ❌ | ✅ | ❌ | ❌ |
298
+ | CLIP | ✅ | ✅ | ✅ | ✅ | ✅ |
299
+ | CLIPSeg | ❌ | ❌ | ✅ | ❌ | ❌ |
300
+ | CodeGen | ✅ | ✅ | ✅ | ❌ | ❌ |
301
+ | Conditional DETR | ❌ | ❌ | ✅ | ❌ | ❌ |
302
+ | ConvBERT | ✅ | ✅ | ✅ | ✅ | ❌ |
303
+ | ConvNeXT | ❌ | ❌ | ✅ | ✅ | ❌ |
304
+ | ConvNeXTV2 | ❌ | ❌ | ✅ | ❌ | ❌ |
305
+ | CPM-Ant | ✅ | ❌ | ✅ | ❌ | ❌ |
306
+ | CTRL | ✅ | ❌ | ✅ | ✅ | ❌ |
307
+ | CvT | ❌ | ❌ | ✅ | ✅ | ❌ |
308
+ | Data2VecAudio | ❌ | ❌ | ✅ | ❌ | ❌ |
309
+ | Data2VecText | ❌ | ❌ | ✅ | ❌ | ❌ |
310
+ | Data2VecVision | ❌ | ❌ | ✅ | ✅ | ❌ |
311
+ | DeBERTa | ✅ | ✅ | ✅ | ✅ | ❌ |
312
+ | DeBERTa-v2 | ✅ | ✅ | ✅ | ✅ | ❌ |
313
+ | Decision Transformer | ❌ | ❌ | ✅ | ❌ | ❌ |
314
+ | Deformable DETR | ❌ | ❌ | ✅ | ❌ | ❌ |
315
+ | DeiT | ❌ | ❌ | ✅ | ✅ | ❌ |
316
+ | DETA | ❌ | ❌ | ✅ | ❌ | ❌ |
317
+ | DETR | ❌ | ❌ | ✅ | ❌ | ❌ |
318
+ | DiNAT | ❌ | ❌ | ✅ | ❌ | ❌ |
319
+ | DistilBERT | ✅ | ✅ | ✅ | ✅ | ✅ |
320
+ | DonutSwin | ❌ | ❌ | ✅ | ❌ | ❌ |
321
+ | DPR | ✅ | ✅ | ✅ | ✅ | ❌ |
322
+ | DPT | ❌ | ❌ | ✅ | ❌ | ❌ |
323
+ | EfficientFormer | ❌ | ❌ | ✅ | ✅ | ❌ |
324
+ | EfficientNet | ❌ | ❌ | ✅ | ❌ | ❌ |
325
+ | ELECTRA | ✅ | ✅ | ✅ | ✅ | ✅ |
326
+ | Encoder decoder | ❌ | ❌ | ✅ | ✅ | ✅ |
327
+ | ERNIE | ❌ | ❌ | ✅ | ❌ | ❌ |
328
+ | ErnieM | ✅ | ❌ | ✅ | ❌ | ❌ |
329
+ | ESM | ✅ | ❌ | ✅ | ✅ | ❌ |
330
+ | FairSeq Machine-Translation | ✅ | ❌ | ✅ | ❌ | ❌ |
331
+ | FlauBERT | ✅ | ❌ | ✅ | ✅ | ❌ |
332
+ | FLAVA | ❌ | ❌ | ✅ | ❌ | ❌ |
333
+ | FNet | ✅ | ✅ | ✅ | ❌ | ❌ |
334
+ | FocalNet | ❌ | ❌ | ✅ | ❌ | ❌ |
335
+ | Funnel Transformer | ✅ | ✅ | ✅ | ✅ | ❌ |
336
+ | GIT | ❌ | ❌ | ✅ | ❌ | ❌ |
337
+ | GLPN | ❌ | ❌ | ✅ | ❌ | ❌ |
338
+ | GPT Neo | ❌ | ❌ | ✅ | ❌ | ✅ |
339
+ | GPT NeoX | ❌ | ✅ | ✅ | ❌ | ❌ |
340
+ | GPT NeoX Japanese | ✅ | ❌ | ✅ | ❌ | ❌ |
341
+ | GPT-J | ❌ | ❌ | ✅ | ✅ | ✅ |
342
+ | GPT-Sw3 | ✅ | ✅ | ✅ | ✅ | ✅ |
343
+ | GPTBigCode | ❌ | ❌ | ✅ | ❌ | ❌ |
344
+ | GPTSAN-japanese | ✅ | ❌ | ✅ | ❌ | ❌ |
345
+ | Graphormer | ❌ | ❌ | ✅ | ❌ | ❌ |
346
+ | GroupViT | ❌ | ❌ | ✅ | ✅ | ❌ |
347
+ | Hubert | ❌ | ❌ | ✅ | ✅ | ❌ |
348
+ | I-BERT | ❌ | ❌ | ✅ | ❌ | ❌ |
349
+ | ImageGPT | ❌ | ❌ | ✅ | ❌ | ❌ |
350
+ | Informer | ❌ | ❌ | ✅ | ❌ | ❌ |
351
+ | Jukebox | ✅ | ❌ | ✅ | ❌ | ❌ |
352
+ | LayoutLM | ✅ | ✅ | ✅ | ✅ | ❌ |
353
+ | LayoutLMv2 | ✅ | ✅ | ✅ | ❌ | ❌ |
354
+ | LayoutLMv3 | ✅ | ✅ | ✅ | ✅ | ❌ |
355
+ | LED | ✅ | ✅ | ✅ | ✅ | ❌ |
356
+ | LeViT | ❌ | ❌ | ✅ | ❌ | ❌ |
357
+ | LiLT | ❌ | ❌ | ✅ | ❌ | ❌ |
358
+ | LLaMA | ✅ | ✅ | ✅ | ❌ | ❌ |
359
+ | Longformer | ✅ | ✅ | ✅ | ✅ | ❌ |
360
+ | LongT5 | ❌ | ❌ | ✅ | ❌ | ✅ |
361
+ | LUKE | ✅ | ❌ | ✅ | ❌ | ❌ |
362
+ | LXMERT | ✅ | ✅ | ✅ | ✅ | ❌ |
363
+ | M-CTC-T | ❌ | ❌ | ✅ | ❌ | ❌ |
364
+ | M2M100 | ✅ | ❌ | ✅ | ❌ | ❌ |
365
+ | Marian | ✅ | ❌ | ✅ | ✅ | ✅ |
366
+ | MarkupLM | ✅ | ✅ | ✅ | ❌ | ❌ |
367
+ | Mask2Former | ❌ | ❌ | ✅ | ❌ | ❌ |
368
+ | MaskFormer | ❌ | ❌ | ✅ | ❌ | ❌ |
369
+ | MaskFormerSwin | ❌ | ❌ | ❌ | ❌ | ❌ |
370
+ | mBART | ✅ | ✅ | ✅ | ✅ | ✅ |
371
+ | MEGA | ❌ | ❌ | ✅ | ❌ | ❌ |
372
+ | Megatron-BERT | ❌ | ❌ | ✅ | ❌ | ❌ |
373
+ | MGP-STR | ✅ | ❌ | ✅ | ❌ | ❌ |
374
+ | MobileBERT | ✅ | ✅ | ✅ | ✅ | ❌ |
375
+ | MobileNetV1 | ❌ | ❌ | ✅ | ❌ | ❌ |
376
+ | MobileNetV2 | ❌ | ❌ | ✅ | ❌ | ❌ |
377
+ | MobileViT | ❌ | ❌ | ✅ | ✅ | ❌ |
378
+ | MPNet | ✅ | ✅ | ✅ | ✅ | ❌ |
379
+ | MT5 | ✅ | ✅ | ✅ | ✅ | ✅ |
380
+ | MVP | ✅ | ✅ | ✅ | ❌ | ❌ |
381
+ | NAT | ❌ | ❌ | ✅ | ❌ | ❌ |
382
+ | Nezha | ❌ | ❌ | ✅ | ❌ | ❌ |
383
+ | NLLB-MOE | ❌ | ❌ | ✅ | ❌ | ❌ |
384
+ | Nyströmformer | ❌ | ❌ | ✅ | ❌ | ❌ |
385
+ | OneFormer | ❌ | ❌ | ✅ | ❌ | ❌ |
386
+ | OpenAI GPT | ✅ | ✅ | ✅ | ✅ | ❌ |
387
+ | OpenAI GPT-2 | ✅ | ✅ | ✅ | ✅ | ✅ |
388
+ | OpenLlama | ❌ | ❌ | ✅ | ❌ | ❌ |
389
+ | OPT | ❌ | ❌ | ✅ | ✅ | ✅ |
390
+ | OWL-ViT | ❌ | ❌ | ✅ | ❌ | ❌ |
391
+ | Pegasus | ✅ | ✅ | ✅ | ✅ | ✅ |
392
+ | PEGASUS-X | ❌ | ❌ | ✅ | ❌ | ❌ |
393
+ | Perceiver | ✅ | ❌ | ✅ | ❌ | ❌ |
394
+ | Pix2Struct | ❌ | ❌ | ✅ | ❌ | ❌ |
395
+ | PLBart | ✅ | ❌ | ✅ | ❌ | ❌ |
396
+ | PoolFormer | ❌ | ❌ | ✅ | ❌ | ❌ |
397
+ | ProphetNet | ✅ | ❌ | ✅ | ❌ | ❌ |
398
+ | QDQBert | ❌ | ❌ | ✅ | ❌ | ❌ |
399
+ | RAG | ✅ | ❌ | ✅ | ✅ | ❌ |
400
+ | REALM | ✅ | ✅ | ✅ | ❌ | ❌ |
401
+ | Reformer | ✅ | ✅ | ✅ | ❌ | ❌ |
402
+ | RegNet | ❌ | ❌ | ✅ | ✅ | ✅ |
403
+ | RemBERT | ✅ | ✅ | ✅ | ✅ | ❌ |
404
+ | ResNet | ❌ | ❌ | ✅ | ✅ | ✅ |
405
+ | RetriBERT | ✅ | ✅ | ✅ | ❌ | ❌ |
406
+ | RoBERTa | ✅ | ✅ | ✅ | ✅ | ✅ |
407
+ | RoBERTa-PreLayerNorm | ❌ | ❌ | ✅ | ✅ | ✅ |
408
+ | RoCBert | ✅ | ❌ | ✅ | ❌ | ❌ |
409
+ | RoFormer | ✅ | ✅ | ✅ | ✅ | ✅ |
410
+ | RWKV | ❌ | ❌ | ✅ | ❌ | ❌ |
411
+ | SAM | ❌ | ❌ | ✅ | ✅ | ❌ |
412
+ | SegFormer | ❌ | ❌ | ✅ | ✅ | ❌ |
413
+ | SEW | ❌ | ❌ | ✅ | ❌ | ❌ |
414
+ | SEW-D | ❌ | ❌ | ✅ | ❌ | ❌ |
415
+ | Speech Encoder decoder | ❌ | ❌ | ✅ | ❌ | ✅ |
416
+ | Speech2Text | ✅ | ❌ | ✅ | ✅ | ❌ |
417
+ | Speech2Text2 | ✅ | ❌ | ❌ | ❌ | ❌ |
418
+ | SpeechT5 | ✅ | ❌ | ✅ | ❌ | ❌ |
419
+ | Splinter | ✅ | ✅ | ✅ | ❌ | ❌ |
420
+ | SqueezeBERT | ✅ | ✅ | ✅ | ❌ | ❌ |
421
+ | SwiftFormer | ❌ | ❌ | ✅ | ❌ | ❌ |
422
+ | Swin Transformer | ❌ | ❌ | ✅ | ✅ | ❌ |
423
+ | Swin Transformer V2 | ❌ | ❌ | ✅ | ❌ | ❌ |
424
+ | Swin2SR | ❌ | ❌ | ✅ | ❌ | ❌ |
425
+ | SwitchTransformers | ❌ | ❌ | ✅ | ❌ | ❌ |
426
+ | T5 | ✅ | ✅ | ✅ | ✅ | ✅ |
427
+ | Table Transformer | ❌ | ❌ | ✅ | ❌ | ❌ |
428
+ | TAPAS | ✅ | ❌ | ✅ | ✅ | ❌ |
429
+ | Time Series Transformer | ❌ | ❌ | ✅ | ❌ | ❌ |
430
+ | TimeSformer | ❌ | ❌ | ✅ | ❌ | ❌ |
431
+ | Trajectory Transformer | ❌ | ❌ | ✅ | ❌ | ❌ |
432
+ | Transformer-XL | ✅ | ❌ | ✅ | ✅ | ❌ |
433
+ | TrOCR | ❌ | ❌ | ✅ | ❌ | ❌ |
434
+ | TVLT | ❌ | ❌ | ✅ | ❌ | ❌ |
435
+ | TVP | ❌ | ❌ | ✅ | ❌ | ❌ |
436
+ | UniSpeech | ❌ | ❌ | ✅ | ❌ | ❌ |
437
+ | UniSpeechSat | ❌ | ❌ | ✅ | ❌ | ❌ |
438
+ | UPerNet | ❌ | ❌ | ✅ | ❌ | ❌ |
439
+ | VAN | ❌ | ❌ | ✅ | ❌ | ❌ |
440
+ | VideoMAE | ❌ | ❌ | ✅ | ❌ | ❌ |
441
+ | ViLT | ❌ | ❌ | ✅ | ❌ | ❌ |
442
+ | Vision Encoder decoder | ❌ | ❌ | ✅ | ✅ | ✅ |
443
+ | VisionTextDualEncoder | ❌ | ❌ | ✅ | ✅ | ✅ |
444
+ | VisualBERT | ❌ | ❌ | ✅ | ❌ | ❌ |
445
+ | ViT | ❌ | ❌ | ✅ | ✅ | ✅ |
446
+ | ViT Hybrid | ❌ | ❌ | ✅ | ❌ | ❌ |
447
+ | ViTMAE | ❌ | ❌ | ✅ | ✅ | ❌ |
448
+ | ViTMSN | ❌ | ❌ | ✅ | ❌ | ❌ |
449
+ | Wav2Vec2 | ✅ | ❌ | ✅ | ✅ | ✅ |
450
+ | Wav2Vec2-Conformer | ❌ | ❌ | ✅ | ❌ | ❌ |
451
+ | WavLM | ❌ | ❌ | ✅ | ❌ | ❌ |
452
+ | Whisper | ✅ | ✅ | ✅ | ✅ | ✅ |
453
+ | X-CLIP | ❌ | ❌ | ✅ | ❌ | ❌ |
454
+ | X-MOD | ❌ | ❌ | ✅ | ❌ | ❌ |
455
+ | XGLM | ✅ | ✅ | ✅ | ✅ | ✅ |
456
+ | XLM | ✅ | ❌ | ✅ | ✅ | ❌ |
457
+ | XLM-ProphetNet | ✅ | ❌ | ✅ | ❌ | ❌ |
458
+ | XLM-RoBERTa | ✅ | ✅ | ✅ | ✅ | ✅ |
459
+ | XLM-RoBERTa-XL | ❌ | ❌ | ✅ | ❌ | ❌ |
460
+ | XLNet | ✅ | ✅ | ✅ | ✅ | ❌ |
461
+ | YOLOS | ❌ | ❌ | ✅ | ❌ | ❌ |
462
+ | YOSO | ❌ | ❌ | ✅ | ❌ | ❌ |
463
+
464
+ <!-- Tamat -->
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/_config.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # docstyle-ignore
2
+ INSTALL_CONTENT = """
3
+ # Transformers installation
4
+ ! pip install transformers datasets evaluate accelerate
5
+ # To install from source instead of the last release, comment the command above and uncomment the following one.
6
+ # ! pip install git+https://github.com/huggingface/transformers.git
7
+ """
8
+
9
+ notebook_first_cells = [{"type": "code", "content": INSTALL_CONTENT}]
10
+ black_avoid_patterns = {
11
+ "{processor_class}": "FakeProcessorClass",
12
+ "{model_class}": "FakeModelClass",
13
+ "{object_class}": "FakeObjectClass",
14
+ }
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/_toctree.yml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - sections:
2
+ - local: index
3
+ title: 🤗 Transformers
4
+ - local: quicktour
5
+ title: Tour rápido
6
+ - local: installation
7
+ title: Instalação
8
+ title: Início
9
+ - sections:
10
+ - local: pipeline_tutorial
11
+ title: Pipelines para inferência
12
+ - local: training
13
+ title: Fine-tuning de um modelo pré-treinado
14
+ - local: accelerate
15
+ title: Treinamento distribuído com 🤗 Accelerate
16
+ title: Tutoriais
17
+ - sections:
18
+ - local: fast_tokenizers
19
+ title: Usando os Tokenizers do 🤗 Tokenizers
20
+ - local: create_a_model
21
+ title: Criando uma arquitetura customizada
22
+ - local: custom_models
23
+ title: Compartilhando modelos customizados
24
+ - local: run_scripts
25
+ title: Treinamento a partir de um script
26
+ - local: converting_tensorflow_models
27
+ title: Convertendo checkpoints do TensorFlow para Pytorch
28
+ - local: serialization
29
+ title: Exportando modelos para ONNX
30
+ - sections:
31
+ - local: tasks/sequence_classification
32
+ title: Classificação de texto
33
+ - local: tasks/token_classification
34
+ title: Classificação de tokens
35
+ title: Fine-tuning para tarefas específicas
36
+ - local: multilingual
37
+ title: Modelos multilinguísticos para inferência
38
+ title: Guias práticos
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/accelerate.md ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # Treinamento distribuído com o 🤗 Accelerate
18
+
19
+ O paralelismo surgiu como uma estratégia para treinar modelos grandes em hardware limitado e aumentar a velocidade
20
+ de treinamento em várias órdens de magnitude. Na Hugging Face criamos a biblioteca [🤗 Accelerate](https://huggingface.co/docs/accelerate)
21
+ para ajudar os usuários a treinar modelos 🤗 Transformers com qualquer configuração distribuída, seja em uma máquina
22
+ com múltiplos GPUs ou em múltiplos GPUs distribuidos entre muitas máquinas. Neste tutorial, você irá aprender como
23
+ personalizar seu laço de treinamento de PyTorch para poder treinar em ambientes distribuídos.
24
+
25
+ ## Configuração
26
+
27
+ De início, instale o 🤗 Accelerate:
28
+
29
+ ```bash
30
+ pip install accelerate
31
+ ```
32
+
33
+ Logo, devemos importar e criar um objeto [`Accelerator`](https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator).
34
+ O `Accelerator` detectará automáticamente a configuração distribuída disponível e inicializará todos os
35
+ componentes necessários para o treinamento. Não há necessidade portanto de especificar o dispositivo onde deve colocar seu modelo.
36
+
37
+ ```py
38
+ >>> from accelerate import Accelerator
39
+
40
+ >>> accelerator = Accelerator()
41
+ ```
42
+
43
+ ## Preparando a aceleração
44
+
45
+ Passe todos os objetos relevantes ao treinamento para o método [`prepare`](https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.prepare).
46
+ Isto inclui os DataLoaders de treino e evaluação, um modelo e um otimizador:
47
+
48
+ ```py
49
+ >>> train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare(
50
+ ... train_dataloader, eval_dataloader, model, optimizer
51
+ ... )
52
+ ```
53
+
54
+ ## Backward
55
+
56
+ Por último, substitua o `loss.backward()` padrão em seu laço de treinamento com o método [`backward`](https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.backward) do 🤗 Accelerate:
57
+
58
+ ```py
59
+ >>> for epoch in range(num_epochs):
60
+ ... for batch in train_dataloader:
61
+ ... outputs = model(**batch)
62
+ ... loss = outputs.loss
63
+ ... accelerator.backward(loss)
64
+
65
+ ... optimizer.step()
66
+ ... lr_scheduler.step()
67
+ ... optimizer.zero_grad()
68
+ ... progress_bar.update(1)
69
+ ```
70
+
71
+ Como se poder ver no seguinte código, só precisará adicionar quatro linhas de código ao seu laço de treinamento
72
+ para habilitar o treinamento distribuído!
73
+
74
+ ```diff
75
+ + from accelerate import Accelerator
76
+ from transformers import AdamW, AutoModelForSequenceClassification, get_scheduler
77
+
78
+ + accelerator = Accelerator()
79
+
80
+ model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2)
81
+ optimizer = AdamW(model.parameters(), lr=3e-5)
82
+
83
+ - device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
84
+ - model.to(device)
85
+
86
+ + train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare(
87
+ + train_dataloader, eval_dataloader, model, optimizer
88
+ + )
89
+
90
+ num_epochs = 3
91
+ num_training_steps = num_epochs * len(train_dataloader)
92
+ lr_scheduler = get_scheduler(
93
+ "linear",
94
+ optimizer=optimizer,
95
+ num_warmup_steps=0,
96
+ num_training_steps=num_training_steps
97
+ )
98
+
99
+ progress_bar = tqdm(range(num_training_steps))
100
+
101
+ model.train()
102
+ for epoch in range(num_epochs):
103
+ for batch in train_dataloader:
104
+ - batch = {k: v.to(device) for k, v in batch.items()}
105
+ outputs = model(**batch)
106
+ loss = outputs.loss
107
+ - loss.backward()
108
+ + accelerator.backward(loss)
109
+
110
+ optimizer.step()
111
+ lr_scheduler.step()
112
+ optimizer.zero_grad()
113
+ progress_bar.update(1)
114
+ ```
115
+
116
+ ## Treinamento
117
+
118
+ Quando tiver adicionado as linhas de código relevantes, inicie o treinamento por um script ou notebook como o Colab.
119
+
120
+ ### Treinamento em um Script
121
+
122
+ Se estiver rodando seu treinamento em um Script, execute o seguinte comando para criar e guardar um arquivo de configuração:
123
+
124
+ ```bash
125
+ accelerate config
126
+ ```
127
+
128
+ Comece o treinamento com:
129
+
130
+ ```bash
131
+ accelerate launch train.py
132
+ ```
133
+
134
+ ### Treinamento em um Notebook
135
+
136
+ O 🤗 Accelerate pode rodar em um notebook, por exemplo, se estiver planejando usar as TPUs do Google Colab.
137
+ Encapsule o código responsável pelo treinamento de uma função e passe-o ao `notebook_launcher`:
138
+
139
+ ```py
140
+ >>> from accelerate import notebook_launcher
141
+
142
+ >>> notebook_launcher(training_function)
143
+ ```
144
+
145
+ Para obter mais informações sobre o 🤗 Accelerate e suas numerosas funções, consulte a [documentación](https://huggingface.co/docs/accelerate/index).
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/converting_tensorflow_models.md ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2020 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # Convertendo checkpoints do TensorFlow para Pytorch
18
+
19
+ Uma interface de linha de comando é fornecida para converter os checkpoints originais Bert/GPT/GPT-2/Transformer-XL/XLNet/XLM em modelos
20
+ que podem ser carregados usando os métodos `from_pretrained` da biblioteca.
21
+
22
+ <Tip>
23
+
24
+ A partir da versão 2.3.0 o script de conversão agora faz parte do transformers CLI (**transformers**) disponível em qualquer instalação
25
+ transformers >= 2.3.0.
26
+
27
+ A documentação abaixo reflete o formato do comando **transformers convert**.
28
+
29
+ </Tip>
30
+
31
+ ## BERT
32
+
33
+ Você pode converter qualquer checkpoint do BERT em TensorFlow (em particular [os modelos pré-treinados lançados pelo Google](https://github.com/google-research/bert#pre-trained-models)) em um arquivo PyTorch usando um
34
+ [convert_bert_original_tf_checkpoint_to_pytorch.py](https://github.com/huggingface/transformers/tree/main/src/transformers/models/bert/convert_bert_original_tf_checkpoint_to_pytorch.py) script.
35
+
36
+ Esta Interface de Linha de Comando (CLI) recebe como entrada um checkpoint do TensorFlow (três arquivos começando com `bert_model.ckpt`) e o
37
+ arquivo de configuração (`bert_config.json`), e então cria um modelo PyTorch para esta configuração, carrega os pesos
38
+ do checkpoint do TensorFlow no modelo PyTorch e salva o modelo resultante em um arquivo PyTorch que pode
39
+ ser importado usando `from_pretrained()` (veja o exemplo em [quicktour](quicktour) , [run_glue.py](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-classification/run_glue.py) ).
40
+
41
+ Você só precisa executar este script de conversão **uma vez** para obter um modelo PyTorch. Você pode então desconsiderar o checkpoint em
42
+ TensorFlow (os três arquivos começando com `bert_model.ckpt`), mas certifique-se de manter o arquivo de configuração (\
43
+ `bert_config.json`) e o arquivo de vocabulário (`vocab.txt`), pois eles também são necessários para o modelo PyTorch.
44
+
45
+ Para executar este script de conversão específico, você precisará ter o TensorFlow e o PyTorch instalados (`pip install tensorflow`). O resto do repositório requer apenas o PyTorch.
46
+
47
+ Aqui está um exemplo do processo de conversão para um modelo `BERT-Base Uncased` pré-treinado:
48
+
49
+ ```bash
50
+ export BERT_BASE_DIR=/path/to/bert/uncased_L-12_H-768_A-12
51
+
52
+ transformers convert --model_type bert \
53
+ --tf_checkpoint $BERT_BASE_DIR/bert_model.ckpt \
54
+ --config $BERT_BASE_DIR/bert_config.json \
55
+ --pytorch_dump_output $BERT_BASE_DIR/pytorch_model.bin
56
+ ```
57
+
58
+ Você pode baixar os modelos pré-treinados do Google para a conversão [aqui](https://github.com/google-research/bert#pre-trained-models).
59
+
60
+ ## ALBERT
61
+
62
+ Converta os checkpoints do modelo ALBERT em TensorFlow para PyTorch usando o
63
+ [convert_albert_original_tf_checkpoint_to_pytorch.py](https://github.com/huggingface/transformers/tree/main/src/transformers/models/albert/convert_albert_original_tf_checkpoint_to_pytorch.py) script.
64
+
65
+ A Interface de Linha de Comando (CLI) recebe como entrada um checkpoint do TensorFlow (três arquivos começando com `model.ckpt-best`) e o
66
+ arquivo de configuração (`albert_config.json`), então cria e salva um modelo PyTorch. Para executar esta conversão, você
67
+ precisa ter o TensorFlow e o PyTorch instalados.
68
+
69
+ Aqui está um exemplo do processo de conversão para o modelo `ALBERT Base` pré-treinado:
70
+
71
+ ```bash
72
+ export ALBERT_BASE_DIR=/path/to/albert/albert_base
73
+
74
+ transformers convert --model_type albert \
75
+ --tf_checkpoint $ALBERT_BASE_DIR/model.ckpt-best \
76
+ --config $ALBERT_BASE_DIR/albert_config.json \
77
+ --pytorch_dump_output $ALBERT_BASE_DIR/pytorch_model.bin
78
+ ```
79
+
80
+ Você pode baixar os modelos pré-treinados do Google para a conversão [aqui](https://github.com/google-research/albert#pre-trained-models).
81
+
82
+ ## OpenAI GPT
83
+
84
+ Aqui está um exemplo do processo de conversão para um modelo OpenAI GPT pré-treinado, supondo que seu checkpoint NumPy
85
+ foi salvo com o mesmo formato do modelo pré-treinado OpenAI (veja [aqui](https://github.com/openai/finetune-transformer-lm)\
86
+ )
87
+
88
+ ```bash
89
+ export OPENAI_GPT_CHECKPOINT_FOLDER_PATH=/path/to/openai/pretrained/numpy/weights
90
+
91
+ transformers convert --model_type gpt \
92
+ --tf_checkpoint $OPENAI_GPT_CHECKPOINT_FOLDER_PATH \
93
+ --pytorch_dump_output $PYTORCH_DUMP_OUTPUT \
94
+ [--config OPENAI_GPT_CONFIG] \
95
+ [--finetuning_task_name OPENAI_GPT_FINETUNED_TASK] \
96
+ ```
97
+
98
+ ## OpenAI GPT-2
99
+
100
+ Aqui está um exemplo do processo de conversão para um modelo OpenAI GPT-2 pré-treinado (consulte [aqui](https://github.com/openai/gpt-2))
101
+
102
+ ```bash
103
+ export OPENAI_GPT2_CHECKPOINT_PATH=/path/to/openai-community/gpt2/pretrained/weights
104
+
105
+ transformers convert --model_type gpt2 \
106
+ --tf_checkpoint $OPENAI_GPT2_CHECKPOINT_PATH \
107
+ --pytorch_dump_output $PYTORCH_DUMP_OUTPUT \
108
+ [--config OPENAI_GPT2_CONFIG] \
109
+ [--finetuning_task_name OPENAI_GPT2_FINETUNED_TASK]
110
+ ```
111
+
112
+ ## XLNet
113
+
114
+ Aqui está um exemplo do processo de conversão para um modelo XLNet pré-treinado:
115
+
116
+ ```bash
117
+ export TRANSFO_XL_CHECKPOINT_PATH=/path/to/xlnet/checkpoint
118
+ export TRANSFO_XL_CONFIG_PATH=/path/to/xlnet/config
119
+
120
+ transformers convert --model_type xlnet \
121
+ --tf_checkpoint $TRANSFO_XL_CHECKPOINT_PATH \
122
+ --config $TRANSFO_XL_CONFIG_PATH \
123
+ --pytorch_dump_output $PYTORCH_DUMP_OUTPUT \
124
+ [--finetuning_task_name XLNET_FINETUNED_TASK] \
125
+ ```
126
+
127
+ ## XLM
128
+
129
+ Aqui está um exemplo do processo de conversão para um modelo XLM pré-treinado:
130
+
131
+ ```bash
132
+ export XLM_CHECKPOINT_PATH=/path/to/xlm/checkpoint
133
+
134
+ transformers convert --model_type xlm \
135
+ --tf_checkpoint $XLM_CHECKPOINT_PATH \
136
+ --pytorch_dump_output $PYTORCH_DUMP_OUTPUT
137
+ [--config XML_CONFIG] \
138
+ [--finetuning_task_name XML_FINETUNED_TASK]
139
+ ```
140
+
141
+ ## T5
142
+
143
+ Aqui está um exemplo do processo de conversão para um modelo T5 pré-treinado:
144
+
145
+ ```bash
146
+ export T5=/path/to/t5/uncased_L-12_H-768_A-12
147
+
148
+ transformers convert --model_type t5 \
149
+ --tf_checkpoint $T5/t5_model.ckpt \
150
+ --config $T5/t5_config.json \
151
+ --pytorch_dump_output $T5/pytorch_model.bin
152
+ ```
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/create_a_model.md ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # Criar uma arquitetura customizada
18
+
19
+ Uma [`AutoClass`](model_doc/auto) automaticamente infere a arquitetura do modelo e baixa configurações e pesos pré-treinados. Geralmente, nós recomendamos usar uma `AutoClass` para produzir um código independente de checkpoints. Mas usuários que querem mais contole sobre parâmetros específicos do modelo pode criar um modelo customizado 🤗 Transformers a partir de algumas classes bases. Isso pode ser particulamente útil para alguém que está interessado em estudar, treinar ou fazer experimentos com um modelo 🤗 Transformers. Nesse tutorial, será explicado como criar um modelo customizado sem uma `AutoClass`. Aprenda como:
20
+
21
+ - Carregar e customizar a configuração de um modelo.
22
+ - Criar a arquitetura de um modelo.
23
+ - Criar um tokenizer rápido e devagar para textos.
24
+ - Criar extrator de features para tarefas envolvendo audio e imagem.
25
+ - Criar um processador para tarefas multimodais.
26
+
27
+ ## configuration
28
+
29
+ A [configuration](main_classes/configuration) refere-se a atributos específicos de um modelo. Cada configuração de modelo tem atributos diferentes; por exemplo, todos modelo de PLN possuem os atributos `hidden_size`, `num_attention_heads`, `num_hidden_layers` e `vocab_size` em comum. Esse atributos especificam o numero de 'attention heads' ou 'hidden layers' para construir um modelo.
30
+
31
+ Dê uma olhada a mais em [DistilBERT](model_doc/distilbert) acessando [`DistilBertConfig`] para observar esses atributos:
32
+
33
+ ```py
34
+ >>> from transformers import DistilBertConfig
35
+
36
+ >>> config = DistilBertConfig()
37
+ >>> print(config)
38
+ DistilBertConfig {
39
+ "activation": "gelu",
40
+ "attention_dropout": 0.1,
41
+ "dim": 768,
42
+ "dropout": 0.1,
43
+ "hidden_dim": 3072,
44
+ "initializer_range": 0.02,
45
+ "max_position_embeddings": 512,
46
+ "model_type": "distilbert",
47
+ "n_heads": 12,
48
+ "n_layers": 6,
49
+ "pad_token_id": 0,
50
+ "qa_dropout": 0.1,
51
+ "seq_classif_dropout": 0.2,
52
+ "sinusoidal_pos_embds": false,
53
+ "transformers_version": "4.16.2",
54
+ "vocab_size": 30522
55
+ }
56
+ ```
57
+
58
+ [`DistilBertConfig`] mostra todos os atributos padrões usados para construir um [`DistilBertModel`] base. Todos atributos são customizáveis, o que cria espaço para experimentos. Por exemplo, você pode customizar um modelo padrão para:
59
+
60
+ - Tentar uma função de ativação diferente com o parâmetro `activation`.
61
+ - Usar uma taxa de desistência maior para as probabilidades de 'attention' com o parâmetro `attention_dropout`.
62
+
63
+ ```py
64
+ >>> my_config = DistilBertConfig(activation="relu", attention_dropout=0.4)
65
+ >>> print(my_config)
66
+ DistilBertConfig {
67
+ "activation": "relu",
68
+ "attention_dropout": 0.4,
69
+ "dim": 768,
70
+ "dropout": 0.1,
71
+ "hidden_dim": 3072,
72
+ "initializer_range": 0.02,
73
+ "max_position_embeddings": 512,
74
+ "model_type": "distilbert",
75
+ "n_heads": 12,
76
+ "n_layers": 6,
77
+ "pad_token_id": 0,
78
+ "qa_dropout": 0.1,
79
+ "seq_classif_dropout": 0.2,
80
+ "sinusoidal_pos_embds": false,
81
+ "transformers_version": "4.16.2",
82
+ "vocab_size": 30522
83
+ }
84
+ ```
85
+
86
+ Atributos de um modelo pré-treinado podem ser modificados na função [`~PretrainedConfig.from_pretrained`]:
87
+
88
+ ```py
89
+ >>> my_config = DistilBertConfig.from_pretrained("distilbert/distilbert-base-uncased", activation="relu", attention_dropout=0.4)
90
+ ```
91
+
92
+ Uma vez que você está satisfeito com as configurações do seu modelo, você consegue salvar elas com [`~PretrainedConfig.save_pretrained`]. Seu arquivo de configurações está salvo como um arquivo JSON no diretório especificado:
93
+
94
+ ```py
95
+ >>> my_config.save_pretrained(save_directory="./your_model_save_path")
96
+ ```
97
+
98
+ Para reusar o arquivo de configurações, carregue com [`~PretrainedConfig.from_pretrained`]:
99
+
100
+ ```py
101
+ >>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/my_config.json")
102
+ ```
103
+
104
+ <Tip>
105
+
106
+ Você pode também salvar seu arquivo de configurações como um dicionário ou até mesmo com a diferença entre as seus atributos de configuração customizados e os atributos de configuração padrões! Olhe a documentação [configuration](main_classes/configuration) para mais detalhes.
107
+
108
+ </Tip>
109
+
110
+ ## Modelo
111
+
112
+ O próximo passo é criar um [model](main_classes/models). O modelo - também vagamente referido como arquitetura - define o que cada camada está fazendo e quais operações estão acontecendo. Atributos como `num_hidden_layers` das configurações são utilizados para definir a arquitetura. Todo modelo compartilha a classe base [`PreTrainedModel`] e alguns métodos em comum como redimensionar o tamanho dos embeddings de entrada e podar as 'self-attention heads'. Além disso, todos os modelos também são subclasses de [`torch.nn.Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html), [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model) ou [`flax.linen.Module`](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html). Isso significa que os modelos são compatíveis com cada respectivo uso de framework.
113
+
114
+ <frameworkcontent>
115
+ <pt>
116
+ Carregar seus atributos de configuração customizados em um modelo:
117
+
118
+ ```py
119
+ >>> from transformers import DistilBertModel
120
+
121
+ >>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/my_config.json")
122
+ >>> model = DistilBertModel(my_config)
123
+ ```
124
+
125
+ Isso cria um modelo com valores aleatórios ao invés de pré-treinar os pesos. Você não irá conseguir usar usar esse modelo para nada útil ainda, até você treinar ele. Treino é um processo caro e demorado. Geralmente é melhor utilizar um modelo pré-treinado para obter melhores resultados mais rápido, enquanto usa apenas uma fração dos recursos necessários para treinar.
126
+
127
+ Criar um modelo pré-treinado com [`~PreTrainedModel.from_pretrained`]:
128
+
129
+ ```py
130
+ >>> model = DistilBertModel.from_pretrained("distilbert/distilbert-base-uncased")
131
+ ```
132
+
133
+ Quando você carregar os pesos pré-treinados, a configuração padrão do modelo é automaticamente carregada se o modelo é provido pelo 🤗 Transformers. No entanto, você ainda consegue mudar - alguns ou todos - os atributos padrões de configuração do modelo com os seus próprio atributos, se você preferir:
134
+
135
+ ```py
136
+ >>> model = DistilBertModel.from_pretrained("distilbert/distilbert-base-uncased", config=my_config)
137
+ ```
138
+ </pt>
139
+ <tf>
140
+ Carregar os seus próprios atributos padrões de contiguração no modelo:
141
+
142
+ ```py
143
+ >>> from transformers import TFDistilBertModel
144
+
145
+ >>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/my_config.json")
146
+ >>> tf_model = TFDistilBertModel(my_config)
147
+ ```
148
+
149
+ Isso cria um modelo com valores aleatórios ao invés de pré-treinar os pesos. Você não irá conseguir usar usar esse modelo para nada útil ainda, até você treinar ele. Treino é um processo caro e demorado. Geralmente é melhor utilizar um modelo pré-treinado para obter melhores resultados mais rápido, enquanto usa apenas uma fração dos recursos necessários para treinar.
150
+
151
+ Criar um modelo pré-treinado com [`~TFPreTrainedModel.from_pretrained`]:
152
+
153
+ ```py
154
+ >>> tf_model = TFDistilBertModel.from_pretrained("distilbert/distilbert-base-uncased")
155
+ ```
156
+
157
+ Quando você carregar os pesos pré-treinados, a configuração padrão do modelo é automaticamente carregada se o modelo é provido pelo 🤗 Transformers. No entanto, você ainda consegue mudar - alguns ou todos - os atributos padrões de configuração do modelo com os seus próprio atributos, se você preferir:
158
+
159
+ ```py
160
+ >>> tf_model = TFDistilBertModel.from_pretrained("distilbert/distilbert-base-uncased", config=my_config)
161
+ ```
162
+ </tf>
163
+ </frameworkcontent>
164
+
165
+ ### Heads do modelo
166
+
167
+ Neste ponto, você tem um modelo básico do DistilBERT que gera os *estados ocultos*. Os estados ocultos são passados como entrada para a head do moelo para produzir a saída final. 🤗 Transformers fornece uma head de modelo diferente para cada tarefa desde que o modelo suporte essa tarefa (por exemplo, você não consegue utilizar o modelo DistilBERT para uma tarefa de 'sequence-to-sequence' como tradução).
168
+
169
+ <frameworkcontent>
170
+ <pt>
171
+ Por exemplo, [`DistilBertForSequenceClassification`] é um modelo DistilBERT base com uma head de classificação de sequência. A head de calssificação de sequência é uma camada linear no topo das saídas agrupadas.
172
+
173
+ ```py
174
+ >>> from transformers import DistilBertForSequenceClassification
175
+
176
+ >>> model = DistilBertForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased")
177
+ ```
178
+
179
+ Reutilize facilmente esse ponto de parada para outra tarefe mudando para uma head de modelo diferente. Para uma tarefe de responder questões, você usaria a head do modelo [`DistilBertForQuestionAnswering`]. A head de responder questões é similar com a de classificação de sequências exceto o fato de que ela é uma camada no topo dos estados das saídas ocultas.
180
+
181
+ ```py
182
+ >>> from transformers import DistilBertForQuestionAnswering
183
+
184
+ >>> model = DistilBertForQuestionAnswering.from_pretrained("distilbert/distilbert-base-uncased")
185
+ ```
186
+ </pt>
187
+ <tf>
188
+ Por exemplo, [`TFDistilBertForSequenceClassification`] é um modelo DistilBERT base com uma head de classificação de sequência. A head de calssificação de sequência é uma camada linear no topo das saídas agrupadas.
189
+
190
+ ```py
191
+ >>> from transformers import TFDistilBertForSequenceClassification
192
+
193
+ >>> tf_model = TFDistilBertForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased")
194
+ ```
195
+
196
+ Reutilize facilmente esse ponto de parada para outra tarefe mudando para uma head de modelo diferente. Para uma tarefe de responder questões, você usaria a head do modelo [`TFDistilBertForQuestionAnswering`]. A head de responder questões é similar com a de classificação de sequências exceto o fato de que ela é uma camada no topo dos estados das saídas ocultas.
197
+
198
+ ```py
199
+ >>> from transformers import TFDistilBertForQuestionAnswering
200
+
201
+ >>> tf_model = TFDistilBertForQuestionAnswering.from_pretrained("distilbert/distilbert-base-uncased")
202
+ ```
203
+ </tf>
204
+ </frameworkcontent>
205
+
206
+ ## Tokenizer
207
+
208
+ A útlima classe base que você precisa antes de usar um modelo para dados textuais é a [tokenizer](main_classes/tokenizer) para converter textos originais para tensores. Existem dois tipos de tokenizers que você pode usar com 🤗 Transformers:
209
+
210
+ - [`PreTrainedTokenizer`]: uma implementação em Python de um tokenizer.
211
+ - [`PreTrainedTokenizerFast`]: um tokenizer da nossa biblioteca [🤗 Tokenizer](https://huggingface.co/docs/tokenizers/python/latest/) baseada em Rust. Esse tipo de tokenizer é significantemente mais rapido - especialmente durante tokenization de codificação - devido a implementação em Rust. O tokenizer rápido tambem oferece métodos adicionais como *offset mapping* que mapeia tokens para suar palavras ou caracteres originais.
212
+
213
+ Os dois tokenizers suporta métodos comuns como os de codificar e decodificar, adicionar novos tokens, e gerenciar tokens especiais.
214
+
215
+ <Tip warning={true}>
216
+
217
+ Nem todo modelo suporta um 'fast tokenizer'. De uma olhada aqui [table](index#supported-frameworks) pra checar se um modelo suporta 'fast tokenizer'.
218
+
219
+ </Tip>
220
+
221
+ Se você treinou seu prórpio tokenizer, você pode criar um a partir do seu arquivo *vocabulary*:
222
+
223
+ ```py
224
+ >>> from transformers import DistilBertTokenizer
225
+
226
+ >>> my_tokenizer = DistilBertTokenizer(vocab_file="my_vocab_file.txt", do_lower_case=False, padding_side="left")
227
+ ```
228
+
229
+ É importante lembrar que o vocabulário de um tokenizer customizado será diferente de um vocabulário gerado pelo tokenizer de um modelo pré treinado. Você precisa usar o vocabulário de um modelo pré treinado se você estiver usando um modelo pré treinado, caso contrário as entradas não farão sentido. Criando um tokenizer com um vocabulário de um modelo pré treinado com a classe [`DistilBertTokenizer`]:
230
+
231
+ ```py
232
+ >>> from transformers import DistilBertTokenizer
233
+
234
+ >>> slow_tokenizer = DistilBertTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
235
+ ```
236
+
237
+ Criando um 'fast tokenizer' com a classe [`DistilBertTokenizerFast`]:
238
+
239
+ ```py
240
+ >>> from transformers import DistilBertTokenizerFast
241
+
242
+ >>> fast_tokenizer = DistilBertTokenizerFast.from_pretrained("distilbert/distilbert-base-uncased")
243
+ ```
244
+
245
+ <Tip>
246
+
247
+ Pos padrão, [`AutoTokenizer`] tentará carregar um 'fast tokenizer'. Você pode disabilitar esse comportamento colocando `use_fast=False` no `from_pretrained`.
248
+
249
+ </Tip>
250
+
251
+ ## Extrator de features
252
+
253
+ Um extrator de features processa entradas de imagem ou áudio. Ele herda da classe base [`~feature_extraction_utils.FeatureExtractionMixin`], e pode também herdar da classe [`ImageFeatureExtractionMixin`] para processamento de features de imagem ou da classe [`SequenceFeatureExtractor`] para processamento de entradas de áudio.
254
+
255
+ Dependendo do que você está trabalhando em um audio ou uma tarefa de visão, crie um estrator de features associado com o modelo que você está usando. Por exemplo, crie um [`ViTFeatureExtractor`] padrão se você estiver usando [ViT](model_doc/vit) para classificação de imagens:
256
+
257
+ ```py
258
+ >>> from transformers import ViTFeatureExtractor
259
+
260
+ >>> vit_extractor = ViTFeatureExtractor()
261
+ >>> print(vit_extractor)
262
+ ViTFeatureExtractor {
263
+ "do_normalize": true,
264
+ "do_resize": true,
265
+ "feature_extractor_type": "ViTFeatureExtractor",
266
+ "image_mean": [
267
+ 0.5,
268
+ 0.5,
269
+ 0.5
270
+ ],
271
+ "image_std": [
272
+ 0.5,
273
+ 0.5,
274
+ 0.5
275
+ ],
276
+ "resample": 2,
277
+ "size": 224
278
+ }
279
+ ```
280
+
281
+ <Tip>
282
+
283
+ Se você não estiver procurando por nenhuma customização, apenas use o método `from_pretrained` para carregar parâmetros do modelo de extrator de features padrão.
284
+
285
+ </Tip>
286
+
287
+ Modifique qualquer parâmetro dentre os [`ViTFeatureExtractor`] para criar seu extrator de features customizado.
288
+
289
+ ```py
290
+ >>> from transformers import ViTFeatureExtractor
291
+
292
+ >>> my_vit_extractor = ViTFeatureExtractor(resample="PIL.Image.BOX", do_normalize=False, image_mean=[0.3, 0.3, 0.3])
293
+ >>> print(my_vit_extractor)
294
+ ViTFeatureExtractor {
295
+ "do_normalize": false,
296
+ "do_resize": true,
297
+ "feature_extractor_type": "ViTFeatureExtractor",
298
+ "image_mean": [
299
+ 0.3,
300
+ 0.3,
301
+ 0.3
302
+ ],
303
+ "image_std": [
304
+ 0.5,
305
+ 0.5,
306
+ 0.5
307
+ ],
308
+ "resample": "PIL.Image.BOX",
309
+ "size": 224
310
+ }
311
+ ```
312
+
313
+ Para entradas de áutio, você pode criar um [`Wav2Vec2FeatureExtractor`] e customizar os parâmetros de uma forma similar:
314
+
315
+ ```py
316
+ >>> from transformers import Wav2Vec2FeatureExtractor
317
+
318
+ >>> w2v2_extractor = Wav2Vec2FeatureExtractor()
319
+ >>> print(w2v2_extractor)
320
+ Wav2Vec2FeatureExtractor {
321
+ "do_normalize": true,
322
+ "feature_extractor_type": "Wav2Vec2FeatureExtractor",
323
+ "feature_size": 1,
324
+ "padding_side": "right",
325
+ "padding_value": 0.0,
326
+ "return_attention_mask": false,
327
+ "sampling_rate": 16000
328
+ }
329
+ ```
330
+
331
+ ## Processor
332
+
333
+ Para modelos que suportam tarefas multimodais, 🤗 Transformers oferece uma classe processadora que convenientemente cobre um extrator de features e tokenizer dentro de um único objeto. Por exemplo, vamos usar o [`Wav2Vec2Processor`] para uma tarefa de reconhecimento de fala automática (ASR). ASR transcreve áudio para texto, então você irá precisar de um extrator de um features e um tokenizer.
334
+
335
+ Crie um extrator de features para lidar com as entradas de áudio.
336
+
337
+ ```py
338
+ >>> from transformers import Wav2Vec2FeatureExtractor
339
+
340
+ >>> feature_extractor = Wav2Vec2FeatureExtractor(padding_value=1.0, do_normalize=True)
341
+ ```
342
+
343
+ Crie um tokenizer para lidar com a entrada de textos:
344
+
345
+ ```py
346
+ >>> from transformers import Wav2Vec2CTCTokenizer
347
+
348
+ >>> tokenizer = Wav2Vec2CTCTokenizer(vocab_file="my_vocab_file.txt")
349
+ ```
350
+
351
+ Combine o extrator de features e o tokenizer no [`Wav2Vec2Processor`]:
352
+
353
+ ```py
354
+ >>> from transformers import Wav2Vec2Processor
355
+
356
+ >>> processor = Wav2Vec2Processor(feature_extractor=feature_extractor, tokenizer=tokenizer)
357
+ ```
358
+
359
+ Com duas classes básicas - configuração e modelo - e um preprocessamento de classe adicional (tokenizer, extrator de features, ou processador), você pode criar qualquer modelo que suportado por 🤗 Transformers. Qualquer uma dessas classes base são configuráveis, te permitindo usar os atributos específicos que você queira. Você pode facilmente preparar um modelo para treinamento ou modificar um modelo pré-treinado com poucas mudanças.
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/custom_models.md ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2020 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # Compartilhando modelos customizados
18
+
19
+ A biblioteca 🤗 Transformers foi projetada para ser facilmente extensível. Cada modelo é totalmente codificado em uma determinada subpasta
20
+ do repositório sem abstração, para que você possa copiar facilmente um arquivo de modelagem e ajustá-lo às suas necessidades.
21
+
22
+ Se você estiver escrevendo um modelo totalmente novo, pode ser mais fácil começar do zero. Neste tutorial, mostraremos
23
+ como escrever um modelo customizado e sua configuração para que possa ser usado com Transformers, e como você pode compartilhá-lo
24
+ com a comunidade (com o código em que se baseia) para que qualquer pessoa possa usá-lo, mesmo se não estiver presente na biblioteca 🤗 Transformers.
25
+
26
+ Ilustraremos tudo isso em um modelo ResNet, envolvendo a classe ResNet do
27
+ [biblioteca timm](https://github.com/rwightman/pytorch-image-models) em um [`PreTrainedModel`].
28
+
29
+ ## Escrevendo uma configuração customizada
30
+
31
+ Antes de mergulharmos no modelo, vamos primeiro escrever sua configuração. A configuração de um modelo é um objeto que
32
+ terá todas as informações necessárias para construir o modelo. Como veremos na próxima seção, o modelo só pode
33
+ ter um `config` para ser inicializado, então realmente precisamos que esse objeto seja o mais completo possível.
34
+
35
+ Em nosso exemplo, pegaremos alguns argumentos da classe ResNet que podemos querer ajustar. Diferentes
36
+ configurações nos dará os diferentes tipos de ResNets que são possíveis. Em seguida, apenas armazenamos esses argumentos,
37
+ após verificar a validade de alguns deles.
38
+
39
+ ```python
40
+ from transformers import PretrainedConfig
41
+ from typing import List
42
+
43
+
44
+ class ResnetConfig(PretrainedConfig):
45
+ model_type = "resnet"
46
+
47
+ def __init__(
48
+ self,
49
+ block_type="bottleneck",
50
+ layers: list[int] = [3, 4, 6, 3],
51
+ num_classes: int = 1000,
52
+ input_channels: int = 3,
53
+ cardinality: int = 1,
54
+ base_width: int = 64,
55
+ stem_width: int = 64,
56
+ stem_type: str = "",
57
+ avg_down: bool = False,
58
+ **kwargs,
59
+ ):
60
+ if block_type not in ["basic", "bottleneck"]:
61
+ raise ValueError(f"`block_type` must be 'basic' or bottleneck', got {block_type}.")
62
+ if stem_type not in ["", "deep", "deep-tiered"]:
63
+ raise ValueError(f"`stem_type` must be '', 'deep' or 'deep-tiered', got {stem_type}.")
64
+
65
+ self.block_type = block_type
66
+ self.layers = layers
67
+ self.num_classes = num_classes
68
+ self.input_channels = input_channels
69
+ self.cardinality = cardinality
70
+ self.base_width = base_width
71
+ self.stem_width = stem_width
72
+ self.stem_type = stem_type
73
+ self.avg_down = avg_down
74
+ super().__init__(**kwargs)
75
+ ```
76
+
77
+ As três coisas importantes a serem lembradas ao escrever sua própria configuração são:
78
+ - você tem que herdar de `PretrainedConfig`,
79
+ - o `__init__` do seu `PretrainedConfig` deve aceitar quaisquer kwargs,
80
+ - esses `kwargs` precisam ser passados para a superclasse `__init__`.
81
+
82
+ A herança é para garantir que você obtenha todas as funcionalidades da biblioteca 🤗 Transformers, enquanto as outras duas
83
+ restrições vêm do fato de um `PretrainedConfig` ter mais campos do que os que você está configurando. Ao recarregar um
84
+ config com o método `from_pretrained`, esses campos precisam ser aceitos pelo seu config e então enviados para a
85
+ superclasse.
86
+
87
+ Definir um `model_type` para sua configuração (aqui `model_type="resnet"`) não é obrigatório, a menos que você queira
88
+ registrar seu modelo com as classes automáticas (veja a última seção).
89
+
90
+ Com isso feito, você pode facilmente criar e salvar sua configuração como faria com qualquer outra configuração de modelo da
91
+ biblioteca. Aqui está como podemos criar uma configuração resnet50d e salvá-la:
92
+
93
+ ```py
94
+ resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True)
95
+ resnet50d_config.save_pretrained("custom-resnet")
96
+ ```
97
+
98
+ Isso salvará um arquivo chamado `config.json` dentro da pasta `custom-resnet`. Você pode então recarregar sua configuração com o
99
+ método `from_pretrained`:
100
+
101
+ ```py
102
+ resnet50d_config = ResnetConfig.from_pretrained("custom-resnet")
103
+ ```
104
+
105
+ Você tamb��m pode usar qualquer outro método da classe [`PretrainedConfig`], como [`~PretrainedConfig.push_to_hub`] para
106
+ carregar diretamente sua configuração para o Hub.
107
+
108
+ ## Escrevendo um modelo customizado
109
+
110
+ Agora que temos nossa configuração ResNet, podemos continuar escrevendo o modelo. Na verdade, escreveremos dois: um que
111
+ extrai os recursos ocultos de um lote de imagens (como [`BertModel`]) e um que é adequado para classificação de imagem
112
+ (como [`BertForSequenceClassification`]).
113
+
114
+ Como mencionamos antes, escreveremos apenas um wrapper solto do modelo para mantê-lo simples para este exemplo. A única
115
+ coisa que precisamos fazer antes de escrever esta classe é um mapa entre os tipos de bloco e as classes de bloco reais. Então o
116
+ modelo é definido a partir da configuração passando tudo para a classe `ResNet`:
117
+
118
+ ```py
119
+ from transformers import PreTrainedModel
120
+ from timm.models.resnet import BasicBlock, Bottleneck, ResNet
121
+ from .configuration_resnet import ResnetConfig
122
+
123
+
124
+ BLOCK_MAPPING = {"basic": BasicBlock, "bottleneck": Bottleneck}
125
+
126
+
127
+ class ResnetModel(PreTrainedModel):
128
+ config_class = ResnetConfig
129
+
130
+ def __init__(self, config):
131
+ super().__init__(config)
132
+ block_layer = BLOCK_MAPPING[config.block_type]
133
+ self.model = ResNet(
134
+ block_layer,
135
+ config.layers,
136
+ num_classes=config.num_classes,
137
+ in_chans=config.input_channels,
138
+ cardinality=config.cardinality,
139
+ base_width=config.base_width,
140
+ stem_width=config.stem_width,
141
+ stem_type=config.stem_type,
142
+ avg_down=config.avg_down,
143
+ )
144
+
145
+ def forward(self, tensor):
146
+ return self.model.forward_features(tensor)
147
+ ```
148
+
149
+ Para o modelo que irá classificar as imagens, vamos apenas alterar o método forward:
150
+
151
+ ```py
152
+ import torch
153
+
154
+
155
+ class ResnetModelForImageClassification(PreTrainedModel):
156
+ config_class = ResnetConfig
157
+
158
+ def __init__(self, config):
159
+ super().__init__(config)
160
+ block_layer = BLOCK_MAPPING[config.block_type]
161
+ self.model = ResNet(
162
+ block_layer,
163
+ config.layers,
164
+ num_classes=config.num_classes,
165
+ in_chans=config.input_channels,
166
+ cardinality=config.cardinality,
167
+ base_width=config.base_width,
168
+ stem_width=config.stem_width,
169
+ stem_type=config.stem_type,
170
+ avg_down=config.avg_down,
171
+ )
172
+
173
+ def forward(self, tensor, labels=None):
174
+ logits = self.model(tensor)
175
+ if labels is not None:
176
+ loss = torch.nn.functional.cross_entropy(logits, labels)
177
+ return {"loss": loss, "logits": logits}
178
+ return {"logits": logits}
179
+ ```
180
+
181
+ Em ambos os casos, observe como herdamos de `PreTrainedModel` e chamamos a inicialização da superclasse com o `config`
182
+ (um pouco parecido quando você escreve um `torch.nn.Module`). A linha que define o `config_class` não é obrigatória, a menos que
183
+ você deseje registrar seu modelo com as classes automáticas (consulte a última seção).
184
+
185
+ <Tip>
186
+
187
+ Se o seu modelo for muito semelhante a um modelo dentro da biblioteca, você poderá reutilizar a mesma configuração desse modelo.
188
+
189
+ </Tip>
190
+
191
+ Você pode fazer com que seu modelo retorne o que você quiser,porém retornando um dicionário como fizemos para
192
+ `ResnetModelForImageClassification`, com a função de perda incluída quando os rótulos são passados, vai tornar seu modelo diretamente
193
+ utilizável dentro da classe [`Trainer`]. Você pode usar outro formato de saída, desde que esteja planejando usar seu próprio
194
+ laço de treinamento ou outra biblioteca para treinamento.
195
+
196
+ Agora que temos nossa classe do modelo, vamos criar uma:
197
+
198
+ ```py
199
+ resnet50d = ResnetModelForImageClassification(resnet50d_config)
200
+ ```
201
+
202
+ Novamente, você pode usar qualquer um dos métodos do [`PreTrainedModel`], como [`~PreTrainedModel.save_pretrained`] ou
203
+ [`~PreTrainedModel.push_to_hub`]. Usaremos o segundo na próxima seção e veremos como enviar os pesos e
204
+ o código do nosso modelo. Mas primeiro, vamos carregar alguns pesos pré-treinados dentro do nosso modelo.
205
+
206
+ Em seu próprio caso de uso, você provavelmente estará treinando seu modelo customizado em seus próprios dados. Para este tutorial ser rápido,
207
+ usaremos a versão pré-treinada do resnet50d. Como nosso modelo é apenas um wrapper em torno dele, será
208
+ fácil de transferir esses pesos:
209
+
210
+ ```py
211
+ import timm
212
+
213
+ pretrained_model = timm.create_model("resnet50d", pretrained=True)
214
+ resnet50d.model.load_state_dict(pretrained_model.state_dict())
215
+ ```
216
+
217
+ Agora vamos ver como ter certeza de que quando fazemos [`~PreTrainedModel.save_pretrained`] ou [`~PreTrainedModel.push_to_hub`], o
218
+ código do modelo é salvo.
219
+
220
+ ## Enviando o código para o Hub
221
+
222
+ <Tip warning={true}>
223
+
224
+ Esta API é experimental e pode ter algumas pequenas alterações nas próximas versões.
225
+
226
+ </Tip>
227
+
228
+ Primeiro, certifique-se de que seu modelo esteja totalmente definido em um arquivo `.py`. Ele pode contar com importações relativas para alguns outros arquivos
229
+ desde que todos os arquivos estejam no mesmo diretório (ainda não suportamos submódulos para este recurso). Para o nosso exemplo,
230
+ vamos definir um arquivo `modeling_resnet.py` e um arquivo `configuration_resnet.py` em uma pasta no
231
+ diretório de trabalho atual chamado `resnet_model`. O arquivo de configuração contém o código para `ResnetConfig` e o arquivo de modelagem
232
+ contém o código do `ResnetModel` e `ResnetModelForImageClassification`.
233
+
234
+ ```
235
+ .
236
+ └── resnet_model
237
+ ├── __init__.py
238
+ ├── configuration_resnet.py
239
+ └── modeling_resnet.py
240
+ ```
241
+
242
+ O `__init__.py` pode estar vazio, apenas está lá para que o Python detecte que o `resnet_model` possa ser usado como um módulo.
243
+
244
+ <Tip warning={true}>
245
+
246
+ Se estiver copiando arquivos de modelagem da biblioteca, você precisará substituir todas as importações relativas na parte superior do arquivo
247
+ para importar do pacote `transformers`.
248
+
249
+ </Tip>
250
+
251
+ Observe que você pode reutilizar (ou subclasse) uma configuração/modelo existente.
252
+
253
+ Para compartilhar seu modelo com a comunidade, siga estas etapas: primeiro importe o modelo ResNet e a configuração do
254
+ arquivos criados:
255
+
256
+ ```py
257
+ from resnet_model.configuration_resnet import ResnetConfig
258
+ from resnet_model.modeling_resnet import ResnetModel, ResnetModelForImageClassification
259
+ ```
260
+
261
+ Então você tem que dizer à biblioteca que deseja copiar os arquivos de código desses objetos ao usar o `save_pretrained`
262
+ e registrá-los corretamente com uma determinada classe automáticas (especialmente para modelos), basta executar:
263
+
264
+ ```py
265
+ ResnetConfig.register_for_auto_class()
266
+ ResnetModel.register_for_auto_class("AutoModel")
267
+ ResnetModelForImageClassification.register_for_auto_class("AutoModelForImageClassification")
268
+ ```
269
+
270
+ Observe que não há necessidade de especificar uma classe automática para a configuração (há apenas uma classe automática,
271
+ [`AutoConfig`]), mas é diferente para os modelos. Seu modelo customizado pode ser adequado para muitas tarefas diferentes, então você
272
+ tem que especificar qual das classes automáticas é a correta para o seu modelo.
273
+
274
+ Em seguida, vamos criar a configuração e os modelos como fizemos antes:
275
+
276
+ ```py
277
+ resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True)
278
+ resnet50d = ResnetModelForImageClassification(resnet50d_config)
279
+
280
+ pretrained_model = timm.create_model("resnet50d", pretrained=True)
281
+ resnet50d.model.load_state_dict(pretrained_model.state_dict())
282
+ ```
283
+
284
+ Agora para enviar o modelo para o Hub, certifique-se de estar logado. Ou execute no seu terminal:
285
+
286
+ ```bash
287
+ hf auth login
288
+ ```
289
+
290
+ ou a partir do notebook:
291
+
292
+ ```py
293
+ from huggingface_hub import notebook_login
294
+
295
+ notebook_login()
296
+ ```
297
+
298
+ Você pode então enviar para seu próprio namespace (ou uma organização da qual você é membro) assim:
299
+
300
+
301
+ ```py
302
+ resnet50d.push_to_hub("custom-resnet50d")
303
+ ```
304
+
305
+ Além dos pesos do modelo e da configuração no formato json, isso também copiou o modelo e
306
+ configuração `.py` na pasta `custom-resnet50d` e carregou o resultado para o Hub. Você pode conferir o resultado
307
+ neste [repositório de modelos](https://huggingface.co/sgugger/custom-resnet50d).
308
+
309
+ Consulte o [tutorial de compartilhamento](model_sharing) para obter mais informações sobre o método push_to_hub.
310
+
311
+ ## Usando um modelo com código customizado
312
+
313
+ Você pode usar qualquer configuração, modelo ou tokenizador com arquivos de código customizados em seu repositório com as classes automáticas e
314
+ o método `from_pretrained`. Todos os arquivos e códigos carregados no Hub são verificados quanto a malware (consulte a documentação de [Segurança do Hub](https://huggingface.co/docs/hub/security#malware-scanning) para obter mais informações), mas você ainda deve
315
+ revisar o código do modelo e o autor para evitar a execução de código malicioso em sua máquina. Defina `trust_remote_code=True` para usar
316
+ um modelo com código customizado:
317
+
318
+ ```py
319
+ from transformers import AutoModelForImageClassification
320
+
321
+ model = AutoModelForImageClassification.from_pretrained("sgugger/custom-resnet50d", trust_remote_code=True)
322
+ ```
323
+
324
+ Também é fortemente recomendado passar um hash de confirmação como uma `revisão` para garantir que o autor dos modelos não
325
+ atualize o código com novas linhas maliciosas (a menos que você confie totalmente nos autores dos modelos).
326
+
327
+
328
+ ```py
329
+ commit_hash = "ed94a7c6247d8aedce4647f00f20de6875b5b292"
330
+ model = AutoModelForImageClassification.from_pretrained(
331
+ "sgugger/custom-resnet50d", trust_remote_code=True, revision=commit_hash
332
+ )
333
+ ```
334
+
335
+ Observe que ao navegar no histórico de commits do repositório do modelo no Hub, há um botão para copiar facilmente o commit
336
+ hash de qualquer commit.
337
+
338
+ ## Registrando um modelo com código customizado para as classes automáticas
339
+
340
+ Se você estiver escrevendo uma biblioteca que estende 🤗 Transformers, talvez queira estender as classes automáticas para incluir seus próprios
341
+ modelos. Isso é diferente de enviar o código para o Hub no sentido de que os usuários precisarão importar sua biblioteca para
342
+ obter os modelos customizados (ao contrário de baixar automaticamente o código do modelo do Hub).
343
+
344
+ Desde que sua configuração tenha um atributo `model_type` diferente dos tipos de modelo existentes e que as classes do seu modelo
345
+ tenha os atributos `config_class` corretos, você pode simplesmente adicioná-los às classes automáticas assim:
346
+
347
+ ```py
348
+ from transformers import AutoConfig, AutoModel, AutoModelForImageClassification
349
+
350
+ AutoConfig.register("resnet", ResnetConfig)
351
+ AutoModel.register(ResnetConfig, ResnetModel)
352
+ AutoModelForImageClassification.register(ResnetConfig, ResnetModelForImageClassification)
353
+ ```
354
+
355
+ Observe que o primeiro argumento usado ao registrar sua configuração customizada para [`AutoConfig`] precisa corresponder ao `model_type`
356
+ de sua configuração customizada. E o primeiro argumento usado ao registrar seus modelos customizados, para qualquer necessidade de classe de modelo automático
357
+ deve corresponder ao `config_class` desses modelos.
358
+
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/fast_tokenizers.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2020 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # Usando os Tokenizers do 🤗 Tokenizers
18
+
19
+ O [`PreTrainedTokenizerFast`] depende da biblioteca [🤗 Tokenizers](https://huggingface.co/docs/tokenizers). O Tokenizer obtido da biblioteca 🤗 Tokenizers pode ser carregado facilmente pelo 🤗 Transformers.
20
+
21
+ Antes de entrar nos detalhes, vamos começar criando um tokenizer fictício em algumas linhas:
22
+
23
+ ```python
24
+ >>> from tokenizers import Tokenizer
25
+ >>> from tokenizers.models import BPE
26
+ >>> from tokenizers.trainers import BpeTrainer
27
+ >>> from tokenizers.pre_tokenizers import Whitespace
28
+
29
+ >>> tokenizer = Tokenizer(BPE(unk_token="[UNK]"))
30
+ >>> trainer = BpeTrainer(special_tokens=["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"])
31
+
32
+ >>> tokenizer.pre_tokenizer = Whitespace()
33
+ >>> files = [...]
34
+ >>> tokenizer.train(files, trainer)
35
+ ```
36
+
37
+ Agora temos um tokenizer treinado nos arquivos que foram definidos. Nós podemos continuar usando nessa execução ou salvar em um arquivo JSON para re-utilizar no futuro.
38
+
39
+ ## Carregando diretamente de um objeto tokenizer
40
+
41
+ Vamos ver como aproveitar esse objeto tokenizer na biblioteca 🤗 Transformers. A classe [`PreTrainedTokenizerFast`] permite uma instanciação fácil, aceitando o objeto *tokenizer* instanciado como um argumento:
42
+
43
+ ```python
44
+ >>> from transformers import PreTrainedTokenizerFast
45
+
46
+ >>> fast_tokenizer = PreTrainedTokenizerFast(tokenizer_object=tokenizer)
47
+ ```
48
+ Esse objeto pode ser utilizado com todos os métodos compartilhados pelos tokenizers dos 🤗 Transformers! Vá para [a página do tokenizer](main_classes/tokenizer) para mais informações.
49
+
50
+ ## Carregando de um arquivo JSON
51
+
52
+ Para carregar um tokenizer de um arquivo JSON vamos primeiro começar salvando nosso tokenizer:
53
+
54
+ ```python
55
+ >>> tokenizer.save("tokenizer.json")
56
+ ```
57
+
58
+ A pasta para qual salvamos esse arquivo pode ser passada para o método de inicialização do [`PreTrainedTokenizerFast`] usando o `tokenizer_file` parâmetro:
59
+
60
+ ```python
61
+ >>> from transformers import PreTrainedTokenizerFast
62
+
63
+ >>> fast_tokenizer = PreTrainedTokenizerFast(tokenizer_file="tokenizer.json")
64
+ ```
65
+
66
+ Esse objeto pode ser utilizado com todos os métodos compartilhados pelos tokenizers dos 🤗 Transformers! Vá para [a página do tokenizer](main_classes/tokenizer) para mais informações.
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/index.md ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2020 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # 🤗 Transformers
18
+
19
+
20
+ Estado da Arte para Aprendizado de Máquina em PyTorch, TensorFlow e JAX.
21
+ O 🤗 Transformers disponibiliza APIs para facilmente baixar e treinar modelos pré-treinados de última geração.
22
+ O uso de modelos pré-treinados pode diminuir os seus custos de computação, a sua pegada de carbono, além de economizar o
23
+ tempo necessário para se treinar um modelo do zero. Os modelos podem ser usados para diversas tarefas:
24
+
25
+ * 📝 Textos: classificação, extração de informações, perguntas e respostas, resumir, traduzir e gerar textos em mais de 100 idiomas.
26
+ * 🖼 Imagens: classificação, deteção de objetos, e segmentação.
27
+ * 🗣 Audio: reconhecimento de fala e classificação de áudio.
28
+ * 🐙 Multimodal: perguntas tabeladas e respsostas, reconhecimento ótico de charactéres, extração de informação de
29
+ documentos escaneados, classificação de vídeo, perguntas e respostas visuais.
30
+
31
+ Nossa biblioteca aceita integração contínua entre três das bibliotecas mais populares de aprendizado profundo:
32
+ Our library supports seamless integration between three of the most popular deep learning libraries:
33
+ [PyTorch](https://pytorch.org/), [TensorFlow](https://www.tensorflow.org/) e [JAX](https://jax.readthedocs.io/en/latest/).
34
+ Treine seu modelo em três linhas de código em um framework, e carregue-o para execução em outro.
35
+
36
+ Cada arquitetura 🤗 Transformers é definida em um módulo individual do Python, para que seja facilmente customizável para pesquisa e experimentos.
37
+
38
+ ## Se você estiver procurando suporte do time da Hugging Face, acesse
39
+
40
+ <a target="_blank" href="https://huggingface.co/support">
41
+ <img alt="HuggingFace Expert Acceleration Program" src="https://huggingface.co/front/thumbnails/support.png" style="width: 100%; max-width: 600px; border: 1px solid #eee; border-radius: 4px; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);">
42
+ </a>
43
+
44
+ ## Conteúdo
45
+
46
+ A documentação é dividida em cinco partes:
47
+ - **INÍCIO** contém um tour rápido de instalação e instruções para te dar um empurrão inicial com os 🤗 Transformers.
48
+ - **TUTORIAIS** são perfeitos para começar a aprender sobre a nossa biblioteca. Essa seção irá te ajudar a desenvolver
49
+ habilidades básicas necessárias para usar o 🤗 Transformers.
50
+ - **GUIAS PRÁTICOS** irão te mostrar como alcançar um certo objetivo, como o fine-tuning de um modelo pré-treinado
51
+ para modelamento de idioma, ou como criar um cabeçalho personalizado para um modelo.
52
+ - **GUIAS CONCEITUAIS** te darão mais discussões e explicações dos conceitos fundamentais e idéias por trás dos modelos,
53
+ tarefas e da filosofia de design por trás do 🤗 Transformers.
54
+ - **API** descreve o funcionamento de cada classe e função, agrupada em:
55
+
56
+ - **CLASSES PRINCIPAIS** para as classes que expõe as APIs importantes da biblioteca.
57
+ - **MODELOS** para as classes e funções relacionadas à cada modelo implementado na biblioteca.
58
+ - **AUXILIARES INTERNOS** para as classes e funções usadas internamente.
59
+
60
+ Atualmente a biblioteca contém implementações do PyTorch, TensorFlow e JAX, pesos para modelos pré-treinados e scripts de uso e conversão de utilidades para os seguintes modelos:
61
+
62
+ ### Modelos atuais
63
+
64
+ <!--This list is updated automatically from the README with _make fix-copies_. Do not update manually! -->
65
+
66
+ 1. **[ALBERT](model_doc/albert)** (from Google Research and the Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://huggingface.co/papers/1909.11942), by Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.
67
+ 1. **[BART](model_doc/bart)** (from Facebook) released with the paper [BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension](https://huggingface.co/papers/1910.13461) by Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer.
68
+ 1. **[BARThez](model_doc/barthez)** (from École polytechnique) released with the paper [BARThez: a Skilled Pretrained French Sequence-to-Sequence Model](https://huggingface.co/papers/2010.12321) by Moussa Kamal Eddine, Antoine J.-P. Tixier, Michalis Vazirgiannis.
69
+ 1. **[BARTpho](model_doc/bartpho)** (from VinAI Research) released with the paper [BARTpho: Pre-trained Sequence-to-Sequence Models for Vietnamese](https://huggingface.co/papers/2109.09701) by Nguyen Luong Tran, Duong Minh Le and Dat Quoc Nguyen.
70
+ 1. **[BEiT](model_doc/beit)** (from Microsoft) released with the paper [BEiT: BERT Pre-Training of Image Transformers](https://huggingface.co/papers/2106.08254) by Hangbo Bao, Li Dong, Furu Wei.
71
+ 1. **[BERT](model_doc/bert)** (from Google) released with the paper [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://huggingface.co/papers/1810.04805) by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova.
72
+ 1. **[BERTweet](model_doc/bertweet)** (from VinAI Research) released with the paper [BERTweet: A pre-trained language model for English Tweets](https://aclanthology.org/2020.emnlp-demos.2/) by Dat Quoc Nguyen, Thanh Vu and Anh Tuan Nguyen.
73
+ 1. **[BERT For Sequence Generation](model_doc/bert-generation)** (from Google) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://huggingface.co/papers/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
74
+ 1. **[BigBird-RoBERTa](model_doc/big_bird)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://huggingface.co/papers/2007.14062) by Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed.
75
+ 1. **[BigBird-Pegasus](model_doc/bigbird_pegasus)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://huggingface.co/papers/2007.14062) by Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed.
76
+ 1. **[Blenderbot](model_doc/blenderbot)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://huggingface.co/papers/2004.13637) by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston.
77
+ 1. **[BlenderbotSmall](model_doc/blenderbot-small)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://huggingface.co/papers/2004.13637) by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston.
78
+ 1. **[BORT](model_doc/bort)** (from Alexa) released with the paper [Optimal Subarchitecture Extraction For BERT](https://huggingface.co/papers/2010.10499) by Adrian de Wynter and Daniel J. Perry.
79
+ 1. **[ByT5](model_doc/byt5)** (from Google Research) released with the paper [ByT5: Towards a token-free future with pre-trained byte-to-byte models](https://huggingface.co/papers/2105.13626) by Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, Colin Raffel.
80
+ 1. **[CamemBERT](model_doc/camembert)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://huggingface.co/papers/1911.03894) by Louis Martin*, Benjamin Muller*, Pedro Javier Ortiz Suárez*, Yoann Dupont, Laurent Romary, Éric Villemonte de la Clergerie, Djamé Seddah and Benoît Sagot.
81
+ 1. **[CANINE](model_doc/canine)** (from Google Research) released with the paper [CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation](https://huggingface.co/papers/2103.06874) by Jonathan H. Clark, Dan Garrette, Iulia Turc, John Wieting.
82
+ 1. **[ConvNeXT](model_doc/convnext)** (from Facebook AI) released with the paper [A ConvNet for the 2020s](https://huggingface.co/papers/2201.03545) by Zhuang Liu, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, Saining Xie.
83
+ 1. **[ConvNeXTV2](model_doc/convnextv2)** (from Facebook AI) released with the paper [ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders](https://huggingface.co/papers/2301.00808) by Sanghyun Woo, Shoubhik Debnath, Ronghang Hu, Xinlei Chen, Zhuang Liu, In So Kweon, Saining Xie.
84
+ 1. **[CLIP](model_doc/clip)** (from OpenAI) released with the paper [Learning Transferable Visual Models From Natural Language Supervision](https://huggingface.co/papers/2103.00020) by Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, Gretchen Krueger, Ilya Sutskever.
85
+ 1. **[ConvBERT](model_doc/convbert)** (from YituTech) released with the paper [ConvBERT: Improving BERT with Span-based Dynamic Convolution](https://huggingface.co/papers/2008.02496) by Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng Yan.
86
+ 1. **[CPM](model_doc/cpm)** (from Tsinghua University) released with the paper [CPM: A Large-scale Generative Chinese Pre-trained Language Model](https://huggingface.co/papers/2012.00413) by Zhengyan Zhang, Xu Han, Hao Zhou, Pei Ke, Yuxian Gu, Deming Ye, Yujia Qin, Yusheng Su, Haozhe Ji, Jian Guan, Fanchao Qi, Xiaozhi Wang, Yanan Zheng, Guoyang Zeng, Huanqi Cao, Shengqi Chen, Daixuan Li, Zhenbo Sun, Zhiyuan Liu, Minlie Huang, Wentao Han, Jie Tang, Juanzi Li, Xiaoyan Zhu, Maosong Sun.
87
+ 1. **[CTRL](model_doc/ctrl)** (from Salesforce) released with the paper [CTRL: A Conditional Transformer Language Model for Controllable Generation](https://huggingface.co/papers/1909.05858) by Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong and Richard Socher.
88
+ 1. **[Data2Vec](model_doc/data2vec)** (from Facebook) released with the paper [Data2Vec: A General Framework for Self-supervised Learning in Speech, Vision and Language](https://huggingface.co/papers/2202.03555) by Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu, Michael Auli.
89
+ 1. **[DeBERTa](model_doc/deberta)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://huggingface.co/papers/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
90
+ 1. **[DeBERTa-v2](model_doc/deberta-v2)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://huggingface.co/papers/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
91
+ 1. **[Decision Transformer](model_doc/decision_transformer)** (from Berkeley/Facebook/Google) released with the paper [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://huggingface.co/papers/2106.01345) by Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch.
92
+ 1. **[DiT](model_doc/dit)** (from Microsoft Research) released with the paper [DiT: Self-supervised Pre-training for Document Image Transformer](https://huggingface.co/papers/2203.02378) by Junlong Li, Yiheng Xu, Tengchao Lv, Lei Cui, Cha Zhang, Furu Wei.
93
+ 1. **[DeiT](model_doc/deit)** (from Facebook) released with the paper [Training data-efficient image transformers & distillation through attention](https://huggingface.co/papers/2012.12877) by Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, Hervé Jégou.
94
+ 1. **[DETR](model_doc/detr)** (from Facebook) released with the paper [End-to-End Object Detection with Transformers](https://huggingface.co/papers/2005.12872) by Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko.
95
+ 1. **[DialoGPT](model_doc/dialogpt)** (from Microsoft Research) released with the paper [DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation](https://huggingface.co/papers/1911.00536) by Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dolan.
96
+ 1. **[DistilBERT](model_doc/distilbert)** (from HuggingFace), released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://huggingface.co/papers/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same method has been applied to compress GPT2 into [DistilGPT2](https://github.com/huggingface/transformers-research-projects/tree/main/distillation), RoBERTa into [DistilRoBERTa](https://github.com/huggingface/transformers-research-projects/tree/main/distillation), Multilingual BERT into [DistilmBERT](https://github.com/huggingface/transformers-research-projects/tree/main/distillation) and a German version of DistilBERT.
97
+ 1. **[DPR](model_doc/dpr)** (from Facebook) released with the paper [Dense Passage Retrieval for Open-Domain Question Answering](https://huggingface.co/papers/2004.04906) by Vladimir Karpukhin, Barlas Oğuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih.
98
+ 1. **[DPT](master/model_doc/dpt)** (from Intel Labs) released with the paper [Vision Transformers for Dense Prediction](https://huggingface.co/papers/2103.13413) by René Ranftl, Alexey Bochkovskiy, Vladlen Koltun.
99
+ 1. **[EfficientNet](model_doc/efficientnet)** (from Google Research) released with the paper [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://huggingface.co/papers/1905.11946) by Mingxing Tan and Quoc V. Le.
100
+ 1. **[EncoderDecoder](model_doc/encoder-decoder)** (from Google Research) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://huggingface.co/papers/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
101
+ 1. **[ELECTRA](model_doc/electra)** (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders as discriminators rather than generators](https://huggingface.co/papers/2003.10555) by Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning.
102
+ 1. **[FlauBERT](model_doc/flaubert)** (from CNRS) released with the paper [FlauBERT: Unsupervised Language Model Pre-training for French](https://huggingface.co/papers/1912.05372) by Hang Le, Loïc Vial, Jibril Frej, Vincent Segonne, Maximin Coavoux, Benjamin Lecouteux, Alexandre Allauzen, Benoît Crabbé, Laurent Besacier, Didier Schwab.
103
+ 1. **[FNet](model_doc/fnet)** (from Google Research) released with the paper [FNet: Mixing Tokens with Fourier Transforms](https://huggingface.co/papers/2105.03824) by James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon.
104
+ 1. **[Funnel Transformer](model_doc/funnel)** (from CMU/Google Brain) released with the paper [Funnel-Transformer: Filtering out Sequential Redundancy for Efficient Language Processing](https://huggingface.co/papers/2006.03236) by Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le.
105
+ 1. **[GLPN](model_doc/glpn)** (from KAIST) released with the paper [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://huggingface.co/papers/2201.07436) by Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim.
106
+ 1. **[GPT](model_doc/openai-gpt)** (from OpenAI) released with the paper [Improving Language Understanding by Generative Pre-Training](https://openai.com/research/language-unsupervised/) by Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever.
107
+ 1. **[GPT-2](model_doc/gpt2)** (from OpenAI) released with the paper [Language Models are Unsupervised Multitask Learners](https://openai.com/research/better-language-models/) by Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei and Ilya Sutskever.
108
+ 1. **[GPT-J](model_doc/gptj)** (from EleutherAI) released in the repository [kingoflolz/mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax/) by Ben Wang and Aran Komatsuzaki.
109
+ 1. **[GPT Neo](model_doc/gpt_neo)** (from EleutherAI) released in the repository [EleutherAI/gpt-neo](https://github.com/EleutherAI/gpt-neo) by Sid Black, Stella Biderman, Leo Gao, Phil Wang and Connor Leahy.
110
+ 1. **[GPTSAN-japanese](model_doc/gptsan-japanese)** released in the repository [tanreinama/GPTSAN](https://github.com/tanreinama/GPTSAN/blob/main/report/model.md) by Toshiyuki Sakamoto(tanreinama).
111
+ 1. **[Hubert](model_doc/hubert)** (from Facebook) released with the paper [HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units](https://huggingface.co/papers/2106.07447) by Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed.
112
+ 1. **[I-BERT](model_doc/ibert)** (from Berkeley) released with the paper [I-BERT: Integer-only BERT Quantization](https://huggingface.co/papers/2101.01321) by Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney, Kurt Keutzer.
113
+ 1. **[ImageGPT](model_doc/imagegpt)** (from OpenAI) released with the paper [Generative Pretraining from Pixels](https://openai.com/blog/image-gpt/) by Mark Chen, Alec Radford, Rewon Child, Jeffrey Wu, Heewoo Jun, David Luan, Ilya Sutskever.
114
+ 1. **[LayoutLM](model_doc/layoutlm)** (from Microsoft Research Asia) released with the paper [LayoutLM: Pre-training of Text and Layout for Document Image Understanding](https://huggingface.co/papers/1912.13318) by Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou.
115
+ 1. **[LayoutLMv2](model_doc/layoutlmv2)** (from Microsoft Research Asia) released with the paper [LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding](https://huggingface.co/papers/2012.14740) by Yang Xu, Yiheng Xu, Tengchao Lv, Lei Cui, Furu Wei, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Wanxiang Che, Min Zhang, Lidong Zhou.
116
+ 1. **[LayoutXLM](model_doc/layoutxlm)** (from Microsoft Research Asia) released with the paper [LayoutXLM: Multimodal Pre-training for Multilingual Visually-rich Document Understanding](https://huggingface.co/papers/2104.08836) by Yiheng Xu, Tengchao Lv, Lei Cui, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Furu Wei.
117
+ 1. **[LED](model_doc/led)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://huggingface.co/papers/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
118
+ 1. **[Longformer](model_doc/longformer)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://huggingface.co/papers/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
119
+ 1. **[LUKE](model_doc/luke)** (from Studio Ousia) released with the paper [LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention](https://huggingface.co/papers/2010.01057) by Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda, Yuji Matsumoto.
120
+ 1. **[mLUKE](model_doc/mluke)** (from Studio Ousia) released with the paper [mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models](https://huggingface.co/papers/2110.08151) by Ryokan Ri, Ikuya Yamada, and Yoshimasa Tsuruoka.
121
+ 1. **[LXMERT](model_doc/lxmert)** (from UNC Chapel Hill) released with the paper [LXMERT: Learning Cross-Modality Encoder Representations from Transformers for Open-Domain Question Answering](https://huggingface.co/papers/1908.07490) by Hao Tan and Mohit Bansal.
122
+ 1. **[M2M100](model_doc/m2m_100)** (from Facebook) released with the paper [Beyond English-Centric Multilingual Machine Translation](https://huggingface.co/papers/2010.11125) by Angela Fan, Shruti Bhosale, Holger Schwenk, Zhiyi Ma, Ahmed El-Kishky, Siddharth Goyal, Mandeep Baines, Onur Celebi, Guillaume Wenzek, Vishrav Chaudhary, Naman Goyal, Tom Birch, Vitaliy Liptchinsky, Sergey Edunov, Edouard Grave, Michael Auli, Armand Joulin.
123
+ 1. **[MarianMT](model_doc/marian)** Machine translation models trained using [OPUS](http://opus.nlpl.eu/) data by Jörg Tiedemann. The [Marian Framework](https://marian-nmt.github.io/) is being developed by the Microsoft Translator Team.
124
+ 1. **[Mask2Former](model_doc/mask2former)** (from FAIR and UIUC) released with the paper [Masked-attention Mask Transformer for Universal Image Segmentation](https://huggingface.co/papers/2112.01527) by Bowen Cheng, Ishan Misra, Alexander G. Schwing, Alexander Kirillov, Rohit Girdhar.
125
+ 1. **[MaskFormer](model_doc/maskformer)** (from Meta and UIUC) released with the paper [Per-Pixel Classification is Not All You Need for Semantic Segmentation](https://huggingface.co/papers/2107.06278) by Bowen Cheng, Alexander G. Schwing, Alexander Kirillov.
126
+ 1. **[MBart](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Denoising Pre-training for Neural Machine Translation](https://huggingface.co/papers/2001.08210) by Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer.
127
+ 1. **[MBart-50](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Translation with Extensible Multilingual Pretraining and Finetuning](https://huggingface.co/papers/2008.00401) by Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan.
128
+ 1. **[Megatron-BERT](model_doc/megatron-bert)** (from NVIDIA) released with the paper [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://huggingface.co/papers/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
129
+ 1. **[Megatron-GPT2](model_doc/megatron_gpt2)** (from NVIDIA) released with the paper [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://huggingface.co/papers/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
130
+ 1. **[MPNet](model_doc/mpnet)** (from Microsoft Research) released with the paper [MPNet: Masked and Permuted Pre-training for Language Understanding](https://huggingface.co/papers/2004.09297) by Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu.
131
+ 1. **[MT5](model_doc/mt5)** (from Google AI) released with the paper [mT5: A massively multilingual pre-trained text-to-text transformer](https://huggingface.co/papers/2010.11934) by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel.
132
+ 1. **[Nyströmformer](model_doc/nystromformer)** (from the University of Wisconsin - Madison) released with the paper [Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention](https://huggingface.co/papers/2102.03902) by Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh.
133
+ 1. **[OneFormer](model_doc/oneformer)** (from SHI Labs) released with the paper [OneFormer: One Transformer to Rule Universal Image Segmentation](https://huggingface.co/papers/2211.06220) by Jitesh Jain, Jiachen Li, MangTik Chiu, Ali Hassani, Nikita Orlov, Humphrey Shi.
134
+ 1. **[Pegasus](model_doc/pegasus)** (from Google) released with the paper [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://huggingface.co/papers/1912.08777) by Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu.
135
+ 1. **[Perceiver IO](model_doc/perceiver)** (from Deepmind) released with the paper [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://huggingface.co/papers/2107.14795) by Andrew Jaegle, Sebastian Borgeaud, Jean-Baptiste Alayrac, Carl Doersch, Catalin Ionescu, David Ding, Skanda Koppula, Daniel Zoran, Andrew Brock, Evan Shelhamer, Olivier Hénaff, Matthew M. Botvinick, Andrew Zisserman, Oriol Vinyals, João Carreira.
136
+ 1. **[PhoBERT](model_doc/phobert)** (from VinAI Research) released with the paper [PhoBERT: Pre-trained language models for Vietnamese](https://www.aclweb.org/anthology/2020.findings-emnlp.92/) by Dat Quoc Nguyen and Anh Tuan Nguyen.
137
+ 1. **[PLBart](model_doc/plbart)** (from UCLA NLP) released with the paper [Unified Pre-training for Program Understanding and Generation](https://huggingface.co/papers/2103.06333) by Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang.
138
+ 1. **[PoolFormer](model_doc/poolformer)** (from Sea AI Labs) released with the paper [MetaFormer is Actually What You Need for Vision](https://huggingface.co/papers/2111.11418) by Yu, Weihao and Luo, Mi and Zhou, Pan and Si, Chenyang and Zhou, Yichen and Wang, Xinchao and Feng, Jiashi and Yan, Shuicheng.
139
+ 1. **[ProphetNet](model_doc/prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://huggingface.co/papers/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
140
+ 1. **[QDQBert](model_doc/qdqbert)** (from NVIDIA) released with the paper [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://huggingface.co/papers/2004.09602) by Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev and Paulius Micikevicius.
141
+ 1. **[REALM](model_doc/realm.html)** (from Google Research) released with the paper [REALM: Retrieval-Augmented Language Model Pre-Training](https://huggingface.co/papers/2002.08909) by Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang.
142
+ 1. **[Reformer](model_doc/reformer)** (from Google Research) released with the paper [Reformer: The Efficient Transformer](https://huggingface.co/papers/2001.04451) by Nikita Kitaev, Łukasz Kaiser, Anselm Levskaya.
143
+ 1. **[RemBERT](model_doc/rembert)** (from Google Research) released with the paper [Rethinking embedding coupling in pre-trained language models](https://huggingface.co/papers/2010.12821) by Hyung Won Chung, Thibault Févry, Henry Tsai, M. Johnson, Sebastian Ruder.
144
+ 1. **[RegNet](model_doc/regnet)** (from META Platforms) released with the paper [Designing Network Design Space](https://huggingface.co/papers/2003.13678) by Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr Dollár.
145
+ 1. **[ResNet](model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://huggingface.co/papers/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun.
146
+ 1. **[RoBERTa](model_doc/roberta)** (from Facebook), released together with the paper [RoBERTa: A Robustly Optimized BERT Pretraining Approach](https://huggingface.co/papers/1907.11692) by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov.
147
+ 1. **[RoFormer](model_doc/roformer)** (from ZhuiyiTechnology), released together with the paper [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://huggingface.co/papers/2104.09864) by Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu.
148
+ 1. **[SegFormer](model_doc/segformer)** (from NVIDIA) released with the paper [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://huggingface.co/papers/2105.15203) by Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo.
149
+ 1. **[SEW](model_doc/sew)** (from ASAPP) released with the paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://huggingface.co/papers/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
150
+ 1. **[SEW-D](model_doc/sew_d)** (from ASAPP) released with the paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://huggingface.co/papers/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
151
+ 1. **[SpeechToTextTransformer](model_doc/speech_to_text)** (from Facebook), released together with the paper [fairseq S2T: Fast Speech-to-Text Modeling with fairseq](https://huggingface.co/papers/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino.
152
+ 1. **[SpeechToTextTransformer2](model_doc/speech_to_text_2)** (from Facebook), released together with the paper [Large-Scale Self- and Semi-Supervised Learning for Speech Translation](https://huggingface.co/papers/2104.06678) by Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau.
153
+ 1. **[Splinter](model_doc/splinter)** (from Tel Aviv University), released together with the paper [Few-Shot Question Answering by Pretraining Span Selection](https://huggingface.co/papers/2101.00438) by Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy.
154
+ 1. **[SqueezeBert](model_doc/squeezebert)** (from Berkeley) released with the paper [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://huggingface.co/papers/2006.11316) by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer.
155
+ 1. **[Swin Transformer](model_doc/swin)** (from Microsoft) released with the paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://huggingface.co/papers/2103.14030) by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo.
156
+ 1. **[T5](model_doc/t5)** (from Google AI) released with the paper [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://huggingface.co/papers/1910.10683) by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu.
157
+ 1. **[T5v1.1](model_doc/t5v1.1)** (from Google AI) released in the repository [google-research/text-to-text-transfer-transformer](https://github.com/google-research/text-to-text-transfer-transformer/blob/main/released_checkpoints.md#t511) by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu.
158
+ 1. **[TAPAS](model_doc/tapas)** (from Google AI) released with the paper [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://huggingface.co/papers/2004.02349) by Jonathan Herzig, Paweł Krzysztof Nowak, Thomas Müller, Francesco Piccinno and Julian Martin Eisenschlos.
159
+ 1. **[TAPEX](model_doc/tapex)** (from Microsoft Research) released with the paper [TAPEX: Table Pre-training via Learning a Neural SQL Executor](https://huggingface.co/papers/2107.07653) by Qian Liu, Bei Chen, Jiaqi Guo, Morteza Ziyadi, Zeqi Lin, Weizhu Chen, Jian-Guang Lou.
160
+ 1. **[Transformer-XL](model_doc/transfo-xl)** (from Google/CMU) released with the paper [Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context](https://huggingface.co/papers/1901.02860) by Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov.
161
+ 1. **[TrOCR](model_doc/trocr)** (from Microsoft), released together with the paper [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://huggingface.co/papers/2109.10282) by Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei.
162
+ 1. **[UniSpeech](model_doc/unispeech)** (from Microsoft Research) released with the paper [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://huggingface.co/papers/2101.07597) by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang.
163
+ 1. **[UniSpeechSat](model_doc/unispeech-sat)** (from Microsoft Research) released with the paper [UNISPEECH-SAT: UNIVERSAL SPEECH REPRESENTATION LEARNING WITH SPEAKER AWARE PRE-TRAINING](https://huggingface.co/papers/2110.05752) by Sanyuan Chen, Yu Wu, Chengyi Wang, Zhengyang Chen, Zhuo Chen, Shujie Liu, Jian Wu, Yao Qian, Furu Wei, Jinyu Li, Xiangzhan Yu.
164
+ 1. **[VAN](model_doc/van)** (from Tsinghua University and Nankai University) released with the paper [Visual Attention Network](https://huggingface.co/papers/2202.09741) by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu.
165
+ 1. **[ViLT](model_doc/vilt)** (from NAVER AI Lab/Kakao Enterprise/Kakao Brain) released with the paper [ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision](https://huggingface.co/papers/2102.03334) by Wonjae Kim, Bokyung Son, Ildoo Kim.
166
+ 1. **[Vision Transformer (ViT)](model_doc/vit)** (from Google AI) released with the paper [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://huggingface.co/papers/2010.11929) by Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby.
167
+ 1. **[ViTMAE](model_doc/vit_mae)** (from Meta AI) released with the paper [Masked Autoencoders Are Scalable Vision Learners](https://huggingface.co/papers/2111.06377) by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr Dollár, Ross Girshick.
168
+ 1. **[VisualBERT](model_doc/visual_bert)** (from UCLA NLP) released with the paper [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://huggingface.co/papers/1908.03557) by Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang.
169
+ 1. **[WavLM](model_doc/wavlm)** (from Microsoft Research) released with the paper [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://huggingface.co/papers/2110.13900) by Sanyuan Chen, Chengyi Wang, Zhengyang Chen, Yu Wu, Shujie Liu, Zhuo Chen, Jinyu Li, Naoyuki Kanda, Takuya Yoshioka, Xiong Xiao, Jian Wu, Long Zhou, Shuo Ren, Yanmin Qian, Yao Qian, Jian Wu, Michael Zeng, Furu Wei.
170
+ 1. **[Wav2Vec2](model_doc/wav2vec2)** (from Facebook AI) released with the paper [wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations](https://huggingface.co/papers/2006.11477) by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli.
171
+ 1. **[Wav2Vec2Phoneme](model_doc/wav2vec2_phoneme)** (from Facebook AI) released with the paper [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://huggingface.co/papers/2109.11680) by Qiantong Xu, Alexei Baevski, Michael Auli.
172
+ 1. **[XGLM](model_doc/xglm)** (From Facebook AI) released with the paper [Few-shot Learning with Multilingual Language Models](https://huggingface.co/papers/2112.10668) by Xi Victoria Lin, Todor Mihaylov, Mikel Artetxe, Tianlu Wang, Shuohui Chen, Daniel Simig, Myle Ott, Naman Goyal, Shruti Bhosale, Jingfei Du, Ramakanth Pasunuru, Sam Shleifer, Punit Singh Koura, Vishrav Chaudhary, Brian O'Horo, Jeff Wang, Luke Zettlemoyer, Zornitsa Kozareva, Mona Diab, Veselin Stoyanov, Xian Li.
173
+ 1. **[XLM](model_doc/xlm)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://huggingface.co/papers/1901.07291) by Guillaume Lample and Alexis Conneau.
174
+ 1. **[XLM-ProphetNet](model_doc/xlm-prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://huggingface.co/papers/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
175
+ 1. **[XLM-RoBERTa](model_doc/xlm-roberta)** (from Facebook AI), released together with the paper [Unsupervised Cross-lingual Representation Learning at Scale](https://huggingface.co/papers/1911.02116) by Alexis Conneau*, Kartikay Khandelwal*, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco Guzmán, Edouard Grave, Myle Ott, Luke Zettlemoyer and Veselin Stoyanov.
176
+ 1. **[XLM-RoBERTa-XL](model_doc/xlm-roberta-xl)** (from Facebook AI), released together with the paper [Larger-Scale Transformers for Multilingual Masked Language Modeling](https://huggingface.co/papers/2105.00572) by Naman Goyal, Jingfei Du, Myle Ott, Giri Anantharaman, Alexis Conneau.
177
+ 1. **[XLNet](model_doc/xlnet)** (from Google/CMU) released with the paper [​XLNet: Generalized Autoregressive Pretraining for Language Understanding](https://huggingface.co/papers/1906.08237) by Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le.
178
+ 1. **[XLSR-Wav2Vec2](model_doc/xlsr_wav2vec2)** (from Facebook AI) released with the paper [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://huggingface.co/papers/2006.13979) by Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli.
179
+ 1. **[XLS-R](model_doc/xls_r)** (from Facebook AI) released with the paper [XLS-R: Self-supervised Cross-lingual Speech Representation Learning at Scale](https://huggingface.co/papers/2111.09296) by Arun Babu, Changhan Wang, Andros Tjandra, Kushal Lakhotia, Qiantong Xu, Naman Goyal, Kritika Singh, Patrick von Platen, Yatharth Saraf, Juan Pino, Alexei Baevski, Alexis Conneau, Michael Auli.
180
+ 1. **[YOSO](model_doc/yoso)** (from the University of Wisconsin - Madison) released with the paper [You Only Sample (Almost) Once: Linear Cost Self-Attention Via Bernoulli Sampling](https://huggingface.co/papers/2111.09714) by Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh.
181
+
182
+
183
+ ### Frameworks aceitos
184
+
185
+ A tabela abaixo representa a lista de suporte na biblioteca para cada um dos seguintes modelos, caso tenham um tokenizer
186
+ do Python (chamado de "slow"), ou um tokenizer construído em cima da biblioteca 🤗 Tokenizers (chamado de "fast"). Além
187
+ disso, são diferenciados pelo suporte em diferentes frameworks: JAX (por meio do Flax); PyTorch; e/ou Tensorflow.
188
+
189
+ <!--This table is updated automatically from the auto modules with _make fix-copies_. Do not update manually!-->
190
+
191
+ | Model | Tokenizer slow | Tokenizer fast | PyTorch support | TensorFlow support | Flax Support |
192
+ |:---------------------------:|:--------------:|:--------------:|:---------------:|:------------------:|:------------:|
193
+ | ALBERT | ✅ | ✅ | ✅ | ✅ | ✅ |
194
+ | BART | ✅ | ✅ | ✅ | ✅ | ✅ |
195
+ | BEiT | ❌ | ❌ | ✅ | ❌ | ✅ |
196
+ | BERT | ✅ | ✅ | ✅ | ✅ | ✅ |
197
+ | Bert Generation | ✅ | ❌ | ✅ | ❌ | ❌ |
198
+ | BigBird | ✅ | ✅ | ✅ | ❌ | ✅ |
199
+ | BigBirdPegasus | ❌ | ❌ | ✅ | ❌ | ❌ |
200
+ | Blenderbot | ✅ | ✅ | ✅ | ✅ | ✅ |
201
+ | BlenderbotSmall | ✅ | ✅ | ✅ | ✅ | ✅ |
202
+ | CamemBERT | ✅ | ✅ | ✅ | ✅ | ❌ |
203
+ | Canine | ✅ | ❌ | ✅ | ❌ | ❌ |
204
+ | CLIP | ✅ | ✅ | ✅ | ✅ | ✅ |
205
+ | ConvBERT | ✅ | ✅ | ✅ | ✅ | ❌ |
206
+ | ConvNext | ❌ | ❌ | ✅ | ✅ | ❌ |
207
+ | CTRL | ✅ | ❌ | ✅ | ✅ | ❌ |
208
+ | Data2VecAudio | ❌ | ❌ | ✅ | ❌ | ❌ |
209
+ | Data2VecText | ❌ | ❌ | ✅ | ❌ | ❌ |
210
+ | Data2VecVision | ❌ | ❌ | ✅ | ❌ | ❌ |
211
+ | DeBERTa | ✅ | ✅ | ✅ | ✅ | ❌ |
212
+ | DeBERTa-v2 | ✅ | ✅ | ✅ | ✅ | ❌ |
213
+ | Decision Transformer | ❌ | ❌ | ✅ | ❌ | ❌ |
214
+ | DeiT | ❌ | ❌ | ✅ | ❌ | ❌ |
215
+ | DETR | ❌ | ❌ | ✅ | ❌ | ❌ |
216
+ | DistilBERT | ✅ | ✅ | ✅ | ✅ | ✅ |
217
+ | DPR | ✅ | ✅ | ✅ | ✅ | ❌ |
218
+ | DPT | ❌ | ❌ | ✅ | ❌ | ❌ |
219
+ | ELECTRA | ✅ | ✅ | ✅ | ✅ | ✅ |
220
+ | Encoder decoder | ❌ | ❌ | ✅ | ✅ | ✅ |
221
+ | FairSeq Machine-Translation | ✅ | ❌ | ✅ | ❌ | ❌ |
222
+ | FlauBERT | ✅ | ❌ | ✅ | ✅ | ❌ |
223
+ | FNet | ✅ | ✅ | ✅ | ❌ | ❌ |
224
+ | Funnel Transformer | ✅ | ✅ | ✅ | ✅ | ❌ |
225
+ | GLPN | ❌ | ❌ | ✅ | ❌ | ❌ |
226
+ | GPT Neo | ❌ | ❌ | ✅ | ❌ | ✅ |
227
+ | GPT-J | ❌ | ❌ | ✅ | ✅ | ✅ |
228
+ | Hubert | ❌ | ❌ | ✅ | ✅ | ❌ |
229
+ | I-BERT | ❌ | ❌ | ✅ | ❌ | ❌ |
230
+ | ImageGPT | ❌ | ❌ | ✅ | ❌ | ❌ |
231
+ | LayoutLM | ✅ | ✅ | ✅ | ✅ | ❌ |
232
+ | LayoutLMv2 | ✅ | ✅ | ✅ | ❌ | ❌ |
233
+ | LED | ✅ | ✅ | ✅ | ✅ | ❌ |
234
+ | Longformer | ✅ | ✅ | ✅ | ✅ | ❌ |
235
+ | LUKE | ✅ | ❌ | ✅ | ❌ | ❌ |
236
+ | LXMERT | ✅ | ✅ | ✅ | ✅ | ❌ |
237
+ | M2M100 | ✅ | ❌ | ✅ | ❌ | ❌ |
238
+ | Marian | ✅ | ❌ | ✅ | ✅ | ✅ |
239
+ | MaskFormer | ❌ | ❌ | ✅ | ❌ | ❌ |
240
+ | mBART | ✅ | ✅ | ✅ | ✅ | ✅ |
241
+ | MegatronBert | ❌ | ❌ | ✅ | ❌ | ❌ |
242
+ | MobileBERT | ✅ | ✅ | ✅ | ✅ | ❌ |
243
+ | MPNet | ✅ | ✅ | ✅ | ✅ | ❌ |
244
+ | mT5 | ✅ | ✅ | ✅ | ✅ | ✅ |
245
+ | Nystromformer | ❌ | ❌ | ✅ | ❌ | ❌ |
246
+ | OpenAI GPT | ✅ | ✅ | ✅ | ✅ | ❌ |
247
+ | OpenAI GPT-2 | ✅ | ✅ | ✅ | ✅ | ✅ |
248
+ | Pegasus | ✅ | ✅ | ✅ | ✅ | ✅ |
249
+ | Perceiver | ✅ | ❌ | ✅ | ❌ | ❌ |
250
+ | PLBart | ✅ | ❌ | ✅ | ❌ | ❌ |
251
+ | PoolFormer | ❌ | ❌ | ✅ | ❌ | ❌ |
252
+ | ProphetNet | ✅ | ❌ | ✅ | ❌ | ❌ |
253
+ | QDQBert | ❌ | ❌ | ✅ | ❌ | ❌ |
254
+ | RAG | ✅ | ❌ | ✅ | ✅ | ❌ |
255
+ | Realm | ✅ | ✅ | ✅ | ❌ | ❌ |
256
+ | Reformer | ✅ | ✅ | ✅ | ❌ | ❌ |
257
+ | RegNet | ❌ | ❌ | ✅ | ✅ | ✅ |
258
+ | RemBERT | ✅ | ✅ | ✅ | ✅ | ❌ |
259
+ | ResNet | ❌ | ❌ | ✅ | ❌ | ✅ |
260
+ | RetriBERT | ✅ | ✅ | ✅ | ❌ | ❌ |
261
+ | RoBERTa | ✅ | ✅ | ✅ | ✅ | ✅ |
262
+ | RoFormer | ✅ | ✅ | ✅ | ✅ | ✅ |
263
+ | SegFormer | ❌ | ❌ | ✅ | ❌ | ❌ |
264
+ | SEW | ❌ | ❌ | ✅ | ❌ | ❌ |
265
+ | SEW-D | ❌ | ❌ | ✅ | ❌ | ❌ |
266
+ | Speech Encoder decoder | ❌ | ❌ | ✅ | ❌ | ✅ |
267
+ | Speech2Text | ✅ | ❌ | ✅ | ✅ | ❌ |
268
+ | Speech2Text2 | ✅ | ❌ | ❌ | ❌ | ❌ |
269
+ | Splinter | ✅ | ✅ | ✅ | ❌ | ❌ |
270
+ | SqueezeBERT | ✅ | ✅ | ✅ | ❌ | ❌ |
271
+ | Swin | ❌ | ❌ | ✅ | ❌ | ❌ |
272
+ | T5 | ✅ | ✅ | ✅ | ✅ | ✅ |
273
+ | TAPAS | ✅ | ❌ | ✅ | ✅ | ❌ |
274
+ | TAPEX | ✅ | ✅ | ✅ | ✅ | ✅ |
275
+ | Transformer-XL | ✅ | ❌ | ✅ | ✅ | ❌ |
276
+ | TrOCR | ❌ | ❌ | ✅ | ❌ | ❌ |
277
+ | UniSpeech | ❌ | ❌ | ✅ | ❌ | ❌ |
278
+ | UniSpeechSat | ❌ | ❌ | ✅ | ❌ | ❌ |
279
+ | VAN | ❌ | ❌ | ✅ | ❌ | ❌ |
280
+ | ViLT | ❌ | ❌ | ✅ | ❌ | ❌ |
281
+ | Vision Encoder decoder | ❌ | ❌ | ✅ | ✅ | ✅ |
282
+ | VisionTextDualEncoder | ❌ | ❌ | ✅ | ❌ | ✅ |
283
+ | VisualBert | ❌ | ❌ | ✅ | ❌ | ❌ |
284
+ | ViT | ❌ | ❌ | ✅ | ✅ | ✅ |
285
+ | ViTMAE | ❌ | ❌ | ✅ | ✅ | ❌ |
286
+ | Wav2Vec2 | ✅ | ❌ | ✅ | ✅ | ✅ |
287
+ | WavLM | ❌ | ❌ | ✅ | ❌ | ❌ |
288
+ | XGLM | ✅ | ✅ | ✅ | ❌ | ✅ |
289
+ | XLM | ✅ | ❌ | ✅ | ✅ | ❌ |
290
+ | XLM-RoBERTa | ✅ | ✅ | ✅ | ✅ | ✅ |
291
+ | XLM-RoBERTa-XL | ❌ | ❌ | ✅ | ❌ | ❌ |
292
+ | XLMProphetNet | ✅ | ❌ | ✅ | ❌ | ❌ |
293
+ | XLNet | ✅ | ✅ | ✅ | ✅ | ❌ |
294
+ | YOSO | ❌ | ❌ | ✅ | ❌ | ❌ |
295
+
296
+ <!-- End table-->
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/installation.md ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2022 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+
16
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
17
+ rendered properly in your Markdown viewer.
18
+
19
+ -->
20
+
21
+ # Guia de Instalação
22
+
23
+ Neste guia poderá encontrar informações para a instalação do 🤗 Transformers para qualquer biblioteca de
24
+ Machine Learning com a qual esteja a trabalhar. Além disso, poderá encontrar informações sobre como gerar cachês e
25
+ configurar o 🤗 Transformers para execução em modo offline (opcional).
26
+
27
+ 🤗 Transformers foi testado com Python 3.6+, PyTorch 1.1.0+, TensorFlow 2.0+, e Flax. Para instalar a biblioteca de
28
+ deep learning com que deseja trabalhar, siga as instruções correspondentes listadas a seguir:
29
+
30
+ * [PyTorch](https://pytorch.org/get-started/locally/)
31
+ * [TensorFlow 2.0](https://www.tensorflow.org/install/pip)
32
+ * [Flax](https://flax.readthedocs.io/en/latest/)
33
+
34
+ ## Instalação pelo Pip
35
+
36
+ É sugerido instalar o 🤗 Transformers num [ambiente virtual](https://docs.python.org/3/library/venv.html). Se precisar
37
+ de mais informações sobre ambientes virtuais em Python, consulte este [guia](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/).
38
+ Um ambiente virtual facilitará a manipulação e organização de projetos e evita problemas de compatibilidade entre dependências.
39
+
40
+ Comece criando um ambiente virtual no diretório do seu projeto:
41
+
42
+ ```bash
43
+ python -m venv .env
44
+ ```
45
+
46
+ E para ativar o ambiente virtual:
47
+
48
+ ```bash
49
+ source .env/bin/activate
50
+ ```
51
+
52
+ Agora É possível instalar o 🤗 Transformers com o comando a seguir:
53
+
54
+ ```bash
55
+ pip install transformers
56
+ ```
57
+
58
+ Somente para a CPU, é possível instalar o 🤗 Transformers e a biblioteca de deep learning respectiva apenas numa linha.
59
+
60
+ Por exemplo, para instalar o 🤗 Transformers e o PyTorch, digite:
61
+
62
+ ```bash
63
+ pip install transformers[torch]
64
+ ```
65
+
66
+ 🤗 Transformers e TensorFlow 2.0:
67
+
68
+ ```bash
69
+ pip install transformers[tf-cpu]
70
+ ```
71
+
72
+ 🤗 Transformers e Flax:
73
+
74
+ ```bash
75
+ pip install transformers[flax]
76
+ ```
77
+
78
+ Por último, verifique se o 🤗 Transformers foi instalado com sucesso usando o seguinte comando para baixar um modelo pré-treinado:
79
+
80
+ ```bash
81
+ python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('we love you'))"
82
+ ```
83
+
84
+ Em seguida, imprima um rótulo e sua pontuação:
85
+
86
+ ```bash
87
+ [{'label': 'POSITIVE', 'score': 0.9998704791069031}]
88
+ ```
89
+
90
+ ## Instalação usando a fonte
91
+
92
+ Para instalar o 🤗 Transformers a partir da fonte use o seguinte comando:
93
+
94
+ ```bash
95
+ pip install git+https://github.com/huggingface/transformers
96
+ ```
97
+
98
+ O comando acima instalará a versão `master` mais atual em vez da última versão estável. A versão `master` é útil para
99
+ utilizar os últimos updates contidos em 🤗 Transformers. Por exemplo, um erro recente pode ter sido corrigido somente
100
+ após a última versão estável, antes que houvesse um novo lançamento. No entanto, há a possibilidade que a versão `master` não esteja estável.
101
+ A equipa trata de mantér a versão `master` operacional e a maioria dos erros são resolvidos em poucas horas ou dias.
102
+ Se encontrar quaisquer problemas, por favor abra um [Issue](https://github.com/huggingface/transformers/issues) para que o
103
+ mesmo possa ser corrigido o mais rápido possível.
104
+
105
+ Verifique que o 🤗 Transformers está instalado corretamente usando o seguinte comando:
106
+
107
+ ```bash
108
+ python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('I love you'))"
109
+ ```
110
+
111
+ ## Instalação editável
112
+
113
+ Uma instalação editável será necessária caso desejas um dos seguintes:
114
+ * Usar a versão `master` do código fonte.
115
+ * Contribuir ao 🤗 Transformers e precisa testar mudanças ao código.
116
+
117
+ Para tal, clone o repositório e instale o 🤗 Transformers com os seguintes comandos:
118
+
119
+ ```bash
120
+ git clone https://github.com/huggingface/transformers.git
121
+ cd transformers
122
+ pip install -e .
123
+ ```
124
+
125
+ Estes comandos vão ligar o diretório para o qual foi clonado o repositório ao caminho de bibliotecas do Python.
126
+ O Python agora buscará dentro dos arquivos que foram clonados além dos caminhos normais da biblioteca.
127
+ Por exemplo, se os pacotes do Python se encontram instalados no caminho `~/anaconda3/envs/main/lib/python3.7/site-packages/`,
128
+ o Python também buscará módulos no diretório onde clonamos o repositório `~/transformers/`.
129
+
130
+ <Tip warning={true}>
131
+
132
+ É necessário manter o diretório `transformers` se desejas continuar usando a biblioteca.
133
+
134
+ </Tip>
135
+
136
+ Assim, É possível atualizar sua cópia local para com a última versão do 🤗 Transformers com o seguinte comando:
137
+
138
+ ```bash
139
+ cd ~/transformers/
140
+ git pull
141
+ ```
142
+
143
+ O ambiente de Python que foi criado para a instalação do 🤗 Transformers encontrará a versão `master` em execuções seguintes.
144
+
145
+ ## Instalação usando o Conda
146
+
147
+ É possível instalar o 🤗 Transformers a partir do canal conda `conda-forge` com o seguinte comando:
148
+
149
+ ```bash
150
+ conda install conda-forge::transformers
151
+ ```
152
+
153
+ ## Configuração do Cachê
154
+
155
+ Os modelos pré-treinados são baixados e armazenados no cachê local, encontrado em `~/.cache/huggingface/transformers/`.
156
+ Este é o diretório padrão determinado pela variável `TRANSFORMERS_CACHE` dentro do shell.
157
+ No Windows, este diretório pré-definido é dado por `C:\Users\username\.cache\huggingface\transformers`.
158
+ É possível mudar as variáveis dentro do shell em ordem de prioridade para especificar um diretório de cachê diferente:
159
+
160
+ 1. Variável de ambiente do shell (por padrão): `TRANSFORMERS_CACHE`.
161
+ 2. Variável de ambiente do shell:`HF_HOME` + `transformers/`.
162
+ 3. Variável de ambiente do shell: `XDG_CACHE_HOME` + `/huggingface/transformers`.
163
+
164
+ <Tip>
165
+
166
+ O 🤗 Transformers usará as variáveis de ambiente do shell `PYTORCH_TRANSFORMERS_CACHE` ou `PYTORCH_PRETRAINED_BERT_CACHE`
167
+ se estiver vindo de uma versão anterior da biblioteca que tenha configurado essas variáveis de ambiente, a menos que
168
+ você especifique a variável de ambiente do shell `TRANSFORMERS_CACHE`.
169
+
170
+ </Tip>
171
+
172
+
173
+ ## Modo Offline
174
+
175
+ O 🤗 Transformers também pode ser executado num ambiente de firewall ou fora da rede (offline) usando arquivos locais.
176
+ Para tal, configure a variável de ambiente de modo que `HF_HUB_OFFLINE=1`.
177
+
178
+ <Tip>
179
+
180
+ Você pode adicionar o [🤗 Datasets](https://huggingface.co/docs/datasets/) ao pipeline de treinamento offline declarando
181
+ a variável de ambiente `HF_DATASETS_OFFLINE=1`.
182
+
183
+ </Tip>
184
+
185
+ Segue um exemplo de execução do programa numa rede padrão com firewall para instâncias externas, usando o seguinte comando:
186
+
187
+ ```bash
188
+ python examples/pytorch/translation/run_translation.py --model_name_or_path google-t5/t5-small --dataset_name wmt16 --dataset_config ro-en ...
189
+ ```
190
+
191
+ Execute esse mesmo programa numa instância offline com o seguinte comando:
192
+
193
+ ```bash
194
+ HF_DATASETS_OFFLINE=1 HF_HUB_OFFLINE=1 \
195
+ python examples/pytorch/translation/run_translation.py --model_name_or_path google-t5/t5-small --dataset_name wmt16 --dataset_config ro-en ...
196
+ ```
197
+
198
+ O script agora deve ser executado sem travar ou expirar, pois procurará apenas por arquivos locais.
199
+
200
+ ### Obtendo modelos e tokenizers para uso offline
201
+
202
+ Outra opção para usar o 🤗 Transformers offline é baixar os arquivos antes e depois apontar para o caminho local onde estão localizados. Existem três maneiras de fazer isso:
203
+
204
+ * Baixe um arquivo por meio da interface de usuário do [Model Hub](https://huggingface.co/models) clicando no ícone ↓.
205
+
206
+ ![download-icon](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/download-icon.png)
207
+
208
+
209
+ * Use o pipeline do [`PreTrainedModel.from_pretrained`] e [`PreTrainedModel.save_pretrained`]:
210
+ 1. Baixa os arquivos previamente com [`PreTrainedModel.from_pretrained`]:
211
+
212
+ ```py
213
+ >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
214
+
215
+ >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/T0_3B")
216
+ >>> model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0_3B")
217
+ ```
218
+
219
+
220
+ 2. Salve os arquivos em um diretório específico com [`PreTrainedModel.save_pretrained`]:
221
+
222
+ ```py
223
+ >>> tokenizer.save_pretrained("./your/path/bigscience_t0")
224
+ >>> model.save_pretrained("./your/path/bigscience_t0")
225
+ ```
226
+
227
+ 3. Quando estiver offline, acesse os arquivos com [`PreTrainedModel.from_pretrained`] do diretório especificado:
228
+
229
+ ```py
230
+ >>> tokenizer = AutoTokenizer.from_pretrained("./your/path/bigscience_t0")
231
+ >>> model = AutoModel.from_pretrained("./your/path/bigscience_t0")
232
+ ```
233
+
234
+ * Baixando arquivos programaticamente com a biblioteca [huggingface_hub](https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub):
235
+
236
+ 1. Instale a biblioteca [huggingface_hub](https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub) em seu ambiente virtual:
237
+
238
+ ```bash
239
+ python -m pip install huggingface_hub
240
+ ```
241
+
242
+ 2. Utiliza a função [`hf_hub_download`](https://huggingface.co/docs/hub/adding-a-library#download-files-from-the-hub) para baixar um arquivo para um caminho específico. Por exemplo, o comando a seguir baixará o arquivo `config.json` para o modelo [T0](https://huggingface.co/bigscience/T0_3B) no caminho desejado:
243
+
244
+ ```py
245
+ >>> from huggingface_hub import hf_hub_download
246
+
247
+ >>> hf_hub_download(repo_id="bigscience/T0_3B", filename="config.json", cache_dir="./your/path/bigscience_t0")
248
+ ```
249
+
250
+ Depois que o arquivo for baixado e armazenado no cachê local, especifique seu caminho local para carregá-lo e usá-lo:
251
+
252
+ ```py
253
+ >>> from transformers import AutoConfig
254
+
255
+ >>> config = AutoConfig.from_pretrained("./your/path/bigscience_t0/config.json")
256
+ ```
257
+
258
+ <Tip>
259
+
260
+ Para obter mais detalhes sobre como baixar arquivos armazenados no Hub, consulte a seção [How to download files from the Hub](https://huggingface.co/docs/hub/how-to-downstream).
261
+
262
+ </Tip>
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/multilingual.md ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # Modelos multilinguísticos para inferência
18
+
19
+ [[open-in-colab]]
20
+
21
+ Existem vários modelos multilinguísticos no 🤗 Transformers e seus usos para inferência diferem dos modelos monolíngues.
22
+ No entanto, nem *todos* os usos dos modelos multilíngues são tão diferentes.
23
+ Alguns modelos, como o [google-bert/bert-base-multilingual-uncased](https://huggingface.co/google-bert/bert-base-multilingual-uncased),
24
+ podem ser usados como se fossem monolíngues. Este guia irá te ajudar a usar modelos multilíngues cujo uso difere
25
+ para o propósito de inferência.
26
+
27
+ ## XLM
28
+
29
+ O XLM tem dez checkpoints diferentes dos quais apenas um é monolíngue.
30
+ Os nove checkpoints restantes do modelo são subdivididos em duas categorias:
31
+ checkpoints que usam de language embeddings e os que não.
32
+
33
+ ### XLM com language embeddings
34
+
35
+ Os seguintes modelos de XLM usam language embeddings para especificar a linguagem utilizada para a inferência.
36
+
37
+ - `FacebookAI/xlm-mlm-ende-1024` (Masked language modeling, English-German)
38
+ - `FacebookAI/xlm-mlm-enfr-1024` (Masked language modeling, English-French)
39
+ - `FacebookAI/xlm-mlm-enro-1024` (Masked language modeling, English-Romanian)
40
+ - `FacebookAI/xlm-mlm-xnli15-1024` (Masked language modeling, XNLI languages)
41
+ - `FacebookAI/xlm-mlm-tlm-xnli15-1024` (Masked language modeling + translation, XNLI languages)
42
+ - `FacebookAI/xlm-clm-enfr-1024` (Causal language modeling, English-French)
43
+ - `FacebookAI/xlm-clm-ende-1024` (Causal language modeling, English-German)
44
+
45
+ Os language embeddings são representados por um tensor de mesma dimensão que os `input_ids` passados ao modelo.
46
+ Os valores destes tensores dependem do idioma utilizado e se identificam pelos atributos `lang2id` e `id2lang` do tokenizador.
47
+
48
+ Neste exemplo, carregamos o checkpoint `FacebookAI/xlm-clm-enfr-1024`(Causal language modeling, English-French):
49
+
50
+ ```py
51
+ >>> import torch
52
+ >>> from transformers import XLMTokenizer, XLMWithLMHeadModel
53
+
54
+ >>> tokenizer = XLMTokenizer.from_pretrained("FacebookAI/xlm-clm-enfr-1024")
55
+ >>> model = XLMWithLMHeadModel.from_pretrained("FacebookAI/xlm-clm-enfr-1024")
56
+ ```
57
+
58
+ O atributo `lang2id` do tokenizador mostra os idiomas deste modelo e seus ids:
59
+
60
+ ```py
61
+ >>> print(tokenizer.lang2id)
62
+ {'en': 0, 'fr': 1}
63
+ ```
64
+
65
+ Em seguida, cria-se um input de exemplo:
66
+
67
+ ```py
68
+ >>> input_ids = torch.tensor([tokenizer.encode("Wikipedia was used to")]) # batch size of 1
69
+ ```
70
+
71
+ Estabelece-se o id do idioma, por exemplo `"en"`, e utiliza-se o mesmo para definir a language embedding.
72
+ A language embedding é um tensor preenchido com `0`, que é o id de idioma para o inglês.
73
+ Este tensor deve ser do mesmo tamanho que os `input_ids`.
74
+
75
+ ```py
76
+ >>> language_id = tokenizer.lang2id["en"] # 0
77
+ >>> langs = torch.tensor([language_id] * input_ids.shape[1]) # torch.tensor([0, 0, 0, ..., 0])
78
+
79
+ >>> # We reshape it to be of size (batch_size, sequence_length)
80
+ >>> langs = langs.view(1, -1) # is now of shape [1, sequence_length] (we have a batch size of 1)
81
+ ```
82
+
83
+ Agora você pode passar os `input_ids` e a language embedding ao modelo:
84
+
85
+ ```py
86
+ >>> outputs = model(input_ids, langs=langs)
87
+ ```
88
+
89
+ O script [run_generation.py](https://github.com/huggingface/transformers/tree/master/examples/pytorch/text-generation/run_generation.py) pode gerar um texto com language embeddings utilizando os checkpoints `xlm-clm`.
90
+
91
+ ### XLM sem language embeddings
92
+
93
+ Os seguintes modelos XLM não requerem o uso de language embeddings durante a inferência:
94
+
95
+ - `FacebookAI/xlm-mlm-17-1280` (Modelagem de linguagem com máscara, 17 idiomas)
96
+ - `FacebookAI/xlm-mlm-100-1280` (Modelagem de linguagem com máscara, 100 idiomas)
97
+
98
+ Estes modelos são utilizados para representações genéricas de frase diferentemente dos checkpoints XLM anteriores.
99
+
100
+ ## BERT
101
+
102
+ Os seguintes modelos do BERT podem ser utilizados para tarefas multilinguísticas:
103
+
104
+ - `google-bert/bert-base-multilingual-uncased` (Modelagem de linguagem com máscara + Previsão de frases, 102 idiomas)
105
+ - `google-bert/bert-base-multilingual-cased` (Modelagem de linguagem com máscara + Previsão de frases, 104 idiomas)
106
+
107
+ Estes modelos não requerem language embeddings durante a inferência. Devem identificar a linguagem a partir
108
+ do contexto e realizar a inferência em sequência.
109
+
110
+ ## XLM-RoBERTa
111
+
112
+ Os seguintes modelos do XLM-RoBERTa podem ser utilizados para tarefas multilinguísticas:
113
+
114
+ - `FacebookAI/xlm-roberta-base` (Modelagem de linguagem com máscara, 100 idiomas)
115
+ - `FacebookAI/xlm-roberta-large` Modelagem de linguagem com máscara, 100 idiomas)
116
+
117
+ O XLM-RoBERTa foi treinado com 2,5 TB de dados do CommonCrawl recém-criados e testados em 100 idiomas.
118
+ Proporciona fortes vantagens sobre os modelos multilinguísticos publicados anteriormente como o mBERT e o XLM em tarefas
119
+ subsequentes como a classificação, a rotulagem de sequências e à respostas a perguntas.
120
+
121
+ ## M2M100
122
+
123
+ Os seguintes modelos de M2M100 podem ser utilizados para traduções multilinguísticas:
124
+
125
+ - `facebook/m2m100_418M` (Tradução)
126
+ - `facebook/m2m100_1.2B` (Tradução)
127
+
128
+ Neste exemplo, o checkpoint `facebook/m2m100_418M` é carregado para traduzir do mandarim ao inglês. É possível
129
+ estabelecer o idioma de origem no tokenizador:
130
+
131
+ ```py
132
+ >>> from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer
133
+
134
+ >>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
135
+ >>> chinese_text = "不要插手巫師的事務, 因為他們是微妙的, 很快就會發怒."
136
+
137
+ >>> tokenizer = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M", src_lang="zh")
138
+ >>> model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M")
139
+ ```
140
+
141
+ Tokenização do texto:
142
+
143
+ ```py
144
+ >>> encoded_zh = tokenizer(chinese_text, return_tensors="pt")
145
+ ```
146
+
147
+ O M2M100 força o id do idioma de destino como o primeiro token gerado para traduzir ao idioma de destino.
148
+ É definido o `forced_bos_token_id` como `en` no método `generate` para traduzir ao inglês.
149
+
150
+ ```py
151
+ >>> generated_tokens = model.generate(**encoded_zh, forced_bos_token_id=tokenizer.get_lang_id("en"))
152
+ >>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
153
+ 'Do not interfere with the matters of the witches, because they are delicate and will soon be angry.'
154
+ ```
155
+
156
+ ## MBart
157
+
158
+ Os seguintes modelos do MBart podem ser utilizados para tradução multilinguística:
159
+
160
+ - `facebook/mbart-large-50-one-to-many-mmt` (Tradução automática multilinguística de um a vários, 50 idiomas)
161
+ - `facebook/mbart-large-50-many-to-many-mmt` (Tradução automática multilinguística de vários a vários, 50 idiomas)
162
+ - `facebook/mbart-large-50-many-to-one-mmt` (Tradução automática multilinguística vários a um, 50 idiomas)
163
+ - `facebook/mbart-large-50` (Tradução multilinguística, 50 idiomas)
164
+ - `facebook/mbart-large-cc25`
165
+
166
+ Neste exemplo, carrega-se o checkpoint `facebook/mbart-large-50-many-to-many-mmt` para traduzir do finlandês ao inglês.
167
+ Pode-se definir o idioma de origem no tokenizador:
168
+
169
+ ```py
170
+ >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
171
+
172
+ >>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
173
+ >>> fi_text = "Älä sekaannu velhojen asioihin, sillä ne ovat hienovaraisia ja nopeasti vihaisia."
174
+
175
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-50-many-to-many-mmt", src_lang="fi_FI")
176
+ >>> model = AutoModelForSeq2SeqLM.from_pretrained("facebook/mbart-large-50-many-to-many-mmt")
177
+ ```
178
+
179
+ Tokenizando o texto:
180
+
181
+ ```py
182
+ >>> encoded_en = tokenizer(en_text, return_tensors="pt")
183
+ ```
184
+
185
+ O MBart força o id do idioma de destino como o primeiro token gerado para traduzir ao idioma de destino.
186
+ É definido o `forced_bos_token_id` como `en` no método `generate` para traduzir ao inglês.
187
+
188
+ ```py
189
+ >>> generated_tokens = model.generate(**encoded_en, forced_bos_token_id=tokenizer.lang_code_to_id("en_XX"))
190
+ >>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
191
+ "Don't interfere with the wizard's affairs, because they are subtle, will soon get angry."
192
+ ```
193
+
194
+ Se estiver usando o checkpoint `facebook/mbart-large-50-many-to-one-mmt` não será necessário forçar o id do idioma de destino
195
+ como sendo o primeiro token generado, caso contrário a usagem é a mesma.
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/pipeline_tutorial.md ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # Pipelines para inferência
18
+
19
+ Um [pipeline] simplifica o uso dos modelos no [Model Hub](https://huggingface.co/models) para a inferência de uma diversidade de tarefas,
20
+ como a geração de texto, a segmentação de imagens e a classificação de áudio.
21
+ Inclusive, se não tem experiência com alguma modalidade específica ou não compreende o código que forma os modelos,
22
+ pode usar eles mesmo assim com o [pipeline]! Este tutorial te ensinará a:
23
+
24
+ * Utilizar um [`pipeline`] para inferência.
25
+ * Utilizar um tokenizador ou model específico.
26
+ * Utilizar um [`pipeline`] para tarefas de áudio e visão computacional.
27
+
28
+ <Tip>
29
+
30
+ Acesse a documentação do [`pipeline`] para obter uma lista completa de tarefas possíveis.
31
+
32
+ </Tip>
33
+
34
+ ## Uso do pipeline
35
+
36
+ Mesmo que cada tarefa tenha um [`pipeline`] associado, é mais simples usar a abstração geral do [`pipeline`] que
37
+ contém todos os pipelines das tarefas mais específicas.
38
+ O [`pipeline`] carrega automaticamenta um modelo predeterminado e um tokenizador com capacidade de inferência para sua
39
+ tarefa.
40
+
41
+ 1. Comece carregando um [`pipeline`] e especifique uma tarefa de inferência:
42
+
43
+ ```py
44
+ >>> from transformers import pipeline
45
+
46
+ >>> generator = pipeline(task="text-generation")
47
+ ```
48
+
49
+ 2. Passe seu dado de entrada, no caso um texto, ao [`pipeline`]:
50
+
51
+ ```py
52
+ >>> generator("Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone")
53
+ [{'generated_text': 'Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone, Seven for the Iron-priests at the door to the east, and thirteen for the Lord Kings at the end of the mountain'}]
54
+ ```
55
+
56
+ Se tiver mais de uma entrada, passe-a como uma lista:
57
+
58
+ ```py
59
+ >>> generator(
60
+ ... [
61
+ ... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone",
62
+ ... "Nine for Mortal Men, doomed to die, One for the Dark Lord on his dark throne",
63
+ ... ]
64
+ ... )
65
+ ```
66
+
67
+ Qualquer parâmetro adicional para a sua tarefa também pode ser incluído no [`pipeline`]. A tarefa `text-generation` tem um método
68
+ [`~generation.GenerationMixin.generate`] com vários parâmetros para controlar a saída.
69
+ Por exemplo, se quiser gerar mais de uma saída, defina-a no parâmetro `num_return_sequences`:
70
+
71
+ ```py
72
+ >>> generator(
73
+ ... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone",
74
+ ... num_return_sequences=2,
75
+ ... )
76
+ ```
77
+
78
+ ### Selecionando um modelo e um tokenizador
79
+
80
+ O [`pipeline`] aceita qualquer modelo do [Model Hub](https://huggingface.co/models). Há rótulos adicionais no Model Hub
81
+ que te permitem filtrar pelo modelo que gostaria de usar para sua tarefa. Uma vez que tiver escolhido o modelo apropriado,
82
+ carregue-o com as classes `AutoModelFor` e [`AutoTokenizer`] correspondentes. Por exemplo, carregue a classe [`AutoModelForCausalLM`]
83
+ para uma tarefa de modelagem de linguagem causal:
84
+
85
+ ```py
86
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
87
+
88
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
89
+ >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
90
+ ```
91
+
92
+ Crie uma [`pipeline`] para a sua tarefa e especifíque o modelo e o tokenizador que foram carregados:
93
+
94
+ ```py
95
+ >>> from transformers import pipeline
96
+
97
+ >>> generator = pipeline(task="text-generation", model=model, tokenizer=tokenizer)
98
+ ```
99
+
100
+ Passe seu texto de entrada ao [`pipeline`] para gerar algum texto:
101
+
102
+ ```py
103
+ >>> generator("Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone")
104
+ [{'generated_text': 'Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone, Seven for the Dragon-lords (for them to rule in a world ruled by their rulers, and all who live within the realm'}]
105
+ ```
106
+
107
+ ## Pipeline de audio
108
+
109
+ A flexibilidade do [`pipeline`] significa que também pode-se extender às tarefas de áudio.
110
+ La flexibilidad de [`pipeline`] significa que también se puede extender a tareas de audio.
111
+
112
+ Por exemplo, classifiquemos a emoção de um breve fragmento do famoso discurso de John F. Kennedy /home/rzimmerdev/dev/transformers/docs/source/pt/pipeline_tutorial.md
113
+ Encontre um modelo de [audio classification](https://huggingface.co/models?pipeline_tag=audio-classification) para
114
+ reconhecimento de emoções no Model Hub e carregue-o usando o [`pipeline`]:
115
+
116
+ ```py
117
+ >>> from transformers import pipeline
118
+
119
+ >>> audio_classifier = pipeline(
120
+ ... task="audio-classification", model="ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition"
121
+ ... )
122
+ ```
123
+
124
+ Passe o arquivo de áudio ao [`pipeline`]:
125
+
126
+ ```py
127
+ >>> audio_classifier("jfk_moon_speech.wav")
128
+ [{'label': 'calm', 'score': 0.13856211304664612},
129
+ {'label': 'disgust', 'score': 0.13148026168346405},
130
+ {'label': 'happy', 'score': 0.12635163962841034},
131
+ {'label': 'angry', 'score': 0.12439591437578201},
132
+ {'label': 'fearful', 'score': 0.12404385954141617}]
133
+ ```
134
+
135
+ ## Pipeline de visão computacional
136
+
137
+ Finalmente, utilizar um [`pipeline`] para tarefas de visão é praticamente a mesma coisa.
138
+ Especifique a sua tarefa de visão e passe a sua imagem ao classificador.
139
+ A imagem pode ser um link ou uma rota local à imagem. Por exemplo, que espécie de gato está presente na imagem?
140
+
141
+ ![pipeline-cat-chonk](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg)
142
+
143
+ ```py
144
+ >>> from transformers import pipeline
145
+
146
+ >>> vision_classifier = pipeline(task="image-classification")
147
+ >>> vision_classifier(
148
+ ... images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
149
+ ... )
150
+ [{'label': 'lynx, catamount', 'score': 0.4403027892112732},
151
+ {'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor',
152
+ 'score': 0.03433405980467796},
153
+ {'label': 'snow leopard, ounce, Panthera uncia',
154
+ 'score': 0.032148055732250214},
155
+ {'label': 'Egyptian cat', 'score': 0.02353910356760025},
156
+ {'label': 'tiger cat', 'score': 0.023034192621707916}]
157
+ ```
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/quicktour.md ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # Tour rápido
18
+
19
+ [[open-in-colab]]
20
+
21
+ Comece a trabalhar com 🤗 Transformers! Comece usando [`pipeline`] para rápida inferência e facilmente carregue um modelo pré-treinado e um tokenizer com [AutoClass](./model_doc/auto) para resolver tarefas de texto, visão ou áudio.
22
+
23
+ <Tip>
24
+
25
+ Todos os exemplos de código apresentados na documentação têm um botão no canto superior direito para escolher se você deseja ocultar ou mostrar o código no Pytorch ou no TensorFlow. Caso contrário, é esperado que funcione para ambos back-ends sem nenhuma alteração.
26
+
27
+ </Tip>
28
+
29
+ ## Pipeline
30
+
31
+ [`pipeline`] é a maneira mais fácil de usar um modelo pré-treinado para uma dada tarefa.
32
+
33
+ <Youtube id="tiZFewofSLM"/>
34
+
35
+ A [`pipeline`] apoia diversas tarefas fora da caixa:
36
+
37
+ **Texto**:
38
+ * Análise sentimental: classifica a polaridade de um texto.
39
+ * Geração de texto (em Inglês): gera texto a partir de uma entrada.
40
+ * Reconhecimento de entidade mencionada: legenda cada palavra com uma classe que a representa (pessoa, data, local, etc...)
41
+ * Respostas: extrai uma resposta dado algum contexto e uma questão
42
+ * Máscara de preenchimento: preenche o espaço, dado um texto com máscaras de palavras.
43
+ * Sumarização: gera o resumo de um texto longo ou documento.
44
+ * Tradução: traduz texto para outra língua.
45
+ * Extração de características: cria um tensor que representa o texto.
46
+
47
+ **Imagem**:
48
+ * Classificação de imagens: classifica uma imagem.
49
+ * Segmentação de imagem: classifica cada pixel da imagem.
50
+ * Detecção de objetos: detecta objetos em uma imagem.
51
+
52
+ **Audio**:
53
+ * Classficação de áudio: legenda um trecho de áudio fornecido.
54
+ * Reconhecimento de fala automático: transcreve audio em texto.
55
+
56
+ <Tip>
57
+
58
+ Para mais detalhes sobre a [`pipeline`] e tarefas associadas, siga a documentação [aqui](./main_classes/pipelines).
59
+
60
+ </Tip>
61
+
62
+ ### Uso da pipeline
63
+
64
+ No exemplo a seguir, você usará [`pipeline`] para análise sentimental.
65
+
66
+ Instale as seguintes dependências se você ainda não o fez:
67
+
68
+
69
+ <frameworkcontent>
70
+ <pt>
71
+ ```bash
72
+ pip install torch
73
+ ```
74
+ </pt>
75
+ <tf>
76
+ ```bash
77
+ pip install tensorflow
78
+ ```
79
+ </tf>
80
+ </frameworkcontent>
81
+
82
+ Importe [`pipeline`] e especifique a tarefa que deseja completar:
83
+
84
+ ```py
85
+ >>> from transformers import pipeline
86
+
87
+ >>> classifier = pipeline("sentiment-analysis")
88
+ ```
89
+
90
+ A pipeline baixa and armazena um [modelo pré-treinado](https://huggingface.co/distilbert/distilbert-base-uncased-finetuned-sst-2-english) padrão e tokenizer para análise sentimental. Agora você pode usar `classifier` no texto alvo:
91
+
92
+ ```py
93
+ >>> classifier("We are very happy to show you the 🤗 Transformers library.")
94
+ [{'label': 'POSITIVE', 'score': 0.9998}]
95
+ ```
96
+
97
+ Para mais de uma sentença, passe uma lista para a [`pipeline`], a qual retornará uma lista de dicionários:
98
+
99
+ ```py
100
+ >>> results = classifier(["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."])
101
+ >>> for result in results:
102
+ ... print(f"label: {result['label']}, with score: {round(result['score'], 4)}")
103
+ label: POSITIVE, with score: 0.9998
104
+ label: NEGATIVE, with score: 0.5309
105
+ ```
106
+
107
+ A [`pipeline`] também pode iterar sobre um Dataset inteiro. Comece instalando a biblioteca de [🤗 Datasets](https://huggingface.co/docs/datasets/):
108
+
109
+ ```bash
110
+ pip install datasets
111
+ ```
112
+
113
+ Crie uma [`pipeline`] com a tarefa que deseja resolver e o modelo que deseja usar.
114
+
115
+ ```py
116
+ >>> import torch
117
+ >>> from transformers import pipeline
118
+
119
+ >>> speech_recognizer = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h")
120
+ ```
121
+
122
+ A seguir, carregue uma base de dados (confira a 🤗 [Iniciação em Datasets](https://huggingface.co/docs/datasets/quickstart) para mais detalhes) que você gostaria de iterar sobre. Por exemplo, vamos carregar o dataset [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14):
123
+
124
+ ```py
125
+ >>> from datasets import load_dataset, Audio
126
+
127
+ >>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") # doctest: +IGNORE_RESULT
128
+ ```
129
+
130
+ Precisamos garantir que a taxa de amostragem do conjunto de dados corresponda à taxa de amostragem em que o facebook/wav2vec2-base-960h foi treinado.
131
+
132
+ ```py
133
+ >>> dataset = dataset.cast_column("audio", Audio(sampling_rate=speech_recognizer.feature_extractor.sampling_rate))
134
+ ```
135
+
136
+ Os arquivos de áudio são carregados e re-amostrados automaticamente ao chamar a coluna `"audio"`.
137
+ Vamos extrair as arrays de formas de onda originais das primeiras 4 amostras e passá-las como uma lista para o pipeline:
138
+
139
+ ```py
140
+ >>> result = speech_recognizer(dataset[:4]["audio"])
141
+ >>> print([d["text"] for d in result])
142
+ ['I WOULD LIKE TO SET UP A JOINT ACCOUNT WITH MY PARTNER HOW DO I PROCEED WITH DOING THAT', "FONDERING HOW I'D SET UP A JOIN TO HET WITH MY WIFE AND WHERE THE AP MIGHT BE", "I I'D LIKE TOY SET UP A JOINT ACCOUNT WITH MY PARTNER I'M NOT SEEING THE OPTION TO DO IT ON THE APSO I CALLED IN TO GET SOME HELP CAN I JUST DO IT OVER THE PHONE WITH YOU AND GIVE YOU THE INFORMATION OR SHOULD I DO IT IN THE AP AND I'M MISSING SOMETHING UQUETTE HAD PREFERRED TO JUST DO IT OVER THE PHONE OF POSSIBLE THINGS", 'HOW DO I TURN A JOIN A COUNT']
143
+ ```
144
+
145
+ Para um conjunto de dados maior onde as entradas são maiores (como em fala ou visão), será necessário passar um gerador em vez de uma lista que carregue todas as entradas na memória. Consulte a [documentação do pipeline](./main_classes/pipelines) para mais informações.
146
+
147
+ ### Use outro modelo e tokenizer na pipeline
148
+
149
+ A [`pipeline`] pode acomodar qualquer modelo do [Model Hub](https://huggingface.co/models), facilitando sua adaptação para outros casos de uso. Por exemplo, se você quiser um modelo capaz de lidar com texto em francês, use as tags no Model Hub para filtrar um modelo apropriado. O principal resultado filtrado retorna um [modelo BERT](https://huggingface.co/nlptown/bert-base-multilingual-uncased-sentiment) bilíngue ajustado para análise de sentimentos. Ótimo, vamos usar este modelo!
150
+
151
+ ```py
152
+ >>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
153
+ ```
154
+
155
+ <frameworkcontent>
156
+ <pt>
157
+ Use o [`AutoModelForSequenceClassification`] e [`AutoTokenizer`] para carregar o modelo pré-treinado e seu tokenizer associado (mais em `AutoClass` abaixo):
158
+
159
+ ```py
160
+ >>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
161
+
162
+ >>> model = AutoModelForSequenceClassification.from_pretrained(model_name)
163
+ >>> tokenizer = AutoTokenizer.from_pretrained(model_name)
164
+ ```
165
+ </pt>
166
+ <tf>
167
+
168
+ Use o [`TFAutoModelForSequenceClassification`] and [`AutoTokenizer`] para carregar o modelo pré-treinado e o tokenizer associado (mais em `TFAutoClass` abaixo):
169
+
170
+ ```py
171
+ >>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
172
+
173
+ >>> model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
174
+ >>> tokenizer = AutoTokenizer.from_pretrained(model_name)
175
+ ```
176
+ </tf>
177
+ </frameworkcontent>
178
+
179
+ Então você pode especificar o modelo e o tokenizador na [`pipeline`] e aplicar o `classifier` no seu texto alvo:
180
+
181
+ ```py
182
+ >>> classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
183
+ >>> classifier("Nous sommes très heureux de vous présenter la bibliothèque 🤗 Transformers.")
184
+ [{'label': '5 stars', 'score': 0.7273}]
185
+ ```
186
+
187
+ Se você não conseguir achar um modelo para o seu caso de uso, precisará usar fine-tune em um modelo pré-treinado nos seus dados. Veja nosso [tutorial de fine-tuning](./training) para descobrir como. Finalmente, depois que você tiver usado esse processo em seu modelo, considere compartilhá-lo conosco (veja o tutorial [aqui](./model_sharing)) na plataforma Model Hub afim de democratizar NLP! 🤗
188
+
189
+ ## AutoClass
190
+
191
+ <Youtube id="AhChOFRegn4"/>
192
+
193
+ Por baixo dos panos, as classes [`AutoModelForSequenceClassification`] e [`AutoTokenizer`] trabalham juntas para fortificar o [`pipeline`]. Um [AutoClass](./model_doc/auto) é um atalho que automaticamente recupera a arquitetura de um modelo pré-treinado a partir de seu nome ou caminho. Basta selecionar a `AutoClass` apropriada para sua tarefa e seu tokenizer associado com [`AutoTokenizer`].
194
+
195
+ Vamos voltar ao nosso exemplo e ver como você pode usar a `AutoClass` para replicar os resultados do [`pipeline`].
196
+
197
+ ### AutoTokenizer
198
+
199
+ Um tokenizer é responsável por pré-processar o texto em um formato que seja compreensível para o modelo. Primeiro, o tokenizer dividirá o texto em palavras chamadas *tokens*. Existem várias regras que regem o processo de tokenização, incluindo como dividir uma palavra e em que nível (saiba mais sobre tokenização [aqui](./tokenizer_summary)). A coisa mais importante a lembrar, porém, é que você precisa instanciar o tokenizer com o mesmo nome do modelo para garantir que está usando as mesmas regras de tokenização com as quais um modelo foi pré-treinado.
200
+
201
+ Carregue um tokenizer com [`AutoTokenizer`]:
202
+
203
+ ```py
204
+ >>> from transformers import AutoTokenizer
205
+
206
+ >>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
207
+ >>> tokenizer = AutoTokenizer.from_pretrained(model_name)
208
+ ```
209
+
210
+ Em seguida, o tokenizer converte os tokens em números para construir um tensor como entrada para o modelo. Isso é conhecido como o *vocabulário* do modelo.
211
+
212
+ Passe o texto para o tokenizer:
213
+
214
+ ```py
215
+ >>> encoding = tokenizer("We are very happy to show you the 🤗 Transformers library.")
216
+ >>> print(encoding)
217
+ {'input_ids': [101, 11312, 10320, 12495, 19308, 10114, 11391, 10855, 10103, 100, 58263, 13299, 119, 102],
218
+ 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
219
+ 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
220
+ ```
221
+
222
+ O tokenizer retornará um dicionário contendo:
223
+
224
+ * [input_ids](./glossary#input-ids): representações numéricas de seus tokens.
225
+ * [attention_mask](.glossary#attention-mask): indica quais tokens devem ser atendidos.
226
+
227
+ Assim como o [`pipeline`], o tokenizer aceitará uma lista de entradas. Além disso, o tokenizer também pode preencher e truncar o texto para retornar um lote com comprimento uniforme:
228
+
229
+ <frameworkcontent>
230
+ <pt>
231
+
232
+ ```py
233
+ >>> pt_batch = tokenizer(
234
+ ... ["We are very happy to show you the 🤗 transformers library.", "We hope you don't hate it."],
235
+ ... padding=True,
236
+ ... truncation=True,
237
+ ... max_length=512,
238
+ ... return_tensors="pt",
239
+ ... )
240
+ ```
241
+ </pt>
242
+ <tf>
243
+
244
+ ```py
245
+ >>> tf_batch = tokenizer(
246
+ ... ["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."],
247
+ ... padding=True,
248
+ ... truncation=True,
249
+ ... max_length=512,
250
+ ... return_tensors="tf",
251
+ ... )
252
+ ```
253
+ </tf>
254
+ </frameworkcontent>
255
+
256
+ Leia o tutorial de [pré-processamento](./pré-processamento) para obter mais detalhes sobre tokenização.
257
+
258
+ ### AutoModel
259
+
260
+ <frameworkcontent>
261
+ <pt>
262
+ 🤗 Transformers fornecem uma maneira simples e unificada de carregar instâncias pré-treinadas. Isso significa que você pode carregar um [`AutoModel`] como carregaria um [`AutoTokenizer`]. A única diferença é selecionar o [`AutoModel`] correto para a tarefa. Como você está fazendo classificação de texto ou sequência, carregue [`AutoModelForSequenceClassification`]:
263
+
264
+ ```py
265
+ >>> from transformers import AutoModelForSequenceClassification
266
+
267
+ >>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
268
+ >>> pt_model = AutoModelForSequenceClassification.from_pretrained(model_name)
269
+ ```
270
+
271
+ <Tip>
272
+
273
+ Veja o [sumário de tarefas](./task_summary) para qual classe de [`AutoModel`] usar para cada tarefa.
274
+
275
+ </Tip>
276
+
277
+ Agora você pode passar seu grupo de entradas pré-processadas diretamente para o modelo. Você apenas tem que descompactar o dicionário usando `**`:
278
+
279
+ ```py
280
+ >>> pt_outputs = pt_model(**pt_batch)
281
+ ```
282
+
283
+ O modelo gera as ativações finais no atributo `logits`. Aplique a função softmax aos `logits` para recuperar as probabilidades:
284
+
285
+ ```py
286
+ >>> from torch import nn
287
+
288
+ >>> pt_predictions = nn.functional.softmax(pt_outputs.logits, dim=-1)
289
+ >>> print(pt_predictions)
290
+ tensor([[0.0021, 0.0018, 0.0115, 0.2121, 0.7725],
291
+ [0.2084, 0.1826, 0.1969, 0.1755, 0.2365]], grad_fn=<SoftmaxBackward0>)
292
+ ```
293
+ </pt>
294
+ <tf>
295
+ 🤗 Transformers fornecem uma maneira simples e unificada de carregar instâncias pré-treinadas. Isso significa que você pode carregar um [`TFAutoModel`] como carregaria um [`AutoTokenizer`]. A única diferença é selecionar o [`TFAutoModel`] correto para a tarefa. Como você está fazendo classificação de texto ou sequência, carregue [`TFAutoModelForSequenceClassification`]:
296
+
297
+ ```py
298
+ >>> from transformers import TFAutoModelForSequenceClassification
299
+
300
+ >>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
301
+ >>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
302
+ ```
303
+
304
+ <Tip>
305
+
306
+ Veja o [sumário de tarefas](./task_summary) para qual classe de [`AutoModel`] usar para cada tarefa.
307
+
308
+ </Tip>
309
+
310
+ Agora você pode passar seu grupo de entradas pré-processadas diretamente para o modelo através da passagem de chaves de dicionários ao tensor.
311
+
312
+ ```py
313
+ >>> tf_outputs = tf_model(tf_batch)
314
+ ```
315
+
316
+ O modelo gera as ativações finais no atributo `logits`. Aplique a função softmax aos `logits` para recuperar as probabilidades:
317
+
318
+ ```py
319
+ >>> import tensorflow as tf
320
+
321
+ >>> tf_predictions = tf.nn.softmax(tf_outputs.logits, axis=-1)
322
+ >>> tf_predictions # doctest: +IGNORE_RESULT
323
+ ```
324
+ </tf>
325
+ </frameworkcontent>
326
+
327
+ <Tip>
328
+
329
+ Todos os modelos de 🤗 Transformers (PyTorch ou TensorFlow) geram tensores *antes* da função de ativação final (como softmax) pois essa função algumas vezes é fundida com a perda.
330
+
331
+
332
+ </Tip>
333
+
334
+ Os modelos são um standard [`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) ou um [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model) para que você possa usá-los em seu loop de treinamento habitual. No entanto, para facilitar as coisas, 🤗 Transformers fornece uma classe [`Trainer`] para PyTorch que adiciona funcionalidade para treinamento distribuído, precisão mista e muito mais. Para o TensorFlow, você pode usar o método `fit` de [Keras](https://keras.io/). Consulte o [tutorial de treinamento](./training) para obter mais detalhes.
335
+
336
+ <Tip>
337
+
338
+ As saídas do modelo 🤗 Transformers são classes de dados especiais para que seus atributos sejam preenchidos automaticamente em um IDE.
339
+ As saídas do modelo também se comportam como uma tupla ou um dicionário (por exemplo, você pode indexar com um inteiro, uma parte ou uma string), caso em que os atributos `None` são ignorados.
340
+
341
+ </Tip>
342
+
343
+ ### Salvar um modelo
344
+
345
+ <frameworkcontent>
346
+ <pt>
347
+ Uma vez que seu modelo estiver afinado, você pode salvá-lo com seu Tokenizer usando [`PreTrainedModel.save_pretrained`]:
348
+
349
+ ```py
350
+ >>> pt_save_directory = "./pt_save_pretrained"
351
+ >>> tokenizer.save_pretrained(pt_save_directory) # doctest: +IGNORE_RESULT
352
+ >>> pt_model.save_pretrained(pt_save_directory)
353
+ ```
354
+
355
+ Quando você estiver pronto para usá-lo novamente, recarregue com [`PreTrainedModel.from_pretrained`]:
356
+
357
+ ```py
358
+ >>> pt_model = AutoModelForSequenceClassification.from_pretrained("./pt_save_pretrained")
359
+ ```
360
+ </pt>
361
+ <tf>
362
+ Uma vez que seu modelo estiver afinado, você pode salvá-lo com seu Tokenizer usando [`TFPreTrainedModel.save_pretrained`]:
363
+
364
+ ```py
365
+ >>> tf_save_directory = "./tf_save_pretrained"
366
+ >>> tokenizer.save_pretrained(tf_save_directory) # doctest: +IGNORE_RESULT
367
+ >>> tf_model.save_pretrained(tf_save_directory)
368
+ ```
369
+
370
+ Quando você estiver pronto para usá-lo novamente, recarregue com [`TFPreTrainedModel.from_pretrained`]
371
+
372
+ ```py
373
+ >>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("./tf_save_pretrained")
374
+ ```
375
+ </tf>
376
+ </frameworkcontent>
377
+
378
+ Um recurso particularmente interessante dos 🤗 Transformers é a capacidade de salvar um modelo e recarregá-lo como um modelo PyTorch ou TensorFlow. Use `from_pt` ou `from_tf` para converter o modelo de um framework para outro:
379
+
380
+ <frameworkcontent>
381
+ <pt>
382
+
383
+ ```py
384
+ >>> from transformers import AutoModel
385
+
386
+ >>> tokenizer = AutoTokenizer.from_pretrained(pt_save_directory)
387
+ >>> pt_model = AutoModelForSequenceClassification.from_pretrained(pt_save_directory, from_pt=True)
388
+ ```
389
+ </pt>
390
+ <tf>
391
+
392
+ ```py
393
+ >>> from transformers import TFAutoModel
394
+
395
+ >>> tokenizer = AutoTokenizer.from_pretrained(tf_save_directory)
396
+ >>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(tf_save_directory, from_tf=True)
397
+ ```
398
+ </tf>
399
+ </frameworkcontent>
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/run_scripts.md ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # Treinamento a partir de um script
18
+
19
+ Junto com os 🤗 Transformers [notebooks](./notebooks), também há scripts de exemplo demonstrando como treinar um modelo para uma tarefa com [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch), [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow) ou [JAX/Flax](https://github.com/huggingface/transformers/tree/main/examples/flax).
20
+
21
+ Você também encontrará scripts que usamos em nossos [projetos de pesquisa](https://github.com/huggingface/transformers-research-projects/) e [exemplos legados](https://github.com/huggingface/transformers/tree/main/examples/legacy) que são principalmente contribuições da comunidade. Esses scripts não são mantidos ativamente e exigem uma versão específica de 🤗 Transformers que provavelmente será incompatível com a versão mais recente da biblioteca.
22
+
23
+ Não se espera que os scripts de exemplo funcionem imediatamente em todos os problemas, você pode precisar adaptar o script ao problema que está tentando resolver. Para ajudá-lo com isso, a maioria dos scripts expõe totalmente como os dados são pré-processados, permitindo que você os edite conforme necessário para seu caso de uso.
24
+
25
+ Para qualquer recurso que você gostaria de implementar em um script de exemplo, discuta-o no [fórum](https://discuss.huggingface.co/) ou em uma [issue](https://github.com/huggingface/transformers/issues) antes de enviar um Pull Request. Embora recebamos correções de bugs, é improvável que mesclaremos um Pull Request que adicione mais funcionalidades ao custo de legibilidade.
26
+
27
+ Este guia mostrará como executar um exemplo de script de treinamento de sumarização em [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch/summarization) e [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/summarization). Espera-se que todos os exemplos funcionem com ambas as estruturas, a menos que especificado de outra forma.
28
+
29
+ ## Configuração
30
+
31
+ Para executar com êxito a versão mais recente dos scripts de exemplo, você precisa **instalar o 🤗 Transformers da fonte** em um novo ambiente virtual:
32
+
33
+ ```bash
34
+ git clone https://github.com/huggingface/transformers
35
+ cd transformers
36
+ pip install .
37
+ ```
38
+
39
+ Para versões mais antigas dos scripts de exemplo, clique no botão abaixo:
40
+
41
+ <details>
42
+ <summary>Exemplos para versões antigas dos 🤗 Transformers</summary>
43
+ <ul>
44
+ <li><a href="https://github.com/huggingface/transformers/tree/v4.5.1/examples">v4.5.1</a></li>
45
+ <li><a href="https://github.com/huggingface/transformers/tree/v4.4.2/examples">v4.4.2</a></li>
46
+ <li><a href="https://github.com/huggingface/transformers/tree/v4.3.3/examples">v4.3.3</a></li>
47
+ <li><a href="https://github.com/huggingface/transformers/tree/v4.2.2/examples">v4.2.2</a></li>
48
+ <li><a href="https://github.com/huggingface/transformers/tree/v4.1.1/examples">v4.1.1</a></li>
49
+ <li><a href="https://github.com/huggingface/transformers/tree/v4.0.1/examples">v4.0.1</a></li>
50
+ <li><a href="https://github.com/huggingface/transformers/tree/v3.5.1/examples">v3.5.1</a></li>
51
+ <li><a href="https://github.com/huggingface/transformers/tree/v3.4.0/examples">v3.4.0</a></li>
52
+ <li><a href="https://github.com/huggingface/transformers/tree/v3.3.1/examples">v3.3.1</a></li>
53
+ <li><a href="https://github.com/huggingface/transformers/tree/v3.2.0/examples">v3.2.0</a></li>
54
+ <li><a href="https://github.com/huggingface/transformers/tree/v3.1.0/examples">v3.1.0</a></li>
55
+ <li><a href="https://github.com/huggingface/transformers/tree/v3.0.2/examples">v3.0.2</a></li>
56
+ <li><a href="https://github.com/huggingface/transformers/tree/v2.11.0/examples">v2.11.0</a></li>
57
+ <li><a href="https://github.com/huggingface/transformers/tree/v2.10.0/examples">v2.10.0</a></li>
58
+ <li><a href="https://github.com/huggingface/transformers/tree/v2.9.1/examples">v2.9.1</a></li>
59
+ <li><a href="https://github.com/huggingface/transformers/tree/v2.8.0/examples">v2.8.0</a></li>
60
+ <li><a href="https://github.com/huggingface/transformers/tree/v2.7.0/examples">v2.7.0</a></li>
61
+ <li><a href="https://github.com/huggingface/transformers/tree/v2.6.0/examples">v2.6.0</a></li>
62
+ <li><a href="https://github.com/huggingface/transformers/tree/v2.5.1/examples">v2.5.1</a></li>
63
+ <li><a href="https://github.com/huggingface/transformers/tree/v2.4.0/examples">v2.4.0</a></li>
64
+ <li><a href="https://github.com/huggingface/transformers/tree/v2.3.0/examples">v2.3.0</a></li>
65
+ <li><a href="https://github.com/huggingface/transformers/tree/v2.2.0/examples">v2.2.0</a></li>
66
+ <li><a href="https://github.com/huggingface/transformers/tree/v2.1.0/examples">v2.1.1</a></li>
67
+ <li><a href="https://github.com/huggingface/transformers/tree/v2.0.0/examples">v2.0.0</a></li>
68
+ <li><a href="https://github.com/huggingface/transformers/tree/v1.2.0/examples">v1.2.0</a></li>
69
+ <li><a href="https://github.com/huggingface/transformers/tree/v1.1.0/examples">v1.1.0</a></li>
70
+ <li><a href="https://github.com/huggingface/transformers/tree/v1.0.0/examples">v1.0.0</a></li>
71
+ </ul>
72
+ </details>
73
+
74
+ Em seguida, mude seu clone atual dos 🤗 Transformers para uma versão específica, como v3.5.1, por exemplo:
75
+
76
+ ```bash
77
+ git checkout tags/v3.5.1
78
+ ```
79
+
80
+ Depois de configurar a versão correta da biblioteca, navegue até a pasta de exemplo de sua escolha e instale os requisitos específicos do exemplo:
81
+
82
+ ```bash
83
+ pip install -r requirements.txt
84
+ ```
85
+
86
+ ## Executando um script
87
+
88
+ <frameworkcontent>
89
+ <pt>
90
+
91
+ O script de exemplo baixa e pré-processa um conjunto de dados da biblioteca 🤗 [Datasets](https://huggingface.co/docs/datasets/). Em seguida, o script ajusta um conjunto de dados com o [Trainer](https://huggingface.co/docs/transformers/main_classes/trainer) em uma arquitetura que oferece suporte à sumarização. O exemplo a seguir mostra como ajustar [T5-small](https://huggingface.co/google-t5/t5-small) no conjunto de dados [CNN/DailyMail](https://huggingface.co/datasets/cnn_dailymail). O modelo T5 requer um argumento `source_prefix` adicional devido à forma como foi treinado. Este prompt informa ao T5 que esta é uma tarefa de sumarização.
92
+
93
+ ```bash
94
+ python examples/pytorch/summarization/run_summarization.py \
95
+ --model_name_or_path google-t5/t5-small \
96
+ --do_train \
97
+ --do_eval \
98
+ --dataset_name cnn_dailymail \
99
+ --dataset_config "3.0.0" \
100
+ --source_prefix "summarize: " \
101
+ --output_dir /tmp/tst-summarization \
102
+ --per_device_train_batch_size=4 \
103
+ --per_device_eval_batch_size=4 \
104
+ --overwrite_output_dir \
105
+ --predict_with_generate
106
+ ```
107
+ </pt>
108
+ <tf>
109
+ Este outro script de exemplo baixa e pré-processa um conjunto de dados da biblioteca 🤗 [Datasets](https://huggingface.co/docs/datasets/). Em seguida, o script ajusta um conjunto de dados usando Keras em uma arquitetura que oferece suporte à sumarização. O exemplo a seguir mostra como ajustar [T5-small](https://huggingface.co/google-t5/t5-small) no conjunto de dados [CNN/DailyMail](https://huggingface.co/datasets/cnn_dailymail). O modelo T5 requer um argumento `source_prefix` adicional devido à forma como foi treinado. Este prompt informa ao T5 que esta é uma tarefa de sumarização.
110
+
111
+ ```bash
112
+ python examples/tensorflow/summarization/run_summarization.py \
113
+ --model_name_or_path google-t5/t5-small \
114
+ --dataset_name cnn_dailymail \
115
+ --dataset_config "3.0.0" \
116
+ --output_dir /tmp/tst-summarization \
117
+ --per_device_train_batch_size 8 \
118
+ --per_device_eval_batch_size 16 \
119
+ --num_train_epochs 3 \
120
+ --do_train \
121
+ --do_eval
122
+ ```
123
+ </tf>
124
+ </frameworkcontent>
125
+
126
+ ## Treinamento distribuído e precisão mista
127
+
128
+ O [Trainer](https://huggingface.co/docs/transformers/main_classes/trainer) oferece suporte a treinamento distribuído e precisão mista, o que significa que você também pode usá-lo em um script. Para habilitar esses dois recursos:
129
+
130
+ - Adicione o argumento `fp16` para habilitar a precisão mista.
131
+ - Defina o número de GPUs a serem usadas com o argumento `nproc_per_node`.
132
+
133
+ ```bash
134
+ torchrun \
135
+ --nproc_per_node 8 pytorch/summarization/run_summarization.py \
136
+ --fp16 \
137
+ --model_name_or_path google-t5/t5-small \
138
+ --do_train \
139
+ --do_eval \
140
+ --dataset_name cnn_dailymail \
141
+ --dataset_config "3.0.0" \
142
+ --source_prefix "summarize: " \
143
+ --output_dir /tmp/tst-summarization \
144
+ --per_device_train_batch_size=4 \
145
+ --per_device_eval_batch_size=4 \
146
+ --overwrite_output_dir \
147
+ --predict_with_generate
148
+ ```
149
+
150
+ Os scripts do TensorFlow utilizam um [`MirroredStrategy`](https://www.tensorflow.org/guide/distributed_training#mirroredstrategy) para treinamento distribuído, e você não precisa adicionar argumentos adicionais ao script de treinamento. O script do TensorFlow usará várias GPUs por padrão, se estiverem disponíveis.
151
+
152
+ ## Executando um script em uma TPU
153
+
154
+ <frameworkcontent>
155
+ <pt>
156
+ As Unidades de Processamento de Tensor (TPUs) são projetadas especificamente para acelerar o desempenho. O PyTorch oferece suporte a TPUs com o compilador de aprendizado profundo [XLA](https://www.tensorflow.org/xla) (consulte [aqui](https://github.com/pytorch/xla/blob/master/README.md) para mais detalhes). Para usar uma TPU, inicie o script `xla_spawn.py` e use o argumento `num_cores` para definir o número de núcleos de TPU que você deseja usar.
157
+
158
+ ```bash
159
+ python xla_spawn.py --num_cores 8 \
160
+ summarization/run_summarization.py \
161
+ --model_name_or_path google-t5/t5-small \
162
+ --do_train \
163
+ --do_eval \
164
+ --dataset_name cnn_dailymail \
165
+ --dataset_config "3.0.0" \
166
+ --source_prefix "summarize: " \
167
+ --output_dir /tmp/tst-summarization \
168
+ --per_device_train_batch_size=4 \
169
+ --per_device_eval_batch_size=4 \
170
+ --overwrite_output_dir \
171
+ --predict_with_generate
172
+ ```
173
+ </pt>
174
+ <tf>
175
+
176
+ As Unidades de Processamento de Tensor (TPUs) são projetadas especificamente para acelerar o desempenho. Os scripts do TensorFlow utilizam uma [`TPUStrategy`](https://www.tensorflow.org/guide/distributed_training#tpustrategy) para treinamento em TPUs. Para usar uma TPU, passe o nome do recurso TPU para o argumento `tpu`.
177
+
178
+ ```bash
179
+ python run_summarization.py \
180
+ --tpu name_of_tpu_resource \
181
+ --model_name_or_path google-t5/t5-small \
182
+ --dataset_name cnn_dailymail \
183
+ --dataset_config "3.0.0" \
184
+ --output_dir /tmp/tst-summarization \
185
+ --per_device_train_batch_size 8 \
186
+ --per_device_eval_batch_size 16 \
187
+ --num_train_epochs 3 \
188
+ --do_train \
189
+ --do_eval
190
+ ```
191
+ </tf>
192
+ </frameworkcontent>
193
+
194
+ ## Execute um script com 🤗 Accelerate
195
+
196
+ 🤗 [Accelerate](https://huggingface.co/docs/accelerate) é uma biblioteca somente do PyTorch que oferece um método unificado para treinar um modelo em vários tipos de configurações (CPU, multiplas GPUs, TPUs), mantendo visibilidade no loop de treinamento do PyTorch. Certifique-se de ter o 🤗 Accelerate instalado se ainda não o tiver:
197
+
198
+ > Nota: Como o Accelerate está se desenvolvendo rapidamente, a versão git do Accelerate deve ser instalada para executar os scripts
199
+
200
+ ```bash
201
+ pip install git+https://github.com/huggingface/accelerate
202
+ ```
203
+
204
+ Em vez do script `run_summarization.py`, você precisa usar o script `run_summarization_no_trainer.py`. Os scripts suportados pelo 🤗 Accelerate terão um arquivo `task_no_trainer.py` na pasta. Comece executando o seguinte comando para criar e salvar um arquivo de configuração:
205
+
206
+ ```bash
207
+ accelerate config
208
+ ```
209
+
210
+ Teste sua configuração para garantir que ela esteja corretamente configurada :
211
+
212
+ ```bash
213
+ accelerate test
214
+ ```
215
+
216
+ Agora você está pronto para iniciar o treinamento:
217
+
218
+ ```bash
219
+ accelerate launch run_summarization_no_trainer.py \
220
+ --model_name_or_path google-t5/t5-small \
221
+ --dataset_name cnn_dailymail \
222
+ --dataset_config "3.0.0" \
223
+ --source_prefix "summarize: " \
224
+ --output_dir ~/tmp/tst-summarization
225
+ ```
226
+
227
+ ## Usando um conjunto de dados personalizado
228
+
229
+ O script de resumo oferece suporte a conjuntos de dados personalizados, desde que sejam um arquivo CSV ou JSON. Ao usar seu próprio conjunto de dados, você precisa especificar vários argumentos adicionais:
230
+
231
+ - `train_file` e `validation_file` especificam o caminho para seus arquivos de treinamento e validação respectivamente.
232
+ - `text_column` é o texto de entrada para sumarização.
233
+ - `summary_column` é o texto de destino para saída.
234
+
235
+ Um script para sumarização usando um conjunto de dados customizado ficaria assim:
236
+
237
+ ```bash
238
+ python examples/pytorch/summarization/run_summarization.py \
239
+ --model_name_or_path google-t5/t5-small \
240
+ --do_train \
241
+ --do_eval \
242
+ --train_file path_to_csv_or_jsonlines_file \
243
+ --validation_file path_to_csv_or_jsonlines_file \
244
+ --text_column text_column_name \
245
+ --summary_column summary_column_name \
246
+ --source_prefix "summarize: " \
247
+ --output_dir /tmp/tst-summarization \
248
+ --overwrite_output_dir \
249
+ --per_device_train_batch_size=4 \
250
+ --per_device_eval_batch_size=4 \
251
+ --predict_with_generate
252
+ ```
253
+
254
+ ## Testando um script
255
+
256
+ Geralmente, é uma boa ideia executar seu script em um número menor de exemplos de conjuntos de dados para garantir que tudo funcione conforme o esperado antes de se comprometer com um conjunto de dados inteiro, que pode levar horas para ser concluído. Use os seguintes argumentos para truncar o conjunto de dados para um número máximo de amostras:
257
+
258
+ - `max_train_samples`
259
+ - `max_eval_samples`
260
+ - `max_predict_samples`
261
+
262
+ ```bash
263
+ python examples/pytorch/summarization/run_summarization.py \
264
+ --model_name_or_path google-t5/t5-small \
265
+ --max_train_samples 50 \
266
+ --max_eval_samples 50 \
267
+ --max_predict_samples 50 \
268
+ --do_train \
269
+ --do_eval \
270
+ --dataset_name cnn_dailymail \
271
+ --dataset_config "3.0.0" \
272
+ --source_prefix "summarize: " \
273
+ --output_dir /tmp/tst-summarization \
274
+ --per_device_train_batch_size=4 \
275
+ --per_device_eval_batch_size=4 \
276
+ --overwrite_output_dir \
277
+ --predict_with_generate
278
+ ```
279
+
280
+ Nem todos os scripts de exemplo suportam o argumento `max_predict_samples`. Se você não tiver certeza se seu script suporta este argumento, adicione o argumento `-h` para verificar:
281
+
282
+ ```bash
283
+ examples/pytorch/summarization/run_summarization.py -h
284
+ ```
285
+
286
+ ## Retomar o treinamento a partir de um checkpoint
287
+
288
+ Outra opção útil para habilitar é retomar o treinamento de um checkpoint anterior. Isso garantirá que você possa continuar de onde parou sem recomeçar se o seu treinamento for interrompido. Existem dois métodos para retomar o treinamento a partir de um checkpoint.
289
+
290
+ O primeiro método usa o argumento `output_dir previous_output_dir` para retomar o treinamento do último checkpoint armazenado em `output_dir`. Neste caso, você deve remover `overwrite_output_dir`:
291
+
292
+ ```bash
293
+ python examples/pytorch/summarization/run_summarization.py
294
+ --model_name_or_path google-t5/t5-small \
295
+ --do_train \
296
+ --do_eval \
297
+ --dataset_name cnn_dailymail \
298
+ --dataset_config "3.0.0" \
299
+ --source_prefix "summarize: " \
300
+ --output_dir /tmp/tst-summarization \
301
+ --per_device_train_batch_size=4 \
302
+ --per_device_eval_batch_size=4 \
303
+ --output_dir previous_output_dir \
304
+ --predict_with_generate
305
+ ```
306
+
307
+ O segundo método usa o argumento `resume_from_checkpoint path_to_specific_checkpoint` para retomar o treinamento de uma pasta de checkpoint específica.
308
+
309
+ ```bash
310
+ python examples/pytorch/summarization/run_summarization.py
311
+ --model_name_or_path google-t5/t5-small \
312
+ --do_train \
313
+ --do_eval \
314
+ --dataset_name cnn_dailymail \
315
+ --dataset_config "3.0.0" \
316
+ --source_prefix "summarize: " \
317
+ --output_dir /tmp/tst-summarization \
318
+ --per_device_train_batch_size=4 \
319
+ --per_device_eval_batch_size=4 \
320
+ --overwrite_output_dir \
321
+ --resume_from_checkpoint path_to_specific_checkpoint \
322
+ --predict_with_generate
323
+ ```
324
+
325
+ ## Compartilhando seu modelo
326
+
327
+ Todos os scripts podem enviar seu modelo final para o [Model Hub](https://huggingface.co/models). Certifique-se de estar conectado ao Hugging Face antes de começar:
328
+
329
+ ```bash
330
+ hf auth login
331
+ ```
332
+
333
+ Em seguida, adicione o argumento `push_to_hub` ao script. Este argumento criará um repositório com seu nome de usuário do Hugging Face e o nome da pasta especificado em `output_dir`.
334
+
335
+ Para dar um nome específico ao seu repositório, use o argumento `push_to_hub_model_id` para adicioná-lo. O repositório será listado automaticamente em seu namespace.
336
+
337
+ O exemplo a seguir mostra como fazer upload de um modelo com um nome de repositório específico:
338
+
339
+ ```bash
340
+ python examples/pytorch/summarization/run_summarization.py
341
+ --model_name_or_path google-t5/t5-small \
342
+ --do_train \
343
+ --do_eval \
344
+ --dataset_name cnn_dailymail \
345
+ --dataset_config "3.0.0" \
346
+ --source_prefix "summarize: " \
347
+ --push_to_hub \
348
+ --push_to_hub_model_id finetuned-t5-cnn_dailymail \
349
+ --output_dir /tmp/tst-summarization \
350
+ --per_device_train_batch_size=4 \
351
+ --per_device_eval_batch_size=4 \
352
+ --overwrite_output_dir \
353
+ --predict_with_generate
354
+ ```
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/serialization.md ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2020 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # Exportando modelos para ONNX
18
+
19
+ Se você precisar implantar modelos 🤗 Transformers em ambientes de produção, recomendamos
20
+ exporta-los para um formato serializado que pode ser carregado e executado em
21
+ tempos de execução e hardware. Neste guia, mostraremos como exportar modelos 🤗 Transformers
22
+ para [ONNX (Open Neural Network eXchange)](http://onnx.ai).
23
+
24
+ <Tip>
25
+
26
+ Uma vez exportado, um modelo pode ser otimizado para inferência por meio de técnicas como
27
+ quantização e poda. Se você estiver interessado em otimizar seus modelos para serem executados com
28
+ máxima eficiência, confira a biblioteca [🤗 Optimum
29
+ ](https://github.com/huggingface/optimum).
30
+
31
+ </Tip>
32
+
33
+ ONNX é um padrão aberto que define um conjunto comum de operadores e um formato de arquivo comum
34
+ para representar modelos de aprendizado profundo em uma ampla variedade de estruturas, incluindo PyTorch e
35
+ TensorFlow. Quando um modelo é exportado para o formato ONNX, esses operadores são usados para
36
+ construir um grafo computacional (muitas vezes chamado de _representação intermediária_) que
37
+ representa o fluxo de dados através da rede neural.
38
+
39
+ Ao expor um grafo com operadores e tipos de dados padronizados, o ONNX facilita a
40
+ alternar entre os frameworks. Por exemplo, um modelo treinado em PyTorch pode ser exportado para
41
+ formato ONNX e depois importado no TensorFlow (e vice-versa).
42
+
43
+ 🤗 Transformers fornece um pacote [`transformers.onnx`](main_classes/onnx) que permite
44
+ que você converta os checkpoints do modelo em um grafo ONNX aproveitando os objetos de configuração.
45
+ Esses objetos de configuração vêm prontos para várias arquiteturas de modelo e são
46
+ projetado para ser facilmente extensível a outras arquiteturas.
47
+
48
+ As configurações prontas incluem as seguintes arquiteturas:
49
+
50
+ <!--This table is automatically generated by `make fix-copies`, do not fill manually!-->
51
+
52
+ - ALBERT
53
+ - BART
54
+ - BEiT
55
+ - BERT
56
+ - BigBird
57
+ - BigBird-Pegasus
58
+ - Blenderbot
59
+ - BlenderbotSmall
60
+ - BLOOM
61
+ - CamemBERT
62
+ - CLIP
63
+ - CodeGen
64
+ - Conditional DETR
65
+ - ConvBERT
66
+ - ConvNeXT
67
+ - ConvNeXTV2
68
+ - Data2VecText
69
+ - Data2VecVision
70
+ - DeBERTa
71
+ - DeBERTa-v2
72
+ - DeiT
73
+ - DETR
74
+ - DistilBERT
75
+ - ELECTRA
76
+ - ERNIE
77
+ - FlauBERT
78
+ - GPT Neo
79
+ - GPT-J
80
+ - GroupViT
81
+ - I-BERT
82
+ - LayoutLM
83
+ - LayoutLMv3
84
+ - LeViT
85
+ - Longformer
86
+ - LongT5
87
+ - M2M100
88
+ - Marian
89
+ - mBART
90
+ - MobileBERT
91
+ - MobileViT
92
+ - MT5
93
+ - OpenAI GPT-2
94
+ - OWL-ViT
95
+ - Perceiver
96
+ - PLBart
97
+ - ResNet
98
+ - RoBERTa
99
+ - RoFormer
100
+ - SegFormer
101
+ - SqueezeBERT
102
+ - Swin Transformer
103
+ - T5
104
+ - Table Transformer
105
+ - Vision Encoder decoder
106
+ - ViT
107
+ - XLM
108
+ - XLM-RoBERTa
109
+ - XLM-RoBERTa-XL
110
+ - YOLOS
111
+
112
+ Nas próximas duas seções, mostraremos como:
113
+
114
+ * Exportar um modelo suportado usando o pacote `transformers.onnx`.
115
+ * Exportar um modelo personalizado para uma arquitetura sem suporte.
116
+
117
+ ## Exportando um modelo para ONNX
118
+
119
+ Para exportar um modelo 🤗 Transformers para o ONNX, primeiro você precisa instalar algumas
120
+ dependências extras:
121
+
122
+ ```bash
123
+ pip install transformers[onnx]
124
+ ```
125
+
126
+ O pacote `transformers.onnx` pode então ser usado como um módulo Python:
127
+
128
+ ```bash
129
+ python -m transformers.onnx --help
130
+
131
+ usage: Hugging Face Transformers ONNX exporter [-h] -m MODEL [--feature {causal-lm, ...}] [--opset OPSET] [--atol ATOL] output
132
+
133
+ positional arguments:
134
+ output Path indicating where to store generated ONNX model.
135
+
136
+ optional arguments:
137
+ -h, --help show this help message and exit
138
+ -m MODEL, --model MODEL
139
+ Model ID on huggingface.co or path on disk to load model from.
140
+ --feature {causal-lm, ...}
141
+ The type of features to export the model with.
142
+ --opset OPSET ONNX opset version to export the model with.
143
+ --atol ATOL Absolute difference tolerance when validating the model.
144
+ ```
145
+
146
+ A exportação de um checkpoint usando uma configuração pronta pode ser feita da seguinte forma:
147
+
148
+ ```bash
149
+ python -m transformers.onnx --model=distilbert/distilbert-base-uncased onnx/
150
+ ```
151
+
152
+ Você deve ver os seguintes logs:
153
+
154
+ ```bash
155
+ Validating ONNX model...
156
+ -[✓] ONNX model output names match reference model ({'last_hidden_state'})
157
+ - Validating ONNX Model output "last_hidden_state":
158
+ -[✓] (2, 8, 768) matches (2, 8, 768)
159
+ -[✓] all values close (atol: 1e-05)
160
+ All good, model saved at: onnx/model.onnx
161
+ ```
162
+
163
+ Isso exporta um grafo ONNX do ponto de verificação definido pelo argumento `--model`. Nisso
164
+ Por exemplo, é `distilbert/distilbert-base-uncased`, mas pode ser qualquer checkpoint no Hugging
165
+ Face Hub ou um armazenado localmente.
166
+
167
+ O arquivo `model.onnx` resultante pode ser executado em um dos [muitos
168
+ aceleradores](https://onnx.ai/supported-tools.html#deployModel) que suportam o ONNX
169
+ padrão. Por exemplo, podemos carregar e executar o modelo com [ONNX
170
+ Tempo de execução](https://onnxruntime.ai/) da seguinte forma:
171
+
172
+ ```python
173
+ >>> from transformers import AutoTokenizer
174
+ >>> from onnxruntime import InferenceSession
175
+
176
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
177
+ >>> session = InferenceSession("onnx/model.onnx")
178
+ >>> # ONNX Runtime expects NumPy arrays as input
179
+ >>> inputs = tokenizer("Using DistilBERT with ONNX Runtime!", return_tensors="np")
180
+ >>> outputs = session.run(output_names=["last_hidden_state"], input_feed=dict(inputs))
181
+ ```
182
+
183
+ Os nomes de saída necessários (como `["last_hidden_state"]`) podem ser obtidos pegando uma
184
+ configuração ONNX de cada modelo. Por exemplo, para DistilBERT temos:
185
+
186
+ ```python
187
+ >>> from transformers.models.distilbert import DistilBertConfig, DistilBertOnnxConfig
188
+
189
+ >>> config = DistilBertConfig()
190
+ >>> onnx_config = DistilBertOnnxConfig(config)
191
+ >>> print(list(onnx_config.outputs.keys()))
192
+ ["last_hidden_state"]
193
+ ```
194
+
195
+ O processo é idêntico para os checkpoints do TensorFlow no Hub. Por exemplo, podemos
196
+ exportar um checkpoint TensorFlow puro do [Keras
197
+ ](https://huggingface.co/keras-io) da seguinte forma:
198
+
199
+ ```bash
200
+ python -m transformers.onnx --model=keras-io/transformers-qa onnx/
201
+ ```
202
+
203
+ Para exportar um modelo armazenado localmente, você precisará ter os pesos e
204
+ arquivos tokenizer armazenados em um diretório. Por exemplo, podemos carregar e salvar um checkpoint como:
205
+
206
+ ```python
207
+ >>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
208
+
209
+ >>> # Load tokenizer and PyTorch weights form the Hub
210
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
211
+ >>> pt_model = AutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased")
212
+ >>> # Save to disk
213
+ >>> tokenizer.save_pretrained("local-pt-checkpoint")
214
+ >>> pt_model.save_pretrained("local-pt-checkpoint")
215
+ ```
216
+
217
+ Uma vez que o checkpoint é salvo, podemos exportá-lo para o ONNX apontando o `--model`
218
+ argumento do pacote `transformers.onnx` para o diretório desejado:
219
+
220
+ ```bash
221
+ python -m transformers.onnx --model=local-pt-checkpoint onnx/
222
+ ```
223
+
224
+ ```python
225
+ >>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
226
+
227
+ >>> # Load tokenizer and TensorFlow weights from the Hub
228
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
229
+ >>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased")
230
+ >>> # Save to disk
231
+ >>> tokenizer.save_pretrained("local-tf-checkpoint")
232
+ >>> tf_model.save_pretrained("local-tf-checkpoint")
233
+ ```
234
+
235
+ Uma vez que o checkpoint é salvo, podemos exportá-lo para o ONNX apontando o `--model`
236
+ argumento do pacote `transformers.onnx` para o diretório desejado:
237
+
238
+ ```bash
239
+ python -m transformers.onnx --model=local-tf-checkpoint onnx/
240
+ ```
241
+
242
+ ## Selecionando features para diferentes tarefas do modelo
243
+
244
+ Cada configuração pronta vem com um conjunto de _features_ que permitem exportar
245
+ modelos para diferentes tipos de tarefas. Conforme mostrado na tabela abaixo, cada recurso é
246
+ associado a uma `AutoClass` diferente:
247
+
248
+ | Feature | Auto Class |
249
+ | ------------------------------------ | ------------------------------------ |
250
+ | `causal-lm`, `causal-lm-with-past` | `AutoModelForCausalLM` |
251
+ | `default`, `default-with-past` | `AutoModel` |
252
+ | `masked-lm` | `AutoModelForMaskedLM` |
253
+ | `question-answering` | `AutoModelForQuestionAnswering` |
254
+ | `seq2seq-lm`, `seq2seq-lm-with-past` | `AutoModelForSeq2SeqLM` |
255
+ | `sequence-classification` | `AutoModelForSequenceClassification` |
256
+ | `token-classification` | `AutoModelForTokenClassification` |
257
+
258
+ Para cada configuração, você pode encontrar a lista de recursos suportados por meio do
259
+ [`~transformers.onnx.FeaturesManager`]. Por exemplo, para DistilBERT temos:
260
+
261
+ ```python
262
+ >>> from transformers.onnx.features import FeaturesManager
263
+
264
+ >>> distilbert_features = list(FeaturesManager.get_supported_features_for_model_type("distilbert").keys())
265
+ >>> print(distilbert_features)
266
+ ["default", "masked-lm", "causal-lm", "sequence-classification", "token-classification", "question-answering"]
267
+ ```
268
+
269
+ Você pode então passar um desses recursos para o argumento `--feature` no
270
+ pacote `transformers.onnx`. Por exemplo, para exportar um modelo de classificação de texto, podemos
271
+ escolher um modelo ajustado no Hub e executar:
272
+
273
+ ```bash
274
+ python -m transformers.onnx --model=distilbert/distilbert-base-uncased-finetuned-sst-2-english \
275
+ --feature=sequence-classification onnx/
276
+ ```
277
+
278
+ Isso exibe os seguintes logs:
279
+
280
+ ```bash
281
+ Validating ONNX model...
282
+ -[✓] ONNX model output names match reference model ({'logits'})
283
+ - Validating ONNX Model output "logits":
284
+ -[✓] (2, 2) matches (2, 2)
285
+ -[✓] all values close (atol: 1e-05)
286
+ All good, model saved at: onnx/model.onnx
287
+ ```
288
+
289
+ Observe que, neste caso, os nomes de saída do modelo ajustado são `logits`
290
+ em vez do `last_hidden_state` que vimos com o checkpoint `distilbert/distilbert-base-uncased`
291
+ mais cedo. Isso é esperado, pois o modelo ajustado (fine-tuned) possui uma cabeça de classificação de sequência.
292
+
293
+ <Tip>
294
+
295
+ Os recursos que têm um sufixo `with-pass` (como `causal-lm-with-pass`) correspondem a
296
+ classes de modelo com estados ocultos pré-computados (chave e valores nos blocos de atenção)
297
+ que pode ser usado para decodificação autorregressiva rápida.
298
+
299
+ </Tip>
300
+
301
+ <Tip>
302
+
303
+ Para modelos do tipo `VisionEncoderDecoder`, as partes do codificador e do decodificador são
304
+ exportados separadamente como dois arquivos ONNX chamados `encoder_model.onnx` e `decoder_model.onnx` respectivamente.
305
+
306
+ </Tip>
307
+
308
+ ## Exportando um modelo para uma arquitetura sem suporte
309
+
310
+ Se você deseja exportar um modelo cuja arquitetura não é suportada nativamente pela
311
+ biblioteca, há três etapas principais a seguir:
312
+
313
+ 1. Implemente uma configuração ONNX personalizada.
314
+ 2. Exporte o modelo para o ONNX.
315
+ 3. Valide as saídas do PyTorch e dos modelos exportados.
316
+
317
+ Nesta seção, veremos como o DistilBERT foi implementado para mostrar o que está envolvido
318
+ em cada passo.
319
+
320
+ ### Implementando uma configuração ONNX personalizada
321
+
322
+ Vamos começar com o objeto de configuração ONNX. Fornecemos três classes abstratas que
323
+ você deve herdar, dependendo do tipo de arquitetura de modelo que deseja exportar:
324
+
325
+ * Modelos baseados em codificador herdam de [`~onnx.config.OnnxConfig`]
326
+ * Modelos baseados em decodificador herdam de [`~onnx.config.OnnxConfigWithPast`]
327
+ * Os modelos codificador-decodificador herdam de [`~onnx.config.OnnxSeq2SeqConfigWithPast`]
328
+
329
+ <Tip>
330
+
331
+ Uma boa maneira de implementar uma configuração ONNX personalizada é observar as
332
+ implementação no arquivo `configuration_<model_name>.py` de uma arquitetura semelhante.
333
+
334
+ </Tip>
335
+
336
+ Como o DistilBERT é um modelo baseado em codificador, sua configuração é herdada de
337
+ `OnnxConfig`:
338
+
339
+ ```python
340
+ >>> from typing import Mapping, OrderedDict
341
+ >>> from transformers.onnx import OnnxConfig
342
+
343
+
344
+ >>> class DistilBertOnnxConfig(OnnxConfig):
345
+ ... @property
346
+ ... def inputs(self) -> Mapping[str, Mapping[int, str]]:
347
+ ... return OrderedDict(
348
+ ... [
349
+ ... ("input_ids", {0: "batch", 1: "sequence"}),
350
+ ... ("attention_mask", {0: "batch", 1: "sequence"}),
351
+ ... ]
352
+ ... )
353
+ ```
354
+
355
+ Todo objeto de configuração deve implementar a propriedade `inputs` e retornar um mapeamento,
356
+ onde cada chave corresponde a uma entrada esperada e cada valor indica o eixo
357
+ dessa entrada. Para o DistilBERT, podemos ver que duas entradas são necessárias: `input_ids` e
358
+ `attention_mask`. Essas entradas têm a mesma forma de `(batch_size, sequence_length)`
359
+ é por isso que vemos os mesmos eixos usados na configuração.
360
+
361
+ <Tip>
362
+
363
+ Notice that `inputs` property for `DistilBertOnnxConfig` returns an `OrderedDict`. This
364
+ ensures that the inputs are matched with their relative position within the
365
+ `PreTrainedModel.forward()` method when tracing the graph. We recommend using an
366
+ `OrderedDict` for the `inputs` and `outputs` properties when implementing custom ONNX
367
+ configurations.
368
+
369
+ Observe que a propriedade `inputs` para `DistilBertOnnxConfig` retorna um `OrderedDict`. Este
370
+ garante que as entradas sejam combinadas com sua posição relativa dentro do
371
+ método `PreTrainedModel.forward()` ao traçar o grafo. Recomendamos o uso de um
372
+ `OrderedDict` para as propriedades `inputs` e `outputs` ao implementar configurações personalizadas ONNX.
373
+
374
+ </Tip>
375
+
376
+ Depois de implementar uma configuração ONNX, você pode instanciá-la fornecendo a
377
+ configuração do modelo base da seguinte forma:
378
+
379
+ ```python
380
+ >>> from transformers import AutoConfig
381
+
382
+ >>> config = AutoConfig.from_pretrained("distilbert/distilbert-base-uncased")
383
+ >>> onnx_config = DistilBertOnnxConfig(config)
384
+ ```
385
+
386
+ O objeto resultante tem várias propriedades úteis. Por exemplo, você pode visualizar o conjunto de operadores ONNX
387
+ que será usado durante a exportação:
388
+
389
+ ```python
390
+ >>> print(onnx_config.default_onnx_opset)
391
+ 11
392
+ ```
393
+
394
+ Você também pode visualizar as saídas associadas ao modelo da seguinte forma:
395
+
396
+ ```python
397
+ >>> print(onnx_config.outputs)
398
+ OrderedDict([("last_hidden_state", {0: "batch", 1: "sequence"})])
399
+ ```
400
+
401
+ Observe que a propriedade outputs segue a mesma estrutura das entradas; ele retorna um
402
+ `OrderedDict` de saídas nomeadas e suas formas. A estrutura de saída está ligada a
403
+ escolha do recurso com o qual a configuração é inicializada. Por padrão, a configuração do ONNX
404
+ é inicializada com o recurso `default` que corresponde à exportação de um
405
+ modelo carregado com a classe `AutoModel`. Se você deseja exportar um modelo para outra tarefa,
406
+ apenas forneça um recurso diferente para o argumento `task` quando você inicializar a configuração ONNX
407
+ . Por exemplo, se quisermos exportar o DistilBERT com uma sequência
408
+ de classificação, poderíamos usar:
409
+
410
+ ```python
411
+ >>> from transformers import AutoConfig
412
+
413
+ >>> config = AutoConfig.from_pretrained("distilbert/distilbert-base-uncased")
414
+ >>> onnx_config_for_seq_clf = DistilBertOnnxConfig(config, task="sequence-classification")
415
+ >>> print(onnx_config_for_seq_clf.outputs)
416
+ OrderedDict([('logits', {0: 'batch'})])
417
+ ```
418
+
419
+ <Tip>
420
+
421
+ Todas as propriedades e métodos básicos associados a [`~onnx.config.OnnxConfig`] e
422
+ as outras classes de configuração podem ser substituídas se necessário. Confira [`BartOnnxConfig`]
423
+ para um exemplo avançado.
424
+
425
+ </Tip>
426
+
427
+ ### Exportando um modelo
428
+
429
+ Depois de ter implementado a configuração do ONNX, o próximo passo é exportar o modelo.
430
+ Aqui podemos usar a função `export()` fornecida pelo pacote `transformers.onnx`.
431
+ Esta função espera a configuração do ONNX, juntamente com o modelo base e o tokenizer,
432
+ e o caminho para salvar o arquivo exportado:
433
+
434
+ ```python
435
+ >>> from pathlib import Path
436
+ >>> from transformers.onnx import export
437
+ >>> from transformers import AutoTokenizer, AutoModel
438
+
439
+ >>> onnx_path = Path("model.onnx")
440
+ >>> model_ckpt = "distilbert/distilbert-base-uncased"
441
+ >>> base_model = AutoModel.from_pretrained(model_ckpt)
442
+ >>> tokenizer = AutoTokenizer.from_pretrained(model_ckpt)
443
+
444
+ >>> onnx_inputs, onnx_outputs = export(tokenizer, base_model, onnx_config, onnx_config.default_onnx_opset, onnx_path)
445
+ ```
446
+
447
+ Os `onnx_inputs` e `onnx_outputs` retornados pela função `export()` são listas de
448
+ chaves definidas nas propriedades `inputs` e `outputs` da configuração. Uma vez que o
449
+ modelo é exportado, você pode testar se o modelo está bem formado da seguinte forma:
450
+
451
+ ```python
452
+ >>> import onnx
453
+
454
+ >>> onnx_model = onnx.load("model.onnx")
455
+ >>> onnx.checker.check_model(onnx_model)
456
+ ```
457
+
458
+ <Tip>
459
+
460
+ Se o seu modelo for maior que 2GB, você verá que muitos arquivos adicionais são criados
461
+ durante a exportação. Isso é _esperado_ porque o ONNX usa [Protocol
462
+ Buffers](https://developers.google.com/protocol-buffers/) para armazenar o modelo e estes
463
+ têm um limite de tamanho de 2GB. Veja a [ONNX
464
+ documentação](https://github.com/onnx/onnx/blob/master/docs/ExternalData.md) para
465
+ instruções sobre como carregar modelos com dados externos.
466
+
467
+ </Tip>
468
+
469
+ ### Validando a saída dos modelos
470
+
471
+ A etapa final é validar se as saídas do modelo base e exportado concordam
472
+ dentro de alguma tolerância absoluta. Aqui podemos usar a função `validate_model_outputs()`
473
+ fornecida pelo pacote `transformers.onnx` da seguinte forma:
474
+
475
+ ```python
476
+ >>> from transformers.onnx import validate_model_outputs
477
+
478
+ >>> validate_model_outputs(
479
+ ... onnx_config, tokenizer, base_model, onnx_path, onnx_outputs, onnx_config.atol_for_validation
480
+ ... )
481
+ ```
482
+
483
+ Esta função usa o método [`~transformers.onnx.OnnxConfig.generate_dummy_inputs`] para
484
+ gerar entradas para o modelo base e o exportado, e a tolerância absoluta pode ser
485
+ definida na configuração. Geralmente encontramos concordância numérica em 1e-6 a 1e-4
486
+ de alcance, embora qualquer coisa menor que 1e-3 provavelmente esteja OK.
487
+
488
+ ## Contribuindo com uma nova configuração para 🤗 Transformers
489
+
490
+ Estamos procurando expandir o conjunto de configurações prontas e receber contribuições
491
+ da comunidade! Se você gostaria de contribuir para a biblioteca, você
492
+ precisará:
493
+
494
+ * Implemente a configuração do ONNX no arquivo `configuration_<model_name>.py` correspondente
495
+ Arquivo
496
+ * Incluir a arquitetura do modelo e recursos correspondentes em
497
+ [`~onnx.features.FeatureManager`]
498
+ * Adicione sua arquitetura de modelo aos testes em `test_onnx_v2.py`
499
+
500
+ Confira como ficou a configuração do [IBERT
501
+ ](https://github.com/huggingface/transformers/pull/14868/files) para obter uma
502
+ idéia do que está envolvido.
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/tasks/sequence_classification.md ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # Classificação de texto
18
+
19
+ <Youtube id="leNG9fN9FQU"/>
20
+
21
+ A classificação de texto é uma tarefa comum de NLP que atribui um rótulo ou classe a um texto. Existem muitas aplicações práticas de classificação de texto amplamente utilizadas em produção por algumas das maiores empresas da atualidade. Uma das formas mais populares de classificação de texto é a análise de sentimento, que atribui um rótulo como positivo, negativo ou neutro a um texto.
22
+
23
+ Este guia mostrará como realizar o fine-tuning do [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased) no conjunto de dados [IMDb](https://huggingface.co/datasets/imdb) para determinar se a crítica de filme é positiva ou negativa.
24
+
25
+ <Tip>
26
+
27
+ Consulte a [página de tarefas de classificação de texto](https://huggingface.co/tasks/text-classification) para obter mais informações sobre outras formas de classificação de texto e seus modelos, conjuntos de dados e métricas associados.
28
+
29
+ </Tip>
30
+
31
+ ## Carregue o conjunto de dados IMDb
32
+
33
+ Carregue o conjunto de dados IMDb utilizando a biblioteca 🤗 Datasets:
34
+
35
+ ```py
36
+ >>> from datasets import load_dataset
37
+
38
+ >>> imdb = load_dataset("imdb")
39
+ ```
40
+
41
+ Em seguida, dê uma olhada em um exemplo:
42
+
43
+ ```py
44
+ >>> imdb["test"][0]
45
+ {
46
+ "label": 0,
47
+ "text": "I love sci-fi and am willing to put up with a lot. Sci-fi movies/TV are usually underfunded, under-appreciated and misunderstood. I tried to like this, I really did, but it is to good TV sci-fi as Babylon 5 is to Star Trek (the original). Silly prosthetics, cheap cardboard sets, stilted dialogues, CG that doesn't match the background, and painfully one-dimensional characters cannot be overcome with a 'sci-fi' setting. (I'm sure there are those of you out there who think Babylon 5 is good sci-fi TV. It's not. It's clichéd and uninspiring.) While US viewers might like emotion and character development, sci-fi is a genre that does not take itself seriously (cf. Star Trek). It may treat important issues, yet not as a serious philosophy. It's really difficult to care about the characters here as they are not simply foolish, just missing a spark of life. Their actions and reactions are wooden and predictable, often painful to watch. The makers of Earth KNOW it's rubbish as they have to always say \"Gene Roddenberry's Earth...\" otherwise people would not continue watching. Roddenberry's ashes must be turning in their orbit as this dull, cheap, poorly edited (watching it without advert breaks really brings this home) trudging Trabant of a show lumbers into space. Spoiler. So, kill off a main character. And then bring him back as another actor. Jeeez! Dallas all over again.",
48
+ }
49
+ ```
50
+
51
+ Existem dois campos neste dataset:
52
+
53
+ - `text`: uma string contendo o texto da crítica do filme.
54
+ - `label`: um valor que pode ser `0` para uma crítica negativa ou `1` para uma crítica positiva.
55
+
56
+ ## Pré-processamento dos dados
57
+
58
+ Carregue o tokenizador do DistilBERT para processar o campo `text`:
59
+
60
+ ```py
61
+ >>> from transformers import AutoTokenizer
62
+
63
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
64
+ ```
65
+
66
+ Crie uma função de pré-processamento para tokenizar o campo `text` e truncar as sequências para que não sejam maiores que o comprimento máximo de entrada do DistilBERT:
67
+
68
+ ```py
69
+ >>> def preprocess_function(examples):
70
+ ... return tokenizer(examples["text"], truncation=True)
71
+ ```
72
+
73
+ Use a função [`map`](https://huggingface.co/docs/datasets/process#map) do 🤗 Datasets para aplicar a função de pré-processamento em todo o conjunto de dados. Você pode acelerar a função `map` definindo `batched=True` para processar vários elementos do conjunto de dados de uma só vez:
74
+
75
+ ```py
76
+ tokenized_imdb = imdb.map(preprocess_function, batched=True)
77
+ ```
78
+
79
+ Use o [`DataCollatorWithPadding`] para criar um batch de exemplos. Ele também *preencherá dinamicamente* seu texto até o comprimento do elemento mais longo em seu batch, para que os exemplos do batch tenham um comprimento uniforme. Embora seja possível preencher seu texto com a função `tokenizer` definindo `padding=True`, o preenchimento dinâmico utilizando um data collator é mais eficiente.
80
+
81
+ <frameworkcontent>
82
+ <pt>
83
+ ```py
84
+ >>> from transformers import DataCollatorWithPadding
85
+
86
+ >>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
87
+ ```
88
+ </pt>
89
+ <tf>
90
+ ```py
91
+ >>> from transformers import DataCollatorWithPadding
92
+
93
+ >>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer, return_tensors="tf")
94
+ ```
95
+ </tf>
96
+ </frameworkcontent>
97
+
98
+ ## Train
99
+
100
+ <frameworkcontent>
101
+ <pt>
102
+ Carregue o DistilBERT com [`AutoModelForSequenceClassification`] junto com o número de rótulos esperados:
103
+
104
+ ```py
105
+ >>> from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer
106
+
107
+ >>> model = AutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased", num_labels=2)
108
+ ```
109
+
110
+ <Tip>
111
+
112
+ Se você não estiver familiarizado com o fine-tuning de um modelo com o [`Trainer`], dê uma olhada no tutorial básico [aqui](../training#finetune-with-trainer)!
113
+
114
+ </Tip>
115
+
116
+ Nesse ponto, restam apenas três passos:
117
+
118
+ 1. Definir seus hiperparâmetros de treinamento em [`TrainingArguments`].
119
+ 2. Passar os argumentos de treinamento para o [`Trainer`] junto com o modelo, conjunto de dados, tokenizador e o data collator.
120
+ 3. Chamar a função [`~Trainer.train`] para executar o fine-tuning do seu modelo.
121
+
122
+ ```py
123
+ >>> training_args = TrainingArguments(
124
+ ... output_dir="./results",
125
+ ... learning_rate=2e-5,
126
+ ... per_device_train_batch_size=16,
127
+ ... per_device_eval_batch_size=16,
128
+ ... num_train_epochs=5,
129
+ ... weight_decay=0.01,
130
+ ... )
131
+
132
+ >>> trainer = Trainer(
133
+ ... model=model,
134
+ ... args=training_args,
135
+ ... train_dataset=tokenized_imdb["train"],
136
+ ... eval_dataset=tokenized_imdb["test"],
137
+ ... processing_class=tokenizer,
138
+ ... data_collator=data_collator,
139
+ ... )
140
+
141
+ >>> trainer.train()
142
+ ```
143
+
144
+ <Tip>
145
+
146
+ O [`Trainer`] aplicará o preenchimento dinâmico por padrão quando você definir o argumento `tokenizer` dele. Nesse caso, você não precisa especificar um data collator explicitamente.
147
+
148
+ </Tip>
149
+ </pt>
150
+ <tf>
151
+ Para executar o fine-tuning de um modelo no TensorFlow, comece convertendo seu conjunto de dados para o formato `tf.data.Dataset` com [`to_tf_dataset`](https://huggingface.co/docs/datasets/package_reference/main_classes#datasets.Dataset.to_tf_dataset). Nessa execução você deverá especificar as entradas e rótulos (no parâmetro `columns`), se deseja embaralhar o conjunto de dados, o tamanho do batch e o data collator:
152
+
153
+ ```py
154
+ >>> tf_train_set = tokenized_imdb["train"].to_tf_dataset(
155
+ ... columns=["attention_mask", "input_ids", "label"],
156
+ ... shuffle=True,
157
+ ... batch_size=16,
158
+ ... collate_fn=data_collator,
159
+ ... )
160
+
161
+ >>> tf_validation_set = tokenized_imdb["test"].to_tf_dataset(
162
+ ... columns=["attention_mask", "input_ids", "label"],
163
+ ... shuffle=False,
164
+ ... batch_size=16,
165
+ ... collate_fn=data_collator,
166
+ ... )
167
+ ```
168
+
169
+ <Tip>
170
+
171
+ Se você não estiver familiarizado com o fine-tuning de um modelo com o Keras, dê uma olhada no tutorial básico [aqui](training#finetune-with-keras)!
172
+
173
+ </Tip>
174
+
175
+ Configure o otimizador e alguns hiperparâmetros de treinamento:
176
+
177
+ ```py
178
+ >>> from transformers import create_optimizer
179
+ >>> import tensorflow as tf
180
+
181
+ >>> batch_size = 16
182
+ >>> num_epochs = 5
183
+ >>> batches_per_epoch = len(tokenized_imdb["train"]) // batch_size
184
+ >>> total_train_steps = int(batches_per_epoch * num_epochs)
185
+ >>> optimizer, schedule = create_optimizer(init_lr=2e-5, num_warmup_steps=0, num_train_steps=total_train_steps)
186
+ ```
187
+
188
+ Carregue o DistilBERT com [`TFAutoModelForSequenceClassification`] junto com o número de rótulos esperados:
189
+
190
+ ```py
191
+ >>> from transformers import TFAutoModelForSequenceClassification
192
+
193
+ >>> model = TFAutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased", num_labels=2)
194
+ ```
195
+
196
+ Configure o modelo para treinamento com o método [`compile`](https://keras.io/api/models/model_training_apis/#compile-method):
197
+
198
+ ```py
199
+ >>> import tensorflow as tf
200
+
201
+ >>> model.compile(optimizer=optimizer)
202
+ ```
203
+
204
+ Chame o método [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) para executar o fine-tuning do modelo:
205
+
206
+ ```py
207
+ >>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3)
208
+ ```
209
+ </tf>
210
+ </frameworkcontent>
211
+
212
+ <Tip>
213
+
214
+ Para obter um exemplo mais aprofundado de como executar o fine-tuning de um modelo para classificação de texto, dê uma olhada nesse [notebook utilizando PyTorch](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb) ou nesse [notebook utilizando TensorFlow](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb).
215
+
216
+ </Tip>
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/tasks/token_classification.md ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # Classificação de tokens
18
+
19
+ <Youtube id="wVHdVlPScxA"/>
20
+
21
+ A classificação de tokens atribui um rótulo a tokens individuais em uma frase. Uma das tarefas de classificação de tokens mais comuns é o Reconhecimento de Entidade Nomeada, também chamada de NER (sigla em inglês para Named Entity Recognition). O NER tenta encontrar um rótulo para cada entidade em uma frase, como uma pessoa, local ou organização.
22
+
23
+ Este guia mostrará como realizar o fine-tuning do [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased) no conjunto de dados [WNUT 17](https://huggingface.co/datasets/wnut_17) para detectar novas entidades.
24
+
25
+ <Tip>
26
+
27
+ Consulte a [página de tarefas de classificação de tokens](https://huggingface.co/tasks/token-classification) para obter mais informações sobre outras formas de classificação de tokens e seus modelos, conjuntos de dados e métricas associadas.
28
+
29
+ </Tip>
30
+
31
+ ## Carregando o conjunto de dados WNUT 17
32
+
33
+ Carregue o conjunto de dados WNUT 17 da biblioteca 🤗 Datasets:
34
+
35
+ ```py
36
+ >>> from datasets import load_dataset
37
+
38
+ >>> wnut = load_dataset("wnut_17")
39
+ ```
40
+
41
+ E dê uma olhada em um exemplo:
42
+
43
+ ```py
44
+ >>> wnut["train"][0]
45
+ {'id': '0',
46
+ 'ner_tags': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0],
47
+ 'tokens': ['@paulwalk', 'It', "'s", 'the', 'view', 'from', 'where', 'I', "'m", 'living', 'for', 'two', 'weeks', '.', 'Empire', 'State', 'Building', '=', 'ESB', '.', 'Pretty', 'bad', 'storm', 'here', 'last', 'evening', '.']
48
+ }
49
+ ```
50
+
51
+ Cada número em `ner_tags` representa uma entidade. Converta o número em um rótulo para obter mais informações:
52
+
53
+ ```py
54
+ >>> label_list = wnut["train"].features[f"ner_tags"].feature.names
55
+ >>> label_list
56
+ [
57
+ "O",
58
+ "B-corporation",
59
+ "I-corporation",
60
+ "B-creative-work",
61
+ "I-creative-work",
62
+ "B-group",
63
+ "I-group",
64
+ "B-location",
65
+ "I-location",
66
+ "B-person",
67
+ "I-person",
68
+ "B-product",
69
+ "I-product",
70
+ ]
71
+ ```
72
+
73
+ O `ner_tag` descreve uma entidade, como uma organização, local ou pessoa. A letra que prefixa cada `ner_tag` indica a posição do token da entidade:
74
+
75
+ - `B-` indica o início de uma entidade.
76
+ - `I-` indica que um token está contido dentro da mesma entidade (por exemplo, o token `State` pode fazer parte de uma entidade como `Empire State Building`).
77
+ - `0` indica que o token não corresponde a nenhuma entidade.
78
+
79
+ ## Pré-processamento
80
+
81
+ <Youtube id="iY2AZYdZAr0"/>
82
+
83
+ Carregue o tokenizer do DistilBERT para processar os `tokens`:
84
+
85
+ ```py
86
+ >>> from transformers import AutoTokenizer
87
+
88
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
89
+ ```
90
+
91
+ Como a entrada já foi dividida em palavras, defina `is_split_into_words=True` para tokenizar as palavras em subpalavras:
92
+
93
+ ```py
94
+ >>> tokenized_input = tokenizer(example["tokens"], is_split_into_words=True)
95
+ >>> tokens = tokenizer.convert_ids_to_tokens(tokenized_input["input_ids"])
96
+ >>> tokens
97
+ ['[CLS]', '@', 'paul', '##walk', 'it', "'", 's', 'the', 'view', 'from', 'where', 'i', "'", 'm', 'living', 'for', 'two', 'weeks', '.', 'empire', 'state', 'building', '=', 'es', '##b', '.', 'pretty', 'bad', 'storm', 'here', 'last', 'evening', '.', '[SEP]']
98
+ ```
99
+
100
+ Ao adicionar os tokens especiais `[CLS]` e `[SEP]` e a tokenização de subpalavras uma incompatibilidade é gerada entre a entrada e os rótulos. Uma única palavra correspondente a um único rótulo pode ser dividida em duas subpalavras. Você precisará realinhar os tokens e os rótulos da seguinte forma:
101
+
102
+ 1. Mapeie todos os tokens para a palavra correspondente com o método [`word_ids`](https://huggingface.co/docs/tokenizers/python/latest/api/reference.html#tokenizers.Encoding.word_ids).
103
+ 2. Atribuindo o rótulo `-100` aos tokens especiais `[CLS]` e `[SEP]` para que a função de loss do PyTorch ignore eles.
104
+ 3. Rotular apenas o primeiro token de uma determinada palavra. Atribuindo `-100` a outros subtokens da mesma palavra.
105
+
106
+ Aqui está como você pode criar uma função para realinhar os tokens e rótulos e truncar sequências para não serem maiores que o comprimento máximo de entrada do DistilBERT:
107
+
108
+ ```py
109
+ >>> def tokenize_and_align_labels(examples):
110
+ ... tokenized_inputs = tokenizer(examples["tokens"], truncation=True, is_split_into_words=True)
111
+
112
+ ... labels = []
113
+ ... for i, label in enumerate(examples[f"ner_tags"]):
114
+ ... word_ids = tokenized_inputs.word_ids(batch_index=i) # Map tokens to their respective word.
115
+ ... previous_word_idx = None
116
+ ... label_ids = []
117
+ ... for word_idx in word_ids: # Set the special tokens to -100.
118
+ ... if word_idx is None:
119
+ ... label_ids.append(-100)
120
+ ... elif word_idx != previous_word_idx: # Only label the first token of a given word.
121
+ ... label_ids.append(label[word_idx])
122
+ ... else:
123
+ ... label_ids.append(-100)
124
+ ... previous_word_idx = word_idx
125
+ ... labels.append(label_ids)
126
+
127
+ ... tokenized_inputs["labels"] = labels
128
+ ... return tokenized_inputs
129
+ ```
130
+
131
+ Use a função [`map`](https://huggingface.co/docs/datasets/process#map) do 🤗 Datasets para tokenizar e alinhar os rótulos em todo o conjunto de dados. Você pode acelerar a função `map` configurando `batched=True` para processar vários elementos do conjunto de dados de uma só vez:
132
+
133
+ ```py
134
+ >>> tokenized_wnut = wnut.map(tokenize_and_align_labels, batched=True)
135
+ ```
136
+
137
+ Use o [`DataCollatorForTokenClassification`] para criar um batch de exemplos. Ele também *preencherá dinamicamente* seu texto e rótulos para o comprimento do elemento mais longo em seu batch, para que tenham um comprimento uniforme. Embora seja possível preencher seu texto na função `tokenizer` configurando `padding=True`, o preenchimento dinâmico é mais eficiente.
138
+
139
+ <frameworkcontent>
140
+ <pt>
141
+ ```py
142
+ >>> from transformers import DataCollatorForTokenClassification
143
+
144
+ >>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)
145
+ ```
146
+ </pt>
147
+ <tf>
148
+ ```py
149
+ >>> from transformers import DataCollatorForTokenClassification
150
+
151
+ >>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer, return_tensors="tf")
152
+ ```
153
+ </tf>
154
+ </frameworkcontent>
155
+
156
+ ## Treinamento
157
+
158
+ <frameworkcontent>
159
+ <pt>
160
+ Carregue o DistilBERT com o [`AutoModelForTokenClassification`] junto com o número de rótulos esperados:
161
+
162
+ ```py
163
+ >>> from transformers import AutoModelForTokenClassification, TrainingArguments, Trainer
164
+
165
+ >>> model = AutoModelForTokenClassification.from_pretrained("distilbert/distilbert-base-uncased", num_labels=14)
166
+ ```
167
+
168
+ <Tip>
169
+
170
+ Se você não estiver familiarizado com o fine-tuning de um modelo com o [`Trainer`], dê uma olhada no tutorial básico [aqui](../training#finetune-with-trainer)!
171
+
172
+ </Tip>
173
+
174
+ Nesse ponto, restam apenas três passos:
175
+
176
+ 1. Definir seus hiperparâmetros de treinamento em [`TrainingArguments`].
177
+ 2. Passar os argumentos de treinamento para o [`Trainer`] junto com o modelo, conjunto de dados, tokenizador e o data collator.
178
+ 3. Chamar a função [`~Trainer.train`] para executar o fine-tuning do seu modelo.
179
+
180
+ ```py
181
+ >>> training_args = TrainingArguments(
182
+ ... output_dir="./results",
183
+ ... eval_strategy="epoch",
184
+ ... learning_rate=2e-5,
185
+ ... per_device_train_batch_size=16,
186
+ ... per_device_eval_batch_size=16,
187
+ ... num_train_epochs=3,
188
+ ... weight_decay=0.01,
189
+ ... )
190
+
191
+ >>> trainer = Trainer(
192
+ ... model=model,
193
+ ... args=training_args,
194
+ ... train_dataset=tokenized_wnut["train"],
195
+ ... eval_dataset=tokenized_wnut["test"],
196
+ ... processing_class=tokenizer,
197
+ ... data_collator=data_collator,
198
+ ... )
199
+
200
+ >>> trainer.train()
201
+ ```
202
+ </pt>
203
+ <tf>
204
+ Para executar o fine-tuning de um modelo no TensorFlow, comece convertendo seu conjunto de dados para o formato `tf.data.Dataset` com [`to_tf_dataset`](https://huggingface.co/docs/datasets/package_reference/main_classes#datasets.Dataset.to_tf_dataset). Nessa execução você deverá especificar as entradas e rótulos (no parâmetro `columns`), se deseja embaralhar o conjunto de dados, o tamanho do batch e o data collator:
205
+
206
+ ```py
207
+ >>> tf_train_set = tokenized_wnut["train"].to_tf_dataset(
208
+ ... columns=["attention_mask", "input_ids", "labels"],
209
+ ... shuffle=True,
210
+ ... batch_size=16,
211
+ ... collate_fn=data_collator,
212
+ ... )
213
+
214
+ >>> tf_validation_set = tokenized_wnut["validation"].to_tf_dataset(
215
+ ... columns=["attention_mask", "input_ids", "labels"],
216
+ ... shuffle=False,
217
+ ... batch_size=16,
218
+ ... collate_fn=data_collator,
219
+ ... )
220
+ ```
221
+
222
+ <Tip>
223
+
224
+ Se você não estiver familiarizado com o fine-tuning de um modelo com o Keras, dê uma olhada no tutorial básico [aqui](training#finetune-with-keras)!
225
+
226
+ </Tip>
227
+
228
+ Configure o otimizador e alguns hiperparâmetros de treinamento:
229
+
230
+ ```py
231
+ >>> from transformers import create_optimizer
232
+
233
+ >>> batch_size = 16
234
+ >>> num_train_epochs = 3
235
+ >>> num_train_steps = (len(tokenized_wnut["train"]) // batch_size) * num_train_epochs
236
+ >>> optimizer, lr_schedule = create_optimizer(
237
+ ... init_lr=2e-5,
238
+ ... num_train_steps=num_train_steps,
239
+ ... weight_decay_rate=0.01,
240
+ ... num_warmup_steps=0,
241
+ ... )
242
+ ```
243
+
244
+ Carregue o DistilBERT com o [`TFAutoModelForTokenClassification`] junto com o número de rótulos esperados:
245
+
246
+ ```py
247
+ >>> from transformers import TFAutoModelForTokenClassification
248
+
249
+ >>> model = TFAutoModelForTokenClassification.from_pretrained("distilbert/distilbert-base-uncased", num_labels=2)
250
+ ```
251
+
252
+ Configure o modelo para treinamento com o método [`compile`](https://keras.io/api/models/model_training_apis/#compile-method):
253
+
254
+ ```py
255
+ >>> import tensorflow as tf
256
+
257
+ >>> model.compile(optimizer=optimizer)
258
+ ```
259
+
260
+ Chame o método [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) para executar o fine-tuning do modelo:
261
+
262
+ ```py
263
+ >>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3)
264
+ ```
265
+ </tf>
266
+ </frameworkcontent>
267
+
268
+ <Tip>
269
+
270
+ Para obter um exemplo mais aprofundado de como executar o fine-tuning de um modelo para classificação de tokens, dê uma olhada nesse [notebook utilizando PyTorch](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb) ou nesse [notebook utilizando TensorFlow](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb).
271
+
272
+ </Tip>
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/pt/training.md ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # Fine-tuning de um modelo pré-treinado
18
+
19
+ [[open-in-colab]]
20
+
21
+ O uso de um modelo pré-treinado tem importantes vantagens. Redução do custo computacional, a pegada de carbono, e te
22
+ permite utilizar modelos de última geração sem ter que treinar um novo desde o início.
23
+ O 🤗 Transformers proporciona acesso a milhares de modelos pré-treinados numa ampla gama de tarefas.
24
+ Quando utilizar um modelo pré-treinado, treine-o com um dataset específico para a sua tarefa.
25
+ Isto é chamado de fine-tuning, uma técnica de treinamento incrivelmente poderosa. Neste tutorial faremos o fine-tuning
26
+ de um modelo pré-treinado com um framework de Deep Learning da sua escolha:
27
+
28
+ * Fine-tuning de um modelo pré-treinado com o 🤗 Transformers [`Trainer`].
29
+ * Fine-tuning de um modelo pré-treinado no TensorFlow com o Keras.
30
+ * Fine-tuning de um modelo pré-treinado em PyTorch nativo.
31
+
32
+ <a id='data-processing'></a>
33
+
34
+ ## Preparando um dataset
35
+
36
+ <Youtube id="_BZearw7f0w"/>
37
+
38
+ Antes de aplicar o fine-tuning a um modelo pré-treinado, baixe um dataset e prepare-o para o treinamento.
39
+ O tutorial anterior ensinará a processar os dados para o treinamento, e então poderá ter a oportunidade de testar
40
+ esse novo conhecimento em algo prático.
41
+
42
+ Comece carregando o dataset [Yelp Reviews](https://huggingface.co/datasets/yelp_review_full):
43
+
44
+ ```py
45
+ >>> from datasets import load_dataset
46
+
47
+ >>> dataset = load_dataset("yelp_review_full")
48
+ >>> dataset[100]
49
+ {'label': 0,
50
+ 'text': 'My expectations for McDonalds are t rarely high. But for one to still fail so spectacularly...that takes something special!\\nThe cashier took my friends\'s order, then promptly ignored me. I had to force myself in front of a cashier who opened his register to wait on the person BEHIND me. I waited over five minutes for a gigantic order that included precisely one kid\'s meal. After watching two people who ordered after me be handed their food, I asked where mine was. The manager started yelling at the cashiers for \\"serving off their orders\\" when they didn\'t have their food. But neither cashier was anywhere near those controls, and the manager was the one serving food to customers and clearing the boards.\\nThe manager was rude when giving me my order. She didn\'t make sure that I had everything ON MY RECEIPT, and never even had the decency to apologize that I felt I was getting poor service.\\nI\'ve eaten at various McDonalds restaurants for over 30 years. I\'ve worked at more than one location. I expect bad days, bad moods, and the occasional mistake. But I have yet to have a decent experience at this store. It will remain a place I avoid unless someone in my party needs to avoid illness from low blood sugar. Perhaps I should go back to the racially biased service of Steak n Shake instead!'}
51
+ ```
52
+
53
+ Como já sabe, é necessário ter um tokenizador para processar o texto e incluir uma estratégia de padding e truncamento,
54
+ para manejar qualquer tamanho varíavel de sequência. Para processar o seu dataset em apenas um passo, utilize o método de
55
+ 🤗 Datasets [`map`](https://huggingface.co/docs/datasets/process#map) para aplicar uma função de preprocessamento sobre
56
+ todo o dataset.
57
+
58
+ ```py
59
+ >>> from transformers import AutoTokenizer
60
+
61
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
62
+
63
+
64
+ >>> def tokenize_function(examples):
65
+ ... return tokenizer(examples["text"], padding="max_length", truncation=True)
66
+
67
+
68
+ >>> tokenized_datasets = dataset.map(tokenize_function, batched=True)
69
+ ```
70
+
71
+ Se desejar, é possível criar um subconjunto menor do dataset completo para aplicar o fine-tuning e assim reduzir o tempo necessário.
72
+
73
+ ```py
74
+ >>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
75
+ >>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
76
+ ```
77
+
78
+ <a id='trainer'></a>
79
+
80
+ ## Fine-tuning com o `Trainer`
81
+
82
+ <Youtube id="nvBXf7s7vTI"/>
83
+
84
+ O 🤗 Transformers proporciona uma classe [`Trainer`] otimizada para o treinamento de modelos de 🤗 Transformers,
85
+ facilitando os primeiros passos do treinamento sem a necessidade de escrever manualmente o seu próprio ciclo.
86
+ A API do [`Trainer`] suporta um grande conjunto de opções de treinamento e funcionalidades, como o logging,
87
+ o gradient accumulation e o mixed precision.
88
+
89
+ Comece carregando seu modelo e especifique o número de labels de previsão.
90
+ A partir do [Card Dataset](https://huggingface.co/datasets/yelp_review_full#data-fields) do Yelp Reveiw, que ja
91
+ sabemos ter 5 labels usamos o seguinte código:
92
+
93
+ ```py
94
+ >>> from transformers import AutoModelForSequenceClassification
95
+
96
+ >>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased", num_labels=5)
97
+ ```
98
+
99
+ <Tip>
100
+
101
+ Você verá um alerta sobre alguns pesos pré-treinados que não estão sendo utilizados e que alguns pesos estão
102
+ sendo inicializados aleatoriamente. Não se preocupe, essa mensagem é completamente normal.
103
+ O header/cabeçário pré-treinado do modelo BERT é descartado e substitui-se por um header de classificação
104
+ inicializado aleatoriamente. Assim, pode aplicar o fine-tuning a este novo header do modelo em sua tarefa
105
+ de classificação de sequências fazendo um transfer learning do modelo pré-treinado.
106
+
107
+ </Tip>
108
+
109
+ ### Hiperparâmetros de treinamento
110
+
111
+ Em seguida, crie uma classe [`TrainingArguments`] que contenha todos os hiperparâmetros que possam ser ajustados, assim
112
+ como os indicadores para ativar as diferentes opções de treinamento. Para este tutorial, você pode começar o treinamento
113
+ usando os [hiperparámetros](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments) padrão,
114
+ porém, sinta-se livre para experimentar com eles e encontrar uma configuração ótima.
115
+
116
+ Especifique onde salvar os checkpoints do treinamento:
117
+
118
+ ```py
119
+ >>> from transformers import TrainingArguments
120
+
121
+ >>> training_args = TrainingArguments(output_dir="test_trainer")
122
+ ```
123
+
124
+ ### Métricas
125
+
126
+ O [`Trainer`] não avalia automaticamente o rendimento do modelo durante o treinamento. Será necessário passar ao
127
+ [`Trainer`] uma função para calcular e fazer um diagnóstico sobre as métricas. A biblioteca 🤗 Datasets proporciona
128
+ uma função de [`accuracy`](https://huggingface.co/metrics/accuracy) simples que pode ser carregada com a função
129
+ `load_metric` (ver este [tutorial](https://huggingface.co/docs/datasets/metrics) para mais informações):
130
+
131
+ ```py
132
+ >>> import numpy as np
133
+ >>> from datasets import load_metric
134
+
135
+ >>> metric = load_metric("accuracy")
136
+ ```
137
+
138
+ Defina a função `compute` dentro de `metric` para calcular a precisão das suas predições.
139
+ Antes de passar as suas predições ao `compute`, é necessário converter as predições à logits (lembre-se que
140
+ todos os modelos de 🤗 Transformers retornam logits).
141
+
142
+ ```py
143
+ >>> def compute_metrics(eval_pred):
144
+ ... logits, labels = eval_pred
145
+ ... predictions = np.argmax(logits, axis=-1)
146
+ ... return metric.compute(predictions=predictions, references=labels)
147
+ ```
148
+
149
+ Se quiser controlar as suas métricas de avaliação durante o fine-tuning, especifique o parâmetro `eval_strategy`
150
+ nos seus argumentos de treinamento para que o modelo considere a métrica de avaliação ao final de cada época:
151
+
152
+ ```py
153
+ >>> from transformers import TrainingArguments
154
+
155
+ >>> training_args = TrainingArguments(output_dir="test_trainer", eval_strategy="epoch")
156
+ ```
157
+
158
+ ### Trainer
159
+
160
+ Crie um objeto [`Trainer`] com o seu modelo, argumentos de treinamento, conjuntos de dados de treinamento e de teste, e a sua função de avaliação:
161
+
162
+ ```py
163
+ >>> trainer = Trainer(
164
+ ... model=model,
165
+ ... args=training_args,
166
+ ... train_dataset=small_train_dataset,
167
+ ... eval_dataset=small_eval_dataset,
168
+ ... compute_metrics=compute_metrics,
169
+ ... )
170
+ ```
171
+
172
+ Em seguida, aplique o fine-tuning a seu modelo chamado [`~transformers.Trainer.train`]:
173
+
174
+ ```py
175
+ >>> trainer.train()
176
+ ```
177
+
178
+ <a id='keras'></a>
179
+
180
+ ## Fine-tuning com Keras
181
+
182
+ <Youtube id="rnTGBy2ax1c"/>
183
+
184
+ Os modelos de 🤗 Transformers também permitem realizar o treinamento com o TensorFlow com a API do Keras.
185
+ Contudo, será necessário fazer algumas mudanças antes de realizar o fine-tuning.
186
+
187
+ ### Conversão do dataset ao formato do TensorFlow
188
+
189
+ O [`DefaultDataCollator`] junta os tensores em um batch para que o modelo possa ser treinado em cima deles.
190
+ Assegure-se de especificar os `return_tensors` para retornar os tensores do TensorFlow:
191
+
192
+ ```py
193
+ >>> from transformers import DefaultDataCollator
194
+
195
+ >>> data_collator = DefaultDataCollator(return_tensors="tf")
196
+ ```
197
+
198
+ <Tip>
199
+
200
+ O [`Trainer`] utiliza [`DataCollatorWithPadding`] por padrão, então você não precisa especificar explicitamente um
201
+ colador de dados (data collator).
202
+
203
+ </Tip>
204
+
205
+ Em seguida, converta os datasets tokenizados em datasets do TensorFlow com o método
206
+ [`to_tf_dataset`](https://huggingface.co/docs/datasets/package_reference/main_classes#datasets.Dataset.to_tf_dataset).
207
+ Especifique suas entradas em `columns` e seu rótulo em `label_cols`:
208
+
209
+ ```py
210
+ >>> tf_train_dataset = small_train_dataset.to_tf_dataset(
211
+ ... columns=["attention_mask", "input_ids", "token_type_ids"],
212
+ ... label_cols="labels",
213
+ ... shuffle=True,
214
+ ... collate_fn=data_collator,
215
+ ... batch_size=8,
216
+ ... )
217
+
218
+ >>> tf_validation_dataset = small_eval_dataset.to_tf_dataset(
219
+ ... columns=["attention_mask", "input_ids", "token_type_ids"],
220
+ ... label_cols="labels",
221
+ ... shuffle=False,
222
+ ... collate_fn=data_collator,
223
+ ... batch_size=8,
224
+ ... )
225
+ ```
226
+
227
+ ### Compilação e ajustes
228
+
229
+ Carregue um modelo do TensorFlow com o número esperado de rótulos:
230
+
231
+ ```py
232
+ >>> import tensorflow as tf
233
+ >>> from transformers import TFAutoModelForSequenceClassification
234
+
235
+ >>> model = TFAutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased", num_labels=5)
236
+ ```
237
+
238
+ A seguir, compile e ajuste o fine-tuning a seu modelo com [`fit`](https://keras.io/api/models/model_training_apis/) como
239
+ faria com qualquer outro modelo do Keras:
240
+
241
+ ```py
242
+ >>> model.compile(
243
+ ... optimizer=tf.keras.optimizers.Adam(learning_rate=5e-5),
244
+ ... loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
245
+ ... metrics=tf.metrics.SparseCategoricalAccuracy(),
246
+ ... )
247
+
248
+ >>> model.fit(tf_train_dataset, validation_data=tf_validation_dataset, epochs=3)
249
+ ```
250
+
251
+ <a id='pytorch_native'></a>
252
+
253
+ ## Fine-tune em PyTorch nativo
254
+
255
+ <Youtube id="Dh9CL8fyG80"/>
256
+
257
+ O [`Trainer`] se encarrega do ciclo de treinamento e permite aplicar o fine-tuning a um modelo em uma linha de código apenas.
258
+ Para os usuários que preferirem escrever o seu próprio ciclo de treinamento, também é possível aplicar o fine-tuning a um
259
+ modelo de 🤗 Transformers em PyTorch nativo.
260
+
261
+ Neste momento, talvez ocorra a necessidade de reinicar seu notebook ou executar a seguinte linha de código para liberar
262
+ memória:
263
+
264
+ ```py
265
+ del model
266
+ del pytorch_model
267
+ del trainer
268
+ torch.cuda.empty_cache()
269
+ ```
270
+
271
+ Em sequência, faremos um post-processing manual do `tokenized_dataset` e assim prepará-lo para o treinamento.
272
+
273
+ 1. Apague a coluna de `text` porque o modelo não aceita texto cru como entrada:
274
+
275
+ ```py
276
+ >>> tokenized_datasets = tokenized_datasets.remove_columns(["text"])
277
+ ```
278
+
279
+ 2. Troque o nome da coluna `label` para `labels`, pois o modelo espera um argumento de mesmo nome:
280
+
281
+ ```py
282
+ >>> tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
283
+ ```
284
+
285
+ 3. Defina o formato do dataset para retornar tensores do PyTorch no lugar de listas:
286
+
287
+ ```py
288
+ >>> tokenized_datasets.set_format("torch")
289
+ ```
290
+
291
+ Em sequência, crie um subconjunto menor do dataset, como foi mostrado anteriormente, para acelerá-lo o fine-tuning.
292
+
293
+ ```py
294
+ >>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
295
+ >>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
296
+ ```
297
+
298
+ ### DataLoader
299
+
300
+ Crie um `DataLoader` para os seus datasets de treinamento e de teste para poder iterar sobre batches de dados:
301
+
302
+ ```py
303
+ >>> from torch.utils.data import DataLoader
304
+
305
+ >>> train_dataloader = DataLoader(small_train_dataset, shuffle=True, batch_size=8)
306
+ >>> eval_dataloader = DataLoader(small_eval_dataset, batch_size=8)
307
+ ```
308
+
309
+ Carregue seu modelo com o número de labels esperados:
310
+
311
+ ```py
312
+ >>> from transformers import AutoModelForSequenceClassification
313
+
314
+ >>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased", num_labels=5)
315
+ ```
316
+
317
+ ### Otimização e configuração do Learning Rate
318
+
319
+ Crie um otimizador e um learning rate para aplicar o fine-tuning ao modelo.
320
+ Iremos utilizar o otimizador [`AdamW`](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html) do PyTorch:
321
+
322
+ ```py
323
+ >>> from torch.optim import AdamW
324
+
325
+ >>> optimizer = AdamW(model.parameters(), lr=5e-5)
326
+ ```
327
+
328
+ Defina o learning rate do [`Trainer`]:
329
+
330
+ ```py
331
+ >>> from transformers import get_scheduler
332
+
333
+ >>> num_epochs = 3
334
+ >>> num_training_steps = num_epochs * len(train_dataloader)
335
+ >>> lr_scheduler = get_scheduler(
336
+ ... name="linear", optimizer=optimizer, num_warmup_steps=0, num_training_steps=num_training_steps
337
+ ... )
338
+ ```
339
+
340
+ Por último, especifique o `device` do ambiente para utilizar uma GPU se tiver acesso à alguma. Caso contrário, o treinamento
341
+ em uma CPU pode acabar levando várias horas em vez de minutos.
342
+
343
+ ```py
344
+ >>> import torch
345
+
346
+ >>> device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
347
+ >>> model.to(device)
348
+ ```
349
+
350
+ <Tip>
351
+
352
+ Se necessário, você pode obter o acesso gratuito a uma GPU na núvem por meio de um notebook no
353
+ [Colaboratory](https://colab.research.google.com/) ou [SageMaker StudioLab](https://studiolab.sagemaker.aws/)
354
+ se não tiver esse recurso de forma local.
355
+
356
+ </Tip>
357
+
358
+ Perfeito, agora estamos prontos para começar o treinamento! 🥳
359
+
360
+ ### Ciclo de treinamento
361
+
362
+ Para visualizar melhor o processo de treinamento, utilize a biblioteca [tqdm](https://tqdm.github.io/) para adicionar
363
+ uma barra de progresso sobre o número de passos percorridos no treinamento atual:
364
+
365
+ ```py
366
+ >>> from tqdm.auto import tqdm
367
+
368
+ >>> progress_bar = tqdm(range(num_training_steps))
369
+
370
+ >>> model.train()
371
+ >>> for epoch in range(num_epochs):
372
+ ... for batch in train_dataloader:
373
+ ... batch = {k: v.to(device) for k, v in batch.items()}
374
+ ... outputs = model(**batch)
375
+ ... loss = outputs.loss
376
+ ... loss.backward()
377
+
378
+ ... optimizer.step()
379
+ ... lr_scheduler.step()
380
+ ... optimizer.zero_grad()
381
+ ... progress_bar.update(1)
382
+ ```
383
+
384
+ ### Métricas
385
+
386
+ Da mesma forma que é necessário adicionar uma função de avaliação ao [`Trainer`], é necessário fazer o mesmo quando
387
+ escrevendo o próprio ciclo de treinamento. Contudo, em vez de calcular e retornar a métrica final de cada época,
388
+ você deverá adicionar todos os batches com [`add_batch`](https://huggingface.co/docs/datasets/package_reference/main_classes?highlight=add_batch#datasets.Metric.add_batch)
389
+ e calcular a métrica apenas no final.
390
+
391
+ ```py
392
+ >>> metric = load_metric("accuracy")
393
+ >>> model.eval()
394
+ >>> for batch in eval_dataloader:
395
+ ... batch = {k: v.to(device) for k, v in batch.items()}
396
+ ... with torch.no_grad():
397
+ ... outputs = model(**batch)
398
+
399
+ ... logits = outputs.logits
400
+ ... predictions = torch.argmax(logits, dim=-1)
401
+ ... metric.add_batch(predictions=predictions, references=batch["labels"])
402
+
403
+ >>> metric.compute()
404
+ ```
405
+
406
+ <a id='additional-resources'></a>
407
+
408
+ ## Recursos adicionais
409
+
410
+ Para mais exemplos de fine-tuning acesse:
411
+
412
+ - [🤗 Transformers Examples](https://github.com/huggingface/transformers/tree/main/examples) inclui scripts
413
+ para treinas tarefas comuns de NLP em PyTorch e TensorFlow.
414
+
415
+ - [🤗 Transformers Notebooks](notebooks) contém vários notebooks sobre como aplicar o fine-tuning a um modelo
416
+ para tarefas específicas no PyTorch e TensorFlow.
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/te/_toctree.yml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ - sections:
2
+ - local: index
3
+ title: 🤗 Transformers
4
+ - local: quicktour
5
+ title: త్వరిత పర్యటన
6
+ title: ప్రారంభించడానికి
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/te/index.md ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2020 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+ -->
15
+
16
+ [పైటోర్చ్](https://pytorch.org/), [టెన్సర్‌ఫ్లో](https://www.tensorflow.org/), మరియు [జాక్స్](https://jax.readthedocs.io/en/latest/) కోసం స్థితి-కలాన యంత్ర అభ్యాసం.
17
+
18
+ 🤗 ట్రాన్స్ఫార్మర్స్ అభివృద్ధిస్తున్నది API మరియు ఉపకరణాలు, పూర్వ-చేతన మోడల్లను సులభంగా డౌన్లోడ్ మరియు శిక్షణ చేయడానికి అవసరమైన సమయం, వనరులు, మరియు వస్తువులను నుంచి మోడల్ను శీర్షికం నుంచి ప్రశిక్షించడం వరకు దేవాయనం చేస్తుంది. ఈ మోడల్లు విభిన్న మోడాలిటీలలో సాధారణ పనులకు మద్దతు చేస్తాయి, వంటివి:
19
+
20
+ 📝 **ప్రాకృతిక భాష ప్రక్రియ**: వచన వర్గీకరణ, పేరుల యొక్క యెంటిటీ గుర్తువు, ప్రశ్న సంవాద, భాషా రచన, సంక్షేపణ, అనువాదం, అనేక ప్రకారాలు, మరియు వచన సృష్టి.<br>
21
+ 🖼️ **కంప్యూటర్ విషయం**: చిత్రం వర్గీకరణ, వస్త్రం గుర్తువు, మరియు విభజన.<br>
22
+ 🗣️ **ఆడియో**: స్వయంచలన ప్రసంగాన్ని గుర్తుచేసేందుకు, ఆడియో వర్గీకరణ.<br>
23
+ 🐙 **బహుమూలిక**: పట్టి ప్రశ్న సంవాద, ఆప్టికల్ సిఫర్ గుర్తువు, డాక్యుమెంట్లు స్క్యాన్ చేసినంతగా సమాచార పొందడం, వీడియో వర్గీకరణ, మరియు దృశ్య ప్రశ్న సంవాద.
24
+
25
+ 🤗 ట్రాన్స్ఫార్మర్స్ పైన మద్దతు చేస్తుంది పైన తొలగించడానికి పైన పైన పైన ప్రోగ్రామ్లో మోడల్ను శిక్షించండి, మరియు అన్ని ప్రాథమిక యొక్కడా ఇన్‌ఫరెన్స్ కోసం లోడ్ చేయండి. మో
26
+
27
+ డల్లు కూడా ప్రొడక్షన్ వాతావరణాలలో వాడుకోవడానికి ONNX మరియు TorchScript వంటి ఆకృతులకు ఎగుమతి చేయవచ్చు.
28
+
29
+ ఈరువులకు [హబ్](https://huggingface.co/models), [ఫోరం](https://discuss.huggingface.co/), లేదా [డిస్కార్డ్](https://discord.com/invite/JfAtkvEtRb) లో ఈ పెద్ద సముదాయంలో చేరండి!
30
+
31
+ ## మీరు హగ్గింగ్ ఫేస్ టీమ్ నుండి అనుకూల మద్దతు కోసం చూస్తున్నట్లయితే
32
+
33
+ <a target="_blank" href="https://huggingface.co/support">
34
+ <img alt="HuggingFace Expert Acceleration Program" src="https://cdn-media.huggingface.co/marketing/transformers/new-support-improved.png" style="width: 100%; max-width: 600px; border: 1px solid #eee; border-radius: 4px; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);">
35
+ </a>
36
+
37
+ ## విషయాలు
38
+
39
+ డాక్యుమెంటేషన్ ఐదు విభాగాలుగా నిర్వహించబడింది:
40
+
41
+ - **ప్రారంభించండి** లైబ్రరీ యొక్క శీఘ్ర పర్యటన మరియు రన్నింగ్ కోసం ఇన్‌స్టాలేషన్ సూచనలను అందిస్తుంది.
42
+ - **ట్యుటోరియల్స్** మీరు అనుభవశూన్యుడు అయితే ప్రారంభి��చడానికి గొప్ప ప్రదేశం. మీరు లైబ్రరీని ఉపయోగించడం ప్రారంభించడానికి అవసరమైన ప్రాథమిక నైపుణ్యాలను పొందడానికి ఈ విభాగం మీకు సహాయం చేస్తుంది.
43
+ - **హౌ-టు-గైడ్‌లు** లాంగ్వేజ్ మోడలింగ్ కోసం ప్రిట్రైన్డ్ మోడల్‌ని ఫైన్‌ట్యూన్ చేయడం లేదా కస్టమ్ మోడల్‌ను ఎలా వ్రాయాలి మరియు షేర్ చేయాలి వంటి నిర్దిష్ట లక్ష్యాన్ని ఎలా సాధించాలో మీకు చూపుతాయి.
44
+ - **కాన్సెప్చువల్ గైడ్స్** మోడల్‌లు, టాస్క్‌లు మరియు 🤗 ట్రాన్స్‌ఫార్మర్ల డిజైన్ ఫిలాసఫీ వెనుక ఉన్న అంతర్లీన భావనలు మరియు ఆలోచనల గురించి మరింత చర్చ మరియు వివరణను అందిస్తుంది.
45
+ - **API** అన్ని తరగతులు మరియు విధులను వివరిస్తుంది:
46
+
47
+ - **ప్రధాన తరగతులు** కాన్ఫిగరేషన్, మోడల్, టోకెనైజర్ మరియు పైప్‌లైన్ వంటి అత్యంత ముఖ్యమైన తరగతులను వివరిస్తుంది.
48
+ - **మోడల్స్** లైబ్రరీలో అమలు చేయబడిన ప్రతి మోడల్‌కు సంబంధించిన తరగతులు మరియు విధులను వివరిస్తుంది.
49
+ - **అంతర్గత సహాయకులు** అంతర్గతంగా ఉపయోగించే యుటిలిటీ క్లాస్‌లు మరియు ఫంక్షన్‌ల వివరాలు.
50
+
51
+ ## మద్దతు ఉన్న నమూనాలు మరియు ఫ్రేమ్‌వర్క్‌లు
52
+
53
+ దిగువన ఉన్న పట్టిక ఆ ప్రతి మోడల్‌కు పైథాన్ కలిగి ఉన్నా లైబ్రరీలో ప్రస్తుత మద్దతును సూచిస్తుంది
54
+ టోకెనైజర్ ("నెమ్మదిగా" అని పిలుస్తారు). Jax (ద్వారా
55
+ ఫ్లాక్స్), పైటార్చ్ మరియు/లేదా టెన్సర్‌ఫ్లో.
56
+
57
+ <!--This table is updated automatically from the auto modules with _make fix-copies_. Do not update manually!-->
58
+
59
+ | Model | PyTorch support | TensorFlow support | Flax Support |
60
+ |:------------------------------------------------------------------------:|:---------------:|:------------------:|:------------:|
61
+ | [ALBERT](model_doc/albert) | ✅ | ✅ | ✅ |
62
+ | [ALIGN](model_doc/align) | ✅ | ❌ | ❌ |
63
+ | [AltCLIP](model_doc/altclip) | ✅ | ❌ | ❌ |
64
+ | [Audio Spectrogram Transformer](model_doc/audio-spectrogram-transformer) | ✅ | ❌ | ❌ |
65
+ | [Autoformer](model_doc/autoformer) | ✅ | ❌ | ❌ |
66
+ | [Bark](model_doc/bark) | ✅ | ❌ | ❌ |
67
+ | [BART](model_doc/bart) | ✅ | ✅ | ✅ |
68
+ | [BARThez](model_doc/barthez) | ✅ | ✅ | ✅ |
69
+ | [BARTpho](model_doc/bartpho) | ✅ | ✅ | ✅ |
70
+ | [BEiT](model_doc/beit) | ✅ | ❌ | ✅ |
71
+ | [BERT](model_doc/bert) | ✅ | ✅ | ✅ |
72
+ | [Bert Generation](model_doc/bert-generation) | ✅ | ❌ | ❌ |
73
+ | [BertJapanese](model_doc/bert-japanese) | ✅ | ✅ | ✅ |
74
+ | [BERTweet](model_doc/bertweet) | ✅ | ✅ | ✅ |
75
+ | [BigBird](model_doc/big_bird) | ✅ | ❌ | ✅ |
76
+ | [BigBird-Pegasus](model_doc/bigbird_pegasus) | ✅ | ❌ | ❌ |
77
+ | [BioGpt](model_doc/biogpt) | ✅ | ❌ | ❌ |
78
+ | [BiT](model_doc/bit) | ✅ | ❌ | ❌ |
79
+ | [Blenderbot](model_doc/blenderbot) | ✅ | ✅ | ✅ |
80
+ | [BlenderbotSmall](model_doc/blenderbot-small) | ✅ | ✅ | ✅ |
81
+ | [BLIP](model_doc/blip) | ✅ | ✅ | ❌ |
82
+ | [BLIP-2](model_doc/blip-2) | ✅ | ❌ | ❌ |
83
+ | [BLOOM](model_doc/bloom) | ✅ | ❌ | ✅ |
84
+ | [BORT](model_doc/bort) | ✅ | ✅ | ✅ |
85
+ | [BridgeTower](model_doc/bridgetower) | ✅ | ❌ | ❌ |
86
+ | [BROS](model_doc/bros) | ✅ | ❌ | ❌ |
87
+ | [ByT5](model_doc/byt5) | ✅ | ✅ | ✅ |
88
+ | [CamemBERT](model_doc/camembert) | ✅ | ✅ | ❌ |
89
+ | [CANINE](model_doc/canine) | ✅ | ❌ | ❌ |
90
+ | [Chinese-CLIP](model_doc/chinese_clip) | ✅ | ❌ | ❌ |
91
+ | [CLAP](model_doc/clap) | ✅ | ❌ | ❌ |
92
+ | [CLIP](model_doc/clip) | ✅ | ✅ | ✅ |
93
+ | [CLIPSeg](model_doc/clipseg) | ✅ | ❌ | ❌ |
94
+ | [CodeGen](model_doc/codegen) | ✅ | ❌ | ❌ |
95
+ | [CodeLlama](model_doc/code_llama) | ✅ | ❌ | ❌ |
96
+ | [Conditional DETR](model_doc/conditional_detr) | ✅ | ❌ | ❌ |
97
+ | [ConvBERT](model_doc/convbert) | ✅ | ✅ | ❌ |
98
+ | [ConvNeXT](model_doc/convnext) | ✅ | ✅ | ❌ |
99
+ | [ConvNeXTV2](model_doc/convnextv2) | ✅ | ❌ | ❌ |
100
+ | [CPM](model_doc/cpm) | ✅ | ✅ | ✅ |
101
+ | [CPM-Ant](model_doc/cpmant) | ✅ | ❌ | ❌ |
102
+ | [CTRL](model_doc/ctrl) | ✅ | ✅ | ❌ |
103
+ | [CvT](model_doc/cvt) | ✅ | ✅ | ❌ |
104
+ | [Data2VecAudio](model_doc/data2vec) | ✅ | ❌ | ❌ |
105
+ | [Data2VecText](model_doc/data2vec) | ✅ | ❌ | ❌ |
106
+ | [Data2VecVision](model_doc/data2vec) | ✅ | ✅ | ❌ |
107
+ | [DeBERTa](model_doc/deberta) | ✅ | ✅ | ❌ |
108
+ | [DeBERTa-v2](model_doc/deberta-v2) | ✅ | ✅ | ❌ |
109
+ | [Decision Transformer](model_doc/decision_transformer) | ✅ | ❌ | ❌ |
110
+ | [Deformable DETR](model_doc/deformable_detr) | ✅ | ❌ | ❌ |
111
+ | [DeiT](model_doc/deit) | ✅ | ✅ | ❌ |
112
+ | [DePlot](model_doc/deplot) | ✅ | ❌ | ❌ |
113
+ | [DETA](model_doc/deta) | ✅ | ❌ | ❌ |
114
+ | [DETR](model_doc/detr) | ✅ | ❌ | ❌ |
115
+ | [DialoGPT](model_doc/dialogpt) | ✅ | ✅ | ✅ |
116
+ | [DiNAT](model_doc/dinat) | ✅ | ❌ | ❌ |
117
+ | [DINOv2](model_doc/dinov2) | ✅ | ❌ | ❌ |
118
+ | [DistilBERT](model_doc/distilbert) | ✅ | ✅ | ✅ |
119
+ | [DiT](model_doc/dit) | ✅ | ❌ | ✅ |
120
+ | [DonutSwin](model_doc/donut) | ✅ | ❌ | ❌ |
121
+ | [DPR](model_doc/dpr) | ✅ | ✅ | ❌ |
122
+ | [DPT](model_doc/dpt) | ✅ | ❌ | ❌ |
123
+ | [EfficientFormer](model_doc/efficientformer) | ✅ | ✅ | ❌ |
124
+ | [EfficientNet](model_doc/efficientnet) | ✅ | ❌ | ❌ |
125
+ | [ELECTRA](model_doc/electra) | ✅ | ✅ | ✅ |
126
+ | [EnCodec](model_doc/encodec) | ✅ | ❌ | ❌ |
127
+ | [Encoder decoder](model_doc/encoder-decoder) | ✅ | ✅ | ✅ |
128
+ | [ERNIE](model_doc/ernie) | ✅ | ❌ | ❌ |
129
+ | [ErnieM](model_doc/ernie_m) | ✅ | ❌ | ❌ |
130
+ | [ESM](model_doc/esm) | ✅ | ✅ | ❌ |
131
+ | [FairSeq Machine-Translation](model_doc/fsmt) | ✅ | ❌ | ❌ |
132
+ | [Falcon](model_doc/falcon) | ✅ | ❌ | ❌ |
133
+ | [FLAN-T5](model_doc/flan-t5) | ✅ | ✅ | ✅ |
134
+ | [FLAN-UL2](model_doc/flan-ul2) | ✅ | ✅ | ✅ |
135
+ | [FlauBERT](model_doc/flaubert) | ✅ | ✅ | ❌ |
136
+ | [FLAVA](model_doc/flava) | ✅ | ❌ | ❌ |
137
+ | [FNet](model_doc/fnet) | ✅ | ❌ | ❌ |
138
+ | [FocalNet](model_doc/focalnet) | ✅ | ❌ | ❌ |
139
+ | [Funnel Transformer](model_doc/funnel) | ✅ | ✅ | ❌ |
140
+ | [GIT](model_doc/git) | ✅ | ❌ | ❌ |
141
+ | [GLPN](model_doc/glpn) | ✅ | ❌ | ❌ |
142
+ | [GPT Neo](model_doc/gpt_neo) | ✅ | ❌ | ✅ |
143
+ | [GPT NeoX](model_doc/gpt_neox) | ✅ | ❌ | ❌ |
144
+ | [GPT NeoX Japanese](model_doc/gpt_neox_japanese) | ✅ | ❌ | ❌ |
145
+ | [GPT-J](model_doc/gptj) | ✅ | ✅ | ✅ |
146
+ | [GPT-Sw3](model_doc/gpt-sw3) | ✅ | ✅ | ✅ |
147
+ | [GPTBigCode](model_doc/gpt_bigcode) | ✅ | ❌ | ❌ |
148
+ | [GPTSAN-japanese](model_doc/gptsan-japanese) | ✅ | ❌ | ❌ |
149
+ | [Graphormer](model_doc/graphormer) | ✅ | ❌ | ❌ |
150
+ | [GroupViT](model_doc/groupvit) | ✅ | ✅ | ❌ |
151
+ | [HerBERT](model_doc/herbert) | ✅ | ✅ | ✅ |
152
+ | [Hubert](model_doc/hubert) | ✅ | ✅ | ❌ |
153
+ | [I-BERT](model_doc/ibert) | ✅ | ❌ | ❌ |
154
+ | [IDEFICS](model_doc/idefics) | ✅ | ❌ | ❌ |
155
+ | [ImageGPT](model_doc/imagegpt) | ✅ | ❌ | ❌ |
156
+ | [Informer](model_doc/informer) | ✅ | ❌ | ❌ |
157
+ | [InstructBLIP](model_doc/instructblip) | ✅ | ❌ | ❌ |
158
+ | [Jukebox](model_doc/jukebox) | ✅ | ❌ | ❌ |
159
+ | [LayoutLM](model_doc/layoutlm) | ✅ | ✅ | ❌ |
160
+ | [LayoutLMv2](model_doc/layoutlmv2) | ✅ | ❌ | ❌ |
161
+ | [LayoutLMv3](model_doc/layoutlmv3) | ✅ | ✅ | ❌ |
162
+ | [LayoutXLM](model_doc/layoutxlm) | ✅ | ❌ | ❌ |
163
+ | [LED](model_doc/led) | ✅ | ✅ | ❌ |
164
+ | [LeViT](model_doc/levit) | ✅ | ❌ | ❌ |
165
+ | [LiLT](model_doc/lilt) | ✅ | ❌ | ❌ |
166
+ | [LLaMA](model_doc/llama) | ✅ | ❌ | ❌ |
167
+ | [Llama2](model_doc/llama2) | ✅ | ❌ | ❌ |
168
+ | [Longformer](model_doc/longformer) | ✅ | ✅ | ❌ |
169
+ | [LongT5](model_doc/longt5) | ✅ | ❌ | ✅ |
170
+ | [LUKE](model_doc/luke) | ✅ | ❌ | ❌ |
171
+ | [LXMERT](model_doc/lxmert) | ✅ | ✅ | ❌ |
172
+ | [M-CTC-T](model_doc/mctct) | ✅ | ❌ | ❌ |
173
+ | [M2M100](model_doc/m2m_100) | ✅ | ❌ | ❌ |
174
+ | [Marian](model_doc/marian) | ✅ | ✅ | ✅ |
175
+ | [MarkupLM](model_doc/markuplm) | ✅ | ❌ | ❌ |
176
+ | [Mask2Former](model_doc/mask2former) | ✅ | ❌ | ❌ |
177
+ | [MaskFormer](model_doc/maskformer) | ✅ | ❌ | ❌ |
178
+ | [MatCha](model_doc/matcha) | ✅ | ❌ | ❌ |
179
+ | [mBART](model_doc/mbart) | ✅ | ✅ | ✅ |
180
+ | [mBART-50](model_doc/mbart50) | ✅ | ✅ | ✅ |
181
+ | [MEGA](model_doc/mega) | ✅ | ❌ | ❌ |
182
+ | [Megatron-BERT](model_doc/megatron-bert) | ✅ | ❌ | ❌ |
183
+ | [Megatron-GPT2](model_doc/megatron_gpt2) | ✅ | ✅ | ✅ |
184
+ | [MGP-STR](model_doc/mgp-str) | ✅ | ❌ | ❌ |
185
+ | [Mistral](model_doc/mistral) | ✅ | ❌ | ❌ |
186
+ | [mLUKE](model_doc/mluke) | ✅ | ❌ | ❌ |
187
+ | [MMS](model_doc/mms) | ✅ | ✅ | ✅ |
188
+ | [MobileBERT](model_doc/mobilebert) | ✅ | ✅ | ❌ |
189
+ | [MobileNetV1](model_doc/mobilenet_v1) | ✅ | ❌ | ❌ |
190
+ | [MobileNetV2](model_doc/mobilenet_v2) | ✅ | ❌ | ❌ |
191
+ | [MobileViT](model_doc/mobilevit) | ✅ | ✅ | ❌ |
192
+ | [MobileViTV2](model_doc/mobilevitv2) | ✅ | ❌ | ❌ |
193
+ | [MPNet](model_doc/mpnet) | ✅ | ✅ | ❌ |
194
+ | [MPT](model_doc/mpt) | ✅ | ❌ | ❌ |
195
+ | [MRA](model_doc/mra) | ✅ | ❌ | ❌ |
196
+ | [MT5](model_doc/mt5) | ✅ | ✅ | ✅ |
197
+ | [MusicGen](model_doc/musicgen) | ✅ | ❌ | ❌ |
198
+ | [MVP](model_doc/mvp) | ✅ | ❌ | ❌ |
199
+ | [NAT](model_doc/nat) | ✅ | ❌ | ❌ |
200
+ | [Nezha](model_doc/nezha) | ✅ | ❌ | ❌ |
201
+ | [NLLB](model_doc/nllb) | ✅ | ❌ | ❌ |
202
+ | [NLLB-MOE](model_doc/nllb-moe) | ✅ | ❌ | ❌ |
203
+ | [Nougat](model_doc/nougat) | ✅ | ✅ | ✅ |
204
+ | [Nyströmformer](model_doc/nystromformer) | ✅ | ❌ | ❌ |
205
+ | [OneFormer](model_doc/oneformer) | ✅ | ❌ | ❌ |
206
+ | [OpenAI GPT](model_doc/openai-gpt) | ✅ | ✅ | ❌ |
207
+ | [OpenAI GPT-2](model_doc/gpt2) | ✅ | ✅ | ✅ |
208
+ | [OpenLlama](model_doc/open-llama) | ✅ | ❌ | ❌ |
209
+ | [OPT](model_doc/opt) | ✅ | ✅ | ✅ |
210
+ | [OWL-ViT](model_doc/owlvit) | ✅ | ❌ | ❌ |
211
+ | [Pegasus](model_doc/pegasus) | ✅ | ✅ | ✅ |
212
+ | [PEGASUS-X](model_doc/pegasus_x) | ✅ | ❌ | ❌ |
213
+ | [Perceiver](model_doc/perceiver) | ✅ | ❌ | ❌ |
214
+ | [Persimmon](model_doc/persimmon) | ✅ | ❌ | ❌ |
215
+ | [PhoBERT](model_doc/phobert) | ✅ | ✅ | ✅ |
216
+ | [Pix2Struct](model_doc/pix2struct) | ✅ | ❌ | ❌ |
217
+ | [PLBart](model_doc/plbart) | ✅ | ❌ | ❌ |
218
+ | [PoolFormer](model_doc/poolformer) | ✅ | ❌ | ❌ |
219
+ | [Pop2Piano](model_doc/pop2piano) | ✅ | ❌ | ❌ |
220
+ | [ProphetNet](model_doc/prophetnet) | ✅ | ❌ | ❌ |
221
+ | [PVT](model_doc/pvt) | ✅ | ❌ | ❌ |
222
+ | [QDQBert](model_doc/qdqbert) | ✅ | ❌ | ❌ |
223
+ | [RAG](model_doc/rag) | ✅ | ✅ | ❌ |
224
+ | [REALM](model_doc/realm) | ✅ | ❌ | ❌ |
225
+ | [Reformer](model_doc/reformer) | ✅ | ❌ | ❌ |
226
+ | [RegNet](model_doc/regnet) | ✅ | ✅ | ✅ |
227
+ | [RemBERT](model_doc/rembert) | ✅ | ✅ | ❌ |
228
+ | [ResNet](model_doc/resnet) | ✅ | ✅ | ✅ |
229
+ | [RetriBERT](model_doc/retribert) | ✅ | ❌ | ❌ |
230
+ | [RoBERTa](model_doc/roberta) | ✅ | ✅ | ✅ |
231
+ | [RoBERTa-PreLayerNorm](model_doc/roberta-prelayernorm) | ✅ | ✅ | ✅ |
232
+ | [RoCBert](model_doc/roc_bert) | ✅ | ❌ | ❌ |
233
+ | [RoFormer](model_doc/roformer) | ✅ | ✅ | ✅ |
234
+ | [RWKV](model_doc/rwkv) | ✅ | ❌ | ❌ |
235
+ | [SAM](model_doc/sam) | ✅ | ✅ | ❌ |
236
+ | [SegFormer](model_doc/segformer) | ✅ | ✅ | ❌ |
237
+ | [SEW](model_doc/sew) | ✅ | ❌ | ❌ |
238
+ | [SEW-D](model_doc/sew-d) | ✅ | ❌ | ❌ |
239
+ | [Speech Encoder decoder](model_doc/speech-encoder-decoder) | ✅ | ❌ | ✅ |
240
+ | [Speech2Text](model_doc/speech_to_text) | ✅ | ✅ | ❌ |
241
+ | [SpeechT5](model_doc/speecht5) | ✅ | ❌ | ❌ |
242
+ | [Splinter](model_doc/splinter) | ✅ | ❌ | ❌ |
243
+ | [SqueezeBERT](model_doc/squeezebert) | ✅ | ❌ | ❌ |
244
+ | [SwiftFormer](model_doc/swiftformer) | ✅ | ❌ | ❌ |
245
+ | [Swin Transformer](model_doc/swin) | ✅ | ✅ | ❌ |
246
+ | [Swin Transformer V2](model_doc/swinv2) | ✅ | ❌ | ❌ |
247
+ | [Swin2SR](model_doc/swin2sr) | ✅ | ❌ | ❌ |
248
+ | [SwitchTransformers](model_doc/switch_transformers) | ✅ | ❌ | ❌ |
249
+ | [T5](model_doc/t5) | ✅ | ✅ | ✅ |
250
+ | [T5v1.1](model_doc/t5v1.1) | ✅ | ✅ | ✅ |
251
+ | [Table Transformer](model_doc/table-transformer) | ✅ | ❌ | ❌ |
252
+ | [TAPAS](model_doc/tapas) | ✅ | ✅ | ❌ |
253
+ | [TAPEX](model_doc/tapex) | ✅ | ✅ | ✅ |
254
+ | [Time Series Transformer](model_doc/time_series_transformer) | ✅ | ❌ | ❌ |
255
+ | [TimeSformer](model_doc/timesformer) | ✅ | ❌ | ❌ |
256
+ | [Trajectory Transformer](model_doc/trajectory_transformer) | ✅ | ❌ | ❌ |
257
+ | [Transformer-XL](model_doc/transfo-xl) | ✅ | ✅ | ❌ |
258
+ | [TrOCR](model_doc/trocr) | ✅ | ❌ | ❌ |
259
+ | [TVLT](model_doc/tvlt) | ✅ | ❌ | ❌ |
260
+ | [UL2](model_doc/ul2) | ✅ | ✅ | ✅ |
261
+ | [UMT5](model_doc/umt5) | ✅ | ❌ | ❌ |
262
+ | [UniSpeech](model_doc/unispeech) | ✅ | ❌ | ❌ |
263
+ | [UniSpeechSat](model_doc/unispeech-sat) | ✅ | ❌ | ❌ |
264
+ | [UPerNet](model_doc/upernet) | ✅ | ❌ | ❌ |
265
+ | [VAN](model_doc/van) | ✅ | ❌ | ❌ |
266
+ | [VideoMAE](model_doc/videomae) | ✅ | ❌ | ❌ |
267
+ | [ViLT](model_doc/vilt) | ✅ | ❌ | ❌ |
268
+ | [Vision Encoder decoder](model_doc/vision-encoder-decoder) | ✅ | ✅ | ✅ |
269
+ | [VisionTextDualEncoder](model_doc/vision-text-dual-encoder) | ✅ | ✅ | ✅ |
270
+ | [VisualBERT](model_doc/visual_bert) | ✅ | ❌ | ❌ |
271
+ | [ViT](model_doc/vit) | ✅ | ✅ | ✅ |
272
+ | [ViT Hybrid](model_doc/vit_hybrid) | ✅ | ❌ | ❌ |
273
+ | [VitDet](model_doc/vitdet) | ✅ | ❌ | ❌ |
274
+ | [ViTMAE](model_doc/vit_mae) | ✅ | ✅ | ❌ |
275
+ | [ViTMatte](model_doc/vitmatte) | ✅ | ❌ | ❌ |
276
+ | [ViTMSN](model_doc/vit_msn) | ✅ | ❌ | ❌ |
277
+ | [VITS](model_doc/vits) | ✅ | ❌ | ❌ |
278
+ | [ViViT](model_doc/vivit) | ✅ | ❌ | ❌ |
279
+ | [Wav2Vec2](model_doc/wav2vec2) | ✅ | ✅ | ✅ |
280
+ | [Wav2Vec2-Conformer](model_doc/wav2vec2-conformer) | ✅ | ❌ | ❌ |
281
+ | [Wav2Vec2Phoneme](model_doc/wav2vec2_phoneme) | ✅ | ✅ | ✅ |
282
+ | [WavLM](model_doc/wavlm) | ✅ | ❌ | ❌ |
283
+ | [Whisper](model_doc/whisper) | ✅ | ✅ | ✅ |
284
+ | [X-CLIP](model_doc/xclip) | ✅ | ❌ | ❌ |
285
+ | [X-MOD](model_doc/xmod) | ✅ | ❌ | ❌ |
286
+ | [XGLM](model_doc/xglm) | ✅ | ✅ | ✅ |
287
+ | [XLM](model_doc/xlm) | ✅ | ✅ | ❌ |
288
+ | [XLM-ProphetNet](model_doc/xlm-prophetnet) | ✅ | ❌ | ❌ |
289
+ | [XLM-RoBERTa](model_doc/xlm-roberta) | ✅ | ✅ | ✅ |
290
+ | [XLM-RoBERTa-XL](model_doc/xlm-roberta-xl) | ✅ | ❌ | ❌ |
291
+ | [XLM-V](model_doc/xlm-v) | ✅ | ✅ | ✅ |
292
+ | [XLNet](model_doc/xlnet) | ✅ | ✅ | ❌ |
293
+ | [XLS-R](model_doc/xls_r) | ✅ | ✅ | ✅ |
294
+ | [XLSR-Wav2Vec2](model_doc/xlsr_wav2vec2) | ✅ | ✅ | ✅ |
295
+ | [YOLOS](model_doc/yolos) | ✅ | ❌ | ❌ |
296
+ | [YOSO](model_doc/yoso) | ✅ | ❌ | ❌ |
297
+
298
+ <!-- End table-->
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/te/quicktour.md ADDED
@@ -0,0 +1,557 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # శీఘ్ర పర్యటన
18
+
19
+ [[ఓపెన్-ఇన్-కోలాబ్]]
20
+
21
+ 🤗 ట్రాన్స్‌ఫార్మర్‌లతో లేచి పరుగెత్తండి! మీరు డెవలపర్ అయినా లేదా రోజువారీ వినియోగదారు అయినా, ఈ శీఘ్ర పర్యటన మీకు ప్రారంభించడానికి సహాయం చేస్తుంది మరియు [`pipeline`] అనుమితి కోసం ఎలా ఉపయోగించాలో మీకు చూపుతుంది, [AutoClass](./model_doc/auto) తో ప్రీట్రైన్డ్ మోడల్ మరియు ప్రిప్రాసెసర్/ ఆటో, మరియు PyTorch లేదా TensorFlowతో మోడల్‌కు త్వరగా శిక్షణ ఇవ్వండి. మీరు ఒక అనుభవశూన్యుడు అయితే, ఇక్కడ పరిచయం చేయబడిన భావనల గురించి మరింత లోతైన వివరణల కోసం మా ట్యుటోరియల్స్ లేదా [course](https://huggingface.co/course/chapter1/1)ని తనిఖీ చేయమని మేము సిఫార్సు చేస్తున్నాము.
22
+
23
+ మీరు ప్రారంభించడానికి ముందు, మీరు అవసరమైన అన్ని లైబ్రరీలను ఇన్‌స్టాల్ చేశారని నిర్ధారించుకోండి:
24
+
25
+ ```bash
26
+ !pip install transformers datasets evaluate accelerate
27
+ ```
28
+
29
+ మీరు మీ ప్రాధాన్య యంత్ర అభ్యాస ఫ్రేమ్‌వర్క్‌ను కూడా ఇన్‌స్టాల్ చేయాలి:
30
+
31
+ <frameworkcontent>
32
+ <pt>
33
+
34
+ ```bash
35
+ pip install torch
36
+ ```
37
+ </pt>
38
+ <tf>
39
+
40
+ ```bash
41
+ pip install tensorflow
42
+ ```
43
+ </tf>
44
+ </frameworkcontent>
45
+
46
+ ## పైప్‌లైన్
47
+
48
+ <Youtube id="tiZFewofSLM"/>
49
+
50
+ [`pipeline`] అనుమితి కోసం ముందుగా శిక్షణ పొందిన నమూనాను ఉపయోగించడానికి సులభమైన మరియు వేగవంతమైన మార్గం. మీరు వివిధ పద్ధతులలో అనేక పనుల కోసం [`pipeline`] వెలుపల ఉపయోగించవచ్చు, వాటిలో కొన్ని క్రింది పట్టికలో చూపబడ్డాయి:
51
+
52
+
53
+ <Tip>
54
+
55
+ అందుబాటులో ఉన్న పనుల పూర్తి జాబితా కోసం, [పైప్‌లైన్ API సూచన](./main_classes/pipelines)ని తనిఖీ చేయండి.
56
+
57
+ </Tip>
58
+
59
+ Here is the translation in Telugu:
60
+
61
+ | **పని** | **వివరణ** | **మోడాలిటీ** | **పైప్‌లైన్ ఐడెంటిఫైయర్** |
62
+ |------------------------------|--------------------------------------------------------------------------------------------------------|-----------------|------------------------------------------|
63
+ | వచన వర్గీకరణు | కొన్ని వచనాల అంతా ఒక లేబుల్‌ను కొడి | NLP | pipeline(task=“sentiment-analysis”) |
64
+ | వచన సృష్టి | ప్రమ్పుటం కలిగినంత వచనం సృష్టించండి | NLP | pipeline(task=“text-generation”) |
65
+ | సంక్షేపణ | వచనం లేదా పత్రం కొరకు సంక్షేపణ తయారుచేసండి | NLP | pipeline(task=“summarization”) |
66
+ | చిత్రం వర్గీ���రణు | చిత్రంలో ఒక లేబుల్‌ను కొడి | కంప్యూటర్ విషయం | pipeline(task=“image-classification”) |
67
+ | చిత్రం విభజన | ఒక చిత్రంలో ప్రతి వ్యక్తిగత పిక్సల్‌ను ఒక లేబుల్‌గా నమోదు చేయండి (సెమాంటిక్, పానొప్టిక్, మరియు ఇన్స్టన్స్ విభజనలను మద్దతు చేస్తుంది) | కంప్యూటర్ విషయం | pipeline(task=“image-segmentation”) |
68
+ | వస్త్రం గుర్తువు | ఒక చిత్రంలో పదాల యొక్క బౌండింగ్ బాక్స్‌లను మరియు వస్త్రాల వర్గాలను అంచనా చేయండి | కంప్యూటర్ విషయం | pipeline(task=“object-detection”) |
69
+ | ఆడియో గుర్తువు | కొన్ని ఆడియో డేటానికి ఒక లేబుల్‌ను కొడి | ఆడియో | pipeline(task=“audio-classification”) |
70
+ | స్వయంచలన ప్రసంగ గుర్తువు | ప్రసంగాన్ని వచనంగా వర్ణించండి | ఆడియో | pipeline(task=“automatic-speech-recognition”) |
71
+ | దృశ్య ప్రశ్న సంవాదం | వచనం మరియు ప్రశ్నను నమోదు చేసిన చిత్రంతో ప్రశ్నకు సమాధానం ఇవ్వండి | బహుమూలిక | pipeline(task=“vqa”) |
72
+ | పత్రం ప్రశ్న సంవాదం | ప్రశ్నను పత్రం లేదా డాక్యుమెంట్‌తో సమాధానం ఇవ్వండి | బహుమూలిక | pipeline(task="document-question-answering") |
73
+ | చిత్రం వ్రాసాయింగ్ | కొన్ని చిత్రానికి పిటియార్లను సృష్టించండి | బహుమూలిక | pipeline(task="image-to-text") |
74
+
75
+
76
+ [`pipeline`] యొక్క ఉదాహరణను సృష్టించడం ద్వారా మరియు మీరు దానిని ఉపయోగించాలనుకుంటున్న పనిని పేర్కొనడం ద్వారా ప్రారంభించండి. ఈ గైడ్‌లో, మీరు సెంటిమెంట్ విశ్లేషణ కోసం [`pipeline`]ని ఉదాహరణగా ఉపయోగిస్తారు:
77
+
78
+ ```py
79
+ >>> from transformers import pipeline
80
+
81
+ >>> classifier = pipeline("sentiment-analysis")
82
+ ```
83
+
84
+ సెంటిమెంట్ విశ్లేషణ కోసం [`pipeline`] డిఫాల్ట్ [ప్రీట్రైన్డ్ మోడల్](https://huggingface.co/distilbert/distilbert-base-uncased-finetuned-sst-2-english) మరియు టోకెనైజర్‌ని డౌన్‌లోడ్ చేస్తుంది మరియు కాష్ చేస్తుంది. ఇప్పుడు మీరు మీ లక్ష్య వచనంలో `classifier`ని ఉపయోగించవచ్చు:
85
+
86
+ ```py
87
+ >>> classifier("We are very happy to show you the 🤗 Transformers library.")
88
+ [{'label': 'POSITIVE', 'score': 0.9998}]
89
+ ```
90
+
91
+ మీరు ఒకటి కంటే ఎక్కువ ఇన్‌పుట్‌లను కలిగి ఉంటే, నిఘంటువుల జాబితాను అందించడానికి మీ ఇన్‌పుట్‌లను జాబితాగా [`pipeline`]కి పంపండి:
92
+
93
+ ```py
94
+ >>> results = classifier(["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."])
95
+ >>> for result in results:
96
+ ... print(f"label: {result['label']}, with score: {round(result['score'], 4)}")
97
+ label: POSITIVE, with score: 0.9998
98
+ label: NEGATIVE, with score: 0.5309
99
+ ```
100
+
101
+ [`pipeline`] మీకు నచ్చిన ఏదైనా పని కోసం మొత్తం డేటాసెట్‌ను కూడా పునరావృతం చేయగలదు. ఈ ఉదాహరణ కోసం, స్వయంచాలక ప్రసంగ గుర్తింపును మన పనిగా ఎంచుకుందాం:
102
+
103
+ ```py
104
+ >>> import torch
105
+ >>> from transformers import pipeline
106
+
107
+ >>> speech_recognizer = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h")
108
+ ```
109
+
110
+ మీరు మళ్లీ మళ్లీ చెప్పాలనుకుంటున్న ఆడియో డేటాసెట్‌ను లోడ్ చేయండి (మరిన్ని వివరాల కోసం 🤗 డేటాసెట్‌లు [త్వరిత ప్రారంభం](https://huggingface.co/docs/datasets/quickstart#audio) చూడండి. ఉదాహరణకు, [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) డేటాసెట్‌ను లోడ్ చేయండి:
111
+
112
+ ```py
113
+ >>> from datasets import load_dataset, Audio
114
+
115
+ >>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") # doctest: +IGNORE_RESULT
116
+ ```
117
+
118
+ డేటాసెట్ యొక్క నమూనా రేటు నమూనాతో సరిపోలుతుందని మీరు నిర్ధారించుకోవాలి
119
+ రేటు [`facebook/wav2vec2-base-960h`](https://huggingface.co/facebook/wav2vec2-base-960h) దీనిపై శిక్షణ పొందింది:
120
+
121
+ ```py
122
+ >>> dataset = dataset.cast_column("audio", Audio(sampling_rate=speech_recognizer.feature_extractor.sampling_rate))
123
+ ```
124
+
125
+ `"ఆడియో"` కాలమ్‌కి కాల్ చేస్తున్నప్పుడు ఆడియో ఫైల్‌లు స్వయంచాలకంగా లోడ్ చేయబడతాయి మరియు మళ్లీ నమూనా చేయబడతాయి.
126
+ మొదటి 4 నమూనాల నుండి ముడి వేవ్‌ఫార్మ్ శ్రేణులను సంగ్రహించి, పైప్‌లైన్‌కు జాబితాగా పాస్ చేయండి:
127
+
128
+ ```py
129
+ >>> result = speech_recognizer(dataset[:4]["audio"])
130
+ >>> print([d["text"] for d in result])
131
+ ['I WOULD LIKE TO SET UP A JOINT ACCOUNT WITH MY PARTNER HOW DO I PROCEED WITH DOING THAT', "FONDERING HOW I'D SET UP A JOIN TO HELL T WITH MY WIFE AND WHERE THE AP MIGHT BE", "I I'D LIKE TOY SET UP A JOINT ACCOUNT WITH MY PARTNER I'M NOT SEEING THE OPTION TO DO IT ON THE APSO I CALLED IN TO GET SOME HELP CAN I JUST DO IT OVER THE PHONE WITH YOU AND GIVE YOU THE INFORMATION OR SHOULD I DO IT IN THE AP AN I'M MISSING SOMETHING UQUETTE HAD PREFERRED TO JUST DO IT OVER THE PHONE OF POSSIBLE THINGS", 'HOW DO I FURN A JOINA COUT']
132
+ ```
133
+
134
+ ఇన్‌పుట్‌లు పెద్దగా ఉన్న పెద్ద డేటాసెట్‌ల కోసం (స్పీచ్ లేదా విజన్ వంటివి), మెమరీలోని అన్ని ఇన్‌పుట్‌లను లోడ్ చేయడానికి మీరు జాబితాకు బదులుగా జెనరేటర్‌ను పాస్ చేయాలనుకుంటున్నారు. మరింత సమాచారం కోసం [పైప్‌లైన్ API సూచన](./main_classes/pipelines)ని చూడండి.
135
+
136
+ ### పైప్‌లైన్‌లో మరొక మోడల్ మరియు టోకెనైజర్‌ని ఉపయోగించండి
137
+
138
+ [`pipeline`] [Hub](https://huggingface.co/models) నుండి ఏదైనా మోడల్‌ను కలిగి ఉంటుంది, దీని వలన ఇతర వినియోగ-కేసుల కోసం [`pipeline`]ని సులభంగా స్వీకరించవచ్చు. ఉదాహరణకు, మీరు ఫ్రెంచ్ టెక్స్ట్‌ను హ్యాండిల్ చేయగల మోడల్ కావాలనుకుంటే, తగిన మోడల్ కోసం ఫిల్టర్ చేయడానికి హబ్‌లోని ట్యాగ్‌లను ఉపయోగించండి. అగ్ర ఫిల్టర్ చేసిన ఫలితం మీరు ఫ్రెంచ్ టెక్స్ట్ కోసం ఉపయోగించగల సెంటిమెంట్ విశ్లేషణ కోసం ఫైన్‌ట్యూన్ చేయబడిన బహుభాషా [BERT మోడల్](https://huggingface.co/nlptown/bert-base-multilingual-uncased-sentiment)ని అందిస్తుంది:
139
+
140
+ ```py
141
+ >>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
142
+ ```
143
+
144
+ <frameworkcontent>
145
+ <pt>
146
+ ముందుగా శిక్షణ పొందిన మోడల్‌ను లోడ్ చేయడానికి [`AutoModelForSequenceClassification`] మరియు [`AutoTokenizer`]ని ఉపయోగించండి మరియు దాని అనుబంధిత టోకెనైజర్ (తదుపరి విభాగంలో `AutoClass`పై మరిన్ని):
147
+
148
+ ```py
149
+ >>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
150
+
151
+ >>> model = AutoModelForSequenceClassification.from_pretrained(model_name)
152
+ >>> tokenizer = AutoTokenizer.from_pretrained(model_name)
153
+ ```
154
+ </pt>
155
+ <tf>
156
+ ముందుగా శిక్షణ పొందిన మోడల్‌ను లోడ్ చేయడానికి [`TFAutoModelForSequenceClassification`] మరియు [`AutoTokenizer`]ని ఉపయోగించండి మరియు దాని అనుబంధిత టోకెనైజర్ (తదుపరి విభాగంలో `TFAutoClass`పై మరిన్ని):
157
+
158
+ ```py
159
+ >>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
160
+
161
+ >>> model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
162
+ >>> tokenizer = AutoTokenizer.from_pretrained(model_name)
163
+ ```
164
+ </tf>
165
+ </frameworkcontent>
166
+
167
+ [`pipeline`]లో మోడల్ మరియు టోకెనైజర్‌ను పేర్కొనండి మరియు ఇప్పుడు మీరు ఫ్రెంచ్ టెక్స్ట్‌పై `క్లాసిఫైయర్`ని వర్తింపజేయవచ్చు:
168
+
169
+ ```py
170
+ >>> classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
171
+ >>> classifier("Nous sommes très heureux de vous présenter la bibliothèque 🤗 Transformers.")
172
+ [{'label': '5 stars', 'score': 0.7273}]
173
+ ```
174
+
175
+ మీరు మీ వినియోగ-కేస్ కోసం మోడల్‌ను కనుగొనలేకపోతే, మీరు మీ డేటాపై ముందుగా శిక్షణ పొందిన మోడల్‌ను చక్కగా మార్చాలి. ఎలాగో తెలుసుకోవడానికి మా [ఫైన్‌ట్యూనింగ్ ట్యుటోరియల్](./training)ని చూడండి. చివరగా, మీరు మీ ప్రీట్రైన్డ్ మోడల్‌ని ఫైన్‌ట్యూన్ చేసిన తర్వాత, దయచేసి అందరి కోసం మెషిన్ లెర్నింగ్‌ని డెమోక్రటైజ్ చేయడానికి హబ్‌లోని సంఘంతో మోడల్‌ను [షేరింగ్](./model_sharing) పరిగణించండి! 🤗
176
+
177
+ ## AutoClass
178
+
179
+ <Youtube id="AhChOFRegn4"/>
180
+
181
+ హుడ్ కింద, మీరు పైన ఉపయోగించిన [`pipeline`]కి శక్తిని అందించడానికి [`AutoModelForSequenceClassification`] మరియు [`AutoTokenizer`] తరగతులు కలిసి పని చేస్తాయి. ఒక [AutoClass](./model_doc/auto) అనేది ముందుగా శిక్షణ పొందిన మోడల్ యొక్క ఆర్కిటెక్చర్‌ను దాని పేరు లేదా మార్గం నుండి స్వయంచాలకంగా తిరిగి పొందే సత్వరమార్గం. మీరు మీ టాస్క్ కోసం తగిన `ఆటోక్లాస్`ని మాత్రమే ఎంచుకోవాలి మరియు ఇది అనుబంధిత ప్రీప్రాసెసింగ్ క్లాస్.
182
+
183
+ మునుపటి విభాగం నుండి ఉదాహరణకి తిరిగి వెళ్లి, [`pipeline`] ఫలితాలను ప్రతిబింబించడానికి మీరు `ఆటోక్లాస్`ని ఎలా ఉపయోగించవచ్చో చూద్దాం.
184
+
185
+ ### AutoTokenizer
186
+
187
+ ఒక మోడల్‌కు ఇన్‌పుట్‌లుగా సంఖ్యల శ్రేణిలో వచనాన్ని ప్రీప్రాసెసింగ్ చేయడానికి టోకెనైజర్ బాధ్యత వహిస్తుంది. పదాన్ని ఎలా విభజించాలి మరియు ఏ స్థాయిలో పదాలను విభజించాలి ([tokenizer సారాంశం](./tokenizer_summary)లో టోకనైజేషన్ గురించి మరింత తెలుసుకోండి) సహా టోకనైజేషన్ ప్రక్రియను నియంత్రించే అనేక నియమాలు ఉన్నాయి. గుర్తుంచుకోవలసిన ముఖ్యమైన విషయం ఏమిటంటే, మీరు మోడల్‌కు ముందే శిక్షణ పొందిన అదే టోకనైజేషన్ నియమాలను ఉపయోగిస్తున్నారని నిర్ధారించుకోవడానికి మీరు అదే మోడల్ పేరుతో టోకెనైజర్‌ను తక్షణం చేయాలి.
188
+
189
+ [`AutoTokenizer`]తో టోకెనైజర్‌ను లోడ్ చేయండి:
190
+
191
+ ```py
192
+ >>> from transformers import AutoTokenizer
193
+
194
+ >>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
195
+ >>> tokenizer = AutoTokenizer.from_pretrained(model_name)
196
+ ```
197
+
198
+ మీ వచనాన్ని టోకెనైజర్‌కు పంపండి:
199
+
200
+ ```py
201
+ >>> encoding = tokenizer("We are very happy to show you the 🤗 Transformers library.")
202
+ >>> print(encoding)
203
+ {'input_ids': [101, 11312, 10320, 12495, 19308, 10114, 11391, 10855, 10103, 100, 58263, 13299, 119, 102],
204
+ 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
205
+ 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
206
+ ```
207
+
208
+ టోకెనైజర్ వీటిని కలిగి ఉన్న నిఘంటువుని అందిస్తుంది:
209
+
210
+ * [input_ids](./glossary#input-ids): మీ టోకెన్‌ల సంఖ్యాపరమైన ప్రాతినిధ్యం.
211
+ * [అటెన్షన్_మాస్క్](./glossary#attention-mask): ఏ టోకెన్‌లకు హాజరు కావాలో సూచిస్తుంది.
212
+
213
+ ఒక టోకెనైజర్ ఇన్‌పుట్‌ల జాబితాను కూడా ఆమోదించగలదు మరియు ఏకరీతి పొడవుతో బ్యాచ్‌ను తిరిగి ఇవ్వడానికి టెక్స్ట్‌ను ప్యాడ్ చేసి కత్తిరించవచ్చు:
214
+
215
+ <frameworkcontent>
216
+ <pt>
217
+
218
+ ```py
219
+ >>> pt_batch = tokenizer(
220
+ ... ["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."],
221
+ ... padding=True,
222
+ ... truncation=True,
223
+ ... max_length=512,
224
+ ... return_tensors="pt",
225
+ ... )
226
+ ```
227
+ </pt>
228
+ <tf>
229
+
230
+ ```py
231
+ >>> tf_batch = tokenizer(
232
+ ... ["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."],
233
+ ... padding=True,
234
+ ... truncation=True,
235
+ ... max_length=512,
236
+ ... return_tensors="tf",
237
+ ... )
238
+ ```
239
+ </tf>
240
+ </frameworkcontent>
241
+
242
+ <Tip>
243
+
244
+ టోకనైజేషన్ గురించి మరిన్ని వివరాల కోసం [ప్రీప్రాసెస్](./preprocessing) ట్యుటోరియల్‌ని చూడండి మరియు ఇమేజ్, ఆడియో మరియు మల్టీమోడల్ ఇన్‌పుట్‌లను ప్రీప్రాసెస్ చేయడానికి [`AutoImageProcessor`], [`AutoFeatureExtractor`] మరియు [`AutoProcessor`] ఎలా ఉపయోగించాలి.
245
+
246
+ </Tip>
247
+
248
+ ### AutoModel
249
+
250
+ <frameworkcontent>
251
+ <pt>
252
+ 🤗 ట్రాన్స్‌ఫార్మర్లు ప్రీట్రైన్డ్ ఇన్‌స్టాన్స్‌లను లోడ్ చేయడానికి సులభమైన మరియు ఏకీకృత మార్గాన్ని అందిస్తాయి. దీని అర్థం మీరు [`AutoTokenizer`]ని లోడ్ చేసినట్లుగా [`AutoModel`]ని లోడ్ చేయవచ్చు. టాస్క్ కోసం సరైన [`AutoModel`]ని ఎంచుకోవడం మాత్రమే తేడా. టెక్స్ట్ (లేదా సీక్వెన్స్) వర్గీకరణ కోసం, మీరు [`AutoModelForSequenceClassification`]ని లోడ్ చేయాలి:
253
+
254
+
255
+ ```py
256
+ >>> from transformers import AutoModelForSequenceClassification
257
+
258
+ >>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
259
+ >>> pt_model = AutoModelForSequenceClassification.from_pretrained(model_name)
260
+ ```
261
+
262
+ <Tip>
263
+
264
+ [`AutoModel`] క్లాస్ ద్వారా సపోర్ట్ చేసే టాస్క్‌ల కోసం [టాస్క్ సారాంశం](./task_summary)ని చూడండి.
265
+
266
+ </Tip>
267
+
268
+ ఇప్పుడు మీ ప్రీప్రాసెస్ చేయబడిన బ్యాచ్ ఇన్‌పుట్‌లను నేరుగా మోడల్‌కి పంపండి. మీరు `**`ని జోడించడం ద్వారా నిఘంటువుని అన్‌ప్యాక్ చేయాలి:
269
+
270
+ ```py
271
+ >>> pt_outputs = pt_model(**pt_batch)
272
+ ```
273
+
274
+ మోడల్ తుది యాక్టివేషన్‌లను `logits` లక్షణంలో అవుట్‌పుట్ చేస్తుంది. సంభావ్యతలను తిరిగి పొందడానికి సాఫ్ట్‌మాక్స్ ఫంక్షన్‌ను `logits` కు వర్తింపజేయండి:
275
+
276
+
277
+ ```py
278
+ >>> from torch import nn
279
+
280
+ >>> pt_predictions = nn.functional.softmax(pt_outputs.logits, dim=-1)
281
+ >>> print(pt_predictions)
282
+ tensor([[0.0021, 0.0018, 0.0115, 0.2121, 0.7725],
283
+ [0.2084, 0.1826, 0.1969, 0.1755, 0.2365]], grad_fn=<SoftmaxBackward0>)
284
+ ```
285
+
286
+ </pt>
287
+ <tf>
288
+ 🤗 ట్రాన్స్‌ఫార్మర్లు ప్ర���ట్రైన్డ్ ఇన్‌స్టాన్స్‌లను లోడ్ చేయడానికి సులభమైన మరియు ఏకీకృత మార్గాన్ని అందిస్తాయి. మీరు [`AutoTokenizer`]ని లోడ్ చేసినట్లుగా మీరు [`TFAutoModel`]ని లోడ్ చేయవచ్చని దీని అర్థం. టాస్క్ కోసం సరైన [`TFAutoModel`]ని ఎంచుకోవడం మాత్రమే తేడా. టెక్స్ట్ (లేదా సీక్వెన్స్) వర్గీకరణ కోసం, మీరు [`TFAutoModelForSequenceClassification`]ని లోడ్ చేయాలి:
289
+
290
+ ```py
291
+ >>> from transformers import TFAutoModelForSequenceClassification
292
+
293
+ >>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
294
+ >>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
295
+ ```
296
+
297
+ <Tip>
298
+
299
+ [`AutoModel`] క్లాస్ ద్వారా సపోర్ట్ చేసే టాస్క్‌ల కోసం [టాస్క్ సారాంశం](./task_summary)ని చూడండి.
300
+
301
+ </Tip>
302
+
303
+ ఇప్పుడు మీ ప్రీప్రాసెస్ చేయబడిన బ్యాచ్ ఇన్‌పుట్‌లను నేరుగా మోడల్‌కి పంపండి. మీరు టెన్సర్‌లను ఇలా పాస్ చేయవచ్చు:
304
+
305
+ ```py
306
+ >>> tf_outputs = tf_model(tf_batch)
307
+ ```
308
+
309
+ మోడల్ తుది యాక్టివేషన్‌లను `logits` లక్షణంలో అవుట్‌పుట్ చేస్తుంది. సంభావ్యతలను తిరిగి పొందడానికి సాఫ్ట్‌మాక్స్ ఫంక్షన్‌ను `logits`కు వర్తింపజేయండి:
310
+
311
+ ```py
312
+ >>> import tensorflow as tf
313
+
314
+ >>> tf_predictions = tf.nn.softmax(tf_outputs.logits, axis=-1)
315
+ >>> tf_predictions # doctest: +IGNORE_RESULT
316
+ ```
317
+ </tf>
318
+ </frameworkcontent>
319
+
320
+ <Tip>
321
+
322
+ అన్ని 🤗 ట్రాన్స్‌ఫార్మర్స్ మోడల్‌లు (PyTorch లేదా TensorFlow) తుది యాక్టివేషన్‌కు *ముందు* టెన్సర్‌లను అవుట్‌పుట్ చేస్తాయి
323
+ ఫంక్షన్ (softmax వంటిది) ఎందుకంటే చివరి యాక్టివేషన్ ఫంక్షన్ తరచుగా నష్టంతో కలిసిపోతుంది. మోడల్ అవుట్‌పుట్‌లు ప్రత్యేక డేటాక్లాస్‌లు కాబట్టి వాటి లక్షణాలు IDEలో స్వయంచాలకంగా పూర్తి చేయబడతాయి. మోడల్ అవుట్‌పుట్‌లు టుపుల్ లేదా డిక్షనరీ లాగా ప్రవర్తిస్తాయి (మీరు పూర్ణాంకం, స్లైస్ లేదా స్ట్రింగ్‌తో ఇండెక్స్ చేయవచ్చు) ఈ సందర్భంలో, ఏదీ లేని గుణాలు విస్మరించబడతాయి.
324
+
325
+ </Tip>
326
+
327
+ ### మోడల్‌ను సేవ్ చేయండి
328
+
329
+ <frameworkcontent>
330
+ <pt>
331
+ మీ మోడల్ చక్కగా ట్యూన్ చేయబడిన తర్వాత, మీరు దానిని [`PreTrainedModel.save_pretrained`]ని ఉపయోగించి దాని టోకెనైజర్‌తో సేవ్ చేయవచ్చు:
332
+
333
+ ```py
334
+ >>> pt_save_directory = "./pt_save_pretrained"
335
+ >>> tokenizer.save_pretrained(pt_save_directory) # doctest: +IGNORE_RESULT
336
+ >>> pt_model.save_pretrained(pt_save_directory)
337
+ ```
338
+
339
+ మీరు మోడల్‌ని మళ్లీ ఉపయోగించడానికి సిద్ధంగా ఉన్నప్పుడు, దాన్ని [`PreTrainedModel.from_pretrained`]తో రీలోడ్ చేయండి:
340
+
341
+ ```py
342
+ >>> pt_model = AutoModelForSequenceClassification.from_pretrained("./pt_save_pretrained")
343
+ ```
344
+ </pt>
345
+ <tf>
346
+ మీ మోడల్ చక్కగా ట్యూన్ చేయబడిన తర్వాత, మీరు దానిని [`TFPreTrainedModel.save_pretrained`]ని ఉపయోగించి దాని టోకెనైజర్‌తో సేవ్ చేయవచ్చు:
347
+
348
+ ```py
349
+ >>> tf_save_directory = "./tf_save_pretrained"
350
+ >>> tokenizer.save_pretrained(tf_save_directory) # doctest: +IGNORE_RESULT
351
+ >>> tf_model.save_pretrained(tf_save_directory)
352
+ ```
353
+ మీరు మోడల్‌ని మళ్లీ ఉపయోగించడానికి సిద్ధంగా ఉన్నప్పుడు, దాన్ని [`TFPreTrainedModel.from_pretrained`]తో రీలోడ్ చేయండి:
354
+
355
+ ```py
356
+ >>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("./tf_save_pretrained")
357
+ ```
358
+ </tf>
359
+ </frameworkcontent>
360
+
361
+ ఒక ప్రత్యేకించి అద్భుతమైన 🤗 ట్రాన్స్‌ఫార్మర్స్ ఫీచర్ మోడల్‌ను సేవ్ చేయగల సామర్థ్యం మరియు దానిని PyTorch లేదా TensorFlow మోడల్‌గా రీలోడ్ చేయగలదు. `from_pt` లేదా `from_tf` పరామితి మోడల్‌ను ఒక ఫ్రేమ్‌వర్క్ నుండి మరొక ఫ్రేమ్‌వర్క్‌కి మార్చగలదు:
362
+
363
+ <frameworkcontent>
364
+ <pt>
365
+
366
+ ```py
367
+ >>> from transformers import AutoModel
368
+
369
+ >>> tokenizer = AutoTokenizer.from_pretrained(pt_save_directory)
370
+ >>> pt_model = AutoModelForSequenceClassification.from_pretrained(pt_save_directory, from_pt=True)
371
+ ```
372
+ </pt>
373
+ <tf>
374
+
375
+ ```py
376
+ >>> from transformers import TFAutoModel
377
+
378
+ >>> tokenizer = AutoTokenizer.from_pretrained(tf_save_directory)
379
+ >>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(tf_save_directory, from_tf=True)
380
+ ```
381
+ </tf>
382
+ </frameworkcontent>
383
+
384
+ ## కస్టమ్ మోడల్ బిల్డ్స్
385
+ మోడల్ ఎలా నిర్మించబడుతుందో మార్చడానికి మీరు మోడల్ కాన్ఫిగరేషన్ క్లాస్‌ని సవరించవచ్చు. దాచిన లేయర్‌లు లేదా అటెన్షన్ హెడ్‌ల సంఖ్య వంటి మోడల్ లక్షణాలను కాన్ఫిగరేషన్ నిర్దేశిస్తుంది. మీరు కస్టమ్ కాన్ఫిగరేషన్ క్లాస్ నుండి మోడల్‌ను ప్రారంభించినప్పుడు మీరు మొదటి నుండి ప్రారంభిస్తారు. మోడల్ అట్రిబ్యూట్‌లు యాదృచ్ఛికంగా ప్రారంభించబడ్డాయి మరియు అర్థవంతమైన ఫలితాలను పొందడానికి మీరు మోడల్‌ను ఉపయోగించే ముందు దానికి శిక్షణ ఇవ్వాలి.
386
+
387
+ [`AutoConfig`]ని దిగుమతి చేయడం ద్వారా ప్రారంభించండి, ఆపై మీరు సవరించాలనుకుంటున్న ప్రీట్రైన్డ్ మోడల్‌ను లోడ్ చేయండి. [`AutoConfig.from_pretrained`]లో, మీరు అటెన్షన్ హెడ్‌ల సంఖ్య వంటి మీరు మార్చాలనుకుంటున్న లక్షణాన్ని పేర్కొనవచ్చు:
388
+
389
+ ```py
390
+ >>> from transformers import AutoConfig
391
+
392
+ >>> my_config = AutoConfig.from_pretrained("distilbert/distilbert-base-uncased", n_heads=12)
393
+ ```
394
+
395
+ <frameworkcontent>
396
+ <pt>
397
+ [`AutoModel.from_config`]తో మీ అనుకూల కాన్ఫిగరేషన్ నుండి మోడల్‌ను సృష్టించండి:
398
+
399
+ ```py
400
+ >>> from transformers import AutoModel
401
+
402
+ >>> my_model = AutoModel.from_config(my_config)
403
+ ```
404
+ </pt>
405
+ <tf>
406
+ [`TFAutoModel.from_config`]తో మీ అనుకూల కాన్ఫిగరేషన్ నుండి మోడల్‌ను సృష్టించండి:
407
+
408
+ ```py
409
+ >>> from transformers import TFAutoModel
410
+
411
+ >>> my_model = TFAutoModel.from_config(my_config)
412
+ ```
413
+ </tf>
414
+ </frameworkcontent>
415
+
416
+ అనుకూల కాన్ఫిగరేషన్‌లను రూపొందించడం గురించి మరింత సమాచారం కోసం [కస్టమ్ ఆర్కిటెక్చర్‌ని సృష్టించండి](./create_a_model) గైడ్‌ను చూడండి.
417
+
418
+ ## శిక్షకుడు - పైటార్చ్ ఆప్టిమైజ్ చేసిన శిక్షణ లూప్
419
+
420
+ అన్ని మోడల్‌లు ప్రామాణికమైన [`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) కాబట్టి మీరు వాటిని ఏదైనా సాధారణ శిక్షణ లూప్‌లో ఉపయోగించవచ్చు. మీరు మీ స్వంత శిక్షణ లూప్‌ను వ్రాయగలిగినప్పటికీ, 🤗 ట్రాన్స్‌ఫార్మర్లు PyTorch కోసం [`ట్రైనర్`] తరగతిని అందజేస్తాయి, ఇందులో ప్రాథమిక శిక్షణ లూప్ ఉంటుంది మరియు పంపిణీ చేయబడిన శిక్షణ, మిశ్రమ ఖచ్చితత్వం మరియు మరిన్ని వంటి ఫీచర్‌ల కోసం అదనపు కార్యాచరణను జోడిస్తుంది.
421
+
422
+ మీ విధిని బట్టి, మీరు సాధారణంగా కింది పారామితులను [`ట్రైనర్`]కి పంపుతారు:
423
+
424
+ 1. మీరు [`PreTrainedModel`] లేదా [`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)తో ప్రారంభిస్తారు:
425
+ ```py
426
+ >>> from transformers import AutoModelForSequenceClassification
427
+
428
+ >>> model = AutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased")
429
+ ```
430
+
431
+ 2. [`TrainingArguments`] మీరు నేర్చుకునే రేటు, బ్యాచ్ పరిమాణం మరియు శిక్షణ పొందవలసిన యుగాల సంఖ్య వంటి మార్చగల మోడల్ హైపర్‌పారామీటర్‌లను కలిగి ఉంది. మీరు ఎలాంటి శిక్షణా వాదనలను పేర్కొనకుంటే డిఫాల్ట్ విలువలు ఉపయోగించబడతాయి:
432
+
433
+ ```py
434
+ >>> from transformers import TrainingArguments
435
+
436
+ >>> training_args = TrainingArguments(
437
+ ... output_dir="path/to/save/folder/",
438
+ ... learning_rate=2e-5,
439
+ ... per_device_train_batch_size=8,
440
+ ... per_device_eval_batch_size=8,
441
+ ... num_train_epochs=2,
442
+ ... )
443
+ ```
444
+
445
+ 3. టోకెనైజర్, ఇమేజ్ ప్రాసెసర్, ఫీచర్ ఎక్స్‌ట్రాక్టర్ లేదా ప్రాసెసర్ వంటి ప్రీప్రాసెసింగ్ క్లాస్‌ని లోడ్ చేయండి:
446
+ ```py
447
+ >>> from transformers import AutoTokenizer
448
+
449
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
450
+ ```
451
+
452
+ 4. డేటాసెట్‌ను లోడ్ చేయండి:
453
+
454
+ ```py
455
+ >>> from datasets import load_dataset
456
+
457
+ >>> dataset = load_dataset("rotten_tomatoes") # doctest: +IGNORE_RESULT
458
+ ```
459
+
460
+ 5. డేటాసెట్‌ను టోకనైజ్ చేయడానికి ఒక ఫంక్షన్‌ను సృష్టించండి:
461
+
462
+ ```py
463
+ >>> def tokenize_dataset(dataset):
464
+ ... return tokenizer(dataset["text"])
465
+ ```
466
+
467
+ ఆపై దానిని [`~datasets.Dataset.map`]తో మొత్తం డేటాసెట్‌లో వర్తింపజేయండి:
468
+
469
+ ```py
470
+ >>> dataset = dataset.map(tokenize_dataset, batched=True)
471
+ ```
472
+
473
+ 6. మీ డేటాసెట్ నుండి ఉదాహరణల సమూహాన్ని సృష్టించడానికి [`DataCollatorWithPadding`]:
474
+
475
+ ```py
476
+ >>> from transformers import DataCollatorWithPadding
477
+
478
+ >>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
479
+ ```
480
+
481
+ ఇప్పుడు ఈ తరగతులన్నింటినీ [`Trainer`]లో సేకరించండి:
482
+
483
+ ```py
484
+ >>> from transformers import Trainer
485
+
486
+ >>> trainer = Trainer(
487
+ ... model=model,
488
+ ... args=training_args,
489
+ ... train_dataset=dataset["train"],
490
+ ... eval_dataset=dataset["test"],
491
+ ... processing_class=tokenizer,
492
+ ... data_collator=data_collator,
493
+ ... ) # doctest: +SKIP
494
+ ```
495
+
496
+ మీరు సిద్ధంగా ఉన్నప్పుడు, శిక్షణను ప్రారంభించడానికి [`~Trainer.train`]కి కాల్ చేయండి:
497
+
498
+ ```py
499
+ >>> trainer.train() # doctest: +SKIP
500
+ ```
501
+
502
+ <Tip>
503
+
504
+ సీక్వెన్స్-టు-సీక్వెన్స్ మోడల్‌ని ఉపయోగించే - అనువాదం లేదా సారాంశం వంటి పనుల కోసం, బదులుగా [`Seq2SeqTrainer`] మరియు [`Seq2SeqTrainingArguments`] తరగతులను ఉపయోగించండి.
505
+
506
+ </Tip>
507
+
508
+ మీరు [`Trainer`] లోపల ఉన్న పద్ధతులను ఉపవర్గీకరించడం ద్వారా శిక్షణ లూప్ ప్రవర్తనను అనుకూలీకరించవచ్చు. ఇది లాస్ ఫంక్షన్, ఆప్టిమైజర్ మరియు షెడ్యూలర్ వంటి లక్షణాలను అనుకూలీకరించడానికి మిమ్మల్ని అనుమతిస్తుంది. ఉపవర్గీకరించబడే పద్ధతుల కోసం [`Trainer`] సూచనను పరిశీలించండి.
509
+
510
+ శిక్షణ లూప్‌ను అనుకూలీకరించడానికి మరొక మార్గం [కాల్‌బ్యాక్‌లు](./main_classes/callback). మీరు ఇతర లైబ్రరీలతో అనుసంధానం చేయడానికి కాల్‌బ్యాక్‌లను ఉపయోగించవచ్చు మరియు పురోగతిపై నివేదించడానికి శిక్షణ లూప్‌ను తనిఖీ చేయవచ్చు లేదా శిక్షణను ముందుగానే ఆపవచ్చు. శిక్షణ లూప్‌లోనే కాల్‌బ్యాక్‌లు దేనినీ సవరించవు. లాస్ ఫంక్షన్ వంటివాటిని అనుకూలీకరించడానికి, మీరు బదులుగా [`Trainer`]ని ఉపవర్గం చేయాలి.
511
+
512
+ ## TensorFlowతో శిక్షణ పొందండి
513
+
514
+ అన్ని మోడల్‌లు ప్రామాణికమైన [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model) కాబట్టి వాటిని [Keras]తో TensorFlowలో శిక్షణ పొందవచ్చు(https: //keras.io/) API. 🤗 ట్రాన్స్‌ఫార్మర్‌లు మీ డేటాసెట్‌ని సులభంగా `tf.data.Dataset`గా లోడ్ చేయడానికి [`~TFPreTrainedModel.prepare_tf_dataset`] పద్ధతిని అందజేస్తుంది కాబట్టి మీరు వెంటనే Keras' [`compile`](https://keras.io/api/models/model_training_apis/#compile-method) మరియు [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) పద్ధతులు.
515
+
516
+ 1. మీరు [`TFPreTrainedModel`] లేదా [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model)తో ప్రారంభిస్తారు:
517
+ ```py
518
+ >>> from transformers import TFAutoModelForSequenceClassification
519
+
520
+ >>> model = TFAutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased")
521
+ ```
522
+
523
+ 2. టోకెనైజర్, ఇమేజ్ ప్రాసెసర్, ఫీచర్ ఎక్స్‌ట్రాక్టర్ లేదా ప్రాసెసర్ వంటి ప్రీప్రాసెసింగ్ క్లాస్‌ని లోడ్ చేయండి:
524
+
525
+ ```py
526
+ >>> from transformers import AutoTokenizer
527
+
528
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
529
+ ```
530
+
531
+ 3. డేటాసెట్‌ను టోకనైజ్ చేయడానికి ఒక ఫంక్షన్‌ను సృష్టించండి:
532
+
533
+ ```py
534
+ >>> def tokenize_dataset(dataset):
535
+ ... return tokenizer(dataset["text"]) # doctest: +SKIP
536
+ ```
537
+
538
+ 4. [`~datasets.Dataset.map`]తో మొత్తం డేటాసెట్‌పై టోకెనైజర్‌ని వర్తింపజేయి, ఆపై డేటాసెట్ మరియు టోకెనైజర్‌ను [`~TFPreTrainedModel.prepare_tf_dataset`]కి పంపండి. మీరు కావాలనుకుంటే బ్యాచ్ పరిమాణాన్ని కూడా మార్చవచ్చు మరియు డేటాసెట్‌ను ఇక్కడ షఫుల్ చేయవచ్చు:
539
+ ```py
540
+ >>> dataset = dataset.map(tokenize_dataset) # doctest: +SKIP
541
+ >>> tf_dataset = model.prepare_tf_dataset(
542
+ ... dataset["train"], batch_size=16, shuffle=True, tokenizer=tokenizer
543
+ ... ) # doctest: +SKIP
544
+ ```
545
+
546
+ 5. మీరు సిద్ధంగా ఉన్నప్పుడు, శిక్షణను ప్రారంభించడానికి మీరు `కంపైల్` మరియు `ఫిట్`కి కాల్ చేయవచ్చు. ట్రాన్స్‌ఫార్మర్స్ మోడల్స్ అన్నీ డిఫాల్ట్ టాస్క్-సంబంధిత లాస్ ఫంక్షన్‌ని కలిగి ఉన్నాయని గుర్తుంచుకోండి, కాబట్టి మీరు కోరుకునే వరకు మీరు ఒకదానిని పేర్కొనవలసిన అవసరం లేదు:
547
+
548
+ ```py
549
+ >>> from tensorflow.keras.optimizers import Adam
550
+
551
+ >>> model.compile(optimizer=Adam(3e-5)) # No loss argument!
552
+ >>> model.fit(tf_dataset) # doctest: +SKIP
553
+ ```
554
+
555
+ ## తరవాత ఏంటి?
556
+
557
+ ఇప్పుడు మీరు 🤗 ట్రాన్స్‌ఫార్మర్స్ త్వరిత పర్యటనను పూర్తి చేసారు, మా గైడ్‌లను తనిఖీ చేయండి మరియు అనుకూల మోడల్‌ను వ్రాయడం, టాస్క్ కోసం మోడల్‌ను చక్కగా తీర్చిదిద్దడం మరియు స్క్రిప్ట్‌తో మోడల్‌కు శిక్షణ ఇవ్వడం వంటి మరింత నిర్దిష్టమైన పనులను ఎలా చేయాలో తెలుసుకోండి. 🤗 ట్రాన్స్‌ఫార్మర్స్ కోర్ కాన్సెప్ట్‌ల గురించి మరింత తెలుసుకోవడానికి మీకు ఆసక్తి ఉంటే, ఒక కప్పు కాఫీ తాగి, మా కాన్సెప్టువల్ గైడ్‌లను చూడండి!
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/tr/_toctree.yml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ - sections:
2
+ - local: index
3
+ title: 🤗 Transformers
4
+ title: Get started
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/tr/index.md ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Telif Hakkı 2020 The HuggingFace Ekibi. Tüm hakları saklıdır.
2
+
3
+ Apache Lisansı, Sürüm 2.0 (Lisans); bu dosyayı yürürlükteki yasalara uygun bir şekilde kullanabilirsiniz. Lisansın bir kopyasını aşağıdaki adresten alabilirsiniz.
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ Lisansa tabi olmayan durumlarda veya yazılı anlaşma olmadıkça, Lisans kapsamında dağıtılan yazılım, herhangi bir türde (açık veya zımni) garanti veya koşul olmaksızın, "OLDUĞU GİBİ" ESASINA GÖRE dağıtılır. Lisans hükümleri, özel belirli dil kullanımı, yetkileri ve kısıtlamaları belirler.
8
+
9
+ ⚠️ Bu dosya Markdown biçimindedir, ancak belge oluşturucumuz için özgü sözdizimleri içerir (MDX gibi) ve muhtemelen Markdown görüntüleyicinizde düzgün bir şekilde görüntülenmeyebilir.
10
+ -->
11
+
12
+ # 🤗 Transformers
13
+
14
+ [PyTorch](https://pytorch.org/), [TensorFlow](https://www.tensorflow.org/) ve [JAX](https://jax.readthedocs.io/en/latest/) için son teknoloji makine öğrenimi.
15
+
16
+ 🤗 Transformers, güncel önceden eğitilmiş (pretrained) modelleri indirmenizi ve eğitmenizi kolaylaştıran API'ler ve araçlar sunar. Önceden eğitilmiş modeller kullanarak, hesaplama maliyetlerinizi ve karbon ayak izinizi azaltabilir, ve sıfırdan bir modeli eğitmek için gereken zaman ve kaynaklardan tasarruf edebilirsiniz. Bu modeller farklı modalitelerde ortak görevleri destekler. Örneğin:
17
+
18
+ 📝 **Doğal Dil İşleme**: metin sınıflandırma, adlandırılmış varlık tanıma, soru cevaplama, dil modelleme, özetleme, çeviri, çoktan seçmeli ve metin oluşturma.<br>
19
+ 🖼️ **Bilgisayarlı Görü**: görüntü sınıflandırma, nesne tespiti ve bölümleme (segmentation).<br>
20
+ 🗣️ **Ses**: otomatik konuşma tanıma ve ses sınıflandırma.<br>
21
+ 🐙 **Çoklu Model**: tablo soru cevaplama, optik karakter tanıma, taranmış belgelerden bilgi çıkarma, video sınıflandırma ve görsel soru cevaplama.
22
+
23
+ 🤗 Transformers, PyTorch, TensorFlow ve JAX arasında çerçeve (framework) uyumluluğu sağlar. Bu, bir modelin yaşam döngüsünün her aşamasında farklı bir çerçeve kullanma esnekliği sunar; bir çerçevede üç satır kodla bir modeli eğitebilir ve başka bir çerçevede tahminleme için kullanabilirsiniz. Modeller ayrıca üretim ortamlarında kullanılmak üzere ONNX ve TorchScript gibi bir formata aktarılabilir.
24
+
25
+ Büyüyen topluluğa [Hub](https://huggingface.co/models), [Forum](https://discuss.huggingface.co/) veya [Discord](https://discord.com/invite/JfAtkvEtRb) üzerinden katılabilirsiniz!
26
+
27
+ ## Hugging Face ekibinden özel destek arıyorsanız
28
+
29
+ <a target="_blank" href="https://huggingface.co/support">
30
+ <img alt="HuggingFace Uzman Hızlandırma Programı" src="https://cdn-media.huggingface.co/marketing/transformers/new-support-improved.png" style="width: 100%; max-width: 600px; border: 1px solid #eee; border-radius: 4px; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);">
31
+ </a>
32
+
33
+ ## İçindekiler
34
+
35
+ Dokümantasyon, beş bölüme ayrılmıştır:
36
+
37
+ - **BAŞLARKEN**, kütüphanenin hızlı bir turunu ve çalışmaya başlamak için kurulum talimatlarını sağlar.
38
+ - **ÖĞRETİCİLER**, başlangıç yapmak için harika bir yerdir. Bu bölüm, kütüphane kullanmaya başlamak için ihtiyacınız olan temel becerileri kazanmanıza yardımcı olacaktır.
39
+ - **NASIL YAPILIR KILAVUZLARI**, önceden eğitilmiş bir modele dil modellemesi için ince ayar (fine-tuning) yapmak veya özel bir model yazmak, ve paylaşmak gibi belirli bir hedefe nasıl ulaşılacağını gösterir.
40
+ - **KAVRAMSAL REHBERLER**, modellerin, görevlerin ve 🤗 Transformers tasarım felsefesinin temel kavramları ve fikirleri hakkında daha fazla tartışma ve açıklama sunar.
41
+ - **API** tüm sınıfları (class) ve fonksiyonları (functions) açıklar:
42
+
43
+ - **ANA SINIFLAR**, yapılandırma, model, tokenizer ve pipeline gibi en önemli sınıfları (classes) ayrıntılandırır.
44
+ - **MODELLER**, kütüphanede kullanılan her modelle ilgili sınıfları ve fonksiyonları detaylı olarak inceler.
45
+ - **DAHİLİ YARDIMCILAR**, kullanılan yardımcı sınıfları ve fonksiyonları detaylı olarak inceler.
46
+
47
+ ## Desteklenen Modeller ve Çerçeveler
48
+
49
+ Aşağıdaki tablo, her bir model için kütüphanede yer alan mevcut desteği temsil etmektedir. Her bir model için bir Python tokenizer'ına ("slow" olarak adlandırılır) sahip olup olmadıkları, 🤗 Tokenizers kütüphanesi tarafından desteklenen hızlı bir tokenizer'a sahip olup olmadıkları, Jax (Flax aracılığıyla), PyTorch ve/veya TensorFlow'da destek olup olmadıklarını göstermektedir.
50
+
51
+ <!--This table is updated automatically from the auto modules with _make fix-copies_. Do not update manually!-->
52
+
53
+ | Model | PyTorch support | TensorFlow support | Flax Support |
54
+ |:------------------------------------------------------------------------:|:---------------:|:------------------:|:------------:|
55
+ | [ALBERT](model_doc/albert) | ✅ | ✅ | ✅ |
56
+ | [ALIGN](model_doc/align) | ✅ | ❌ | ❌ |
57
+ | [AltCLIP](model_doc/altclip) | ✅ | ❌ | ❌ |
58
+ | [Audio Spectrogram Transformer](model_doc/audio-spectrogram-transformer) | ✅ | ❌ | ❌ |
59
+ | [Autoformer](model_doc/autoformer) | ✅ | ❌ | ❌ |
60
+ | [Bark](model_doc/bark) | ✅ | ❌ | ❌ |
61
+ | [BART](model_doc/bart) | ✅ | ✅ | ✅ |
62
+ | [BARThez](model_doc/barthez) | ✅ | ✅ | ✅ |
63
+ | [BARTpho](model_doc/bartpho) | ✅ | ✅ | ✅ |
64
+ | [BEiT](model_doc/beit) | ✅ | ❌ | ✅ |
65
+ | [BERT](model_doc/bert) | ✅ | ✅ | ✅ |
66
+ | [Bert Generation](model_doc/bert-generation) | ✅ | ❌ | ❌ |
67
+ | [BertJapanese](model_doc/bert-japanese) | ✅ | ✅ | ✅ |
68
+ | [BERTweet](model_doc/bertweet) | ✅ | ✅ | ✅ |
69
+ | [BigBird](model_doc/big_bird) | ✅ | ❌ | ✅ |
70
+ | [BigBird-Pegasus](model_doc/bigbird_pegasus) | ✅ | ❌ | ❌ |
71
+ | [BioGpt](model_doc/biogpt) | ✅ | ❌ | ❌ |
72
+ | [BiT](model_doc/bit) | ✅ | ❌ | ❌ |
73
+ | [Blenderbot](model_doc/blenderbot) | ✅ | ✅ | ✅ |
74
+ | [BlenderbotSmall](model_doc/blenderbot-small) | ✅ | ✅ | ✅ |
75
+ | [BLIP](model_doc/blip) | ✅ | ✅ | ❌ |
76
+ | [BLIP-2](model_doc/blip-2) | ✅ | ❌ | ❌ |
77
+ | [BLOOM](model_doc/bloom) | ✅ | ❌ | ✅ |
78
+ | [BORT](model_doc/bort) | ✅ | ✅ | ✅ |
79
+ | [BridgeTower](model_doc/bridgetower) | ✅ | ❌ | ❌ |
80
+ | [BROS](model_doc/bros) | ✅ | ❌ | ❌ |
81
+ | [ByT5](model_doc/byt5) | ✅ | ✅ | ✅ |
82
+ | [CamemBERT](model_doc/camembert) | ✅ | ✅ | ❌ |
83
+ | [CANINE](model_doc/canine) | ✅ | ❌ | ❌ |
84
+ | [Chinese-CLIP](model_doc/chinese_clip) | ✅ | ❌ | ❌ |
85
+ | [CLAP](model_doc/clap) | ✅ | ❌ | ❌ |
86
+ | [CLIP](model_doc/clip) | ✅ | ✅ | ✅ |
87
+ | [CLIPSeg](model_doc/clipseg) | ✅ | ❌ | ❌ |
88
+ | [CodeGen](model_doc/codegen) | ✅ | ❌ | ❌ |
89
+ | [CodeLlama](model_doc/code_llama) | ✅ | ❌ | ❌ |
90
+ | [Conditional DETR](model_doc/conditional_detr) | ✅ | ❌ | ❌ |
91
+ | [ConvBERT](model_doc/convbert) | ✅ | ✅ | ❌ |
92
+ | [ConvNeXT](model_doc/convnext) | ✅ | ✅ | ❌ |
93
+ | [ConvNeXTV2](model_doc/convnextv2) | ✅ | ❌ | ❌ |
94
+ | [CPM](model_doc/cpm) | ✅ | ✅ | ✅ |
95
+ | [CPM-Ant](model_doc/cpmant) | ✅ | ❌ | ❌ |
96
+ | [CTRL](model_doc/ctrl) | ✅ | ✅ | ❌ |
97
+ | [CvT](model_doc/cvt) | ✅ | ✅ | ❌ |
98
+ | [Data2VecAudio](model_doc/data2vec) | ✅ | ❌ | ❌ |
99
+ | [Data2VecText](model_doc/data2vec) | ✅ | ❌ | ❌ |
100
+ | [Data2VecVision](model_doc/data2vec) | ✅ | ✅ | ❌ |
101
+ | [DeBERTa](model_doc/deberta) | ✅ | ✅ | ❌ |
102
+ | [DeBERTa-v2](model_doc/deberta-v2) | ✅ | ✅ | ❌ |
103
+ | [Decision Transformer](model_doc/decision_transformer) | ✅ | ❌ | ❌ |
104
+ | [Deformable DETR](model_doc/deformable_detr) | ✅ | ❌ | ❌ |
105
+ | [DeiT](model_doc/deit) | ✅ | ✅ | ❌ |
106
+ | [DePlot](model_doc/deplot) | ✅ | ❌ | ❌ |
107
+ | [DETA](model_doc/deta) | ✅ | ❌ | ❌ |
108
+ | [DETR](model_doc/detr) | ✅ | ❌ | ❌ |
109
+ | [DialoGPT](model_doc/dialogpt) | ✅ | ✅ | ✅ |
110
+ | [DiNAT](model_doc/dinat) | ✅ | ❌ | ❌ |
111
+ | [DINOv2](model_doc/dinov2) | ✅ | ❌ | ❌ |
112
+ | [DistilBERT](model_doc/distilbert) | ✅ | ✅ | ✅ |
113
+ | [DiT](model_doc/dit) | ✅ | ❌ | ✅ |
114
+ | [DonutSwin](model_doc/donut) | ✅ | ❌ | ❌ |
115
+ | [DPR](model_doc/dpr) | ✅ | ✅ | ❌ |
116
+ | [DPT](model_doc/dpt) | ✅ | ❌ | ❌ |
117
+ | [EfficientFormer](model_doc/efficientformer) | ✅ | ✅ | ❌ |
118
+ | [EfficientNet](model_doc/efficientnet) | ✅ | ❌ | ❌ |
119
+ | [ELECTRA](model_doc/electra) | ✅ | ✅ | ✅ |
120
+ | [EnCodec](model_doc/encodec) | ✅ | ❌ | ❌ |
121
+ | [Encoder decoder](model_doc/encoder-decoder) | ✅ | ✅ | ✅ |
122
+ | [ERNIE](model_doc/ernie) | ✅ | ❌ | ❌ |
123
+ | [ErnieM](model_doc/ernie_m) | ✅ | ❌ | ❌ |
124
+ | [ESM](model_doc/esm) | ✅ | ✅ | ❌ |
125
+ | [FairSeq Machine-Translation](model_doc/fsmt) | ✅ | ❌ | ❌ |
126
+ | [Falcon](model_doc/falcon) | ✅ | ❌ | ❌ |
127
+ | [FLAN-T5](model_doc/flan-t5) | ✅ | ✅ | ✅ |
128
+ | [FLAN-UL2](model_doc/flan-ul2) | ✅ | ✅ | ✅ |
129
+ | [FlauBERT](model_doc/flaubert) | ✅ | ✅ | ❌ |
130
+ | [FLAVA](model_doc/flava) | ✅ | ❌ | ❌ |
131
+ | [FNet](model_doc/fnet) | ✅ | ❌ | ❌ |
132
+ | [FocalNet](model_doc/focalnet) | ✅ | ❌ | ❌ |
133
+ | [Funnel Transformer](model_doc/funnel) | ✅ | ✅ | ❌ |
134
+ | [Fuyu](model_doc/fuyu) | ✅ | ❌ | ❌ |
135
+ | [GIT](model_doc/git) | ✅ | ❌ | ❌ |
136
+ | [GLPN](model_doc/glpn) | ✅ | ❌ | ❌ |
137
+ | [GPT Neo](model_doc/gpt_neo) | ✅ | ❌ | ✅ |
138
+ | [GPT NeoX](model_doc/gpt_neox) | ✅ | ❌ | ❌ |
139
+ | [GPT NeoX Japanese](model_doc/gpt_neox_japanese) | ✅ | ❌ | ❌ |
140
+ | [GPT-J](model_doc/gptj) | ✅ | ✅ | ✅ |
141
+ | [GPT-Sw3](model_doc/gpt-sw3) | ✅ | ✅ | ✅ |
142
+ | [GPTBigCode](model_doc/gpt_bigcode) | ✅ | ❌ | ❌ |
143
+ | [GPTSAN-japanese](model_doc/gptsan-japanese) | ✅ | ❌ | ❌ |
144
+ | [Graphormer](model_doc/graphormer) | ✅ | ❌ | ❌ |
145
+ | [GroupViT](model_doc/groupvit) | ✅ | ✅ | ❌ |
146
+ | [HerBERT](model_doc/herbert) | ✅ | ✅ | ✅ |
147
+ | [Hubert](model_doc/hubert) | ✅ | ✅ | ❌ |
148
+ | [I-BERT](model_doc/ibert) | ✅ | ❌ | ❌ |
149
+ | [IDEFICS](model_doc/idefics) | ✅ | ❌ | ❌ |
150
+ | [ImageGPT](model_doc/imagegpt) | ✅ | ❌ | ❌ |
151
+ | [Informer](model_doc/informer) | ✅ | ❌ | ❌ |
152
+ | [InstructBLIP](model_doc/instructblip) | ✅ | ❌ | ❌ |
153
+ | [Jukebox](model_doc/jukebox) | ✅ | ❌ | ❌ |
154
+ | [LayoutLM](model_doc/layoutlm) | ✅ | ✅ | ❌ |
155
+ | [LayoutLMv2](model_doc/layoutlmv2) | ✅ | ❌ | ❌ |
156
+ | [LayoutLMv3](model_doc/layoutlmv3) | ✅ | ✅ | ❌ |
157
+ | [LayoutXLM](model_doc/layoutxlm) | ✅ | ❌ | ❌ |
158
+ | [LED](model_doc/led) | ✅ | ✅ | ❌ |
159
+ | [LeViT](model_doc/levit) | ✅ | ❌ | ❌ |
160
+ | [LiLT](model_doc/lilt) | ✅ | ❌ | ❌ |
161
+ | [LLaMA](model_doc/llama) | ✅ | ❌ | ❌ |
162
+ | [Llama2](model_doc/llama2) | ✅ | ❌ | ❌ |
163
+ | [Longformer](model_doc/longformer) | ✅ | ✅ | ❌ |
164
+ | [LongT5](model_doc/longt5) | ✅ | ❌ | ✅ |
165
+ | [LUKE](model_doc/luke) | ✅ | ❌ | ❌ |
166
+ | [LXMERT](model_doc/lxmert) | ✅ | ✅ | ❌ |
167
+ | [M-CTC-T](model_doc/mctct) | ✅ | ❌ | ❌ |
168
+ | [M2M100](model_doc/m2m_100) | ✅ | ❌ | ❌ |
169
+ | [Marian](model_doc/marian) | ✅ | ✅ | ✅ |
170
+ | [MarkupLM](model_doc/markuplm) | ✅ | ❌ | ❌ |
171
+ | [Mask2Former](model_doc/mask2former) | ✅ | ❌ | ❌ |
172
+ | [MaskFormer](model_doc/maskformer) | ✅ | ❌ | ❌ |
173
+ | [MatCha](model_doc/matcha) | ✅ | ❌ | ❌ |
174
+ | [mBART](model_doc/mbart) | ✅ | ✅ | ✅ |
175
+ | [mBART-50](model_doc/mbart50) | ✅ | ✅ | ✅ |
176
+ | [MEGA](model_doc/mega) | ✅ | ❌ | ❌ |
177
+ | [Megatron-BERT](model_doc/megatron-bert) | ✅ | ❌ | ❌ |
178
+ | [Megatron-GPT2](model_doc/megatron_gpt2) | ✅ | ✅ | ✅ |
179
+ | [MGP-STR](model_doc/mgp-str) | ✅ | ❌ | ❌ |
180
+ | [Mistral](model_doc/mistral) | ✅ | ❌ | ❌ |
181
+ | [mLUKE](model_doc/mluke) | ✅ | ❌ | ❌ |
182
+ | [MMS](model_doc/mms) | ✅ | ✅ | ✅ |
183
+ | [MobileBERT](model_doc/mobilebert) | ✅ | ✅ | ❌ |
184
+ | [MobileNetV1](model_doc/mobilenet_v1) | ✅ | ❌ | ❌ |
185
+ | [MobileNetV2](model_doc/mobilenet_v2) | ✅ | ❌ | ❌ |
186
+ | [MobileViT](model_doc/mobilevit) | ✅ | ✅ | ❌ |
187
+ | [MobileViTV2](model_doc/mobilevitv2) | ✅ | ❌ | ❌ |
188
+ | [MPNet](model_doc/mpnet) | ✅ | ✅ | ❌ |
189
+ | [MPT](model_doc/mpt) | ✅ | ❌ | ❌ |
190
+ | [MRA](model_doc/mra) | ✅ | ❌ | ❌ |
191
+ | [MT5](model_doc/mt5) | ✅ | ✅ | ✅ |
192
+ | [MusicGen](model_doc/musicgen) | ✅ | ❌ | ❌ |
193
+ | [MVP](model_doc/mvp) | ✅ | ❌ | ❌ |
194
+ | [NAT](model_doc/nat) | ✅ | ❌ | ❌ |
195
+ | [Nezha](model_doc/nezha) | ✅ | ❌ | ❌ |
196
+ | [NLLB](model_doc/nllb) | ✅ | ❌ | ❌ |
197
+ | [NLLB-MOE](model_doc/nllb-moe) | ✅ | ❌ | ❌ |
198
+ | [Nougat](model_doc/nougat) | ✅ | ✅ | ✅ |
199
+ | [Nyströmformer](model_doc/nystromformer) | ✅ | ❌ | ❌ |
200
+ | [OneFormer](model_doc/oneformer) | ✅ | ❌ | ❌ |
201
+ | [OpenAI GPT](model_doc/openai-gpt) | ✅ | ✅ | ❌ |
202
+ | [OpenAI GPT-2](model_doc/gpt2) | ✅ | ✅ | ✅ |
203
+ | [OpenLlama](model_doc/open-llama) | ✅ | ❌ | ❌ |
204
+ | [OPT](model_doc/opt) | ✅ | ✅ | ✅ |
205
+ | [OWL-ViT](model_doc/owlvit) | ✅ | ❌ | ❌ |
206
+ | [OWLv2](model_doc/owlv2) | ✅ | ❌ | ❌ |
207
+ | [Pegasus](model_doc/pegasus) | ✅ | ✅ | ✅ |
208
+ | [PEGASUS-X](model_doc/pegasus_x) | ✅ | ❌ | ❌ |
209
+ | [Perceiver](model_doc/perceiver) | ✅ | ❌ | ❌ |
210
+ | [Persimmon](model_doc/persimmon) | ✅ | ❌ | ❌ |
211
+ | [PhoBERT](model_doc/phobert) | ✅ | ✅ | ✅ |
212
+ | [Pix2Struct](model_doc/pix2struct) | ✅ | ❌ | ❌ |
213
+ | [PLBart](model_doc/plbart) | ✅ | ❌ | ❌ |
214
+ | [PoolFormer](model_doc/poolformer) | ✅ | ❌ | ❌ |
215
+ | [Pop2Piano](model_doc/pop2piano) | ✅ | ❌ | ❌ |
216
+ | [ProphetNet](model_doc/prophetnet) | ✅ | ❌ | ❌ |
217
+ | [PVT](model_doc/pvt) | ✅ | ❌ | ❌ |
218
+ | [QDQBert](model_doc/qdqbert) | ✅ | ❌ | ❌ |
219
+ | [RAG](model_doc/rag) | ✅ | ✅ | ❌ |
220
+ | [REALM](model_doc/realm) | ✅ | ❌ | ❌ |
221
+ | [Reformer](model_doc/reformer) | ✅ | ❌ | ❌ |
222
+ | [RegNet](model_doc/regnet) | ✅ | ✅ | ✅ |
223
+ | [RemBERT](model_doc/rembert) | ✅ | ✅ | ❌ |
224
+ | [ResNet](model_doc/resnet) | ✅ | ✅ | ✅ |
225
+ | [RetriBERT](model_doc/retribert) | ✅ | ❌ | ❌ |
226
+ | [RoBERTa](model_doc/roberta) | ✅ | ✅ | ✅ |
227
+ | [RoBERTa-PreLayerNorm](model_doc/roberta-prelayernorm) | ✅ | ✅ | ✅ |
228
+ | [RoCBert](model_doc/roc_bert) | ✅ | ❌ | ❌ |
229
+ | [RoFormer](model_doc/roformer) | ✅ | ✅ | ✅ |
230
+ | [RWKV](model_doc/rwkv) | ✅ | ❌ | ❌ |
231
+ | [SAM](model_doc/sam) | ✅ | ✅ | ❌ |
232
+ | [SeamlessM4T](model_doc/seamless_m4t) | ✅ | ❌ | ❌ |
233
+ | [SegFormer](model_doc/segformer) | ✅ | ✅ | ❌ |
234
+ | [SEW](model_doc/sew) | ✅ | ❌ | ❌ |
235
+ | [SEW-D](model_doc/sew-d) | ✅ | ❌ | ❌ |
236
+ | [Speech Encoder decoder](model_doc/speech-encoder-decoder) | ✅ | ❌ | ✅ |
237
+ | [Speech2Text](model_doc/speech_to_text) | ✅ | ✅ | ❌ |
238
+ | [SpeechT5](model_doc/speecht5) | ✅ | ❌ | ❌ |
239
+ | [Splinter](model_doc/splinter) | ✅ | ❌ | ❌ |
240
+ | [SqueezeBERT](model_doc/squeezebert) | ✅ | ❌ | ❌ |
241
+ | [SwiftFormer](model_doc/swiftformer) | ✅ | ❌ | ❌ |
242
+ | [Swin Transformer](model_doc/swin) | ✅ | ✅ | ❌ |
243
+ | [Swin Transformer V2](model_doc/swinv2) | ✅ | ❌ | ❌ |
244
+ | [Swin2SR](model_doc/swin2sr) | ✅ | ❌ | ❌ |
245
+ | [SwitchTransformers](model_doc/switch_transformers) | ✅ | ❌ | ❌ |
246
+ | [T5](model_doc/t5) | ✅ | ✅ | ✅ |
247
+ | [T5v1.1](model_doc/t5v1.1) | ✅ | ✅ | ✅ |
248
+ | [Table Transformer](model_doc/table-transformer) | ✅ | ❌ | ❌ |
249
+ | [TAPAS](model_doc/tapas) | ✅ | ✅ | ❌ |
250
+ | [TAPEX](model_doc/tapex) | ✅ | ✅ | ✅ |
251
+ | [Time Series Transformer](model_doc/time_series_transformer) | ✅ | ❌ | ❌ |
252
+ | [TimeSformer](model_doc/timesformer) | ✅ | ❌ | ❌ |
253
+ | [Trajectory Transformer](model_doc/trajectory_transformer) | ✅ | ❌ | ❌ |
254
+ | [Transformer-XL](model_doc/transfo-xl) | ✅ | ✅ | ❌ |
255
+ | [TrOCR](model_doc/trocr) | ✅ | ❌ | ❌ |
256
+ | [TVLT](model_doc/tvlt) | ✅ | ❌ | ❌ |
257
+ | [UL2](model_doc/ul2) | ✅ | ✅ | ✅ |
258
+ | [UMT5](model_doc/umt5) | ✅ | ❌ | ❌ |
259
+ | [UniSpeech](model_doc/unispeech) | ✅ | ❌ | ❌ |
260
+ | [UniSpeechSat](model_doc/unispeech-sat) | ✅ | ❌ | ❌ |
261
+ | [UPerNet](model_doc/upernet) | ✅ | ❌ | ❌ |
262
+ | [VAN](model_doc/van) | ✅ | ❌ | ❌ |
263
+ | [VideoMAE](model_doc/videomae) | ✅ | ❌ | ❌ |
264
+ | [ViLT](model_doc/vilt) | ✅ | ❌ | ❌ |
265
+ | [Vision Encoder decoder](model_doc/vision-encoder-decoder) | ✅ | ✅ | ✅ |
266
+ | [VisionTextDualEncoder](model_doc/vision-text-dual-encoder) | ✅ | ✅ | ✅ |
267
+ | [VisualBERT](model_doc/visual_bert) | ✅ | ❌ | ❌ |
268
+ | [ViT](model_doc/vit) | ✅ | ✅ | ✅ |
269
+ | [ViT Hybrid](model_doc/vit_hybrid) | ✅ | ❌ | ❌ |
270
+ | [VitDet](model_doc/vitdet) | ✅ | ❌ | ❌ |
271
+ | [ViTMAE](model_doc/vit_mae) | ✅ | ✅ | ❌ |
272
+ | [ViTMatte](model_doc/vitmatte) | ✅ | ❌ | ❌ |
273
+ | [ViTMSN](model_doc/vit_msn) | ✅ | ❌ | ❌ |
274
+ | [VITS](model_doc/vits) | ✅ | ❌ | ❌ |
275
+ | [ViViT](model_doc/vivit) | ✅ | ❌ | ❌ |
276
+ | [Wav2Vec2](model_doc/wav2vec2) | ✅ | ✅ | ✅ |
277
+ | [Wav2Vec2-Conformer](model_doc/wav2vec2-conformer) | ✅ | ❌ | ❌ |
278
+ | [Wav2Vec2Phoneme](model_doc/wav2vec2_phoneme) | ✅ | ✅ | ✅ |
279
+ | [WavLM](model_doc/wavlm) | ✅ | ❌ | ❌ |
280
+ | [Whisper](model_doc/whisper) | ✅ | ✅ | ✅ |
281
+ | [X-CLIP](model_doc/xclip) | ✅ | ❌ | ❌ |
282
+ | [X-MOD](model_doc/xmod) | ✅ | ❌ | ❌ |
283
+ | [XGLM](model_doc/xglm) | ✅ | ✅ | ✅ |
284
+ | [XLM](model_doc/xlm) | ✅ | ✅ | ❌ |
285
+ | [XLM-ProphetNet](model_doc/xlm-prophetnet) | ✅ | ❌ | ❌ |
286
+ | [XLM-RoBERTa](model_doc/xlm-roberta) | ✅ | ✅ | ✅ |
287
+ | [XLM-RoBERTa-XL](model_doc/xlm-roberta-xl) | ✅ | ❌ | ❌ |
288
+ | [XLM-V](model_doc/xlm-v) | ✅ | ✅ | ✅ |
289
+ | [XLNet](model_doc/xlnet) | ✅ | ✅ | ❌ |
290
+ | [XLS-R](model_doc/xls_r) | ✅ | ✅ | ✅ |
291
+ | [XLSR-Wav2Vec2](model_doc/xlsr_wav2vec2) | ✅ | ✅ | ✅ |
292
+ | [YOLOS](model_doc/yolos) | ✅ | ❌ | ❌ |
293
+ | [YOSO](model_doc/yoso) | ✅ | ❌ | ❌ |
294
+
295
+ <!-- End table-->
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/zh/_toctree.yml ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - sections:
2
+ - local: index
3
+ title: 🤗 Transformers 简介
4
+ - local: quicktour
5
+ title: 快速上手
6
+ - local: installation
7
+ title: 安装
8
+ title: 开始使用
9
+ - sections:
10
+ - local: pipeline_tutorial
11
+ title: 使用pipelines进行推理
12
+ - local: autoclass_tutorial
13
+ title: 使用AutoClass编写可移植的代码
14
+ - local: preprocessing
15
+ title: 预处理数据
16
+ - local: training
17
+ title: 微调预训练模型
18
+ - local: run_scripts
19
+ title: 通过脚本训练模型
20
+ - local: accelerate
21
+ title: 使用🤗Accelerate进行分布式训练
22
+ - local: peft
23
+ title: 使用🤗 PEFT加载和训练adapters
24
+ - local: model_sharing
25
+ title: 分享您的模型
26
+ - local: llm_tutorial
27
+ title: 使用LLMs进行生成
28
+ title: 教程
29
+ - sections:
30
+ - isExpanded: false
31
+ sections:
32
+ - local: tasks/asr
33
+ title: 自动语音识别
34
+ - sections:
35
+ - local: fast_tokenizers
36
+ title: 使用 🤗 Tokenizers 中的分词器
37
+ - local: multilingual
38
+ title: 使用多语言模型进行推理
39
+ - local: create_a_model
40
+ title: 使用特定于模型的 API
41
+ - local: custom_models
42
+ title: 共享自定义模型
43
+ - local: chat_templating
44
+ title: 聊天模型的模板
45
+ - local: serialization
46
+ title: 导出为 ONNX
47
+ - local: tflite
48
+ title: 导出为 TFLite
49
+ - local: torchscript
50
+ title: 导出为 TorchScript
51
+ - local: gguf
52
+ title: 与 GGUF 格式的互操作性
53
+ - local: tiktoken
54
+ title: 与 Tiktoken 文件的互操作性
55
+ - local: community
56
+ title: 社区资源
57
+ title: 开发者指南
58
+ - sections:
59
+ - local: performance
60
+ title: 综述
61
+ - sections:
62
+ - local: fsdp
63
+ title: 完全分片数据并行
64
+ - local: perf_train_special
65
+ title: 在 Apple silicon 芯片上进行 PyTorch 训练
66
+ - local: perf_infer_gpu_multi
67
+ title: 多GPU推理
68
+ - local: perf_train_cpu
69
+ title: 在CPU上进行高效训练
70
+ - local: perf_hardware
71
+ title: 用于训练的定制硬件
72
+ - local: hpo_train
73
+ title: 使用Trainer API 进行超参数搜索
74
+ title: 高效训练技术
75
+ - local: big_models
76
+ title: 实例化大模型
77
+ - local: debugging
78
+ title: 问题定位及解决
79
+ - local: tf_xla
80
+ title: TensorFlow模型的XLA集成
81
+ - local: perf_torch_compile
82
+ title: 使用 `torch.compile()` 优化推理
83
+ title: 性能和可扩展性
84
+ - sections:
85
+ - local: contributing
86
+ title: 如何为 🤗 Transformers 做贡献?
87
+ - local: add_new_pipeline
88
+ title: 如何将流水线添加到 🤗 Transformers?
89
+ title: 贡献
90
+ - sections:
91
+ - local: philosophy
92
+ title: Transformers的设计理念
93
+ - local: task_summary
94
+ title: 🤗Transformers能做什么
95
+ - local: tokenizer_summary
96
+ title: 分词器的摘要
97
+ - local: attention
98
+ title: 注意力机制
99
+ - local: bertology
100
+ title: 基于BERT进行的相关研究
101
+ title: 概念指南
102
+ - sections:
103
+ - sections:
104
+ - local: main_classes/callback
105
+ title: Callbacks
106
+ - local: main_classes/configuration
107
+ title: Configuration
108
+ - local: main_classes/data_collator
109
+ title: Data Collator
110
+ - local: main_classes/keras_callbacks
111
+ title: Keras callbacks
112
+ - local: main_classes/logging
113
+ title: Logging
114
+ - local: main_classes/model
115
+ title: 模型
116
+ - local: main_classes/text_generation
117
+ title: 文本生成
118
+ - local: main_classes/onnx
119
+ title: ONNX
120
+ - local: main_classes/optimizer_schedules
121
+ title: Optimization
122
+ - local: main_classes/output
123
+ title: 模型输出
124
+ - local: main_classes/pipelines
125
+ title: Pipelines
126
+ - local: main_classes/processors
127
+ title: Processors
128
+ - local: main_classes/quantization
129
+ title: Quantization
130
+ - local: main_classes/tokenizer
131
+ title: Tokenizer
132
+ - local: main_classes/trainer
133
+ title: Trainer
134
+ - local: main_classes/deepspeed
135
+ title: DeepSpeed集成
136
+ - local: main_classes/feature_extractor
137
+ title: Feature Extractor
138
+ - local: main_classes/image_processor
139
+ title: Image Processor
140
+ title: 主要类
141
+ - sections:
142
+ - local: internal/modeling_utils
143
+ title: 自定义层和工具
144
+ - local: internal/pipelines_utils
145
+ title: pipelines工具
146
+ - local: internal/tokenization_utils
147
+ title: Tokenizers工具
148
+ - local: internal/trainer_utils
149
+ title: 训练器工具
150
+ - local: internal/generation_utils
151
+ title: 生成工具
152
+ - local: internal/image_processing_utils
153
+ title: 图像处理工具
154
+ - local: internal/audio_utils
155
+ title: 音频处理工具
156
+ - local: internal/file_utils
157
+ title: 通用工具
158
+ - local: internal/time_series_utils
159
+ title: 时序数据工具
160
+ - sections:
161
+ - local: model_doc/bert
162
+ title: BERT
163
+ title: 内部辅助工具
164
+ title: 应用程序接口 (API)
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/zh/accelerate.md ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权2023年HuggingFace团队保留所有权利。
2
+
3
+ 根据Apache许可证第2.0版(“许可证”)许可;除非符合许可证,否则您不得使用此文件。您可以在以下网址获取许可证的副本:
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 除非适用法律要求或书面同意,否则按“按原样”分发的软件,无论是明示还是暗示的,都没有任何担保或条件。请参阅许可证以了解特定语言下的权限和限制。
8
+
9
+ ⚠️ 请注意,本文件虽然使用Markdown编写,但包含了特定的语法,适用于我们的doc-builder(类似于MDX),可能无法在您的Markdown查看器中正常渲染。
10
+
11
+ -->
12
+
13
+ # 🤗 加速分布式训练
14
+
15
+ 随着模型变得越来越大,并行性已经成为在有限硬件上训练更大模型和加速训练速度的策略,增加了数个数量级。在Hugging Face,我们创建了[🤗 加速](https://huggingface.co/docs/accelerate)库,以帮助用户在任何类型的分布式设置上轻松训练🤗 Transformers模型,无论是在一台机器上的多个GPU还是在多个机器上的多个GPU。在本教程中,了解如何自定义您的原生PyTorch训练循环,以启用分布式环境中的训练。
16
+
17
+ ## 设置
18
+
19
+ 通过安装🤗 加速开始:
20
+
21
+ ```bash
22
+ pip install accelerate
23
+ ```
24
+
25
+ 然后导入并创建[`~accelerate.Accelerator`]对象。[`~accelerate.Accelerator`]将自动检测您的分布式设置类型,并初始化所有必要的训练组件。您不需要显式地将模型放在设备上。
26
+
27
+ ```py
28
+ >>> from accelerate import Accelerator
29
+
30
+ >>> accelerator = Accelerator()
31
+ ```
32
+
33
+ ## 准备加速
34
+
35
+ 下一步是将所有相关的训练对象传递给[`~accelerate.Accelerator.prepare`]方法。这包括您的训练和评估DataLoader、一个模型和一个优化器:
36
+
37
+ ```py
38
+ >>> train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare(
39
+ ... train_dataloader, eval_dataloader, model, optimizer
40
+ ... )
41
+ ```
42
+
43
+ ## 反向传播
44
+
45
+ 最后一步是用🤗 加速的[`~accelerate.Accelerator.backward`]方法替换训练循环中的典型`loss.backward()`:
46
+
47
+ ```py
48
+ >>> for epoch in range(num_epochs):
49
+ ... for batch in train_dataloader:
50
+ ... outputs = model(**batch)
51
+ ... loss = outputs.loss
52
+ ... accelerator.backward(loss)
53
+
54
+ ... optimizer.step()
55
+ ... lr_scheduler.step()
56
+ ... optimizer.zero_grad()
57
+ ... progress_bar.update(1)
58
+ ```
59
+
60
+ 如您在下面的代码中所见,您只需要添加四行额外的代码到您的训练循环中即可启用分布式训练!
61
+
62
+ ```diff
63
+ + from accelerate import Accelerator
64
+ from transformers import AdamW, AutoModelForSequenceClassification, get_scheduler
65
+
66
+ + accelerator = Accelerator()
67
+
68
+ model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2)
69
+ optimizer = AdamW(model.parameters(), lr=3e-5)
70
+
71
+ - device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
72
+ - model.to(device)
73
+
74
+ + train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare(
75
+ + train_dataloader, eval_dataloader, model, optimizer
76
+ + )
77
+
78
+ num_epochs = 3
79
+ num_training_steps = num_epochs * len(train_dataloader)
80
+ lr_scheduler = get_scheduler(
81
+ "linear",
82
+ optimizer=optimizer,
83
+ num_warmup_steps=0,
84
+ num_training_steps=num_training_steps
85
+ )
86
+
87
+ progress_bar = tqdm(range(num_training_steps))
88
+
89
+ model.train()
90
+ for epoch in range(num_epochs):
91
+ for batch in train_dataloader:
92
+ - batch = {k: v.to(device) for k, v in batch.items()}
93
+ outputs = model(**batch)
94
+ loss = outputs.loss
95
+ - loss.backward()
96
+ + accelerator.backward(loss)
97
+
98
+ optimizer.step()
99
+ lr_scheduler.step()
100
+ optimizer.zero_grad()
101
+ progress_bar.update(1)
102
+ ```
103
+
104
+ ## 训练
105
+
106
+ 在添加了相关代码行后,可以在脚本或笔记本(如Colaboratory)中启动训练。
107
+
108
+ ### 用脚本训练
109
+
110
+ 如果您从脚本中运行训练,请运行以下命令以创建和保存配置文件:
111
+
112
+ ```bash
113
+ accelerate config
114
+ ```
115
+
116
+ 然后使用以下命令启动训练:
117
+
118
+ ```bash
119
+ accelerate launch train.py
120
+ ```
121
+
122
+ ### 用笔记本训练
123
+
124
+ 🤗 加速还可以在笔记本中运行,如果您计划使用Colaboratory的TPU,则可在其中运行。将负责训练的所有代码包装在一个函数中,并将其传递给[`~accelerate.notebook_launcher`]:
125
+
126
+ ```py
127
+ >>> from accelerate import notebook_launcher
128
+
129
+ >>> notebook_launcher(training_function)
130
+ ```
131
+
132
+ 有关🤗 加速及其丰富功能的更多信息,请参阅[文档](https://huggingface.co/docs/accelerate)。
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/zh/add_new_pipeline.md ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--
2
+ Copyright 2020 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5
+ the License. You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+ -->
15
+
16
+ # 如何创建自定义流水线?
17
+
18
+ 在本指南中,我们将演示如何创建一个自定义流水线并分享到 [Hub](https://hf.co/models),或将其添加到 🤗 Transformers 库中。
19
+
20
+ 首先,你需要决定流水线将能够接受的原始条目。它可以是字符串、原始字节、字典或任何看起来最可能是期望的输入。
21
+ 尽量保持输入为纯 Python 语言,因为这样可以更容易地实现兼容性(甚至通过 JSON 在其他语言之间)。
22
+ 这些将是流水线 (`preprocess`) 的 `inputs`。
23
+
24
+ 然后定义 `outputs`。与 `inputs` 相同的策略。越简单越好。这些将是 `postprocess` 方法的输出。
25
+
26
+ 首先继承基类 `Pipeline`,其中包含实现 `preprocess`、`_forward`、`postprocess` 和 `_sanitize_parameters` 所需的 4 个方法。
27
+
28
+ ```python
29
+ from transformers import Pipeline
30
+
31
+
32
+ class MyPipeline(Pipeline):
33
+ def _sanitize_parameters(self, **kwargs):
34
+ preprocess_kwargs = {}
35
+ if "maybe_arg" in kwargs:
36
+ preprocess_kwargs["maybe_arg"] = kwargs["maybe_arg"]
37
+ return preprocess_kwargs, {}, {}
38
+
39
+ def preprocess(self, inputs, maybe_arg=2):
40
+ model_input = Tensor(inputs["input_ids"])
41
+ return {"model_input": model_input}
42
+
43
+ def _forward(self, model_inputs):
44
+ # model_inputs == {"model_input": model_input}
45
+ outputs = self.model(**model_inputs)
46
+ # Maybe {"logits": Tensor(...)}
47
+ return outputs
48
+
49
+ def postprocess(self, model_outputs):
50
+ best_class = model_outputs["logits"].softmax(-1)
51
+ return best_class
52
+ ```
53
+
54
+ 这种分解的结构旨在为 CPU/GPU 提供相对无缝的支持,同时支持在不同线程上对 CPU 进行预处理/后处理。
55
+
56
+ `preprocess` 将接受最初定义的输入,并将其转换为可供模型输入的内容。它可能包含更多信息,通常是一个 `Dict`。
57
+
58
+ `_forward` 是实现细节,不应直接调用。`forward` 是首选的调用方法,因为它包含保障措施,以确保一切都在预期的设备上运作。
59
+ 如果任何内容与实际模型相关,它应该属于 `_forward` 方法,其他内容应该在 preprocess/postprocess 中。
60
+
61
+ `postprocess` 方法将接受 `_forward` 的输出,并将其转换为之前确定的最终输出。
62
+
63
+ `_sanitize_parameters` 存在是为了允许用户在任何时候传递任何参数,无论是在初始化时 `pipeline(...., maybe_arg=4)`
64
+ 还是在调用时 `pipe = pipeline(...); output = pipe(...., maybe_arg=4)`。
65
+
66
+ `_sanitize_parameters` 的返回值是将直接传递给 `preprocess`、`_forward` 和 `postprocess` 的 3 个关键字参数字典。
67
+ 如果调用方没有使用任何额外参数调用,则不要填写任何内容。这样可以保留函数定义中的默认参数,这总是更"自然"的。
68
+
69
+ 在分类任务中,一个经典的例子是在后处理中使用 `top_k` 参数。
70
+
71
+ ```python
72
+ >>> pipe = pipeline("my-new-task")
73
+ >>> pipe("This is a test")
74
+ [{"label": "1-star", "score": 0.8}, {"label": "2-star", "score": 0.1}, {"label": "3-star", "score": 0.05}
75
+ {"label": "4-star", "score": 0.025}, {"label": "5-star", "score": 0.025}]
76
+
77
+ >>> pipe("This is a test", top_k=2)
78
+ [{"label": "1-star", "score": 0.8}, {"label": "2-star", "score": 0.1}]
79
+ ```
80
+
81
+ 为了实现这一点,我们将更新我们的 `postprocess` 方法,将默认参数设置为 `5`,
82
+ 并编辑 `_sanitize_parameters` 方法,以允许这个新参数。
83
+
84
+ ```python
85
+ def postprocess(self, model_outputs, top_k=5):
86
+ best_class = model_outputs["logits"].softmax(-1)
87
+ # Add logic to handle top_k
88
+ return best_class
89
+
90
+
91
+ def _sanitize_parameters(self, **kwargs):
92
+ preprocess_kwargs = {}
93
+ if "maybe_arg" in kwargs:
94
+ preprocess_kwargs["maybe_arg"] = kwargs["maybe_arg"]
95
+
96
+ postprocess_kwargs = {}
97
+ if "top_k" in kwargs:
98
+ postprocess_kwargs["top_k"] = kwargs["top_k"]
99
+ return preprocess_kwargs, {}, postprocess_kwargs
100
+ ```
101
+
102
+ 尽量保持简单输入/输出,最好是可 JSON 序列化的,因为这样可以使流水线的使用非常简单,而不需要用户了解新的对象类型。
103
+ 通常也相对常见地支持许多不同类型的参数以便使用(例如音频文件,可以是文件名、URL 或纯字节)。
104
+
105
+ ## 将其添加到支持的任务列表中
106
+
107
+ 要将你的 `new-task` 注册到支持的任务列表中,你需要将其添加到 `PIPELINE_REGISTRY` 中:
108
+
109
+ ```python
110
+ from transformers.pipelines import PIPELINE_REGISTRY
111
+
112
+ PIPELINE_REGISTRY.register_pipeline(
113
+ "new-task",
114
+ pipeline_class=MyPipeline,
115
+ pt_model=AutoModelForSequenceClassification,
116
+ )
117
+ ```
118
+
119
+ 如果需要,你可以指定一个默认模型,此时它应该带有一个特定的修订版本(可以是分支名称或提交哈希,这里我们使用了 `"abcdef"`),以及类型:
120
+
121
+ ```python
122
+ PIPELINE_REGISTRY.register_pipeline(
123
+ "new-task",
124
+ pipeline_class=MyPipeline,
125
+ pt_model=AutoModelForSequenceClassification,
126
+ default={"pt": ("user/awesome_model", "abcdef")},
127
+ type="text", # current support type: text, audio, image, multimodal
128
+ )
129
+ ```
130
+
131
+ ## 在 Hub 上分享你的流水线
132
+
133
+ 要在 Hub 上分享你的自定义流水线,你只需要将 `Pipeline` 子类的自定义代码保存在一个 Python 文件中。
134
+ 例如,假设我们想使用一个自定义流水线进行句对分类,如下所示:
135
+
136
+ ```py
137
+ import numpy as np
138
+
139
+ from transformers import Pipeline
140
+
141
+
142
+ def softmax(outputs):
143
+ maxes = np.max(outputs, axis=-1, keepdims=True)
144
+ shifted_exp = np.exp(outputs - maxes)
145
+ return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True)
146
+
147
+
148
+ class PairClassificationPipeline(Pipeline):
149
+ def _sanitize_parameters(self, **kwargs):
150
+ preprocess_kwargs = {}
151
+ if "second_text" in kwargs:
152
+ preprocess_kwargs["second_text"] = kwargs["second_text"]
153
+ return preprocess_kwargs, {}, {}
154
+
155
+ def preprocess(self, text, second_text=None):
156
+ return self.tokenizer(text, text_pair=second_text, return_tensors=self.framework)
157
+
158
+ def _forward(self, model_inputs):
159
+ return self.model(**model_inputs)
160
+
161
+ def postprocess(self, model_outputs):
162
+ logits = model_outputs.logits[0].numpy()
163
+ probabilities = softmax(logits)
164
+
165
+ best_class = np.argmax(probabilities)
166
+ label = self.model.config.id2label[best_class]
167
+ score = probabilities[best_class].item()
168
+ logits = logits.tolist()
169
+ return {"label": label, "score": score, "logits": logits}
170
+ ```
171
+
172
+ 这个实现与框架无关,适用于 PyTorch 和 TensorFlow 模型。如果我们将其保存在一个名为
173
+ `pair_classification.py` 的文件中,然后我们可以像这样导入并注册它:
174
+
175
+ ```py
176
+ from pair_classification import PairClassificationPipeline
177
+ from transformers.pipelines import PIPELINE_REGISTRY
178
+ from transformers import AutoModelForSequenceClassification, TFAutoModelForSequenceClassification
179
+
180
+ PIPELINE_REGISTRY.register_pipeline(
181
+ "pair-classification",
182
+ pipeline_class=PairClassificationPipeline,
183
+ pt_model=AutoModelForSequenceClassification,
184
+ tf_model=TFAutoModelForSequenceClassification,
185
+ )
186
+ ```
187
+
188
+ 完成这些步骤后,我们可以将其与预训练模型一起使用。例如,`sgugger/finetuned-bert-mrpc`
189
+ 已经在 MRPC 数据集上进行了微调,用于将句子对分类为是释义或不是释义。
190
+
191
+ ```py
192
+ from transformers import pipeline
193
+
194
+ classifier = pipeline("pair-classification", model="sgugger/finetuned-bert-mrpc")
195
+ ```
196
+
197
+ 然后,我们可以通过在 `Repository` 中使用 `save_pretrained` 方法将其分享到 Hub 上:
198
+
199
+ ```py
200
+ from huggingface_hub import Repository
201
+
202
+ repo = Repository("test-dynamic-pipeline", clone_from="{your_username}/test-dynamic-pipeline")
203
+ classifier.save_pretrained("test-dynamic-pipeline")
204
+ repo.push_to_hub()
205
+ ```
206
+
207
+ 这将会复制包含你定义的 `PairClassificationPipeline` 的文件到文件夹 `"test-dynamic-pipeline"` 中,
208
+ 同时保存流水线的模型和分词器,然后将所有内容推送到仓库 `{your_username}/test-dynamic-pipeline` 中。
209
+ 之后,只要提供选项 `trust_remote_code=True`,任何人都可以使用它:
210
+
211
+ ```py
212
+ from transformers import pipeline
213
+
214
+ classifier = pipeline(model="{your_username}/test-dynamic-pipeline", trust_remote_code=True)
215
+ ```
216
+
217
+ ## 将流水线添加到 🤗 Transformers
218
+
219
+ 如果你想将你的流水线贡献给 🤗 Transformers,你需要在 `pipelines` 子模块中添加一个新模块,
220
+ 其中包含你的流水线的代码,然后将其添加到 `pipelines/__init__.py` 中定义的任务列表中。
221
+
222
+ 然后,你需要添加测试。创建一个新文件 `tests/test_pipelines_MY_PIPELINE.py`,其中包含其他测试的示例。
223
+
224
+ `run_pipeline_test` 函数将非常通用,并在每种可能的架构上运行小型随机模型,如 `model_mapping` 和 `tf_model_mapping` 所定义。
225
+
226
+ 这对于测试未来的兼容性非常重要,这意味着如果有人为 `XXXForQuestionAnswering` 添加了一个新模型,
227
+ 流水线测试将尝试在其上运行。由于模型是随机的,所以不可能检查实际值,这就是为什么有一个帮助函数 `ANY`,它只是尝试匹配流水线的输出类型。
228
+
229
+ 你还 **需要** 实现 2(最好是 4)个测试。
230
+
231
+ - `test_small_model_pt`:为这个流水线定义一个小型模型(结果是否合理并不重要),并测试流水线的输出。
232
+ 结���应该与 `test_small_model_tf` 的结果相同。
233
+ - `test_small_model_tf`:为这个流水线定义一个小型模型(结果是否合理并不重要),并测试流水线的输出。
234
+ 结果应该与 `test_small_model_pt` 的结果相同。
235
+ - `test_large_model_pt`(可选):在一个真实的流水线上测试流水线,结果应该是有意义的。
236
+ 这些测试速度较慢,应该被如此标记。这里的目标是展示流水线,并确保在未来的发布中没有漂移。
237
+ - `test_large_model_tf`(可选):在一个真实的流水线上测试流水线,结果应该是有意义的。
238
+ 这些测试速度较慢,应该被如此标记。这里的目标是展示流水线,并确保在未来的发布中没有漂移。
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/zh/attention.md ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权2023年HuggingFace团队保留所有权利。
2
+
3
+ 根据Apache许可证第2.0版(“许可证”)许可;除非符合许可证,否则您不得使用此文件。您可以在以下网址获取许可证的副本:
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 除非适用法律要求或书面同意,否则按“按原样”分发的软件,无论是明示还是暗示的,都没有任何担保或条件。请参阅许可证以了解特定语言下的权限和限制。
8
+
9
+ ⚠️ 请注意,本文件虽然使用Markdown编写,但包含了特定的语法,适用于我们的doc-builder(类似于MDX),可能无法在您的Markdown查看器中正常渲染。
10
+
11
+ -->
12
+
13
+ # 注意力机制
14
+
15
+ 大多数 transformer 模型使用完全注意力机制,该机制采用正方形的注意力矩阵。当输入很长的文本时,这将导致巨大的计算瓶颈。Longformer 和 Reformer 是提高注意力机制效率的改进模型,它们使用稀疏化的注意力矩阵来加速训练。
16
+
17
+ ## 局部敏感哈希注意力机制(LSH attention)
18
+
19
+ [Reformer](model_doc/reformer)使用LSH(局部敏感哈希)的注意力机制。在计算softmax(QK^t)时,只有矩阵QK^t中的最大元素(在softmax维度上)会做出有用的贡献。所以对于Q中的每个查询q,我们只需要考虑K中与q接近的键k,这里使用了一个哈希函数来确定q和k是否接近。注意力掩码被修改以掩盖当前的词符(token)(除了第一个位置之外),因为这样会使得查询和键相等(因此非常相似)。由于哈希可能会有些随机性,所以在实践中使用多个哈希函数(由n_rounds参数确定),然后一起求平均。
20
+
21
+ ## 局部注意力机制(Local attention)
22
+ [Longformer](model_doc/longformer)使用局部注意力机制:通常情况下,局部上下文(例如,左边和右边的两个词符是什么?)对于给定词符的操作已经足够了。此外,通过堆叠具有小窗口的注意力层,最后一层将拥有不仅仅是窗口内词符的感受野,这使得它们能构建整个句子的表示。
23
+
24
+ 一些预先选定的输入词符也被赋予全局注意力:对于这些少数词符,注意力矩阵可以访问所有词符(tokens),并且这个过程是对称的:所有其他词符除了它们局部窗口内的词符之外,也可以访问这些特定的词符。这在论文的图2d中有展示,下面是一个样本注意力掩码:
25
+
26
+ <div class="flex justify-center">
27
+ <img scale="50 %" align="center" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/local_attention_mask.png"/>
28
+ </div>
29
+
30
+ 使用参数更少的注意力矩阵,可以让模型处理更长的输入序列。
31
+
32
+ ## 其他技巧
33
+
34
+ ### 轴向位置编码
35
+
36
+ [Reformer](model_doc/reformer)模型使用轴向位置编码:在传统的transformer模型中,位置编码矩阵E的大小是\\(l\\)乘以\\(d\\),其中\\(l\\)是序列长度,\\(d\\)是隐藏状态的维度。如果你有非常长的文本,这个矩阵可能会非常大,将会占用大量的GPU显存。为了缓解这个问题,轴向位置编码将这个大矩阵E分解成两个较小的矩阵E1和E2,它们的维度分别是\\(l_{1} \times d_{1}\\) 和\\(l_{2} \times d_{2}\\),满足\\(l_{1} \times l_{2} = l\\)和\\(d_{1} + d_{2} = d\\)(通过长度的乘积,最终得到的矩阵要小得多)。在E中,对于时间步\\(j\\) 的嵌入是通过连接E1中时间步 \\(j \% l1\\) 的嵌入和E2中时间步\\(j // l1\\)的嵌入来获得的。
37
+
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/zh/autoclass_tutorial.md ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+
12
+ ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13
+ rendered properly in your Markdown viewer.
14
+
15
+ -->
16
+
17
+ # 使用AutoClass加载预训练实例
18
+
19
+ 由于存在许多不同的Transformer架构,因此为您的checkpoint创建一个可用架构可能会具有挑战性。通过`AutoClass`可以自动推断并从给定的checkpoint加载正确的架构, 这也是🤗 Transformers易于使用、简单且灵活核心规则的重要一部分。`from_pretrained()`方法允许您快速加载任何架构的预训练模型,因此您不必花费时间和精力从头开始训练模型。生成这种与checkpoint无关的代码意味着,如果您的代码适用于一个checkpoint,它将适用于另一个checkpoint - 只要它们是为了类似的任务进行训练的 - 即使架构不同。
20
+
21
+ <Tip>
22
+
23
+ 请记住,架构指的是模型的结构,而checkpoints是给定架构的权重。例如,[BERT](https://huggingface.co/google-bert/bert-base-uncased)是一种架构,而`google-bert/bert-base-uncased`是一个checkpoint。模型是一个通用术语,可以指代架构或checkpoint。
24
+
25
+
26
+ </Tip>
27
+
28
+ 在这个教程中,学习如何:
29
+
30
+ * 加载预训练的分词器(`tokenizer`)
31
+ * 加载预训练的图像处理器(`image processor`)
32
+ * 加载预训练的特征提取器(`feature extractor`)
33
+ * 加载预训练的处理器(`processor`)
34
+ * 加载预训练的模型。
35
+
36
+
37
+ ## AutoTokenizer
38
+
39
+ 几乎所有的NLP任务都以`tokenizer`开始。`tokenizer`将您的输入转换为模型可以处理的格式。
40
+
41
+ 使用[`AutoTokenizer.from_pretrained`]加载`tokenizer`:
42
+
43
+ ```py
44
+ >>> from transformers import AutoTokenizer
45
+
46
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
47
+ ```
48
+
49
+ 然后按照如下方式对输入进行分词:
50
+
51
+ ```py
52
+ >>> sequence = "In a hole in the ground there lived a hobbit."
53
+ >>> print(tokenizer(sequence))
54
+ {'input_ids': [101, 1999, 1037, 4920, 1999, 1996, 2598, 2045, 2973, 1037, 7570, 10322, 4183, 1012, 102],
55
+ 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
56
+ 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
57
+ ```
58
+
59
+ ## AutoImageProcessor
60
+
61
+ 对于视觉任务,`image processor`将图像处理成正确的输入格式。
62
+
63
+ ```py
64
+ >>> from transformers import AutoImageProcessor
65
+
66
+ >>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
67
+ ```
68
+
69
+
70
+ ## AutoFeatureExtractor
71
+
72
+ 对于音频任务,`feature extractor`将音频信号处理成正确的输入格式。
73
+
74
+ 使用[`AutoFeatureExtractor.from_pretrained`]加载`feature extractor`:
75
+
76
+ ```py
77
+ >>> from transformers import AutoFeatureExtractor
78
+
79
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained(
80
+ ... "ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition"
81
+ ... )
82
+ ```
83
+
84
+ ## AutoProcessor
85
+
86
+ 多模态任务需要一种`processor`,将两种类型的预处理工具结合起来。例如,[LayoutLMV2](model_doc/layoutlmv2)模型需要一个`image processor`来处理图像和一个`tokenizer`来处理文本;`processor`将两者结合起来。
87
+
88
+ 使用[`AutoProcessor.from_pretrained`]加载`processor`:
89
+
90
+
91
+ ```py
92
+ >>> from transformers import AutoProcessor
93
+
94
+ >>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
95
+ ```
96
+
97
+ ## AutoModel
98
+
99
+ <frameworkcontent>
100
+ <pt>
101
+
102
+ 最后,`AutoModelFor`类让你可以加载给定任务的预训练模型(参见[这里](model_doc/auto)获取可用任务的完整列表)。例如,使用[`AutoModelForSequenceClassification.from_pretrained`]加载用于序列分类的模型:
103
+
104
+ ```py
105
+ >>> from transformers import AutoModelForSequenceClassification
106
+
107
+ >>> model = AutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased")
108
+ ```
109
+
110
+ 轻松地重复使用相同的checkpoint来为不同任务加载模型架构:
111
+
112
+
113
+ ```py
114
+ >>> from transformers import AutoModelForTokenClassification
115
+
116
+ >>> model = AutoModelForTokenClassification.from_pretrained("distilbert/distilbert-base-uncased")
117
+ ```
118
+
119
+ <Tip warning={true}>
120
+
121
+ 对于PyTorch模型,`from_pretrained()`方法使用`torch.load()`,它内部使用已知是不安全的`pickle`。一般来说,永远不要加载来自不可信来源或可能被篡改的模型。对于托管在Hugging Face Hub上的公共模型,这种安全风险在一定程度上得到了缓解,因为每次提交都会进行[恶意软件扫描](https://huggingface.co/docs/hub/security-malware)。请参阅[Hub文档](https://huggingface.co/docs/hub/security)以了解最佳实践,例如使用GPG进行[签名提交验证](https://huggingface.co/docs/hub/security-gpg#signing-commits-with-gpg)。
122
+
123
+ TensorFlow和Flax的checkpoints不受影响,并且可以在PyTorch架构中使用`from_tf`和`from_flax`关键字参数,通过`from_pretrained`方法进行加载,来绕过此问题。
124
+
125
+ </Tip>
126
+
127
+ 一般来说,我们建议使用`AutoTokenizer`类和`AutoModelFor`类来加载预训练的模型实例。这样可以确保每次加载正确的架构。在下一个[教程](preprocessing)中,学习如何使用新加载的`tokenizer`, `image processor`, `feature extractor`和`processor`对数据集进行预处理以进行微调。
128
+
129
+ </pt>
130
+ <tf>
131
+ 最后,`TFAutoModelFor`类允许您加载给定任务的预训练模型(请参阅[这里](model_doc/auto)获取可用任务的完整列表)。例如,使用[`TFAutoModelForSequenceClassification.from_pretrained`]加载用于序列分类的模型:
132
+
133
+ ```py
134
+ >>> from transformers import TFAutoModelForSequenceClassification
135
+
136
+ >>> model = TFAutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased")
137
+ ```
138
+
139
+ 轻松地重复使用相同的checkpoint来为不同任务加载模型架构:
140
+
141
+ ```py
142
+ >>> from transformers import TFAutoModelForTokenClassification
143
+
144
+ >>> model = TFAutoModelForTokenClassification.from_pretrained("distilbert/distilbert-base-uncased")
145
+ ```
146
+ 一般来说,我们推荐使用`AutoTokenizer`类和`TFAutoModelFor`类来加载模型的预训练实例。这样可以确保每次加载正确的架构。在下一个[教程](preprocessing)中,学习如何使用新加载的`tokenizer`, `image processor`, `feature extractor`和`processor`对数据集进行预处理以进行微调。
147
+
148
+ </tf>
149
+ </frameworkcontent>